A memory experiment on a distance-7 surface code uses 97 qubits. Simulating it the textbook way, with a state vector, would need complex amplitudes, more memory than exists. Yet sampling and decoding 20,000 shots of it takes about 0.03 seconds on a laptop. The reason is that error-correction circuits use a special gate set. They prepare qubits in or , apply Clifford gates such as , and , measure Pauli operators, and suffer Pauli noise. Such circuits never need amplitudes at all.

This lecture explains why (tableaux and the Gottesman–Knill theorem), how Stim turns that into fast sampling (Pauli frames), and how a circuit tells the simulator what to report (detectors and observables). It then shows the two kinds of circuit object you meet in Deltakit, and the leakage gates that Deltakit’s fork of Stim adds.

Notebook and field map

Notebook 2: Stim and detectors builds small circuits by hand, watches detectors fire in a repetition-code memory experiment, draws its detector slices, and plays with leakage. Field map: Clifford tableaux and Gottesman–Knill, Detectors and observables, Sampling with Stim, The deltakit-stim fork.

Clifford gates and tableaux

Lecture 1 described states by the Pauli operators that fix them. The natural way to evolve such a description is the Heisenberg picture: instead of asking what a gate does to a state, ask what it does to Pauli operators, . If then , so the new state is fixed by the conjugated stabilizers. For this to stay inside the Pauli formalism, must map Paulis to Paulis.

Definition 2.1 (Clifford group).

The -qubit Clifford group is the set of unitaries with for every . It is generated, up to global phase, by , and .

The generators of the Clifford group (Definition 2.1) act as follows ( with control 1 and target 2):

gate
, ,

The row is the most used fact in syndrome extraction: spreads forward from control to target, and spreads backward from target to control. A from a data qubit onto an ancilla copies the data qubit’s errors onto the ancilla, which is how an ancilla measures a -type check (Lecture 3).

Because conjugation respects products, a Clifford is fixed, up to a global phase, by the images of the generators . That list of signed Pauli strings is the Clifford’s tableau. In the binary picture of Lecture 1 it is a symplectic matrix plus sign bits, so it takes bits instead of the entries of a unitary. Composing a one- or two-qubit gate onto a tableau touches bits. Not every useful gate is Clifford: maps to , which is not a Pauli string, and Stim has no gate at all (stim.Circuit("T 0") raises ValueError: Gate not found: 'T').

import deltakit_stim as stim
 
bell = stim.Tableau.from_circuit(stim.Circuit("H 0\nCNOT 0 1"))
print(bell)
print("X0 ->", bell.x_output(0), "  Z0 ->", bell.z_output(0),
      "  X1 ->", bell.x_output(1), "  Z1 ->", bell.z_output(1))
print("1-qubit Cliffords:", len(list(stim.Tableau.iter_all(1))))
+-xz-xz-
| ++ ++
| ZX _Z
| _X XZ
X0 -> +Z_   Z0 -> +XX   X1 -> +_X   Z1 -> +ZZ
1-qubit Cliffords: 24

Read the printed tableau by columns: the column under qubit 0’s z is the image of , read top to bottom as a sign and one letter per qubit, here . Since is fixed by and , the circuit’s output is fixed by their images and : a Bell pair. The last line counts the single-qubit Cliffords up to phase, the 24 rotational symmetries of the octahedron whose vertices are .

Measurement and the Gottesman–Knill theorem

Measuring a Pauli on a stabilizer state with generators has two cases. If anticommutes with some generator, the outcome is uniformly random: pick one anticommuting generator, multiply it into the other anticommuting ones so they commute with , and replace it by according to the outcome. If commutes with every generator, then is in the stabilizer group and the outcome is fixed; finding its sign means writing as a product of generators. Done naively that is Gaussian elimination, . Aaronson and Gottesman store extra destabilizer rows, one partner for each generator, so that the product can be read off in .

Theorem 2.1 (Gottesman–Knill).

A circuit that starts in a computational basis state and uses only Clifford gates, Pauli measurements, random Pauli errors and Clifford gates conditioned on earlier outcomes can be simulated classically in time polynomial in the number of qubits and operations.

The theorem (Theorem 2.1) says nothing about universal quantum computing being easy: add the gate and the tableau no longer closes. It says that error-correction circuits, which are Clifford by design, are cheap to simulate. Stim’s TableauSimulator implements the procedure above. On the three-qubit GHZ state it gives the stabilizers, the expectation values of Pauli strings without measuring, and the collapse after a measurement:

sim = stim.TableauSimulator(seed=7)
sim.do_circuit(stim.Circuit("H 0\nCX 0 1 0 2"))
print("stabilizers:", [str(s) for s in sim.canonical_stabilizers()])
for p in ["ZZI", "YYX", "XII"]:
    print(f"<{p}> =", sim.peek_observable_expectation(stim.PauliString(p)))
print("measure qubit 1:", sim.measure(1))
print("stabilizers:", [str(s) for s in sim.canonical_stabilizers()])
stabilizers: ['+XXX', '+Z_Z', '+_ZZ']
<ZZI> = 1
<YYX> = -1
<XII> = 0
measure qubit 1: True
stabilizers: ['-Z__', '-_Z_', '-__Z']

is a product of stabilizers, so its value is certain. , so its value is certain too, with a minus sign. anticommutes with , so its outcome would be a coin flip, reported as expectation 0. Measuring qubit 1 gave and collapsed the state to . The seed fixes the coin flips, but only “partially”, in the docstring’s word: the same calls with the same seed give the same results on the same machine with the same Stim version, and may differ across versions or SIMD widths.

Why Stim samples fast: Pauli frames

The tableau simulator costs per random measurement (a deterministic one is ), which is fine for one run but slow for a million shots of a circuit with thousands of measurements. Stim’s sampler uses a second idea, from Gidney’s Stim paper: simulate the noiseless circuit once with the tableau simulator to get a reference sample, and then, for each shot, track only how that shot differs from the reference.

Definition 2.2 (Pauli frame).

A shot’s Pauli frame is a Pauli string, stored as an bit and a bit per qubit, such that the shot’s state equals the frame applied to the reference state. A Clifford gate conjugates the frame, a noise channel multiplies a random Pauli into it, and a -basis measurement reports the reference outcome XOR the frame’s bit on that qubit.

The frame (Definition 2.2) update for a gate is a few bit operations: a XORs the control’s bit into the target and the target’s bit into the control, the spreading rule from the table above. Stim stripes the frames of many shots across SIMD words (256 bits in an AVX2 build, as in Gidney’s paper; the released wheels of Stim, and so of the deltakit_stim fork, leave AVX2 off, so words are 128 bits on x86 and 64 bits on an arm64 Mac), one bit per shot, so one XOR instruction updates a whole batch of shots. One wrinkle remains: a measurement whose reference outcome was random must also be random in every shot. When a qubit is reset or measured in the basis, Stim multiplies a into its frame with probability 1/2. That does nothing to the outcome but makes later anticommuting measurements random. Stim calls this stabilizer randomization; the switch disable_stabilizer_randomization on stim.FlipSimulator turns it off.

reference run noiseless, tableau, once reference bits one per measurement Pauli frames many shots per word flip bits per shot frame X bit at each M samples reference XOR flips gates conjugate the frame; noise multiplies in a random Pauli

Detectors and observables

A sampler that reports every measurement leaves the user to work out which combinations matter. Stim lets the circuit say so itself.

Definition 2.3 (Detector and observable).

A detector is a set of measurements whose parity is fixed in the noiseless circuit. Stim declares one with DETECTOR rec[-k] ..., where rec[-1] is the most recent measurement so far, rec[-2] the one before, and so on. A logical observable is a set of measurements whose parity equals the value of a logical operator; OBSERVABLE_INCLUDE(i) rec[-k] ... adds measurements to observable . Samplers report each detector and observable as a flip relative to the noiseless circuit.

In a stabilizer-measurement circuit, the typical detector (Definition 2.3) compares a check’s outcome in one round with the same check in the previous round: without noise the two agree, so their parity is fixed. In the first round, a check whose value is fixed by the initial reset is a detector on its own. At the end, the data qubits are measured directly, and each check is recomputed from them and compared with its last ancilla outcome. Here is the smallest example: one ancilla (qubit 2) measuring twice with MR (measure and reset), and an error on qubit 0 in between, applied with probability 1.

circ = stim.Circuit("""
R 0 1 2
CX 0 2 1 2
MR 2
X_ERROR(1) 0
CX 0 2 1 2
MR 2
DETECTOR rec[-2]
DETECTOR rec[-1] rec[-2]
""")
print(circ.num_measurements, "measurements,", circ.num_detectors, "detectors")
print(circ.compile_detector_sampler(seed=1).sample(3).astype(int).tolist())
 
flipped = stim.Circuit("X 0\nM 0\nDETECTOR rec[-1]")
print(flipped.compile_detector_sampler(seed=1).sample(3).astype(int).tolist())
2 measurements, 2 detectors
[[0, 1], [0, 1], [0, 1]]
[[0], [0], [0]]

The first detector, the first-round outcome, stays quiet; the second, the change between rounds, fires in every shot. The last line shows that detectors are flips: flipped always measures 1, its noiseless parity is 1, and the detector reads 0. A detector that fires is a detection event. Detection events, not raw measurements, are what decoders consume, and Lecture 4 turns them into a detector error model: a list of independent error mechanisms and the detectors and observables each one flips.

In Deltakit

Deltakit has its own circuit class, deltakit.circuit.Circuit: Python objects for gate layers, noise layers, detectors and observables, which the QPU class compiles to a native gate set and decorates with noise. Simulation always happens in Stim, so every Deltakit circuit converts to a deltakit_stim.Circuit with .as_stim_circuit(), and back with Circuit.from_stim_circuit. The conversion adds a TICK between gate layers.

from deltakit.circuit import Circuit, Detector, GateLayer, MeasurementRecord
from deltakit.circuit.gates import CX, MZ, RZ
 
dk = Circuit([
    GateLayer([RZ(0), RZ(1), RZ(2)]),
    GateLayer([CX(0, 2)]),
    GateLayer([CX(1, 2)]),
    GateLayer([MZ(2)]),
    Detector([MeasurementRecord(-1)]),
])
sc = dk.as_stim_circuit()
print(type(dk).__module__, "->", type(sc).__module__)
print(sc)
print("round trip:", Circuit.from_stim_circuit(sc) == dk)
deltakit_circuit._circuit -> deltakit_stim._stim_polyfill
R 0 1 2
TICK
CX 0 2
TICK
CX 1 2
TICK
M 2
DETECTOR rec[-1]
round trip: True

The first line is from a Mac (arm64 or Intel); on Linux x86 it reads deltakit_stim._stim_sse2. The round trip is exact here because each layer holds one gate type; a layer that mixes gate types comes back split into several, so compare DEMs rather than circuits.

You rarely build circuits by hand. css_code_memory_circuit writes the memory experiment of Lecture 0 for any CSS code, detectors and observable included. For a distance-3 repetition code and two rounds, five qubits produce seven measurements: two ancilla outcomes per round, then the three data qubits.

from deltakit.circuit.gates import PauliBasis
from deltakit.explorer.codes import RepetitionCode, css_code_memory_circuit
 
rep = RepetitionCode(distance=3)
mem = css_code_memory_circuit(rep, num_rounds=2, logical_basis=PauliBasis.Z)
smem = mem.as_stim_circuit()
print(smem.num_qubits, "qubits,", smem.num_measurements, "measurements,",
      smem.num_detectors, "detectors,", smem.num_observables, "observable")
for line in str(smem).splitlines():
    if line.startswith(("DETECTOR", "OBSERVABLE")):
        print(line)
5 qubits, 7 measurements, 6 detectors, 1 observable
DETECTOR(1, 0, 0) rec[-2]
DETECTOR(3, 0, 0) rec[-1]
DETECTOR(1, 0, 0) rec[-7] rec[-5]
DETECTOR(3, 0, 0) rec[-6] rec[-4]
OBSERVABLE_INCLUDE(0) rec[-1]
DETECTOR(1, 0, 0) rec[-5] rec[-1] rec[-2]
DETECTOR(3, 0, 0) rec[-4] rec[-3] rec[-2]

The relative indices are hard to read, because rec[-1] means a different measurement on each line. The figure translates them into absolute measurement numbers . The arguments of DETECTOR(x, y, t) are coordinates: the ancilla’s position and a time that SHIFT_COORDS lines (not printed) advance by one each round.

qubit x 0 1 2 3 4 round 0 round 1 data M D0 D1 D2 D3 D4 D5 L0 m0 m1 m2 m3 m6 m5 m4 D0 = m0 D1 = m1 D2 = m0 + m2 D3 = m1 + m3 D4 = m2 + m5 + m6 D5 = m3 + m4 + m5 L0 = m6 + is XOR rec[-1] = m6, rec[-7] = m0

Two details in the figure are worth checking against the printout. The data qubits are measured in the order , so , the last measurement, is the data qubit at , and the observable on that qubit is just rec[-1] (Lecture 1 found the same weight-one for the repetition code). And the final detectors are three-body: the check recomputed from the data, , compared with its last ancilla outcome .

To sample, compile the noisy circuit to a detector sampler. With separate_observables=True it returns two boolean arrays, detection events and observable flips, one row per shot; with bit_packed=True it packs eight columns into each byte.

from deltakit.explorer.qpu import QPU, SI1000Noise
 
SEED = 2026
qpu = QPU(qubits=rep.qubits, noise_model=SI1000Noise(p=1e-2))
noisy = qpu.compile_and_add_noise_to_circuit(mem).as_stim_circuit()
dets, obs = noisy.compile_detector_sampler(seed=SEED).sample(
    5, separate_observables=True)
print("dets", dets.shape, dets.dtype, "  obs", obs.shape, obs.dtype)
print(dets.astype(int))
packed = noisy.compile_detector_sampler(seed=SEED).sample(5, bit_packed=True)
print("bit_packed", packed.shape, packed.dtype)
dets (5, 6) bool   obs (5, 1) bool
[[0 0 0 0 0 0]
 [0 0 0 0 0 0]
 [0 1 0 1 0 0]
 [0 0 0 1 0 1]
 [0 0 0 0 0 0]]
bit_packed (5, 1) uint8

A single wrong measurement outcome fires exactly the detectors that contain it. The third shot (row 2) fires and , the two detectors that contain ; the fourth (row 3) fires and , the two that contain . Each is explained by one wrong outcome of the right-hand ancilla. A data error instead fires neighbouring checks in the same round (Notebook 2 shows both).

The leakage gates. deltakit_stim is a fork of Stim that adds instructions for leakage, a qubit escaping to a state outside . LEAKAGE(p) leaks a qubit with probability , HERALD_LEAKAGE_EVENT records a measurement bit that is 1 if the qubit is leaked, and RELAX(p) and RL return leaked qubits to the computational subspace. The semantics below were measured with the sampler:

circuits = [
    "R 0\nLEAKAGE(1) 0\nHERALD_LEAKAGE_EVENT 0\nM 0",
    "R 0\nLEAKAGE(0.3) 0\nHERALD_LEAKAGE_EVENT 0\nM 0",
    "R 0 1\nLEAKAGE(1) 0\nCX 0 1\nHERALD_LEAKAGE_EVENT 0 1\nM 0 1",
    "R 0\nLEAKAGE(1) 0\nRL 0\nHERALD_LEAKAGE_EVENT 0\nM 0",
]
for text in circuits:
    bits = stim.Circuit(text).compile_sampler(seed=SEED).sample(10_000)
    print(bits.mean(axis=0).round(3).tolist())
[1.0, 0.5]
[0.295, 0.152]
[1.0, 0.0, 0.498, 0.5]
[0.0, 0.5]

A leaked qubit heralds 1 and measures at random. A from a leaked control randomizes its partner without leaking it (third line: heralds 1 and 0, both measurements random). RL clears the leakage flag but does not reset the qubit, so its measurement stays random.

Remark 2.1 (Where leakage is not modelled).

Only the samplers simulate leakage. detector_error_model() drops LEAKAGE silently, and the TableauSimulator ignores it. Treat a detector error model of a leaky circuit as a Pauli approximation and check it against sampled data. With a HERALD_LEAKAGE_EVENT inside a detector, the model instead gains conditional rows that only a herald-aware decoder can use.

leaky = stim.Circuit("R 0\nLEAKAGE(0.1) 0\nM 0\nDETECTOR rec[-1]")
print(repr(str(leaky.detector_error_model())))
events = leaky.compile_detector_sampler(seed=SEED).sample(100_000)
print("sampled:", events.mean())
tab = stim.TableauSimulator(seed=SEED)
tab.do_circuit(stim.Circuit("R 0\nLEAKAGE(1) 0\nHERALD_LEAKAGE_EVENT 0"))
print("tableau herald:", tab.current_measurement_record())
'detector D0'
sampled: 0.05038
tableau herald: [False]

The model lists the detector but no error, while the sampler fires it in about 5% of shots (half of the 10% that leak), as Remark 2.1 warns. SI1000Noise(p=..., pL=...) adds LEAKAGE and RELAX to compiled circuits when pL is not zero.

The PyMatching trap. A fork is a separate package, and libraries that check types against upstream stim reject its objects. PyMatching is the one you will meet: its constructor from a detector error model raises a TypeError (`model` must be a `stim.DetectorErrorModel`) when handed a deltakit_stim model.

import pymatching
 
pymatching.Matching.from_detector_error_model(noisy.detector_error_model())

Use Deltakit’s PyMatchingDecoder, as in Lecture 0, or pass the model through a file:

import pathlib
import tempfile
 
import pymatching
 
dem = noisy.detector_error_model(decompose_errors=True)
with tempfile.TemporaryDirectory() as tmp:
    path = pathlib.Path(tmp) / "rep.dem"
    dem.to_file(str(path))
    matching = pymatching.Matching.from_detector_error_model_file(str(path))
print(matching)
dets, obs = noisy.compile_detector_sampler(seed=SEED).sample(
    20_000, separate_observables=True)
pred = matching.decode_batch(dets)
print("predictions", pred.shape, pred.dtype,
      "| failures:", int((pred[:, 0] != obs[:, 0]).sum()), "of 20000")
<pymatching.Matching object with 6 detectors, 0 boundary nodes, and 15 edges>
predictions (20000, 1) uint8 | failures: 563 of 20000

At the distance-3 repetition code fails in 563 of 20,000 shots (2.8%), the same count that PyMatchingDecoder gives when you sample the circuit it returns with the same seed.

Try this

  • In the two-round detector example, move X_ERROR(1) 0 before the first CX layer. Which detectors fire now, and why does fire but not?
  • Replace X_ERROR(1) 0 by X_ERROR(1) 2 placed just before the first MR 2, a lying measurement. Check that the two detectors that fire are consecutive in time.
  • Use stim.Tableau.iter_all(2) to count the two-qubit Cliffords, with and without unsigned=True, and explain the ratio.
  • Build the repetition-code memory with num_rounds=3 and predict num_detectors and the DETECTOR lines before printing them.

Readings