A memory experiment on a distance-7 surface code uses 97 qubits. Simulating it the textbook
way, with a state vector, would need
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
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 (
| gate | ||
|---|---|---|
The
Because conjugation respects products, a Clifford is fixed, up to a global phase, by the
images of the 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: 24Read the printed tableau by columns: the column under qubit 0’s z is the image of
Measurement and the Gottesman–Knill theorem
Measuring a Pauli
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 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']Why Stim samples fast: Pauli frames
The tableau simulator costs
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 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 disable_stabilizer_randomization on stim.FlipSimulator turns it off.
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] ..., whererec[-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 MR (measure and reset), and an
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: TrueThe 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 DETECTOR(x, y, t) are coordinates: the ancilla’s position and a time that
SHIFT_COORDS lines (not printed) advance by one each round.
Two details in the figure are worth checking against the printout. The data qubits are measured
in the order rec[-1] (Lecture 1 found the same
weight-one
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) uint8A single wrong measurement outcome fires exactly the detectors that contain it. The third shot
(row 2) fires
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 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()dropsLEAKAGEsilently, and theTableauSimulatorignores it. Treat a detector error model of a leaky circuit as a Pauli approximation and check it against sampled data. With aHERALD_LEAKAGE_EVENTinside 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 20000At 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) 0before the firstCXlayer. Which detectors fire now, and why doesfire but not? - Replace
X_ERROR(1) 0byX_ERROR(1) 2placed just before the firstMR 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 withoutunsigned=True, and explain the ratio. - Build the repetition-code memory with
num_rounds=3and predictnum_detectorsand theDETECTORlines before printing them.
Readings
- C. Gidney, Stim: a fast stabilizer circuit simulator, Quantum 5, 497 (2021), arXiv 2103.02202. Pauli frames and the reference sample.
- S. Aaronson and D. Gottesman, Improved simulation of stabilizer circuits, Phys. Rev. A 70, 052328 (2004), arXiv quant-ph/0406196. Tableaux with destabilizers.
- D. Gottesman, The Heisenberg representation of quantum computers, arXiv quant-ph/9807006 (1998). The Gottesman–Knill theorem.
- The Stim documentation on GitHub, especially the gate
reference and the getting-started notebook; and the
Deltakit documentation for
deltakit.circuit.