47 min read

> *"A measurement in the middle of a circuit is not a debugging convenience. It is a control-flow

Prerequisites

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

Learning Objectives

  • Write mid-circuit measurements and classical feedforward with if_test, and read the resulting circuit diagram.
  • Implement quantum teleportation and verify it in more than one measurement basis.
  • Explain why teleportation does not violate no-cloning and does not transmit information faster than light.
  • Implement superdense coding and account for the bit ordering in the decoded result.
  • Use reset to reuse a qubit, and state when that trade is worth making.
  • Measure what dynamic circuits cost on hardware relative to an equivalent static circuit.

Chapter 9: Dynamic Circuits

"A measurement in the middle of a circuit is not a debugging convenience. It is a control-flow primitive, and it lets you write programs that a fixed gate sequence cannot express."

Overview

Every circuit so far has been a straight line: gates, then measurement, then done. That is the dominant model and it is a genuine restriction, because it means the circuit cannot react to anything.

Dynamic circuits lift it. You measure a qubit mid-circuit, read the classical bit, and apply gates conditioned on the result — inside a single execution, with the quantum state still live. That capability is what makes three important things possible: quantum teleportation, which moves a state from one qubit to another using entanglement and two classical bits; qubit reuse, which lets a small device run a wider circuit; and, ultimately, quantum error correction, which is nothing but measure-diagnose-correct in a loop (Chapter 25).

Teleportation is the centerpiece, and it is worth doing carefully because it is the most misunderstood protocol in the field. You will implement it, and — more importantly — you will verify it in two measurement bases, because verifying in one basis proves almost nothing, exactly as Chapter 4's Case Study 2 established.

The chapter ends with the honest accounting. Dynamic circuits are supported on current hardware and they are not free: the measured teleportation circuit runs at more than twice the depth of a comparable static one, and there is a latency cost that circuit depth does not capture at all.

In this chapter, you will learn to:

  • Write mid-circuit measurement and classical feedforward with if_test.
  • Implement quantum teleportation, and verify it in more than one basis.
  • Explain why teleportation violates neither no-cloning nor relativity.
  • Implement superdense coding, and account for the bit ordering in the result.
  • Use reset for qubit reuse, and say when the trade is worth it.
  • Measure what dynamic circuits cost against an equivalent static circuit.

Learning Paths

How to read this chapter by track. - 🔰 Beginner — §9.1, §9.3, and §9.4. Teleportation is the one to actually build. - 🔬 Researcher — §9.3's two-basis verification is the methodological point, and §9.7's cost measurement is what you need for a feasibility argument. - 🤖 Quantum ML — this chapter is largely optional for you; §9.5's qubit reuse is the part that might matter, if your feature map is wider than your device. - 🏗️ Quantum Engineer — §9.5, §9.6, and §9.7. Qubit reuse and the latency discussion are operational knowledge, and repeat-until-success is a pattern worth having. - 🔐 Security — §9.3 and §9.4. Teleportation and superdense coding are the two protocols behind most quantum-network claims, and knowing exactly what they do and do not achieve is directly useful.


9.1 Mid-Circuit Measurement and Feedforward

The syntax is a context manager, and it reads like the classical code it is:

from qiskit import QuantumCircuit

qc = QuantumCircuit(2, 2)
qc.h(0)
qc.measure(0, 0)                            # measure MID-CIRCUIT

with qc.if_test((qc.clbits[0], 1)):         # if that bit came out 1 ...
    qc.x(1)                                 # ... flip qubit 1

qc.measure(1, 1)
print(qc.draw())
     ┌───┐┌─┐
q_0: ┤ H ├┤M├─────────────────────────────
     └───┘└╥┘  ┌──────  ┌───┐ ───────┐ ┌─┐
q_1: ──────╫───┤ If-0  ─┤ X ├  End-0 ├─┤M├
           ║   └──╥───  └───┘ ───────┘ └╥┘
           ║ ┌────╨────┐                ║
c: 2/══════╩═╡ c_0=0x1 ╞════════════════╩═
           0 └─────────┘                1
counts: {'00': 2031, '11': 2065}

Qubit 1 ends up matching qubit 0 every time — the classically-conditioned correlation from Chapter 4 §4.4's impostor circuit, which is where you first met this syntax.

The condition can be on a single bit or on a whole register:

with qc.if_test((qc.clbits[0], 1)):         # one bit equals 1
    ...

creg = qc.cregs[0]
with qc.if_test((creg, 3)):                 # the whole register equals 3
    ...

with qc.if_test((qc.clbits[0], 1)) as else_:    # with an else branch
    qc.x(1)
with else_:
    qc.z(1)

🗝️ Version Notec_if is gone.

Older code conditions gates with a method on the instruction:

python qc.x(1).c_if(qc.clbits[0], 1) # ✗ removed

c_if was removed in Qiskit 1.0. It could only condition a single gate on a register equality, which is exactly the limitation that made OpenQASM 2 unable to express dynamic circuits (Chapter 6 §6.4). The if_test context manager conditions arbitrary blocks and supports else.

If you find c_if in a tutorial, the whole tutorial predates 1.0 and probably has other problems.

⚛️ The Physics Underneath — What the measurement does to the rest of the circuit.

Chapter 5 §5.1 said measurement replaces a qubit's state with the outcome. In a dynamic circuit that is still true, and there is a second effect: measuring one qubit of an entangled group collapses the whole group.

That is not a side effect to be worked around. It is the mechanism the protocols in this chapter exploit. Teleportation works because Alice's measurement instantaneously determines what Bob's qubit is — up to a correction that depends on her outcome, which is precisely what the two classical bits carry.

What if_test actually becomes

The context manager is syntax; what it builds is a single instruction. Close the block and inspect the last element of the circuit and you find an IfElseOp whose operands are circuits — one body for the true branch, optionally a second for the false branch — not a gate with a flag attached.

Three consequences follow, and each shows up somewhere you will trip over it.

A conditional block is one instruction, so the compiler cannot see through it. The gates inside the body are transpiled against the same basis and coupling map as everything else, but no optimization pass moves a gate across the boundary in either direction. A conditional block is an optimization barrier in exactly Chapter 8 §8.6's sense — with the difference that you cannot strip it before running, because it is the program.

The condition is classical, and it is evaluated on classical hardware. (qc.clbits[0], 1) is a predicate over a classical register, resolved by the control electronics in between stretches of quantum evolution. Nothing about it is reversible and nothing about it is in superposition. That is why §9.2's claim — dynamic circuits add control flow to the programming model — is the precise statement rather than a hedge.

Blocks nest, and the condition can read a register written earlier in the same circuit. Chapter 25 §25.7's syndrome decoding is a three-way branch on a two-bit register, written exactly this way.

⚙️ Under the Transpiler — the one instruction with no price on it.

Almost every instruction a backend supports appears in its Target with a duration and an error rate attached. Ask a 127-qubit ECR device what it charges for the operations in this chapter:

```text instruction duration properties


rz 0.0 ns (virtual) 127 qubit entries sx 56.9 ns 127 qubit entries ecr 341.3 - 881.8 ns 144 link entries measure 1,216.0 ns 127 qubit entries reset 1,272.9 - 1,400.9 ns 127 qubit entries if_else -- {None: None} ```

if_else is in the target and carries nothing. No duration, no error rate, no per-qubit properties — the entry is literally {None: None}. Ask the duration lookup for one and it refuses, while the measurement beside it answers immediately:

text durations().get("measure", [2]) -> 5472 dt = 1,216.0 ns durations().get("if_else", [2]) -> TranspilerError: 'Duration of if_else on qubits [2] is not found.'

That is not an oversight in a mock backend. The cost of a conditional block is not a property of the block — it depends on how fast the control stack can read a result, evaluate a predicate, and emit a pulse, and no per-instruction table can express that. §9.7's "cost that depth() cannot see" is this same fact from the compiler's side: the compiler cannot see it either.

🔀 In Another Framework — feedforward in Cirq, PennyLane, and Q#.

The capability is not Qiskit's, and the three spellings are worth recognising.

Cirq 1.7.0 attaches the condition to the operation, keyed by measurement label:

python circ = cirq.Circuit([ cirq.H(q[0]), cirq.measure(q[0], key="m"), cirq.X(q[1]).with_classical_controls("m"), # feedforward cirq.measure(q[1], key="out"), ])

Run at 2,000 repetitions, m and out agree on every single shot — §9.1's classically-conditioned correlation, in another dialect. Note the shape: this is closer to the c_if Qiskit removed, one operation at a time, than to a block.

PennyLane 0.45.1 returns a measurement value you then branch on:

python m0 = qml.measure(0) m1 = qml.measure(1) qml.cond(m1, qml.PauliX)(wires=2) qml.cond(m0, qml.PauliZ)(wires=2)

That is teleportation's step 4 in four lines. Measured on default.qubit at 4,096 shots, the teleported qubit's three Bloch components come back

text <Z> <X> <Y> got +0.7690 +0.1567 +0.6348 ideal +0.7648 +0.1723 +0.6207 worst disagreement 0.0156, sampling error 1/sqrt(4096) = 0.0156 -> consistent

— verified in three bases rather than one, which is §9.3's standard regardless of framework. (PennyLane 0.45 deprecates shots= on the device in favour of a set_shots transform on the QNode. The warning fires; the run is fine.)

Q# has the most conventional-looking version, because M(q) returns a first-class Result type and if is the language's ordinary if. Chapter 15 §15.5 uses exactly that to show something worth carrying into §9.5: reusing a qubit without resetting it is not caught by the compiler.

9.2 Why This Is a Real Extension

It is worth being precise about what dynamic circuits add, because "you can measure in the middle" undersells it.

They add classical control flow to a quantum program. A static circuit is a fixed sequence; a dynamic circuit is a program with branches. That is a genuine increase in expressive power for the programming model, even though it does not increase what is computable — anything a dynamic circuit does could in principle be done with a larger static circuit and post-selection, at exponentially worse cost.

They enable qubit reuse. Measure, reset, and use the same physical qubit again (§9.5). On a device with a hard qubit limit, this converts a width constraint into a depth constraint — often a good trade.

They are how error correction works. Chapter 25's syndrome extraction is exactly this: measure ancillas mid-circuit, decode the result classically, and apply a correction to qubits that are still carrying live quantum information. Fault-tolerant quantum computing is a dynamic circuit, run continuously. Everything in this chapter is a rehearsal for that.

★ The deferred-measurement principle, and when you can throw all of this away

Before building anything, know when you do not have to. There is a theorem that removes mid-circuit measurement from a great many circuits, and it is the first thing to check.

The principle of deferred measurement. A measurement whose result is used only to control later quantum gates can be replaced by a coherent controlled gate, with the measurement moved to the end of the circuit — or dropped entirely if nothing else reads it. The output statistics are identical.

Chapter 20 §20.4 already leaned on it: Simon's algorithm never measures its $n$ output qubits, and the derivation proceeds as though it had.

Teleportation is the cleanest place to see it, because its conditional corrections are exactly what the principle targets. Replace them with controlled gates and the classical registers vanish:

qc.cx(0, 1); qc.h(0)      # Alice's Bell measurement, minus the measuring
qc.cx(1, 2)               # the X correction, now CONTROLLED on q1
qc.cz(0, 2)               # the Z correction, now CONTROLLED on q0

No measure, no if_test, no feedforward at all. Run §9.3's three-basis verification on both:

   basis |  ideal <P> |    dynamic |   deferred
  --------------------------------------------
       Z |    +0.7648 |    +0.7708 |    +0.7678
       X |    +0.1723 |    +0.1768 |    +0.1680
       Y |    +0.6207 |    +0.6240 |    +0.6270

  worst |dynamic  - ideal| = 0.0059
  worst |deferred - ideal| = 0.0062        sampling error ~0.0110

Both land on the same state, and neither disagreement exceeds the sampling error. The deferred circuit is a genuine teleportation by the same standard §9.3 applies to the dynamic one.

★★ And it costs more, not less

The obvious next thought is that the deferred version must be cheaper — no measurements, no conditional blocks, none of §9.7's latency. Transpile all three for the same 127-qubit device and the thought does not survive:

  circuit                    ISA depth   2q   ops
  --------------------------------------------------------------------------------
  static GHZ                         9    2   {'rz': 8, 'sx': 5, 'measure': 3, 'ecr': 2, 'x': 1}
  teleportation (dynamic)           14    2   {'rz': 10, 'sx': 6, 'measure': 3, 'ecr': 2, 'if_else': 2}
  teleportation (deferred)          25    7   {'rz': 19, 'sx': 14, 'ecr': 7, 'x': 2, 'measure': 1}

Deferring the measurement costs eleven more layers and five more two-qubit gates. It removes two if_else blocks and two of the three measurements, and it is by a wide margin the worst of the three.

Where the five extra two-qubit gates come from is worth tracing, because the mechanism is general. The deferred circuit has four two-qubit gates in its logical description — cx(1,2), cx(0,1), cx(1,2), cz(0,2) — against the dynamic version's two. That accounts for two of the five. The other three are routing. The transpiler laid the three virtual qubits onto physical qubits 124, 123, 122, which form a linear chain: q0→124, q1→123, q2→122. The deferred cz(0,2) therefore needs 124 to talk to 122, and those two are not coupled — 123 sits between them. One SWAP goes in, and Chapter 4 §4.6 priced a SWAP at three two-qubit gates. Four logical plus three for the SWAP is seven.

This is "every remedy is denominated in the currency of the disease" again. Deferring buys you out of classical latency by spending two-qubit gates and connectivity, which are the two things a superconducting device has least of. Which remedy is cheaper is a property of the device, not of the protocol — and on a device with all-to-all connectivity the arithmetic above would come out the other way, because there would be no SWAP.

📐 Math Aside — why deferring is allowed at all.

The claim is that measuring qubit $a$ and then applying $U$ to qubit $b$ if the outcome was 1 gives the same statistics as applying controlled-$U$ from $a$ to $b$ and measuring $a$ afterwards. Two lines.

Write the pre-measurement state as $\sum_{k\in\{0,1\}} |k\rangle_a \otimes |\phi_k\rangle_b$, where the $|\phi_k\rangle$ are unnormalised.

Measure first. Outcome $k$ occurs with probability $\langle\phi_k|\phi_k\rangle$, leaving $|k\rangle_a\otimes|\phi_k\rangle_b$ normalised; the feedforward then applies $U^k$, giving $|k\rangle_a \otimes U^k|\phi_k\rangle_b$ with that probability.

Defer. Controlled-$U$ acts term by term as $|k\rangle\otimes|\phi_k\rangle \mapsto |k\rangle\otimes U^k|\phi_k\rangle$, giving $\sum_k |k\rangle_a \otimes U^k|\phi_k\rangle_b$. Measuring $a$ now yields $k$ with probability $\langle\phi_k|U^{k\dagger}U^k|\phi_k\rangle = \langle\phi_k|\phi_k\rangle$, leaving $|k\rangle\otimes U^k|\phi_k\rangle$. The same ensemble, outcome by outcome.

The step doing the work is $U^{k\dagger}U^k = I$ — unitarity, nothing more. And the condition that makes the theorem applicable is visible in the setup: the control qubit $a$ must not be touched again after the measurement point. If it is, the deferred version retains a coherence the measured version destroyed, and the two circuits genuinely differ.

That condition is also why deferring rescues neither qubit reuse (§9.5) nor error correction (Chapter 25). Reuse needs the measured qubit back. Error correction needs the syndrome as a classical value it can hand to a decoder and act on within the coherence time, round after round, for the life of the computation — and deferring an unbounded number of rounds means never measuring at all.

9.3 Quantum Teleportation

The protocol: move an unknown quantum state from one qubit to another, using a shared entangled pair and two classical bits.

The construction

from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister

def teleport(theta: float, phi: float) -> QuantumCircuit:
    qr = QuantumRegister(3, "q")
    m0 = ClassicalRegister(1, "m0")        # Alice's two measurement outcomes
    m1 = ClassicalRegister(1, "m1")
    out = ClassicalRegister(1, "out")      # Bob's final readout
    qc = QuantumCircuit(qr, m0, m1, out)

    # 1. The state to teleport, on q0. Alice does not know theta and phi.
    qc.ry(theta, 0)
    qc.rz(phi, 0)
    qc.barrier()

    # 2. A Bell pair shared between Alice (q1) and Bob (q2).
    qc.h(1)
    qc.cx(1, 2)
    qc.barrier()

    # 3. Alice performs a BELL MEASUREMENT on her two qubits (q0, q1).
    qc.cx(0, 1)
    qc.h(0)
    qc.measure(0, m0[0])
    qc.measure(1, m1[0])
    qc.barrier()

    # 4. Bob corrects, conditioned on Alice's two classical bits.
    with qc.if_test((m1[0], 1)):
        qc.x(2)
    with qc.if_test((m0[0], 1)):
        qc.z(2)

    return qc

Four steps, and each one is something you already know.

Step 3 is Chapter 4 §4.5's Bell measurementcx then h, the entangling circuit run backward, which maps the four Bell states onto the four computational basis states so that a measurement can distinguish them.

Step 4 is the correction table. Alice's two bits tell Bob which of the four Bell states her measurement collapsed onto, and therefore which of four Pauli corrections his qubit needs:

$m_0$ $m_1$ Bob's qubit is Correction
0 0 $\lvert\psi\rangle$ none
0 1 $X\lvert\psi\rangle$ $X$
1 0 $Z\lvert\psi\rangle$ $Z$
1 1 $ZX\lvert\psi\rangle$ $X$ then $Z$

Why two classical bits are exactly enough

The correction table is usually presented as something to memorise. It is not — it falls out of one line of algebra, and doing that algebra once is what makes the protocol stop feeling like a trick.

Start with the state to move, $|\psi\rangle = \alpha|0\rangle + \beta|1\rangle$ on $q_0$, and the Bell pair $|\Phi^+\rangle = \tfrac{1}{\sqrt2}(|00\rangle + |11\rangle)$ on $q_1q_2$:

$$|\Psi\rangle = \big(\alpha|0\rangle + \beta|1\rangle\big)_0 \otimes \tfrac{1}{\sqrt2}\big(|00\rangle + |11\rangle\big)_{12}$$

Alice's Bell measurement is cx(0,1) then h(0). The CNOT flips $q_1$ when $q_0$ is 1:

$$\tfrac{1}{\sqrt2}\Big[\alpha|0\rangle\big(|00\rangle + |11\rangle\big) + \beta|1\rangle\big(|10\rangle + |01\rangle\big)\Big]$$

Then the Hadamard on $q_0$, using $|0\rangle \to \tfrac{1}{\sqrt2}(|0\rangle+|1\rangle)$ and $|1\rangle \to \tfrac{1}{\sqrt2}(|0\rangle-|1\rangle)$:

$$\tfrac{1}{2}\Big[\alpha\big(|0\rangle+|1\rangle\big)\big(|00\rangle+|11\rangle\big) + \beta\big(|0\rangle-|1\rangle\big)\big(|10\rangle+|01\rangle\big)\Big]$$

Now collect the terms by what Alice's two qubits are, writing $q_0q_1$ first and Bob's $q_2$ last:

$$\tfrac{1}{2}\Big[\;|00\rangle\big(\alpha|0\rangle + \beta|1\rangle\big) \;+\; |01\rangle\big(\alpha|1\rangle + \beta|0\rangle\big) \;+\; |10\rangle\big(\alpha|0\rangle - \beta|1\rangle\big) \;+\; |11\rangle\big(\alpha|1\rangle - \beta|0\rangle\big)\;\Big]$$

Read the four brackets. They are $|\psi\rangle$, $X|\psi\rangle$, $Z|\psi\rangle$, and $ZX|\psi\rangle$ — the correction table above, derived rather than asserted. Bob's qubit is already in $|\psi\rangle$ up to one of four Pauli operators, and Alice's two bits say which one.

Three things in that expression are worth noticing, because each answers a question people actually ask.

Every branch has amplitude exactly $1/2$, independent of $\alpha$ and $\beta$. That is the measured 25/25/25/25 in the tally below — and it is not approximately true, it is exact for every input state. The uniformity is a theorem, not an empirical regularity.

Two bits index four branches, and four is all there are. The single-qubit Pauli group modulo phase has exactly four elements — $I$, $X$, $Z$, $XZ$ — so $\log_2 4 = 2$ classical bits is not a convenient amount of communication, it is the exact amount. One bit would leave Bob unable to separate two of the four cases, and nothing he could do would help, because those two cases are genuinely different states. Three bits would be waste.

Neither $\alpha$ nor $\beta$ appears anywhere on Alice's side. They live only in Bob's factor. Alice's measurement statistics are $\{1/4, 1/4, 1/4, 1/4\}$ for every possible input — which is the entire no-signalling argument compressed into one observation, and is made explicit below.

Verifying it — and why one basis is not enough

Run it and measure Bob's qubit:

original state, Z basis:     [0.8824, 0.1176]
teleported q2,  Z basis:     [0.8843, 0.1157]

Close. But Chapter 4's Case Study 2 established the discipline: matching in one basis proves almost nothing. A circuit that simply prepared the right probabilities on q2 — with no phase information at all — would pass this test.

So check all three Bloch axes — $Z$, $X$ (apply h before measuring), and $Y$ (sdg then h), from Chapter 5 §5.6. Comparing expectation values at 8,192 shots:

   basis |  ideal <P> |  teleported |  difference
  -----------------------------------------------
       Z |    +0.7648 |     +0.7708 |      0.0059
       X |    +0.1723 |     +0.1768 |      0.0044
       Y |    +0.6207 |     +0.6240 |      0.0033

  worst disagreement 0.0059, sampling error ~0.0110  ->  consistent

All three agree, and every disagreement is smaller than the sampling error.

Three Bloch components completely determine a single-qubit pure state, so this is a real verification rather than a suggestive one. It is also, precisely, single-qubit state tomography — and it is the honest standard for a teleportation experiment. Chapter 26 §26.8 does tomography properly, including why it costs exponentially many measurement settings for many qubits.

Alice's outcomes are uniformly random, and that is the point

Tallying which correction Bob had to apply, across 8,192 shots:

    m0   m1 |          Bob had |   correction | shots
  -------------------------------------------------
     0    0 |            |psi> |         none |  2109
     0    1 |           X|psi> |            X |  1998
     1    0 |           Z|psi> |            Z |  2074
     1    1 |          ZX|psi> |     X then Z |  2011

Four outcomes, each about a quarter. Alice's measurement result is uniformly random and carries no information about the state she teleported. That is not incidental — it is exactly why nothing travels faster than light, and it is the cleanest way to see it. Bob's qubit, before the classical bits arrive, is maximally mixed: an equal mixture of the four possibilities, holding nothing.

📐 Math Aside — the no-signalling statement, computed rather than asserted.

"Bob's qubit is maximally mixed until the bits arrive" is a claim about a density matrix, and it is short enough to check.

Before Alice's bits arrive Bob does not know which branch occurred, so his qubit is the mixture over branches weighted by their probabilities — each exactly $1/4$, from the derivation above:

$$\rho_B = \tfrac14\Big(|\psi\rangle\langle\psi| + X|\psi\rangle\langle\psi|X + > Z|\psi\rangle\langle\psi|Z + XZ|\psi\rangle\langle\psi|ZX\Big)$$

That is the Pauli twirl of $|\psi\rangle\langle\psi|$, and for any single-qubit state it equals $I/2$. Check it in the Bloch representation, $|\psi\rangle\langle\psi| = \tfrac12(I + \vec r\cdot \vec\sigma)$. Conjugating by $X$ sends $(r_x, r_y, r_z) \to (r_x, -r_y, -r_z)$; by $Z$ it goes to $(-r_x, -r_y, r_z)$; by $XZ$ to $(-r_x, r_y, -r_z)$. Every component appears twice with a plus sign and twice with a minus, so the average of the four is $\vec r = 0$ and $\rho_B = I/2$.

$I/2$ contains no $\alpha$, no $\beta$, no $\vec r$. It is the same density matrix for every state Alice might have teleported, so no measurement Bob can perform — not one, not a million, not one yet to be invented — has a distribution that depends on what she sent. That is not "the information is hard to extract." It is "the information is not there."

Run the same calculation with the two classical bits in hand and the twirl collapses to a single branch, which is a pure state again. The bits are what turn a uniform mixture into a state, and they travel at $c$ like everything else.

⚠️ Common Pitfall — What teleportation does not do.

Three misreadings, all common, all worth being able to correct on the spot.

It does not violate no-cloning. The original state is destroyed by Alice's measurement. There is never a moment when two copies exist. Teleportation moves a state; it does not duplicate one.

It does not transmit information faster than light. Bob's qubit is in a definite state immediately after Alice measures — but it is one of four states, and without her two classical bits he cannot tell which. Those bits travel by ordinary classical channel at ordinary speed. The classical message is not an implementation detail; it is what carries the information. Before it arrives, Bob's qubit is maximally mixed and holds nothing.

It does not transmit matter or energy. Nothing physical moves from Alice to Bob except two classical bits. What is "teleported" is the state — the information about how a qubit is configured — onto a qubit that was already there.

A useful one-line summary: teleportation converts one shared entangled pair plus two classical bits into one transmitted qubit state. That exchange rate is exact, and §9.4's superdense coding is the same trade run in reverse.

9.4 Superdense Coding

The mirror image. Teleportation sends one qubit's state using one entangled pair and two classical bits. Superdense coding sends two classical bits using one entangled pair and one qubit.

def superdense(bits: str) -> QuantumCircuit:
    qc = QuantumCircuit(2, 2)

    qc.h(0)                       # a shared Bell pair; q0 is Alice's, q1 is Bob's
    qc.cx(0, 1)
    qc.barrier()

    if bits[1] == "1":            # Alice encodes TWO bits into HER ONE qubit
        qc.x(0)
    if bits[0] == "1":
        qc.z(0)
    qc.barrier()

    qc.cx(0, 1)                   # Bob performs a Bell measurement on both
    qc.h(0)
    qc.measure([0, 1], [0, 1])
    return qc
  Alice sends 00 -> Bob measures {'00': 1024}
  Alice sends 01 -> Bob measures {'10': 1024}
  Alice sends 10 -> Bob measures {'01': 1024}
  Alice sends 11 -> Bob measures {'11': 1024}

Four for four, deterministically. Alice touched only her own qubit, applied one of four operations, and Bob recovered two full bits.

⚠️ Common Pitfall — Read those results again: 01 came back as 10.

Alice sent 01 and Bob measured '10'. That is not an error in the protocol; it is Chapter 2 §2.7's little-endian convention, showing up in a place where it is easy to mistake for a bug.

Alice's second bit (bits[1]) controls the $X$ gate, which flips the first classical bit Bob reads; and Qiskit prints classical bit 0 on the right. The two reversals interact.

The fix is not to memorize which way it goes. It is to test with an asymmetric input — exactly Chapter 5 §5.3's rule. 00 and 11 are palindromes and would have hidden this completely; 01 and 10 are what reveal it. Had this protocol been tested only on 00 and 11, the bit ordering would have shipped wrong.

What it does and does not achieve

Superdense coding is often described as "sending two bits with one qubit," which is true and incomplete. The full accounting:

Resource Cost
Entangled pair 1, distributed in advance
Qubits transmitted at message time 1
Classical bits delivered 2

The entangled pair had to get from Alice to Bob somehow, and distributing it required sending a qubit. So the total qubit traffic is two, for two bits — no better than sending the bits directly.

What superdense coding actually buys is a shift in timing. The expensive part (entanglement distribution) happens whenever it is convenient; the message costs one qubit at the moment you need to send it. For a quantum network with pre-distributed entanglement that is a real and useful property, and it is the honest version of the claim.

Derived as teleportation's dual

The mirror-image framing is accurate, and it can be made exact. Both protocols are the same two facts about the Bell basis, read in opposite directions.

Fact one: a Pauli on one half moves you around the Bell basis. Start from $|\Phi^+\rangle = \tfrac{1}{\sqrt2}(|00\rangle+|11\rangle)$ and apply each Pauli to Alice's qubit alone:

$$I\otimes I\,|\Phi^+\rangle = |\Phi^+\rangle, \qquad X\otimes I\,|\Phi^+\rangle = |\Psi^+\rangle$$

$$Z\otimes I\,|\Phi^+\rangle = |\Phi^-\rangle, \qquad ZX\otimes I\,|\Phi^+\rangle = |\Psi^-\rangle$$

Four local operations, four globally orthogonal states. Chapter 4 §4.5 built all four and showed they form a basis for the two-qubit space.

Fact two: the Bell basis is distinguishable — if you hold both halves. cx then h, the entangling circuit run backward, maps those four onto $|00\rangle$, $|01\rangle$, $|10\rangle$, $|11\rangle$, which a computational-basis measurement separates deterministically. That is Chapter 4 §4.5's bell_measure, and it is the same gate pair as teleportation's step 3.

Now read the two facts in each order.

Superdense coding is fact one, then fact two. Alice's local Pauli writes two bits into which Bell state the pair is in; Bob, holding both halves, reads them off with certainty. The information was never in the qubit Alice sent — it was in the correlation, and her one qubit is merely the half Bob was missing.

Teleportation is fact two, then fact one. Alice's Bell measurement forces the pair into one of four Bell states and tells her which; her two bits let Bob undo it with the matching Pauli.

The resource ledger is one equation solved for different unknowns:

  teleportation       1 ebit  +  2 classical bits     ->  1 qubit of quantum state
  superdense coding   1 ebit  +  1 transmitted qubit  ->  2 classical bits

Add the two lines and the ebits cancel: one qubit of state plus one transmitted qubit yields two classical bits plus one qubit of state — a tautology, which is the correct answer. Neither protocol creates a resource. Each converts between two of them at a fixed rate, and the rate is fixed by the number of Bell states, which is four.

Where the reversed bits actually come from

The pitfall callout above named the 01'10' reversal a convention collision and gave you the testing rule. The algebra says exactly which two conventions collided, and it is worth a minute.

In the code, bits[1] — the second character of Alice's string — drives $X$, and bits[0] drives $Z$. From fact one, $X$ on Alice's qubit sends $|\Phi^+\rangle \to |\Psi^+\rangle$, and a $\Psi$ reads out after cx+h with $q_1 = 1$; $Z$ produces the minus sign that reads out as $q_0 = 1$:

  Alice's bits[1]  ->  X  ->  Phi becomes Psi   ->  Bob's q1 = 1
  Alice's bits[0]  ->  Z  ->  plus becomes minus ->  Bob's q0 = 1

Alice's second character lands on Bob's qubit 1, and her first on his qubit 0 — one reversal, and it lives in the encoding. Then Qiskit prints clbit 0 on the right — a second reversal, living in the display. The two do not cancel, because they act on different things: one maps a string index to a qubit index, the other orders characters on a page. 01 goes in and '10' comes out.

Nothing is wrong and nothing needs fixing. But notice what would happen if you "fixed" it by swapping the gates: the protocol would become correct for this printing convention and silently wrong for every other consumer of the same counts — a plotting routine that indexes the string the other way, a comparison against a hand-derived table, a partner implementation. A convention belongs at one boundary, in one place, with a test on it. Moving it into the physics is how a display bug becomes a protocol bug.

📊 What the Numbers Say — "two bits per qubit" is an exchange rate, not a saving.

The headline invites a scaling fantasy: if one qubit carries two bits, then $n$ qubits carry $2n$, and quantum communication is twice as dense. The second half is true and the inference is not.

Read the resource table again as a rate. The protocol delivers 2 classical bits per transmitted qubit, and 1 classical bit per qubit that ever moved, counting the entanglement distribution. Without a pre-shared pair, a qubit carries at most one classical bit — that is Holevo's bound, and superdense coding does not evade it. It spends an ebit to reach the factor of two, and the ebit cost one qubit-transmission to establish.

The number that is easy to get here — "2 bits per qubit" — is not the number that answers "should I build this?" The number that answers that one is: can you distribute and store entanglement more cheaply, or at a different time, than you can send the message? If yes, superdense coding is a genuine engineering win; if no, it is a demonstration. The same reframing settles teleportation's routing question in Case Study 2, and it is the chapter's version of the easy number is almost always the flattering one.

9.5 Reset and Qubit Reuse

reset returns a qubit to $|0\rangle$ mid-circuit — physically, by measuring it and conditionally flipping. That makes a used qubit reusable:

qc = QuantumCircuit(1, 2)        # ONE qubit, two classical bits
qc.h(0)
qc.measure(0, 0)
qc.reset(0)                      # back to |0>
qc.h(0)
qc.measure(0, 1)
{'00': 993, '01': 1008, '10': 1038, '11': 1057}

Four outcomes at roughly 25% each: two independent coin flips from one physical qubit.

This converts a width constraint into a depth constraint, and on hardware with a hard qubit limit that is often the trade you want. A circuit that logically needs 20 qubits but never uses more than 5 simultaneously can run on a 5-qubit device.

The costs are real:

  • Depth grows, and so does exposure to decoherence.
  • Reset is not instantaneous. It is a measurement plus a conditional gate, and on superconducting hardware measurement is the slowest operation (Chapter 2 Case Study 2: ~1,200 ns).
  • Reset is not perfect. It inherits the readout error of the measurement it is built on.

Pricing the width-for-depth trade

"Depth grows" is the right shape at the wrong resolution. Put real durations on it. On the 133-qubit device Chapter 39 §39.2 measured:

  rz          0.0 ns             (virtual -- Chapter 31)
  sx         32.0 -    64.0 ns
  cz         68.0 -   184.0 ns
  measure          1,560.0 ns
  reset    1,600.0 - 1,848.0 ns

A reset costs between 8.7 and 27.2 two-qubit gates — $1{,}600/184 = 8.7$ if you are lucky on both ends, $1{,}848/68 = 27.2$ if you are not. Against a single-qubit gate it is worse: the measurement alone is $1{,}560/32 = 49$ sx gates.

The 127-qubit ECR device this chapter transpiles for gives the same picture in different units:

  sx              56.9 ns
  ecr        341.3 -   881.8 ns        (median 533.3 -- Chapter 31 §31.2)
  measure        1,216.0 ns
  reset    1,272.9 - 1,400.9 ns

Here a reset is 1.4 to 4.1 ECRs — a much milder ratio, because this device's two-qubit gate is itself slow. The same operation costs six times more, in gate-equivalents, on one device than the other. "Reuse costs depth" is not a portable claim, and neither is any rule of thumb built on it.

Now the constraint that actually binds. Reuse is not limited by wall clock; it is limited by $T_2$, because every qubit you are not resetting sits in superposition losing phase while you do it. Chapter 31 §31.2 measured the coherence spread on the 127-qubit device:

   T2:   min 2.6 us      median 170.0 us      max 488.8 us      spread 188x

Divide through by one reset at the 133-qubit device's worst case, 1,848 ns:

   best-T2 qubit      488.8 us / 1,848 ns  =  264 resets
   median-T2 qubit    170.0 us / 1,848 ns  =   92 resets
   worst-T2 qubit       2.6 us / 1,848 ns  =    1.4 resets

On the median qubit there is room for about ninety resets before coherence is gone. On the worst qubit of the same chip there is room for one. And you do not choose which qubit you get — Chapter 29 §29.4 is the entire argument about that, and Chapter 30 §30.3's factor-of-9.6 spread in a single chip's quoted two-qubit error is the same phenomenon in another column.

That is the honest version of "reuse converts width into depth": it converts a resource the device either has or does not have into one you are already spending, at an exchange rate that varies by a factor of 188 across qubits on one chip.

★ What the coin-flip demonstration cannot see

The two-flips-from-one-qubit result above is real, and as evidence about reset quality it is worth nothing. Working out why is worth more than the demonstration, because the reasoning generalises to almost every reuse benchmark you will be shown.

Suppose the reset is imperfect and leaves the qubit in the mixed state

$$\rho = (1-\epsilon)\,|0\rangle\langle 0| \;+\; \epsilon\,|1\rangle\langle 1|$$

for some leakage probability $\epsilon$. The next thing the circuit does is apply $H$ and measure in $Z$. Under $H$, $|0\rangle\langle0| \to |{+}\rangle\langle{+}|$ and $|1\rangle\langle1| \to |{-}\rangle\langle{-}|$ — and **both of those give $P(0) = P(1) = 1/2$.** So

$$P(0) \;=\; (1-\epsilon)\cdot\tfrac12 \;+\; \epsilon\cdot\tfrac12 \;=\; \tfrac12$$

exactly, for every $\epsilon$. A reset that does nothing at all ($\epsilon = 1/2$) passes this test perfectly. A reset that is completely wrong ($\epsilon = 1$) also passes.

Chapter 15 §15.5 measured precisely this from the other direction, in Q#: a qubit measured and then reused with no reset at all returned Zero: 251, One: 249 out of 500. A fair coin is the one thing this circuit is guaranteed to produce, whatever happened in between, which is what makes it a bad detector of the thing it appears to be testing.

This is the book's recurring failure mode — a measurement that cannot detect the property being claimed — in another costume. Chapter 4's impostor had the right counts and no entanglement; this chapter's Case Study 1 impostor has the right populations and no phase; this circuit has the right uniformity whatever the reset does.

What would detect it: prepare $|1\rangle$, reset, and measure without the intervening $H$ — then $P(1)$ reads $\epsilon$ directly. The fix is always the same shape. Ask what the claim depends on, and put the measurement where that property lives.

📊 What the Numbers Say — a deviation statistic whose scale depends on how many bins you have.

The natural way to score a reuse experiment is "worst deviation from uniform," and it is a trap. Measured on the noiseless simulator at 8,192 shots, 20 independent repeats per row:

```text flips bins mean worst dev sd min max shot-noise SE mean/SE


  2      4          0.00624   0.00213   0.00317   0.01086         0.00478      1.31
  3      8          0.00634   0.00244   0.00366   0.01208         0.00365      1.73
  4     16          0.00551   0.00155   0.00244   0.00867         0.00267      2.06
  5     32          0.00469   0.00092   0.00330   0.00647         0.00192      2.44
  6     64          0.00347   0.00054   0.00269   0.00476         0.00137      2.53
  7    128          0.00287   0.00040   0.00220   0.00366         0.00097      2.95
  8    256          0.00201   0.00023   0.00171   0.00256         0.00069      2.91

```

The statistic goes down as you reuse the qubit more — 0.0062 at two flips, 0.0020 at eight — on a simulator with no noise in it at all. It has to. A single bin's shot-noise scale is $\sqrt{p(1-p)/N}$ with $p = 2^{-k}$, which shrinks like $2^{-k/2}$, while the maximum over $2^k$ bins grows only like $\sqrt{2\ln 2^k}$. The mean/SE column is that growing factor, and it climbs from 1.31 to 2.91 exactly as it should. The product falls.

Two lessons, and the second is the general one. Never compare a max-over-bins statistic across different bin counts — it is not the same statistic at $k=2$ and $k=8$. And read the sd, min and max columns: at two flips, a single draw could have landed anywhere from 0.0032 to 0.0109, a factor of 3.4. A trend read off three single draws of this quantity is a trend read off three coin flips, which is this book's most frequently repeated warning and its most frequently repeated mistake.

🐛 Debug This — your seed sweep on a reset circuit is producing a fake error bar.

The obvious way to get an error bar from a simulator is to vary seed_simulator and take the spread. On a circuit containing reset, that silently stops working.

Four flips on one qubit, 8,192 shots, counting the '0000' outcome, twenty repeats each way (Qiskit 2.5.1 / qiskit-aer 0.17.2):

```text method min max sd


seed_simulator = 1 .. 20 526 528 0.489 no seed, 20 fresh runs 445 549 26.332 binomial sd for n = 8192, p = 1/16 21.909

CONTROL: static 4-qubit H^4, seeds 1 .. 20 472 550 20.740 ```

Across twenty different seeds the answer moved by two counts. Unseeded it moved by 104, and the spread matches the binomial prediction to within 20%. The control rules out "this circuit is somehow deterministic": the same sixteen outcomes at the same shot count, produced by a static circuit, respond to the seed correctly — sd 20.7 against a predicted 21.9.

Symptom: error bars that collapse to almost nothing, and a difference between two variants that looks overwhelmingly significant. Cause: on circuits Aer cannot sample from a final statevector — which is any circuit with mid-circuit measurement or reset — varying seed_simulator did not deliver independent draws in this environment. Fix: take repeats by re-running unseeded, or by building a fresh simulator per repeat, and check the observed spread against the binomial prediction before you trust any error bar built from it.

Chapter 27 §27.7 makes the general version of this argument under a title worth memorising: seeding makes tests reproducible, not accurate. Here it did not even make them reproducible in the useful direction — it made twenty runs into one run, reported twenty times.

📉 Noise Report — what eight reuses actually cost on the device model.

Since the bin-counting statistic cannot answer "does reuse degrade," use one that does not depend on bin count: $P(\text{bit } i = 1)$ for each flip position, which is $0.5$ for every $i$ if nothing is wrong. Eight flips on one qubit, 8,192 shots, 12 independent repeats, on the 127-qubit noise model — ISA depth 39, with 8 measure and 7 reset:

```text flip mean P(1) SEM dev from 0.5


  0      0.5058   0.0022          +0.0058
  1      0.5062   0.0026          +0.0062
  2      0.5047   0.0014          +0.0047
  3      0.5053   0.0017          +0.0053
  4      0.5076   0.0014          +0.0076
  5      0.5047   0.0011          +0.0047
  6      0.5042   0.0015          +0.0042
  7      0.5051   0.0012          +0.0051

linear fit of deviation against flip index: slope -0.00014 per flip noiseless control, same metric, 12 repeats: mean P(1) = 0.4997 ```

Two findings, pointing in different directions.

There is a real bias, and it is not sampling noise. The noisy model gives a pooled $P(1) = 0.5054$ against the noiseless control's $0.4997$ — about half a percentage point, sitting comfortably inside this device's readout-error spread (min 0.0029, median 0.0198 across 127 qubits) and far outside the run-to-run scatter.

And it does not accumulate. The fitted slope is $-0.00014$ per flip: flat, if anything faintly negative. Flips 0–3 average $|\text{dev}| = 0.0055$; flips 4–7 average $0.0054$. Out to eight reuses on this model, reusing a qubit costs a constant per-measurement bias, not a growing one.

So the honest statement is narrower than "reuse degrades": this metric, on this noise model, out to eight reuses, sees a constant offset and no trend. Whether a real device accumulates something the model does not carry — leakage out of the computational subspace, a reset leaving population that a later gate is sensitive to, heating over a long shot — is a question this measurement cannot answer, and the standing caveat about mock backends (Chapter 11) applies in full: a noise model contains exactly the noise somebody chose to put into it.

🔬 Honest Assessment — When is qubit reuse worth it?

Worth it when your circuit's simultaneous qubit requirement is much smaller than its total, and when the added depth stays inside the coherence budget. Circuits with a natural sequential structure — repeated sampling, some state-preparation routines, certain simulation algorithms — fit this well.

Not worth it when the qubits are entangled with each other for most of the circuit, which is most interesting quantum algorithms. You cannot reuse a qubit that is still carrying part of an entangled state, and in a VQE ansatz essentially every qubit is.

The general shape: qubit reuse trades a resource you may not have (qubits) for one you certainly do not have much of (coherence time). On current hardware that is usually a bad trade, which is why you see it in demonstrations more than in practice. It becomes much more attractive as coherence times improve, and it is genuinely important for constrained architectures.

9.6 Repeat-Until-Success

A pattern that dynamic circuits make natural: attempt an operation that succeeds probabilistically, measure whether it worked, and retry if it did not.

# Sketch -- the loop bound matters, see below
for attempt in range(max_attempts):
    ...                                    # the probabilistic operation
    qc.measure(flag, c[attempt])
    with qc.if_test((c[attempt], 0)):      # failed?
        ...                                # reset and try again

The technique matters most in fault-tolerant contexts, where certain gates (notably $T$ gates synthesized from magic states) are implemented probabilistically and simply retried. It converts a gate that works 50% of the time into one that works essentially always, at the cost of a variable number of attempts.

The practical caveat on current hardware: a real repeat-until-success loop needs unbounded classical control flow, and hardware support for while-loops is more limited than for if. In practice you unroll to a fixed number of attempts and accept a small failure probability — which is fine, and is what the sketch above does.

The expected number of attempts, and why the mean is the wrong number

That unroll bound is a number somebody has to choose, so here is the cost model that chooses it.

If each attempt succeeds independently with probability $p$, the number of attempts $K$ until the first success is geometric:

$$P(K = k) = (1-p)^{k-1}p, \qquad \mathbb{E}[K] = \frac{1}{p}, \qquad \operatorname{Var}(K) = \frac{1-p}{p^2}$$

At the $p = 1/2$ typical of magic-state gate synthesis, $\mathbb{E}[K] = 2$. That is the number everybody quotes and it is the least useful one, because the standard deviation is $\sqrt{1-p}\,/\,p = \sqrt{2} \approx 1.41$ — 70% of the mean. The distribution has a long tail and no useful concentration.

What you actually need is the unrolled version's failure probability. Unroll to $k$ attempts and the loop fails only when all $k$ fail:

$$P(\text{fail}) = (1-p)^k \quad\Longrightarrow\quad k \;=\; \left\lceil \frac{\ln P_{\text{target}}}{\ln(1-p)} \right\rceil$$

At $p = 1/2$ with a target of $10^{-3}$: $k = \lceil \ln(10^{-3})/\ln(0.5) \rceil = \lceil 9.97 \rceil = 10$. Ten attempts to make a coin-flip gate work 999 times in 1,000 — five times the mean. For $10^{-6}$ it is 20, for $10^{-9}$ it is 30. The unroll depth grows like $\log(1/P_{\text{target}})$, which is the good news; at $p = 1/2$ the constant is exactly one attempt per factor of two, which is the bad news.

Now price it against the thing that binds. Each attempt costs at minimum one measurement and one reset, and §9.5 put those at 1,560 ns and 1,600 ns on Chapter 39's device — call it 3.2 μs of unavoidable per-attempt cost, before any gates and before any classical round trip:

   10 unrolled attempts  x  3.2 us  =  32 us   of measure + reset alone
   against median T2 (Ch. 31)          170.0 us   ->   19% of the budget
   against best-qubit T2               488.8 us   ->    7%
   against worst-qubit T2                2.6 us   ->  1,200%  -- impossible

A single repeat-until-success gate, unrolled to a 0.1% failure rate, spends about a fifth of a median qubit's coherence budget — and a fault-tolerant circuit needs many of them in sequence. That is why repeat-until-success is presented as a fault-tolerance technique rather than a NISQ one: it presupposes the very coherence budget that only error correction supplies, which is the circularity Chapter 25 §25.10 describes from the other side.

📐 Math Aside — size for the tail, not the mean.

The geometric distribution is memoryless, and that is what makes its mean misleading here. Having already failed $j$ times tells you nothing about how many more attempts you need: $P(K > j+m \mid K > j) = (1-p)^m$, independent of $j$. There is no "it's due," and no averaging down within a single gate.

The consequence bites when you count gates. If a circuit contains $n$ independent repeat-until-success gates, each unrolled to failure probability $q$, the whole circuit succeeds with probability $(1-q)^n \approx 1 - nq$ for small $nq$. To keep a circuit of 1,000 such gates working 99% of the time you need $q \le 10^{-5}$ per gate — which at $p = 1/2$ is $k = \lceil \ln(10^{-5})/\ln(0.5)\rceil = 17$ attempts, not 10, and 54 μs of measure-and-reset per gate rather than 32.

Per-item targets do not survive being multiplied together. This is the same arithmetic as Chapter 25 §25.8's threshold discussion and as Chapter 15's resource-estimate cliff — 450 physical qubits for a circuit with zero $T$ gates, 2,882 with one — where a per-item cost that looks trivial becomes the entire budget once you count the items. Every remedy is denominated in the currency of the disease.

9.7 What Dynamic Circuits Cost

The honest measurement. Compare a static three-qubit circuit against the teleportation circuit, both transpiled for the same device:

  circuit          ISA depth   2q   ops
  ------------------------------------------------------------------------
  static GHZ               9    2   {'rz': 8, 'sx': 5, 'measure': 3, 'ecr': 2, 'x': 1}
  teleportation           14    2   {'rz': 10, 'sx': 6, 'measure': 3, 'ecr': 2, 'if_else': 2}

Over 50% more depth for the same number of two-qubit gates. The extra is entirely the mid-circuit measurements and the two if_else blocks.

(A note that connects to Chapter 8: the same teleportation circuit with barriers between its four stages transpiles to depth 20 rather than 14. Barriers block optimization — §8.6 — and here they cost six layers. Keep them while you are reading the diagram; strip them before you run.)

And on the noisy device model, teleporting a state whose ideal $Z$ distribution is $[0.8824, 0.1176]$:

  ideal    P(0) = 0.8824
  hardware P(0) = 0.8350      (3420 / 4096)
  degradation   = 0.0474

The teleported state is recognizably right and measurably degraded — about five percentage points, consistent with the noise budget of a circuit this size.

💰 Cost and Queue — The cost that depth does not capture.

The ISA-depth comparison above understates the real difference, because a dynamic circuit has a cost with no static analogue: classical latency inside the quantum execution.

When the circuit reaches an if_test, the control system must read the measurement result, decide, and issue the conditional pulses — while the other qubits sit idle and decohere. That round trip is fast in absolute terms and slow compared to a gate. On superconducting hardware, gates take tens of nanoseconds and the measure-decide-act loop takes hundreds of nanoseconds to microseconds.

So a conditional block can cost more coherence than a dozen gates, and none of that appears in depth() or count_ops(). It is why dynamic circuits, despite being supported, are used sparingly outside error correction — and why reducing that latency is a major hardware engineering target.

When evaluating whether a dynamic circuit is worth it, the question to ask is not "how many extra gates" but "how long do my other qubits sit idle?" Chapter 31 §31.2's coherence budget and §31.4's dynamical decoupling measurements are the tools for reasoning about it.

The latency budget, and why it is error correction's hardest problem

The callout above says the round trip is "hundreds of nanoseconds to microseconds." The vagueness is not evasion — it is the honest state of a number that vendors do not publish per instruction and that no calibration table carries. What can be pinned down is the budget the number has to fit inside, and that is a calculation from measurements already in this book.

The constraint is $T_2$, not wall clock. A classical round trip of $\tau$ is neither fast nor slow in absolute terms; it is a fraction $\tau/T_2$ of the coherence of every qubit idling through it. On the 127-qubit device of §9.5, with $\tau = 1$ μs:

   against median T2   170.0 us   ->   0.59% of coherence per conditional block
   against best   T2   488.8 us   ->   0.20%
   against worst  T2     2.6 us   ->     38%

One conditional block, on the wrong qubit of the same chip, costs nearly 40% of its coherence. The teleportation circuit in this section has two of them. Nothing in depth() or count_ops() moves between the best case and the worst — the circuit is identical, and Chapter 29 §29.4 is the argument about how little say you have in which qubits you get.

Now scale it to the thing dynamic circuits exist for. Chapter 25 §25.7 showed syndrome extraction — measure the ancillas, decode the syndrome, apply the correction — and Chapter 25 is emphatic that this must run repeatedly, for the whole duration of the computation, because errors keep arriving. Each round costs at minimum a measurement plus a round trip.

That produces a hard real-time constraint with a specific failure mode. If the decoder takes longer to process one round of syndromes than the hardware takes to produce the next, the backlog grows without bound. It is a queueing condition rather than a fidelity one: at utilisation $\rho = t_{\text{decode}}/t_{\text{cycle}} \ge 1$ the queue diverges, and no amount of coherence rescues it, because the corrections arrive later and later relative to the errors they describe. Chapter 25 §25.7 states the requirement as "classical control fast enough to act inside the coherence time"; the queueing form is why it must be strictly less than one and not merely small.

This is exactly why Chapter 40 §40.1 lists error-correction decoder as one of seven distinct careers, and describes it as a real-time inference problem under a latency budget set by the physics — wanting algorithms, HPC, sometimes FPGA or ASIC, increasingly machine learning, and the stabilizer formalism but nothing beyond it. It is one of very few roles in that chapter where the binding constraint is measured in microseconds rather than in mathematics.

The through-line of this chapter is that job description. if_test is the syntax; the latency of the loop it opens is the engineering problem; Chapter 25's threshold is what you get if the problem is solved. A reader who finds §9.7 the least interesting section of this chapter has the ranking exactly inverted.

🐛 Debug This — "just schedule it and read the duration."

Case Study 2 tells you to ask for a dynamic circuit's duration rather than its depth. Reasonable advice, and the obvious way to act on it does not work:

python from qiskit.transpiler.passes import ALAPScheduleAnalysis PassManager([ALAPScheduleAnalysis(backend.target.durations())]).run(isa_teleportation)

text TranspilerError: 'Duration of if_else on qubits [2] is not found.'

The scheduler is not broken and the backend is not incomplete. §9.1's ⚙️ callout showed why: if_else sits in the target with {None: None} against it. There is no duration to look up, because the duration is not a property of the instruction — it depends on the control stack, its firmware, and how the job was compiled.

The fix is not a workaround; it is to stop expecting the number from the compiler. If you need it, measure it on the device: run a circuit with a conditional block and an idling witness qubit, run the same circuit with the block removed, and read the difference off the witness's decay. Exercise 9.13 and Case Study 2's question 5 both ask you to design exactly that, and they ask rather than tell because the answer is device-specific and stale the moment it is written down.

A number no API will give you is usually a number that is not a property of the thing you are asking about.

🧪 Run It — three measurements, about ten minutes.

  1. Reproduce §9.2's three-way table. Build static GHZ, dynamic teleportation, and deferred teleportation; transpile all three for the same mock backend with the same seed_transpiler; print depth() and count_ops(). Then change the seed and print them again. Chapter 39's 24-seed sweep found a 2.03× fidelity spread on a 14-qubit layout and exactly zero variation on four qubits — predict which regime a 3-qubit teleportation is in before you look, then check.

  2. Break the teleportation and see which basis catches it. Delete the $Z$ correction; then the $X$ correction; then swap them. Run the three-basis check on each and build the diagnosis table. One of the three bugs is invisible in two of the three bases. Find out which, and you will never again accept a single-basis verification from anybody.

  3. Find the reuse ceiling that matters to you. Take §9.5's reuse circuit out to 12 flips on the noise model and track $P(\text{bit } i = 1)$ per flip — not a max-over-bins statistic, for the reason the 📊 callout gives. Get your repeats without seed_simulator, for the reason the 🐛 callout gives. Then state, with an error bar, the number of reuses at which the bias exceeds your tolerance. If it never does within 12, say that instead — a ceiling you failed to find is a result, and a more useful one than a ceiling you assumed.

🧱 Project Checkpointmeasure.py v1, and a negative result.

This checkpoint adds a mid-circuit measurement variant of the project's expectation-value routine — and then establishes that VQE should not use it.

That is a deliberate and slightly unusual checkpoint. The reasoning:

A VQE's ansatz keeps every qubit entangled with the others throughout the circuit (that is what the entangling layers are for), so there is no qubit to reuse. Adding mid-circuit measurement would buy nothing and cost the latency above.

Knowing why a technique does not apply is worth as much as knowing how to use one, and it is the more common situation. The checkpoint implements the variant, measures that it is slower and no more accurate on the project's ansatz, and records the conclusion — so that when someone proposes it in six months, the answer is a measurement rather than an opinion.

The genuinely useful piece it does add: measure_with_reset(), for the case where the project's Hamiltonian eventually needs more measurement qubits than the device has. Chapter 36 will not need it for H₂. It might for LiH.

9.8 Summary

Dynamic circuits add classical control flow to a quantum program: measure mid-circuit, branch on the result, act — inside a single execution with the state still live. The syntax is if_test as a context manager, with optional else. c_if was removed in Qiskit 1.0.

They do not increase what is computable, and they do change what is practical: they enable qubit reuse, they are how error correction works, and they make protocols like teleportation expressible in a single circuit.

Check the deferred-measurement principle before you write a dynamic circuit at all. A measurement used only to control later gates can be replaced by a coherent controlled gate, with identical output statistics — proved in two lines from $U^{k\dagger}U^k = I$. Teleportation with its corrections deferred verified in all three bases (worst disagreement 0.0062 against a sampling error of 0.0110) and was the most expensive of the three circuits: ISA depth 25 and seven two-qubit gates, against the dynamic version's 14 and two. Three of those seven are one SWAP the router had to insert, because the deferred $Z$ correction spans physical qubits 124 and 122 with 123 in between. Deferring buys you out of latency by spending connectivity, and which is cheaper is a property of the device, not of the protocol. The principle also cannot rescue qubit reuse or error correction: both need the measured value as a classical value, which is precisely what deferring refuses to produce.

The exchange rate is set by the Pauli group, not by convenience. Expanding the three-qubit state gives four branches of amplitude exactly $1/2$ each — $|\psi\rangle$, $X|\psi\rangle$, $Z|\psi\rangle$, $ZX|\psi\rangle$ — so two classical bits is the exact amount of communication, one bit being provably insufficient. Bob's pre-message state is the Pauli twirl of $|\psi\rangle\langle\psi|$, which equals $I/2$ for every input: not information that is hard to extract, information that is not there.

Teleportation moves an unknown state using a shared Bell pair and two classical bits: prepare, share entanglement, Bell-measure Alice's two qubits (Chapter 4 §4.5's construction, run backward), and apply one of four Pauli corrections conditioned on her outcomes.

Verify it in more than one basis. Measured across all three Bloch axes at 8,192 shots, the worst disagreement between the teleported and original expectation values was 0.0059 against a sampling error of 0.0110 — consistent on every axis. One basis proves almost nothing; three bases is single-qubit tomography and is the honest standard. Alice's four outcomes each occurred about a quarter of the time, which is the cleanest demonstration that her result carries no information about the state.

Teleportation does not violate no-cloning — the original is destroyed. It does not beat light — the two classical bits carry the information and travel classically; before they arrive Bob's qubit is maximally mixed. Nothing physical is transported. The exact exchange rate: one entangled pair + two classical bits → one transmitted qubit state.

Superdense coding is the same trade reversed: one entangled pair + one transmitted qubit → two classical bits, and it works deterministically for all four messages. Its real benefit is a shift in timing — the expensive entanglement distribution happens in advance — not a reduction in total qubit traffic.

⚠️ Superdense coding's output shows Alice's 01 arriving as Bob's '10', which is little-endian ordering, not a bug. Test protocols with asymmetric inputs; palindromes hide ordering errors.

reset enables qubit reuse, converting a width constraint into a depth constraint. Verified: two independent coin flips from one physical qubit. Worth it when simultaneous qubit usage is much lower than total; not worth it for most quantum algorithms, where qubits stay entangled throughout — as in every VQE ansatz.

Dynamic circuits cost more than they look. Measured: teleportation at ISA depth 14 against a comparable static circuit's 9, with the same two-qubit gate count — and depth 20 if you leave the barriers in. On the noisy model the teleported state came back about five percentage points degraded.

The larger cost is invisible to depth(): the measure-decide-act latency, during which every other qubit sits idle and decoheres. Gates take tens of nanoseconds; that round trip takes hundreds to thousands. Ask "how long do my qubits sit idle," not "how many extra gates."

And it is invisible to the compiler too, not only to you. if_else appears in a real backend's target with {None: None} against it — no duration, no error rate — so durations().get("if_else", [2]) raises TranspilerError while measure beside it answers 1,216.0 ns. The cost is not a property of the instruction; it belongs to the control stack. Denominate it in $T_2$ rather than in nanoseconds and it becomes legible: a 1 μs round trip is 0.59% of a median qubit's coherence on the 127-qubit device and 38% of the worst qubit's on the same chip, for the same circuit. That fraction, not the gate count, is what decides whether a dynamic circuit is worth running — and driving it below one syndrome cycle is the whole of the decoder role Chapter 40 §40.1 describes.

Reuse is priced in the same currency. A reset is 8.7 to 27.2 two-qubit gates on Chapter 39's device and 1.4 to 4.1 on this one — a factor of six between devices, so no portable rule of thumb exists. Against measured coherence it is 264 resets on the best qubit, 92 on the median, 1.4 on the worst. And beware the demonstration: $H$ after an imperfect reset gives $P(0) = \tfrac12$ exactly, for every leakage probability $\epsilon$, so the coin-flip test cannot detect a bad reset at all — Chapter 15 §15.5 measured 251/249 from a qubit that was never reset. Measured properly, with a bin-count-independent metric and 12 repeats, the noise model shows a real but constant per-measurement bias (pooled $P(1) = 0.5054$ against a noiseless 0.4997, fitted slope $-0.00014$ per flip): out to eight reuses it does not accumulate.

Repeat-until-success is a fault-tolerance technique, and the arithmetic says why. Attempts are geometric, so $\mathbb{E}[K] = 1/p$ but the standard deviation is 70% of the mean at $p = 1/2$; the number that matters is the unroll bound, $k = \lceil \ln P_{\text{target}}/\ln(1-p)\rceil$ — 10 attempts for a $10^{-3}$ failure rate, five times the mean, and 17 if a thousand such gates must all work. At 3.2 μs of measure-plus-reset per attempt that is 19% of a median qubit's coherence budget for one gate.


Next: Chapter 10 — the transpiler in full. Basis gates, coupling maps, routing, layout algorithms, optimization levels, custom passes, and how to read the difference between what you wrote and what runs.