Skip to main content
IBM Quantum Platform

Error correction I: Detection and post-selection

Estimated QPU usage in this lesson: 3 minutes. Actual usage depends on the backend and execution settings.

In previous lessons, you studied the noise that arises in quantum hardware and worked through current techniques for suppressing and mitigating it. This lesson takes the next step along the path from error mitigation to error correction: instead of actively correcting detected errors, we detect them and discard the runs they touched.

We call this post-selected quantum error correction. A set of checks is attached to the circuit, a run that fails a check is flagged as containing an error and discarded, and the accepted runs are used as they are. Nothing is decoded and nothing is corrected, so this workflow does not require real-time decoding or recovery; the price is paid in discarded shots instead. Throughout this lesson, error detection means this post-selected form. Section 1.1 is the limiting case with no code at all: the check is a symmetry of the ideal output, read directly from the measured bits. Beginning with Section 1.2, the checks are stabilizer measurements on ancilla qubits, first the [[4,2,2]][[4,2,2]] error-detecting code at the end of the circuit, then coherent Pauli checks and spacetime checks placed around and inside the payload.

Quantum error mitigation and quantum error correction (QEC) are often framed as tools for different eras of quantum computing: mitigation for today's devices and correction for scalable fault tolerance. IBM® instead describes a continuous path from error mitigation to error correction, along which removing errors trades time (samples) against space (qubits). At one end, we have error suppression and mitigation. Some of these techniques are low-overhead. But others, like Probabilistic error cancellation (PEC), pay a sampling cost that grows quickly, even exponentially with the noise in the system. At the other end, full quantum error correction can make a computation reliable in a single shot, but large-scale fault-tolerant architectures require substantial qubit and gate overhead; their connectivity, error-rate, and decoding requirements depend on the code and architecture. Post-selected error correction sits between them, and spacetime codes can make it hardware-efficient by distributing low-weight Pauli checks across both space and time in a circuit. The Qiskit Paulice addon lets you place such checks in your own circuits today (see its documentation). In this blog post, IBM reports that a recent demonstration encoded 64 logical qubits in spacetime codes on 76 physical qubits, in a circuit that also contained 314 TT gates, and gave roughly a tenfold effective improvement in gate error rates after post-selection.

The basic protocol is as follows. One first selects a detection strategy. Depending on the strategy, the original circuit is either augmented with additional gates that implement an explicit consistency check (placed internally in the circuit, or at the end), or, when the ideal output obeys a known constraint, the circuit is run unchanged and that constraint serves as the check. The (augmented) circuit is then executed and measured, and the check outcomes, or the structural constraint evaluated on the measured bitstrings, are used to flag shots as likely corrupted and reject them in classical post-processing (or recover the correct state probabilistically, as in configuration recovery). The aim is to improve the accepted samples, at the cost of fewer usable shots, and the benefit must be checked against the errors introduced by the detection circuit.

This lesson builds up to spacetime codes through a continuum of post-selection techniques, starting from the simplest — a symmetry rule on the measured bitstring — and ending with checks whose detection regions reach deep into the circuit's interior. In the hardware examples in Parts 1 and 2, we weigh the gain from post-selection against its cost in added gates and discarded shots.

This lesson is organized in two parts.

  • Part 1: End-of-circuit detection. All check information is read out at the end of the circuit. We consider two strategies under this constraint: in Section 1.1, the circuit is run unchanged and a known symmetry of the ideal output distribution serves as the check; in Section 1.2, additional gates are appended at the end of the circuit, and their measurement outcome serves as the check.

  • Part 2: Mid-circuit detection. Check operations are sensitive to errors that occur during the circuit's execution, defining a detection region, the set of locations at which a fault would be flagged by the check. We develop two such methods: coherent Pauli checks, which use a paired check construction applicable to any Clifford circuit, and spacetime codes, which exploit the specific circuit's structure to reduce overhead.

Fault tolerance remains the north star. The first IBM fault-tolerant quantum computer, IBM Quantum® Starling, is designed around quantum LDPC codes rather than the detection schemes practiced here, and IBM expects error mitigation and post-selection to keep working alongside error correction even then. The skills in this lesson, choosing what to check, placing checks where they catch the most, and accounting for their cost, carry over to that setting.

Common imports and shared helper functions are defined once in the Setup section below.


Setup and shared utilities

The cells in this section install dependencies, import the libraries used throughout the notebook, and define helper functions shared by Parts 1 and 2. Sections 2.4 and 2.5 follow the IBM Quantum tutorial Low-overhead error detection with spacetime codes and use the qiskit-paulice addon to search for check placements. On a first read, run these cells once and proceed to Section 1.1.

# Environment setup
# Uncomment if needed in a fresh environment.
# Runtime 0.50 uses the client-side Sampler; Qiskit 2.5.1 fixes issue #16594.
# %pip install "qiskit[visualization]>=2.5.1" qiskit-aer "qiskit-ibm-runtime==0.50.0" qiskit-paulice scipy pandas networkx
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import pandas as pd
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
from qiskit.quantum_info import Pauli, hellinger_fidelity
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import (
    Collect2qBlocks,
    ConsolidateBlocks,
    UnitarySynthesis,
)
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit.visualization import plot_coupling_map
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import QiskitRuntimeService
from qiskit_ibm_runtime.executor_sampler import Sampler
from qiskit_paulice import add_pauli_checks
from qiskit_paulice.layout import get_check_qubits
from qiskit_paulice.noise_models import NoiseModel as PauliceNoiseModel
# utilities


# --- CPC helpers ---
def apply_controlled_paulis(qc, pauli, anc_qubit, data_reg):
    """Controlled-Pauli gates via phase kickback (CZ + basis rotation)."""
    for q in range(len(data_reg)):
        p = pauli[q].to_label()
        if p == "Z":
            qc.cz(anc_qubit, data_reg[q])
        elif p == "X":
            qc.h(data_reg[q])
            qc.cz(anc_qubit, data_reg[q])
            qc.h(data_reg[q])
        elif p == "Y":
            qc.sdg(data_reg[q])
            qc.h(data_reg[q])
            qc.cz(anc_qubit, data_reg[q])
            qc.h(data_reg[q])
            qc.s(data_reg[q])


def create_payload_circuit(num_qubits, depth=5, seed=16):
    """Random Clifford circuit with controllable depth.
    Uses hardware-native gates: H, CZ, SX, S.
    Brickwork CZ pattern + random single-qubit Cliffords."""
    rng = np.random.RandomState(seed)
    circuit = QuantumCircuit(num_qubits)
    circuit.h(range(num_qubits))
    for d in range(depth):
        for i in range(d % 2, num_qubits - 1, 2):
            circuit.cz(i, i + 1)
        for q in range(num_qubits):
            if rng.randint(0, 2):
                circuit.sx(q)
            if rng.randint(0, 2):
                circuit.s(q)
            if rng.randint(0, 2):
                circuit.sx(q)
    return circuit


# --- Right-only checks routed on a line (Section 2.3.3) ---
def right_only_network(stabilizers, num_data):
    """One ancilla per stabilizer, placed below the data on a line and swapped through it.
    When an ancilla meets a data qubit in its stabilizer's support, the controlled-Pauli
    factor is applied just before the swap. Returns the circuit, number of swaps,
    and number of controlled-Pauli/swap pairs."""
    n, m = num_data, len(stabilizers)
    qc = QuantumCircuit(n + m, m)
    pos = [("d", i) for i in range(n)] + [("a", j) for j in range(m)]
    qc.h(range(n, n + m))
    n_swaps = n_fused = 0
    while True:
        pairs = [
            p for p in range(n + m - 1) if pos[p][0] == "d" and pos[p + 1][0] == "a"
        ]
        if not pairs:
            break
        for p in pairs:
            i, j = pos[p][1], pos[p + 1][1]
            factor = stabilizers[j][i].to_label()
            if factor == "X":
                qc.cx(p + 1, p)
            elif factor == "Y":
                qc.cy(p + 1, p)
            elif factor == "Z":
                qc.cz(p + 1, p)
            qc.swap(p, p + 1)
            pos[p], pos[p + 1] = pos[p + 1], pos[p]
            n_swaps += 1
            n_fused += factor != "I"
    for p, (kind, j) in enumerate(pos):
        if kind == "a":
            if stabilizers[j].phase == 2:  # a minus sign becomes a Z on the ancilla
                qc.z(p)
            qc.h(p)
            qc.measure(p, j)
    return qc, n_swaps, n_fused

Runtime configuration

This notebook uses the client-side Sampler introduced in qiskit-ibm-runtime v0.50; for more information, see the migration guide. Saved hardware outputs are reference measurements from earlier runs.

The following code assumes you have saved your credentials. To set them up, follow the instructions in Save your login credentials.

service = QiskitRuntimeService()

backend = service.least_busy(
    operational=True,
)

pm = generate_preset_pass_manager(
    backend=backend, optimization_level=1, seed_transpiler=7
)
sampler = Sampler(mode=backend)
print("Backend:", backend.name)

Output:

Backend: ibm_marrakesh

Part 1: End-of-circuit detection

In Part 1, we focus on methods in which all check information is read out at the end of the circuit. We consider two strategies under this constraint:

  1. Symmetry post-selection: the simplest but most limited form (Section 1.1). The check is a rule applied to the measured bitstring, and the original circuit is run unchanged, with no extra qubits, and no encoding. This requires prior knowledge of the ideal output distribution, and the data is consumed by the final measurement before the check is applied.

  2. Stabilizer-code post-selection with syndrome qubits (Section 1.2). The check is the outcome of an ancilla measurement appended to the circuit. This adds qubits and gates, but does not require knowing the full output distribution and can detect both bit-flip and phase-flip Pauli errors.

Both strategies are post-selected: a flagged shot is discarded, and no correction is attempted. Section 1.3 outlines three limitations of end-of-circuit detection that motivate the interior-check constructions of Part 2.

Prerequisite

This part assumes the stabilizer formalism at the level of the IBM Quantum Learning Foundations of Quantum Error Correction course, specifically Repetition code revisited and Stabilizer codes. Codespace, stabilizer generators, syndromes via anti-commutation, code distance, and [[n,k,d]][[n,k,d]] notation are defined there. We include a short refresher before using these terms operationally in Section 1.2.

1.1 Symmetry post-selection on classical bitstrings

Parity checking is a classical error-detection technique. The parity of a bitstring is the number of 1s it contains, modulo 2. In the example below, a sender appends a parity bit to each data block so that the total number of 1s in the resulting codeword is even.

Data (7 bits)
Number of 1s
Parity bit
Codeword with even parity (8 bits)
00000000000000000
10100013110100011
11010014011010010
11111117111111111

The receiver recomputes the parity of the 8-bit codeword and rejects it if the parity is no longer even. A single bit-flip during transmission changes the parity by one and is flagged; two flips leave the parity unchanged and slip through undetected.

The same idea, a structural rule on the bitstring that valid messages must satisfy, applies to the measurement outcomes of a quantum circuit. Parity is one such rule, but it is not the only one. More generally, when the ideal output distribution of a circuit is restricted by some structural constraint, that constraint can be used as the check: any measured bitstring that violates it can be rejected in classical post-processing as likely corrupted.

Such constraints typically originate from a symmetry of the ideal state; in other words, an operator SS that leaves the state invariant (S∣ψ⟩=∣ψ⟩S|\psi\rangle = |\psi\rangle), so that measurement outcomes must respect the constraint associated with SS. For example, the GHZ state (∣0n⟩+∣1n⟩)/2(|0^n\rangle + |1^n\rangle)/\sqrt{2} is stabilized by the pairwise parity operators ZiZjZ_i Z_j, which enforce the all-agree computational-basis support {0n,1n}\{0^n, 1^n\}; it is also stabilized by X⊗nX^{\otimes n}, which fixes the relative ++ phase between the two components. As another example, in an occupation-number encoding of an electronic-structure problem, particle-number conservation restricts measurement outcomes to a fixed sector, so outcomes outside that sector can be rejected in classical post-processing as unphysical. This is why the technique is commonly called symmetry post-selection. It requires no extra qubits, no encoding, and no syndrome extraction, and thus the original circuit is run unchanged.

The simplicity comes with two costs. First, the check operates entirely on the post-measurement record: errors that are visible in the bitstring can be flagged, but the quantum information itself is consumed by the final measurement before any check is applied, so the technique cannot protect a state for further use. Second, it requires that the ideal output distribution have a known structure that can be tested directly on a bitstring; for example, the two-bitstring support of a GHZ state, or a fixed particle-number sector of a chemistry ansatz. Most deep computational circuits do not come with such diagnostic structure, in which case no symmetry rule is available. The technique is best viewed as a low-overhead first line of defense for circuits whose ideal output is well understood, rather than a general-purpose detection method.

Even so, symmetry post-selection is an instructive entry point: it is simple enough to expose the core trade-offs of post-selected detection (post-selection rate, sampling overhead, and fidelity) that recur throughout the rest of the notebook. We define these quantities next.

Definitions

We use the following terms throughout the notebook.

  • Post-selection rate AA (also called acceptance rate): the fraction of shots that satisfy the check.

  • Sampling overhead 1/A1/A: the multiplicative factor by which raw shots must grow to recover one accepted shot.

  • Hellinger fidelity between two probability distributions pp and qq on nn-bit strings:

    F(p,q)=(∑ipi qi )2,F(p, q) = \bigg(\sum_i \sqrt{p_i\, q_i}\,\bigg)^2,

    where the sum runs over all nn-bit strings ii, and pip_i and qiq_i are the probabilities that pp and qq assign to ii. F=1F = 1 for identical distributions and F=0F = 0 when no bitstring is assigned positive probability by both distributions. FF is a classical distribution-level quantity computed after measurement and does not certify the full quantum state; for example, a GHZ state and its phase-flipped counterpart can produce identical computational-basis distributions and therefore identical FF. We return to this potential obstacle when motivating stabilizer-code checks in Section 1.2.

  • Detection region of a check: the set of circuit locations at which a fault can flip that check; which Pauli types are caught at each location depends on the check. The final checks of Part 1 can only respond to faults whose effects survive to the final measurements, and whether a surviving fault is actually detected depends on the particular check. Part 2 places checks whose regions are deliberately narrower and traces them through the circuit.

1.1.1 GHZ as a benchmark for symmetry filtering

We use the nn-qubit GHZ state

∣GHZn⟩=12(∣0⟩⊗n+∣1⟩⊗n).|\mathrm{GHZ}_n\rangle = \tfrac{1}{\sqrt 2}\big(|0\rangle^{\otimes n} + |1\rangle^{\otimes n}\big).

In the computational basis, the ideal outcome distribution is supported on exactly two bitstrings, 0n0^n and 1n1^n. Any other bitstring can be rejected in classical post-processing as inconsistent with this support.

For our run we use n=10n = 10. Both ideal outputs 0100^{10} and 1101^{10} have an even number of 1s (0 and 10, respectively), so we compare two rules on the same dataset:

  • Even-parity rule. Keep shots whose number of 1s is even. This rule applies only when nn is even (the case here); for odd nn the two ideal outputs have opposite parity, and no single parity rule keeps both.
  • All-agree rule. Keep shots that are exactly 0n0^n or 1n1^n.

The all-agree rule is more restrictive than even parity: every all-agree bitstring has an even number of 1s, but most bitstrings with an even number of 1s are not all-agree. Even parity catches any odd number of bit flips but lets through any pair of compensating flips. Under noise, we therefore expect the all-agree rule to give higher post-selected fidelity at a lower post-selection rate.

def ghz_circuit(n: int) -> QuantumCircuit:
    q = QuantumRegister(n, "q")
    c = ClassicalRegister(n, "c")
    qc = QuantumCircuit(q, c)

    qc.h(0)
    for i in range(n - 1):
        qc.cx(i, i + 1)

    qc.barrier()

    qc.measure(range(n), range(n))
    return qc


n_qubit = 10
qc_ghz = ghz_circuit(n_qubit)
qc_ghz.draw("mpl", style="iqp")

Output:

Output of the previous code cell

Run the 10-qubit GHZ circuit on the hardware backend.

# Transpile and submit the n=10 GHZ circuit
qc_ghz_tr = pm.run(qc_ghz)
job = sampler.run([qc_ghz_tr], shots=10000)
job_id_ghz = job.job_id()
# print("Submitted job:", job_id_ghz)
service.job(job_id_ghz).status()

Output:

'QUEUED'
result = service.job(job_id_ghz).result()
counts = result[0].data.c.get_counts()

Apply both rules to the same dataset.

def is_all_agree(bitstr: str) -> bool:
    b = bitstr.replace(" ", "")
    return (set(b) == {"0"}) or (set(b) == {"1"})


def has_even_parity(bitstr: str) -> bool:
    b = bitstr.replace(" ", "")
    return (b.count("1") % 2) == 0


total = sum(counts.values())

post_parity = {}
post_allagree = {}
kept_parity = 0
kept_allagree = 0

for b, cts in counts.items():
    b2 = b.replace(" ", "")
    if has_even_parity(b2):
        post_parity[b2] = post_parity.get(b2, 0) + cts
        kept_parity += cts
    if is_all_agree(b2):
        post_allagree[b2] = post_allagree.get(b2, 0) + cts
        kept_allagree += cts

A_parity = kept_parity / total
A_allagree = kept_allagree / total

print(f"Total shots:    {total}")
print(
    f"Even-parity rule: accepted {kept_parity:>5d}, A = {A_parity:.4f}, overhead 1/A = {1 / A_parity:.2f}"
)
print(
    f"All-agree rule:   accepted {kept_allagree:>5d}, A = {A_allagree:.4f}, overhead 1/A = {1 / A_allagree:.2f}"
)

Output:

Total shots:    10000
Even-parity rule: accepted  8757, A = 0.8757, overhead 1/A = 1.14
All-agree rule:   accepted  8482, A = 0.8482, overhead 1/A = 1.18
# Hellinger fidelity to the ideal GHZ distribution
ideal_probs = {"0" * n_qubit: 0.5, "1" * n_qubit: 0.5}

# hellinger_fidelity normalizes count dictionaries internally.
F_raw = hellinger_fidelity(
    {k.replace(" ", ""): v for k, v in counts.items()}, ideal_probs
)
F_parity = hellinger_fidelity(post_parity, ideal_probs) if kept_parity else float("nan")
F_allagree = (
    hellinger_fidelity(post_allagree, ideal_probs) if kept_allagree else float("nan")
)

labels = ["raw", "even-parity rule", "all-agree rule"]
fids = [F_raw, F_parity, F_allagree]
accs = [1.0, A_parity, A_allagree]

x = np.arange(len(labels))
fig, ax = plt.subplots()
ax.bar(x, fids, label="Hellinger fidelity $F$")
ax.plot(x, accs, marker="o", color="C1", linewidth=2, label="post-selection rate $A$")
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.set_ylim(0, 1.0)
ax.set_title(f"GHZ n={n_qubit}, hardware: fidelity and post-selection rate by rule")
ax.legend(loc="best")
ax.grid(True, axis="y", alpha=0.3)
plt.show()

Output:

Output of the previous code cell

Use the plot to compare the Hellinger fidelity and acceptance of the two filters. The all-agree rule keeps a subset of the even-parity shots, so its acceptance cannot be higher. This is the accuracy-throughput trade-off introduced by post-selection: stricter filters can make the accepted distribution cleaner, but they also reduce the number of usable samples and therefore raise the sampling overhead. Here both filters preserve the full ideal GHZ support, so Hellinger fidelity cannot decrease as the accepted set shrinks, provided some shots remain. Every shot the all-agree rule keeps lies in the ideal support by construction, so its Hellinger fidelity falls short of 1 only when 0n0^n and 1n1^n are not equally frequent. This distribution-level improvement does not certify phase coherence.

Even parity is good at catching any odd number of bit flips, but it has a structural flaw: any pair of compensating flips slips through. The next subsection addresses this issue.

1.1.2 When parity is not enough

Even parity catches any odd number of bit flips but lets through any even number of flips. We can quantify this directly from the hardware run above: every shot that satisfies the even-parity rule but is not in the all-agree set {010,110}\{0^{10}, 1^{10}\} is a corrupted shot that an even number of bit flips moved into the same parity sector as the ideal output.

# Shots that pass the even-parity rule but are not in the all-agree set
# = corrupted shots that an even number of bit flips moved into even parity.
all_agree = {"0" * n_qubit, "1" * n_qubit}
parity_pass_not_allagree = sum(
    v for k, v in counts.items() if k.count("1") % 2 == 0 and k not in all_agree
)
total_shots = sum(counts.values())
miss_fraction = parity_pass_not_allagree / total_shots

print(
    f"Even-parity rule false accepts: {parity_pass_not_allagree} / {total_shots} "
    f"({100 * miss_fraction:.2f}% of shots)"
)

Output:

Even-parity rule false accepts: 275 / 10000 (2.75% of shots)

The false-accept rate measures how often the even-parity rule accepts an output outside the ideal support.

The previous analysis exposes a more fundamental limitation: a final computational-basis filter only sees what is recorded in the bit values. Errors that change bit values (bit-flip errors) leave a trace there and can in principle be filtered. Errors that change only the phase between basis states (phase-flip errors) can rotate the relative phase between, say, ∣0n⟩|0^n\rangle and ∣1n⟩|1^n\rangle without changing the bitstring distribution, so no rule applied only to the final bitstrings can detect them.

This limitation motivates the next section. To detect phase-flip errors, the check itself must access information that is not visible in the bitstring, which is what stabilizer codes provide.

Check your understanding

Suppose you prepare a three-qubit state whose ideal outcomes are only 000 and 111. What rule would you use for post-selection, and what single-qubit errors would that rule catch?

  • The natural choice is the all-agree rule: keep only 000 and 111. The even-parity rule does not work here, because 000 has zero 11s and 111 has three, so their parities are opposite. Any single bit-flip (XX) error breaks the all-agree pattern, so the rule catches every weight-11 bit-flip. It does not catch phase-flip (ZZ) errors, which leave bit values unchanged. The phase-flip problem motivates Section 1.2.

1.2 Stabilizer-code post-selection: the [[4,2,2]][[4,2,2]] code

Section 1.1 left two open limitations. First, the bitstring rules used there only see what is recorded in the computational basis, that is, the eigenbasis of the ZZ operator. They cannot see phase-flip errors, which are invisible in that basis. (Changing the measurement basis can make different error information visible, but no single final measurement basis gives a complete, non-destructive check of both bit- and phase-type errors for an arbitrary encoded state.) Second, applying the check requires measuring the data qubits, which collapses the state and consumes the information we wanted to keep. The classical fix to the second problem, keeping redundant copies and checking that they agree, is unavailable here because the no-cloning theorem forbids duplicating an unknown quantum state.

  • The no-cloning theorem says there is no unitary UU that takes an arbitrary unknown state ∣ψ⟩|\psi\rangle together with a fresh register and produces ∣ψ⟩⊗∣ψ⟩|\psi\rangle \otimes |\psi\rangle. Cloning is a non-linear operation in ∣ψ⟩|\psi\rangle, but every quantum operation is linear: if UU cloned the two basis states ∣0⟩|0\rangle and ∣1⟩|1\rangle, linearity would force UU to send the superposition 12(∣0⟩+∣1⟩)\tfrac{1}{\sqrt 2}(|0\rangle+|1\rangle) to 12(∣0⟩∣0⟩+∣1⟩∣1⟩)\tfrac{1}{\sqrt 2}(|0\rangle|0\rangle+|1\rangle|1\rangle), which is not the cloned state 12(∣0⟩+∣1⟩)⊗12(∣0⟩+∣1⟩)\tfrac{1}{\sqrt 2}(|0\rangle+|1\rangle) \otimes \tfrac{1}{\sqrt 2}(|0\rangle+|1\rangle). The contradiction arises specifically because the input is a superposition; cloning basis states alone is fine.

    This does not forbid preparing multiple copies of a state we already know how to prepare: we can simply run the preparation procedure on fresh registers. A CNOT cleanly copies computational-basis information, sending ∣a⟩∣0⟩↦∣a⟩∣a⟩|a\rangle|0\rangle \mapsto |a\rangle|a\rangle for a∈{0,1}a \in \{0, 1\}, but this does not extend to arbitrary superpositions. The encoding circuits used by stabilizer codes combine the logical input, which may be unknown, with initialized ancillas and distribute its information across an encoded register without making copies. What no-cloning rules out is duplicating a state that arrives unknown from an earlier computation.

Stabilizer codes resolve both limitations at once. The logical state is encoded across multiple physical qubits through entanglement, and an ancilla qubit couples to the data to report a stabilizer eigenvalue, enough to flag whether the state has left the codespace, but not enough to reveal the logical amplitudes. By using two complementary stabilizers, one diagonal in the ZZ basis and one in the XX basis, the check is sensitive to both bit-flip and phase-flip errors. Because only the ancilla is measured, this can in principle be applied without collapsing the encoded state. Used this way, the code is post-selected quantum error correction in its original form: an error-detecting code whose flagged shots are discarded rather than corrected. The reach of the check is bounded by the code distance dd: with d=2d=2, the [[4,2,2]][[4,2,2]] code we use here detects every weight-11 Pauli error on a data qubit but is blind to certain weight-22 errors, including the even-bit-flip patterns that already escaped the parity rule in Section 1.1.2.

  • The terms collected below are the ones used most often in this section. For full details, refer to the IBM Quantum Learning Stabilizer codes course.

    • Physical qubit, logical qubit. The hardware qubits used to store encoded information are the physical qubits. The abstract qubits whose state is being protected are the logical qubits.
    • Stabilizer generators. A set of mutually commuting multi-qubit Pauli operators P1,…,PrP_1, \ldots, P_r. The states satisfying Pk∣ψ⟩=∣ψ⟩P_k|\psi\rangle = |\psi\rangle for every kk form the codespace.
    • Codespace. The simultaneous +1+1 eigenspace of the stabilizer generators.
    • Ancilla qubit. An auxiliary qubit coupled to the data qubits to extract a stabilizer eigenvalue without measuring the data directly.
    • Syndrome. The string of stabilizer-measurement outcomes, under the convention that outcome 0 corresponds to eigenvalue +1+1 and outcome 1 to eigenvalue −1-1.
    • [[n,k,d]][[n, k, d]] notation. A stabilizer code on nn physical qubits that encodes kk logical qubits with code distance dd.
    • Weight of a Pauli operator. The number of qubits on which the operator acts as something other than the identity.
    • Logical operator. A Pauli operator that commutes with every stabilizer generator and is not proportional to a stabilizer element.
    • Code distance dd. The minimum weight of a logical operator.

The [[4,2,2]][[4,2,2]] code uses n=4n=4 physical qubits to encode k=2k=2 logical qubits with code distance d=2d=2. Its codespace is the simultaneous +1+1 eigenspace of two stabilizer generators,

Z3Z2Z1Z0andX3X2X1X0.Z_3 Z_2 Z_1 Z_0 \quad \text{and} \quad X_3 X_2 X_1 X_0.

A single-qubit XX error anti-commutes with Z3Z2Z1Z0Z_3 Z_2 Z_1 Z_0 and is flagged by the corresponding syndrome bit; a single-qubit ZZ error anti-commutes with X3X2X1X0X_3 X_2 X_1 X_0 and is flagged by the other. Every weight-11 Pauli error on a data qubit is detected by at least one of the two stabilizers. The two-bit syndrome identifies the error type (XX, ZZ, YY, or none) but not the qubit on which the error occurred. With d=2d=2, this information is insufficient to determine a correction, so the [[4,2,2]][[4,2,2]] code is used as a detection-only code.

The experiments below run syndrome extraction on the logical Bell state:

∣Φ+⟩L=12(∣00⟩L+∣11⟩L),|\Phi^+\rangle_L = \tfrac{1}{\sqrt 2}\big(|00\rangle_L + |11\rangle_L\big),

a state in the codespace.

  • The [[4,2,2]][[4,2,2]] code encodes two logical qubits using four physical qubits. As with any two-qubit system, there are four logical computational-basis states, ∣00⟩L|00\rangle_L, ∣01⟩L|01\rangle_L, ∣10⟩L|10\rangle_L, ∣11⟩L|11\rangle_L, read as the values of the two encoded qubits (for example, ∣00⟩L|00\rangle_L has both logical qubits in the logical-zero state). What makes this an encoding is that each ∣ab⟩L|ab\rangle_L is a specific superposition of physical four-qubit basis states, chosen so that all four logical basis states satisfy the codespace conditions Z3Z2Z1Z0=+1Z_3 Z_2 Z_1 Z_0 = +1 and X3X2X1X0=+1X_3 X_2 X_1 X_0 = +1.

    The standard choice is

    ∣00⟩L=12(∣0000⟩+∣1111⟩),∣01⟩L=12(∣0011⟩+∣1100⟩),∣10⟩L=12(∣0101⟩+∣1010⟩),∣11⟩L=12(∣0110⟩+∣1001⟩).\begin{aligned} |00\rangle_L &= \tfrac{1}{\sqrt 2}\big(|0000\rangle + |1111\rangle\big), \\ |01\rangle_L &= \tfrac{1}{\sqrt 2}\big(|0011\rangle + |1100\rangle\big), \\ |10\rangle_L &= \tfrac{1}{\sqrt 2}\big(|0101\rangle + |1010\rangle\big), \\ |11\rangle_L &= \tfrac{1}{\sqrt 2}\big(|0110\rangle + |1001\rangle\big). \end{aligned}

    Each line pairs two four-qubit strings related by flipping all four bits. Both strings in each line have an even number of 11s. Since ZZ has eigenvalue +1+1 on ∣0⟩|0\rangle and −1-1 on ∣1⟩|1\rangle, the eigenvalue of Z3Z2Z1Z0Z_3 Z_2 Z_1 Z_0 on a computational-basis string is (−1)number of 1s(-1)^{\text{number of }1\text{s}}, so a string with an even number of 11s gives eigenvalue +1+1. The ++ combination is also invariant under X3X2X1X0X_3 X_2 X_1 X_0, which simply permutes the two terms within each line.

    The logical Bell state used in the experiments is:

    ∣Φ+⟩L=12(∣00⟩L+∣11⟩L),|\Phi^+\rangle_L = \tfrac{1}{\sqrt 2}\big(|00\rangle_L + |11\rangle_L\big),

    the analog of the standard Bell state 12(∣00⟩+∣11⟩)\tfrac{1}{\sqrt 2}(|00\rangle + |11\rangle) on the two logical qubits. Substituting the codeword expressions above gives its physical four-qubit form:

    ∣Φ+⟩L=12(∣0000⟩+∣1111⟩+∣0110⟩+∣1001⟩).|\Phi^+\rangle_L = \tfrac{1}{2}\big(|0000\rangle + |1111\rangle + |0110\rangle + |1001\rangle\big).

    The preparation circuit applies two H + CNOT pairs, on (q0,q3)(q_0, q_3) and (q1,q2)(q_1, q_2). Each pair produces a physical Bell state 12(∣00⟩+∣11⟩)\tfrac{1}{\sqrt 2}(|00\rangle + |11\rangle) on its two qubits, so the full four-qubit output is the tensor product:

    12(∣00⟩+∣11⟩)q0q3⊗(∣00⟩+∣11⟩)q1q2.\tfrac{1}{2}\big(|00\rangle + |11\rangle\big)_{q_0 q_3} \otimes \big(|00\rangle + |11\rangle\big)_{q_1 q_2}.

    Expanding this tensor product, the four computational-basis strings that appear with equal amplitude are ∣0000⟩,∣1111⟩,∣0110⟩,∣1001⟩|0000\rangle, |1111\rangle, |0110\rangle, |1001\rangle, the same four strings that appear in the expression for ∣Φ+⟩L|\Phi^+\rangle_L above. The circuit therefore prepares ∣Φ+⟩L|\Phi^+\rangle_L directly.

We start by building the circuit that prepares the logical Bell state ∣Φ+⟩L|\Phi^+\rangle_L. The construction uses two H + CNOT pairs to create two physical Bell pairs: one between data qubits 0 and 3, the other between data qubits 1 and 2. Their tensor product lies inside the [[4,2,2]][[4,2,2]] codespace and is equal to ∣Φ+⟩L|\Phi^+\rangle_L as defined in the previous section.

# Logical Bell state |Phi^+>_L of the [[4,2,2]] code.
# Two H + CNOT pairs build two physical Bell pairs:
#   (data_0, data_3) and (data_1, data_2).
data = QuantumRegister(4, "data")
qc_logical_phi_plus = QuantumCircuit(data, name="logical_phi_plus")
qc_logical_phi_plus.h(data[0])
qc_logical_phi_plus.cx(data[0], data[3])
qc_logical_phi_plus.h(data[1])
qc_logical_phi_plus.cx(data[1], data[2])
qc_logical_phi_plus.draw("mpl", style="iqp")

Output:

Output of the previous code cell

Now we extract both syndromes simultaneously. The Z3Z2Z1Z0Z_3 Z_2 Z_1 Z_0 check is implemented by applying CNOTs from each data qubit into a single ancilla, so the ancilla parity records the joint ZZ-eigenvalue. The X3X2X1X0X_3 X_2 X_1 X_0 check uses Hadamard conjugation: applying H gates on the data qubits before and after the CNOTs converts the XX-parity check into a ZZ-parity check on a rotated frame, which the same CNOT pattern then extracts onto a second ancilla.

# Joint Z_3Z_2Z_1Z_0 + X_3X_2X_1X_0 syndrome extraction on the logical Bell state.
# syn[0] carries the Z-stabilizer outcome; syn[1] carries the X-stabilizer outcome.
data_r = QuantumRegister(4, "data")
syn_r = QuantumRegister(2, "syn")
c_r = ClassicalRegister(2, "c")
qc_check = QuantumCircuit(data_r, syn_r, c_r)

# Prepare |Phi^+>_L
qc_check.append(qc_logical_phi_plus.to_instruction(), data_r)
qc_check.barrier(label="|Phi^+>_L")
# Z_3 Z_2 Z_1 Z_0 onto syn[0]
for i in range(4):
    qc_check.cx(data_r[i], syn_r[0])

qc_check.barrier(label="Z3Z2Z1Z0")

# X_3 X_2 X_1 X_0 onto syn[1] (Hadamard conjugation: H X H = Z)
for i in range(4):
    qc_check.h(data_r[i])
for i in range(4):
    qc_check.cx(data_r[i], syn_r[1])
for i in range(4):
    qc_check.h(data_r[i])
qc_check.barrier(label="X3X2X1X0")
# Measure both syndromes
qc_check.measure(syn_r[0], c_r[0])
qc_check.measure(syn_r[1], c_r[1])

qc_check.draw("mpl", style="iqp")

Output:

Output of the previous code cell

1.2.1 Simulator validation

Before running on hardware, we verify the syndrome extraction on a noiseless simulator. We prepare the logical Bell state ∣Φ+⟩L|\Phi^+\rangle_L and measure both stabilizers, Z3Z2Z1Z0Z_3 Z_2 Z_1 Z_0 and X3X2X1X0X_3 X_2 X_1 X_0, onto separate ancillas. Since ∣Φ+⟩L|\Phi^+\rangle_L lies in the codespace, both syndrome bits should return 0 deterministically.

sim = AerSimulator()
pm_sim = generate_preset_pass_manager(backend=sim, optimization_level=0)
sampler_sim = Sampler(mode=sim)

result = sampler_sim.run([pm_sim.run(qc_check)], shots=2048).result()
counts = result[0].data.c.get_counts()

# Marginalize: key "s_X s_Z" -> separate counts for each syndrome bit
sz_counts = {"0": 0, "1": 0}
sx_counts = {"0": 0, "1": 0}
for bitstring, n in counts.items():
    sx_counts[bitstring[0]] += n  # leftmost bit = c[1] = s_X
    sz_counts[bitstring[1]] += n  # rightmost bit = c[0] = s_Z

print(f"Joint syndrome counts (s_X s_Z): {counts}")
print(f"  s_Z (Z3 Z2 Z1 Z0): {sz_counts}")
print(f"  s_X (X3 X2 X1 X0): {sx_counts}")

Output:

Joint syndrome counts (s_X s_Z): {'00': 2048}
  s_Z (Z3 Z2 Z1 Z0): {'0': 2048, '1': 0}
  s_X (X3 X2 X1 X0): {'0': 2048, '1': 0}

Both syndrome bits return 0 deterministically on the clean logical Bell state, confirming that ∣Φ+⟩L|\Phi^+\rangle_L lies in the simultaneous +1+1 eigenspace of Z3Z2Z1Z0Z_3 Z_2 Z_1 Z_0 and X3X2X1X0X_3 X_2 X_1 X_0, that is, in the codespace.

Before moving to hardware, we walk through how the two stabilizers respond to single-qubit Pauli errors. A stabilizer measurement returns −1-1 (syndrome bit 1) when the error operator anti-commutes with the stabilizer, and +1+1 (syndrome bit 0) when it commutes. This follows from how Pauli operators act on eigenstates: if S∣ψ⟩=+∣ψ⟩S|\psi\rangle = +|\psi\rangle and EE anti-commutes with SS (ES=−SEES = -SE), then S(E∣ψ⟩)=−ES∣ψ⟩=−E∣ψ⟩S(E|\psi\rangle) = -E S|\psi\rangle = -E|\psi\rangle, so the corrupted state E∣ψ⟩E|\psi\rangle is a −1-1 eigenstate of SS.

We verify this directly on the simulator by injecting XX, ZZ, and YY errors on different data qubits and reading both syndrome bits.

# Inject a single-qubit Pauli error before syndrome extraction and read both syndromes.
def build_check_circuit_with_error(error_type=None, error_qubit=0):
    data_r = QuantumRegister(4, "data")
    syn_r = QuantumRegister(2, "syn")
    c_r = ClassicalRegister(2, "c")
    qc = QuantumCircuit(data_r, syn_r, c_r)

    qc.append(qc_logical_phi_plus.to_instruction(), data_r)

    if error_type == "X":
        qc.x(data_r[error_qubit])
    elif error_type == "Y":
        qc.y(data_r[error_qubit])
    elif error_type == "Z":
        qc.z(data_r[error_qubit])

    # Z_3 Z_2 Z_1 Z_0 onto syn[0]
    for i in range(4):
        qc.cx(data_r[i], syn_r[0])

    # X_3 X_2 X_1 X_0 onto syn[1]
    for i in range(4):
        qc.h(data_r[i])
    for i in range(4):
        qc.cx(data_r[i], syn_r[1])
    for i in range(4):
        qc.h(data_r[i])

    qc.measure(syn_r[0], c_r[0])
    qc.measure(syn_r[1], c_r[1])
    return qc


cases = [
    ("no error", None, None),
    ("X on q0", "X", 0),
    ("X on q2", "X", 2),
    ("Z on q1", "Z", 1),
    ("Z on q3", "Z", 3),
    ("Y on q0", "Y", 0),
    ("Y on q2", "Y", 2),
]

print(f"{'case':<12} {'s_X':>4} {'s_Z':>4}")
print("-" * 24)
for label, err, q in cases:
    qc = build_check_circuit_with_error(err, q)
    res = sampler_sim.run([pm_sim.run(qc)], shots=1024).result()
    counts = res[0].data.c.get_counts()
    bitstring = max(counts, key=counts.get)  # deterministic on noiseless sim
    s_X, s_Z = bitstring[0], bitstring[1]
    print(f"{label:<12} {s_X:>4} {s_Z:>4}")

Output:

case          s_X  s_Z
------------------------
no error        0    0
X on q0         0    1
X on q2         0    1
Z on q1         1    0
Z on q3         1    0
Y on q0         1    1
Y on q2         1    1

The simulation confirms the anti-commutation analysis: every single-qubit XX error gives the same syndrome regardless of which data qubit it hits, and similarly for ZZ and YY. The four possible outcomes of the two-bit syndrome correspond cleanly to four error classes (the table below lists the syndrome bits as (sX,sZ)(s_X, s_Z), matching the displayed bitstring order convention in Qiskit c[1] c[0]):

Error on any single data qubit
sXs_X
sZs_Z
no error00
XX01
ZZ10
YY11

Two limitations of this scheme are worth stating now. First, the table identifies the type of error (XX, ZZ, YY, or none) but not the qubit on which the error occurred: an XX error on data qubit 0 and an XX error on data qubit 2 produce identical syndromes, as the simulation shows directly. Without knowing the qubit location we cannot apply a corresponding inverse to undo the error, which is why we use the [[4,2,2]][[4,2,2]] code for detection only: we post-select on sX=sZ=0s_X = s_Z = 0 and do not attempt correction. Second, the table covers only single-qubit errors; certain weight-2 errors commute with both stabilizers and escape the syndrome entirely. We return to that limitation in Section 1.3.

Check your understanding

We just saw that an XX error flips the Z3Z2Z1Z0Z_3Z_2Z_1Z_0 syndrome, and a ZZ error would flip the X3X2X1X0X_3X_2X_1X_0 syndrome. What happens if a YY error hits a single data qubit? Which stabilizer or stabilizers would detect it?

Hint: Y=iXZY = iXZ, so a YY error is both a bit-flip and a phase-flip on the same qubit.

  • Since Y=iXZY = iXZ, it anti-commutes with both ZZ-type and XX-type stabilizer operators on the affected qubit. A single YY error therefore triggers both stabilizers at once, giving syndrome sZ=1s_Z = 1 and sX=1s_X = 1. The four single-qubit Pauli outcomes (none, XX, ZZ, YY) map to four distinct syndrome patterns, as the simulation above confirms.

1.2.2 Hardware demonstration: joint ZZ and XX syndrome extraction

We now run the same circuit on hardware and quantify the trade-off introduced by post-selecting on sX=sZ=0s_X = s_Z = 0. The metrics we report are the post-selection rate AA (fraction of shots that pass both checks), the sampling overhead 1/A1/A, and the Hellinger fidelity to the ideal data-qubit distribution before and after post-selection.

The hardware circuit reuses the syndrome-extraction circuit qc_check built in the simulator validation above and adds measurements on the four data qubits at the end, in keeping with the end-of-circuit detection scope in Part 1. The two registers are kept separate: the syndrome bits land in c (sZ=c[0]s_Z = c[0], sX=c[1]s_X = c[1]), and the four data bits land in a new register data_c.

# Reuse the syndrome circuit and add measurements on the four data qubits.
qc_check_hw = qc_check.copy()

data_c = ClassicalRegister(4, "data_c")
qc_check_hw.add_register(data_c)

data_q = qc_check_hw.qregs[0]  # the data register from qc_check
for i in range(4):
    qc_check_hw.measure(data_q[i], data_c[i])

qc_check_hw.draw("mpl", style="iqp")

Output:

Output of the previous code cell

Submit the circuit. Wait for completion before proceeding.

# Transpile for the chosen IBM backend
qc_tr = pm.run(qc_check_hw)

job = sampler.run([qc_tr], shots=10000)
job_id_hw = job.job_id()
# print("Submitted job:", job_id_hw)
# Check job status
job = service.job(job_id_hw)
job.status()

Output:

'QUEUED'

Parse the six-bit results into the two syndromes (sZs_Z, sXs_X) and the four data bits, then apply each post-selection filter independently.

result = job.result()
data_dist = result[0].data

# Per-shot bitstrings preserve syndrome-data pairing across the two registers.
syn_bitstrings = data_dist.c.get_bitstrings()  # 2 bits each: c[1] c[0] = s_X s_Z
data_bitstrings = data_dist.data_c.get_bitstrings()  # 4 bits each: data qubits

raw_data_counts = {}
postZ_data_counts = {}
postX_data_counts = {}
postB_data_counts = {}

acc_Z = acc_X = acc_B = 0
total = len(syn_bitstrings)

for sb, db in zip(syn_bitstrings, data_bitstrings):
    sZ, sX = sb[-1], sb[-2]  # Qiskit prints c[0] on the right
    raw_data_counts[db] = raw_data_counts.get(db, 0) + 1

    if sZ == "0":
        acc_Z += 1
        postZ_data_counts[db] = postZ_data_counts.get(db, 0) + 1
    if sX == "0":
        acc_X += 1
        postX_data_counts[db] = postX_data_counts.get(db, 0) + 1
    if sZ == "0" and sX == "0":
        acc_B += 1
        postB_data_counts[db] = postB_data_counts.get(db, 0) + 1

A_Z = acc_Z / total
A_X = acc_X / total
A_B = acc_B / total

print(f"Total shots: {total}")
print(f"{'Filter':<24s} {'Accepted':>10s} {'Post-sel rate':>14s} {'Overhead 1/A':>14s}")
print("-" * 64)
print(f"{'Z_3 Z_2 Z_1 Z_0 only':<24s} {acc_Z:>10d} {A_Z:>14.4f} {1 / A_Z:>14.2f}")
print(f"{'X_3 X_2 X_1 X_0 only':<24s} {acc_X:>10d} {A_X:>14.4f} {1 / A_X:>14.2f}")
print(f"{'Both':<24s} {acc_B:>10d} {A_B:>14.4f} {1 / A_B:>14.2f}")

Output:

Total shots: 10000
Filter                     Accepted  Post-sel rate   Overhead 1/A
----------------------------------------------------------------
Z_3 Z_2 Z_1 Z_0 only           9088         0.9088           1.10
X_3 X_2 X_1 X_0 only           7938         0.7938           1.26
Both                           7475         0.7475           1.34
# Ideal reference distribution (probabilities)
ideal_data_probs = {
    "0000": 0.25,
    "1111": 0.25,
    "0110": 0.25,
    "1001": 0.25,
}

# hellinger_fidelity normalizes count dictionaries internally.
F_raw = hellinger_fidelity(raw_data_counts, ideal_data_probs)
F_postZ = (
    hellinger_fidelity(postZ_data_counts, ideal_data_probs) if acc_Z else float("nan")
)
F_postX = (
    hellinger_fidelity(postX_data_counts, ideal_data_probs) if acc_X else float("nan")
)
F_postB = (
    hellinger_fidelity(postB_data_counts, ideal_data_probs) if acc_B else float("nan")
)

print(f"Hellinger fidelity (raw)               = {F_raw:.4f}")
print(f"Hellinger fidelity (post Z_3Z_2Z_1Z_0) = {F_postZ:.4f}")
print(f"Hellinger fidelity (post X_3X_2X_1X_0) = {F_postX:.4f}")
print(f"Hellinger fidelity (post both)         = {F_postB:.4f}")

labels = ["raw", "$Z_3Z_2Z_1Z_0$ only", "$X_3X_2X_1X_0$ only", "both"]
fids = [F_raw, F_postZ, F_postX, F_postB]
accs = [1.0, A_Z, A_X, A_B]

x = np.arange(len(labels))
fig, ax = plt.subplots()
ax.bar(x, fids, label="Hellinger fidelity $F$")
ax.plot(x, accs, marker="o", color="C1", linewidth=2, label="post-selection rate $A$")
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.set_ylim(0, 1.0)
ax.set_title("[[4,2,2]] hardware: fidelity and post-selection rate by filter")
ax.legend(loc="best")
ax.grid(True, axis="y", alpha=0.3)
plt.show()

Output:

Hellinger fidelity (raw)               = 0.8195
Hellinger fidelity (post Z_3Z_2Z_1Z_0) = 0.8686
Hellinger fidelity (post X_3X_2X_1X_0) = 0.8743
Hellinger fidelity (post both)         = 0.9071
Output of the previous code cell

In the saved run, post-selection improves the measured Hellinger fidelity, with the highest value obtained when both syndromes pass. Requiring both checks also gives the lowest acceptance, so the improvement comes at the cost of fewer usable shots. This measures agreement of the final Z-basis distribution with the ideal distribution, rather than certifying the full quantum state. On another backend or calibration, compare the fidelity and acceptance again. Requiring both syndromes always keeps a subset of the shots accepted by either check alone, but the fidelity ordering can change.

Check your understanding

Suppose XX errors strike both qubit 00 and qubit 11 simultaneously (X0X1X_0 X_1). What syndrome would Z3Z2Z1Z0Z_3Z_2Z_1Z_0 produce? Would X3X2X1X0X_3X_2X_1X_0 catch it? Would the error be detected at all?

  • For Z3Z2Z1Z0Z_3Z_2Z_1Z_0: each XX flips one qubit's contribution to the ZZ-eigenvalue, and two flips cancel, so Z3Z2Z1Z0Z_3Z_2Z_1Z_0 returns +1+1 (syndrome bit 0). For X3X2X1X0X_3X_2X_1X_0: X0X1X_0 X_1 commutes with X3X2X1X0X_3X_2X_1X_0 (both are products of XXs), so X3X2X1X0X_3X_2X_1X_0 also returns +1+1. The error goes undetected. This is the d=2d=2 shortcoming: X0X1X_0 X_1 is a weight-22 logical operator that maps one valid codeword to another without leaving the codespace.

Consider two errors: X0X_0 (single bit-flip on qubit 00) and X1X_1 (single bit-flip on qubit 11). Both are weight-11 errors that the [[4,2,2]][[4,2,2]] code does detect. Can the code also tell them apart, that is, can it identify which qubit was hit?

  • No. Both X0X_0 and X1X_1 produce the same syndrome, sZ=1s_Z = 1 and sX=0s_X = 0. The two-bit syndrome identifies that an XX-type error happened, but not which qubit was affected. Equivalently, X0X_0 and X1X_1 differ by the logical operator Xˉ1=X0X1\bar X_1 = X_0 X_1, and logical operators are invisible to stabilizer measurements, so X0X_0 and X1=X0⋅(X0X1)X_1 = X_0 \cdot (X_0 X_1) look identical to the syndrome.

    This is why we use the [[4,2,2]][[4,2,2]] code for detection only: it cannot correct an arbitrary single-qubit error. Codes with d≥3d \geq 3, such as the Steane [[7,1,3]][[7,1,3]] code, can correct any single-qubit error with ideal syndrome extraction.

The post-selection filter keeps shots where both syndrome bits read 00, but passing the filter is not the same as correctness: some accepted shots can still land outside the ideal support of ∣Φ+⟩L|\Phi^+\rangle_L. The cell below extracts these false-accept shots from the hardware data and breaks them into two categories: those whose data bitstrings have even parity but lie outside the target support, and those with odd parity. These are categories of computational-basis outcomes, not a test of whether the quantum state was in the codespace.

# Ideal support of |Phi^+>_L
ideal_support = {"0000", "1111", "0110", "1001"}

# Z-basis support of the code: the eight even-parity bitstrings.
even_parity_bitstrings = {
    "0000",
    "1111",  # support of logical |00>
    "0011",
    "1100",  # support of logical |01>
    "0101",
    "1010",  # support of logical |10>
    "0110",
    "1001",  # support of logical |11>
}

false_accept = {
    db: cts for db, cts in postB_data_counts.items() if db not in ideal_support
}
n_false = sum(false_accept.values())
n_ideal = acc_B - n_false

print(f"Both-checks accepted shots: {acc_B}")
print(f"  in ideal support of |Phi^+>_L: {n_ideal}")
print(
    f"  false accepts:                 {n_false} ({100 * n_false / acc_B:.2f}% of accepted)"
)

if n_false == 0:
    print("\nNo false-accept shots in this run.")
else:
    n_even = sum(
        cts for db, cts in false_accept.items() if db in even_parity_bitstrings
    )
    n_odd = n_false - n_even

    print()
    print("False-accept breakdown:")
    print(
        f"  even parity, outside target support: "
        f"{n_even} ({100 * n_even / n_false:.1f}%)"
    )
    print(
        f"  odd parity, inconsistent with Z check: "
        f"{n_odd} ({100 * n_odd / n_false:.1f}%)"
    )

    # Per-bitstring detail: closest ideal pattern(s) + differing qubit positions.
    # If multiple ideals tie for the minimum Hamming distance, we mark the
    # bit-flip pattern as ambiguous rather than picking one arbitrarily.
    def hamming(a, b):
        return sum(x != y for x, y in zip(a, b))

    print()
    print(
        f"{'observed':<10s} {'even parity':<14s} {'closest ideal(s)':<28s} "
        f"{'differing qubits':<22s} {'count':>8s}"
    )
    print("-" * 86)
    for db in sorted(false_accept, key=lambda k: -false_accept[k]):
        parity_flag = "yes" if db in even_parity_bitstrings else "no"
        dists = {ip: hamming(db, ip) for ip in ideal_support}
        d_min = min(dists.values())
        closest = sorted(ip for ip, d in dists.items() if d == d_min)
        if len(closest) == 1:
            best = closest[0]
            # Qiskit string position i (left-to-right) maps to qubit index 3 - i.
            diffs = sorted(3 - i for i, (a, b) in enumerate(zip(db, best)) if a != b)
            diff_str = ", ".join(f"q{p}" for p in diffs)
        else:
            best = " | ".join(closest)
            diff_str = f"ambiguous (d={d_min})"
        print(
            f"{db:<10s} {parity_flag:<14s} {best:<28s} {diff_str:<22s} "
            f"{false_accept[db]:>8d}"
        )

Output:

Both-checks accepted shots: 7475
  in ideal support of |Phi^+>_L: 6796
  false accepts:                 679 (9.08% of accepted)

False-accept breakdown:
  even parity, outside target support: 49 (7.2%)
  odd parity, inconsistent with Z check: 630 (92.8%)

observed   even parity    closest ideal(s)             differing qubits          count
--------------------------------------------------------------------------------------
0001       no             0000 | 1001                  ambiguous (d=1)             145
0111       no             0110 | 1111                  ambiguous (d=1)             104
1000       no             0000 | 1001                  ambiguous (d=1)              87
1110       no             0110 | 1111                  ambiguous (d=1)              86
0100       no             0000 | 0110                  ambiguous (d=1)              68
1101       no             1001 | 1111                  ambiguous (d=1)              53
1011       no             1001 | 1111                  ambiguous (d=1)              45
0010       no             0000 | 0110                  ambiguous (d=1)              42
0101       yes            0000 | 0110 | 1001 | 1111    ambiguous (d=2)              18
1100       yes            0000 | 0110 | 1001 | 1111    ambiguous (d=2)              13
1010       yes            0000 | 0110 | 1001 | 1111    ambiguous (d=2)               9
0011       yes            0000 | 0110 | 1001 | 1111    ambiguous (d=2)               9

The false-accept shots could have arisen from several mechanisms: readout errors on the data or ancilla qubits, gate errors in the syndrome circuit, weight-22 errors that the syndrome cannot detect, or non-Pauli errors such as energy relaxation, which a stabilizer measurement catches only with some probability. The "closest ideal(s)" column compares bitstrings, but it does not identify which of these mechanisms occurred or certify that the quantum state was in the codespace. Section 1.3 takes up these limits.

Readout error mitigation techniques such as M3 or TREX could be applied to reduce the readout contribution and obtain higher-fidelity post-selected results.

Check your understanding

A stabilizer code has parameters [[n,k,d]][[n, k, d]] with r=n−kr = n - k stabilizer generators. Suppose we want to encode more logical qubits at the same distance. Must the number of stabilizer generators increase, and what determines the syndrome-extraction cost?

  • Not necessarily: r=n−kr = n - k need not increase with kk. For example, even-nn codes with n≥4n \geq 4 and generators X⊗nX^{\otimes n} and Z⊗nZ^{\otimes n} have parameters [[n,n−2,2]][[n,n-2,2]]: they keep two generators while their weights grow. Syndrome-extraction cost depends on the number and weights of the generators, routing, and whether ancillas are reused. Two-qubit gates are typically a major noise source on near-term hardware, so a larger extraction circuit can introduce more noise and reduce the post-selection rate.

    The following examples illustrate different encoding rates and generator counts:

    Code
    nn
    kk
    dd
    Encoding rate k/nk/n
    Stabilizer generators
    [[4,2,2]][[4,2,2]]4220.502
    [[5,1,3]][[5,1,3]]5130.204
    [[7,1,3]][[7,1,3]] (Steane)7130.146
    [[9,1,3]][[9,1,3]] (Shor)9130.118

    In these examples, the distance-33 codes use more stabilizer generators and have lower encoding rates than the [[4,2,2]][[4,2,2]] code. This comparison is not a universal scaling rule. The cost of code-based detection depends on the chosen code and its implementation.

1.3 Limits of end-of-circuit detection

So far we have looked at end-of-circuit post-selection through two examples: bitstring filtering (Section 1.1) and stabilizer-code post-selection (Section 1.2). Three limitations follow from the architecture they share.

Some errors are not flagged

With d=2d = 2, weight-22 Pauli operators that act non-trivially on the encoded data can commute with both stabilizers and therefore go undetected. The reach is set by the code distance: detecting more errors of higher weight requires a code with larger dd.

The syndrome does not localize the fault

When a syndrome bit fires, the syndrome record tells us that something went wrong somewhere in the circuit but not on which qubit, in which gate layer, or whether the underlying fault was a gate error in the payload, a gate error in the syndrome extraction, or a measurement readout error on the data or ancilla qubits. The single-shot ambiguity reported in the false-accept table (multiple ideal codewords often equally close in bitstring distance) is consistent with the same limit.

Detection itself adds gates

At the logical level, the ∣Φ+⟩L|\Phi^+\rangle_L preparation uses four gates (two H + two CNOT), and the joint Z3Z2Z1Z0Z_3 Z_2 Z_1 Z_0 + X3X2X1X0X_3 X_2 X_1 X_0 syndrome extraction adds 16 logical gates (four CNOT for Z-check + 12 gates for X-check with Hadamard conjugation) and two ancilla qubits. However, transpilation to hardware-native gates increases these counts, as the cell below demonstrates.

# Physical gate counts after transpiling to the hardware backend.
def n_gates(qc):
    return sum(
        n for op, n in qc.count_ops().items() if op not in ("barrier", "measure")
    )


prep_tr = pm.run(qc_logical_phi_plus)
check_tr = pm.run(qc_check)

print(
    f"|Phi^+>_L preparation     : {n_gates(prep_tr):4d} gates, depth {prep_tr.depth():3d}"
)
print(
    f"|Phi^+>_L + joint syndrome: {n_gates(check_tr):4d} gates, depth {check_tr.depth():3d}"
)
print(
    f"  -> syndrome overhead    : {n_gates(check_tr) - n_gates(prep_tr):4d} gates added per shot"
)

Output:

|Phi^+>_L preparation     :   20 gates, depth   7
|Phi^+>_L + joint syndrome:  124 gates, depth  70
  -> syndrome overhead    :  104 gates added per shot

This example is intentionally extreme. In the [[4,2,2]][[4,2,2]] code, the ∣Φ+⟩L|\Phi^+\rangle_L preparation here uses only four logical gates, so the syndrome-extraction block makes up most of the transpiled circuit. The gate-count comparison above illustrates a large relative overhead. When the payload is minimal, syndrome extraction can dominate the total gate count. In a payload with many more gates, the same fixed-size syndrome block would be a smaller fraction of the total. The conclusion that the syndrome-extraction circuit is itself noisy still holds, even though the ratio above does not.

The cost depends on the code's stabilizer count and weights, routing, and ancilla reuse (note the scaling question above). As target circuits grow toward utility scale (40+ qubits), end-of-circuit code-based detection in this direct form might not be the most efficient option on near-term hardware.


Part 2: Mid-circuit detection

Section 1.3 listed three limitations of end-of-circuit detection: certain weight-2 errors go undetected, the syndrome does not localize the fault, and a fixed syndrome-extraction block is applied to every shot. In Part 2, we move detection inside the circuit and partially address the third limitation. Checks couple ancillas to the data at selected circuit locations, including interior points. In these examples, the ancillas are measured at the end alongside the data, and post-selection happens in classical post-processing. When lighter checks are distributed across multiple interior points, the per-shot gate cost can track the circuit structure rather than a fixed code block. Some faults still pass undetected, and these checks do not in general identify a unique fault location.

We work through two ideas:

  1. Coherent Pauli checks (Sections 2.2-2.3): the algebraic foundation. For any Clifford payload UU and post-payload check RR, the pre-payload check L=U†R UL = U^\dagger R\, U defines a valid check pair.
  2. Spacetime codes (Sections 2.4-2.5): a hardware-aware refinement. Place lightweight checks at points in the circuit where the local stabilizer structure makes LL unnecessary, and trace their detection regions through the circuit graph.

Both CPC and spacetime codes are designed for Clifford circuits (or circuits dominated by Clifford gates). The space of valid checks shrinks exponentially as non-Clifford content increases (Martiel & Javadi-Abhari, 2025, Supp. V). The random Clifford payload used in Part 2 is entirely Clifford, which is why it is a convenient testbed.

2.1 From end-of-circuit filtering to mid-circuit checks

End-of-circuit post-selection collects all check information from a final measurement. The checks can only see the cumulative effect of errors across the entire circuit. Mid-circuit checks change what the detection can see. A check ancilla couples to the data at selected points during the circuit. In these examples it is measured at the end alongside the data, and post-selection rejects flagged shots in classical post-processing.

The framework for mid-circuit checks is coherent Pauli checks (CPC), introduced in Section 2.2. CPC tells us what to check and why the check is guaranteed to pass on an error-free circuit. The challenge is making these checks practical. A CPC-derived check can involve a high-weight Pauli operator spanning many qubits, which on a connectivity-constrained device requires routing gates that add more noise than the check removes. Martiel & Javadi-Abhari (2025) address this directly. Spacetime codes keep the same CPC algebra but constrain checks to be spatially local, spreading their sensitivity across many circuit layers instead of many qubits. This transition begins in Section 2.3.3 and is developed in Sections 2.4-2.5.

  • The benefit of a mid-circuit check is not the timing of the measurement, but the fact that the check couples to the circuit at an interior point, which means that its detection region can be tailored to selected parts of the payload. When we say "mid-circuit check," think "interior-coupled check with a spacetime detection region."

    In the Section 2.5 hardware experiment, each check ancilla couples to the payload at a few points along a target wire and is measured at the end of the circuit alongside the data qubits, not at an intermediate point with reset and reuse. Its sensitivity nevertheless extends into the circuit interior because the check operator propagates through the payload under conjugation (discussed in Section 2.4). What we demonstrate is the spacetime-code principle, checks whose detection regions extend deep into the circuit's interior, even though the measurement happens at the boundary. A fully mid-circuit implementation (measure, reset, reuse) would further reduce idle time on ancillas and is an important engineering step. See Lanes et al. (2025) for how dynamic circuit capabilities enable these protocols at scale.

Check your understanding

A 40-qubit circuit has post-selection rate A=0.6A = 0.6 with one mid-circuit check. How many raw shots do you need to collect 3,000 accepted shots? What happens to this number if you add a second independent check with the same per-check post-selection rate?

  • With one check at A=0.6A = 0.6, the sampling overhead is 1/A≈1.671/A \approx 1.67, so you need 3 000/0.6=5 0003\,000 / 0.6 = 5\,000 raw shots.

    If a second independent check also passes 60% of shots, the combined post-selection rate is Acombined=0.6×0.6=0.36A_\text{combined} = 0.6 \times 0.6 = 0.36. Now you need 3 000/0.36≈8 3343\,000 / 0.36 \approx 8\,334 raw shots, about 1.67×1.67\times the single-check case.

    This illustrates that each additional check multiplies the sampling cost, which shows that adding checks is not free. The fidelity gain from each extra check needs to justify the additional loss in post-selection rate. Section 2.5 examines this trade-off in real hardware data.

    (Note: this calculation assumes check outcomes are independent. In practice, checks may share sensitivity to the same noise sources, so the combined post-selection rate can differ from the simple product.)

2.2 Coherent Pauli checks (CPC)

Coherent Pauli checks (CPC) provide a framework for what to check and why the check works.

Here we have a Clifford circuit UU (the payload) that we want to protect. We pick a Pauli operator RR and apply it to the payload's output through a controlled-Pauli gate from an ancilla. The pre-payload partner LL, obtained by pulling RR back through UU, is applied to the input through a second controlled-Pauli. In the ideal (error-free) circuit the two controlled-Paulis cancel coherently on the ancilla, so the ancilla measurement is deterministic. Errors between the two controlled-Paulis that anti-commute with the effective check operator break this cancellation and can flip the ancilla outcome.

Two ways the deterministic outcome can arise
  • State-preparation setting. When UU is run on the standard input ∣0⟩⊗n|0\rangle^{\otimes n} and RR is chosen to be a stabilizer of the target output state U∣0⟩⊗nU|0\rangle^{\otimes n}, then RR alone returns +1+1 on the ideal output. This is the case for the right-only checks in Section 2.3.3. An input stabilizer ZjZ_j pushed forward through the payload stabilizes the output state, so it returns +1+1 with no LL needed.

  • General CPC setting. RR need not be a stabilizer by itself. The guarantee comes from the pair (L,R)(L, R): the coherent LL-UU-RR sandwich returns the ancilla to its starting value on an error-free circuit. If RR is not a stabilizer of the output, measuring it alone need not give a deterministic result. The consistency between LL and RR is checked, not the eigenvalue of either operator individually.

In both settings the detection mechanism is the same.

The detection mechanism is anti-commutation: an error anti-commuting with the check flips its outcome from +1+1 to −1-1, while an error commuting with the check passes undetected. (Concretely, R=Z0Z1R = Z_0 Z_1 catches XX or YY on qubits 0-1 because XZ=−ZXXZ = -ZX, but misses ZZ-type errors there because ZZ commutes with itself.)

To see what this looks like in practice, and why it creates a scalability challenge, we build an example step by step.

2.2.1 CPC in practice: the cost of conjugation

We build a 20-qubit random Clifford payload using a hardware-friendly Clifford gate set (H, CZ, SX, S). The circuit has a brickwork structure: alternating layers of nearest-neighbor CZ entangling gates, interleaved with random single-qubit Clifford gates (randomly chosen sequences of SX and S). The depth parameter counts CZ layers and we use five layers for the examples in Sections 2.2-2.3. Its nearest-neighbor structure can be mapped to a physical line. Section 2.4 extends this construction to a deeper payload for the Paulice benchmark.

# === 2.2.1 Build the payload ===
N_CPC = 20
PAYLOAD_DEPTH = 5
PAYLOAD_SEED = 16

qr = QuantumRegister(N_CPC, "data")
anc_R = QuantumRegister(1, "anc")
payload_qc = QuantumCircuit(qr)
payload_qc.compose(
    create_payload_circuit(N_CPC, depth=PAYLOAD_DEPTH, seed=PAYLOAD_SEED), inplace=True
)

payload_qc_t = pm.run(payload_qc)
print(f"Payload: {N_CPC}-qubit random Clifford, depth parameter {PAYLOAD_DEPTH}")
print(f"  Before transpile: {payload_qc.size()} gates, depth {payload_qc.depth()}")
print(f"  After transpile:  {payload_qc_t.size()} gates, depth {payload_qc_t.depth()}")
payload_qc.draw("mpl", style="iqp", fold=-1)

Output:

Payload: 20-qubit random Clifford, depth parameter 5
  Before transpile: 220 gates, depth 18
  After transpile:  246 gates, depth 19
Output of the previous code cell

This is the payload UU. Now we pick a weight-2 check R=Z8Z9R = Z_8 Z_9 near the center of the qubit register. The RR check circuit is simple:

# === R check: weight 2 ===
R = Pauli(
    "I" * 10 + "ZZ" + "I" * 8
)  # ZZ on qubits 8,9 (Qiskit little-endian: rightmost char = qubit 0)
support_R = [q for q in range(N_CPC) if R[q].to_label() != "I"]
weight_R = len(support_R)

qc_R_check = QuantumCircuit(qr, anc_R)
qc_R_check.h(anc_R)
apply_controlled_paulis(qc_R_check, R, anc_R[0], qr)
qc_R_check.h(anc_R)

# Render R label from its actual support so it cannot drift from the operator.
R_label = "".join(f"Z_{q}" for q in support_R)
print(f"R = {R_label} (weight {weight_R}): {qc_R_check.size()} gates")
qc_R_check.draw("mpl", style="iqp")

Output:

R = Z_8Z_9 (weight 2): 4 gates
Output of the previous code cell

The check uses two CZ gates and two H gates, local on the register. We then conjugate RR through the payload to obtain LL. evolve(..., frame="h") returns the Heisenberg-picture conjugate U†R UU^\dagger R\, U directly:

# === L check: conjugated through payload ===
L = R.evolve(payload_qc, frame="h")
weight_L = sum(L[q].to_label() != "I" for q in range(N_CPC))

qc_L_check = QuantumCircuit(qr, anc_R)
qc_L_check.h(anc_R)
apply_controlled_paulis(qc_L_check, L, anc_R[0], qr)
if L.phase == 1:
    qc_L_check.sdg(anc_R)
elif L.phase == 2:
    qc_L_check.z(anc_R)
elif L.phase == 3:
    qc_L_check.s(anc_R)
qc_L_check.h(anc_R)

print(f"R = {R.to_label()}  (weight {weight_R})")
print(f"L = {L.to_label()}  (weight {weight_L})")
print(f"\nWeight change: {weight_R} → {weight_L} ({weight_L / weight_R:.1f}×)")
print(f"R check: {qc_R_check.size()} gates vs L check: {qc_L_check.size()} gates")
qc_L_check.draw("mpl", style="iqp", fold=-1)

Output:

R = IIIIIIIIIIZZIIIIIIII  (weight 2)
L = -IIIIIIIIIIIYZZIIIIII  (weight 3)

Weight change: 2 → 3 (1.5×)
R check: 4 gates vs L check: 10 gates
Output of the previous code cell

The conjugation produces a different Pauli operator with larger weight and a support that no longer coincides with that of RR. Even modest weight increases can become costly after transpilation: the controlled-Pauli gates for LL could target qubits poorly aligned with the hardware connectivity, forcing extra routing depth. We now assemble the full CPC circuit (LL check, payload, RR check on a single ancilla) and measure exactly that overhead after transpilation.

# === Full CPC circuit + transpile overhead ===
qc_full = QuantumCircuit(qr, anc_R)
qc_full.h(anc_R)
apply_controlled_paulis(qc_full, L, anc_R[0], qr)
qc_full.barrier()
qc_full.compose(payload_qc, qubits=qr, inplace=True)
qc_full.barrier()
apply_controlled_paulis(qc_full, R, anc_R[0], qr)
phase = (L.phase + R.phase) % 4
if phase == 1:
    qc_full.sdg(anc_R[0])
elif phase == 2:
    qc_full.z(anc_R[0])
elif phase == 3:
    qc_full.s(anc_R[0])
qc_full.h(anc_R[0])

qc_full_t = pm.run(qc_full)
twoq_p = payload_qc_t.num_nonlocal_gates()
twoq_f = qc_full_t.num_nonlocal_gates()

twoq_depth_p = payload_qc_t.depth(lambda x: x.operation.num_qubits == 2)
twoq_depth_f = qc_full_t.depth(lambda x: x.operation.num_qubits == 2)

print("Before transpilation:")
print(f"  Payload only:     {payload_qc.size()} gates, depth {payload_qc.depth()}")
print(f"  Full CPC circuit: {qc_full.size()} gates, depth {qc_full.depth()}")
print(
    f"  Check overhead:   +{qc_full.size() - payload_qc.size()} gates ({(qc_full.size() - payload_qc.size()) / payload_qc.size() * 100:.1f}%)"
)
print(f"\nAfter transpilation for {backend.name}:")
print(
    f"  Payload only:     {payload_qc_t.size()} gates, total depth {payload_qc_t.depth()}, 2Q gates {twoq_p}, 2Q depth {twoq_depth_p}"
)
print(
    f"  Full CPC circuit: {qc_full_t.size()} gates, total depth {qc_full_t.depth()}, 2Q gates {twoq_f}, 2Q depth {twoq_depth_f}"
)
print(
    f"  Check overhead:   +{twoq_f - twoq_p} 2Q gates ({(twoq_f - twoq_p) / twoq_p * 100:.1f}%), 2Q depth {twoq_depth_p} → {twoq_depth_f}"
)
qc_full.draw("mpl", style="iqp", fold=-1)

Output:

Before transpilation:
  Payload only:     220 gates, depth 18
  Full CPC circuit: 232 gates, depth 28
  Check overhead:   +12 gates (5.5%)

After transpilation for ibm_marrakesh:
  Payload only:     246 gates, total depth 19, 2Q gates 48, 2Q depth 5
  Full CPC circuit: 367 gates, total depth 75, 2Q gates 89, 2Q depth 32
  Check overhead:   +41 2Q gates (85.4%), 2Q depth 5 → 32
Output of the previous code cell

Before transpilation the CPC adds only a small, fixed number of gates over the bare payload. After transpilation to the backend, the overhead concentrates in the two-qubit layers. The two-qubit gate count rises, and the two-qubit depth, a useful indicator of accumulated noise, also grows. Part of this overhead is routing. A single ancilla has to reach the supports of both LL and RR, so even the weight-2 RR coupling can need extra gates, and this full-circuit count does not separate the two contributions.

Two questions follow:

  1. Does the check actually detect errors? We verify the anti-commutation rule by analyzing which errors the (L,R)(L, R) pair catches (Section 2.3.1).
  2. Can we simplify the check implementation? Sections 2.3.2-2.3.3 show how final measurements or known input stabilizers can replace one side of the CPC pair, leading toward spacetime checks.

2.3 From checks to spacetime codes

We continue with the same five-layer, 20-qubit payload from Section 2.2.1. We verify the detection rule, simplify the check implementation, and then distribute its couplings over time.

# === Section 2.3: Split payload into U_A and U_B ===
mid = len(payload_qc.data) // 2

U_A = QuantumCircuit(qr)
U_B = QuantumCircuit(qr)
for j, inst in enumerate(payload_qc.data):
    if j < mid:
        U_A.append(inst)
    else:
        U_B.append(inst)

qc_split = QuantumCircuit(qr)
qc_split.compose(U_A, inplace=True)
qc_split.barrier(label="error here")
qc_split.compose(U_B, inplace=True)

print(f"Payload split: U_A = {U_A.size()} gates, U_B = {U_B.size()} gates")
qc_split.draw("mpl", style="iqp", fold=-1)

Output:

Payload split: U_A = 110 gates, U_B = 110 gates
Output of the previous code cell

2.3.1 Anti-commutation rule

A CPC check detects an error if and only if the error anti-commutes with the check operator. For an error injected between UAU_A and UBU_B, there are two equivalent ways to see it:

  • From RR's side: the error propagates forward through UBU_B, arriving at RR as UBEUB†U_B E U_B^\dagger. Detection depends on whether this commutes with RR.
  • From LL's side: the error propagates backward through UA†U_A^\dagger, arriving at LL as UA†EUAU_A^\dagger E U_A. Detection depends on whether this commutes with LL.

Since L=U†RUL = U^\dagger R U, these two conditions are algebraically equivalent: LL and RR always agree. We verify this:

# === Verify L and R agree: examples near and far from R ===
L_evolved = L.evolve(payload_qc, frame="s")
print("=== No error: CPC consistency ===")
print(f"  L         = {L.to_label()}")
print(f"  R         = {R.to_label()}")
print(f"  U·L·U†    = {L_evolved.to_label()}")
print(f"  Equals R? {L_evolved.equiv(R)}  → both checks pass.\n")

# Test errors at different positions: near R (qubit 9,10) and far (qubit 0)
test_errors = [
    ("X₉", "I" * (N_CPC - 10) + "X" + "I" * 9),
    ("Z₉", "I" * (N_CPC - 10) + "Z" + "I" * 9),
    ("X₀", "I" * (N_CPC - 1) + "X"),
    ("Z₀", "I" * (N_CPC - 1) + "Z"),
]

for name, E_label in test_errors:
    E = Pauli(E_label)
    E_at_R = E.evolve(U_B, frame="s")
    E_at_L = E.evolve(U_A.inverse(), frame="s")
    comm_R = R.commutes(E_at_R)
    comm_L = L.commutes(E_at_L)
    flag_R = "pass" if comm_R else "FLAGGED"
    flag_L = "pass" if comm_L else "FLAGGED"
    print(f"=== {name} error between U_A and U_B ===")
    print(f"  Commutes with R? {comm_R} → {flag_R}")
    print(f"  Commutes with L? {comm_L} → {flag_L}")
    print(f"  L and R agree: {'✓' if comm_R == comm_L else '✗'}\n")

Output:

=== No error: CPC consistency ===
  L         = -IIIIIIIIIIIYZZIIIIII
  R         = IIIIIIIIIIZZIIIIIIII
  U·L·U†    = IIIIIIIIIIZZIIIIIIII
  Equals R? True  → both checks pass.

=== X₉ error between U_A and U_B ===
  Commutes with R? True → pass
  Commutes with L? True → pass
  L and R agree: ✓

=== Z₉ error between U_A and U_B ===
  Commutes with R? False → FLAGGED
  Commutes with L? False → FLAGGED
  L and R agree: ✓

=== X₀ error between U_A and U_B ===
  Commutes with R? True → pass
  Commutes with L? True → pass
  L and R agree: ✓

=== Z₀ error between U_A and U_B ===
  Commutes with R? True → pass
  Commutes with L? True → pass
  L and R agree: ✓

LL and RR always agree on each error: what one detects, the other detects too. Whether a given error is caught is not simply a matter of distance from the check's support: the rule is anti-commutation between the check operator and the error at the location it is evaluated. Some errors near the support are caught, others commute with the check there and pass. Errors far from the support often propagate through too few gates to reach RR as a non-trivial operator, and so they pass as well.

Now we quantify this: each of the 20 qubits can suffer an XX, YY, or ZZ error, giving 20×3=6020 \times 3 = 60 possible single-qubit errors at the mid-circuit location. How many does this single CPC pair catch?

# === 2.3.1: Full sweep, summary statistics ===
R_at_mid = R.evolve(U_B, frame="h")  # U_B† R U_B
total = N_CPC * 3

print(f"R at boundary:       {R.to_label()}")
print(f"R at error location: {R_at_mid.to_label()}")

r_support = sum(1 for q in range(N_CPC) if R_at_mid[q].to_label() != "I")
by_type = {
    E: sum(R_at_mid.anticommutes(Pauli(E), qargs=[q]) for q in range(N_CPC))
    for E in ["X", "Y", "Z"]
}
r_detected = sum(by_type.values())

print(f"\nSupport: {r_support}/{N_CPC} qubits")
print(f"Detects: {r_detected}/{total} errors ({r_detected / total * 100:.0f}%)")
print(
    f"  X: {by_type['X']}/{N_CPC},  Y: {by_type['Y']}/{N_CPC},  Z: {by_type['Z']}/{N_CPC}"
)
print(
    f"Blind spots: {total - r_detected}/{total} ({(total - r_detected) / total * 100:.0f}%)"
)

Output:

R at boundary:       IIIIIIIIIIZZIIIIIIII
R at error location: -IIIIIIIIIIXXYIIIIIII

Support: 3/20 qubits
Detects: 6/60 errors (10%)
  X: 1/20,  Y: 2/20,  Z: 3/20
Blind spots: 54/60 (90%)

The detected fraction depends on the check's support at the error location. If the propagated check acts on ww of the nn data qubits there, it anti-commutes with two of {X,Y,Z}\{X,Y,Z\} on each supported qubit and commutes with all three on the others. This sweep therefore detects 2w2w of the 3n3n single-qubit Pauli faults, a fraction 2w/(3n)2w/(3n). Read the support and detected count from the output above; they change with the payload and the chosen insertion point. The support at this slice is part of the check's detection region, the spacetime wires reached by its back-cumulant (Martiel & Javadi-Abhari, Supp. III-A).

Checks with larger support at this slice catch a larger fraction of this sweep. Additional check pairs at different positions can extend coverage, but each brings its own LL operator. The detection rule as stated covers Pauli errors; a general error is a combination of Paulis, and a coherent or non-unitary error is caught only with the probability carried by the components that anti-commute with the check.

2.3.2 One-sided CPC: reading RR from the data

The compiled resource counts in Section 2.2.1 show why a valid CPC can still be expensive: one ancilla must reach the supports of both LL and RR. Their weights count the controlled-Pauli couplings, while hardware connectivity and routing determine the additional cost. A lower-weight check need not give a shallower compiled circuit.

In Section 2.5 of their paper, van den Berg et al. reduce that cost by moving the check qubit along a line and combining each controlled-Pauli gate with the following swap. Their construction shows why designing checks together with qubit motion can be cheaper than relying on a generic router. Their one-sided construction also removes controlled-RR gates by evaluating a Z-type RR from the final data bits; we illustrate that option below.

  • Pauli.phase from Qiskit stores an overall factor (−i)k(-i)^k. The apply_controlled_paulis helper implements the tensor factors but omits that phase. Under control it becomes a relative phase on the ancilla, so we restore it with S†S^\dagger, ZZ, or SS for exponents 1, 2, or 3. For a CPC pair, use L.phase + R.phase modulo four. The one-sided example below uses L.phase alone. See Martiel & Javadi-Abhari, Supplementary Information §II-C and Fig. S3.

One-sided checks

A CPC pair can also compare an ancilla result with the final data bits. As in van den Berg et al., implement L=U†RUL = U^\dagger R U with controlled gates and evaluate RR classically when it is diagonal in the measurement basis. For the R=Z8Z9R=Z_8Z_9 example from Section 2.2, the syndrome is the input-check bit XOR the two output bits. Ideal shots give zero, while an XX fault on qubit 8 after the payload flips that syndrome.

The cell below reuses apply_controlled_paulis on the same payload, with no inverse and no controlled-RR gates. This preserves the ideal final Z-basis statistics, although measuring LL can change the underlying data state. It illustrates the check identity, rather than benchmarking its hardware benefit.

# Reuse the R = Z_8 Z_9 and L = U^dagger R U from Section 2.2.
# Only L is implemented with gates; R is read from the final data bits.
assert not R.x.any() and R.phase == 0
r_support = np.flatnonzero(R.z).tolist()
assert L.phase in (0, 2)

cd_os = ClassicalRegister(N_CPC, "meas")
cf_os = ClassicalRegister(1, "flag")
qc_os = QuantumCircuit(qr, anc_R, cd_os, cf_os)
qc_os.h(anc_R[0])
apply_controlled_paulis(qc_os, L, anc_R[0], qr)
if L.phase == 2:
    qc_os.z(anc_R[0])
qc_os.h(anc_R[0])
qc_os.compose(payload_qc, qubits=qr, inplace=True)

demo_labels = ["No fault", f"X_{r_support[0]} after U"]
demo_circuits = []
for inject_error in (False, True):
    qc = qc_os.copy()
    if inject_error:
        qc.x(qr[r_support[0]])  # anticommutes with R
    qc.measure(qr, cd_os)
    qc.measure(anc_R[0], cf_os[0])
    demo_circuits.append(qc)

demo_result = (
    AerSimulator(method="stabilizer")
    .run(demo_circuits, shots=256, seed_simulator=7)
    .result()
)
for j, label in enumerate(demo_labels):
    counts = demo_result.get_counts(j)
    accepted = 0
    for bitstring, count in counts.items():
        flag, data = bitstring.split()
        syndrome = (int(flag) + sum(int(data[-1 - q]) for q in r_support)) % 2
        accepted += count * (syndrome == 0)
    print(
        f"{label}: P(flag XOR data parity = 0) = {accepted / sum(counts.values()):.3f}"
    )

Output:

No fault: P(flag XOR data parity = 0) = 1.000
X_8 after U: P(flag XOR data parity = 0) = 0.000

Measuring LL on an ancilla is a projective measurement of the payload. Unless LL is a stabilizer of the state at that point, the measurement collapses the state onto a random ±1\pm 1 eigenspace of LL. The eigenvalue is then faithfully carried to RR (which is why the XOR still passes), but the payload that continues through the circuit is no longer the state the computation prepared. In this one-sided construction, the data state can change while the ideal statistics in the chosen measurement basis remain unchanged.

Section 2.3.3 takes a different simplification of the CPC identity, as follows: choose LL to be a known input stabilizer, so its physical check can be omitted. This leads to an interior stabilizer check.

2.3.3 From CPC to spacetime codes: placing checks where they work

Two-sided CPC compares LL at the input with RR at the output. If LL is a known input stabilizer, its value supplies the reference and its physical check can be omitted, leaving a right-only check. The input ∣0⟩⊗n|0\rangle^{\otimes n} is stabilized by any product of ZZ operators, such as ZjZ_j or the all-ZZ operator. Choose L=ZjL=Z_j and propagate it forward through the payload:

Rj=UZjU†,Rj U∣0⟩⊗n=U∣0⟩⊗n.R_j=U Z_j U^\dagger,\qquad R_j\, U|0\rangle^{\otimes n}=U|0\rangle^{\otimes n}.

Measuring RjR_j at the output therefore gives +1+1 ideally. An arbitrary CPC choice of RR need not have a known value, so dropping its partner can produce random outcomes. Clifford propagation keeps each RjR_j a single Pauli, and the circuit sets its type and support. Finding RjR_j means computing classically what the payload does to ZjZ_j: efficient at any depth for our Clifford payload, but in a general circuit with non-Clifford gates typically cheap only through the first layers. A right-only check therefore gives a general computation a solid start, not a way around classical simulation.

Check your understanding

Why not measure an arbitrary CPC pair LL and RR separately, then XOR their outcomes?

  • The XOR agrees ideally, but measuring LL can project the data onto a random eigenstate and disrupt later coherent computation. The coherent CPC sandwich avoids revealing either individual value. Measuring a known stabilizer is harmless ideally, while reconstructing a partner from compatible final data measurements, as above, preserves those measurement statistics.

For each RjR_j, prepare an ancilla in ∣+⟩|+\rangle, apply its controlled-Pauli factors and any sign correction, then measure in the XX basis (H followed by a computational-basis measurement). The ideal result is bit 0, corresponding to eigenvalue +1+1.

The next cell measures all 20 generators to illustrate the routing cost; using a subset also gives valid right-only checks. The 20 data qubits and 20 ancillas sit on one line, as on a device with only nearest-neighbor couplers. Each ancilla must meet every data qubit in the support of its RjR_j, so the ancillas are swapped through the data line. A controlled-Pauli fused with the swap that follows it costs two CZ gates van den Berg et al., and a swap past a data qubit outside the support still costs three. The cell checks that no ancilla fires without noise, compares CZ counts, and draws the circuit. The payload sits left of the barrier, and the diamond of SWAP gates carries the ancillas up through the data line.

# === Right-only checks: one ancilla per R_j = U Z_j U^dagger, routed on a line ===
sim_stab = AerSimulator(method="stabilizer")
stabs_out = [
    Pauli("I" * (N_CPC - 1 - j) + "Z" + "I" * j).evolve(payload_qc, frame="s")
    for j in range(N_CPC)
]
qc_net, n_swaps, n_fused = right_only_network(stabs_out, N_CPC)

qc_all = QuantumCircuit(2 * N_CPC, N_CPC)
qc_all.compose(payload_qc, qubits=range(N_CPC), inplace=True)
qc_all.barrier()
qc_all.compose(qc_net, inplace=True)
counts = sim_stab.run(qc_all, shots=1000, seed_simulator=7).result().get_counts()
print(
    f"Noiseless: all {N_CPC} ancillas read 0 in every shot: {counts == {'0' * N_CPC: 1000}}"
)

cz_basis = ["cz", "rz", "sx", "x"]
fuse = PassManager(
    [
        Collect2qBlocks(),
        ConsolidateBlocks(basis_gates=cz_basis),
        UnitarySynthesis(basis_gates=cz_basis),
    ]
)
cz_checks = fuse.run(qc_net).count_ops().get("cz", 0)
weights = [sum(S_j[q].to_label() != "I" for q in range(N_CPC)) for S_j in stabs_out]
print(f"Weights of the R_j: {min(weights)} to {max(weights)}")
print(f"Payload: {payload_qc.count_ops()['cz']} CZ")
print(
    f"Right-only checks: {cz_checks} CZ over {n_swaps} swaps, "
    f"{n_fused} of them fused with a controlled-Pauli"
)
qc_all.draw("mpl", style="iqp", fold=-1, scale=0.35)

Output:

Noiseless: all 20 ancillas read 0 in every shot: True
Weights of the R_j: 3 to 7
Payload: 48 CZ
Right-only checks: 1104 CZ over 400 swaps, 96 of them fused with a controlled-Pauli
Output of the previous code cell

Every check in this circuit is valid, and each ancilla measures one stabilizer, so each catches the faults that anti-commute with its RjR_j. The cost is the problem. In this layout, reaching the supports takes 400 swaps, and even with each controlled-Pauli fused into a swap, the checks need more than twenty times as many CZ gates as the payload they protect. Those gates and the waiting ancillas add errors of their own, so on hardware the added noise can easily outweigh what the checks detect. These counts describe this routing construction, not a minimum: placement and check support determine the routing cost on the nearest-neighbor line.

A check need not occupy one time slice. A wire ww is a qubit between two layers. Let AwA_w be the circuit prefix up to that wire. The Pauli's back-propagator is B(P,w)=Aw†PAwB(P,w)=A_w^\dagger P A_w. For input ∣0⟩⊗n|0\rangle^{\otimes n}, couplings in time order 1,…,m1,\ldots,m form a valid check when:

B(Pm,wm)⋯B(P1,w1)=iϕS,S∈⟨Z0,…,Zn−1⟩.B(P_m,w_m)\cdots B(P_1,w_1)=i^\phi S,\qquad S\in\langle Z_0,\ldots,Z_{n-1}\rangle.

Prepare the ancilla in ∣+⟩|+\rangle, apply each controlled Pauli at its wire, cancel the accumulated phase iϕi^\phi on the ancilla, and measure it in the XX basis (Martiel & Javadi-Abhari, Eq. 2). We keep every coupling on one neighboring data qubit to avoid routing while allowing support at different times.

2.4 Spacetime checks with Paulice

The right-only example in Section 2.3.3 showed that removing LL does not eliminate routing. Each ancilla still has to reach the support of its output stabilizer. The local spacetime construction introduced above avoids this routing by placing an ancilla's couplings at different times on a single neighboring data wire.

Qiskit Paulice automates this search for a given circuit and measurement. Each data qubit with a free neighbor on the device can be a target, and that neighbor becomes its check ancilla. With method="windowed", as in the IBM Quantum spacetime-code tutorial, add_pauli_checks searches windows of couplings along each target's wire. A check's syndrome is the XOR of its ancilla bit and, where the search needs them, final data bits listed in check_support. Data bits are read out anyway, so that part of a check costs no gates.

Paulice scores checks with gamma: under a noise model built from the device calibration, it estimates the quasi-probability cost of cancelling the noise the checks leave undetected within the lightcone of the measurement, and lower is better. Gamma is a model score, distinct from the acceptance overhead 1/A1/A of Part 1. Checks are committed one target at a time, and the search returns the circuit after each commitment. The model takes the error of each data-line coupler from the calibration but gives the couplers a check adds a typical rate, so it would not notice a faulty one; we therefore keep only target-ancilla pairs with calibrated coupler error below 0.05 and ancilla readout error below 0.1.

For Sections 2.4-2.5, we extend the same 20-qubit circuit construction from five to ten CZ layers, keeping the generator and random seed fixed. The deeper payload gives errors more opportunities to accumulate and spread, so that we can test whether post-selection can outweigh the added check cost. We run this payload forward, without its inverse, and sample ten signed stabilizers of its ideal output. The stabilizers and Paulice checks are computed for this deeper circuit. We select one physical data line and reuse it for every unchecked and checked circuit. The first sampled stabilizer G0G_0 supplies the measurement for the placement comparison below, and Section 2.5 repeats the search for each stabilizer. We first recall how a check's support moves backward through the gates.

The idea is to take a check operator and pull it backward through the circuit, one gate at a time. At each layer, we record which qubits the operator touches; together, these qubits and layers form the check's detection region. To do this, we need to know how Pauli operators transform when they pass through a gate in reverse. For any Clifford gate, the result is always another Pauli, which is what makes the tracking exact. Our payload uses CZ gates and single-qubit Clifford gates. A CZ, for example, maps:

Xa→CZ(a,b)XaZb,X_a \xrightarrow{\text{CZ}(a, b)} X_a Z_b,

so an XX in a check's support picks up a ZZ on the partner qubit, while a ZZ passes through unchanged. Each two-qubit layer can add qubits to the support or remove them, so the detection region changes shape as it moves backward in time. The rules for CNOT and CZ are collected below.

  • The conjugation U†PUU^\dagger P U pulls a check operator PP at the output of a gate back to its input. Forward propagation of an error instead uses UPU†U P U^\dagger. For Clifford gates, the result is always another Pauli.

    Single-qubit gates (H, S, and so on) can change the type of error on a wire (for example, X↔ZX \leftrightarrow Z through H) but cannot spread it to another qubit. Only two-qubit entangling gates move errors between wires, which is why detection regions grow only at entangling layers.

    CNOT (control cc, target tt), an asymmetric gate:

    Xc↦XcXt,Zc↦Zc,Xt↦Xt,Zt↦ZcZt.X_c \mapsto X_c X_t, \quad Z_c \mapsto Z_c, \quad X_t \mapsto X_t, \quad Z_t \mapsto Z_c Z_t.

    CNOT does "if control is 1, flip target." This asymmetry determines how different errors propagate:

    Bit-flips (XX) travel control → target. An XX on the control changes whether the target gets flipped, so the error spreads to the target (Xc↦XcXtX_c \mapsto X_c X_t). An XX on the target flips it regardless of the control, so it stays put (Xt↦XtX_t \mapsto X_t).

    Phase-flips (ZZ) travel target → control. CNOT makes the target's value depend on the control (∣c,t⟩→∣c,c⊕t⟩|c,t\rangle \to |c, c \oplus t\rangle), so a phase applied to the target effectively becomes conditional on the control's value, kicking a phase back to the control. This is the same phase kickback mechanism used in algorithms like Deutsch-Jozsa and quantum phase estimation. The result is Zt↦ZcZtZ_t \mapsto Z_c Z_t. Meanwhile ZZ on the control does not involve the target at all, so Zc↦ZcZ_c \mapsto Z_c.

    In short: bit-flips flow forward (control → target), phase-flips flow backward (target → control). This directional asymmetry is why backward propagation of ZZ-type checks through a CNOT chain fans out from target toward controls.

    CZ (qubits aa, bb), a symmetric gate:

    Xa↦XaZb,Za↦Za,Xb↦ZaXb,Zb↦Zb.X_a \mapsto X_a Z_b, \quad Z_a \mapsto Z_a, \quad X_b \mapsto Z_a X_b, \quad Z_b \mapsto Z_b.

    Unlike CNOT, CZ treats both qubits identically; there is no "control" or "target." A bit-flip on either qubit picks up a phase-flip on the other. Phase-flips pass through unchanged on both sides. The symmetry means error propagation looks the same from either direction.

    The pattern to remember: entangling gates spread errors. A single-qubit error before the gate can become a two-qubit error after it. This is both the source of the problem (errors propagate through the circuit) and the basis of detection (a check's sensitivity propagates the same way).

# Extend the Section 2.3 circuit to ten CZ layers for the Paulice experiment.
from qiskit.quantum_info import Clifford

ST_DEPTH = 10
payload_st = create_payload_circuit(N_CPC, depth=ST_DEPTH, seed=PAYLOAD_SEED)

N_STAB = 10
stab_rng = np.random.default_rng(250)
payload_cliff = Clifford(payload_st)
stabilizers = [
    Pauli(
        (stab_rng.integers(0, 2, N_CPC).astype(bool), np.zeros(N_CPC, dtype=bool))
    ).evolve(payload_cliff, frame="s")
    for _ in range(N_STAB)
]

bare_circuits = []
for G in stabilizers:
    qc = QuantumCircuit(qr, ClassicalRegister(N_CPC, "meas"))
    qc.compose(payload_st, qubits=qr, inplace=True)
    for q in range(N_CPC):
        if G.x[q]:
            if G.z[q]:
                qc.sdg(qr[q])
            qc.h(qr[q])
    qc.measure(qr, qc.cregs[0])
    bare_circuits.append(qc)

# Choose the data line once, then keep it fixed for every measured stabilizer.
isa_ref = pm.run(bare_circuits[0])
data_line = list(isa_ref.layout.initial_index_layout(filter_ancillas=True))[:N_CPC]
pm_line = generate_preset_pass_manager(
    backend=backend, optimization_level=1, seed_transpiler=7, initial_layout=data_line
)
bare_isa = [pm_line.run(qc) for qc in bare_circuits]

# Screen the available check couplers and ancilla readouts before the search.
gate_2q = next(g for g in ("cz", "ecr", "cx") if g in backend.target.operation_names)
cz_error = {
    frozenset(e): p.error
    for e, p in backend.target[gate_2q].items()
    if p is not None and p.error is not None
}
readout_error = {
    q: p.error
    for (q,), p in backend.target["measure"].items()
    if p is not None and p.error is not None
}
coupling_graph = nx.Graph([tuple(e) for e, err in cz_error.items() if err < 0.05])
print(f"Data line on {backend.name}: {data_line}")
print(f"Sampled {N_STAB} signed stabilizers; first G = {stabilizers[0].to_label()}")

Output:

Data line on ibm_marrakesh: [1, 2, 3, 4, 5, 6, 7, 17, 27, 28, 29, 30, 31, 32, 33, 39, 53, 54, 55, 59]
Sampled 10 signed stabilizers; first G = IZXYYIZYYIZXYZXIXIXX
# === 2.4: Paulice windowed search on the fixed forward-payload data line ===
PAULICE_SEED = 7
G0, isa_G0 = stabilizers[0], bare_isa[0]  # forward payload measured in the basis of G_0
check_targets, check_ancillas = get_check_qubits(backend, data_line)
usable = [
    (t, a)
    for t, a in zip(
        check_targets, check_ancillas
    )  # screen check couplers and ancilla readout
    if coupling_graph.has_edge(t, a) and readout_error.get(a, 1) < 0.1
]
if not usable:
    raise ValueError(
        "No target-ancilla pairs pass the screening. Choose another data line "
        "or backend, or review the screening thresholds."
    )
check_targets, check_ancillas = [t for t, _ in usable], [a for _, a in usable]
paulice_noise = PauliceNoiseModel.from_backend(backend, data_line)


def search(targets, ancillas, circuit=isa_G0):
    return add_pauli_checks(
        circuit,
        targets,
        ancilla_qubits=ancillas,
        noise_model=paulice_noise,
        cost="gamma",
        method="windowed",
        seed=PAULICE_SEED,
    )


def coupling_layers(cc, k):
    """For check k, the data two-qubit layer of its target after which each ancilla coupling acts."""
    circ, depth, found = cc.circuit, {q: 0 for q in data_line}, []
    for inst in circ.data:
        qs = [circ.find_bit(q).index for q in inst.qubits]
        if len(qs) == 2 and all(q in depth for q in qs):
            depth[qs[0]] = depth[qs[1]] = 1 + max(depth[q] for q in qs)
        elif len(qs) == 2 and cc.check_qubits[k] in qs:
            found.append(depth[cc.target_qubits[k]])
    return found


def syndrome_bits(cc, k):
    bits = [
        f"q{data_line.index(q)}" for q in cc.check_support[k] if q != cc.check_qubits[k]
    ]
    return " + ".join(["ancilla", *sorted(bits, key=lambda b: int(b[1:]))])


single_best, target_rows = {}, []
for t, a in zip(check_targets, check_ancillas):
    prog_t = search([t], [a])
    cc = prog_t[-1]
    row = {
        "target": f"q{data_line.index(t)}",
        "physical target": t,
        "ancilla": a,
        "gamma": cc.cost,
        "added 2Q gates": cc.circuit.num_nonlocal_gates() - isa_G0.num_nonlocal_gates(),
    }
    if cc.check_qubits:
        single_best[t] = cc
        row.update(
            {
                "couplings after data layer": coupling_layers(cc, 0),
                "syndrome": syndrome_bits(cc, 0),
            }
        )
    else:
        row.update({"couplings after data layer": [], "syndrome": "no check found"})
    target_rows.append(row)
gamma_bare = prog_t[0].cost
print(f"G_0 = {G0.to_label()}")
print(f"gamma without checks: {gamma_bare:.4f}; one check per row:")
print(pd.DataFrame(target_rows).sort_values("gamma").round(4).to_string())

Output:

G_0 = IZXYYIZYYIZXYZXIXIXX
gamma without checks: 1.8968; one check per row:
  target  physical target  ancilla   gamma  added 2Q gates couplings after data layer                syndrome
3     q8               27       26  1.7615               3                  [0, 3, 6]  ancilla + q7 + q8 + q9
2     q6                7        8  1.7763               3                  [1, 5, 7]  ancilla + q4 + q5 + q6
1     q2                3       16  1.7779               4              [0, 3, 9, 10]  ancilla + q1 + q2 + q4
5    q12               31       18  1.8029               3                 [1, 6, 10]                 ancilla
6    q14               33       34  1.8307               5           [2, 3, 6, 9, 10]                 ancilla
4    q10               29       38  1.8379               2                    [0, 10]                 ancilla
7    q16               53       52  1.8438               2                     [0, 9]           ancilla + q16
0     q0                1        0  1.8506               4               [1, 3, 7, 9]       ancilla + q1 + q2
8    q19               59       75  1.8827               3                  [1, 5, 9]     ancilla + q17 + q18
# Commit checks target by target, the best single check first.
order = sorted(single_best, key=lambda t: single_best[t].cost)
anc_of = dict(zip(check_targets, check_ancillas))
progression = search(order, [anc_of[t] for t in order])
by_count = {}
for cc in progression:
    by_count.setdefault(len(cc.check_qubits), cc)
ladder_rows = []
for n_checks, cc in by_count.items():
    ladder_rows.append(
        {
            "checks": n_checks,
            "gamma": cc.cost,
            "added 2Q gates": cc.circuit.num_nonlocal_gates()
            - isa_G0.num_nonlocal_gates(),
        }
    )
print(pd.DataFrame(ladder_rows).round(4).to_string())
all_checks = progression[-1]
data_set = set(data_line)
ancilla_set = set(all_checks.check_qubits)
plot_coupling_map(
    num_qubits=backend.num_qubits,
    qubit_coordinates=getattr(backend.configuration(), "qubit_coordinates", None),
    coupling_map=backend.configuration().coupling_map,
    figsize=(12, 12),
    qubit_color=[
        "#4CAF50" if q in data_set else "#FF9800" if q in ancilla_set else "#DDDDDD"
        for q in backend.coupling_map.graph.node_indices()
    ],
    qubit_size=220,
    line_width=2,
    font_size=90,
)

Output:

   checks   gamma  added 2Q gates
0       0  1.8968               0
1       1  1.7615               3
2       2  1.6542               6
3       3  1.5514               9
4       4  1.4856              12
5       5  1.4467              17
6       6  1.4333              19
7       7  1.4015              21
8       8  1.4005              25
9       9  1.3981              27
Output of the previous code cell

The first table lists one check per target. Each check couples its ancilla to the target wire at a few points along the payload, the layers shown in the table, and its syndrome might add final data bits. The second table follows the search as it commits checks. Compare the change in gamma and the added two-qubit gates at each step. The targets are ordered by their single-check scores, but overlapping detection regions and noise from added gates mean that the largest improvement need not come first, and a committed check can raise gamma. The device map shows data qubits in green, committed check ancillas in orange, and unused qubits in gray. Each check ancilla is next to its target, so the couplings need no routing.

Each check covers the spacetime region its couplings and syndrome bits reach by back-propagation, as in Section 2.3.3. Coverage is not the whole story, however. Each check adds gates, and gamma weighs the detected noise against the noise those gates bring. Gamma depends on the noise model and on the chosen measurement, so a lower gamma is a search preference, not a guarantee of a better hardware result, and it is not an acceptance rate or a measured fidelity.

The checks also depend on the measured observable. Here they were chosen for G0G_0. Section 2.5 repeats the search for every sampled stabilizer and runs the resulting circuits on hardware.

Check your understanding

A check has a detection region covering some set of spacetime locations. Does this mean it catches every error at those locations?

  • Not every type. At each location in the detection region, the check detects errors that anti-commute with its propagated support there; errors that commute pass through undetected. For one check, the propagated support at a location is a single Pauli, so the check catches two of XX, YY, and ZZ there and misses the third. This is why a single check has weaknesses even within its own detection region, and why complementary checks with different Pauli types or placements are needed for broader protection.

2.5 Hardware experiment: spacetime checks on the payload

Section 2.4 used a device-based noise model to select and score checks. We now test on hardware whether post-selection brings the measured observables closer to their ideal values, and how many shots that improvement costs. Using the same ten-layer payload and fixed data line, we compare an unchecked baseline with an increasing number of checks. Following the spacetime-code tutorial, we repeat the search for each sampled stabilizer and compare raw and post-selected expectation values alongside acceptance.

Why sampled stabilizers?

The payload prepares a stabilizer state ∣ψ⟩=U∣0⟩⊗n|\psi\rangle = U|0\rangle^{\otimes n}, and its projector is the average of the 2n2^n signed elements of its stabilizer group, ∣ψ⟩⟨ψ∣=2−n∑GG|\psi\rangle\langle\psi| = 2^{-n} \sum_G G. The fidelity ⟨ψ∣ρ∣ψ⟩\langle\psi|\rho|\psi\rangle of a prepared state ρ\rho is therefore the average of ⟨G⟩ρ\langle G\rangle_\rho over a uniformly random stabilizer GG, and every GG has ideal value +1+1. Measuring one GG needs only single-qubit rotations before readout, and its value in each shot is a sign times the parity of the measured bits on its support. A few sampled stabilizers give an estimate of the fidelity whose uncertainty shrinks with the number of samples, so the benchmark stays verifiable at any qubit count. Because the sampled stabilizers carry XX and YY factors as well as ZZ, the estimate responds to phase errors as well as bit flips.

A note on the word "fidelity" in this section

For the bare circuits (B0), the average of ⟨G⟩\langle G\rangle over the sampled stabilizers estimates the fidelity of the prepared state. Ten samples give a rough estimate, whose uncertainty depends on both shot noise and variation between the sampled stabilizers. For the checked layouts it does not, even before post-selection. Their checks are chosen separately for every stabilizer, so the data need not be in the same state across the measurement settings. A check can preserve the ideal measurement statistics without preserving the full data state, as noted for the one-sided example. We therefore read both the raw and the post-selected averages of the checked layouts as benchmarks of expectation values, observable by observable, and not as the fidelity of one state.

To test how the number of checks affects detection performance, we compare a ladder of check counts on every sampled stabilizer. All layouts share the payload, the data line, and the measurement, and they differ only in how many checks they add.

2.5.1 The layouts

For every sampled stabilizer GG, add_pauli_checks runs the search of Section 2.4 on the circuit that measures GG, with the targets in the order found there for G0G_0, from the best single check down. It commits one check per target and returns the circuit after each commitment, so one call per stabilizer gives the whole ladder. The important question is how many committed checks to keep.

The layouts are B0, P1, P2, P4, and the last P layout: zero, one, two, and four committed checks, and all of them. The name gives the check count. The last layout keeps every check the search commits, as the tutorial does, and its count depends on how many data qubits have a usable free neighbor. Reading the ladder in order compares successive check-augmented implementations, with B0, the unchecked circuit returned by the search, as the control.

Each GG gets its own checks, because the search depends on the measured observable. The selected data line, committed checks, gate counts, and model scores depend on the backend and its calibration. Use the tables generated by the current run as the reference, and compare the hardware results within that run.

Availability note

On a data line with few usable free neighbors, the search commits fewer than four checks. P4 is then dropped and the last P layout keeps the checks as they are. If one stabilizer commits fewer checks than the others, the ladder stops at that smaller count for all of them.

# === 2.5: the Section 2.4 search, repeated for every sampled stabilizer ===
LADDER = (
    1,
    2,
    4,
)  # check counts to run, followed by the layout with every committed check

progressions = [search(order, [anc_of[t] for t in order], isa) for isa in bare_isa]
n_all = min(len(p) - 1 for p in progressions)
ladder_counts = [k for k in LADDER if k < n_all] + ([n_all] if n_all > 0 else [])
layouts = {"B0": [p[0] for p in progressions]}
layouts.update({f"P{k}": [p[k] for p in progressions] for k in ladder_counts})

zero_shot = pd.DataFrame(
    [
        {
            "layout": name,
            "checks": len(ccs[0].check_qubits),
            "gamma": np.mean([cc.cost for cc in ccs]),
            "added 2Q gates": np.mean(
                [
                    cc.circuit.num_nonlocal_gates() - p[0].circuit.num_nonlocal_gates()
                    for cc, p in zip(ccs, progressions)
                ]
            ),
        }
        for name, ccs in layouts.items()
    ]
)
print(f"Committed checks per stabilizer: {[len(p) - 1 for p in progressions]}")
print(f"Averages over the {N_STAB} sampled stabilizers:")
print(zero_shot.round(4).to_string())

Output:

Committed checks per stabilizer: [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
Averages over the 10 sampled stabilizers:
  layout  checks   gamma  added 2Q gates
0     B0       0  1.9258             0.0
1     P1       1  1.7127             3.8
2     P2       2  1.6198             7.2
3     P4       4  1.4302            14.5
4     P9       9  1.3045            30.7

2.5.2 Comparing layouts without running

The table compares the layouts on two quantities available before any shot is taken, both averaged over the stabilizers. Compare gamma at each step with B0 and the preceding layout. A lower value indicates less uncovered noise under the model, and neither a monotonic decrease nor the highest value at B0 is guaranteed. The added two-qubit gates show the price. Each check couples its ancilla to its target at a few points, and because the ancilla is a neighbor of the target, no routing is needed.

The addon models device noise as a sparse Pauli-Lindblad channel: a set of Pauli fault generators PkP_k, one per gate location and Pauli type, each with a rate λk\lambda_k. For a two-qubit gate with calibrated error probability pp, the error is split evenly over the 15 non-identity two-qubit Paulis, and each generator gets λ=−12ln⁡(1−2p/15)\lambda = -\tfrac{1}{2}\ln(1 - 2p/15). Propagating operators through the circuit sorts the generators into three groups: those that commute with every measured operator (harmless, since they cannot change the output), those that anti-commute with some check's propagated support (detected, since they flip a syndrome bit), and the remainder, the uncovered faults within the measurement lightcone. Gamma is:

γ=exp⁡(2∑k ∈ uncoveredλk),\gamma = \exp\Big(2 \sum_{k\,\in\,\text{uncovered}} \lambda_k\Big),

the quasi-probability cost of the channel that would invert exactly that residual noise (van den Berg, Minev, Kandala, and Temme, Nat. Phys. 2023). For this convention, the usual PEC sampling cost scales as γ2\gamma^2, while post-selection has a separate acceptance cost 1/A1/A. γ=1\gamma = 1 means no positive-rate generator remains uncovered within the measurement lightcone. Committing a check that covers generators of total rate Λ\Lambda divides gamma by e2Λe^{2\Lambda}, while the generators of the check's own gates that it leaves undetected multiply gamma back up. This multiplicative structure is why each well-placed check lowers gamma by its own factor, and why a check that adds more noise than it covers can raise it.

Because the exponent accumulates hundreds of generator rates, absolute gamma is exponentially sensitive to the calibration scale. A modest change in the per-gate error rate raises gamma to a power, so values can differ substantially between backends and between calibration days. Compare gammas only within a single run on a single backend, where the ordering is what matters. When a linear, additive quantity is needed, use ln⁡γ/2=∑kλk\ln\gamma / 2 = \sum_k \lambda_k, the uncovered rate budget; each check's contribution then reads off as a difference of ln⁡γ\ln\gamma.

The noise model comes from PauliceNoiseModel.from_backend(backend, data_line). Each data-line coupler keeps its own calibrated error, readout enters as the average over the data line, and the couplers a check adds get a typical rate, which is why Section 2.4 screens the actual ancilla couplers against the calibration.

2.5.3 Hardware results

The addon inserts its checks on the transpiled circuit, so it returns each layout as a ready-to-run ISA circuit: payload, check ancillas, and measurements, already placed on physical qubits. Every circuit therefore goes to hardware exactly as scored, with no further transpilation (because re-routing would move the checks off the qubits the search chose). Submit all circuits in one job and wait for completion before proceeding.

The submitted circuits retain their check rules, sampled stabilizers, and model scores in metadata. When retrieving a job, use these saved definitions. Repeating the search can change the checks and must not change how an earlier job is analyzed.

# Save the checks and observables with the submitted circuits for later analysis.
circuits_st = []
for name, ccs in layouts.items():
    for j, (G, cc) in enumerate(zip(stabilizers, ccs)):
        qc = cc.circuit.copy()
        qc.metadata["spacetime"] = {
            "layout": name,
            "stabilizer": G.to_label(),
            "check_data": {
                "target_qubits": [int(q) for q in cc.target_qubits],
                "check_qubits": [int(q) for q in cc.check_qubits],
                "check_support": [[int(q) for q in s] for s in cc.check_support],
                "cost": float(cc.cost),
                "cost_metric": cc.cost_metric,
            },
            # Registers and measurements: all that the post-selection rule reads.
            "readout": {
                "num_qubits": qc.num_qubits,
                "cregs": [[r.name, r.size] for r in qc.cregs],
                "measure": [
                    [qc.find_bit(ins.clbits[0]).index, qc.find_bit(ins.qubits[0]).index]
                    for ins in qc.data
                    if ins.operation.name == "measure"
                ],
            },
            "added_2q_gates": qc.num_nonlocal_gates()
            - layouts["B0"][j].circuit.num_nonlocal_gates(),
        }
        circuits_st.append(qc)
job_st = sampler.run(circuits_st, shots=4096)
job_id_st = job_st.job_id()
# print(f"Submitted {len(circuits_st)} circuits to {backend.name}: {job_id_st}")
service.job(job_id_st).status()

Output:

'QUEUED'
from qiskit.primitives.containers import SamplerPub
from qiskit_paulice import CheckedCircuit

job_st = service.job(job_id_st)
result_st = job_st.result()


def readout_circuit(readout):
    """Registers and measurements of a submitted circuit, rebuilt from its metadata."""
    qc = QuantumCircuit(readout["num_qubits"])
    for name, size in readout["cregs"]:
        qc.add_register(ClassicalRegister(size, name))
    for clbit, qubit in readout["measure"]:
        qc.measure(qubit, clbit)
    return qc


submitted_st = []
for i, pub in enumerate(result_st):
    info = pub.metadata.get("circuit_metadata", {}).get("spacetime")
    if info is not None and "readout" in info:
        qc = readout_circuit(info["readout"])
    else:
        # Older SamplerV2 jobs saved the full submitted circuits in their inputs.
        saved_pubs = job_st.inputs.get("pubs", [])
        if len(saved_pubs) != len(result_st):
            raise ValueError(
                "This job has no saved readout definitions. Recover its original "
                "circuits and checks; do not analyze old samples with a new search."
            )
        qc = SamplerPub.coerce(saved_pubs[i]).circuit
        info = qc.metadata.get("spacetime")
    if info is None:
        raise ValueError(
            "This job has no saved check metadata. Recover its original checks "
            "before analysis; do not use a new search to interpret old results."
        )
    submitted_st.append(
        (
            info["layout"],
            Pauli(info["stabilizer"]),
            CheckedCircuit(circuit=qc, **info["check_data"]),
            info["added_2q_gates"],
        )
    )


def evaluate(pub, cc, G):
    """Signed <G> over all shots and over the shots that pass every check, with the shot counts."""
    expected = {r.name: len(r) for r in cc.circuit.cregs}
    actual = {name: bits.num_bits for name, bits in pub.data.items()}
    if actual != expected:
        raise ValueError(
            f"Result registers {actual} do not match the submitted circuit {expected}."
        )
    counts = pub.join_data(list(expected)).get_counts()
    # Register "meas" (data qubit q in bit q) sits in the lowest bits.
    fired = cc.get_postselection_method()
    support, sign = (
        [q for q in range(G.num_qubits) if G.x[q] or G.z[q]],
        (1 if G.phase == 0 else -1),
    )
    value = {
        bs: sign * (-1) ** sum(bs[-1 - q] == "1" for q in support) for bs in counts
    }
    kept = {bs: n for bs, n in counts.items() if not fired(bs).any()}
    n_total, n_kept = sum(counts.values()), sum(kept.values())
    raw = sum(n * value[bs] for bs, n in counts.items()) / n_total
    post = sum(n * value[bs] for bs, n in kept.items()) / n_kept if n_kept else np.nan
    return raw, post, n_kept / n_total, n_total, n_kept


per_layout, run_info = {}, {}
for pub, (name, G, cc, added) in zip(result_st, submitted_st):
    per_layout.setdefault(name, []).append(evaluate(pub, cc, G))
    run_info.setdefault(name, []).append((len(cc.check_qubits), cc.cost, added))
per_layout = {name: np.array(stats) for name, stats in per_layout.items()}
n_stab_st = len(per_layout["B0"])
assert all(len(stats) == n_stab_st for stats in per_layout.values())

z_95, bare_raw = 1.96, per_layout["B0"][:, 0]
rows = []
for name, stats in per_layout.items():
    raw, post, acc, n_total, n_kept = stats.T
    gain = post - bare_raw
    rows.append(
        {
            "layout": name,
            "checks": run_info[name][0][0],
            "gamma": np.mean([r[1] for r in run_info[name]]),
            "added 2Q gates": np.mean([r[2] for r in run_info[name]]),
            "A": acc.mean(),
            "1/A": 1 / acc.mean(),
            "raw": raw.mean(),
            "raw_ci": z_95 * np.sqrt(np.sum((1 - raw**2) / n_total)) / n_stab_st,
            "post": post.mean(),
            "post_ci": z_95 * np.sqrt(np.sum((1 - post**2) / n_kept)) / n_stab_st,
            "gain vs B0": gain.mean(),
            "gain_se": gain.std(ddof=1) / np.sqrt(n_stab_st),
        }
    )

results_st = pd.DataFrame(rows)
print(results_st.round(4).to_string())

Output:

  layout  checks   gamma  added 2Q gates       A     1/A     raw  raw_ci    post  post_ci  gain vs B0  gain_se
0     B0       0  1.9258             0.0  1.0000  1.0000  0.3293  0.0091  0.3293   0.0091      0.0000   0.0000
1     P1       1  1.7127             3.8  0.7418  1.3481  0.3047  0.0092  0.3503   0.0105      0.0210   0.0086
2     P2       2  1.6198             7.2  0.6344  1.5764  0.2888  0.0093  0.3727   0.0113      0.0434   0.0090
3     P4       4  1.4302            14.5  0.4777  2.0933  0.2799  0.0093  0.4505   0.0125      0.1212   0.0155
4     P9       9  1.3045            30.7  0.2974  3.3623  0.2255  0.0094  0.4830   0.0155      0.1537   0.0119

The following explains how the post-selection works. Each circuit measures the data qubits into register meas and the check ancillas into register checks_c. Each check contributes one syndrome bit per shot, the XOR of the measured bits of the qubits in its check_support; 0 means the comparison came out clean and 1 means the check fired. cc.get_postselection_method() returns the rule that reads this record. We rebuild it from the check definitions and the register and measurement map saved with each circuit, then pass it the bitstring from join_data() in that circuit's register order, and a shot is kept only when no check fired. The value of GG in a shot is its sign times the parity of the data bits on its support, as described above.

The table reports the following metrics for each layout:

Column
Meaning
layoutB0 has no checks; P1, P2, P4, and the last P layout hold that many committed checks
checksNumber of checks per circuit
gammaThe addon's residual-noise cancellation cost estimate from Section 2.5.2
added 2Q gatesTwo-qubit gates added to the unchecked circuit
APost-selection rate: fraction of shots passing all checks (1.0 = no checks)
1/ASampling overhead: how many raw shots are needed per accepted shot
rawMean signed ⟨G⟩\langle G\rangle over all shots, before post-selection
postMean signed ⟨G⟩\langle G\rangle over the accepted shots only
raw_ci, post_ci95% half-widths from shot noise, for this fixed set of stabilizers
gain vs B0post minus the raw value of B0 for the same stabilizer
gain_seStandard error of that gain across the sampled stabilizers

Rates and values are averaged over the ten sampled stabilizers; 1/A uses the averaged A.

Read the table along the check count, and compare the following two things measured on hardware:

1. Whether the post-selected value improves, and at what cost in post-selection rate. Each added check can cover more faults, but it also adds gates, and the search commits the best check it finds for each target in turn, even when that check raises gamma. Neither post nor gamma is guaranteed to improve at every step, so compare each change in post with the measured A and the uncertainty of the gain.

2. How the raw value changes as checks are added. The added gates can introduce errors, so compare both raw and post with the raw value of B0. A gain over the checked layout's own raw value is not enough by itself to establish a benefit over running the bare circuit.

In the saved run, raw means decrease along the check ladder, while all post-selected point estimates exceed B0. The checked circuits therefore start from lower raw values, and the improvement appears after filtering. Compare the paired gains and their uncertainty before judging the benefit of each layout.

fig, axes = plt.subplots(1, 2, figsize=(14, 5))

df = results_st
names = df["layout"].tolist()
x = np.arange(len(names))
colors = plt.rcParams["axes.prop_cycle"].by_key()["color"]
w = 0.35

# 1. raw vs post-selected (grouped bars, same color per layout)
ax = axes[0]
for i_b in range(len(names)):
    ax.bar(
        x[i_b] - w / 2,
        df["raw"].iloc[i_b],
        w,
        color=colors[i_b % len(colors)],
        alpha=0.4,
        edgecolor=colors[i_b % len(colors)],
        yerr=df["raw_ci"].iloc[i_b],
        capsize=3,
        error_kw={"linewidth": 1},
    )
    ax.bar(
        x[i_b] + w / 2,
        df["post"].iloc[i_b],
        w,
        color=colors[i_b % len(colors)],
        edgecolor=plt.rcParams["axes.facecolor"],
        yerr=df["post_ci"].iloc[i_b],
        capsize=3,
        error_kw={"linewidth": 1},
    )
ax.set_xticks(x)
ax.set_xticklabels(names)
ax.set_ylabel(r"Mean signed $\langle G\rangle$")
ax.set_title("Raw (faded) vs post-selected, averaged over stabilizers")
ax.axhline(
    y=df["raw"].iloc[0],
    color=plt.rcParams["axes.edgecolor"],
    linestyle="--",
    alpha=0.5,
    label="Bare baseline",
)
ax.legend()

# 2. Acceptance vs post-selected value (scatter)
ax = axes[1]
for i_b, r in df.iterrows():
    ax.scatter(
        r["A"],
        r["post"],
        s=120,
        color=colors[i_b % len(colors)],
        edgecolor=plt.rcParams["axes.facecolor"],
        zorder=3,
    )
    ax.annotate(
        r["layout"],
        (r["A"], r["post"]),
        textcoords="offset points",
        xytext=(6, 6),
        fontsize=9,
        color=colors[i_b % len(colors)],
        fontweight="bold",
    )
ax.set_xlabel("Acceptance (A)")
ax.set_ylabel(r"Post-selected mean $\langle G\rangle$")
ax.set_title("Post-selected value vs acceptance tradeoff")
ax.axhline(
    y=df["post"].iloc[0],
    color=plt.rcParams["axes.edgecolor"],
    linestyle="--",
    alpha=0.5,
    label="Bare (B0)",
)
ax.legend()

plt.tight_layout()
plt.show()

Output:

Output of the previous code cell

In the left panel, faded bars show the raw mean of ⟨G⟩\langle G\rangle, solid bars show the post-selected mean, and the dashed line marks the bare baseline. The right panel shows the trade-off between post-selected mean and acceptance.

In the saved run, the post-selected mean rises along the check ladder while acceptance falls. The layout with all committed checks gives the highest post-selected mean and the lowest accepted-shot yield. This ordering agrees with decreasing gamma in the model table, but it does not establish which layout is best for every application.

Gamma is a model score computed without experimental shots, not a guarantee of hardware performance. Agreement gives a rough check of its ranking for these sampled observables, and another backend or calibration can produce a different ordering. Compare the gain, its uncertainty, acceptance, and added circuit cost when choosing a layout.

2.5.4 Interpretation

The saved run illustrates the central trade-off of post-selected QEC: accepting fewer shots can improve agreement with the ideal observable values. Every checked layout improves on its own raw mean, and the all-check layout gives the largest post-selected gain over B0. Every checked raw mean is below B0 in this run, so the improvement over bare appears only after filtering.

This is the same principle used in the spacetime-code demonstration cited in the introduction, but that demonstration's tenfold figure concerns effective gate error rates. Our observable-by-observable benchmark measures a different quantity and does not reproduce that numerical claim.

Report acceptance AA alongside the post-selected mean and the uncertainty of the paired gain. The sampling overhead 1/A1/A and added gates determine the cost of obtaining accepted shots; more checks need not improve that trade-off. Both the values and their ordering can change with backend calibration, and the model's gamma ranking need not match the hardware ranking.

Check your understanding

Two layouts use the same qubit layout. One has no checks (acceptance rate = 1.0); the other has multiple checks (lower acceptance rate). The checked layout shows a higher post-selected value of ⟨G⟩\langle G\rangle. Which layout is better?

  • It depends on the application.

    If the goal is accurate individual samples, for example in sampling-based algorithms where each accepted shot is a single-shot output, the checked layout might be preferable. Its accepted shots agree more often with the ideal value of the measured observable, and each kept shot is a sample, not a statistical reconstruction. This single-shot property is what distinguishes error detection from error mitigation. A higher post-selected ⟨G⟩\langle G\rangle alone does not show that each accepted shot comes from a higher-fidelity state, because a check can change the data state without changing the statistics of GG.

    If the goal is many samples quickly and lower per-shot accuracy is acceptable (for example, for estimating expectation values), the unchecked layout may be more practical, because it produces more usable shots from the same batch.

    A useful shorthand for comparing layouts. A layout with post-selection rate AA keeps about ANA N of NN raw shots, so it needs 1/A1/A times as many raw shots for the same number of accepted shots. Equal accepted counts give equal precision only if the observable's variance among the accepted shots is also similar. Set that cost against the gap between the post-selected value and the raw value of the bare layout. Comparing layouts on both numbers illustrates that more checks do not always win.

    Caveat: error detection is not unbiased.

    Post-selection removes the errors the checks detect, but not all errors. Faults that commute with every check or that occur outside any check's detection region pass through undetected. The post-selected distribution therefore remains biased: post-selection can reduce the bias, but it guarantees neither an improvement nor its complete removal. For tasks that require unbiased estimates of observables, error detection has to be combined with other error mitigation techniques (for example, probabilistic error cancellation on the post-selected data). The three relevant axes are:

    • Bias: detection can reduce it, with no guarantee of a reduction or of its complete removal;
    • Variance: at comparable per-shot variance, fewer accepted shots mean higher statistical noise per estimate;
    • Cost: checks add gates, and rejected shots reduce the usable yield.

    Design must consider all three of these.


Wrap-up

This lesson covered error detection in quantum circuits through two complementary approaches that differ in where and how checks are placed. Part 1 focused on end-of-circuit detection (checks applied after the circuit completes), while Part 2 developed mid-circuit detection (checks placed at interior points during circuit execution).

Part 1: End-of-circuit detection demonstrated two strategies. Symmetry post-selection (Section 1.1) uses known output constraints, like GHZ's two-bitstring support, to filter corrupted shots in classical post-processing, requiring no extra qubits but only catching errors visible in the final measurement basis. Stabilizer-code post-selection (Section 1.2) adds ancilla qubits and syndrome extraction at the circuit's end, detecting both bit-flip and phase-flip errors through the [[4,2,2]][[4,2,2]] code. The key limitation: all check information is collected at the final boundary, so the syndrome cannot localize when or where faults occurred during execution.

Part 2: Mid-circuit detection moved checks inside the circuit to access errors as they happen. Throughout, mid-circuit refers to where a check's detection region reaches, the circuit interior; the ancillas themselves are read out at the end alongside the data, with no dynamic-circuit operations. Coherent Pauli checks (Sections 2.2-2.3) provided the algebraic foundation: for any Clifford circuit UU, the relation L=U†R UL = U^\dagger R\, U defines valid check pairs, with detection via anti-commutation. The 20-qubit random Clifford payload provides a benchmark for testing whether the detection benefit outweighs the noise from added gates and routing. Spacetime codes (Sections 2.4-2.5) refined this by placing lightweight checks where the circuit structure naturally supports them, with no LL needed, and tracing each check's detection region backward through the circuit. The qiskit-paulice addon automates that search and ranks placements by their model cost for residual noise. Sections 2.4-2.5 use a deeper version of the same circuit construction and compare checks through sampled stabilizers, weighing the post-selected gain of each added check against the acceptance it costs.

This lesson intentionally does not apply error mitigation or suppression techniques (for example, dynamical decoupling, readout error mitigation, or ZNE) that could further improve the results. The goal is to isolate the effect of error detection alone. Martiel & Javadi-Abhari report fidelity gains up to 236×\times in their spacetime-check experiments, which also use dynamical decoupling and readout folding.

Limitations to consider.

  • Spacetime checks are a heuristic. They do not catch all errors. Faults that commute with every check, or that occur outside any detection region, pass undetected. Post-selection can therefore reduce the bias of the results, but it guarantees neither an improvement nor the removal of every error. For unbiased estimation of observables, error detection should be combined with other quantum error mitigation techniques (Martiel & Javadi-Abhari, Supp. I).
  • The checks are most effective for Clifford-dominated circuits; the space of valid checks shrinks exponentially with non-Clifford content (Martiel & Javadi-Abhari, Supp. V).
  • A Pauli operator's overall phase becomes a relative phase between the ancilla branches when the operator is controlled, and may need compensation by a single-qubit gate on the ancilla wire. The one-sided example of Section 2.3.2 corrects a minus sign on LL this way, and general implementations must account for it.

Three concrete open directions follow from this lesson. First, Sections 2.4 and 2.5 apply the placement search to a ten-layer 20-qubit payload; how its runtime scales to deeper circuits on hundreds of qubits determines whether the approach is practical for larger utility-scale circuits. Second, Part 2 used a random Clifford circuit construction at two depths. A natural next step is to check how the detection benefit holds up on deeper circuits and on circuits with some non-Clifford content, such as QAOA or VQE ansatze. Third, spacetime codes here use syndrome information for post-selection rather than active correction, and their heuristic construction has no particular distance guarantee. Moving to fault-tolerant correction requires checks with suitable distance, fault-tolerant syndrome extraction, and a decoder.

References

Coherent Pauli checks and spacetime codes

  1. E. van den Berg, S. Bravyi, J. M. Gambetta, P. Jurcevic, D. Maslov, K. Temme, "Single-shot error mitigation by coherent Pauli checks," Phys. Rev. Research 5, 033193 (2023). arXiv:2212.03937.

  2. S. Martiel and A. Javadi-Abhari, "Low-overhead error detection with spacetime codes," arXiv:2504.15725 (2025).

  3. A. Gonzales, R. Shaydulin, Z. H. Saleem, M. Suchara, "Quantum error mitigation by Pauli check sandwiching," Sci. Rep. 13, 2122 (2023). arXiv:2206.00215.

  4. J. Roffe, D. Headley, N. Chancellor, D. Horsman, V. Kendon, "Protecting quantum memories using coherent parity check codes," Quantum Sci. Technol. 3, 035010 (2018).

  5. D. M. Debroy and K. R. Brown, "Extended flag gadgets for low-overhead circuit verification," Phys. Rev. A 102, 052409 (2020).

Spacetime code foundations

  1. D. Bacon, S. T. Flammia, A. W. Harrow, J. Shi, "Sparse quantum codes from quantum circuits," IEEE Trans. Inf. Theory 63, 2464-2479 (2017). arXiv:1411.3334.

  2. N. Delfosse and A. Paetznick, "Spacetime codes of Clifford circuits," arXiv:2304.05943 (2023).

Stabilizer formalism and the Clifford group

  1. D. Gottesman, "The Heisenberg representation of quantum computers," arXiv:quant-ph/9807006 (1998).

Hardware demonstrations

  1. A. Javadi-Abhari, S. Martiel, A. Seif, M. Takita, K. Wei, "Big cats: entanglement in 120 qubits and beyond," arXiv:2510.09520 (2025).

  2. O. Lanes et al., "A Framework for Quantum Advantage," arXiv:2506.20658 (2025).

  3. E. van den Berg, Z. K. Minev, A. Kandala, K. Temme, "Probabilistic error cancellation with sparse Pauli-Lindblad models on noisy quantum processors," Nat. Phys. 19, 1116-1121 (2023). arXiv:2201.09866.

Software

  1. qiskit-paulice: Pauli check error detection addon for Qiskit, https://github.com/Qiskit/qiskit-paulice
Was this page helpful?
Report a bug, typo, or request content on GitHub.