About this notebook

Companion to Lecture 2: Clifford simulation and Stim. Every cell below was executed headless with the course’s pinned Deltakit (deltakit 0.10.2, deltakit-stim 0.2.7, pymatching 2.4.0, Python 3.12.12); each output is exactly what the code printed. Download the notebook (.ipynb)

Lecture 2 explained why Clifford circuits are cheap to simulate and how a circuit declares detectors: parities of measurements that are fixed when there is no noise. This notebook makes both concrete. You will:

  1. write a small circuit in Stim’s text format and sample it;
  2. check the propagation rules with a tableau, and watch a parity measurement leave a Bell pair alone;
  3. inject single errors into a repetition-code memory experiment and see which detectors fire;
  4. read the shapes and bit order of the sampler’s output;
  5. draw detection events in space and time, and the circuit’s detector slices;
  6. see what the leakage gates of deltakit_stim do, and what the detector error model misses.

Everything runs locally in a few seconds, and every sampled number comes from a seeded sampler.

import deltakit
import deltakit_stim as stim
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import SVG
from matplotlib_inline.backend_inline import set_matplotlib_formats
 
from deltakit.circuit.gates import PauliBasis
from deltakit.explorer.codes import RepetitionCode, css_code_memory_circuit
from deltakit.explorer.qpu import QPU, SI1000Noise
 
set_matplotlib_formats("svg")
SEED = 2026
print("deltakit", deltakit.__version__)
deltakit 0.10.2

1. A circuit by hand

Stim’s text format has one instruction per line: a gate name, optional arguments in parentheses, then qubit indices. H 0 is a Hadamard on qubit 0, CX 0 1 a with control 0 and target 1, and M 0 1 measures both qubits in the basis. Note the import: in this course Stim is always deltakit_stim, Deltakit’s fork, never upstream stim.

bell = stim.Circuit("""
H 0
CX 0 1
M 0 1
""")
samples = bell.compile_sampler(seed=SEED).sample(10_000)
print("shape", samples.shape, samples.dtype)
print("P(m0 = 1)    =", samples[:, 0].mean())
print("P(m0 != m1)  =", (samples[:, 0] != samples[:, 1]).mean())
shape (10000, 2) bool
P(m0 = 1)    = 0.4978
P(m0 != m1)  = 0.0

Each outcome is a fair coin, but the two always agree: the Bell state is stabilized by . It is also stabilized by , and has value . Measuring in the other bases (MX, MY) shows all three correlations.

for basis in ["M", "MX", "MY"]:
    c = stim.Circuit(f"H 0\nCX 0 1\n{basis} 0 1")
    s = c.compile_sampler(seed=SEED).sample(10_000)
    print(f"{basis:3s} P(outcomes differ) = {(s[:, 0] != s[:, 1]).mean()}")
M   P(outcomes differ) = 0.0
MX  P(outcomes differ) = 0.0
MY  P(outcomes differ) = 1.0

2. Tableaux: the rules, and a measurement that does not disturb

A stim.Tableau stores where a Clifford gate sends each Pauli generator. Calling it on a PauliString conjugates the string. Here is the table from Lecture 2, plus two products: spreads forward from control to target, spreads backward, and products follow, signs included.

cx = stim.Tableau.from_named_gate("CX")
for p in ["X_", "_X", "Z_", "_Z", "Y_", "XZ"]:
    print(f"{p} -> {cx(stim.PauliString(p))}")
X_ -> +XX
_X -> +_X
Z_ -> +Z_
_Z -> +ZZ
Y_ -> +YX
XZ -> -YY

Lecture 1 claimed that measuring a stabilizer does not disturb an encoded state. Check it with the tableau simulator: make a Bell pair on qubits 0 and 1, then use ancilla 2 to measure (two s copy the parity onto the ancilla). The pair’s stabilizers survive, and the ancilla reads 0. After an error on qubit 0, the same measurement reads 1 and the pair’s stabilizer has flipped sign: the error is detected, and the state is still a Bell state, just a different one.

sim = stim.TableauSimulator(seed=SEED)
sim.do_circuit(stim.Circuit("H 0\nCX 0 1"))
print("Bell pair:        ", [str(s) for s in sim.canonical_stabilizers()])
sim.do_circuit(stim.Circuit("CX 0 2 1 2\nM 2"))
print("after measuring:  ", [str(s) for s in sim.canonical_stabilizers()])
sim.do_circuit(stim.Circuit("R 2\nX 0\nCX 0 2 1 2\nM 2"))
print("after X_0 and M:  ", [str(s) for s in sim.canonical_stabilizers()])
print("ancilla outcomes: ", sim.current_measurement_record())
Bell pair:         ['+XX', '+ZZ']
after measuring:   ['+XX_', '+ZZ_', '+__Z']
after X_0 and M:   ['+XX_', '-ZZ_', '-__Z']
ancilla outcomes:  [False, True]

3. Detectors in a repetition-code memory experiment

Now let Deltakit write the circuit. css_code_memory_circuit turns any CSS code into a memory experiment: reset, num_rounds rounds of check measurements, a final measurement of every data qubit, and the detectors and logical observable. We use the distance-3 repetition code, which protects against errors with two checks, and two rounds.

rep = RepetitionCode(distance=3)
mem = css_code_memory_circuit(rep, num_rounds=2, logical_basis=PauliBasis.Z)
circ = mem.as_stim_circuit()
print(type(mem).__name__, "from", type(mem).__module__, "->",
      type(circ).__name__, "from", type(circ).__module__)
print(circ.num_qubits, "qubits,", circ.num_measurements, "measurements,",
      circ.num_detectors, "detectors,", circ.num_observables, "observable")
print("qubit index -> (x, y):", circ.get_final_qubit_coordinates())
Circuit from deltakit_circuit._circuit -> Circuit from deltakit_stim._stim_polyfill
5 qubits, 7 measurements, 6 detectors, 1 observable
qubit index -> (x, y): {0: [4.0, 0.0], 1: [0.0, 0.0], 2: [1.0, 0.0], 3: [2.0, 0.0], 4: [3.0, 0.0]}

Stim numbers qubits 0 to 4; the coordinates say where each one sits. Qubits 1, 3 and 0 are the data qubits at , and qubits 2 and 4 are the ancillas at . The full circuit is short enough to read:

print(circ)
QUBIT_COORDS(4, 0) 0
QUBIT_COORDS(0, 0) 1
QUBIT_COORDS(1, 0) 2
QUBIT_COORDS(2, 0) 3
QUBIT_COORDS(3, 0) 4
R 3 0 1
RX 2 4
TICK
I 1 3 0
TICK
CZ 2 1 4 3
TICK
CZ 2 3 4 0
TICK
MX 2 4
TICK
DETECTOR(1, 0, 0) rec[-2]
DETECTOR(3, 0, 0) rec[-1]
SHIFT_COORDS(0, 0, 1)
RX 2 4
I 1 3 0
TICK
CZ 2 1 4 3
TICK
CZ 2 3 4 0
TICK
MX 2 4
M 0 3 1
DETECTOR(1, 0, 0) rec[-7] rec[-5]
DETECTOR(3, 0, 0) rec[-6] rec[-4]
SHIFT_COORDS(0, 0, 1)
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]
SHIFT_COORDS(0, 0, 1)

Deltakit measures each check with an ancilla prepared in (RX), two controlled- gates and an -basis measurement (MX), which is equivalent to the version of Lecture 2. The I lines are idle data qubits, where a noise model can attach idling errors. Counting the measurements in order gives the layout below ( are the absolute measurement indices; the lecture’s figure draws the same thing).

 qubit x:       0      1      2      3      4
               data   anc    data   anc    data
 round 0               m0            m1                D0 = m0          D1 = m1
 round 1               m2            m3                D2 = m0 + m2     D3 = m1 + m3
 final M        m6            m5            m4         D4 = m2 + m5 + m6
                                                       D5 = m3 + m4 + m5
 observable L0 = m6  (Z on the data qubit at x = 0)

Without noise, no detector fires:

print(circ.compile_detector_sampler(seed=SEED).sample(3).astype(int))
[[0 0 0 0 0 0]
 [0 0 0 0 0 0]
 [0 0 0 0 0 0]]

To see what each detector is for, insert one deterministic error into the Stim text and sample once. The helper puts an error line just before the nth line that starts with a given instruction. X_ERROR(1) q flips data qubit q; Z_ERROR(1) 2 just before an MX flips that ancilla’s outcome, which is how a measurement error looks.

def with_error(circuit, before, error, nth=0):
    """Insert the line `error` before the nth line that starts with `before`."""
    lines = str(circuit).splitlines()
    hits = [i for i, line in enumerate(lines) if line.startswith(before)]
    lines.insert(hits[nth], error)
    return stim.Circuit("\n".join(lines))
 
 
cases = {
    "X on data x=2, between rounds": ("RX 2 4", "X_ERROR(1) 3", 1),
    "X on data x=4, between rounds": ("RX 2 4", "X_ERROR(1) 0", 1),
    "wrong outcome of ancilla x=1, round 0": ("MX 2 4", "Z_ERROR(1) 2", 0),
    "X on data x=0, before final M": ("M 0 3 1", "X_ERROR(1) 1", 0),
}
for name, (before, error, nth) in cases.items():
    c = with_error(circ, before, error, nth)
    dets, obs = c.compile_detector_sampler(seed=SEED).sample(
        1, separate_observables=True)
    fired = [f"D{k}" for k in np.flatnonzero(dets[0])]
    print(f"{name:38s} fires {fired}, observable flipped: {bool(obs[0, 0])}")
X on data x=2, between rounds          fires ['D2', 'D3'], observable flipped: False
X on data x=4, between rounds          fires ['D3'], observable flipped: False
wrong outcome of ancilla x=1, round 0  fires ['D0', 'D2'], observable flipped: False
X on data x=0, before final M          fires ['D4'], observable flipped: True

Four patterns, and they are the whole vocabulary of matching decoders (Lecture 5):

  • A data error in the bulk fires the two checks on either side of it, in the same round: a space-like pair (, ).
  • A data error at the boundary has only one neighbouring check, so it fires a single detector (). The decoder must allow a chain to end at the boundary.
  • A measurement error fires the same check in two consecutive rounds: a time-like pair (, ). The data are fine, and nothing should be corrected.
  • An error on the observable’s qubit flips the observable and fires only . The other cheap explanation of alone is a pair of errors on and , which does not flip . A decoder has to weigh one error against two (Lecture 5).

Why both rounds are needed

With a single snapshot of the checks (one round and no final data readout), the measurement error and a data error on would both fire only the first-round detector and look identical. Repeating the measurement turns “which checks are unhappy” into “where and when did something change”.

4. What the sampler returns

Real noise comes from a noise model. QPU compiles the circuit to a native gate set and adds the SI1000 model (Lecture 4) at strength . A detector sampler then returns detection events, optionally with the observable flips in a separate array.

qpu = QPU(qubits=rep.qubits, noise_model=SI1000Noise(p=1e-2))
noisy = qpu.compile_and_add_noise_to_circuit(mem).as_stim_circuit()
sampler = noisy.compile_detector_sampler(seed=SEED)
dets, obs = sampler.sample(1000, separate_observables=True)
print("separate_observables=True:", dets.shape, dets.dtype, obs.shape, obs.dtype)
both = noisy.compile_detector_sampler(seed=SEED).sample(1000, append_observables=True)
print("append_observables=True: ", both.shape, "| same bits:",
      np.array_equal(both, np.hstack([dets, obs])))
packed = noisy.compile_detector_sampler(seed=SEED).sample(1000, bit_packed=True)
print("bit_packed=True:          ", packed.shape, packed.dtype)
separate_observables=True: (1000, 6) bool (1000, 1) bool
append_observables=True:  (1000, 7) | same bits: True
bit_packed=True:           (1000, 1) uint8

Bit packing stores eight detectors per byte, with the first detector in the lowest bit. Unpack with bitorder="little", then drop the padding columns:

unpacked = np.unpackbits(packed, axis=1, bitorder="little")[:, :noisy.num_detectors]
print("little-endian unpack matches:", np.array_equal(unpacked.astype(bool), dets))
big = np.unpackbits(packed, axis=1)[:, :noisy.num_detectors]
print("default (big-endian) unpack matches:", np.array_equal(big.astype(bool), dets))
little-endian unpack matches: True
default (big-endian) unpack matches: False

Re-seed for each comparison

Each call to sample advances the sampler’s random stream. The three arrays above match because each came from a fresh sampler compiled with the same seed. Two calls on one sampler give different shots.

5. Detection events in space and time

A larger code makes the picture clearer. Take the distance-7 repetition code (seven data qubits, six ancillas) for seven rounds at . The detector coordinates give each detector a place: is its ancilla’s position and the round, with for the final detectors recomputed from the data.

rep7 = RepetitionCode(distance=7)
mem7 = css_code_memory_circuit(rep7, num_rounds=7, logical_basis=PauliBasis.Z)
qpu7 = QPU(qubits=rep7.qubits, noise_model=SI1000Noise(p=5e-3))
noisy7 = qpu7.compile_and_add_noise_to_circuit(mem7).as_stim_circuit()
coords = noisy7.get_detector_coordinates()
xy_t = np.array([(coords[k][0], coords[k][2]) for k in range(noisy7.num_detectors)])
print(noisy7.num_qubits, "qubits,", noisy7.num_detectors, "detectors")
print("x positions:", sorted({int(x) for x, _ in xy_t}),
      " layers t:", sorted({int(t) for _, t in xy_t}))
dets7, obs7 = noisy7.compile_detector_sampler(seed=SEED).sample(
    100_000, separate_observables=True)
print("mean detection events per shot:", round(dets7.sum(axis=1).mean(), 2))
print("events in the first four shots:", dets7[:4].sum(axis=1).tolist())
13 qubits, 48 detectors
x positions: [1, 3, 5, 7, 9, 11]  layers t: [0, 1, 2, 3, 4, 5, 6, 7]
mean detection events per shot: 4.59
events in the first four shots: [6, 7, 6, 2]
fig, axes = plt.subplots(1, 4, figsize=(6.4, 3.4), sharey=True)
for k, ax in enumerate(axes):
    ax.scatter(xy_t[:, 0], xy_t[:, 1], s=22, facecolors="none",
               edgecolors="#b5aea4", linewidths=0.8)
    hit = dets7[k]
    ax.scatter(xy_t[hit, 0], xy_t[hit, 1], s=34, color="C1", zorder=3)
    ax.set_title(f"shot {k}: {int(hit.sum())} events")
    ax.set_xticks([1, 3, 5, 7, 9, 11])
    ax.set_xlim(0, 12)
    ax.set_ylim(-0.7, 7.7)
    ax.set_xlabel("ancilla x")
    ax.grid(False)
axes[0].set_ylabel("detector layer t (round)")
axes[0].set_yticks(range(8))
plt.show()
Detection events (filled) among all 48 detectors (open circles) of a distance-7 repetition-code memory experiment, seven rounds, SI1000 noise at p = 5×10⁻³, for the first four shots. Horizontal: the ancilla's position x; vertical: the detector layer t, where t = 7 compares the last round with the final data measurement. Pairs close in space or time are the signatures of single errors.

Detection events (filled) among all 48 detectors (open circles) of a distance-7 repetition-code memory experiment, seven rounds, SI1000 noise at p = 5×10⁻³, for the first four shots. Horizontal: the ancilla's position x; vertical: the detector layer t, where t = 7 compares the last round with the final data measurement. Pairs close in space or time are the signatures of single errors.

Averaged over many shots, every detector in the bulk fires at about the same rate. The first and last layers are different: the first compares against a reset with a known outcome, so only errors from one round feed it, and the last compares the final ancilla outcome with data measurements, a different mix of error sources.

rate = dets7.mean(axis=0)
layers = sorted({int(t) for _, t in xy_t})
by_layer = [rate[xy_t[:, 1] == t].mean() for t in layers]
for t, r in zip(layers, by_layer):
    print(f"layer {t}: detection rate {r:.4f}")
print("raw observable flip rate (no decoding):", obs7.mean())
layer 0: detection rate 0.0598
layer 1: detection rate 0.1029
layer 2: detection rate 0.1031
layer 3: detection rate 0.1036
layer 4: detection rate 0.1033
layer 5: detection rate 0.1032
layer 6: detection rate 0.1035
layer 7: detection rate 0.0864
raw observable flip rate (no decoding): 0.1251
fig, ax = plt.subplots(figsize=(6.4, 3.0))
ax.bar(layers, by_layer, color="C0", width=0.6)
ax.set_xticks(layers)
ax.set_xlabel("detector layer t (round)")
ax.set_ylabel("detection rate per detector")
plt.show()
Mean detection-event rate per detector in each layer, 100,000 shots of the same experiment. The bulk layers t = 1 to 6 sit at one value; the time boundaries t = 0 (first round, compared with a known reset) and t = 7 (compared with the final data measurement) are lower.

Mean detection-event rate per detector in each layer, 100,000 shots of the same experiment. The bulk layers t = 1 to 6 sit at one value; the time boundaries t = 0 (first round, compared with a known reset) and t = 7 (compared with the final data measurement) are lower.

6. Drawing the circuit: detector slices

Stim can draw a circuit in several ways (circuit.diagram(kind)). The most useful for QEC is "detslice-svg": one panel per TICK, showing for every detector the Pauli product it tracks at that moment. An error that anticommutes with that product flips the detector. Draw it from the noiseless circuit; noisy circuits make huge diagrams. Here is the distance-3, two-round experiment of section 3.

SVG(str(circ.diagram("detslice-svg")))
Detector slices of the noiseless distance-3, two-round repetition-code memory circuit, drawn by Stim, one panel per TICK. Dots are the five qubits on the line y = 0. Red marks X, blue marks Z; the blended shapes are products with X on an ancilla and Z on a data qubit, created by the CZ gates.

Detector slices of the noiseless distance-3, two-round repetition-code memory circuit, drawn by Stim, one panel per TICK. Dots are the five qubits on the line y = 0. Red marks X, blue marks Z; the blended shapes are products with X on an ancilla and Z on a data qubit, created by the CZ gates.

Read it against the circuit text above. Just before each MX, a detector’s product is on its ancilla (a red disc). Earlier, the gates have spread it onto the neighbouring data qubits as , so a data-qubit error in that window flips the detector. Between the two rounds, the comparison detectors and track the checks themselves, on a pair of data qubits (the two all-blue shapes): an error on either data qubit at that moment flips them.

7. Leakage in deltakit_stim

Leakage is a qubit leaving the two-level subspace, for example a superconducting qubit excited to . Deltakit’s fork of Stim adds instructions for it. The table measures their behaviour with the ordinary measurement sampler: each row is a circuit, each column the fraction of 10,000 shots in which a measurement read 1.

leak_circuits = {
    "LEAKAGE(1), herald, M": "R 0\nLEAKAGE(1) 0\nHERALD_LEAKAGE_EVENT 0\nM 0",
    "LEAKAGE(0.3), herald, M": "R 0\nLEAKAGE(0.3) 0\nHERALD_LEAKAGE_EVENT 0\nM 0",
    "leak 0, CX 0 1, herald 0 1, M 0 1":
        "R 0 1\nLEAKAGE(1) 0\nCX 0 1\nHERALD_LEAKAGE_EVENT 0 1\nM 0 1",
    "leak, R, herald, M": "R 0\nLEAKAGE(1) 0\nR 0\nHERALD_LEAKAGE_EVENT 0\nM 0",
    "leak, RELAX(1), herald, M":
        "R 0\nLEAKAGE(1) 0\nRELAX(1) 0\nHERALD_LEAKAGE_EVENT 0\nM 0",
    "leak, RL, herald, M": "R 0\nLEAKAGE(1) 0\nRL 0\nHERALD_LEAKAGE_EVENT 0\nM 0",
}
for name, text in leak_circuits.items():
    bits = stim.Circuit(text).compile_sampler(seed=SEED).sample(10_000)
    print(f"{name:36s}", bits.mean(axis=0).round(3).tolist())
LEAKAGE(1), herald, M                [1.0, 0.5]
LEAKAGE(0.3), herald, M              [0.295, 0.152]
leak 0, CX 0 1, herald 0 1, M 0 1    [1.0, 0.0, 0.498, 0.5]
leak, R, herald, M                   [0.0, 0.0]
leak, RELAX(1), herald, M            [0.0, 0.5]
leak, RL, herald, M                  [0.0, 0.5]

Reading the rows: a leaked qubit heralds 1 and its measurement is a coin flip. Leakage does not spread through a , but it randomizes the partner. A reset (R) undoes it completely. RELAX(p) and RL clear the leakage flag but leave the qubit in a random computational state.

The sampler simulates all of this. The detector error model does not: it keeps only Pauli noise. With Deltakit’s SI1000 model, pL switches leakage on. Compare the detection-event rate of the real circuit with the rate predicted by sampling its own detector error model:

mem3 = css_code_memory_circuit(rep, num_rounds=3, logical_basis=PauliBasis.Z)
for pL in [0.0, 1e-2]:
    q = QPU(qubits=rep.qubits, noise_model=SI1000Noise(p=1e-3, pL=pL))
    nc = q.compile_and_add_noise_to_circuit(mem3).as_stim_circuit()
    leak_gates = sorted({op.name for op in nc.flattened()}
                        & {"LEAKAGE", "RELAX", "HERALD_LEAKAGE_EVENT"})
    dem = nc.detector_error_model()
    circuit_rate = nc.compile_detector_sampler(seed=SEED).sample(200_000).mean()
    dem_dets, _, _ = dem.compile_sampler(seed=SEED).sample(200_000)
    print(f"pL = {pL:<5}  leakage gates {leak_gates}, DEM has {dem.num_errors} "
          f"errors; detection rate: circuit {circuit_rate:.4f}, "
          f"DEM {dem_dets.mean():.4f}")
pL = 0.0    leakage gates [], DEM has 21 errors; detection rate: circuit 0.0185, DEM 0.0187
pL = 0.01   leakage gates ['LEAKAGE', 'RELAX'], DEM has 21 errors; detection rate: circuit 0.0744, DEM 0.0187

Without leakage the two rates agree to within 0.0002, about the sampling error. With the circuit’s detection rate is four times higher, while the detector error model is unchanged, error for error: detector_error_model() drops LEAKAGE and RELAX silently. A decoder built from that model has never heard of leakage. Handling leakage in decoding is an open topic; Lecture 4 says more about noise models.

Two more places where leakage is invisible

stim.TableauSimulator ignores LEAKAGE (a HERALD_LEAKAGE_EVENT after LEAKAGE(1) reads 0). Only the samplers, compile_sampler and compile_detector_sampler, model it.

Try this

  1. In section 3, add X_ERROR(1) on two data qubits between rounds. Which detectors fire for neighbouring qubits, and which for qubits and ?
  2. Rerun section 5 at and . How does the bulk detection rate scale with ?
  3. Draw circ.diagram("timeline-svg") for the same small circuit and match each MX box to in the layout above.
  4. In section 7, raise pL to and and plot the circuit’s detection rate against the DEM’s.