Skip to main content
KetQat

Appearance

Lesson 51 h 20 min

Syndrome extraction with Stim

Measurement circuits, circuit-level noise models and detector error models in Stim.

After this lesson you can

  • Write a complete memory experiment in Stim with resets, entangling layers, measurements, detectors and an observable
  • State a circuit-level noise model precisely and implement it with Stim's noise channels
  • Define detectors as deterministic parities of measurements and choose them correctly in the first, middle and final rounds
  • Generate and read a detector error model, and explain graphlike decomposition
  • Explain hook errors and compute how a bad CNOT schedule reduces the circuit-level distance
  • Diagnose a non-deterministic detector with noiseless sampling and Stim's error analysis, and repair it

Read first: The surface code, The repetition code

From codes to circuits

A code is a list of checks. An experiment is a circuit: qubits are reset, checks are measured over and over by entangling gates and ancilla measurements, and at the end the data qubits are read out. Every one of these operations can fail, and errors propagate through the gates. To learn how a code performs on hardware we must simulate that circuit with a noise model attached to every operation, and then tell the decoder which measurement outcomes should agree in the absence of noise.

Stim (Gidney 2021) is a stabilizer-circuit simulator built for exactly this. It samples millions of shots of circuits with thousands of qubits per second, and, more importantly for us, it analyses a circuit and produces a detector error model: the list of independent error mechanisms and which checks each one would trip. This lesson teaches the four ideas that every QEC simulation rests on: measurement schedules, circuit-level noise, detectors and observables, and detector error models. You will build a memory experiment by hand, compare it with Stim's generator, measure the cost of a bad schedule, and debug a broken circuit.

All code below runs with stim 1.16 as pinned in the course environment.

Measuring checks with ancillas

Each check gets a measure qubit (ancilla). For a ZZ-type check the data qubits control CNOTs onto the ancilla; for an XX-type check the ancilla is prepared in ∣+⟩\ket{+}, controls CNOTs onto the data, and is measured in the XX basis. In the rotated surface code of the previous lesson, the XX check on data qubits 0,1,3,40, 1, 3, 4 and the ZZ check on 1,2,4,51, 2, 4, 5 are measured like this:

Quantum circuit on 5 wires (q0, q1, q3, q4, ax). step 1: H on ax. step 2: CNOT, control ax, target q0. step 3: CNOT, control ax, target q1. step 4: CNOT, control ax, target q3. step 5: CNOT, control ax, target q4. step 6: H on ax. step 7: measure ax.q0q1q3q4axHH
Measuring the X check on qubits 0, 1, 3, 4 (order 0, 1, 3, 4)
Quantum circuit on 5 wires (q1, q2, q4, q5, az). step 1: CNOT, control q1, target az. step 2: CNOT, control q4, target az. step 3: CNOT, control q2, target az. step 4: CNOT, control q5, target az. step 5: measure az.q1q2q4q5az
Measuring the Z check on qubits 1, 2, 4, 5 (order 1, 4, 2, 5)

On hardware all checks are measured in parallel, in four layers of CNOTs, one per data qubit of each check. Two constraints shape the schedule:

  1. No qubit in two gates at once. Each layer must be a matching between ancillas and data.
  2. Commuting checks must still be measured as commuting. An XX check and a ZZ check that share two data qubits interleave their CNOTs on them. Unless both shared qubits are touched in the same relative order (both first by the XX ancilla, or both first by the ZZ ancilla), the circuit measures something other than the two checks, and some detectors become random. Of the 24 orderings of the four CNOT layers in Stim's generated distance-3 rotated circuit, only 4 keep every detector deterministic (you count them in the exercise); Stim reports the others as having non-deterministic detectors (see "Debugging detectors" below).

Hook errors

The order inside one check matters for a subtler reason. Suppose the XX ancilla above suffers an XX error after its second CNOT. The remaining CNOTs copy it onto data qubits 3 and 4: one fault has become a weight-2 data error X3X4X_3X_4. Such hook errors are unavoidable for weight-4 checks, but their direction is a choice. In this course's layout, Xˉ\bar X runs down a column. The order 0,1,3,40, 1, 3, 4 makes every XX hook horizontal (X3X4X_3X_4, both on one row), perpendicular to Xˉ\bar X: a horizontal pair advances a vertical logical string by only one row, so it is no worse than a single error. The order 0,3,1,40, 3, 1, 4 would make the hook X1X4X_1X_4 vertical, parallel to Xˉ\bar X, and then about d/2d/2 faults suffice for a logical error. The ZZ checks need the opposite orientation, because Zˉ\bar Z runs along a row. The importance of this ordering is discussed in Dennis et al. (2002) and, for small rotated codes, in Tomita and Svore (2014).

We will not take this on trust. Stim can compute the circuit-level distance: the smallest number of error mechanisms that flip the logical observable without tripping any detector (circuit.shortest_graphlike_error()). Stim's generated rotated surface-code circuits use four CNOT layers per round; in the exercise you write permute_cx_layers, swap the middle two layers (order 0, 2, 1, 3, which exchanges the two orientations above) and recompute. The reference solution gives the following, with after_clifford_depolarization noise as in the exercise checks; the uniform model below gives the same distances:

Circuit (memory basis, dd rounds) Detectors deterministic? Circuit-level distance
generated, d=3d = 3 (XX or ZZ memory) yes 3
middle layers swapped, d=3d = 3 yes 2
generated, d=5d = 5 (XX or ZZ memory) yes 5
middle layers swapped, d=5d = 5 yes 3

The swapped circuit still measures the right checks (every detector is deterministic) but loses distance to hook errors: ⌈d/2⌉\lceil d/2 \rceil instead of dd. Nothing in a noiseless simulation would reveal this; only the noisy analysis does.

Circuit-level noise, stated precisely

"Depolarizing noise with p=10−3p = 10^{-3}" is not a noise model until you say where the channels act. Stim's channels are:

  • DEPOLARIZE1(p): with probability pp apply one of X,Y,ZX, Y, Z, each with probability p/3p/3;
  • DEPOLARIZE2(p): with probability pp apply one of the 15 non-identity two-qubit Paulis, each with probability p/15p/15;
  • X_ERROR(p) / Z_ERROR(p): flip with probability pp.

In this course, uniform circuit-level depolarizing noise with parameter pp means the model produced by stim.Circuit.generated(...) with all four of its noise arguments set to pp:

Argument Channel Where
after_clifford_depolarization DEPOLARIZE1(p) / DEPOLARIZE2(p) after every one- and two-qubit Clifford gate
before_round_data_depolarization DEPOLARIZE1(p) on every data qubit at the start of each round
before_measure_flip_probability X_ERROR(p) (or Z_ERROR for XX-basis) before every measurement
after_reset_flip_probability X_ERROR(p) (or Z_ERROR) after every reset

Other models are common and give different numbers: some leave out the measurement and reset terms, some add idle noise on qubits waiting during measurement, some scale the terms differently per operation. The KetQat SDK's surface-code-memory product, for example, uses only after_clifford_depolarization. A logical error rate or threshold quoted without its model cannot be compared with anything.

Detectors and observables

A detector is a set of measurement results whose parity is deterministic when the circuit runs without noise. It "fires" in a shot when its parity differs from the noiseless value. A logical observable is a set of measurement results whose parity equals the encoded logical value we want to protect. Stim refers to earlier measurements by rec[-k], the kk-th most recent result.

For a memory experiment in the ZZ basis (data reset to ∣0⟩\ket{0}, logical ∣0L⟩\ket{0_L}, final data measurement in ZZ):

  • First round. The ZZ checks have value +1+1 on ∣0⋯0⟩\ket{0\cdots0}, so each ZZ-check outcome is by itself a detector. The XX checks do not have a definite value on ∣0⋯0⟩\ket{0\cdots0}: their first outcomes are random, and must not be detectors.
  • Later rounds. Every check is compared with its own previous outcome: DETECTOR rec[-m] rec[-2m]-style pairs. These are the detection events of the repetition-code lesson.
  • Final round. After measuring all data qubits in ZZ, each ZZ check's value can be recomputed from the data outcomes and compared with its last ancilla outcome. XX checks cannot be recomputed from ZZ-basis data.
  • Observable. The product of the data outcomes along a Zˉ\bar Z representative, for example one row.

The repetition code has only ZZ checks, so all of its first-round outcomes are detectors. Here is a complete distance-3, two-round repetition-code memory written by hand, with the uniform noise model above (data qubits 0 to 2, ancillas 3 and 4):

import stim

p = 0.01
circuit = stim.Circuit(f"""
    R 0 1 2 3 4
    X_ERROR({p}) 0 1 2 3 4
    TICK
    DEPOLARIZE1({p}) 0 1 2
    CX 0 3 1 4
    DEPOLARIZE2({p}) 0 3 1 4
    TICK
    CX 1 3 2 4
    DEPOLARIZE2({p}) 1 3 2 4
    TICK
    X_ERROR({p}) 3 4
    MR 3 4
    X_ERROR({p}) 3 4
    DETECTOR(0, 0) rec[-2]
    DETECTOR(1, 0) rec[-1]
    TICK
    DEPOLARIZE1({p}) 0 1 2
    CX 0 3 1 4
    DEPOLARIZE2({p}) 0 3 1 4
    TICK
    CX 1 3 2 4
    DEPOLARIZE2({p}) 1 3 2 4
    TICK
    X_ERROR({p}) 3 4
    MR 3 4
    X_ERROR({p}) 3 4
    DETECTOR(0, 1) rec[-2] rec[-4]
    DETECTOR(1, 1) rec[-1] rec[-3]
    TICK
    X_ERROR({p}) 0 1 2
    M 0 1 2
    DETECTOR(0, 2) rec[-3] rec[-2] rec[-5]
    DETECTOR(1, 2) rec[-2] rec[-1] rec[-4]
    OBSERVABLE_INCLUDE(0) rec[-1]
""")
print(circuit.num_qubits, circuit.num_measurements, circuit.num_detectors, circuit.num_observables)

dem = circuit.detector_error_model(decompose_errors=True)
print(dem.num_errors, "error mechanisms")
print(len(circuit.shortest_graphlike_error()), "faults in the shortest undetectable logical error")

reference = stim.Circuit.generated(
    "repetition_code:memory", distance=3, rounds=2,
    after_clifford_depolarization=p, before_round_data_depolarization=p,
    before_measure_flip_probability=p, after_reset_flip_probability=p,
)
print(reference.num_detectors, reference.detector_error_model(decompose_errors=True).num_errors)
for line in str(dem).splitlines()[:6]:
    print(line)

It prints 5 qubits, 7 measurements, 6 detectors and 1 observable; 19 error mechanisms; a circuit-level distance of 3; and 6 detectors and 19 mechanisms for Stim's generated circuit too. MR measures and resets in one step, which is why there is an X_ERROR on both sides of it. The coordinates in DETECTOR(x, t) are optional annotations (position and round) that make diagrams and debugging much easier. In the exercise you write a function that builds this circuit for any dd and number of rounds, and prove that it is the same experiment as Stim's generator by comparing detector error models mechanism by mechanism.

Detector error models

The last loop prints the first lines of the detector error model:

error(0.01911873511075362) D0
error(0.01911873511075362) D0 D1
error(0.02236793284649183) D0 D2
error(0.005333333333333312) D0 D3
error(0.02236793284649183) D1 D3
error(0.01911873511075362) D1 L0

Each line is an independent mechanism: with the stated probability it flips the listed detectors (D) and observables (L). Stim derives it by propagating every Pauli that every noise channel can insert through the rest of the circuit, and merges mechanisms with identical effects (their probabilities combine as q1(1−q2)+q2(1−q1)q_1(1-q_2) + q_2(1-q_1)). For example D0 D1 is an XX on data qubit 1 in the first round, which trips both first-round checks; D0 D2 trips check 0 in rounds 1 and 2 (detectors D2 and D3 belong to round 2): a measurement error on ancilla 3 in round 1, or an XX that reaches that ancilla just before it is measured; D1 L0 flips the last data qubit, which is on the observable and in check 1 only.

A mechanism that flips at most two detectors is graphlike: it can be drawn as an edge (or an edge to the boundary). Matching decoders need a graph. In the surface code a YY error, or a two-qubit depolarizing term, can flip more than two detectors; decompose_errors=True asks Stim to write such mechanisms as a combination of graphlike pieces, separated by ^ in the model. This decomposition is an approximation the decoder makes, not a property of the noise.

Distances and sampling

Two quantities summarise a circuit before any decoding. The circuit-level distance is what we computed above. The detection fraction (mean fraction of detectors firing per shot) says how busy the decoder will be. For the d=5d = 5 rotated memory under uniform noise:

import numpy as np
import stim

def uniform(d, p, rounds=None):
    return stim.Circuit.generated(
        "surface_code:rotated_memory_z", distance=d, rounds=rounds or d,
        after_clifford_depolarization=p, before_round_data_depolarization=p,
        before_measure_flip_probability=p, after_reset_flip_probability=p,
    )

c = uniform(5, 0.001)
dem = c.detector_error_model(decompose_errors=True)
print(c.num_detectors, dem.num_errors, len(c.shortest_graphlike_error()))

for p in (0.001, 0.003, 0.01):
    det = uniform(5, p).compile_detector_sampler(seed=1).sample(20_000)
    print(p, round(float(det.mean()), 4))

This prints 120 detectors, 1953 error mechanisms and distance 5, then detection fractions 0.0147, 0.043 and 0.1283 for p=0.001,0.003,0.01p = 0.001, 0.003, 0.01: roughly proportional to pp at these rates, between 13 and 15 detection events per thousand detectors for every 10−310^{-3} of pp. Every detector sits in the support of many mechanisms, so it fires far more often than pp itself.

Debugging detectors

The most common bug in a hand-written circuit is a detector whose parity is not deterministic: a wrong rec offset, a first-round XX-check detector in a ZZ memory, a missing measurement, or a schedule that measures the wrong operator. Stim refuses to build an error model for such a circuit:

ValueError: The circuit contains non-deterministic detectors.
...
The collapse anti-commuted with these detectors/observables:
    D1 [coords (2, 2, 0)]

Two independent checks locate the culprit:

  1. Noiseless sampling. Sample circuit.without_noise(). A correct detector never fires; a non-deterministic one fires in about half of the shots.
  2. Stim's analysis. Read the detector names in the error message, together with the reset whose collapse anticommutes with it and the detector's backward-propagating sensitivity.

Then find which measurement the detector really reads. Walk the flattened circuit, keep the list of measured qubits in record order, and resolve each rec[-k]. Compare the qubit's coordinates (get_final_qubit_coordinates()) with the detector's coordinates; in Stim's generated circuits a first-round detector sits on the measure qubit it reads. In the debugging exercise the faulty detector carries the coordinates of a ZZ check but reads the neighbouring XX-check ancilla, whose first-round outcome is random on ∣0⋯0⟩\ket{0\cdots0}. Changing one rec offset repairs it, and the repaired circuit reproduces Stim's reference error model exactly.

Never "fix" a non-deterministic detector by passing allow_gauge_detectors=True or by deleting it without understanding it. The first hides a bug; the second can silently remove information the decoder needs and reduce the distance.

What the exercises cover

  1. Memory circuits by hand (stim-memory-circuits): build the repetition memory for any dd and number of rounds, show its detector error model is identical to the generator's, check its circuit-level distance, and measure the hook-error penalty of the swapped schedule in both memory bases.
  2. Debugging (debug-detector-definitions): find the non-deterministic detector in a hand-edited surface-code circuit with noiseless sampling and Stim's analysis, explain it, and repair it with a one-line change.

Common mistakes

  • Quoting "pp" without the model. State which channels act where; results with and without measurement and reset noise differ substantially.
  • Detectors on random first-round checks. In a ZZ memory, first-round XX-check outcomes are random. Only ZZ checks get first-round detectors (and vice versa for an XX memory).
  • Off-by-one rec offsets. rec[-1] is the most recent measurement in the order the targets were listed. After MR 3 4, rec[-2] is qubit 3.
  • Trusting noiseless sampling alone. It catches non-deterministic detectors, but a schedule with hook errors or a missing detector samples perfectly cleanly. Check the circuit-level distance as well.
  • Forgetting the error after MR. A measure-and-reset needs both a measurement error before and a reset error after it in a uniform model.
  • Comparing circuits by their text. Two correct circuits can differ in qubit numbering and gate order. Compare detector error models, distances and logical error rates instead.

Summary

  • A memory experiment is resets, repeated check measurements, a final readout, detectors and observables.
  • CNOT order matters twice: for measuring commuting checks correctly, and for the direction of hook errors, which can cut the circuit-level distance from dd to ⌈d/2⌉\lceil d/2\rceil.
  • A noise model is a list of channels and where they act; this course's "uniform" model sets all four of Stim's generator noise arguments to pp.
  • Detectors are deterministic parities; the detector error model lists independent mechanisms and the detectors and observables they flip.
  • Non-deterministic detectors are found by noiseless sampling and by Stim's analysis, and repaired by reading the measurement record.

Next, minimum-weight perfect matching turns the detector error model into a graph and decodes it. For a broader discussion of surface-code circuits see Fowler et al. (2012).

Exercises

Run these on your own computer. Each comes with automated checks: python -m pytest test_exercise.py. Nothing you write is sent to KetQat.

Building a memory circuit by hand and finding hook errors

advanced · about 2 h · needs numpy, stim, pytest

Part A: write a complete repetition-code memory experiment in Stim, with detectors, an observable and a one-parameter circuit-level noise model, and prove it is the same experiment as Stim's built-in generator by comparing detector error models. Part B: take Stim's rotated surface-code circuit, reorder its entangling gates, and measure how much circuit-level distance a bad schedule costs.

Part A: conventions

Data qubits are 0 .. d-1; measure qubit d+i measures ZiZi+1Z_iZ_{i+1} for i=0,…,d−2i = 0, \dots, d-2. The noise model has one parameter pp:

  • X_ERROR(p) after every reset (the initial R and every MR);
  • DEPOLARIZE1(p) on every data qubit at the start of every round;
  • DEPOLARIZE2(p) after every CX;
  • X_ERROR(p) before every measurement.

The docstring of repetition_memory_circuit fixes the order of gates and of detectors. Detector order matters for the comparison: Stim's generator emits one detector per measure qubit per round, then one per measure qubit after the final data readout.

Functions to implement in starter.py

Function Contract
repetition_memory_circuit(d, rounds, p) The hand-built circuit described above.
detectors_are_deterministic(circuit, shots, seed) Sample circuit.without_noise(); True when nothing ever fires.
circuit_distance(circuit) len(circuit.shortest_graphlike_error()).
canonical_error_model(circuit) {sorted target names: probability} from the undecomposed DEM, merging repeated keys as independent mechanisms.
permute_cx_layers(circuit, order) Reorder each round's four CX layers of a generated rotated surface code; (0, 2, 1, 3) swaps the middle two. ValueError for a non-permutation or a circuit without four CX layers per round.
detection_event_fraction(circuit, shots, seed) Mean fraction of detectors firing per shot.

What the checks verify

  • Your circuit has 2d−12d-1 qubits, (d−1)(rounds+1)(d-1)(\text{rounds}+1) detectors, one observable and the right number of measurements, and Stim can build its detector error model (which it refuses for non-deterministic detectors).
  • Your detector error model equals the one from stim.Circuit.generated("repetition_code:memory", ...) with all four noise arguments set to pp, mechanism by mechanism.
  • The circuit-level distance of your circuit is dd.
  • Detection events are absent without noise, grow with pp, and are reproducible with a seed.
  • The identity order reproduces the flattened circuit, and of the 24 layer orders exactly 4 keep every detector deterministic (Stim's own error analysis decides, not your helper).
  • The generated surface-code circuits (both bases, d=3,5d = 3, 5) have circuit-level distance dd. After swapping the middle CX layers every detector is still deterministic, so the circuit still measures the stabilizers, but the distance drops to ⌈d/2⌉\lceil d/2\rceil because of hook errors.

Run the checks

python -m pytest test_exercise.py

Before you look at the distances, predict them. Then use circuit.shortest_graphlike_error() (or circuit.diagram("detslice-svg")) to find the fault that propagates from one measure qubit to two data qubits.

Terminal
python -m pip install numpy stim pytest

starter.py

Python
"""Starter: syndrome-extraction circuits in Stim.

Part A builds a repetition-code memory experiment by hand. Qubit indices:
data qubits 0 .. d-1, measure (ancilla) qubits d .. 2d-2; ancilla d+i measures
Z_i Z_{i+1}. Noise model with one parameter p (the same placement as Stim's
generator with all four noise arguments equal to p):

- X_ERROR(p) after every reset (the initial R and every MR);
- DEPOLARIZE1(p) on every data qubit at the start of every round;
- DEPOLARIZE2(p) after every CX;
- X_ERROR(p) before every measurement (MR of ancillas, final M of data).

Part B analyses rotated surface-code circuits produced by Stim's generator.
"""

from __future__ import annotations

import numpy as np
import stim


def repetition_memory_circuit(d: int, rounds: int, p: float) -> stim.Circuit:
    """Hand-built bit-flip repetition-code memory with `rounds` rounds of extraction.

    Per round: DEPOLARIZE1 on data; CX data[i] -> anc[i] for all i, then
    DEPOLARIZE2 on those pairs; CX data[i+1] -> anc[i], then DEPOLARIZE2;
    X_ERROR on ancillas; MR on ancillas; X_ERROR on ancillas. Separate layers
    with TICK.

    Detectors, in this order: round 1, one per ancilla (its outcome alone, since
    |0...0> is a +1 eigenstate of every check); later rounds, one per ancilla
    comparing it with the same ancilla one round earlier; after the final
    X_ERROR + M on all data qubits, one per ancilla: data[i] xor data[i+1] xor
    the last outcome of ancilla i. OBSERVABLE_INCLUDE(0) on the final
    measurement of data qubit d-1.
    """
    raise NotImplementedError("repetition_memory_circuit: implement this function")


def detectors_are_deterministic(circuit: stim.Circuit, shots: int = 256, seed: int = 0) -> bool:
    """Sample the noiseless version of the circuit; True when no detector or observable ever fires."""
    raise NotImplementedError("detectors_are_deterministic: implement this function")


def circuit_distance(circuit: stim.Circuit) -> int:
    """Number of error mechanisms in the smallest graphlike undetectable logical error."""
    raise NotImplementedError("circuit_distance: implement this function")


def canonical_error_model(circuit: stim.Circuit) -> dict[tuple[str, ...], float]:
    """The circuit's detector error model as {sorted target names: probability}.

    Use circuit.detector_error_model(decompose_errors=False), flatten it, and for
    each `error(q)` instruction use the sorted tuple of its target strings (for
    example ("D0", "D3", "L0")) as the key. Combine repeated keys as independent
    mechanisms: q = q1 (1 - q2) + q2 (1 - q1).
    """
    raise NotImplementedError("canonical_error_model: implement this function")


def permute_cx_layers(circuit: stim.Circuit, order: tuple[int, int, int, int]) -> stim.Circuit:
    """Reorder the four CX layers of every round of a generated rotated surface code.

    Flatten the circuit. Every maximal run of instructions that starts at a CX and
    consists of exactly four groups [CX, DEPOLARIZE2 (if present), TICK] is one
    round's entangling schedule; emit its groups in the given order (a
    permutation of 0, 1, 2, 3) and keep every other instruction unchanged. Raise
    ValueError if `order` is not a permutation of range(4) or a run does not have
    four groups. Swapping the middle layers is order (0, 2, 1, 3).
    """
    raise NotImplementedError("permute_cx_layers: implement this function")


def detection_event_fraction(circuit: stim.Circuit, shots: int, seed: int) -> float:
    """Mean fraction of detectors that fire per shot, from compile_detector_sampler(seed=seed)."""
    raise NotImplementedError("detection_event_fraction: implement this function")

test_exercise.py

Python
import importlib.util
import os
from pathlib import Path

def _load_target():
    name = os.environ.get("KETQAT_COMMONS_TARGET", "starter")
    path = Path(__file__).with_name(f"{name}.py")
    spec = importlib.util.spec_from_file_location(f"{Path(__file__).parent.name}_{name}", path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

target = _load_target()

import itertools

import pytest
import stim


def generated_repetition(d, rounds, p):
    return stim.Circuit.generated(
        "repetition_code:memory", distance=d, rounds=rounds,
        after_clifford_depolarization=p, before_round_data_depolarization=p,
        before_measure_flip_probability=p, after_reset_flip_probability=p,
    )


def generated_surface(d, basis, p=0.001):
    return stim.Circuit.generated(f"surface_code:rotated_memory_{basis}", distance=d, rounds=d, after_clifford_depolarization=p)


# --- Part A: the repetition-code memory, by hand --------------------------

@pytest.mark.parametrize("d,rounds", [(2, 1), (3, 1), (3, 4), (5, 3)])
def test_shape_and_determinism(d, rounds):
    c = target.repetition_memory_circuit(d, rounds, 0.01)
    assert c.num_qubits == 2 * d - 1
    assert c.num_detectors == (d - 1) * (rounds + 1)
    assert c.num_observables == 1
    assert c.num_measurements == (d - 1) * rounds + d
    # Independent of your helper: Stim's own analysis refuses non-deterministic detectors.
    c.detector_error_model(decompose_errors=True)
    assert target.detectors_are_deterministic(c)


def test_canonical_error_model_on_a_tiny_circuit():
    c = stim.Circuit("""
        R 0
        X_ERROR(0.1) 0
        X_ERROR(0.2) 0
        M 0
        DETECTOR rec[-1]
    """)
    model = target.canonical_error_model(c)
    assert list(model) == [("D0",)]
    assert model[("D0",)] == pytest.approx(0.1 * 0.8 + 0.2 * 0.9)


@pytest.mark.parametrize("d,rounds", [(3, 1), (3, 3), (5, 4)])
def test_error_model_equals_stims_generator(d, rounds):
    p = 0.01
    mine = target.canonical_error_model(target.repetition_memory_circuit(d, rounds, p))
    reference = target.canonical_error_model(generated_repetition(d, rounds, p))
    assert set(mine) == set(reference)
    for key, q in reference.items():
        assert mine[key] == pytest.approx(q, rel=1e-9, abs=1e-15)


@pytest.mark.parametrize("d", [3, 5, 7])
def test_repetition_circuit_distance(d):
    assert target.circuit_distance(target.repetition_memory_circuit(d, 3, 0.01)) == d


def test_detection_events_grow_with_noise():
    c0 = target.repetition_memory_circuit(5, 5, 0.0)
    assert target.detection_event_fraction(c0, 500, seed=1) == 0.0
    low = target.detection_event_fraction(target.repetition_memory_circuit(5, 5, 0.002), 20_000, seed=1)
    high = target.detection_event_fraction(target.repetition_memory_circuit(5, 5, 0.02), 20_000, seed=1)
    assert 0 < low < high
    again = target.detection_event_fraction(target.repetition_memory_circuit(5, 5, 0.002), 20_000, seed=1)
    assert again == low


# --- Part B: scheduling and hook errors ----------------------------------

@pytest.mark.parametrize("basis", ["x", "z"])
@pytest.mark.parametrize("d", [3, 5])
def test_generated_schedule_has_full_distance(basis, d):
    assert target.circuit_distance(generated_surface(d, basis)) == d


@pytest.mark.parametrize("basis", ["x", "z"])
@pytest.mark.parametrize("d", [3, 5])
def test_swapped_schedule_is_valid_but_loses_distance_to_hook_errors(basis, d):
    swapped = target.permute_cx_layers(generated_surface(d, basis), (0, 2, 1, 3))
    assert swapped.num_detectors == generated_surface(d, basis).num_detectors
    assert target.detectors_are_deterministic(swapped)  # still measures the right stabilizers
    # A single ancilla fault spreads to two data qubits aligned with a logical
    # operator, so roughly half as many faults suffice: ceil(d / 2).
    assert target.circuit_distance(swapped) == (d + 1) // 2


def test_permute_rejects_other_schedules_and_bad_orders():
    with pytest.raises(ValueError):
        target.permute_cx_layers(target.repetition_memory_circuit(3, 2, 0.01), (0, 1, 2, 3))
    with pytest.raises(ValueError):
        target.permute_cx_layers(generated_surface(3, "z"), (0, 1, 1, 3))


def test_identity_order_reproduces_the_circuit():
    c = generated_surface(3, "z")
    assert target.permute_cx_layers(c, (0, 1, 2, 3)) == c.flattened()


def test_most_layer_orders_break_the_measurement():
    # Only orders that keep every X/Z pair of checks interleaved consistently
    # measure commuting operators; Stim's own analysis (not your helper) decides.
    c = generated_surface(3, "z")
    valid = []
    for order in itertools.permutations(range(4)):
        try:
            target.permute_cx_layers(c, order).detector_error_model()
            valid.append(order)
        except ValueError:
            pass
    assert (0, 1, 2, 3) in valid and (0, 2, 1, 3) in valid
    assert len(valid) == 4

Debugging a non-deterministic detector

intermediate · about 1 h · needs numpy, stim, pytest

A colleague hand-edited a distance-3 rotated surface-code memory circuit (ZZ basis, 3 rounds, DEPOLARIZE1/DEPOLARIZE2 with p=0.001p = 0.001 after every Clifford gate). It is stored in BUGGY_CIRCUIT in starter.py. When they try to decode it, circuit.detector_error_model() raises an error and nothing works. Your job is to find the faulty detector with two independent methods, explain why it is wrong, and repair it with a one-line change.

Functions to implement in starter.py

Function Contract
buggy_memory_circuit() Provided. Returns the circuit. Do not change it.
firing_detectors_without_noise(circuit, shots, seed) Indices of detectors that fire at least once when circuit.without_noise() is sampled.
stim_reported_detectors(circuit) Names such as "D1" that Stim lists as non-deterministic in the ValueError raised by circuit.detector_error_model(); [] when the model builds.
detector_measurement_qubits(circuit, k) The qubits whose measurement results detector k combines, found by walking the flattened circuit and resolving each rec[-j]. IndexError for a detector that does not exist.
fixed_memory_circuit() BUGGY_CIRCUIT with exactly one line changed so that every detector is deterministic.

Method

  1. Sample the noiseless circuit. A correct detector never fires without noise; a detector that fires about half the time compares measurements whose parity is random.
  2. Read Stim's own diagnosis. It names the detector, the reset whose collapse anticommutes with it, and the detector's backward-propagating sensitivity.
  3. Compare the detector's coordinates with the coordinates of the qubit it actually reads (circuit.get_final_qubit_coordinates()). In Stim's generated circuits a first-round detector sits at the position of the measure qubit it reads.
  4. Ask which stabilizers have a definite value in the first round of a ZZ-basis memory, then repair the line.

What the checks verify

  • Noiseless sampling and Stim's stabilizer analysis name the same detector.
  • The reference circuit from Stim's generator fires nothing.
  • The faulty detector reads a single measure qubit whose position differs from the detector's coordinates.
  • Your repair changes one line, makes every detector deterministic, puts every single-qubit detector at the position of the qubit it reads, and reproduces the reference circuit's detector error model and circuit-level distance 3.

Run the checks

python -m pytest test_exercise.py
Terminal
python -m pip install numpy stim pytest

starter.py

Python
"""Starter: find and repair a non-deterministic detector.

BUGGY_CIRCUIT is a distance-3 rotated surface-code memory experiment in the Z
basis (3 rounds, DEPOLARIZE1/DEPOLARIZE2 with p = 0.001 after every Clifford
gate) that a colleague edited by hand. Stim refuses to build its detector error
model. Find out which detector is wrong, why, and repair it with a one-line
change.
"""

from __future__ import annotations

import re

import numpy as np
import stim

BUGGY_CIRCUIT = """\
QUBIT_COORDS(1, 1) 1
QUBIT_COORDS(2, 0) 2
QUBIT_COORDS(3, 1) 3
QUBIT_COORDS(5, 1) 5
QUBIT_COORDS(1, 3) 8
QUBIT_COORDS(2, 2) 9
QUBIT_COORDS(3, 3) 10
QUBIT_COORDS(4, 2) 11
QUBIT_COORDS(5, 3) 12
QUBIT_COORDS(6, 2) 13
QUBIT_COORDS(0, 4) 14
QUBIT_COORDS(1, 5) 15
QUBIT_COORDS(2, 4) 16
QUBIT_COORDS(3, 5) 17
QUBIT_COORDS(4, 4) 18
QUBIT_COORDS(5, 5) 19
QUBIT_COORDS(4, 6) 25
R 1 3 5 8 10 12 15 17 19 2 9 11 13 14 16 18 25
TICK
H 2 11 16 25
DEPOLARIZE1(0.001) 2 11 16 25
TICK
CX 2 3 16 17 11 12 15 14 10 9 19 18
DEPOLARIZE2(0.001) 2 3 16 17 11 12 15 14 10 9 19 18
TICK
CX 2 1 16 15 11 10 8 14 3 9 12 18
DEPOLARIZE2(0.001) 2 1 16 15 11 10 8 14 3 9 12 18
TICK
CX 16 10 11 5 25 19 8 9 17 18 12 13
DEPOLARIZE2(0.001) 16 10 11 5 25 19 8 9 17 18 12 13
TICK
CX 16 8 11 3 25 17 1 9 10 18 5 13
DEPOLARIZE2(0.001) 16 8 11 3 25 17 1 9 10 18 5 13
TICK
H 2 11 16 25
DEPOLARIZE1(0.001) 2 11 16 25
TICK
MR 2 9 11 13 14 16 18 25
DETECTOR(0, 4, 0) rec[-4]
DETECTOR(2, 2, 0) rec[-8]
DETECTOR(4, 4, 0) rec[-2]
DETECTOR(6, 2, 0) rec[-5]
REPEAT 2 {
    TICK
    H 2 11 16 25
    DEPOLARIZE1(0.001) 2 11 16 25
    TICK
    CX 2 3 16 17 11 12 15 14 10 9 19 18
    DEPOLARIZE2(0.001) 2 3 16 17 11 12 15 14 10 9 19 18
    TICK
    CX 2 1 16 15 11 10 8 14 3 9 12 18
    DEPOLARIZE2(0.001) 2 1 16 15 11 10 8 14 3 9 12 18
    TICK
    CX 16 10 11 5 25 19 8 9 17 18 12 13
    DEPOLARIZE2(0.001) 16 10 11 5 25 19 8 9 17 18 12 13
    TICK
    CX 16 8 11 3 25 17 1 9 10 18 5 13
    DEPOLARIZE2(0.001) 16 8 11 3 25 17 1 9 10 18 5 13
    TICK
    H 2 11 16 25
    DEPOLARIZE1(0.001) 2 11 16 25
    TICK
    MR 2 9 11 13 14 16 18 25
    SHIFT_COORDS(0, 0, 1)
    DETECTOR(2, 0, 0) rec[-8] rec[-16]
    DETECTOR(2, 2, 0) rec[-7] rec[-15]
    DETECTOR(4, 2, 0) rec[-6] rec[-14]
    DETECTOR(6, 2, 0) rec[-5] rec[-13]
    DETECTOR(0, 4, 0) rec[-4] rec[-12]
    DETECTOR(2, 4, 0) rec[-3] rec[-11]
    DETECTOR(4, 4, 0) rec[-2] rec[-10]
    DETECTOR(4, 6, 0) rec[-1] rec[-9]
}
M 1 3 5 8 10 12 15 17 19
DETECTOR(0, 4, 1) rec[-3] rec[-6] rec[-13]
DETECTOR(2, 2, 1) rec[-5] rec[-6] rec[-8] rec[-9] rec[-16]
DETECTOR(4, 4, 1) rec[-1] rec[-2] rec[-4] rec[-5] rec[-11]
DETECTOR(6, 2, 1) rec[-4] rec[-7] rec[-14]
OBSERVABLE_INCLUDE(0) rec[-7] rec[-8] rec[-9]"""


def buggy_memory_circuit() -> stim.Circuit:
    """The circuit under investigation (provided; do not change)."""
    return stim.Circuit(BUGGY_CIRCUIT)


def firing_detectors_without_noise(circuit: stim.Circuit, shots: int = 512, seed: int = 0) -> list[int]:
    """Indices of detectors that fire at least once when the circuit is sampled without noise.

    A correct detector is deterministic: without noise it never fires. Use
    circuit.without_noise().compile_detector_sampler(seed=seed).
    """
    raise NotImplementedError("firing_detectors_without_noise: implement this function")


def stim_reported_detectors(circuit: stim.Circuit) -> list[str]:
    """Names like "D1" that Stim's error-model analysis reports as non-deterministic.

    Call circuit.detector_error_model(); if it raises ValueError, return the
    detector names listed in the message after "anti-commuted with these
    detectors/observables:" in order of appearance, without duplicates. Return
    [] if the model builds.
    """
    raise NotImplementedError("stim_reported_detectors: implement this function")


def detector_measurement_qubits(circuit: stim.Circuit, detector: int) -> list[int]:
    """The qubits whose measurement results detector `detector` combines.

    Walk circuit.flattened() keeping a list of measured qubits in record order
    (M, MR, MX, ... each append one entry per target). For the detector-th
    DETECTOR instruction, translate every rec[-k] target into the qubit at
    position len(record) - k. Return them in the order they appear.
    """
    raise NotImplementedError("detector_measurement_qubits: implement this function")


def fixed_memory_circuit() -> stim.Circuit:
    """BUGGY_CIRCUIT with the faulty detector repaired by changing exactly one line."""
    raise NotImplementedError("fixed_memory_circuit: implement this function")

test_exercise.py

Python
import importlib.util
import os
from pathlib import Path

def _load_target():
    name = os.environ.get("KETQAT_COMMONS_TARGET", "starter")
    path = Path(__file__).with_name(f"{name}.py")
    spec = importlib.util.spec_from_file_location(f"{Path(__file__).parent.name}_{name}", path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

target = _load_target()

import pytest
import stim


def reference():
    # What the colleague started from: Stim's generator with the same parameters.
    return stim.Circuit.generated("surface_code:rotated_memory_z", distance=3, rounds=3, after_clifford_depolarization=0.001)


def canonical(circuit):
    model = {}
    for inst in circuit.detector_error_model(decompose_errors=True).flattened():
        if inst.type == "error":
            key = tuple(sorted(str(t) for t in inst.targets_copy() if not t.is_separator()))
            model[key] = model.get(key, 0.0) + inst.args_copy()[0]
    return model


def test_sampling_and_stim_analysis_agree_on_the_culprit():
    buggy = target.buggy_memory_circuit()
    with pytest.raises(ValueError, match="non-deterministic"):
        buggy.detector_error_model()
    fired = target.firing_detectors_without_noise(buggy, shots=512, seed=3)
    reported = target.stim_reported_detectors(buggy)
    assert fired, "noiseless sampling should expose at least one random detector"
    # Two independent methods: Monte Carlo of the noiseless circuit and Stim's
    # stabilizer analysis of the same circuit.
    assert [f"D{i}" for i in fired] == reported


def test_noiseless_reference_never_fires():
    assert target.firing_detectors_without_noise(reference(), shots=512, seed=3) == []
    assert target.stim_reported_detectors(reference()) == []


def test_measurement_qubits_reveal_the_mismatch():
    buggy = target.buggy_memory_circuit()
    coords = buggy.get_final_qubit_coordinates()
    bad = target.firing_detectors_without_noise(buggy, shots=512, seed=3)[0]
    detector_xy = buggy.get_detector_coordinates([bad])[bad][:2]
    qubits = target.detector_measurement_qubits(buggy, bad)
    assert len(qubits) == 1
    assert coords[qubits[0]] != detector_xy  # the detector reads a different measure qubit
    with pytest.raises(IndexError):
        target.detector_measurement_qubits(buggy, buggy.num_detectors)


def test_fixed_circuit_is_a_one_line_repair():
    buggy_lines = str(target.buggy_memory_circuit()).splitlines()
    fixed = target.fixed_memory_circuit()
    fixed_lines = str(fixed).splitlines()
    assert len(fixed_lines) == len(buggy_lines)
    assert sum(a != b for a, b in zip(buggy_lines, fixed_lines)) == 1


def test_fixed_circuit_is_deterministic_and_consistent():
    fixed = target.fixed_memory_circuit()
    assert target.stim_reported_detectors(fixed) == []
    assert target.firing_detectors_without_noise(fixed, shots=512, seed=3) == []
    coords = fixed.get_final_qubit_coordinates()
    det_coords = fixed.get_detector_coordinates()
    for k in range(fixed.num_detectors):
        qubits = set(target.detector_measurement_qubits(fixed, k))
        if len(qubits) == 1:  # a bulk-round detector reads one measure qubit
            assert coords[qubits.pop()] == det_coords[k][:2]


def test_fixed_circuit_has_the_reference_error_model_and_distance():
    fixed = target.fixed_memory_circuit()
    assert fixed.num_detectors == reference().num_detectors
    mine, ref = canonical(fixed), canonical(reference())
    assert set(mine) == set(ref)
    for key in ref:
        assert mine[key] == pytest.approx(ref[key], rel=1e-9)
    assert len(fixed.shortest_graphlike_error()) == 3

Check your understanding

8 questions. Pass with 70% of the points. Answers are checked on the server; retakes are allowed. Explanations appear once you pass or after three complete attempts.

  1. In a ZZ-basis memory experiment of the rotated surface code (data reset to ∣0⟩\ket{0}), which first-round check outcomes may be used as detectors on their own?

    1 pt
  2. How many detectors does a rotated surface-code ZZ-memory with d=7d = 7 and 10 rounds have, using the detector scheme of the lesson (first-round ZZ checks, all checks compared between consecutive rounds, ZZ checks recomputed from the final data readout)?

    1 pt
  3. Under DEPOLARIZE2(0.003) after a CNOT, what is the probability that the specific two-qubit Pauli X⊗ZX \otimes Z is applied?

    1 pt
  4. Why can a bad CNOT order inside weight-4 checks reduce the circuit-level distance?

    1 pt
  5. Generate stim.Circuit.generated("surface_code:rotated_memory_x", distance=7, rounds=7, after_clifford_depolarization=0.001), apply your permute_cx_layers(circuit, (0, 2, 1, 3)) and compute the circuit-level distance with your circuit_distance. What is it?

    2 pts

    Computed by running exercise “stim-memory-circuits” on your computer.

  6. What does circuit.detector_error_model(decompose_errors=True) do with an error mechanism that flips four detectors?

    1 pt
  7. Stim refuses to build a detector error model because of a non-deterministic detector. Select every sound step.

    1 pt

    Select all that apply.

  8. In the debugging exercise, run your firing_detectors_without_noise(buggy_memory_circuit(), shots=512, seed=3). What is the index of the faulty detector?

    1 pt

    Computed by running exercise “debug-detector-definitions” on your computer.

Sign in with GitHub to check answers and save progress. Reading stays free without an account.

References

  1. Craig Gidney (2021). Stim: a fast stabilizer circuit simulator. Quantum 5, 497. doi:10.22331/q-2021-07-06-497
  2. Eric Dennis et al. (2002). Topological quantum memory. Journal of Mathematical Physics 43, 4452-4505. doi:10.1063/1.1499754
  3. Yu Tomita, Krysta M. Svore (2014). Low-distance surface codes under realistic quantum noise. Physical Review A 90, 062320. doi:10.1103/PhysRevA.90.062320
  4. Austin G. Fowler et al. (2012). Surface codes: Towards practical large-scale quantum computation. Physical Review A 86, 032324. doi:10.1103/PhysRevA.86.032324