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 -type check the data qubits control CNOTs onto the ancilla; for an -type check the ancilla is prepared in , controls CNOTs onto the data, and is measured in the basis. In the rotated surface code of the previous lesson, the check on data qubits and the check on are measured like this:
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:
- No qubit in two gates at once. Each layer must be a matching between ancillas and data.
- Commuting checks must still be measured as commuting. An check and a 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 ancilla, or both first by the 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 ancilla above suffers an 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 . Such hook errors are unavoidable for weight-4 checks, but their direction is a choice. In this course's layout, runs down a column. The order makes every hook horizontal (, both on one row), perpendicular to : a horizontal pair advances a vertical logical string by only one row, so it is no worse than a single error. The order would make the hook vertical, parallel to , and then about faults suffice for a logical error. The checks need the opposite orientation, because 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, rounds) | Detectors deterministic? | Circuit-level distance |
|---|---|---|
| generated, ( or memory) | yes | 3 |
| middle layers swapped, | yes | 2 |
| generated, ( or memory) | yes | 5 |
| middle layers swapped, | yes | 3 |
The swapped circuit still measures the right checks (every detector is deterministic) but loses distance to hook errors: instead of . Nothing in a noiseless simulation would reveal this; only the noisy analysis does.
Circuit-level noise, stated precisely
"Depolarizing noise with " is not a noise model until you say where the channels act. Stim's channels are:
DEPOLARIZE1(p): with probability apply one of , each with probability ;DEPOLARIZE2(p): with probability apply one of the 15 non-identity two-qubit Paulis, each with probability ;X_ERROR(p)/Z_ERROR(p): flip with probability .
In this course, uniform circuit-level depolarizing noise with parameter
means the model produced by stim.Circuit.generated(...) with all four of its
noise arguments set to :
| 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 -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 -th most
recent result.
For a memory experiment in the basis (data reset to , logical , final data measurement in ):
- First round. The checks have value on , so each -check outcome is by itself a detector. The checks do not have a definite value on : 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 , each check's value can be recomputed from the data outcomes and compared with its last ancilla outcome. checks cannot be recomputed from -basis data.
- Observable. The product of the data outcomes along a representative, for example one row.
The repetition code has only 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 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 ). For example D0 D1 is an 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
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 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 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 : roughly proportional to at these rates, between 13 and 15 detection events per thousand detectors for every of . Every detector sits in the support of many mechanisms, so it fires far more often than 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 -check detector in a
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:
- Noiseless sampling. Sample
circuit.without_noise(). A correct detector never fires; a non-deterministic one fires in about half of the shots. - 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 check but reads the
neighbouring -check ancilla, whose first-round outcome is random on
. 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
- Memory circuits by hand (
stim-memory-circuits): build the repetition memory for any 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. - 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 "" 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 memory, first-round -check outcomes are random. Only checks get first-round detectors (and vice versa for an memory).
- Off-by-one
recoffsets.rec[-1]is the most recent measurement in the order the targets were listed. AfterMR 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 to .
- 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 .
- 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).