Error-detected preparation of the W state with dynamic circuits
Usage estimate: 10 seconds on a Nighthawk r2 processor (Note: This is an estimate only. Your runtime might vary.)
Learning outcomes
- Understand how to implement the constant-depth preparation of W states with dynamic circuits
- Learn to implement the DisCo ED protocol through example
- Compare the explicit and implicit DisCo ED checks with no error detection, and identify which errors each one catches
Prerequisites
- Dynamic circuits
- Long-range entanglement with dynamic circuits
- Stabilizer formalism and the repetition code
Background
This tutorial reproduces the error-detected, approximate preparation of a W state by using dynamic circuits, as presented in Smith, Pokharel, Maurya, Takita, "Resilience Beyond the Light Cone: Error-Detected Primitives for Practical Dynamic Circuits" (2026) [1].
The approach is an adaptation of the algorithm presented in Piroli, Styliaris, Cirac, "Approximating many-body quantum states with quantum circuits and measurements" (2024) [2], upgraded with the Distributed Control Error Detection (DisCo ED) scheme of Smith et al. The paper runs the protocol on a heavy-hex processor. Here, the protocol runs on the square lattice of a Nighthawk processor. The noisy simulation reproduces its main finding: both DisCo ED checks improve the prepared state compared with no error detection, and the implicit check gives the best state. On hardware at , the idle time during the feedforward limits how much error detection can recover, as discussed after the hardware results.
The following sections describe the ingredients of this tutorial in detail.
The W state
The -qubit W state is the equal superposition of all states with exactly one excitation,
where has a single on qubit . Unlike the GHZ state, its entanglement survives the loss of any one qubit. This tutorial characterizes the prepared state with two simple observables.
- Hamming-weight distribution. Measure every qubit in the basis and count the number of 1s, . A perfect W state gives .
- Coherence. alone does not certify a W state: an incoherent mixture , or a superposition with random signs, also has . To probe the relative phases, use
The operator moves an excitation between qubits and . For a state it gives , so for , for the incoherent mixture, and random signs push toward zero. Measuring takes only two extra circuits: one with every W qubit measured in the basis, and one in the basis.
Dynamic circuits
A unitary circuit of nearest-neighbor gates spreads correlations only within a light cone that grows by a fixed distance per layer. Preparing a long-range entangled state such as a GHZ or W state on a line of qubits therefore takes a depth that grows with . Dynamic circuits, which use mid-circuit measurements and classical feedforward, get around this limit: measurement outcomes are processed classically and sent to qubits anywhere on the chip, in a time that does not depend on distance.
A paradigmatic example is the constant-depth GHZ state (see the long-range entanglement tutorial and [3]). The protocol splits the line into small patches and prepares small GHZ states on each patch in parallel. It then fuses neighboring patches by measuring the parity across each boundary. Outcome means the two patches disagree. Applying to every qubit of patch whenever the cumulative parity is 1 fixes every disagreement in a single round of feedforward. In this circuit, each measured qubit is then reset and re-entangled with its own patch, so all qubits end up in
in a depth that does not depend on .
Approximate preparation of the W state
The idea of the W-state-preparation protocol of Ref. [2] is to start from a product state that overlaps strongly with , then project away the unwanted components. Rotating every qubit with , where , gives
where is the uniform superposition of all weight- states (the Dicke state, with ). For small , almost all of the weight is in and . Projecting onto odd parity with removes and leaves
The projection succeeds with probability , and the fidelity with the W state is . Choosing , for large
Neither depends on , so the cost of the protocol does not grow with system size. The parameter trades fidelity against success rate. This tutorial uses , which gives and . The small remaining infidelity comes from higher odd-weight components.
Single-ancilla projection. One way to apply is a Hadamard test. Prepare an ancilla in , apply between the ancilla and every system qubit (a controlled-), and measure the ancilla in the basis:
Outcome "" heralds the odd sector. The catch is that a single ancilla must interact with all qubits, requiring a circuit depth proportional to .
Distributed control. Replace the single ancilla with an -qubit GHZ state prepared via dynamic circuits, and place the GHZ qubit next to W qubit . The GHZ state behaves as one logical qubit, with , , and logical operator . The controlled- becomes on every pair at once, a single layer of gates. Measuring means measuring every GHZ qubit in the basis and multiplying the outcomes, so an odd number of 1s heralds success. Every step now has constant depth. On a square lattice, the GHZ line and the W line form a ladder: two rows of qubits joined by rungs.
(a) The GHZ line and the W line occupy two neighboring rows of the square lattice and are joined by rungs. (b) The GHZ line alone. The staggered prep patches (shaded) are fused by mid-circuit measurements at the marked boundaries. Each boundary falls inside one of the DisCo ED detection pairs (check , root ), so a faulty fusion is detected.
DisCo ED
While the distributed control technique reduces the procedure to a constant depth circuit, it does not come for free. It requires ancillas and, more importantly, mid-circuit measurements. Readout error is typically slightly worse than two-qubit gate error on superconducting devices, so implementing this strategy can introduce significant noise. Additional challenges include the fact that the GHZ qubits sit idle during the mid-circuit measurements and feedforward, making them susceptible to relaxation and dephasing errors, and the final readout requires measurement of an -qubit operator.
To dig further into the impact of noise, consider the effect of each type of error on the GHZ state throughout this protocol:
- Bit flips: The CZ layer turns (with denoting the -th GHZ qubit) into (with denoting the -th W state qubit), so a bit flip on applies to . Because commutes with , the herald is unaffected, and the error flips the sign of one W amplitude. The Hamming weight is blind to this, but drops.
- Fusion readout errors: Because the parity of fusion mid-circuit measurement outcomes determines the pattern of X-corrections applied via feedforward when preparing the GHZ state, a wrong fusion outcome creates a pattern of bit flip errors called a domain wall. Depending on how the feedforward corrections are applied, a domain wall between sites and produces a bit-flip error on all GHZ qubits to the left (or right) of the domain wall. The impact of these bit flip errors on the state is as discussed above.
- Phase flips and readout errors on the GHZ qubits flip the herald, so the protocol accepts the even-parity sector by mistake. These show up as weight 0 and weight 2 in the Hamming-weight distribution.
DisCo ED starts from the observation that the GHZ state is a repetition code: its stabilizers are and its logical operator is . A plain readout measures each qubit in the basis, which reveals but by gathering independent pieces of information that are not useful to the protocol (that is, each individual ). The idea of DisCo ED is to replace these "useless" measurements with more useful ones, while still gathering the necessary information to construct . In particular, group the GHZ qubits into pairs , each with a check qubit and a root qubit . Because and commute, you can measure both. A from to maps and , so afterward:
- the root, measured in the basis, gives bit , the value of . The product of all root outcomes is , so the herald is an odd number of 1s among the .
- the check, measured in the basis, gives bit , the value of the stabilizer . Without errors, .
This gives two variants.
- Explicit check: , then on . Reject the shot if any .
- Implicit check: add a second after the . The root still gives , but the check now measures the product , so without errors . Reject the shot if any .
Both variants check the same stabilizers. The difference is what happens when a readout error occurs on a root qubit: it flips the herald without touching any stabilizer, so the explicit check misses it, while the implicit check catches it because no longer matches . The implicit readout compiles to the same single two-qubit gate as , so this extra protection costs no additional two-qubit gates.
Each pair is a detection patch of size . The paper also considers larger patches, which check more stabilizers at the cost of a deeper readout; this tutorial uses throughout. With , DisCo ED detects:
- any single bit flip on a GHZ qubit, because every GHZ qubit belongs to exactly one checked pair.
- fusion errors, provided the domain wall falls inside a pair. This is why the GHZ preparation, as shown below, uses the staggered patches : their boundaries lie inside the detection pairs . If the prep patches were aligned with the pairs, every domain wall would fall between two pairs, where nothing is checked.
- readout errors on the root qubits, with the implicit check only.
DisCo ED does not detect phase flips on the GHZ qubits, or any error on the W qubits themselves, so postselection improves the state without making it perfect. The price is the fraction of shots discarded (the acceptance rate is less than 1) and one extra layer of two-qubit gates in the readout. No additional qubits are needed over the non-error detected implementation.
Requirements
Before starting this tutorial, be sure you have the following installed:
- Qiskit SDK v2.0 or later, with visualization support
- Qiskit Runtime v0.47 or later (
pip install qiskit-ibm-runtime) - Qiskit Aer v0.17 or later (
pip install qiskit-aer), for the noiseless and noisy simulations - NumPy, SciPy, and Matplotlib
For best results, the hardware runs should be conducted on ibm_chicago, a Nighthawk R2 device. These latest devices have fast resets, an important component to the demonstration in this tutorial.
Setup
The cell below imports the required tools and defines the helper functions used to analyze the results. The functions that build the circuit are defined step by step in the small-scale example below.
Each circuit stores its measurement outcomes in up to four classical registers:
fusion: the parity measurements used to fuse the GHZ patchesghz: the GHZ readout bits that herald the W state (the root of each pair, or every GHZ qubit with no error detection)flag: the DisCo ED check bits (one per pair; not present without error detection)w: the final measurement of the W qubits
The analysis has three steps. postselect keeps only the shots that pass the DisCo ED check (flag is cross-checked with ghz) and that herald the odd-parity sector (an odd number of 1s in ghz). The kept w bits then give the Hamming-weight distribution, the coherence , and bounds on the fidelity with . Finally, exact_reference gives the ideal values derived in the Background section. (If the circuits were built with feedforward=False, postselect first applies the GHZ corrections that were left for postprocessing. See Step 1 below.)
import heapq
from collections import defaultdict
from math import comb
import matplotlib.pyplot as plt
import numpy as np
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
from qiskit.circuit import IfElseOp, Measure, Reset
from qiskit.circuit.classical import expr
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit.primitives import BitArray
from qiskit.transpiler import generate_preset_pass_manager
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import QiskitRuntimeService
from qiskit_ibm_runtime import SamplerV2 as Sampler
from qiskit_ibm_runtime.fake_provider import FakeMiami
from scipy.optimize import linear_sum_assignment
CHECKS = [
None,
"explicit",
"implicit",
] # DisCo ED modes compared in this tutorial
BASES = ["Z", "X", "Y"] # measurement bases for the W qubits
COLORS = {None: "#2a78d6", "explicit": "#eb6834", "implicit": "#1baf7a"}
EXACT_COLOR = "#898781"
GHZ_COLOR = "#6250d6"
W_COLOR = "#d55181"
def ghz_patches(n):
"""Staggered GHZ prep patches [0], [1, 2], [3, 4], ..., with the last qubit added to the last patch.
Their boundaries fall inside the DisCo ED pairs [0, 1], [2, 3], ...
"""
patches = [[0]] + [[2 * k - 1, 2 * k] for k in range(1, n // 2)]
patches[-1].append(n - 1)
return patches
def fast_readout(qct, backend):
"""Swap in the backend's fused fast-readout instructions on an already-transpiled circuit.
Two rewrites on the circuit DAG:
- A ``measure`` immediately followed by a ``reset`` on the same qubit is fused into a single
``measure_reset_2`` (one calibrated measure-and-reset, faster than a separate measure then
reset). The reset's sole quantum predecessor on that wire must be the measure, so only a
genuine measure->reset pair fuses.
- Every remaining (final) ``measure`` becomes ``measure_2``. The fused ones are already
``measure_reset_2`` nodes by now, so this loop only touches the true final measures.
``measure_reset_2`` / ``measure_2`` are hardware-specific; ``backend.target`` must define them.
Clbits are preserved exactly, so ``postselect`` is unaffected. The
circuit_to_dag/dag_to_circuit round-trip drops the TranspileLayout, so we carry it back over
(plot_layout and the sampler need qct.layout to survive).
"""
tgt = backend.target
mr2 = tgt.operation_from_name("measure_reset_2")
m2 = tgt.operation_from_name("measure_2")
dag = circuit_to_dag(qct)
for rnode in list(dag.op_nodes(Reset)):
preds = list(dag.quantum_predecessors(rnode))
if (
len(preds) == 1
and getattr(preds[0], "op", None) is not None
and isinstance(preds[0].op, Measure)
):
dag.substitute_node(preds[0], mr2, inplace=True)
dag.remove_op_node(rnode)
for mnode in list(dag.op_nodes(Measure)):
dag.substitute_node(mnode, m2, inplace=True)
new_qct = dag_to_circuit(dag)
new_qct._layout = (
qct._layout
) # dag_to_circuit resets .layout to None; restore the transpile layout
return new_qct
def deferred_corrections(fusion, n):
"""The X corrections of the GHZ preparation, one bit per shot and GHZ qubit.
GHZ qubits in patch k need an X when the parity of the first k fusion outcomes is odd.
"""
parity = np.cumsum(fusion.to_bool_array(order="little"), axis=1) % 2
flips = np.zeros((fusion.num_shots, n), dtype=bool)
for k, patch in enumerate(ghz_patches(n)[1:]):
flips[:, patch] = parity[:, [k]]
return flips
def postselect(data, basis, check, feedforward=True):
"""Keep the shots that pass the DisCo ED check and herald the odd-parity sector.
With feedforward=False the GHZ corrections were not applied on the device, so we apply them to
the measured bits here. An X on GHZ qubit g_j commutes with the X-basis readout, so the herald is
unchanged. The CZ layer turns it into a Z on w_j, which flips an X- or Y-basis outcome of w_j,
and the DisCo ED readout moves it onto the check bit of its pair.
Returns the kept W-qubit bits and a dict with the acceptance rate (fraction of shots passing
the check) and the success rate (fraction of accepted shots heralding odd parity).
"""
ghz, w, flag = data.ghz, data.w, getattr(data, "flag", None)
if not feedforward:
flips = deferred_corrections(data.fusion, w.num_bits)
if basis in ("X", "Y"):
w = w ^ BitArray.from_bool_array(flips, order="little")
if check is not None:
flag = flag ^ BitArray.from_bool_array(
flips[:, 0::2] ^ flips[:, 1::2], order="little"
)
if check is None:
passed = np.ones(ghz.num_shots, dtype=bool)
elif check == "explicit":
passed = flag.bitcount() == 0 # every stabilizer Z_c Z_r = +1
elif check == "implicit":
passed = (
flag ^ ghz
).bitcount() == 0 # every flag bit equals its root bit
heralded = (
ghz.bitcount() % 2 == 1
) # odd number of 1s: logical X of the GHZ state is -1
rates = {"acceptance": passed.mean(), "success": heralded[passed].mean()}
return w.slice_shots(np.flatnonzero(passed & heralded)), rates
def hamming_weight_distribution(w_bits):
"""Probability of each Hamming weight 0, ..., n among the measured W-qubit bitstrings."""
weights = w_bits.bitcount().astype(int)
return (
np.bincount(weights, minlength=w_bits.num_bits + 1) / w_bits.num_shots
)
def coherence(x_bits, y_bits):
"""C = (n/4) * average over pairs i != j of <X_i X_j + Y_i Y_j>.
For one shot with outcomes s_j = +/-1, the sum over pairs i != j of s_i s_j is S^2 - n,
where S is the sum of all s_j.
"""
n = x_bits.num_bits
def mean_pair_correlation(bits):
s = 1 - 2 * bits.to_bool_array().astype(int)
total = s.sum(axis=1)
return np.mean((total**2 - n) / (n * (n - 1)))
return (
n
/ 4
* (mean_pair_correlation(x_bits) + mean_pair_correlation(y_bits))
)
def fidelity_bounds(hamming, coherence):
"""Lower and upper bounds on the fidelity F with |W_n>, from the Hamming weights and C.
F = (P(w=1) + h_1) / n, where h_1 is the weight-1 part of the hopping operator
h = sum over i != j of sigma_i^+ sigma_j^-. The total of h is (n - 1) C, and its weight-k part
lies between -k P(w=k) and k (n - k) P(w=k), which bounds h_1. F is also at most P(w=1).
With finite shots the estimated lower bound can exceed P(w=1), so we clip it there.
"""
n = len(hamming) - 1
k = np.arange(n + 1)
total = (n - 1) * coherence
lower = (hamming[1] + total - np.sum((k * (n - k) * hamming)[2:])) / n
upper = (hamming[1] + total + np.sum((k * hamming)[2:])) / n
return float(np.clip(lower, 0, hamming[1])), float(min(upper, hamming[1]))
def exact_reference(n, delta):
"""Ideal success rate, Hamming-weight distribution, and coherence of the protocol."""
p = delta / n
k = np.arange(n + 1)
weights = np.array(
[comb(n, j) * p**j * (1 - p) ** (n - j) for j in k]
) * (k % 2)
hamming = weights / weights.sum()
return {
"success": weights.sum(),
"hamming": hamming,
"coherence": np.sum(
hamming * k * (n - k) / (n - 1)
), # C of the Dicke state D_k is k(n-k)/(n-1)
"fidelity": hamming[1], # the weight-1 component is exactly |W_n>
}
def add_stretch_dd(qc, q, name):
s = qc.add_stretch(name)
qc.delay(s, q)
qc.x(q)
qc.delay(s, q)
qc.delay(s, q)
qc.rz(np.pi, q)
qc.x(q)
qc.rz(-np.pi, q)
qc.delay(s, q)
return qc
def summarize(results, exact, feedforward=True):
"""Postselect every (check, basis) result, print a table, and return the metrics."""
summary = {}
print(
f"{'check':>9} {'acceptance':>11} {'success':>8} {'P(w=1)':>7} {'C':>6} {'F':>12}"
)
print(
f"{'expected':>9} {1:>11.3f} {exact['success']:>8.3f} {exact['hamming'][1]:>7.3f} "
f"{exact['coherence']:>6.3f} {exact['fidelity']:>12.3f}"
)
for check in CHECKS:
kept = {}
for basis in BASES:
kept[basis], rates = postselect(
results[check, basis].data, basis, check, feedforward
)
if basis == "Z":
s = dict(rates)
s["hamming"] = hamming_weight_distribution(kept["Z"])
s["coherence"] = coherence(kept["X"], kept["Y"])
s["fidelity"] = fidelity_bounds(s["hamming"], s["coherence"])
summary[check] = s
low, high = s["fidelity"]
print(
f"{str(check):>9} {s['acceptance']:>11.3f} {s['success']:>8.3f} {s['hamming'][1]:>7.3f} "
f"{s['coherence']:>6.3f} {low:>5.3f}-{high:.3f}"
)
return summary
def plot_results(summary, exact, title, max_weight=4):
"""Hamming-weight distribution (left), and P(w=1), C, and the fidelity lower bound (right)."""
fig, (ax_hw, ax_obs) = plt.subplots(
1, 2, figsize=(11, 4), gridspec_kw={"width_ratios": [3, 2]}
)
width = 0.2
bar_style = {"width": width, "edgecolor": "white", "linewidth": 1}
weights = np.arange(max_weight + 1)
ax_hw.bar(
weights - 1.5 * width,
exact["hamming"][: max_weight + 1],
color=EXACT_COLOR,
label="expected",
**bar_style,
)
for i, check in enumerate(CHECKS):
hamming = summary[check]["hamming"][: max_weight + 1]
ax_hw.bar(
weights + (i - 0.5) * width,
hamming,
color=COLORS[check],
label=f"check = {check}",
**bar_style,
)
ax_hw.set(
xlabel="Hamming weight",
ylabel="Probability",
xticks=weights,
ylim=(0, 1.05),
)
ax_hw.legend(frameon=False)
metrics = np.arange(3)
for i, check in enumerate(CHECKS):
values = [
summary[check]["hamming"][1],
summary[check]["coherence"],
summary[check]["fidelity"][0],
]
ax_obs.bar(
metrics + (i - 1) * width,
values,
color=COLORS[check],
**bar_style,
)
ax_obs.hlines(
[exact["hamming"][1], exact["coherence"], exact["fidelity"]],
metrics - 0.35,
metrics + 0.35,
colors=EXACT_COLOR,
linestyles="--",
label="expected",
)
ax_obs.set(
xticks=metrics,
xticklabels=[r"$P(w=1)$", r"$C$", r"$F$ (lower bound)"],
ylim=(0, 1.15),
)
ax_obs.legend(frameon=False, loc="upper right")
for ax in (ax_hw, ax_obs):
ax.spines[["top", "right"]].set_visible(False)
fig.suptitle(title)
fig.tight_layout()
plt.show()
def plot_layout(isa_circuit, backend):
"""Draw the backend's square lattice and mark the physical qubits of the GHZ and W lines."""
edges = {tuple(sorted(edge)) for edge in backend.coupling_map.get_edges()}
# Qubits are numbered row by row: horizontal neighbors differ by 1, vertical ones by the row width
width = min(abs(a - b) for a, b in edges if abs(a - b) > 1)
xy = {q: (q % width, -(q // width)) for q in range(backend.num_qubits)}
# Physical qubit of each circuit qubit, in the order q_ghz[0..n-1], then q_w[0..n-1]
physical = isa_circuit.layout.initial_index_layout(filter_ancillas=True)
n = len(physical) // 2
ghz, w = physical[:n], physical[n:]
ladder = {tuple(sorted(pair)) for pair in zip(ghz[:-1], ghz[1:])} | {
tuple(sorted(pair)) for pair in zip(ghz, w)
}
fig, ax = plt.subplots(
figsize=(0.5 * width, 0.5 * (backend.num_qubits // width))
)
for a, b in edges:
used = (a, b) in ladder
ax.plot(
*zip(xy[a], xy[b]),
color="#383835" if used else "#e1e0d9",
lw=2.5 if used else 1,
zorder=1,
)
ax.scatter(*zip(*xy.values()), s=12, color="#c3c2b7", zorder=2)
for qubits, color, name in [
(ghz, GHZ_COLOR, "GHZ line"),
(w, W_COLOR, "W line"),
]:
ax.scatter(
*zip(*(xy[q] for q in qubits)),
s=180,
color="white",
edgecolors=color,
linewidths=2,
zorder=3,
label=name,
)
for j, q in enumerate(qubits):
ax.text(
*xy[q], str(j), ha="center", va="center", fontsize=7, zorder=4
)
ax.set_aspect("equal")
ax.axis("off")
ax.legend(loc="upper left", bbox_to_anchor=(1, 1), frameon=False)
ax.set_title(f"Layout on {backend.name}: qubit j of each line")
plt.show()Small-scale simulator example
First, run the protocol in simulation for W qubits (12 qubits in total), in two ways:
- Expected reference: the ideal values derived in the Background section, computed by
exact_reference.StatevectorSamplercannot run circuits that contain classical feedforward (if_test), so this example also runs the logical (untranspiled) circuits on the noiselessAerSimulator. This checks both the circuits and the postprocessing: without noise, every shot should pass the DisCo ED check, and the results should agree with the expected values up to shot noise. - Noisy run: local testing mode with
FakeMiami, a fake Nighthawk backend with the same square lattice as the hardware example. This shows how far a hardware-like result drifts from the expected one, and how much of the gap DisCo ED recovers.
Step 1: Map classical inputs to a quantum problem
The circuit uses two lines of qubits: the GHZ line q_ghz, which serves as the distributed control, and the W line q_w, which ends up in the W state. The circuit has three pieces, one for each stage of the protocol.
1. Prepare the GHZ state. prepare_ghz splits the GHZ line into the staggered patches (the last patch also takes the final qubit) and prepares a small GHZ state in each patch. It then fuses neighboring patches. A CNOT copies the parity of the two qubits on either side of a boundary onto , the first qubit of the right patch. Qubit is then measured into fusion, reset, and re-entangled with its patch. Finally, the feedforward applies to every qubit of patch if the parity of the first fusion outcomes is odd. The conditions are built with expr.bit_xor, so all corrections happen in one round of feedforward.
Every correction is an , and the rest of the circuit only moves it around: the CZ layer turns into , and the GHZ readout carries it onto known bits. So the measurement statistics are the same if, instead of applying the corrections on the device, you apply them to the measured bits afterward (deferred_corrections and postselect in the Setup cell). This is called tracking the Pauli frame. Note that it does not prepare the W state on the device; it only reproduces the outcomes that the device would have measured. prepare_ghz therefore applies the corrections in real time by default (feedforward=True). Setting feedforward=False is a useful diagnostic: it removes the wait for the fusion outcomes to reach the controller and come back, during which the whole GHZ line idles, so comparing the two settings shows how much error that wait adds.
def prepare_ghz(qc, qr_ghz, cr_fusion, use_DD=True, feedforward=True):
"""Prepare an n-qubit GHZ state (n even) in constant depth with mid-circuit measurements.
With feedforward=False, the X corrections are left for postselect to apply to the measured bits
(a diagnostic; the state itself is then not prepared on the device).
"""
n = len(qr_ghz)
patches = ghz_patches(n)
# Small GHZ state in each patch, spread out from the middle qubit
for patch in patches:
middle = patch[len(patch) // 2]
qc.h(qr_ghz[middle])
for q in patch:
if q != middle:
qc.cx(qr_ghz[middle], qr_ghz[q])
# Fuse neighboring patches: measure Z_a Z_b across each boundary, then reset b and
# re-entangle it with the next qubit of its own patch
for k in range(1, len(patches)):
qc.cx(qr_ghz[patches[k - 1][-1]], qr_ghz[patches[k][0]])
# Measure and reset the boundary qubits. The rest of the GHZ line idles through the slow
# mid-circuit measurement, so fill that window with stretch DD. The barriers pin the DD to
# the measure/reset window; the re-entangling CNOTs come after.
measured = [patches[k][0] for k in range(1, len(patches))]
qc.barrier(qr_ghz)
for k in range(1, len(patches)):
first = patches[k][0]
qc.measure(qr_ghz[first], cr_fusion[k - 1])
qc.reset(qr_ghz[first])
if use_DD:
for q in range(n):
if q not in measured:
add_stretch_dd(qc, qr_ghz[q], f"dd_fusion_{q}")
qc.barrier(qr_ghz)
for k in range(1, len(patches)):
first, second = patches[k][0], patches[k][1]
qc.cx(qr_ghz[second], qr_ghz[first])
# Feedforward: flip patch k if the parity of the first k fusion outcomes is odd
if not feedforward:
return
parity = None
for k in range(1, len(patches)):
bit = cr_fusion[k - 1]
parity = (
expr.lift(bit) if parity is None else expr.bit_xor(parity, bit)
)
with qc.if_test(parity):
for q in patches[k]:
qc.x(qr_ghz[q])2. Seed and couple the W qubits. couple_w_qubits rotates every W qubit with , where so that . It then applies on every rung of the ladder, which is the controlled- of the distributed Hadamard test. The circuit applies the rotations after the GHZ preparation, just before the CZ layer. That way, the W qubits wait in , which does not decay, during the slow mid-circuit measurements and feedforward.
def couple_w_qubits(qc, qr_ghz, qr_w, delta):
"""Rotate each W qubit so that P(|1>) = delta / n, then couple it to its GHZ partner."""
n = len(qr_w)
qc.ry(2 * np.arcsin(np.sqrt(delta / n)), qr_w)
for j in range(n):
qc.cz(qr_ghz[j], qr_w[j])3. Read out the GHZ state with DisCo ED. readout_ghz measures the logical of the GHZ state. With check=None, every GHZ qubit is measured in the basis into ghz. With "explicit" or "implicit", the GHZ line is split into the pairs , as described in the Background section. The root is measured into bit of ghz, and the check into bit of flag. The only difference between the two checks is the second CNOT.
def readout_ghz(qc, qr_ghz, cr_ghz, cr_flag, check):
"""Measure the logical X of the GHZ state, with DisCo ED checks on pairs (2k, 2k + 1)."""
if check is None:
qc.h(qr_ghz)
qc.measure(qr_ghz, cr_ghz)
return
for k in range(len(qr_ghz) // 2):
check_qubit, root = qr_ghz[2 * k], qr_ghz[2 * k + 1]
qc.cx(
root, check_qubit
) # check now holds Z_c Z_r; root holds X_c X_r
qc.h(root)
if check == "implicit":
qc.cx(root, check_qubit) # check now holds (X_c X_r)(Z_c Z_r)
qc.measure(root, cr_ghz[k])
qc.measure(check_qubit, cr_flag[k])build_w_state_circuit puts the three pieces together, then measures the W qubits in the requested basis. The barriers only separate the stages in the circuit drawing.
def build_w_state_circuit(
n, delta, check, basis="Z", use_DD=True, feedforward=True
):
"""Full protocol: GHZ prep, W coupling, DisCo ED readout, then measure the W qubits in `basis`."""
qr_ghz = QuantumRegister(n, "q_ghz")
qr_w = QuantumRegister(n, "q_w")
cr_fusion = ClassicalRegister(n // 2 - 1, "fusion")
cr_ghz = ClassicalRegister(n if check is None else n // 2, "ghz")
cr_flag = ClassicalRegister(n // 2, "flag") if check is not None else None
cr_w = ClassicalRegister(n, "w")
cregs = (
[cr_fusion, cr_ghz]
+ ([cr_flag] if cr_flag is not None else [])
+ [cr_w]
)
qc = QuantumCircuit(qr_ghz, qr_w, *cregs)
prepare_ghz(qc, qr_ghz, cr_fusion, use_DD=use_DD, feedforward=feedforward)
qc.barrier()
couple_w_qubits(qc, qr_ghz, qr_w, delta)
qc.barrier()
readout_ghz(qc, qr_ghz, cr_ghz, cr_flag, check)
# Rotate the W qubits so that a Z-basis measurement measures X or Y
if basis == "Y":
qc.sdg(qr_w)
if basis in ("X", "Y"):
qc.h(qr_w)
qc.measure(qr_w, cr_w)
return qcThis example builds nine circuits for : three DisCo ED modes, each measured in three bases. The -basis circuits give the Hamming-weight distribution, and the - and -basis circuits give the coherence . The cell below draws the implicit-check circuit with -basis measurements. From left to right, you can see the GHZ preparation, with its two fusion measurements and the feedforward corrections (if_test blocks); the rotations and the CZ rungs; and the paired DisCo ED readout. Note that the two-qubit depth of each stage does not depend on .
n = 6 # number of W qubits (and of GHZ qubits); must be even
delta = 0.3 # sets p = delta / n; smaller delta gives higher fidelity but a lower success rate
circuits = {
(check, basis): build_w_state_circuit(
n, delta, check, basis, use_DD=False
)
for check in CHECKS
for basis in BASES
}
circuits["implicit", "Z"].draw("mpl", fold=-1)Output:
Step 2: Optimize problem for quantum hardware execution
Transpile the circuits for FakeMiami. The snapshot behind this fake backend does not list the reset and if_else instructions that real Nighthawk processors support, so the code below adds them to its target first. The simulator then models reset as noiseless.
The target qubit layout is a ladder: the GHZ line is a path of connected qubits, and each W qubit is a neighbor of its GHZ partner, joined by a CZ rung. Many ladders fit on the square lattice, and qubit quality varies across the device, so choose_layout picks one from the backend's calibration data. It estimates the expected number of errors of a ladder: the CZ errors of the edges it uses, the readout errors of every measurement, and the dephasing of the GHZ line while the fusion qubits are measured. It grows candidate GHZ lines one qubit at a time, keeping the cheapest, then gives each line its best W qubits. The code passes this layout to the transpiler for all nine circuits, so that every mode runs on the same physical qubits and the comparison between modes is fair. No SWAP gates are needed, and the CZ depth is 4 without error detection and 5 with it. The extra layer is the readout CNOT. The second CNOT of the implicit check merges with the first one into a single CZ, so the implicit and explicit circuits have the same CZ count.
def calibration_errors(backend):
"""Readout and CZ errors, and the dephasing of a qubit idling through one mid-circuit measurement."""
target = backend.target
meas = "measure_2" if "measure_2" in target.operation_names else "measure"
readout = {
q[0]: p.error
for q, p in target[meas].items()
if p is not None and p.error is not None
}
cz = {
tuple(sorted(q)): p.error
for q, p in target["cz"].items()
if p is not None and p.error is not None
}
idle = target[meas][(0,)].duration
dephasing = {}
for q in range(backend.num_qubits):
t2 = backend.qubit_properties(q).t2
dephasing[q] = idle / t2 if t2 else 1.0
return readout, cz, dephasing
def layout_cost(errors, ghz, w):
"""Expected number of errors of a ladder with GHZ line `ghz` and W qubits `w`."""
readout, cz, dephasing = errors
fusion = {
patch[0] for patch in ghz_patches(len(ghz))[1:]
} # measured twice: fusion, then readout
def edge(a, b):
return cz.get(tuple(sorted((a, b))), 1.0)
return (
sum(
readout[g] * (2 if j in fusion else 1) + dephasing[g]
for j, g in enumerate(ghz)
)
+ sum(
2 * edge(a, b) for a, b in zip(ghz, ghz[1:])
) # each GHZ edge carries about two CZs
+ sum(edge(g, x) + readout[x] for g, x in zip(ghz, w))
)
def choose_layout(backend, n, beam=1000):
"""Pick the GHZ line and its W qubits with the lowest layout_cost on the backend's calibration.
The GHZ line grows one qubit at a time, keeping the `beam` cheapest partial lines. Each finished
line then gets its best W qubits: one neighbor of each GHZ qubit, all distinct.
"""
errors = calibration_errors(backend)
readout, cz, dephasing = errors
neighbors = defaultdict(list)
for (a, b), error in cz.items():
if (
error < 0.05 and a in readout and b in readout
): # skip broken couplers
neighbors[a].append(b)
neighbors[b].append(a)
def edge(a, b):
return cz[tuple(sorted((a, b)))]
best_rung = {
g: min(edge(g, w) + readout[w] for w in neighbors[g])
for g in neighbors
}
fusion = {patch[0] for patch in ghz_patches(n)[1:]}
def qubit_cost(
j, g
): # GHZ qubit j on physical qubit g, assuming its best W partner is free
return (
readout[g] * (2 if j in fusion else 1)
+ dephasing[g]
+ best_rung[g]
)
lines = [(qubit_cost(0, g), (g,)) for g in neighbors]
for j in range(1, n):
grown = [
(cost + 2 * edge(line[-1], g) + qubit_cost(j, g), line + (g,))
for cost, line in lines
for g in neighbors[line[-1]]
if g not in line
]
lines = heapq.nsmallest(beam, grown)
# Neighboring GHZ qubits can share their best W qubit, so assign the W qubits jointly
best_cost, best_layout = np.inf, None
for _, line in lines[:100]:
free = sorted({w for g in line for w in neighbors[g]} - set(line))
rung_cost = np.array(
[
[
edge(g, w) + readout[w] if w in neighbors[g] else 1e6
for w in free
]
for g in line
]
)
rows, cols = linear_sum_assignment(rung_cost)
if (
rung_cost[rows, cols].max() >= 1e6
): # some GHZ qubit has no free W partner
continue
layout = (list(line), [free[i] for i in cols])
if (cost := layout_cost(errors, *layout)) < best_cost:
best_cost, best_layout = cost, layout
return best_layout# The fake backend stands in for the QPU in this section. Keep the name `backend`
# for the real QPU in the hardware example.
fake_backend = FakeMiami()
# The FakeMiami snapshot does not list reset and if_else; add them so the dynamic circuit transpiles
fake_backend.target.add_instruction(IfElseOp, name="if_else")
fake_backend.target.add_instruction(
Reset(), {(q,): None for q in range(fake_backend.num_qubits)}
)
# Choose a layout once, then use it for every mode so that they all run on the same physical qubits
ghz_qubits, w_qubits = choose_layout(fake_backend, n)
pm = generate_preset_pass_manager(
optimization_level=3,
backend=fake_backend,
initial_layout=ghz_qubits + w_qubits,
seed_transpiler=0,
)
isa_circuits = {key: pm.run(qc) for key, qc in circuits.items()}
for check in CHECKS:
isa = isa_circuits[check, "Z"]
cz_depth = isa.depth(
lambda instruction: instruction.operation.name == "cz"
)
print(
f"check = {str(check):8} CZ gates: {isa.count_ops()['cz']:3} CZ depth: {cz_depth}"
)Output:
check = None CZ gates: 13 CZ depth: 4
check = explicit CZ gates: 16 CZ depth: 5
check = implicit CZ gates: 16 CZ depth: 5
Step 3: Execute using Qiskit primitives
Compute the expected reference with exact_reference, then run the circuits with SamplerV2 in two ways: the logical circuits on a noiseless AerSimulator, and the transpiled circuits on FakeMiami, with its noise model. Each (check, basis) circuit is one PUB. Store the results in a dictionary with the same keys as circuits.
shots = 4000
# Expected reference: the closed-form values from the Background section
exact = exact_reference(n, delta)
# Noiseless check: the logical (untranspiled) circuits, with no noise
ideal_sampler = Sampler(mode=AerSimulator())
ideal_sampler.options.simulator.seed_simulator = 42
ideal_job = ideal_sampler.run(list(circuits.values()), shots=shots)
# Noisy run: local testing mode with the FakeMiami noise model
noisy_sampler = Sampler(mode=fake_backend)
noisy_sampler.options.simulator.seed_simulator = 42
noisy_job = noisy_sampler.run(list(isa_circuits.values()), shots=shots)
ideal_results = dict(zip(circuits, ideal_job.result()))
noisy_results = dict(zip(isa_circuits, noisy_job.result()))Step 4: Post-process and return result in desired classical format
For each mode, the table reports:
- the acceptance: the fraction of shots that pass the DisCo ED check
- the success: the fraction of accepted shots that herald the odd-parity sector, which should match the projection success rate
- P(w=1) and C, computed from the shots that are both accepted and heralded
- F: a lower and an upper bound on the fidelity with , computed from the Hamming-weight distribution and (see
fidelity_bounds). The paper reports this fidelity, so it is the number to compare with Ref. [1].
The expected value of is slightly above 1. This is because the small weight-3 component of the approximate W state has (see the comment in exact_reference).
First, the noiseless run. Every shot passes the DisCo ED check (acceptance = 1), and all three modes agree with the expected reference up to shot noise. Only about 900 of the 4,000 shots per circuit are heralded, so carries a statistical uncertainty of about , and deviations of a few hundredths are expected. So the error detection never discards a good shot, and the circuits and postprocessing are correct.
print("Noiseless simulation")
ideal_summary = summarize(ideal_results, exact)Output:
Noiseless simulation
check acceptance success P(w=1) C F
expected 1.000 0.234 0.991 1.007 0.991
None 1.000 0.245 0.996 1.058 0.996-0.996
explicit 1.000 0.232 0.989 0.988 0.972-0.989
implicit 1.000 0.240 0.991 1.019 0.991-0.991
Now the noisy run. The plot shows the Hamming-weight distribution of the postselected W state (left), and the two observables and (right), compared with the expected values (gray).
print("Noisy simulation (FakeMiami)")
noisy_summary = summarize(noisy_results, exact)
plot_results(noisy_summary, exact, f"Noisy simulation on FakeMiami, n = {n}")Output:
Noisy simulation (FakeMiami)
check acceptance success P(w=1) C F
expected 1.000 0.234 0.991 1.007 0.991
None 1.000 0.328 0.566 0.532 0.447-0.561
explicit 0.865 0.286 0.666 0.700 0.581-0.666
implicit 0.780 0.255 0.870 0.843 0.768-0.869
Hardware runs
Steps 1–3: Map, optimize, and submit
Here, put these steps together at a larger scale and submit the job to real quantum hardware. Prepare a W state on qubits, using 20 qubits of ibm_chicago, a Nighthawk processor. The functions are the same as in the small-scale example; only , , the backend, and the number of shots change. Because the protocol has constant depth, the transpiled circuits have the same CZ depth as for .
Three settings matter on hardware:
- Layout.
choose_layoutpicks the 20 qubits from the current calibration, and all nine circuits run on them. - Fast readout and dynamical decoupling.
fast_readoutswaps in the device's faster measure and measure-and-reset instructions, and the GHZ line runs a dynamical decoupling sequence while the fusion qubits are measured. - A larger . On hardware, some even-parity shots pass the herald (see the DisCo ED section). Most of them have weight 0, and their size relative to the weight-1 component scales as . A larger dilutes them, at the cost of more weight-3 contamination (about ). This tutorial uses , which gives an ideal fidelity of 0.95 and .
Only a fraction of the shots are kept, so this run uses 20,000 shots per circuit.
service = QiskitRuntimeService()
backend = service.backend("ibm_chicago")
# -------------------------Step 1-------------------------
n = 10
delta = 0.6
circuits = {
(check, basis): build_w_state_circuit(n, delta, check, basis, use_DD=True)
for check in CHECKS
for basis in BASES
}
# -------------------------Step 2-------------------------
ghz_qubits, w_qubits = choose_layout(backend, n)
pm = generate_preset_pass_manager(
optimization_level=3,
backend=backend,
initial_layout=ghz_qubits + w_qubits,
seed_transpiler=0,
)
isa_circuits = {
key: fast_readout(pm.run(qc), backend) for key, qc in circuits.items()
}
for check in CHECKS:
isa = isa_circuits[check, "Z"]
cz_depth = isa.depth(
lambda instruction: instruction.operation.name == "cz"
)
print(
f"check = {str(check):8} CZ gates: {isa.count_ops()['cz']:3} CZ depth: {cz_depth}"
)
plot_layout(isa_circuits["implicit", "Z"], backend)Output:
check = None CZ gates: 23 CZ depth: 4
check = explicit CZ gates: 28 CZ depth: 5
check = implicit CZ gates: 28 CZ depth: 5
# -------------------------Step 3-------------------------
sampler = Sampler(mode=backend)
sampler.options.environment.job_tags = ["TUT_DISCO"]
job = sampler.run(list(isa_circuits.values()), shots=20_000)
print(f"Job ID: {job.job_id()}")Output:
Job ID: dbqahb9abdes73fnth8g
Step 4: Post-process and return result in desired classical format
The analysis is the same as for the small-scale example. Postselect each mode, print the table, and compare the Hamming-weight distribution and the two observables with the expected values for .
# job.result() waits for the job to finish. To analyze a job from an earlier session
# without submitting it again, use job = service.job("<job ID>") in place of the
# sampler.run call in the previous cell (Steps 1 and 2 still define `circuits`).
hardware_results = dict(zip(circuits, job.result()))
exact = exact_reference(n, delta)
print(f"Hardware ({backend.name})")
hardware_summary = summarize(hardware_results, exact)
plot_results(hardware_summary, exact, f"Hardware ({backend.name}), n = {n}")Output:
Hardware (ibm_chicago)
check acceptance success P(w=1) C F
expected 1.000 0.361 0.953 1.063 0.953
None 1.000 0.410 0.672 0.712 0.503-0.672
explicit 0.692 0.385 0.759 0.883 0.697-0.759
implicit 0.673 0.397 0.761 0.867 0.676-0.761
On hardware, DisCo ED recovers a clear part of the gap to the noiseless result. Without error detection, is about 0.67 and about 0.71. With either check, rises to about 0.76 and to about 0.87, and the lower fidelity bound rises from about 0.50 to about 0.68, at the cost of discarding about a third of the shots. The explicit and implicit checks perform about the same in this run.
The remaining gap comes mostly from errors that DisCo ED cannot see. While the fusion outcomes travel to the control electronics and back, the whole GHZ line idles, and the phase errors it picks up flip the herald. DisCo ED checks only the stabilizers, so it does not detect these phase flips (see the DisCo ED section above), and the success rate stays above . Two ways to explore this further:
- Rebuild the circuits with
feedforward=False. This removes the wait, so comparing the two settings shows how much of the error the feedforward adds. The W state is then not prepared on the device, but without errors the measured statistics are the same. - Try a larger . More GHZ qubits idle during the wait, so the undetected phase errors grow with .
References
- K. C. Smith, B. Pokharel, S. Maurya, and M. Takita, "Resilience Beyond the Light Cone: Error-Detected Primitives for Practical Dynamic Circuits" (2026), arXiv:2609.08925.
- L. Piroli, G. Styliaris, and J. I. Cirac, "Approximating many-body quantum states with quantum circuits and measurements," Physical Review Letters 133, 230401 (2024), arXiv:2403.07604.
- E. Bäumer, V. Tripathi, D. S. Wang, P. Rall, E. H. Chen, S. Majumder, A. Seif, and Z. K. Minev, "Efficient Long-Range Entanglement using Dynamic Circuits," PRX Quantum 5, 030339 (2024), arXiv:2308.13065.
Next steps
If you found this work interesting, you might be interested in the following material: