Every concept of the primer on one page, with the Deltakit call that implements it. Click a card for its chapter.
38 cards
Read the map by territory: Foundations (what a code is), Simulation (how noisy
circuits become detector error models), Decoding (turning syndromes into corrections),
Performance (what the numbers mean) and Toolchain (how Deltakit’s packages fit together).
Each card’s chapter has an In Deltakit section with the exact import and a snippet that
runs. Filter by territory, or search for a call name such as StimDecoderManager.
M1 Stabilizer foundations
A code is an abelian Pauli group; an error shows up as the set of generators it anticommutes with.
The Pauli group and commutation
Pauli strings either commute or anticommute. In bits, and anticommute exactly when is odd, which counts the sites where both are non-identity and different. Overlap alone decides nothing.
details ›
QP = XXYZ and Q = ZYXX act on the same four qubits with a different letter on every one. Do they commute?
AYes. All four sites clash, and four is even, so the four sign flips cancel and . Overlap decides nothing; only the parity of the clash count does.
Stabilizer groups and the code space
dimension of the code space3216842each independentgenerator halves itredundant: the product of the four
A stabilizer group is an abelian subgroup of that does not contain . With independent generators, its code space has dimension and projector . Count independent generators, not rows.
details ›
QXX, ZZ and YY commute pairwise. What is the code space of the group they generate on two qubits?
AEmpty. , so , and no state is fixed by . The projector has trace 0. With instead of the group is fine, and it fixes one state, .
Syndromes and logical operators
weight 2weight 2weight 3
Syndrome bit is 1 when error anticommutes with generator . Zero-syndrome Paulis are stabilizers (harmless) or logicals, . Errors with one syndrome form cosets: decode the coset.
details ›
QA decoder sees the syndrome above and applies a correction . Has it failed?
ANot necessarily. has zero syndrome, so it is a stabilizer or a logical. If , then and the data are intact. It fails only if lies in the other coset, such as , which leaves .
Code distance and ⟦n, k, d⟧
1234nonzero syndrome: all detected12341234123tie: detected, not corrected
The distance is the smallest weight of a logical operator. An code detects any errors and corrects any . CSS codes have two distances, , and Deltakit’s planar codes set them apart.
details ›
QUnrotatedPlanarCode(width=2, height=4) has x_distance 2 and z_distance 4. How many errors and how many errors does it always correct?
ANo errors and one error. errors are corrected up to (one is detected), errors up to . Its distance is .
CSS codes and the binary picture
110011repetition code6 rows6 rows
A CSS code takes checks and checks from classical codes with . Then , with ranks over , not row counts. Hypergraph-product and bivariate bicycle codes are CSS.
details ›
QThe ⟦72, 12, 6⟧ bivariate bicycle code has 36 checks and 36 checks on 72 qubits. Where do its 12 logical qubits come from?
AFrom dependent checks. Each matrix has GF(2) rank 30, not 36, so . Counting rows gives 0, and the real rank from np.linalg.matrix_rank (32) gives 8. Both are wrong.
A Clifford maps Paulis to Paulis, so the images of and fix it: a tableau of signed rows. Gates update it in , measurements in : Gottesman–Knill. Stim’s sampler goes further and tracks Pauli frames only.
details ›
QWhy does Stim sample a million shots of a memory circuit with Pauli frames instead of running its tableau simulator a million times?
AA frame is bits per shot, with work per gate and 64 shots per machine word on arm64. A tableau is bits, with per gate and up to per measurement. On an arm64 laptop: about 57 µs per tableau shot against 0.6 µs per frame shot.
Sources: Lectures 1–2; Gottesman 1997
M2 Codes
From the repetition code to bivariate bicycle codes: geometry sets the checks, and the checks set the decoder.
The repetition code
Copy a bit onto qubits and measure neighbour parities . Majority vote fixes up to bit flips, and failures shrink with whenever . Phase flips pass unseen: as a quantum code its distance is 1.
details ›
QA colleague runs repetition-code memories in the X basis and sees failures grow from d = 3 to d = 7. Is the decoder broken?
ANo. The checks never see a error, and one anywhere flips the -basis observable, so the circuit distance is 1. A longer chain just offers more places to fail: 4.4%, 10.1% and 17.6% raw flips at SI1000 (seed 2026).
The toric code
dashed lines = the opposite sidesclosed around the torus: no defects,
Qubits on the edges of an torus. Stars ( at a vertex) and plaquettes ( around a face) are the checks. Errors are strings whose ends light up; loops around the torus are logicals, so .
details ›
QThe L = 4 toric code has 16 star and 16 plaquette checks on 32 qubits. Why is k = 2 and not 0?
ARows are not ranks. The product of all stars is the identity, and so is the product of all plaquettes, so each set has GF(2) rank 15 and . The two logical qubits are the two directions in which a loop can wrap the torus.
The rotated surface code and its boundaries
in a checkerboard8 weight-2 checks on the edges:
A grid of data qubits with weight-4 checks and weight-2 edge checks: on qubits. The edge types decide where logical strings may end, so width and height are two separate distances.
details ›
QIn a RotatedPlanarCode(width=5, height=3) memory, which basis fails more often, Z or X, and why?
AThe basis. Its observable is flipped by vertical strings, which need only 3 qubits to span the height. The -basis memory is protected by the width, 5. SI1000 runs (seed 2026) give 2,180 against 74 failures in 200,000 shots.
Syndrome extraction schedules and hook errors
A weight-4 check takes four CNOTs, and their order matters. An ancilla fault halfway through leaves a weight-2 hook error. If it lies along the logical, the circuit distance drops to about . Deltakit’s built-in orders all avoid this.
details ›
QYou put the X checks of a d = 7 rotated code in Z order (TL TR BL BR) and run a 7-round memory. Which basis suffers, and what circuit distance do you get?
AThe basis. An ancilla fault after two CNOTs leaves a horizontal pair, along , so about faults complete it: circuit distance 4, not 7. A one-round test would hide part of the damage, since it gives 5.
Hypergraph product codes
repetition code, used twiceeach acts on its grid neighbours⟦13, 1, 3⟧: the planar codeHamming × Hamming:⟦58, 16, 3⟧, not distance 9
Two classical codes in, one CSS code out, with commuting checks by construction. can grow in proportion to , but the distance is the smallest input distance, so . The toric code is one.
details ›
QThe hypergraph product of two [7, 4, 3] Hamming codes has k = 16. Is its distance 3 or 9?
A3. The distance is , not a product. One Hamming codeword laid along a single line of the grid is already a logical. Brute force on ⟦58, 16, 3⟧ gives .
Bivariate bicycle codes and the gross code
0123456789101101234512 × 6 torus; each site holds an L and an R qubitoppositeedgeswrap
Two commuting sums of shifts on an torus give and . Weight-6 checks with a few long-range links make ⟦144, 12, 12⟧, the gross code: 12 logical qubits on 288 physical qubits.
details ›
QBivariateBicycleCode(9, 6, [3, 1, 2], [3, 1, 2]) returns logicals of weight 12 or more. Is its distance 12?
ANo. Returned weights only bound from above. Bravyi et al. list this code as ⟦108, 8, 10⟧, and a random search (seed 2026) finds a weight-10 logical. Distance is a minimum over all logicals, not over one returned basis.
Sources: Lectures 3, 7; Dennis et al. 2002; Bravyi et al. 2024
M3 Noise and simulation
A noisy Clifford circuit with detectors compiles to a detector error model: the only input a decoder needs.
one round, left to rightreset1q gate2q gatereadoutidleidle at M, RSD6SI1000Toyphen.gates are perfect
A noise model places the faults of a syndrome round, relative to one number . SD6 puts on every operation; SI1000 makes readout , reset and one-qubit gates ; phenomenological noise keeps only data and readout flips.
details ›
QAt p = 10⁻³ a d = 3 surface-code memory fails 515 times in 200,000 shots under SD6 and 730 times under SI1000. Is SI1000 the harsher model?
ANot in general. At the counts are 186 (SD6) and 177 (SI1000). Going from to divides the SI1000 failures by 4.1 but the SD6 failures by only 2.8. The same means different things in different models, so compare them at the distances you care about.
The deltakit-stim fork
deltakitCircuitCircuitDetectorErrorModelTypeError+ its own circuit
Deltakit ships its own Stim build, imported as deltakit_stim. It adds leakage gates and is the only Stim installed, so tools that check for upstream stim classes, such as PyMatching’s constructors, reject its objects.
details ›
QPyMatching’s from_detector_error_model raises a TypeError on a DEM from deltakit_stim. Name two ways to get a working matcher.
AWrite the DEM to a file with dem.to_file(path) and call pymatching.Matching.from_detector_error_model_file(path). Or build PyMatchingDecoder.construct_decoder_and_stim_circuit(noisy) from the Deltakit circuit, and sample from the circuit it returns.
Detectors and observables
measurement record, oldest to newestMR 2MR 2M 0M 1recordrec[-1]rec[-2]rec[-1]rec[-3]rec[-2]rec[-1]rec[-2]
A detector is a parity of measurement outcomes that is fixed when nothing goes wrong; it fires when a fault flips it. rec[-k] counts back from the newest measurement. An observable is the parity that carries the logical value.
details ›
QA memory circuit starts with all data qubits reset to |0⟩. You add a DETECTOR on the very first outcome of an X-type check. What does Stim do?
AIt refuses to build the DEM: ValueError: The circuit contains non-deterministic detectors. That outcome is a fair coin even without noise (the sampler reports it firing in about half the shots), so no fault can be read from it. Compare the X check across two rounds instead; that detector is deterministic.
Detector error models
mechanisms in the circuitD0 D1 : 0.01D0 D2 : 0.005D2 L0 : 0.0296detector error modelall the decoder sees
A detector error model (DEM) lists every independent error mechanism by its symptoms: the detectors and observables it flips, plus its probability. Mechanisms with identical symptoms merge. The decoder sees only this table.
details ›
QA data qubit flips just before readout (p = 0.01) and its readout also flips (p = 0.02). How many DEM rows do these give, and with what probability?
AOne row, with . The two mechanisms flip the same detectors and observables, so no decoder can tell them apart.
From DEM to decoding graph
Matching needs every DEM row to flip at most two detectors. Each graphlike piece becomes an edge, a one-detector piece an edge to a boundary node, weighted . Pieces with the same endpoints merge into one edge.
details ›
QFour graphlike pieces of a decomposed DEM connect D9 and D13; the largest has p = 6.67×10⁻⁵ (weight 9.62). What weight does the edge D9–D13 get?
AOne edge with the merged probability, (the chance that an odd number of the pieces fire), so . That is lighter than any single piece. Weights add along a path, never across parallel pieces. (The undecomposed DEM and sampled data put this pair at twice : four more decomposed rows split the pair.)
Stim runs the noiseless circuit once, then tracks each shot as a Pauli frame, many shots per machine word. compile_detector_sampler(seed=…) returns booleans, shots × detectors; bit_packed=True packs eight per byte, little-endian.
details ›
QYou sample 2,000 shots from a detector sampler compiled with seed 2026. Later you redo it with a fresh sampler, same seed, as two calls of 1,000 shots. Same data?
ANo. With the same seed, the output also depends on how the shots are split into calls; even the first 1,000 rows differ. To reproduce a run, keep the seed and the batch sizes. Recompiling with the same seed and the same calls gives identical arrays (on the same Stim build and machine type).
Leakage
qubit subspaceRELAX, R, RLwhile leakedM does not return itM: random bitCX partner: randomherald reads 1DEM: no rowdropped
Leakage takes a qubit out of . It is not a Pauli fault, so a DEM ignores it: with SI1000Noise(pL=0.01) the DEM keeps 21 rows while the detection rate quadruples. Leakage removal and heralds are the remedies.
details ›
QYou turn on SI1000Noise(p=1e-3, pL=0.01) and rebuild the DEM: it has the same 21 rows as at pL = 0. Can the decoder built from it handle leakage?
ANo. The DEM drops LEAKAGE and RELAX, so the decoder is identical to the one without leakage. The detectors do notice: their rate goes from 0.0185 to 0.0744, while the DEM still predicts 0.0187.
Sources: Lectures 2, 4; Gidney 2021
M4 Decoding
A decoder guesses the logical class from detection events; speed, accuracy and the code family decide which one to use.
Maximum likelihood vs minimum weight
readML: 2 against 1, class 0
An optimal decoder returns the most likely class of errors, not the most likely error. Minimum weight agrees with it only when one lightest error dominates; ties, and how many equally light errors a class holds, are invisible to it.
details ›
QA syndrome has three lightest explanations, all of weight 2: two in class 0 and one in class 1. Which class does ML choose, and how often is a decoder that picks class 1 wrong on this syndrome when is small?
AML chooses class 0, which is about twice as likely. A decoder that picks class 1 is wrong about 2/3 of the time on this syndrome, ML about 1/3. Minimum weight cannot tell them apart; PyMatching happens to pick class 1 here.
Matching and PyMatching
PyMatching finds a minimum-weight perfect matching on the decoding graph, with weights . Deltakit wraps it as PyMatchingDecoder, which rewrites your circuit: sample from the circuit it returns. Errors must be graphlike.
details ›
QYou sample detectors from your noisy , 3-round circuit (24 detectors) and pass them to the decoder from PyMatchingDecoder.construct_decoder_and_stim_circuit. What happens?
AA ValueError: the decoder expects 16 or 17 columns. Its circuit keeps only the 16 -type detectors of a memory. Sample from the circuit it returns, which has the right detectors in the right order.
Union–Find decoding
unit growth: every edge is 2 half-steps6.914.604.606.91round 1: each odd cluster grows half an edge each way149914
Union–Find grows clusters around defects until each holds an even number of them or touches the boundary, then peels each cluster’s spanning tree into a correction. Almost-linear time, a little less accurate than matching.
details ›
QTwo defects sit two inner edges apart ( each), and each is one edge () from the boundary. What does unit-growth Union–Find return, and what does matching return?
AUnit growth fills all four edges in the same round, so the merged cluster touches the boundary and peeling sends both defects there (weight 13.8). Matching joins them through the middle (weight 9.19), which is about 102 times more likely. Weighted growth recovers the matching answer.
Belief propagation passes likelihood messages between errors and checks; it is exact on trees. On a degenerate code it splits its belief between equivalent corrections and stalls. OSD then solves for the likeliest columns by elimination.
details ›
QBP oscillates on a weight-3 error of the ⟦72,12,6⟧ code. Its last iterate gives the six qubits of one stabilizer LLR and every other qubit between 4.4 and 8.4. What does OSD-0 return, and does it fail?
AOSD ranks the six last, so it solves the syndrome with other columns: a weight-11 correction that satisfies the syndrome but differs from the error by a logical operator. A logical failure. Fed iterate 29 or the mean of the iterates, it returns weight 3 and succeeds.
Matching splits a error, or any fault that trips detectors of both types, into independent edges and overcharges it. Correlated matching and belief-matching restore the link by reweighting edges before matching.
details ›
QDepolarizing noise, , decoded by matching the and parts separately with weight ,. What weight does a single get, and what should it get?
ATwo edges of 3.37, so 6.73. Its true weight is , the same as an or a . Matching treats the as about 15 times less likely than it is, so it misses corrections built from s.
Tensor-network maximum-likelihood decoding
012345678spins on checks, factors on qubits81, 26, 7054334
ML decoding needs class probabilities: sums over every error in a class. For a planar code with independent flips, each sum is a 2D Ising partition function. A sweep contracts it exactly in time ; a boundary MPS approximates it.
details ›
QAt , (code capacity, noise), exact ML fails on 2,413 of 20,000 shots and matching on 2,621. Is ML right on every shot where matching is right?
ANo. ML is wrong on 410 shots where matching is right, and matching is wrong on 618 where ML is right. ML maximises the success probability of each syndrome, so it wins on average, not shot by shot.
Windowed and real-time decoding
05001000one global matching: 7450138919312820376857498747
Syndrome rounds keep arriving. A decoder slower than the hardware builds a backlog that grows exponentially across gates. Windows decode a few rounds at a time: commit the oldest, keep about buffer rounds for chains that continue.
details ›
QA decoder needs 1.1 µs per round on hardware that produces a round every 1.0 µs. Between gates the program runs 10 rounds. Is a lower decoding latency enough to fix this?
ANo. With the rounds to clear before each gate grow as : about 185 before gate 10 and before gate 100 (counting from gate 0). Only throughput (faster or parallel decoding) keeps the backlog bounded; latency then sets the fixed wait per gate.
Sources: Lectures 5, 7; Higgott & Gidney 2023
M5 Performance analysis
Count failures, put error bars on them, convert to error per round, then fit Λ to see whether bigger codes help.
Logical error probability and its uncertainty
051015ValueError
Estimate by . The plug-in bar breaks at small : it crosses zero, and at it vanishes. Use likelihood intervals instead. Zero failures give only a bound, .
details ›
QA run gives 0 failures in 10,000 shots, and calculate_lep_and_lep_stddev raises ValueError. What do you report?
AAn upper bound. With the plug-in error is zero, so Deltakit refuses. calculate_lep_asymmetric gives : at , or at (the rule of three). The same bound holds whatever the true noise is, because it depends only on .
Logical error per round
0.91.01.12010532
A run of rounds fails with , where . Fit against : the slope gives and the intercept gives the SPAM term . One run with adds to .
details ›
QYou fit at from one run each with rounds , then run ten times more shots. Does the gap to the slope-fit close?
ANo. Each single run estimates , and changes sign between and . That bias does not shrink with shots: at a million shots the shortcut still gives against 5.4 from the slope.
Thresholds
The threshold is where the curves for different cross: below it, larger codes fail less. It depends on the noise model, the decoder and per-shot or per-round counting. Being below it is necessary, not sufficient.
details ›
QYour rounds curves for and cross at . At , is a patch worse per round than a patch?
ANot necessarily. A rounds run of lasts 7 rounds, against 5 for , so the per-shot curves cross where , while still wins per round. With slope fits the per-round crossing sits near , and at the slope fits give .
The error-suppression factor Λ
357911
is the factor by which the logical error per round falls when :. means below threshold. Fit it on per-round errors, never on total LEP.
details ›
QYou compute from total LEPs of runs with rounds at and , and get 3.8. Is the code suppressing errors less than you thought?
ANo. Total LEP grows with the number of rounds, , so the ratio is off by a factor of . The same data give per round.
An error budget splits among noise sources: at , so . It ranks which error to reduce a little, not what removing a source buys.
details ›
QA budget gives readout a contribution of 0.066 out of . A vendor promises perfect readout. What should you expect?
ANot . A contribution is , a statement about small changes. Seeded runs with the readout flip set to zero give : along the readout direction is flat up to the midpoint and only then rises, so a slope taken at the midpoint overstates what removing readout buys. Simulate the end point before promising what an upgrade buys.
QuOps and resource prediction
91521273339252333same fit, lambda0 not inverted
A QuOp is one -round block of a distance- patch, and QuOps of that block. Deltakit’s helpers turn into QuOps or into a distance; a patch costs qubits. Pass them 1/ld.lambda0.
details ›
QYou need 100 logical patches, each running -round blocks. The rounds fit picks , the slope fit . What does the smaller patch cost you?
AIt saves physical qubits. Under the unbiased slope fit, though, expects 1.1 failures in the blocks, against 0.22 at . A 15% bias in became a fivefold rise in expected failures.
Sources: Lecture 6; Google Quantum AI 2024
M6 The Deltakit toolchain
Several packages, one pipeline: code → circuit → noise → sample → decode → analyse; deltakit-compile builds logical programs.
The Deltakit package map
deltakit_stim: Stim fork (+ leakage)deltakit.circuitdeltakit.coredeltakit.decode+ PyMatchingdeltakit.explorerdeltakit_compile+ xDSLdeltakit_visualisedeltakit.* names: aliasesRiverlane cloud6 decoder classesclient=uv pip install deltakit pulls in all seven
One install, seven packages. Four have deltakit.* names (circuit, core, decode, explorer); the Stim fork, compiler and visualiser import as deltakit_stim, deltakit_compile, deltakit_visualise. Only six cloud decoders leave your machine.
details ›
QAfter pip install deltakit, which of these imports work: deltakit.decode, deltakit.compile, deltakit_compile, stim?
Adeltakit.decode and deltakit_compile. The meta-package adds deltakit.* aliases for circuit, core, decode and explorer only. The compiler and the Stim fork are imported by their own names, and upstream stim is not installed at all.
The memory-experiment pipeline
RotatedPlanarCode(3, 3)css_code_memory_circuitRotatedPlanarCodePYTHONHASHSEED=0fixes target orderqpu.compile_and_add_noise_to_circuitCircuit (deltakit_circuit)construct_decoder_and_stim_circuitCircuit + noise, 24 detectors24 → 16 detectorscompile_detector_sampler(seed).samplestim Circuit (16 det.) + decoderseed=2026fixes the random bitsdecode_batch_to_logical_flipdets 100000×16, obs 100000×1344 fails → LEP 3.44e-3pred: uint8, 100000×1loop over d = 3, 5, 7 → Λ
Code → circuit → noisy circuit → (decoder, trimmed circuit) → seeded samples → predicted flips → failures. Each arrow passes one object; sample from the decoder’s circuit, seed the sampler and fix PYTHONHASHSEED, or counts drift.
details ›
QYou build the decoder from the noisy circuit noisy, then sample from noisy.as_stim_circuit() instead of from the circuit returned with the decoder. What happens for the d = 3, 3-round Z memory?
ADecoding fails with a ValueError: the samples have 24 columns but the decoder expects 16. The decoder kept only the detectors it uses. Always sample from the circuit it returns.
deltakit-compile and logical assembly
Write a program on logical patches with LogAsmBuilder, compile it with LogicalAssembler and StimExportPipelineConfig, get Stim text. The compiler finds every detector itself. Version 0.1.0 compiles memory-style programs only.
details ›
QA d = 3 patch is prepared in Z, measured for three rounds and read out in Z. The compiled Stim circuit has 25 detectors and no OBSERVABLE_INCLUDE. Where did the logical outcome go?
AInto the last detector. Without noise the readout of a patch prepared in is deterministic, an flow, so the compiler declares it a detector. With no observable, a decoder has nothing to predict and every run scores zero failures; add an observable but keep that detector, and the decoder reads the logical straight off the syndrome. Turn that detector into the observable before counting failures.
Lattice surgery
patch 1patch 2merged patchZZZZ× d roundsXXX
Merge two patches along a seam, measure the merged patch for about rounds, split. The product of the new seam checks is . Two-qubit logical measurements with only nearest-neighbour gates, paid for in rounds.
details ›
QYou call multi_pauli_measure with pauli_bases=["X", "X"] on two side-by-side patches whose logicals run vertically. What does the program describe?
AA merge, not an one. The builder places an -prepared bridge between the facing boundaries, which carry , and only records the requested XX; nothing checks the pair in 0.1.0. Stack the patches (the bridge is then prepared in ) or rotate one.
deltakit-compile is an xDSL compiler. A program is one IR module mixing dialects (log_asm, plaquette, qref, stab, qec, stim, …); 45 passes lower it stage by stage until only stim operations remain.
details ›
QIn deltakit-compile, which dialect is the patch-level instruction set, and which file defines it?
AThe dialect is log_asm (ops such as log_asm.prepare and log_asm.multi_pauli_meas), defined in dialects/logical_assembly.py. The file name is not the dialect name, so search for Dialect("log_asm" rather than for logical_assembly.
Contributing to Deltakit and the community fund
One guide governs every Deltakit repo: file in the right tracker, ask before starting, use Conventional Commits, sign the CLA, disclose substantial AI use. The community fund pays up to 4k USD; the next round closes 2 Dec 2026.
details ›
QA coding agent drafted the tests in your Deltakit PR. What must the PR say, and what must stay out of the commits?
AThe PR description names the tool and model, what it changed and how you checked it (“Used LLMs” is not enough). The tool is not credited as an author, and agent files such as CLAUDE.md or .claude/ are not committed. You must still understand every line and answer review questions yourself.
Pauli strings either commute or anticommute. In bits, and anticommute exactly when is odd, which counts the sites where both are non-identity and different. Overlap alone decides nothing.
The group, its phases and its weight
The -qubit Pauli group is the set of operators with and each . It has elements: 16 for one qubit and 4,096 for five. The four phases are there only so that the set is closed under multiplication. A product of two Hermitian strings can pick up , as in . For error correction one nearly always works modulo phase, with the strings. Elements with phase are Hermitian, square to and have eigenvalues , which is what makes them measurable as checks. Modulo phase, is just the vector space , and that quotient is what the bit rows below represent.
The weight is the number of qubits on which is not . Weight is the natural cost of an error: under independent single-qubit noise of strength , a weight- error has probability of order . A counts once, even though in bits it is an and a , so while the bit rows hold six ones.
Commutation is one bit
On a single qubit, two Paulis commute when one of them is or they are equal. Two different non-identity Paulis anticommute. Swapping and across qubits multiplies the sitewise signs, so , where is the number of clashing sites. Only the parity of survives. Two Pauli strings therefore either commute or anticommute, with nothing in between. Commuting operators can be measured together, in any order, with no effect on each other. An anticommuting pair shares no eigenbasis, so measuring one randomizes the other. That single fact decides which operators can serve as checks, and why measuring a logical operator destroys an encoded superposition.
In bits, write with , so that , and . Site clashes exactly when , which gives the symplectic product
Two facts carry the rest of this module.
Multiplication is addition., so a product of strings is the XOR of their bit rows, up to a phase you track separately.
The product is bilinear.. A string that commutes with every generator of a group commutes with the whole group, which is why a syndrome needs only one bit per generator.
The binary form, with check matrices and their symplectic product, is Gottesman’s (thesis, §3.4, eq. 3.23). Lecture 1 develops it in full and writes the product with a matrix .
Why Pauli errors are enough
Every operator on one qubit is a combination , and every operator on qubits is a combination of Pauli strings supported on those qubits. Expand each Kraus operator of a noise channel this way. Each Pauli term has a definite syndrome, so measuring the checks projects the corrupted state onto one syndrome class, and the decoder then undoes a Pauli. By linearity, a code that corrects a set of Pauli errors corrects every operator in their span. This is Gottesman’s §2.3. Knill and Laflamme state the general condition, and Code distance and ⟦n, k, d⟧ gives its one-line Pauli form.
Amplitude damping shows it on a non-unitary channel. At its Kraus operators are and . A code that corrects single-qubit , and errors corrects this channel too, even though no Pauli ever “happened”. Only the probabilities differ between channels. Linearity does not tell the decoder how likely is compared with ; that comes from a noise model (Circuit noise models: SD6, SI1000, phenomenological).
Worked example: overlap is not anticommutation
Take and . Their supports share qubits 0, 1, 2 and 4.
qubit
0
1
2
3
4
clash
1
0
1
0
0
Qubits 1 and 4 carry the same letter, and qubit 3 has an in . That leaves two clashes, so and commute. The product, site by site, is . The two factors of give the overall . In bits, the clash row is AND , XOR AND , which is exactly what the snippet below computes.
How rare is commuting? Of the 81 strings that use non-identity letters on exactly 's support, 41 commute with . That is : each site clashes for two of its three letters, and even clash counts win by one.
In Deltakit
Deltakit’s Stim build is deltakit_stim. Its PauliString does the algebra, phases included, and prints as _. (deltakit.circuit.PauliX and its siblings are gates on Qubit objects, not algebra.)
import deltakit_stim as stimp = stim.PauliString("XZYIY")q = stim.PauliString("ZZXXY")print("p*q =", p * q, " commute:", p.commutes(q))print("weights:", p.weight, q.weight)xp, zp = p.to_numpy()xq, zq = q.to_numpy()clash = (xp & zq) ^ (zp & xq)print("clash:", clash.astype(int).tolist())print("p == -p:", p == -p, " commute:", p.commutes(-p))
to_numpy() returns the and rows as boolean arrays, so the symplectic product is two ANDs and an XOR. weight counts a once. Phases live in p.sign, one of and :-p prints -XZY_Y and 1j * p prints +iXZY_Y. For small ,to_unitary_matrix(endian="little") returns the dense matrix with qubit 0 as the least significant bit. Stabilizer groups and the code space uses it to build projectors.
Traps
Overlap, clashes and parity
Strings that overlap everywhere can commute (the quiz), and strings that overlap on one site can anticommute. Count clashes, then take the parity.
== compares signs, commutes does notp == -p is False, yet both describe the same check up to its outcome sign. Compare str(p)[1:] to ignore the sign.
Short operands are padded silentlyPauliString("XZYIY") * PauliString("Z") returns -iYZY_Y. The one-qubit string acted on qubit 0, and the result is not Hermitian. Nothing warns you if you meant the last qubit.
Weight is not the bit count counts every twice. Use , or PauliString.weight.
Dense matrices need an endiannessto_unitary_matrix requires endian. With "little", has diagonal ; with "big", . Mixing the two silently permutes the qubits of a dense check.
Related cards
Stabilizer groups and the code space uses these strings as checks. Syndromes and logical operators turns the symplectic product into syndrome bits. CSS codes and the binary picture writes whole codes as bit matrices. Clifford tableaux and Gottesman–Knill tracks how gates move Pauli strings around. The deltakit-stim fork explains why the import is deltakit_stim and never stim.
dimension of the code space3216842each independentgenerator halves itredundant: the product of the four
A stabilizer group is an abelian subgroup of that does not contain . With independent generators, its code space has dimension and projector . Count independent generators, not rows.
What the definition asks for
A stabilizer group is a group of Pauli strings that commute with each other and does not contain . Its code space is the set of states fixed by every element, . Both conditions are there to keep nonempty:
If anticommute, a fixed state would satisfy , so .
If , a fixed state would satisfy . Gottesman’s §3.2 asks that “neither nor is in ” (thesis). With excluded, cannot occur either, since its square is .
So every element squares to , is Hermitian and has eigenvalues . A group is described by generators, and they are independent when none is a product of the others. Independence is linear algebra over : the generators’ bit rows must be linearly independent. Then , because every element is a product of a subset of generators and distinct subsets give distinct elements.
The code space is one of joint eigenspaces, one for each pattern of eigenvalues of the generators. These eigenspaces all have the same dimension and together fill the Hilbert space. An error moves the state from the code space into another eigenspace, and the pattern of signs it lands in is the syndrome (Syndromes and logical operators).
Why each generator halves the space
The projector onto the eigenspace of a Hermitian Pauli is . For commuting generators these projectors commute, and the code-space projector is their product:
Expanding the product gives one term per subset of generators, which is one term per group element. Every Pauli string other than a multiple of is traceless, so only the identity term survives the trace, and . This one-line count is the whole reason a code with independent generators stores qubits.
The step-by-step picture explains why the factor is exactly one half. Suppose are already imposed and is independent of them. Then there is a Pauli string that commutes with but anticommutes with . (In the bit picture, this is a linear system with a solution, because the rows are independent.) maps the eigenspace of inside the current space onto the eigenspace, and back. The two halves therefore have equal dimension. A dependent generator has no such : it is already fixed to or on the current space, so it either changes nothing or empties the space.
Worked example: the five-qubit code, by matrices
The five-qubit code is generated by and its cyclic shifts , and . Building as matrices and taking the trace after each factor gives 32, 16, 8, 4 and then 2. The final has rank 2, is idempotent and is Hermitian, so it is a projector onto a qubit. Summing all 16 group elements and dividing by 16 gives the same matrix, and 15 of those 16 elements are traceless. All of their signs are .
The fifth cyclic shift, , also commutes with everything. It looks like a fifth generator, but it is the product of the other four. Adding it to the product leaves the trace at 2. Counting rows instead of the rank predicts , which is wrong. Adding gives trace 0, because the group then contains .
Two qubits show the same trap in miniature. , and commute pairwise, but , so . The projector for has trace 0, and the one for has trace 1.
When , the code space is a single state, a stabilizer state. and alone fix exactly . Stabilizer states are what Clifford circuits produce from , and they are what Stim’s tableau simulator stores.
In Deltakit
Deltakit’s code classes hold only CSS codes. StabiliserCode is abstract: constructing it raises TypeError: Can't instantiate abstract class …. CSSCode rejects checks that mix and with a ValueError that ends “Each stabiliser must consist of either all X or all Z Paulis terms.” For a general group, work in deltakit_stim, with dense matrices for small and Tableau.from_stabilizers as a validator:
import numpy as npimport deltakit_stim as stimgens = ["XZZXI", "IXZZX", "XIXZZ", "ZXIXZ"]I32 = np.eye(32)proj = I32for g in gens: m = stim.PauliString(g).to_unitary_matrix( endian="little") proj = proj @ (I32 + m) / 2 print(g, round(proj.trace().real))print("rank:", np.linalg.matrix_rank(proj))PRE = "Some of the given stabilizers "for s in (["XX", "ZZ", "YY"], ["XX", "ZZ", "-YY"], ["XX", "ZZ"]): ps = [stim.PauliString(t) for t in s] try: stim.Tableau.from_stabilizers(ps) print(*s, "-> ok") except ValueError as e: msg = str(e).replace(PRE, "") print(*s, "->", msg.splitlines()[0])
XZZXI 16
IXZZX 8
XIXZZ 4
ZXIXZ 2
rank: 2
XX ZZ YY -> contradict each other.
XX ZZ -YY -> are redundant.
XX ZZ -> ok
from_stabilizers reports the two failure modes separately: dependent generators with a consistent sign are “redundant”, and dependent generators that multiply to “contradict each other”. The snippet prints only the first line; the full message goes on to name the offending row and the product of earlier rows that it equals or negates. The redundant case passes with allow_redundant=True. The function builds a full state tableau, so a code with also needs allow_underconstrained=True. Without it, Stim says “There weren’t enough stabilizers to uniquely specify the state.”
Traps
Rows are not generators needs = the number of independent generators, the GF(2) rank of the check matrix. Five cyclic shifts give , not 0. Bivariate bicycle codes do this at scale (CSS codes and the binary picture).
Pairwise commuting is not enough
Commuting generators can still multiply to . Check the sign of every product of dependent generators, or let from_stabilizers do it.
A flipped sign is a different code, not a broken one
Replacing an independent by selects the other half of the space. The code space has the same dimension and is for a Pauli . Only a sign flip on a dependent generator can empty the space.
Dense projectors do not scale is a matrix. That is fine for the five-qubit code and hopeless for a distance-5 surface code, where gives entries. Beyond toy sizes, count dimensions with GF(2) ranks in the binary picture.
Related cards
The Pauli group and commutation supplies the commutation rule. Syndromes and logical operators asks what happens when an error moves a state out of .Code distance and ⟦n, k, d⟧ counts the five-qubit code’s logical operators. Clifford tableaux and Gottesman–Knill treats the case , a stabilizer state.
Syndrome bit is 1 when error anticommutes with generator . Zero-syndrome Paulis are stabilizers (harmless) or logicals, . Errors with one syndrome form cosets: decode the coset.
Syndrome bits
Let a Pauli error hit a code state. Each generator either commutes or anticommutes with , so . Measuring therefore returns with certainty and does not disturb the encoded data. The bits form the syndrome. Three properties matter in practice:
It sees the error, not the data. is the same for every code state, which is why measuring it is safe.
It is linear., by the bilinearity of the symplectic product. With the check matrix of CSS codes and the binary picture, .
It splits by type in CSS codes. checks see only the part of an error: .
With independent generators, every one of the bit strings occurs as a syndrome. With redundant checks, as in bivariate bicycle codes, the syndrome bits obey parity constraints, which give free consistency checks against measurement errors. In hardware, an ancilla measures each check every round. The decoder then works on changes of syndrome bits between rounds, the detectors of Detectors and observables.
Zero syndrome: stabilizers and logicals
A Pauli with zero syndrome commutes with every generator, so it lies in the normalizer. For Pauli groups the normalizer equals the centralizer, the set of Paulis that commute with all of (Gottesman’s thesis, §3.2). It comes in two kinds.
Elements of , up to phase, act as the identity on the code space. They are harmless.
Elements of map the code space to itself but act on it nontrivially. These are the logical operators.
Counting modulo phase, and . The quotient therefore has classes, which is exactly the -qubit Pauli group: and for each logical qubit, and their products. The five-qubit code has 64 normalizer elements, of which 48 are logicals in 3 classes of 16 (see Code distance and ⟦n, k, d⟧).
Cosets and degeneracy
Two errors have the same syndrome exactly when their product is in . The errors with a given syndrome therefore split into cosets, one per logical class , each with members. Two consequences follow.
Correct the coset, not the error. The decoder applies some with the observed syndrome. The net operator has zero syndrome. If is in the coset of , then and the correction worked, even though . Otherwise a logical error has happened, and no later syndrome reveals it.
Degeneracy is normal. Gottesman calls a code degenerate when has elements of weight below . Then distinct low-weight errors share both syndrome and effect. Surface codes are highly degenerate: their checks have weight 4 and their distance grows without bound.
The optimal decoder picks the most probable coset, summing over all its members. A minimum-weight decoder picks the coset of the lightest error. Maximum likelihood vs minimum weight explains when the two differ.
Worked example: one syndrome, two cosets
Take RotatedPlanarCode(width=5, height=5), with 25 data qubits at odd , 12 checks and 12 checks. Consider only errors.
Let . It flips one check, the one with its ancilla at (4, 8).
Multiply by the check on . This gives , with the same syndrome. It is the same coset, so the same correction fixes both.
Multiply by , the five qubits with . This gives , again with the same syndrome. It is the other coset.
The parity of overlap with (the column ) tells the cosets apart: it is 1 for and and 0 for .
The counting checks out. There are errors and syndromes, so each syndrome has errors, which form 2 cosets of . Enumerating all of them:
coset
lightest
members of weight
2
3 at , 16 at 4, 76 at 6
3
6 at , 31 at 5, 203 at 7
Under independent flips with , the coset probabilities are and , a ratio of 49.5. Even an optimal decoder, given this syndrome, fails with probability 0.0198. At the ratio drops to 9.5, and the failure probability rises to 0.095.
In Deltakit
from deltakit.explorer.codes import RotatedPlanarCode. A code’s checks live in code.stabilisers, nested one level (a tuple of groups). Each Stabiliser has .paulis, a tuple of PauliX/PauliZ gates or None, and .ancilla_qubit. Qubits carry their coordinates in .unique_identifier.
from deltakit.circuit import PauliZfrom deltakit.explorer.codes import ( RotatedPlanarCode,)code = RotatedPlanarCode(width=5, height=5)checks = [s for grp in code.stabilisers for s in grp]def xy(q): return tuple(int(c) for c in q.unique_identifier)def syndrome(err): """Z checks flipped by X on `err`.""" fired = [] for s in checks: ps = [p for p in s.paulis if p is not None] if not isinstance(ps[0], PauliZ): continue hit = {xy(p.qubit) for p in ps} & err if len(hit) % 2: fired.append(xy(s.ancilla_qubit)) return sorted(fired)xl = {xy(p.qubit) for p in code.x_logical_operators[0]}zl = {xy(p.qubit) for p in code.z_logical_operators[0]}E = {(1, 9), (3, 9)}g = {(1, 7), (1, 9), (3, 7), (3, 9)}for name, e in [("E", E), ("E*g", E ^ g), ("E*XL", E ^ xl)]: print(f"{name:5}", syndrome(e), "Z_L parity:", len(e & zl) % 2)print("X_L:", syndrome(xl))
The last line confirms that itself has an empty syndrome: no check sees it.
Traps
Sets have hash ordercode.data_qubits is a set. It iterates in an unsorted order that no documented rule fixes, so never read it as a column order. Sort by coordinate, or report syndromes as sorted coordinates, as above.
is not a failure
Only the coset matters (the quiz). Benchmarks that compare a decoder’s with the sampled bit by bit overcount failures. Compare the logical observable instead.
A weight-2 error can fire one check has weight 2 but flips a single check, because sits on the boundary, where no second check sees it. The decoder must pair that lone defect with the boundary, which is why matching graphs carry a boundary node (From DEM to decoding graph).
Related cards
The rotated surface code and its boundaries explains why the top row is a logical. Code distance and ⟦n, k, d⟧ asks how light a logical can be. Tensor-network maximum-likelihood decoding computes these same coset sums for large codes, approximately, with a bond-dimension cut.
QA decoder sees the syndrome above and applies a correction . Has it failed?
ANot necessarily. has zero syndrome, so it is a stabilizer or a logical. If , then and the data are intact. It fails only if lies in the other coset, such as , which leaves .
1234nonzero syndrome: all detected12341234123tie: detected, not corrected
The distance is the smallest weight of a logical operator. An code detects any errors and corrects any . CSS codes have two distances, , and Deltakit’s planar codes set them apart.
Definition
The distance of a stabilizer code is
the weight of the lightest Pauli that commutes with every check but is not, even up to phase, a stabilizer. A code on qubits with logical qubits and distance is written . The double brackets separate it from a classical code. In the figure, every error on the way from to a minimum-weight logical is detected, because none of them is in until the walk arrives.
Distance is a worst-case quantity. It guarantees what happens to every error of a given weight, and it says nothing about how many errors of weight are dangerous. Two codes with the same can have quite different logical error rates, because they differ in the number of minimum-weight logicals. Distance also ignores degeneracy: errors lighter than may differ by a stabilizer and act identically, and that is harmless. Only logicals count.
Detect , correct
The Knill–Laflamme condition says that a set of errors is correctable exactly when for all pairs. For Pauli errors on a stabilizer code, this collapses to one line: no product may be a logical operator. The three numbers follow at once (Gottesman’s thesis, §2.3).
Correction. If every error has weight at most , every product has weight at most . That stays below when .
Detection. An error is detectable when it has a nonzero syndrome or is itself a stabilizer. Every error of weight 1 to qualifies.
Erasure. If the locations are known, the decoder only needs to tell apart errors on those qubits. All their products live on the same qubits, so located errors are correctable. That is about twice as many as unlocated ones, which is why heralded faults, such as detected leakage or atom loss, are worth flagging (Leakage).
For nondegenerate codes that correct errors, the syndromes of all errors of weight up to must be distinct. That gives the quantum Hamming bound, . The counting needs distinct syndromes, so as stated it applies to nondegenerate codes.
Worked example: the five-qubit code, by enumeration
Enumerate all five-qubit Pauli strings modulo phase. Of these, 64 commute with all four generators, 16 of them are stabilizers, and 48 are logicals. The logicals have weights 3 (30 of them) and 5 (18), so , and the code is .
Hamming bound. The 15 single-qubit errors have 15 distinct, nonzero syndromes. With , the bound reads , an equality: the code is perfect (Gottesman §8.4).
Where correction stops. and multiply to , a weight-3 logical. They have the same syndrome but differ by a logical, so no decoder corrects both. Of the pairs of a weight-1 and a weight-2 error, 90 fail this way.
What distance buys at low noise
The lightest errors that a minimum-weight decoder gets wrong have weight : put errors on a minimum-weight logical, and the decoder completes it. For odd that is , so at small the logical error rate scales as . Each step buys one more power of .The error-suppression factor Λ measures this on real circuits.
Two distances for CSS codes
In a CSS code, errors meet only checks and errors only checks. Each type has its own distance.
is the smallest weight of an -type logical, a vector in outside . It bounds how many errors are corrected, .
is the same with the roles swapped.
.
Deltakit’s planar codes take the two sizes separately, as UnrotatedPlanarCode(width, height) and RotatedPlanarCode(width, height). Brute force confirms what the attributes report (counts of lightest logicals in brackets):
patch
unrotated, 2 × 4
11
2 (4)
4 (2)
unrotated, 3 × 5
23
3 (5)
5 (3)
rotated, 4 × 2
8
4 (4)
2 (8)
Which boundaries a lightest logical joins, and which shape suits biased noise, is hw01’s A rectangular surface code. The two distances also depend on the constructor’s boundary options, not only on the size, so read the attributes rather than infer them.
In Deltakit
code.x_distance and code.z_distance exist on RotatedPlanarCode and UnrotatedPlanarCode only. Brute force checks them. For , a vector in is a nontrivial logical exactly when it anticommutes with , which avoids any rank computation. For , test against every :
from itertools import combinationsimport numpy as npfrom deltakit.explorer.codes import ( UnrotatedPlanarCode,)code = UnrotatedPlanarCode(width=2, height=4)hx, hz = code.parity_check_matricescols = sorted(q.unique_identifier for q in code.data_qubits)def vec(op): v = np.zeros(len(cols), dtype=int) for p in op: uid = p.qubit.unique_identifier v[cols.index(uid)] = 1 return vlx = vec(code.x_logical_operators[0])lz = vec(code.z_logical_operators[0])def lightest(checks, partner): """Lightest v: checks@v=0, v@partner=1.""" n = checks.shape[1] for w in range(1, n + 1): for s in combinations(range(n), w): v = np.zeros(n, dtype=int) v[list(s)] = 1 if (checks @ v % 2).any(): continue if v @ partner % 2: return wprint("n:", len(cols), " k:", code.calculate_number_of_logical_qubits())print("d_X brute:", lightest(hz, lz), " x_distance:", code.x_distance)print("d_Z brute:", lightest(hx, lx), " z_distance:", code.z_distance)
The columns of parity_check_matrices follow the qubits’ coordinates in sorted order, so sorting data_qubits (a set) rebuilds the column map. The row order does not have this property: stabilisers sit in sets hashed partly by memory address, so the order changes from run to run even with PYTHONHASHSEED fixed. Compare check matrices as sets of rows, never row by row.
Traps
Most code classes have no distance attributeRepetitionCode, UnrotatedToricCode, BivariateBicycleCode and CSSCode.from_matrix have no x_distance. Brute force on RepetitionCode(5) gives but : as a quantum code it is .
x_distance is about errors
It is the weight of the lightest -type logical, the fewest flips that cause an undetected logical error.
Code distance is not circuit distance
The attributes describe the code. A syndrome-extraction circuit can spread one fault into a weight-2 data error and lower the effective distance (Syndrome extraction schedules and hook errors).
Brute force explodes
The searches above try at most 561 supports on 11 qubits (330 at weight 4). A bivariate bicycle code [PUBLISHED, Bravyi et al., Nature 627, 778 (2024)] needs at the last weight, and the gross code’s is out of reach.
Related cards
Syndromes and logical operators defines .The repetition code and The rotated surface code and its boundaries show where and come from geometrically. Maximum likelihood vs minimum weight asks what a decoder can still do beyond errors.
A CSS code takes checks and checks from classical codes with . Then , with ranks over , not row counts. Hypergraph-product and bivariate bicycle codes are CSS.
The binary symplectic picture
Drop phases and every stabilizer code becomes linear algebra over . Write each generator as a row of length , and stack the rows into an check matrix. Then three things follow.
Commutation. The generators commute exactly when . In Lecture 1’s notation this is . The row space is then isotropic: every pair of rows has symplectic product zero.
Logical qubits., with the rank over . A product of generators adds their rows mod 2, phases dropped, so the stabilizer group is the row space, with elements.
Logical operators. They are the vectors whose symplectic product with every row is zero, minus the row space.
Clifford gates act on these vectors as symplectic matrices (Clifford tableaux and Gottesman–Knill). The five-qubit code fits this picture but not the next one. Its check matrix has rank 4, so , but none of its rows is purely or purely . A code like this is decoded with the full matrix, not with two halves.
CSS codes
A CSS code has generators that are each all- or all-. The check matrix is then block diagonal, with (the supports of the -type checks) in the half and in the half. Everything splits in two.
Commutation. This becomes : every check overlaps every check on an even number of qubits.
Logical qubits..
Logical operators.-type logicals are vectors in outside . Counting dimensions, , the same .-type logicals swap the roles.
Decoding. checks see only errors, , and checks see only errors. Decoding becomes two classical problems. The price is correlation: a error is an and a error on the same qubit, and two separate decoders treat the halves as unrelated.
In the original constructions of Calderbank and Shor and of Steane, the two check matrices come from classical codes, and the orthogonality condition says that one code contains the dual of the other. The seven-qubit Steane code of Lecture 1 takes both halves from the classical Hamming code, which contains its own dual.
Orthogonality is easy to break. Take checks and . A check overlaps each of them on one qubit, so , and the checks anticommute. overlaps each on two qubits and is allowed.
Hypergraph products: CSS by construction
Tillich and Zémor turn any two classical codes into a CSS code. Take () and (), and set
on qubits. Then for every choice of and , and , where is the dimension of .
The checks stay light. An check of the product has the weight of a row of plus that of a column of , so sparse inputs give sparse checks: a quantum LDPC code. Tillich and Zémor use this to build families with fixed nonzero rate and distance growing as . Before them, the best proven lower bound at fixed rate was logarithmic in .
Worked example. Use the repetition check twice.
The product has qubits, and and are both , with row weights 3 and 4, because has row weight 2 and column weights 1 and 2.
Both have GF(2) rank 6, so , matching .
Brute force gives , with 3 lightest logicals of each type.
Its Tanner graph, which joins every check to its qubits, is isomorphic to that of UnrotatedPlanarCode(3, 3).
The distance-3 unrotated surface code is this product. With the cyclic repetition check (three checks on a ring), the same construction gives an -qubit code with , isomorphic to UnrotatedToricCode(3, 3).
Rows are not ranks: bivariate bicycle codes
BivariateBicycleCode(6, 6, [3, 1, 2], [3, 1, 2]) is the code of Bravyi et al. [PUBLISHED, Bravyi et al., Nature 627, 778 (2024)]. It is CSS. and are each , every check has weight 6, and every qubit sits in 3 checks of each type. Each matrix has GF(2) rank 30, so six of its rows are products of others, and . Counting rows predicts no logical qubit at all. The redundant checks are free consistency conditions on the syndrome. Bivariate bicycle codes and the gross code builds the matrices.
In Deltakit
from deltakit.explorer.codes import CSSCode, BivariateBicycleCode. CSSCode.from_matrix(h_x=..., h_z=...) builds a code from matrices; the logical operators are optional. calculate_number_of_logical_qubits() does the GF(2) rank count. parity_check_matrices returns (hx, hz) as uint8 arrays.
The snippet assembles the product with np.kron, checks orthogonality mod 2 and leaves the rank count to Deltakit. The last line is the first trap below. One more numeric detail: a uint8 matrix product wraps at 256, so 300 overlaps come out as 44. Since 256 is even, parity survives and % 2 stays correct, but an overlap count read from hx @ hz.T does not. Cast to int first.
Traps
np.linalg.matrix_rank is the wrong rank
It works over the reals. Three checks on a ring, , and , have determinant 2, so real rank 3, but GF(2) rank 2. On the BB code the real rank is 32, not 30. Use Gaussian elimination mod 2, or calculate_number_of_logical_qubits().
detects errors
The subscript names the Pauli type of the checks. checks catch errors, and is the weight of the lightest -type logical. Swapping the two conventions mid-calculation is the most common CSS bug.
Related cards
Hypergraph product codes and Bivariate bicycle codes and the gross code develop both families. The toric code is the cyclic product above. Belief propagation and BP-OSD decodes the two classical halves.
QThe ⟦72, 12, 6⟧ bivariate bicycle code has 36 checks and 36 checks on 72 qubits. Where do its 12 logical qubits come from?
AFrom dependent checks. Each matrix has GF(2) rank 30, not 36, so . Counting rows gives 0, and the real rank from np.linalg.matrix_rank (32) gives 8. Both are wrong.
A Clifford maps Paulis to Paulis, so the images of and fix it: a tableau of signed rows. Gates update it in , measurements in : Gottesman–Knill. Stim’s sampler goes further and tracks Pauli frames only.
Conjugation tables
A unitary is Clifford if is a Pauli string for every Pauli string . In the Heisenberg picture, a gate acts on the checks and errors rather than on the state. If , then . Three generators suffice, up to phase (Gottesman’s thesis, §5.3):
: and .
:,,.
: and . So spreads from control to target, and from target to control.
Each rule is a short check with matrices. For example, , because and so . Counted as tableaux, there are 24 single-qubit Cliffords up to global phase (Lecture 2); hw01’s A tableau by hand counts the two-qubit ones and the unsigned ones. The signs are not decoration. sends to , so a -type check measured after reports the opposite outcome.
The tableau
Conjugation respects products, so is fixed, up to a global phase, by images: and . Each image is a row of bits, bits and a sign bit, which makes bits in all instead of the entries of a unitary.
The same table stores a stabilizer state. Starting from , the state is fixed by the images, its stabilizers. The images are the destabilizers: each anticommutes with exactly one stabilizer and commutes with the rest. This is the layout of Aaronson and Gottesman (§III), and the figure checks it bit for bit against Stim’s tableau of the circuit X 0; H 0; CX 0 1.
A gate updates every row with a few bit operations at the qubits it touches.
on : swap the and columns, and flip where .
:,, with a sign rule .
Both are per gate.
Measurement and the Gottesman–Knill theorem
Measuring has two cases.
Random outcome. Some stabilizer row has , so it anticommutes with . The outcome is a fair coin. Every other row with is multiplied by so that it commutes with . Then moves into the destabilizer slot, and , with the coin’s sign, takes its place. Up to row products of length cost .
Deterministic outcome. No stabilizer row has , so commutes with every stabilizer and equals a product of them. That sign is the outcome. Gaussian elimination would find the product in . The destabilizers name it directly: anticommutes with alone, so over exactly those for which anticommutes with . This costs .
Hence the Gottesman–Knill theorem. Circuits of Clifford gates, Pauli measurements and Clifford gates conditioned on earlier outcomes, started in a basis state, are simulable in polynomial time. It says nothing about universal computing: a gate maps outside the Pauli group. It does say that error-correction circuits, which are Clifford by design, are cheap. Aaronson and Gottesman’s program CHP, built on this layout, handles thousands of qubits. They also prove that simulating stabilizer circuits is complete for the class L, so these circuits are probably not even universal for classical computation.
Stim refines this (Gidney 2021, §4). It keeps the inverse tableau, whose row for is . The state is , so measuring is deterministic exactly when contains no or , and its sign is then the outcome: an check. This gives a total cost of for gates, deterministic and random measurements. Error-correction circuits are mostly deterministic. In the noiseless 7-round memory circuit (97 qubits, 385 measurements), only 48 measurements are random: the 24 first-round checks and 24 of the 49 final data readouts. The other 337 are fixed by earlier outcomes.
Frames: cheaper still
For sampling, Stim runs the tableau simulator once to get a reference sample. For each shot it then tracks only a Pauli frame: the Pauli by which that shot differs from the reference. A frame is bits. A gate conjugates it in , noise multiplies a random Pauli into it, and a measurement reports the reference bit XOR the frame’s bit (Gidney 2021, §3). Shots are bit-packed, one bit per shot in each machine word: 256 shots per word in Gidney’s AVX build, 128 in deltakit_stim on x86 (AVX2 is disabled) and 64 on arm64.
Random measurements need one more step. The reference sample fixes a single outcome for each, so the frame simulator re-randomizes them per shot with random insertions, which change no deterministic outcome (Gidney 2021, §3). In FlipSimulator, a circuit H 0; M 0 flips in 490 of 1000 shots, and in none with disable_stabilizer_randomization=True.
On the circuit a tableau holds 37,830 bits and a frame 194. Measured on an arm64 laptop, noiseless circuit, 200 tableau shots and frame shots: about 57 µs per tableau shot and 0.6 µs per frame shot, roughly 100 times faster (ratios from 75 to 101 over eight runs on a shared laptop). Treat these timings as machine-dependent. Sampling with Stim covers the sampler API.
In Deltakit
import deltakit_stim as stim, which provides Tableau, TableauSimulator and FlipSimulator:
import deltakit_stim as stimcirc = stim.Circuit("X 0\nH 0\nCX 0 1")t = stim.Tableau.from_circuit(circ)for k in range(2): print(f"X{k} ->", t.x_output(k), f" Z{k} ->", t.z_output(k))print("YY ->", t(stim.PauliString("YY")))sim = stim.TableauSimulator(seed=3)sim.do_circuit(circ)for p in ["XX", "ZZ", "YY", "XI"]: e = sim.peek_observable_expectation( stim.PauliString(p)) print(f"<{p}> = {e}")try: stim.Tableau.from_circuit( circ + stim.Circuit("M 0"))except ValueError as err: why = str(err).split("because ")[1] print("refused:", why.splitlines()[0])
The printed rows match the last step of the figure: destabilizers and , stabilizers and . Calling a tableau on a PauliString conjugates it: . The expectations follow from the group. Since , the product is a stabilizer too, with value . anticommutes with , so it is not a stabilizer, and its expectation is 0. peek_observable_expectation is deterministic, for stabilizer elements and 0 otherwise, so it needs no seed.
Three more tools help when you check a state by hand. sim.canonical_stabilizers() returns a canonical generating set, so two states are equal exactly when the lists are. The circuits X 0; H 0; CX 0 1 and H 1; CX 1 0; Z 0; X 0; X 1 both give -XX, +ZZ. sim.current_inverse_tableau() returns the inverse tableau that Stim actually stores. stim.FlipSimulator(batch_size=..., num_qubits=...) exposes the frame simulator itself, so you can inject your own Pauli errors.
Traps
from_circuit refuses non-unitary steps
Measurements, resets and noise raise ValueError, and the message names the first offending operation. Pass ignore_measurement=True, ignore_reset=True or ignore_noise=True to drop them.
Missing and renamed methodsTableauSimulator has no measure_pauli_string; use measure_observable(stim.PauliString(...)). Tableau.from_stabilizers wants a full set of stabilizers unless allow_underconstrained=True.
Related cards
The Pauli group and commutation supplies the bit rules. Detectors and observables uses deterministic measurements. The deltakit-stim fork explains the import.
QWhy does Stim sample a million shots of a memory circuit with Pauli frames instead of running its tableau simulator a million times?
AA frame is bits per shot, with work per gate and 64 shots per machine word on arm64. A tableau is bits, with per gate and up to per measurement. On an arm64 laptop: about 57 µs per tableau shot against 0.6 µs per frame shot.
Copy a bit onto qubits and measure neighbour parities . Majority vote fixes up to bit flips, and failures shrink with whenever . Phase flips pass unseen: as a quantum code its distance is 1.
What it is
The distance- bit-flip code maps and . Its stabilizer group is generated by the checks , and its logical operators are
Every single is equivalent to , since is a product of checks. So the code is as a quantum code: and . In CSS language it has only checks, so is empty. As a classical code it is , and that half is what it protects.
A check is measured with one ancilla between its two data qubits: two CNOTs onto the ancilla, then a readout. An error flips the checks that touch it: two in the middle of the chain, one at either end. A run of flips lights only the checks at its two ends, and the decoder pairs the ends up along the shorter side of the chain (figure, step 3). That is minimum-weight matching on a line. For independent flips it is the same as majority vote.
A worked example at , read off the code’s own . on gives the syndrome 0 1 1 0. on gives 1 0 0 1, and so does on . Matching picks the two-flip explanation, so the three real flips plus the two corrections cover all five qubits, which is . Majority vote fails exactly when more than half the bits flip.
Readouts fail too, so real experiments repeat the checks and compare each round with the one before. A wrong ancilla readout then lights the same check twice, in that round and the next, while a data error lights two neighbouring checks in the same round. On a space-time sheet, data errors are horizontal edges and readout errors vertical ones, and matching pairs defects on that two-dimensional graph.
Why is the threshold
Majority vote fails when more than half of the bits flip:
The flip fraction concentrates near as grows, so for every and for every . Our script evaluates the sum for :
0.10
0.1
0.028
0.0086
0.0027
0.45
0.45
0.425
0.407
0.392
0.50
0.5
0.5
0.5
0.5
0.55
0.55
0.575
0.593
0.608
The curves for different all meet at : that is the threshold, in the sense of the Thresholds card. Far below it, the leading term is enough. At , it gives against the exact .
With circuit noise the readouts fail too, so the checks are repeated for rounds and matching runs on a space-time graph (Detectors and observables). The threshold-like crossing survives but moves. Here are -basis memories with SI1000 noise and PyMatching (seed 2026, batch_size 100,000), failures per 100,000 shots:
41
4
0
3,774
2,101
1,132
21,938
24,884
27,639
A finer sweep with 200,000 shots puts the and per-shot crossings at . Below the crossing, each step divides the failures by about 10 at and under 2 at . These are whole runs, and the larger code also runs longer. Per round the factors are about 17 at (from only 4 failures at , so ±50%) and 3.0 and 2.6 at . The per-round factor is (The error-suppression factor Λ). Even at , past the per-shot crossing, still beats per round, by 1.2 (Thresholds).
The trap: one error type only
Everything above concerns errors. A error commutes with every check, so it lights nothing, and it is a logical error on its own (figure, step 4). An -basis memory prepares and reads out . Any single flips that observable unseen, so its circuit distance is 1 at every . Deltakit builds the circuit without complaint. At SI1000 with rounds and seed 2026, the raw observable flips per 100,000 shots are 4,375, 10,147 and 17,583 for . Decoding cannot fix what the checks never see. With PyMatching (batch_size 100,000) the counts are 8,129, 20,053 and 32,144, worse than not decoding at all. The DEM even contains error mechanisms that flip the observable and no detector. Compare the basis at the same noise, where matching turns 1,439, 2,054 and 2,742 raw flips into 41, 4 and 0.
The phase-flip code swaps the roles: checks , blind to . Hardware runs one or the other as a benchmark of a single noise channel. Google’s first demonstration used both, on 5 to 21 qubits, and cut the logical error per round by more than (Google Quantum AI 2021). Google’s repetition codes later reached , on Willow’s 72-qubit processor (the surface-code memory ran on the 105-qubit one), and hit a floor set by rare correlated events about once an hour [PUBLISHED, Nature 638, 920; Google Quantum AI 2024]. A logical qubit needs both kinds of check at once: The toric code.
In Deltakit
from deltakit.explorer.codes import RepetitionCode. Data qubits sit at even on the line , with ancillas between them, so a distance- code uses qubits. The snippet reads off the matrices, the logical weights and the circuit distance in both bases:
The memory has detectors: each round compares every check with the round before (the first with the reset value), and the final data readout rebuilds the checks once more. The memory has fewer. After resets the first round of checks is random, and the final readout cannot rebuild them, which leaves .
No distance attributeRepetitionCode has no x_distance, z_distance or draw_patch. Read the distances off the logical weights, as above. stabiliser_type=PauliBasis.X gives the phase-flip code, with of shape (4, 5) and an empty .
Row order is not stable
The rows of hz come in set order, which changes from run to run even with PYTHONHASHSEED fixed. Compare check matrices as sets of rows (CSS codes and the binary picture).
Related cards
Code distance and ⟦n, k, d⟧ explains why caps the code. The toric code adds the missing checks. Matching and PyMatching is the decoder behind the tables, and Thresholds explains the crossing.
QA colleague runs repetition-code memories in the X basis and sees failures grow from d = 3 to d = 7. Is the decoder broken?
ANo. The checks never see a error, and one anywhere flips the -basis observable, so the circuit distance is 1. A longer chain just offers more places to fail: 4.4%, 10.1% and 17.6% raw flips at SI1000 (seed 2026).
dashed lines = the opposite sidesclosed around the torus: no defects,
Qubits on the edges of an torus. Stars ( at a vertex) and plaquettes ( around a face) are the checks. Errors are strings whose ends light up; loops around the torus are logicals, so .
What it is
Take an square lattice and glue opposite sides, so that it lives on a torus. Put one qubit on each edge: . Each vertex and each face carries a weight-4 check:
A star and a plaquette share either no edge or two, so all checks commute. There are of each, but they are not independent. Every edge touches two vertices, so the product of all stars is the identity, and likewise for plaquettes. Each set has rank , so
The count does not grow with . The rate goes to zero, and only the distance improves: the price of checks that stay local.
For a physicist this is Kitaev’s model of topological order. The code space is the four-fold degenerate ground space of , and no local operator can tell the four states apart.
Strings, defects and anyons
A error on an edge anticommutes with the stars at both of its endpoints. Along a path of errors, every inner vertex is touched twice and stays quiet. Only the two ends flip (figure, step 3). These flipped stars are the defects, the -type anyons of the model. They are created in pairs, and a longer string moves them apart. errors behave the same way on the dual lattice. An on an edge flips the two plaquettes that share it, and an string across a row of edges lights the plaquettes at its two ends (-type anyons). Drag an defect once around an defect and the closed loop crosses the string once. The two anticommute, so the state picks up a sign: and are mutual semions. The same algebra makes each anticommute with the it crosses.
The decoder sees only the defects. It must pair them up with strings of its own, so that error plus correction forms closed loops. Two kinds of loop exist:
A contractible loop bounds a region, and it equals the product of the plaquettes (or stars) inside. It does nothing to the code space. This is degeneracy: many different errors are equally good to undo.
A non-contractible loop wraps the torus. It commutes with every check but is no product of them. It is a logical operator.
So and are loops along the two cycles of the torus. and are loops on the dual lattice, each crossing one loop once. The shortest wrapping loop has edges, so . Wrongly paired defects close into such a loop, and that is a logical error. Dennis et al. map optimal decoding onto a random-bond Ising model and its threshold onto a phase transition. This is where minimum-weight matching enters QEC. For CSS noise the two problems decouple. Stars catch errors and plaquettes catch errors, so matching runs on two separate graphs. A error lights both, a correlation that Correlated matching and BeliefMatching puts back.
Worked example: rows, ranks and circuits
Our script builds UnrotatedToricCode(L, L) for to 6:
checks per type
rank
logical weight
3
18
9
8
2
3
4
32
16
15
2
4
5
50
25
24
2
5
6
72
36
35
2
6
Every check has weight 4, and every column of has weight 2. That is the “product of all stars is ” statement as a matrix fact. With one ancilla per check, the device needs qubits. Memory circuits with rounds and SD6 noise keep circuit distance in both bases, for , with detectors: 54, 128 and 250. Unlike the repetition code, both bases are protected, because every qubit sits in two stars and two plaquettes.
The figure of merit is , the same as for the surface code. By the Bravyi–Poulin–Terhal bound, no code with local checks on a flat layout does better than a constant times this (Hypergraph product codes).
In Deltakit
from deltakit.explorer.codes import UnrotatedToricCode. Coordinates have period :
data qubits sit at (even, even) on vertical edges and at (odd, odd) on horizontal edges;
stars sit at (even, odd) on the vertices;
plaquettes sit at (odd, even) on the faces.
At the star at (2, 1) acts on (2, 2), (1, 1), (3, 1) and (2, 0). The returned is (0, 0), (0, 2), (0, 4), a vertical loop. is (0, 0), (2, 0), (4, 0), a dual loop. They overlap on one qubit, so they anticommute.
from deltakit.explorer.codes import ( UnrotatedToricCode,)for L in (3, 4, 5): t = UnrotatedToricCode(L, L) hx, hz = t.parity_check_matrices k = t.calculate_number_of_logical_qubits() w = [len(o) for o in t.z_logical_operators] print(f"L={L}: n={len(t.data_qubits)}", f"stars={hx.shape[0]} k={k} Z_L={w}")t = UnrotatedToricCode(4, 4)hx, hz = t.parity_check_matricesprint("product of all stars is I:", not (hx.sum(axis=0) % 2).any())
L=3: n=18 stars=9 k=2 Z_L=[3, 3]
L=4: n=32 stars=16 k=2 Z_L=[4, 4]
L=5: n=50 stars=25 k=2 Z_L=[5, 5]
product of all stars is I: True
Counting rows predicts stars plus plaquettes on qubits looks like zero logical qubits. Use calculate_number_of_logical_qubits(), which works with GF(2) ranks, or compute the ranks yourself.
No distance attribute, but a drawingUnrotatedToricCode has no x_distance or z_distance. The returned logicals have weight , which only bounds from above. Unlike RepetitionCode, it does have draw_patch.
Two logical qubits, two observables
A toric memory circuit carries two observables, one per logical qubit. Count failures on each, or on either, but say which.
Why chips use a planar patch
Periodic boundaries need couplers that wrap around the chip. Cutting the torus open removes them but costs one logical qubit. UnrotatedPlanarCode(L, L) is that cut-open lattice: data qubits (13, 41 and 85 for ), and distance . Rotating it saves almost half the qubits: The rotated surface code and its boundaries. The torus is the hypergraph product of two cyclic repetition codes, and this cut-open lattice that of two open ones (Hypergraph product codes). From DEM to decoding graph turns its defect pairs into matching edges.
QThe L = 4 toric code has 16 star and 16 plaquette checks on 32 qubits. Why is k = 2 and not 0?
ARows are not ranks. The product of all stars is the identity, and so is the product of all plaquettes, so each set has GF(2) rank 15 and . The two logical qubits are the two directions in which a loop can wrap the torus.
A grid of data qubits with weight-4 checks and weight-2 edge checks: on qubits. The edge types decide where logical strings may end, so width and height are two separate distances.
From torus to patch
The toric code needs a torus. To put it on a chip, cut it open. A cut creates a boundary, and a string of one type can end on a boundary that has no check of the opposite type beyond it, without lighting a defect. Choose two opposite boundaries where strings may end and two where strings may end. Then one logical qubit survives: is a string between the first pair and a string between the second. The torus had two independent wraps per type; the patch keeps one.
In the unrotated planar code, these are the “rough” and “smooth” boundaries. It is : 41 data qubits and 81 qubits in all for . Turning the lattice by and keeping a block of data qubits reaches the same distance with about half as many. Bombin and Martin-Delgado find layouts with for planar surface codes, against 2 for the standard layout; they call it optimal, by construction rather than by proof. This rotated patch is the one built in hardware. Tomita and Svore recommend its 17-qubit version for early experiments.
Anatomy of the patch
Data. qubits on a grid.
Bulk. weight-4 checks on the faces, and in a checkerboard. Neighbouring checks of opposite type overlap on two qubits, so all checks commute.
Edges. weight-2 checks, half of each type, on every other pair of boundary qubits: per edge. The -type ones sit on one pair of opposite edges and the -type ones on the other. We call the edges by these types, which is less ambiguous than “rough” and “smooth”.
Counting. The checks are independent, so . One ancilla per check gives qubits.
Our script checks the counts for RotatedPlanarCode(d, d):
data
weight 4
weight 2
qubits
3
9
4
4
17
5
25
16
8
49
7
49
36
12
97
Where can a logical end? An string is detected by checks. On the -type edges there is no check beyond the last qubit, so an string can end there unseen. Hence runs between the two -type edges, and runs between the two -type edges. The lightest such strings are a row and a column, so both distances equal .
A worked syndrome at , from our script:
on (5, 9), in the middle of the top row, fires the checks at (4, 8) and (6, 10).
Add on (3, 9). The check at (4, 8) now sees two flips and goes quiet, and (2, 10) fires instead: the defects sit at the two ends of the string.
on the whole top row fires nothing. Each check meets the row in 0 or 2 qubits, and the row is .
One round of the default schedule uses two-qubit gates: 24, 80 and 168 for . A -round memory has detectors in either basis: 24, 120 and 336.
Width and height are two distances
Nothing forces a square. RotatedPlanarCode(width, height) has of weight width and of weight height, and the attributes say so: x_distance is the width and z_distance the height.
Take : 15 data qubits and 29 qubits in all. Six checks (two of weight 2) and eight checks (four of weight 2). Which memory does each distance protect? A -basis memory reads , which strings flip, so it is protected by x_distance. With 5 rounds and SD6 noise, the circuit distance is 5 for the -basis memory and 3 for the -basis memory.
The square patch is balanced: 177 against 183 is within shot noise. The thin patch’s memory even beats the square one: three rows offer fewer places for a horizontal string to form. Its memory pays for that. Under noise biased towards , make the patch taller, not wider.
In Deltakit
from deltakit.explorer.codes import RotatedPlanarCode. Data qubits sit at odd and ancillas at even , with up. At , the -type edge checks are at (0, 2), (0, 6), (10, 4) and (10, 8), and the -type ones are at (4, 0), (8, 0), (2, 10) and (6, 10). The returned is the top row, . is the left column, .
from collections import Counterfrom deltakit.explorer.codes import ( RotatedPlanarCode,)code = RotatedPlanarCode(width=5, height=3)count = Counter()for s in code.stabilisers[0]: ps = [p for p in s.paulis if p is not None] count[type(ps[0]).__name__, len(ps)] += 1for (kind, wt), n in sorted(count.items()): print(f"{kind} weight {wt}: {n}")print("qubits:", len(code.data_qubits), "data,", len(code.qubits), "total")print("x_distance", code.x_distance, " z_distance", code.z_distance)
A weight-2 check keeps four slots in .paulis, with None where a corner is missing. The slot order is the CNOT order. The defaults are ScheduleType.SIMULTANEOUS and ScheduleOrder.HORIZONTALLY_REFLECTED: an N-shaped order for checks and a Z-shaped one for checks, so that hook errors lie across the logicals rather than along them (Syndrome extraction schedules and hook errors).
Traps
One basis is half a test
A -basis memory only checks that survives, which a classical repetition code could also do. Run both bases. The (5, 3) patch looks excellent in the basis alone.
Which distance guards which memory
The -basis memory fails through strings, so x_distance (the width) protects it. Swap the two and you will build the wrong rectangle.
Code distance is not circuit distancex_distance describes the code. A bad CNOT order can lower the circuit distance to about . Deltakit’s built-in orders all keep , but your own may not.
Related cards
The toric code is the uncut version. Syndromes and logical operators shows syndromes on this patch, and Code distance and ⟦n, k, d⟧ checks the distances by brute force. Lattice surgery merges patches along these edges.
QIn a RotatedPlanarCode(width=5, height=3) memory, which basis fails more often, Z or X, and why?
AThe basis. Its observable is flipped by vertical strings, which need only 3 qubits to span the height. The -basis memory is protected by the width, 5. SI1000 runs (seed 2026) give 2,180 against 74 failures in 200,000 shots.
A weight-4 check takes four CNOTs, and their order matters. An ancilla fault halfway through leaves a weight-2 hook error. If it lies along the logical, the circuit distance drops to about . Deltakit’s built-in orders all avoid this.
What a schedule has to get right
One round of the rotated surface code resets the ancillas, runs four layers of CNOTs and measures. In layer , every check touches its -th data qubit. Name the four corners of a face TL, TR, BL and BR. A schedule then gives each check type a corner order. It must satisfy two conditions.
Commutation. Neighbouring and checks share two data qubits. Both shared qubits must meet the two checks in the same order, both first or both first. Otherwise the circuit does not measure commuting operators and the detectors turn random. Cyclic orders, clockwise or anticlockwise, always fail: most pairs of them break commutation (Fowler et al., App. B, work through the clockwise case), and the few that commute send two CNOTs to one data qubit in the same layer. That is why the usual orders trace an “N” or a “Z”.
Fault spreading. A fault on the ancilla partway through a check is copied onto the data qubits that come after it. That is the hook.
Hook errors
An check’s ancilla starts in and controls four CNOTs onto the data. An fault on the ancilla after gate reaches every later data qubit:
after gate 1: three data qubits. That is the check times one qubit, so it is no worse than a single error;
after gate 2: the last two data qubits, the dangerous case;
after gate 3: one data qubit.
The pair matters because of its direction. is a horizontal row. If the hook pair is horizontal too, each fault supplies two of the qubits needs, and faults complete it. If the pair is vertical, it crosses and costs no more than a single error. The rule:
The hook must cross the logical, not run along it checks visit one column and then the other (the N order, TL BL TR BR), so that the hook pair is vertical. checks visit one row and then the other (the Z order, TL TR BL BR), so that their hook pair is horizontal and crosses the vertical .
Tomita and Svore (Sec. III B) found this the hard way. With one order for both check types, a single ancilla fault in their simulations left two aligned errors, and the decoder completed the chain of three. They fixed it by giving the two types different orders. (The names N and Z are ours. The paper names only its original “S” or “Z” shape, and its fixed Z-check order, top right, bottom right, top left, bottom left, is not Deltakit’s.)
What a hook costs, measured
We built the bad order (X checks in Z order) and asked Stim for the circuit distance: the fewest graphlike faults (Stim’s shortest_graphlike_error) that flip the observable of the memory without lighting a detector, under SD6 noise.
1 round
2 rounds
3+ rounds
safe order
3
2
2
2
3
5
3
3
3
5
7
5
4
4
7
From three rounds on it is exactly . A short experiment hides part of the drop, so measure circuit distance with as many rounds as you will run.
Distance is a worst case. The failure rate also moves: at , 5 rounds, SI1000 , 200,000 shots, seed 2026 and batch_size 100,000, the memory fails 547 times with the bad order against 185 with the safe one. The memory barely changes (214 against 192). The DEM does know about hooks: each is one mechanism, an edge between detectors that no single data error joins (From DEM to decoding graph), and matching weighs it correctly. What no decoder can undo is the lost distance.
In Deltakit
from deltakit.explorer.codes import RotatedPlanarCode, ScheduleOrder, ScheduleType. A check’s .paulis tuple is its CNOT order, with None in idle slots. The snippet reads the bulk orders for each ScheduleOrder and counts time steps for each ScheduleType:
from deltakit.circuit.gates import PauliBasisfrom deltakit.explorer.codes import ( RotatedPlanarCode, ScheduleOrder, ScheduleType, css_code_memory_circuit,)NAME = {(-1, 1): "TL", (1, 1): "TR", (-1, -1): "BL", (1, -1): "BR"}def order(s): a = s.ancilla_qubit.unique_identifier out = [] for p in s.paulis: q = p.qubit.unique_identifier out.append(NAME[q[0] - a[0], q[1] - a[1]]) return " ".join(out)for o in ScheduleOrder: c = RotatedPlanarCode(5, 5, schedule_order=o) seen = {"X": set(), "Z": set()} for s in c.stabilisers[0]: if None in s.paulis: continue # weight-2 boundary check kind = type(s.paulis[0]).__name__[-1] seen[kind].add(order(s)) name = o.name.split("_")[0] print(f"{name:12}", "X:", *seen["X"], "| Z:", *seen["Z"])for t in ScheduleType: c = RotatedPlanarCode(5, 5, schedule_type=t) s = css_code_memory_circuit( c, num_rounds=5, logical_basis=PauliBasis.Z, ).as_stim_circuit() n = sum(i.name == "TICK" for i in s.flattened()) print(f"{t.name:12}", n, "ticks in 5 rounds")
The default, HORIZONTALLY_REFLECTED, is exactly N for checks and Z for checks, with pointing up. The other three are mirror images. All four visit checks column by column and checks row by row, so all are hook-safe. Every pairing of SIMULTANEOUS, Z_FIRST or X_FIRST with each of the four orders keeps circuit distance 5 at in both bases. Z_FIRST and X_FIRST measure the two types one after the other. That costs 55 time steps for 5 rounds against 30, and the extra steps are extra idle noise. Z_ONLY and X_ONLY measure a single type, a repetition-code-like half test.
Traps
Deltakit will not build a bad order for you
To see a hook, rebuild the checks with your own .paulis order and wrap them in a CSSCode. Lecture 3’s reorder helper does this; it borrows the unexported Stabiliser class from an existing check.
Same DEM, different random draws
At , the reorder copy with N/Z orders reads the data out in a different order, so its record offsets shift, but its DEM is identical to the default’s. The same seed then assigns the random draws differently: 185 -memory failures against 177, a gap within shot noise. A seed reproduces counts only for the identical circuit text.
Drawings flip
Deltakit’s points up. In a -down drawing, TL and BL swap. “Column first for , row first for ” survives the flip.
Related cards
The rotated surface code and its boundaries fixes the directions of and .Circuit noise models: SD6, SI1000, phenomenological explains why hooks exist only at circuit level. Code distance and ⟦n, k, d⟧ is the code-level number that hooks undercut.
QYou put the X checks of a d = 7 rotated code in Z order (TL TR BL BR) and run a 7-round memory. Which basis suffers, and what circuit distance do you get?
AThe basis. An ancilla fault after two CNOTs leaves a horizontal pair, along , so about faults complete it: circuit distance 4, not 7. A one-round test would hide part of the damage, since it gives 5.
repetition code, used twiceeach acts on its grid neighbours⟦13, 1, 3⟧: the planar codeHamming × Hamming:⟦58, 16, 3⟧, not distance 9
Two classical codes in, one CSS code out, with commuting checks by construction. can grow in proportion to , but the distance is the smallest input distance, so . The toric code is one.
on qubits. CSS codes and the binary picture proves that the checks commute. Here is the picture behind the formula. Draw each classical code as its Tanner graph, with bits and checks joined when . Put one graph on each axis and take the product grid (figure):
cells () and cells () are the qubits;
cells () are the checks;
cells () are the checks.
Every check acts on the cells one Tanner-graph step away along either axis. An check’s weight is a row weight of plus a column weight of . So sparse inputs give sparse checks, and the product is a quantum LDPC code. With two repetition codes on a line the grid is the planar surface code, and with two cyclic ones it is the toric code. In the toric case the and cells are the two sets of edges, the checks are the vertices and the checks the faces.
Logical qubits and distance
Write for the classical code and for its redundant checks. Write for the distance of the code with checks , infinite when . Then
The distances are easy to see on the grid. Take a codeword of and lay it along one line of bit cells, as . Every check on that line sees an even number of its bits. On a suitable line it is a nontrivial -type logical of weight , whatever is. Distance is therefore a minimum over the inputs, never a product. In the repetition-code grid of the figure, along a column of bit cells is the familiar surface-code string from one edge to the other.
The two terms of live in different places. The logical qubits come from codewords of both inputs and sit in the block. The come from redundant checks and sit in the block.
That is the weakness. Take two good classical LDPC codes of length , with and . The product then has but only . Tillich and Zémor’s point was that this still beats the logarithmic distance, the best bound known before for quantum LDPC codes of fixed rate. Codes with local checks on a flat layout are capped at by Bravyi, Poulin and Terhal. Products escape the cap with long-range checks. Later constructions push past ; see the review by Breuckmann and Eberhardt.
Worked examples
Our script builds the products with np.kron, counts with GF(2) ranks and with Deltakit, and finds the distances by brute force:
inputs
,
check weights
rep(3) × rep(3), open
13
1
3, 3
3–4
rep(4) × rep(4), cyclic
32
2
4, 4
4
rep(5) × Hamming
47
4
3, 5
3–6
Hamming × Hamming
58
16
3, 3
5–7
Every row follows the formulas. The open repetition code has , but the cyclic one has (its checks sum to zero), which is why the torus carries two logical qubits. In rep(5) × Hamming the two distances differ, and the code’s distance is the smaller one. With rep(5) as , the formulas give , and , which is what brute force finds. The two check types are not even equal in number: 28 checks of weight 3 to 5 against 15 checks of weight 5 or 6, because the shapes of the two inputs differ.
Hamming × Hamming stores 16 logical qubits at distance 3 in 58 data qubits, or 100 with one ancilla per check: . Sixteen rotated patches need qubits. Counting data qubits only, the rate is , against for one patch. The planar surface code, repetition × repetition, stays near : 0.78, 0.74 and 0.72 for , 11 and 21. The rotated patch reaches 1.
In Deltakit
Deltakit 0.10.2 has no hypergraph-product class. Build the matrices and pass them to CSSCode.from_matrix (from deltakit.explorer.codes import CSSCode):
n = 58 k = 16
checks: 21 X + 21 Z
H_X H_Z^T = 0: True
X-check weights: [5, 6, 7]
from_matrix computes from ranks but reports no distance. At this size brute force is cheap. For anything larger, use the formula above.
It also returns no logical operators unless you pass them as log_x_ops and log_z_ops: x_logical_operators is empty here. css_code_memory_circuit on this code stops with NotImplementedError: No logical Z operators provided so cannot prepare logical zeroes state. To simulate a memory, compute a basis of logicals first (a GF(2) exercise) and hand it over. The code’s parity_check_matrices keeps your column order, since column becomes qubit , but returns the rows in set order.
Traps
Distance does not multiply
Classical tensor-product codes have distance . Hypergraph products have the minimum. Expecting 9 from two Hamming codes is the classic slip.
Matching stops working
In Hamming × Hamming a qubit sits in up to four checks of each type, so one error can flip four detectors. The DEM is no longer a graph. Use BP-OSD (Belief propagation and BP-OSD). Matching needs every qubit in at most two checks of each type, and in a product that forces both inputs to be repetition codes.
Transposes count
Swapping in , or adding a redundant check, changes and , and with them and the distance. A cyclic repetition code is not “the same code” as the open one here.
Bivariate bicycle codes and the gross code trades the product structure for shift symmetry and gets far larger distances at the same .
QThe hypergraph product of two [7, 4, 3] Hamming codes has k = 16. Is its distance 3 or 9?
A3. The distance is , not a product. One Hamming codeword laid along a single line of the grid is already a logical. Brute force on ⟦58, 16, 3⟧ gives .
0123456789101101234512 × 6 torus; each site holds an L and an R qubitoppositeedgeswrap
Two commuting sums of shifts on an torus give and . Weight-6 checks with a few long-range links make ⟦144, 12, 12⟧, the gross code: 12 logical qubits on 288 physical qubits.
What it is
Let be the cyclic shift. Set and : two commuting permutations with . Pick and as sums of three monomials in and , and define the CSS code on qubits
The checks commute because : all monomials commute. Every check has weight 6, and every qubit sits in three and three checks.
On the torus, think of sites, each holding an L qubit (left block) and an R qubit (right block). Each site also holds one check and one check, so the Tanner graph is a lattice with four nodes per cell. A monomial is a translation. The check at site is a fixed six-qubit shape moved to (figure). For the gross code, ,, and . The steps ,, and are short, but and jump three sites. Laid flat on a chip, these jumps and the torus wrap-around become long couplers. A family that keeps beating the surface code needs such links: with short links in a plane, Bravyi–Poulin–Terhal cap at (Hypergraph product codes).
Bravyi et al. prove and show that and distances are equal (Lemma 1). They found good and by computer search. The name echoes the bicycle codes of MacKay, Mitchison and McFadden, built from one random sparse cyclic matrix as , with some rows then deleted (Sec. 4.6); here there are two commuting shifts, hence bivariate.
The check at site (2, 1) uses the transposed shape. It acts on L qubits (0, 1), (1, 1), (2, 4) and R qubits (2, 0), (2, 5), (11, 1). The last one wraps around the torus from back to .
The family in Table 3
These are the codes from Table 3 of Bravyi et al., as Deltakit parameters, with computed from the paper’s distances:
code
,
m_A_powers, m_B_powers
⟦72, 12, 6⟧
6, 6
[3,1,2], [3,1,2]
6.0
⟦90, 8, 10⟧
15, 3
[9,1,2], [0,2,7]
8.9
⟦108, 8, 10⟧
9, 6
[3,1,2], [3,1,2]
7.4
⟦144, 12, 12⟧
12, 6
[3,1,2], [3,1,2]
12.0
⟦288, 12, 18⟧
12, 12
[3,2,7], [3,1,2]
13.5
For all five, our script confirms that and match, that , that , that the rank count of equals , and that the weights and degrees are 6 and 3. A rotated surface code has . Twelve of them, one per logical qubit, need qubits. The gross code needs 288 with one ancilla per check. At a similar size, the hypergraph product of two Hamming codes reaches only , against 6 for ⟦72, 12, 6⟧: shift symmetry buys distance that products do not.
What the paper reports
All of the following is from simulations with circuit-level noise, not from a device [PUBLISHED, Nature 627, 778 (2024); Bravyi et al., v2 checked 2026-11-09].
The Tanner graph has thickness at most 2: it splits into two planar layers of degree-3 couplers (Lemma 2, Sec. 4).
One syndrome cycle needs 7 layers of CNOTs, whatever the code length.
The v2 abstract puts the threshold at about 0.8% (the Nature version says 0.7%); the decoder is BP-OSD (Section 3). The pseudo-thresholds in Table 1 run from 0.48% to 0.69%; only the 144- and 288-qubit codes come close to 0.7%.
At a physical error rate of 0.1%, the gross code keeps its 12 logical qubits for nearly a million syndrome cycles on 288 qubits. The surface code would need nearly 3,000 qubits for the same.
The syndrome circuit costs distance. Table 1 bounds the circuit-level distance of the gross code by 10, below its code distance of 12.
IBM’s roadmap builds Starling, planned for 2029 with 200 logical qubits and gates, on these codes; the post names the gross code ⟦144, 12, 12⟧ and the two-gross code ⟦288, 12, 18⟧ [VENDOR, IBM 2025, 2025-06-10].
In Deltakit
from deltakit.explorer.codes import BivariateBicycleCode. The powers follow and .m_Hx is exactly , built with , and m_Hz is exactly . Column of each block is the site . So the check at acts on L qubits ,, and on R qubits ,,, all mod .
css_code_memory_circuit accepts these codes. For the gross code it builds 288 qubits with 9 time steps per round, 7 of them CNOT layers, and 864 two-qubit gates per round, which is simply 144 checks with six CNOTs each. That depth matches the paper’s count of seven, but we have not checked that it is the same schedule. A -basis memory of the gross code gains 144 detectors per round.
Traps
Returned logicals are not the distance
The middle line above says 12, but Table 3 lists for this code. Our random search (seed 2026, 400 column orders) finds a weight-10 logical. There is no distance attribute, and the returned weights are only upper bounds. For the other four Table 3 codes they happen to equal . The basis is not chosen to be light either: the gross code’s twelve logicals weigh 12, 12, 24, 24, 26, 26, 28, 34, 34, 36, 36 and 38. A randomised search can only ever confirm an upper bound, never a lower one.
[3, 1, 2] twice does not mean
The same list gives but : and swap roles. Read the convention before translating a paper’s polynomials.
Two matrices for one code
Do the algebra with m_Hx and m_Hz. parity_check_matrices holds the same checks, but its columns are the data qubits sorted by coordinate, mixing L and R, and its rows come in set order. Its two halves are not and and do not commute, although still holds.
Matching refuses these DEMs
One circuit fault can flip many detectors, so the DEM does not decompose into edges (Detector error models). With SI1000 noise and 2 rounds, the ⟦72, 12, 6⟧ DEM has 4,284 rows, and 4,032 of them flip more than two detectors, up to 9. The gross code doubles that: 8,568 rows, 8,064 of them beyond a graph. Decode with BP-OSD or Relay-BP (Belief propagation and BP-OSD). In Deltakit 0.10.2 BPOSDecoder runs only in the cloud.
QBivariateBicycleCode(9, 6, [3, 1, 2], [3, 1, 2]) returns logicals of weight 12 or more. Is its distance 12?
ANo. Returned weights only bound from above. Bravyi et al. list this code as ⟦108, 8, 10⟧, and a random search (seed 2026) finds a weight-10 logical. Distance is a minimum over all logicals, not over one returned basis.
one round, left to rightreset1q gate2q gatereadoutidleidle at M, RSD6SI1000Toyphen.gates are perfect
A noise model places the faults of a syndrome round, relative to one number . SD6 puts on every operation; SI1000 makes readout , reset and one-qubit gates ; phenomenological noise keeps only data and readout flips.
Three levels, one letter
Noise models come at three levels of detail:
Code capacity. Only the data qubits fail, once, and the syndrome is read perfectly. Useful for comparing codes, not circuits.
Phenomenological. In every round, each data qubit fails with probability and each syndrome bit is misread with probability . The gates in between are perfect, so a fault never spreads.
Circuit level. Every reset, gate, idle step and readout can fail, and a fault spreads through the CNOTs that follow it. Hook errors and the diagonal edges of the decoding graph exist only at this level.
The letter changes meaning between levels, and even between two circuit-level models. In SD6 it is the error rate of every operation. In SI1000 it is the two-qubit gate rate, and the other rates are multiples of it. In a phenomenological model it is a per-round data error that already lumps a round of gates together. A “threshold of 1%” and a “threshold of 0.5%” from two papers can describe the same hardware.
Where the faults go
Both circuit models come from the honeycomb-memory paper, Gidney et al. 2021, Table 2. SD6 (“standard depolarizing”, six steps per honeycomb cycle) is the baseline that most of the literature uses. SI1000 (“superconducting inspired”, a cycle of about 1000 ns) models chips on which readout and reset take about ten times longer than gates. Each rule describes one noisy operation, and the rules stack. A qubit idling next to a readout gets both the idle channel and the resonator-idle channel.
location
SD6
SI1000
Toy
two-qubit gate
one-qubit gate
reset
readout flip
idle
idle during M, R
Deltakit writes these as Stim channels after compiling the circuit to its default native gates (H, CX, R, M):
gate and idle faults are DEPOLARIZE1 or DEPOLARIZE2;
reset faults are X_ERROR (Toy: DEPOLARIZE1);
a readout fault is a flip of the recorded bit, M(0.005) at . ToyNoise also depolarizes each measured qubit at right after the readout.
It departs from the paper in two small ways. It compiles to CX where SI1000 assumes CZ. And the paper flips the qubit before measuring it, while Deltakit flips the record. In a memory circuit, where every ancilla readout is followed by a reset, the two give the same statistics.
Worked example: the fault budget of one memory
Take the rotated surface code with three rounds at : 17 qubits and 25 time steps. Summing the probabilities of all channels gives the expected number of faults per shot. Seventeen channels (34 for ToyNoise) come after the final readout and cannot change any outcome, so we leave them out.
share of faults
SD6
SI1000
faults per shot
0.336
0.395
readout flips
9.8%
41.8%
reset flips
9.8%
16.7%
idling during M, R
10.7%
19.1%
two-qubit gates
21.4%
18.2%
one-qubit gates, other idling
48.2%
4.1%
SD6 spends half its budget on single-qubit faults. SI1000 spends 42% on readout, and 36% more on resets and the qubits waiting for them. ToyNoise has only 0.130 faults per shot, 55.5% of them on two-qubit gates. Readout flips mostly become time-like edges of the decoding graph, gate faults space-like and diagonal ones. So the models stress different parts of the decoder. In the graph, SI1000’s time-like edges carry , against – under SD6 (see From DEM to decoding graph).
The failure counts (seed 2026, rounds , PyMatching, 200,000 shots) show what that does:
model
ratio
SD6
515
186
2.8 ± 0.2
SI1000
730
177
4.1 ± 0.4
Toy
96
14
6.9 ± 2
SI1000 fails 1.4 times as often as SD6 at , a gap. At the two tie within noise (186 vs 177), and at too (55 vs 48), because SI1000’s failures fall faster with distance. The ratio column carries Poisson errors. A single comparison at one distance does not tell you which model is “harsher”.
Choosing a model
SD6 when you compare with published thresholds and values. Much of the literature quotes it, and its is easy to state.
SI1000 when you want the budget of a superconducting chip: slow, noisy readout and quiet single-qubit gates. It is also the only model here with leakage.
ToyNoise for quick tests. It is light, so small codes already fail rarely.
Phenomenological when you develop a decoder and want time-like and space-like edges without circuit details such as hook errors.
None of them is hardware. Real devices have spread from qubit to qubit, crosstalk and leakage. An error budget fitted to a device (see Error budgets) replaces the single with a rate per operation.
In Deltakit
The models live in deltakit.explorer.qpu. Each is a keyword-only dataclass handed to a QPU, which compiles the circuit and inserts the channels. The snippet counts the expected faults per shot up to the final readout:
from deltakit.circuit.gates import PauliBasisfrom deltakit.explorer.codes import ( RotatedPlanarCode, css_code_memory_circuit)from deltakit.explorer.qpu import ( QPU, SD6Noise, SI1000Noise, ToyNoise)mem = css_code_memory_circuit( RotatedPlanarCode(3, 3), num_rounds=3, logical_basis=PauliBasis.Z)NOISY = {"DEPOLARIZE1", "DEPOLARIZE2", "X_ERROR", "M"}def budget(model): qpu = QPU(mem.qubits, noise_model=model) sc = qpu.compile_and_add_noise_to_circuit( mem).as_stim_circuit() ops = list(sc.flattened()) last = max(i for i, o in enumerate(ops) if o.name == "M") total = readout = 0.0 for o in ops[:last + 1]: args = o.gate_args_copy() if o.name not in NOISY or not args: continue n = len(o.targets_copy()) if o.name == "DEPOLARIZE2": n //= 2 total += n * args[0] if o.name == "M": readout += n * args[0] return total, readoutfor m in (SD6Noise(p=1e-3), SI1000Noise(p=1e-3), ToyNoise(p=1e-3)): t, r = budget(m) name = type(m).__name__ print(f"{name:12s}{t:.4f} {r:.4f}")
ToyNoise(p, p_measurement_flip=…) lets you set the readout rate separately. SI1000Noise(p=…, pL=…) also switches on leakage (see Leakage).
Traps
Phenomenological noise needs its I gatesPhenomenologicalNoise hangs its data noise on the identity layer that each round contains. compile_and_add_noise_to_circuit compiles that layer away. At only the 33 readout flips survive. Keep the circuit’s own gates with QPU(qubits, ExhaustiveGateSet(), noise_model=…).add_noise_to_circuit(circ). That gives 27 DEPOLARIZE1 kicks (9 data qubits × 3 rounds) and 33 readout flips: 0.06 expected faults per shot at .
Qubit order changes seeded results.QPU(code.qubits, …) and QPU(circ.qubits, …) give the same channels and the same DEM, but list the qubits in a different order. With the same seed, SD6 at then fails 525 times instead of 515. Pick one and keep it.
One shared default gate set. Building a phenomenological QPU adds I to the default native gate set, which every later QPU shares.
Channels after the final readout. Counting every channel inflates the SD6 budget from 0.336 to 0.353.
Related cards: Leakage adds a non-Pauli process on top of SI1000. Detector error models turns these channels into the decoder’s input, and Error budgets asks which of them dominates the logical error.
QAt p = 10⁻³ a d = 3 surface-code memory fails 515 times in 200,000 shots under SD6 and 730 times under SI1000. Is SI1000 the harsher model?
ANot in general. At the counts are 186 (SD6) and 177 (SI1000). Going from to divides the SI1000 failures by 4.1 but the SD6 failures by only 2.8. The same means different things in different models, so compare them at the distances you care about.
deltakitCircuitCircuitDetectorErrorModelTypeError+ its own circuit
Deltakit ships its own Stim build, imported as deltakit_stim. It adds leakage gates and is the only Stim installed, so tools that check for upstream stim classes, such as PyMatching’s constructors, reject its objects.
What the fork is
deltakit-stim (0.2.7 here) is a build of Stim with extra gates, published by Riverlane as part of Deltakit. Import it under the usual name:
import deltakit_stim as stim
The API is Stim’s: Circuit, DetectorErrorModel, TableauSimulator, FlipSimulator, the samplers. The classes live in a compiled submodule picked at import time: deltakit_stim._stim_polyfill on any Mac (this course’s is arm64), deltakit_stim._stim_sse2 on Linux x86. So here type(stim.Circuit()) prints deltakit_stim._stim_polyfill.Circuit. In this course’s environment upstream stim is not installed at all: importlib.util.find_spec("stim") returns None. That is deliberate. One Stim means one set of classes.
reset of leakage only: a leaked qubit returns in a random state
0
HERALD_LEAKAGE_EVENT
noise that records a measurement: 1 if leaked
0 or 1
HERALDED_ERASE and HERALDED_PAULI_CHANNEL_1 also parse, but those come from upstream. What the leakage gates do to samples is on the Leakage card. Upstream Stim cannot parse a circuit that contains them.
You meet the fork whether you import it or not. as_stim_circuit() always returns a fork object, and every SI1000Noise(pL>0) circuit needs the leakage gates. For everything else it behaves like Stim: the DEMs, samplers and tableau tools on the other cards of this module all run on it.
Why the two are not interchangeable
Many tools in the Stim ecosystem take Stim objects and check their type. PyMatching 2.4.0 is the one you will meet first. On a surface-code memory ( basis, three rounds, SI1000 at , 24 detectors, 286 DEM rows):
Matching.from_detector_error_model(dem) raises a TypeError: the model “must be a stim.DetectorErrorModel”. The message then names the class it got and adds that the stim package isn’t installed.
Matching.from_stim_circuit(sc) raises the same for stim.Circuit.
Matching(dem) fails differently, inside SciPy: ValueError: scipy.sparse does not support dtype object. Not recognising a Stim object, PyMatching tries to read it as a check matrix.
The two DetectorErrorModel classes print the same text format. Python’s isinstance does not care: it compares classes, and a class defined in deltakit_stim is not the one defined in stim. Duck typing would work; a type check does not. PyMatching checks types at its entry points, so the failure comes at the first call, with a clear message.
Two routes work.
Through text. Both libraries speak Stim’s text formats. dem.to_file(path) followed by Matching.from_detector_error_model_file(path) gives a matcher with 24 detectors and 78 edges. sc.to_file(path) with Matching.from_stim_circuit_file(path) gives identical predictions. On 50,000 shots sampled from sc, it fails 712 times.
Through Deltakit.deltakit.decode.PyMatchingDecoder.construct_decoder_and_stim_circuit(noisy) takes the Deltakit circuit and returns a decoder and a circuit. 50,000 shots sampled from that circuit fail 695 times. The two counts come from different samples, so they are not a comparison of decoders.
The decoder’s circuit is not yours
For this memory the returned circuit has 16 detectors, not 24: it keeps only the 4 checks, out of 8 checks, because the logical depends on nothing else. Feed it shots from your own circuit and PyMatching stops with a ValueError: the shots array “should have at least 16 columns (the number of detectors), and no more than 17 columns (the number of nodes), but instead has 24 columns”.
Knowing which side you are on
Three checks tell you where an object comes from:
importlib.metadata.version("deltakit-stim") gives the fork’s version, 0.2.7 here.
importlib.util.find_spec("stim") returns None when upstream Stim is absent.
type(obj).__module__ of a circuit or DEM starts with deltakit_stim. for fork objects (_stim_polyfill on a Mac, _stim_sse2 on Linux x86).
If a traceback asks for stim.DetectorErrorModel while your object’s module is the fork’s, you have crossed the boundary.
Crossing between deltakit.circuit and deltakit_stim
deltakit.circuit.Circuit.as_stim_circuit(qubit_mapping=None) goes one way, Circuit.from_stim_circuit(stim_circuit, qubit_mapping=None) the other. The physics survives the round trip; the object does not. For the noisy circuit above:
the DEM text after from_stim_circuit(sc).as_stim_circuit() is identical;
the circuit text differs in 15 of 137 lines: R and H targets come back reordered (H 1 10 15 7 becomes H 10 1 15 7), and so do the rec targets of five DETECTORs;
qubits come back as Qubit(Coordinate(0.0, 2.0)) instead of Qubit(Coord2D(0, 2)); the two compare (and hash) equal;
yet == with the original is False. The importer rebuilds the layers from Stim lines, so the layer structure changes: the noisy circuit’s 100 top-level layers come back as 96. On the noiseless memory, a GateLayer that mixes CX and CZ comes back as two layers (48 become 62).
Seeded samples survive the round trip: 50,000 shots at seed 2026 are identical before and after. What changes seeded samples is qubit numbering (the Circuit noise models card measures 525 vs 515 failures for two qubit orders). Pick one object, sample from it, and compare DEMs rather than circuits. Equality depends on layer structure, not size: a 20-qubit hand-built circuit with one gate type per layer round-trips with ==, a 2-qubit one with RZ and H in one layer does not.
TypeError: `model` must be a `stim.DetectorErrorModel.
24 detectors, 78 edges
failures: 712
Traps
import stim fails here, and where both are installed, mixing them fails later and less clearly. Keep one alias in every file.
Leaky circuits are fork-only. Upstream tools that parse circuit text reject LEAKAGE, RELAX, RL and HERALD_LEAKAGE_EVENT; strip them before export, knowing the result is a different model.
Save text, not objects. Write circuits and DEMs with to_file; the text format is shared by both builds, the Python classes are not.
No sinter here. Upstream’s batch-sampling tool is not installed either; deltakit.decode.analysis.StimDecoderManager runs the sample-and-decode loop.
Related cards: Sampling with Stim, Leakage, Matching and PyMatching, and The Deltakit package map.
QPyMatching’s from_detector_error_model raises a TypeError on a DEM from deltakit_stim. Name two ways to get a working matcher.
AWrite the DEM to a file with dem.to_file(path) and call pymatching.Matching.from_detector_error_model_file(path). Or build PyMatchingDecoder.construct_decoder_and_stim_circuit(noisy) from the Deltakit circuit, and sample from the circuit it returns.
measurement record, oldest to newestMR 2MR 2M 0M 1recordrec[-1]rec[-2]rec[-1]rec[-3]rec[-2]rec[-1]rec[-2]
A detector is a parity of measurement outcomes that is fixed when nothing goes wrong; it fires when a fault flips it. rec[-k] counts back from the newest measurement. An observable is the parity that carries the logical value.
What a detector promises
A detector is a set of measurement outcomes whose XOR is deterministic in the noiseless circuit. In a noisy shot the detector fires when that XOR differs from its noiseless value. You never write the expected value down. Stim computes it with one noiseless reference run (Gidney 2021) and reports every detector as a flip relative to it, so a noiseless circuit samples all zeros.
An observable is a set of outcomes whose XOR equals a logical operator’s value in the noiseless circuit. OBSERVABLE_INCLUDE(k) adds records to observable , and repeated lines accumulate by XOR. Including the same record twice cancels it: after X_ERROR(1) 0, an observable built from rec[-2] twice reports no flip.
The two play opposite roles. Detectors are what the decoder sees. Observables are what it must predict. A memory fails when its predicted observable flip differs from the true one. Neither changes the quantum state; both are bookkeeping on the measurement record.
rec[-k] by hand
A DETECTOR line refers to measurements by lookback: rec[-1] is the most recent result at the point where the line appears. The Stim circuit format calls this the measurement record, an append-only log. Because the record grows, the same measurement changes name as the circuit goes on. The circuit in the figure is a two-qubit repetition code with one ancilla:
Call the four outcomes (ancilla, rounds 1 and 2) and (qubits 0 and 1). Then:
D0. A first-round check on is certain to read .
D1. This is the same check in consecutive rounds, the bulk pattern of every memory.
D2. The data readout recomputes , and D2 compares it with the last ancilla result.
L0. For a repetition code a single data qubit already carries .
Inserting one fault at a time with probability 1 tells you which detectors each fault fires:
fault
fires
L0 flipped
on before round 1
D0
yes
on between rounds
D1
yes
on between rounds
D1
no
on before readout
D2
yes
wrong ancilla outcome, round 1
D0, D1
no
wrong ancilla outcome, round 2
D1, D2
no
A data error fires the next comparison of the check that contains it. A wrong ancilla outcome fires two consecutive comparisons of its own check, a time-like pair. Notice rows two and three: both fire only D1, but only one flips L0. With errors of 0.01 on the data, the DEM keeps them as two rows, error(0.01) D1 L0 and error(0.01) D1. A decoder that sees D1 alone must guess which one happened, which is exactly the decoder’s dilemma (see Detector error models).
When a detector is not deterministic
Stim checks determinism when it builds the DEM. Three failures we reproduced:
R 0, MX 0, DETECTOR rec[-1]: an measurement of . The DEM stops with ValueError: The circuit contains non-deterministic detectors. The sampler still runs and reports the detector firing in 51% of shots, which is worse than useless.
A first-round -check detector after resets: the same error. Comparing the check across two rounds fixes it, and the noiseless toy’s DEM becomes plain detector D0.
A random observable gives the same error for observables.
A lookback past the start parses (M 0, DETECTOR rec[-2]). It only fails when you build the DEM or sample, with Referred to a measurement result before the beginning of time. rec[0] is a parse error: lookbacks are negative.
Where memory circuits put them
For the rotated surface code with three rounds, css_code_memory_circuit declares 24 detectors in four time layers of 4, 8, 8 and 4. That is :
First round: only the 4 checks of the memory basis. For memory they sit at ; for memory at . The other 4 checks start random.
Bulk: all 8 checks, each compared with its previous round.
Final: the 4 checks recomputed from the data readout.
The -memory observable is three data readouts, OBSERVABLE_INCLUDE(0) rec[-8] rec[-6] rec[-2]: a string of weight .
Memory circuits also give every detector coordinates, written DETECTOR(x, y, t) rec[…]. They do not change the parity. get_detector_coordinates() returns them, and the layer counts above come from their values. Plots and decoding-graph tools use them too; Deltakit’s Detector takes them as coordinate=.
One observable per logical
A code with logical qubits gets observables in a memory experiment, one per logical operator you protect. Any representative of will do. Two representatives differ by a product of checks, and the final detectors already fix the values of those checks. Changing the representative therefore changes which faults are booked as flipping , but not whether a decoded shot fails.
Two consequences:
Few faults touch the observable. Only faults that cross the chosen string flip it. In the decoding graph, just 8 of 78 edges carry (see From DEM to decoding graph).
Observables must be deterministic too. An observable on an measurement of stops the DEM with The circuit contains non-deterministic observables.
In Deltakit
deltakit.circuit has its own Detector, Observable and MeasurementRecord types, which become DETECTOR and OBSERVABLE_INCLUDE lines in as_stim_circuit():
R 0 1 2
TICK
CX 0 2
TICK
CX 1 2
TICK
M 2
TICK
DETECTOR rec[-1]
M 0 1
DETECTOR rec[-3] rec[-1] rec[-2]
OBSERVABLE_INCLUDE(0) rec[-2]
Two details: a TICK separates consecutive GateLayers (there is none after the last), and the order of records inside a detector is not kept. Order does not matter for an XOR.
Related cards: Detector error models builds on these lines, Syndrome extraction schedules and hook errors explains which faults reach which detector, and Sampling with Stim returns them as arrays.
QA memory circuit starts with all data qubits reset to |0⟩. You add a DETECTOR on the very first outcome of an X-type check. What does Stim do?
AIt refuses to build the DEM: ValueError: The circuit contains non-deterministic detectors. That outcome is a fair coin even without noise (the sampler reports it firing in about half the shots), so no fault can be read from it. Compare the X check across two rounds instead; that detector is deterministic.
mechanisms in the circuitD0 D1 : 0.01D0 D2 : 0.005D2 L0 : 0.0296detector error modelall the decoder sees
A detector error model (DEM) lists every independent error mechanism by its symptoms: the detectors and observables it flips, plus its probability. Mechanisms with identical symptoms merge. The decoder sees only this table.
What goes in and what comes out
The input is a Clifford circuit with Pauli noise channels, annotated with DETECTOR and OBSERVABLE_INCLUDE lines (see Detectors and observables). The output is a list of rows of the form error(p) D… L…. Each row is one error mechanism: a Pauli fault that happens with probability , independently of every other row. Stim’s format calls the detectors a row flips its symptoms, and the observables it flips its frame changes.
Stim builds the table in three moves:
It splits every noise channel into Pauli terms.
It finds the measurements each term flips by propagating it through the Clifford gates. (Stim actually walks backwards from the detectors; the result is the same.) By Gottesman–Knill this is cheap and deterministic.
It marks a detector as flipped when an odd number of its measurements flip.
Rows with the same symptoms and frame changes are then merged. Two independent mechanisms produce a visible flip only when exactly one of them fires, so the merged probability is
Channels that are disjoint mixtures are first rewritten as independent ones. DEPOLARIZE1(p) applies exactly one of ,,, each with probability . Stim instead writes three independent rows, each with . That is 0.010102 rather than 0.01 at ; we checked the formula against Stim’s output to all printed digits.
Assumptions, and what breaks without them
Pauli noise on a Clifford circuit. This is what gives every mechanism a fixed set of symptoms. Coherent over-rotations and leakage are not Pauli faults, so a DEM can carry only a Pauli approximation of them (see Leakage).
Independence between rows. Correlated faults must be written as one mechanism, for example a DEPOLARIZE2 term or a CORRELATED_ERROR, never as two rows that happen to co-occur.
Deterministic detectors. If a detector’s parity is random even without noise, there is nothing for a fault to flip. Stim stops with ValueError: The circuit contains non-deterministic detectors. In hand-written circuits this is the most common bug. Typical causes are comparing measurements taken in different bases, or putting a first-round detector on an -type check right after a -basis reset.
One shot, not one round. Every probability in a DEM is for the whole circuit. Rates per round come later (Logical error per round).
Worked example: three data qubits and one round of checks
The circuit in the next section is a three-qubit bit-flip code:
data qubits and ancillas ;
one round of and checks, then a final data readout;
X_ERROR(0.01) on every data qubit before the checks and again before readout;
a 0.5% ancilla readout error and a 2% data readout error.
That is eleven mechanisms. The DEM has eight rows:
D0 D1 (0.01): on before the checks trips both checks. This is a space-like edge.
D0 D2 (0.005): a misread ancilla fires its first-round detector and the final comparison. This is a time-like edge.
D0 L0 (0.01): on before the checks fires and flips the logical readout. stays quiet, because the final data parity agrees with the flipped ancilla.
D2 L0, D2 D3 and D3 (0.0296 each): a late and a readout flip on the same data qubit are indistinguishable, so each pair merges.
The merge, by hand. As a matching weight, , this is 3.49, against 4.60 for the unmerged 0.01 rows. Merged edges are cheaper, so the decoder prefers them.
Decomposition: the road to a decoding graph
Matching needs every row to flip at most two detectors, so that it can be drawn as an edge. In the surface code, a fault trips an -type pair and a -type pair. detector_error_model(decompose_errors=True) asks Stim to split such rows into graphlike pieces separated by ^. Stim’s format calls this a suggested decomposition: the row is still one mechanism.
For the , three-round SI1000 memory at :
without decomposition, 221 rows, by number of detectors flipped: 24, 84, 76 and 37 rows for 1, 2, 3 and 4;
with decomposition, 290 rows, 212 of which contain ^.
The 290 collapse back to exactly 221 distinct net symptom sets. The extra rows are the same symptoms with different suggested splits, which Stim keeps apart. When decomposition is impossible, Stim raises Failed to decompose errors into graphlike components. Bivariate bicycle codes, with up to 9 detectors per row, do this, so matching is ruled out before it starts.
In Deltakit
Deltakit ships its own Stim build. Import it as deltakit_stim, never upstream stim:
For a Deltakit circuit, use noisy.as_stim_circuit().detector_error_model(decompose_errors=True). deltakit.core.decoding_graphs turns a decomposed DEM into the graph that matching works on. Node 4 is the added boundary:
from deltakit.core.decoding_graphs import ( dem_to_decoding_graph_and_logicals,)g, logicals = dem_to_decoding_graph_and_logicals( dem)n, m = len(g.nodes), len(g.edges)print(n, "nodes,", m, "edges")print("boundary:", set(g.boundaries))flips = sorted(tuple(e) for e in logicals[0])print("flip L0:", flips)
Two DEM types that look the samepymatching.Matching.from_detector_error_model(dem) rejects a deltakit_stim DEM, because it checks for upstream stim classes. Use PyMatchingDecoder. Or write str(dem) to a file and call pymatching.Matching.from_detector_error_model_file.
The decoder’s DEM is not yoursPyMatchingDecoder.construct_decoder_and_stim_circuit drops detectors that no logical depends on. For the memory, that is 24 → 16. Sample from the circuit it returns, not from your own.
Checks before trusting a DEM
Compare dem.num_detectors and dem.num_observables with the circuit’s, and dem.num_errors with the size you expect for the code and noise model.
Watch for rows with zero symptoms but an L. These are undetectable logical errors, and no decoder can fix them.
A DEM certifies only that the circuit’s model is self-consistent. It says nothing about whether the hardware’s noise is Pauli and independent. For the format itself, see the Stim DEM specification and Gidney 2021. The next card, From DEM to decoding graph, turns these rows into weighted edges.
Matching needs every DEM row to flip at most two detectors. Each graphlike piece becomes an edge, a one-detector piece an edge to a boundary node, weighted . Pieces with the same endpoints merge into one edge.
From rows to edges
A decoding graph has one node per detector plus a virtual boundary node. Every error mechanism of the DEM that flips two detectors is an edge –. One that flips a single detector is an edge –boundary, because its partner flip went off the edge of the code. Each edge carries a probability and the set of observables it flips. A shot’s detection events are then the endpoints, counted mod 2, of the edges that fired.
Matching looks for the most likely set of edges with exactly those endpoints. If edges fire independently, a set has probability proportional to . Taking turns the product into a sum of weights
so the most likely set is the one of minimum total weight. Space-time matching on such a graph goes back to Dennis et al. 2002. Rare edges are heavy: gives , gives .
Two steps turn a DEM into this graph.
Decompose. A row that flips three or four detectors (a fault trips an -type pair and a -type pair) is split into graphlike pieces, written with ^ in the DEM (see Detector error models).
Merge. Pieces with the same endpoints and observables become one edge. Two pieces flip the edge’s detectors only when exactly one of them fires, so probabilities combine as , applied repeatedly.
Worked example: the graph, piece by piece
Take the rotated surface code, memory, three rounds, SI1000 at . The figure draws a smaller patch over two rounds (11 detectors, 29 edges) so that every edge fits; the numbers here are for the full patch. The decomposed DEM has 290 rows. Splitting at every ^ gives 566 pieces: 78 rows have one piece, 152 two, 56 three and 4 four. Grouping by endpoints leaves 78 edges on 25 nodes: 24 detectors and the boundary node, numbered 24. In detail:
Boundary edges. 24 of the 78 edges touch the boundary, one per detector, and 54 are bulk edges. Detector degrees are 3, 5, 6 or 8.
Merging is heavy. Edges carry between 1 and 35 pieces. No edge mixes pieces that disagree on the observable, and every edge’s probability equals the XOR-merge of its pieces.
The lightest edge is detector 7 to the boundary: 34 pieces, the largest , merged to , so .
The biggest drop. Edge 9–13 has four pieces, none above (). Merged, and , about lighter.
The weights fall into four classes, in line with Lecture 4:
class
edges
weights
time-like (same check, next round)
16
4.87–4.88
boundary
24
3.90–5.93
space-like (two checks, one round)
18
5.09–6.06
diagonal (fault between CNOT layers)
20
6.84–8.23
The median weight is 5.26. Only 8 edges flip the observable , all to the boundary, with weights 4.35–5.59.
What the weights encode
Turn the weights back into probabilities and the noise model reappears. Under SI1000 a time-like edge has –. A readout flip at and a reset flip at on the same ancilla merge into it, together with smaller gate and idle terms. Under SD6, where readout and reset cost only each, time-like edges carry –. Diagonal edges are the rarest in both models, down to : only faults between particular CNOT layers make them, and decomposition halves some (see below). Boundary edges span the widest range, to , depending on how many faults at the patch edge share one detector.
So the same pair of detection events can get different explanations under the two models. Under SI1000, two events in one check one round apart look like a misread ancilla, and matching pays little for that. A decoder built for the wrong model still runs; it just weighs the explanations wrongly. Deltakit’s PyMatchingDecoder avoids that by building its graph from the noisy circuit you will sample.
The shortest path that flips without firing any detector has 3 edges, the code distance. Its smallest total weight is 13.9, so the single most likely logical error that fires no detector has odds of about . At the graph has 121 nodes and 502 edges (72 to the boundary), built from 4100 pieces. The lightest logical path has 5 edges and weight 24.1. Under SD6 at the same the graph has the same 78 edges, but its time-like weights rise to 5.31–5.55 and the lightest logical path to 14.3.
Hyperedges, and what decomposition loses
Without decomposition the same DEM has 221 rows: 24 flip one detector, 84 two, 76 three and 37 four. dem_to_hypergraph_and_logicals keeps them as a DecodingHyperGraph with 221 hyperedges, 36 of which flip . Matching cannot use this. Passing the raw DEM to the graph builder fails with ValueError: Edge of degree 3 cannot be converted to decoding edge.
Decomposition splits each row on its own, so two detectors stay correlated only if they land in the same piece. Six undecomposed rows flip both D9 and D13: four at and two at , each of which merges two faults. Together the pair fires with probability . The decomposed DEM writes the same faults as eight rows of . Four keep the pair in one piece, such as D9 D13 ^ D15. The other four split it into two boundary pieces, such as D13 ^ D9. The graph edge gets , half the truth, and so do all 8 diagonal edges at that value.
Sampled data side with the raw DEM. The method of Google Quantum AI 2021 estimates a pair probability from detection events alone. With firing rates , and joint rate ,
On 2,000,000 shots (seed 2026) it gives – on those 8 edges. Time-like and space-like edges lose less: the graph is at most 12% low there. Correlated decoders put the lost correlations back (see Correlated matching and BeliefMatching).
In Deltakit
deltakit.core.decoding_graphs builds the graph. dem_to_decoding_graph_and_logicals(dem) returns an NXDecodingGraph and one set of edges per observable. edge_records[e] holds p_err and weight.
import mathfrom deltakit.circuit.gates import PauliBasisfrom deltakit.core.decoding_graphs import ( dem_to_decoding_graph_and_logicals)from deltakit.explorer.codes import ( RotatedPlanarCode, css_code_memory_circuit)from deltakit.explorer.qpu import QPU, SI1000Noisemem = css_code_memory_circuit( RotatedPlanarCode(3, 3), num_rounds=3, logical_basis=PauliBasis.Z)qpu = QPU(mem.qubits, noise_model=SI1000Noise(p=1e-3))sc = qpu.compile_and_add_noise_to_circuit( mem).as_stim_circuit()dem = sc.detector_error_model( decompose_errors=True)g, logicals = ( dem_to_decoding_graph_and_logicals(dem))B = dem.num_detectorsbnd = [e for e in g.edges if B in tuple(e)]print(len(g.nodes), "nodes,", len(g.edges), "edges,", len(bnd), "to the boundary")w = lambda e: g.edge_records[e].weighte = min(g.edges, key=w)p = g.edge_records[e].p_errprint(sorted(tuple(e)), f"p={p:.4f}", f"w={w(e):.2f}", f"ln((1-p)/p)={math.log((1-p)/p):.2f}")print("L0 edges:", len(logicals[0]))
25 nodes, 78 edges, 24 to the boundary
[7, 24] p=0.0198 w=3.90 ln((1-p)/p)=3.90
L0 edges: 8
compute_graph_distance(g, logicals) returns the 3 above (weighted=True gives 13.9). g.to_parity_check_matrix() gives the node–edge incidence matrix, boundary row included.
Traps
The boundary is a real node index. It is dem.num_detectors (24 here), with coordinates in detector_records. Shot arrays have 24 columns, not 25.
Decompose first. The graph builder needs decompose_errors=True; the hypergraph builder takes either.
A merged weight is not a sum. Parallel pieces make an edge lighter, never heavier.
The graph is not the noise. Check its edges against from samples before you trust the weights; here 8 of them are off by a factor of 2.
Related cards: Matching and PyMatching runs on this graph, Belief propagation and BP-OSD on its hypergraph.
QFour graphlike pieces of a decomposed DEM connect D9 and D13; the largest has p = 6.67×10⁻⁵ (weight 9.62). What weight does the edge D9–D13 get?
AOne edge with the merged probability, (the chance that an odd number of the pieces fire), so . That is lighter than any single piece. Weights add along a path, never across parallel pieces. (The undecomposed DEM and sampled data put this pair at twice : four more decomposed rows split the pair.)
Stim runs the noiseless circuit once, then tracks each shot as a Pauli frame, many shots per machine word. compile_detector_sampler(seed=…) returns booleans, shots × detectors; bit_packed=True packs eight per byte, little-endian.
Tableau or frame
Stim has two ways to simulate a stabilizer circuit (see Clifford tableaux and Gottesman–Knill):
The tableau simulator (TableauSimulator) keeps the whole stabilizer state and updates it gate by gate. A random measurement costs (a deterministic one ). Use it for one shot you want to inspect: peek at an expectation value, postselect, branch on a result.
The frame simulator runs the noiseless circuit once with the tableau simulator to get a reference sample. Each shot is then stored only as its difference from that reference, a Pauli frame: one bit and one bit per qubit. A gate updates the frame with a few XORs, a noise channel XORs in a random Pauli, and a measurement reports the reference bit XOR the frame’s bit.
This is the main idea of Gidney 2021. Frames of many shots sit side by side in SIMD words, so one instruction updates a whole batch.
A two-qubit example makes it concrete. The noiseless circuit R 0 1, CX 0 1, M 0 1 has reference sample [0, 0]. Insert X_ERROR(1) 0 before the CNOT and run FlipSimulator(batch_size=4, …) with stabilizer randomization off. The flips are 1 on both measurements in all four shots: the CNOT copied the frame’s bit to qubit 1. The compiled sampler returns [1, 1] for every shot, the reference XOR the flips.
What a frame can carry
The frame trick needs Clifford gates and Pauli noise. Within that, Stim accepts more than plain gates:
Feedback.CX rec[-1] 1 applies to qubit 1 if the last result was 1. After X_ERROR(1) 0, M 0, that feedback flips qubit 1, so its detector fires in every shot and the DEM reads error(1) D0.
Leakage, in the fork, as random bits in the frame (see Leakage).
It refuses the rest at parse time. T 0 gives Gate not found: 'T'. There are no rotation gates either: RZ is a -basis reset in Stim, so RZ(0.1) 0 fails because a reset takes no argument. Coherent errors must first be approximated by Pauli channels.
Measurements taken elsewhere, such as on hardware, can be turned into detection events after the fact. circuit.compile_m2d_converter().convert(measurements=m, append_observables=False) applies the circuit’s DETECTOR lines to a measurement array. On 1,000 shots of a small test circuit it matches the XORs computed by hand.
The calls and their shapes
Take the repetition code with four rounds under SI1000 at : 11 measurements, 10 detectors, 1 observable. With six shots:
flag on det.sample(6)
returns
none
(6, 10) bool
separate_observables
(6, 10) and (6, 1) bool
append_observables
(6, 11) bool
bit_packed
(6, 2) uint8
packed and separate
(6, 2) and (6, 1) uint8
Here det is circuit.compile_detector_sampler(seed=…), and each flag is set to True. The measurement sampler, circuit.compile_sampler(seed=…), returns all 11 outcomes, (6, 11) bool. dem.compile_sampler(seed=…) returns a 3-tuple whose last item is None. With the same seed, separate_observables=True returns the same detector bits as a plain sample, and its observable column is the eleventh column of append_observables=True. The DEM sampler draws from the DEM rather than the circuit, which matters when the two disagree (see Leakage).
Bit packing
bit_packed=True stores detector as bit of byte , lowest bit first. In 2,000 shots of the circuit above, shot 8 fires D7 and D8, which packs to [128, 1]. np.unpackbits(…, bitorder="little") restores the booleans exactly. NumPy’s default, "big", turns the same two bytes into D0 and a padding bit, with no error raised.
Packing is also faster, 225 against 335 ns per shot in the timing below, probably because it writes eight times fewer bytes. It matters most at scale. For the surface code with five rounds (120 detectors), one million shots take 120 MB as booleans and 15 MB packed. PyMatching’s decode_batch accepts packed input too (bit_packed_shots=True).
Seeds
Probing the same circuit with seed 2026:
Recompiling with the same seed and calling sample(1000) gives identical arrays.
A second call on the same sampler continues the random stream, so its shots differ from the first call’s.
One call of 2,000 is not two calls of 1,000. The arrays differ, and so do the first 1,000 rows. Splits of 256 + 1,744 and 1,024 + 976 differ as well.
So a seeded result is reproducible only together with its batch sizes, and only on the same Stim version and the same kind of machine (SIMD width), as Stim’s docstring warns. Sweeps over round counts need one seed per run (see Logical error per round). Deltakit’s StimDecoderManager samples in batches of batch_size. With seed 2026, the SI1000 surface-code memory fails 730 times in 200,000 shots with batch_size=100_000, and 701 times with 50,000.
Speed, measured
Apple M4 Pro, macOS 15.7, Python 3.12, with other jobs running (load about 4), wall clock, median of three runs. The circuit is the surface code with five rounds under SI1000 at : 49 qubits, 145 measurements, 120 detectors.
method
per shot
detector sampler
335 ns
detector sampler, bit_packed
225 ns
measurement sampler
665 ns
TableauSimulator, do_circuit
35 µs
The frame sampler is about 100 times faster here. The tableau pays per random measurement and the frame a few bit operations per gate, so the gap should widen for bigger circuits. Constructing the sampler object takes 5 µs, construction plus one shot 19 µs, and one more shot on the same sampler 16 µs. So each sample call has a fixed cost, and the per-shot figures hold for large calls only.
In Deltakit
Deltakit circuits become deltakit_stim circuits with as_stim_circuit(), and sampling is plain Stim:
QYou sample 2,000 shots from a detector sampler compiled with seed 2026. Later you redo it with a fresh sampler, same seed, as two calls of 1,000 shots. Same data?
ANo. With the same seed, the output also depends on how the shots are split into calls; even the first 1,000 rows differ. To reproduce a run, keep the seed and the batch sizes. Recompiling with the same seed and the same calls gives identical arrays (on the same Stim build and machine type).
qubit subspaceRELAX, R, RLwhile leakedM does not return itM: random bitCX partner: randomherald reads 1DEM: no rowdropped
Leakage takes a qubit out of . It is not a Pauli fault, so a DEM ignores it: with SI1000Noise(pL=0.01) the DEM keeps 21 rows while the detection rate quadruples. Leakage removal and heralds are the remedies.
Leaving the qubit
A superconducting transmon is an anharmonic oscillator, and its “qubit” is only the lowest two levels. A two-qubit gate or a readout pulse can push population into or higher. That is leakage.
A leaked qubit is not a qubit with a Pauli error on it. No Pauli maps or to , and three things make leakage worse than a Pauli fault:
It lasts. The qubit stays leaked until it decays or is reset. A memory experiment never resets its data qubits, so they can stay leaked for many rounds.
It spreads. A gate that assumes two levels does something unplanned when one of them is outside, so the partner qubit is scrambled.
It hides. Readout of a leaked qubit gives a bit that carries no information, so the checks it takes part in fire at random.
The result is a cluster of detection events in space and time, the opposite of the independent rows a DEM assumes (see Detector error models). McEwen et al. 2021 traced such correlated errors to leakage on transmons. A reset that returns a qubit to from every higher level lowered the logical error rate of a bit-flip code and improved its scaling with size. Google’s leakage-removal experiment shows how hardware fights back. It removes leakage from every qubit in every cycle on a surface code and a bit-flip code. It reports a ten-fold reduction in the steady-state leakage of the data qubits, and an average leakage population below across the device [PUBLISHED, Nat. Phys. 19, 1780; Miao et al. 2023].
How deltakit_stim models it
The fork adds gates that upstream Stim lacks. We measured their behaviour in the samplers:
LEAKAGE(p) leaks the qubit with probability .
RELAX(p) returns a leaked qubit with probability , in a random state. R returns it too. M does not: a herald after M still reads 1.
A leaked qubit measures 0 or 1 with probability 1/2. A CX with a leaked partner, on either side, randomizes the other qubit.
HERALD_LEAKAGE_EVENT adds a measurement that reads 1 if the qubit is leaked, without touching it. With an argument , a leaked qubit’s herald is missed with probability .LEAKAGE(0.2) followed by a herald with reads 1 in 18.1% of shots.
SI1000Noise(p=…, pL=…) adds LEAKAGE(pL) after two-qubit gates and resets, and RELAX at three rates: after two-qubit gates, on one-qubit gates and idling, and on qubits idling while others are read out or reset. On the repetition code with three rounds, and , that is 33 LEAKAGE targets and 59 RELAX targets. It emits no heralds.
Worked example: what the detectors see
Same repetition code, , 200,000 shots, seed 2026. The DEM text is identical at and : 21 rows, which predict a detection rate of 0.0187. The circuit itself gives:
rate by round
mean
0
0.012, 0.022, 0.022, 0.018
0.0185
0.01
0.041, 0.081, 0.092, 0.084
0.0744
Over ten rounds the bulk rate climbs from 0.081 to 0.160, while it stays flat at 0.022 without leakage. Leaked qubits pile up faster than they relax.
To see who is leaked, append HERALD_LEAKAGE_EVENT on every qubit at the end of the circuit, each with its own DETECTOR. After ten rounds:
Data qubits are leaked with probability 0.094 and 0.095 at the ends, and 0.164 in the middle. The middle one takes part in two CNOTs per round.
Ancillas sit at 0.029, because their reset clears them every round.
Shots with a herald (35% of all shots) show a detection rate of 0.231, against 0.056 in shots without one.
You can predict the leaked fractions without sampling. Leakage cannot spread to a partner here, so each qubit is a two-state chain on its own: LEAKAGE(p) moves of the probability into ,RELAX(r) moves back, and a reset empties it. Walking that rule along the circuit gives 0.165 for the middle data qubit after ten rounds, 0.095 at the ends and 0.029 for the ancillas. All five are within 0.001 of the heralds. After 200 rounds the chain gives 0.41 and 0.35. At this , a leaked data qubit is the normal state of a long memory, not a rare event.
A matching decoder built from the DEM ignores all of this. Failures per 200,000 shots, rounds :
3
90
4654
5
6
2561
7
0
1961
Distance still helps, but slowly. Lecture 4 shows the surface-code version: at , no longer beats .
In Deltakit
Leakage is switched on in deltakit.explorer.qpu.SI1000Noise; the gates are deltakit.circuit.gates.HERALD_LEAKAGE_EVENT and the channel deltakit.circuit.noise_channels.Leakage. The trap, in two lines of output:
pL=0.0: 21 rows, circuit 0.0185, DEM 0.0187
pL=0.01: 21 rows, circuit 0.0744, DEM 0.0187
Traps
The DEM is blind. It is the same object with and without leakage. Check a leaky model by sampling the circuit, never the DEM.
Heralds do not make a plain DEM. Add the same end-of-circuit heralds to the three-round circuit and its DEM grows from 21 to 37 rows. Sixteen are conditional: error(0.125) D0 D2 D9 means “if herald D9 fires, D0 and D2 fire with probability 0.125”. The fork’s help text says reading them needs “knowledge of which detectors are heralding detectors”, and that a herald must sit before its measurement. With end heralds the rows do not even match the samples: , not 0.125. A matching decoder would read them as independent faults.
Short runs underestimate long ones. The bulk detection rate keeps climbing with the number of rounds, so a logical error per round measured over three rounds is likely too optimistic for thirty (see Logical error per round).
TableauSimulator ignores leakage.R, LEAKAGE(1), a herald and M give the record [False, False]: the herald reads 0.
SI1000Noise takes keywords only.SI1000Noise(1e-3) raises a TypeError.
Riverlane’s local clustering decoder adapts in real time to heralded leakage events, and its paper is the source of the SI1000Noise leakage model. It reports one million error-free operations with four times fewer physical qubits, under a circuit-level noise model in which leakage dominates [PUBLISHED, Nat. Commun. 16, 11048 (2025); Ziad et al.].
Related cards: Circuit noise models: SD6, SI1000, phenomenological, The deltakit-stim fork, Windowed and real-time decoding.
QYou turn on SI1000Noise(p=1e-3, pL=0.01) and rebuild the DEM: it has the same 21 rows as at pL = 0. Can the decoder built from it handle leakage?
ANo. The DEM drops LEAKAGE and RELAX, so the decoder is identical to the one without leakage. The detectors do notice: their rate goes from 0.0185 to 0.0744, while the DEM still predicts 0.0187.
An optimal decoder returns the most likely class of errors, not the most likely error. Minimum weight agrees with it only when one lightest error dominates; ties, and how many equally light errors a class holds, are invisible to it.
Errors, classes and the two decoders
Fix a syndrome and any error that produces it. Every other error with that syndrome is , where is a stabilizer and is a logical operator. Multiplying by changes nothing that matters, so the errors split into classes, one per logical . A correction succeeds when it lies in the same class as the error that happened. For independent flips with probability on locations, write . Then
where counts the errors of weight in class .
Maximum likelihood (ML) compares the whole sums.
Minimum weight (MW) finds one lightest error and returns its class, so it compares only the smallest with .
At small each sum is dominated by its first term, . If the two classes have different , both decoders agree. If ties, ML breaks the tie with , the number of lightest errors. MW has no rule for it.
When minimum weight is already optimal
In the rotated surface code with odd and independent errors, ties cannot happen. Two errors in different classes differ by a logical of odd weight times stabilizers of even weight, so their weights have opposite parity. MW and ML then agree at leading order, and they differ only where many slightly heavier errors outweigh one light one. At that is 181 of the 4,096 syndromes. At the failure rates are 0.124416 (MW) and 0.123897 (ML), a 0.4% gap. Lecture 5 got these by enumerating errors; the card Tensor-network maximum-likelihood decoding recomputes them by contraction. The gap at the threshold is also small: on the toric code with bit-flip noise, matching reaches 10.3% (Wang, Harrington and Preskill 2003) and ML about 10.9% (Dennis et al. 2002).
Three things break this comfortable picture:
Ties. As soon as measurements are noisy, a logical loop in space-time can detour through time, and its weight can be even. The parity argument fails and lightest classes can tie.
Correlations. A error is one event but two edges, one in each matching graph. MW on the decomposed graphs then does not even find the lightest Pauli error (Correlated matching and BeliefMatching).
High . Near threshold, the count of heavier errors (the entropy) matters as much as their weight.
Worked example: noisy checks create ties
Take the 3-qubit repetition code with checks and . Run noisy rounds, with every data qubit flipping before each round and every check misread, each with probability , then read the data perfectly. That gives fault locations and detectors. An exact enumeration of all fault sets gives:
: no syndrome is tied, and MW equals ML exactly ( at leading order).
: 104 of the 256 syndromes have tied lightest classes. The leading failure rates are for ML and for MW breaking ties with a fair coin.
PyMatching on the same graph:. It agrees with MW on all 152 untied syndromes, so the whole gap comes from how it breaks ties. At it fails with probability , against for ML: 18% more.
More rounds: the fair-coin MW/ML ratio at small grows from 1.083 () to 1.103 (). It does not vanish as , because the ties sit at leading order.
The ties are not exotic events. Sorted by the number of fired detectors, the 104 tied syndromes of have 2 (6 syndromes), 3 (20), 4 (24), 5 (36), 6 (10) or 7 (8) defects; the figure’s syndrome has only two. PyMatching breaks every tie deterministically, by the order in which its search meets the candidates. With the snippet’s column order it sends 56 tied syndromes to class 0 and 48 to class 1 (57 and 47 with the columns reversed). That is close to a fair coin by count, but worse once each syndrome is weighted by its probability: against , in either order. The gap survives at high noise: at , ML fails with probability 0.134, the fair coin with 0.146 and PyMatching with 0.149.
The figure shows one tied syndrome. Class 0 has two weight-2 explanations, the two ways around one space-time plaquette. Class 1 has one, which leaves through both boundaries and flips the logical. Their product, at , at , a misread of and at , has weight 4 and is a logical: the even-weight loop that defeats the parity argument.
In Deltakit
Deltakit has no ML decoder. PyMatchingDecoder (deltakit.decode) is minimum weight, with the tie-breaking of its matching engine. The block below builds the example’s check matrix by hand and calls pymatching, the library inside PyMatchingDecoder. It counts the weight-2 errors in each class for the figure’s syndrome and asks the matching which class it picks.
import itertoolsimport numpy as npimport pymatchingH, L = [], []for t in range(3): # 3 noisy rounds for q in range(3): # X flip on qubit q col = [0] * 8 for c in (0, 1): if q in (c, c + 1): col[2 * t + c] = 1 H.append(col) L.append(int(q == 0)) for c in (0, 1): # misread check c col = [0] * 8 col[2 * t + c] = 1 col[2 * t + 2 + c] = 1 H.append(col) L.append(0)H = np.array(H).T # 8 detectors x 15s = np.zeros(8, dtype=np.uint8)s[[1, 2]] = 1 # D(0,b) and D(1,a)count = {0: 0, 1: 0}for f in itertools.combinations(range(15), 2): if (H[:, f].sum(axis=1) % 2 == s).all(): count[sum(L[i] for i in f) % 2] += 1m = pymatching.Matching.from_check_matrix( H, faults_matrix=np.array([L]))print("weight-2 errors per class:", count)print("matching picks class", m.decode(s)[0])
weight-2 errors per class: {0: 2, 1: 1}
matching picks class 1
For exact references on small codes, enumerate (Notebook 5) or contract (the tensor-network card).
“Matching is optimal” is a leading-order statement about untied syndromes
It holds for independent / noise in code capacity with odd . With noisy measurements, ties are common: here 104 of 256 syndromes. On every one of them, ML has information that MW throws away.
Exact ML does not scale
Exact ML decoding of stabilizer codes is #P-hard in general (Iyer and Poulin 2015). Planar codes with independent bit and phase flips are the exception: there it is a 2D contraction. Everything else is approximate.
Related cards: Matching and PyMatching, Tensor-network maximum-likelihood decoding, Correlated matching and BeliefMatching, Syndromes and logical operators.
QA syndrome has three lightest explanations, all of weight 2: two in class 0 and one in class 1. Which class does ML choose, and how often is a decoder that picks class 1 wrong on this syndrome when is small?
AML chooses class 0, which is about twice as likely. A decoder that picks class 1 is wrong about 2/3 of the time on this syndrome, ML about 1/3. Minimum weight cannot tell them apart; PyMatching happens to pick class 1 here.
PyMatching finds a minimum-weight perfect matching on the decoding graph, with weights . Deltakit wraps it as PyMatchingDecoder, which rewrites your circuit: sample from the circuit it returns. Errors must be graphlike.
From syndrome to matching
The decoding graph has one node per detector plus a boundary node. Each edge is an error mechanism that flips at most two detectors; an edge to the boundary flips one. An edge carries its probability , a weight , and a bit saying whether it flips the logical observable (From DEM to decoding graph). A correction is a set of edges whose odd-degree nodes are exactly the fired detectors. Its probability is proportional to , so the lightest correction is the single most likely error. That is minimum weight, not maximum likelihood (Maximum likelihood vs minimum weight).
Finding the lightest correction is a minimum-weight perfect matching problem, as set out in Dennis et al. 2002. The textbook route has three steps:
compute shortest-path distances between all fired detectors and to the boundary;
build a complete graph on them;
run Edmonds’ blossom algorithm.
The complete graph is quadratic in the number of defects. Sparse blossom, inside PyMatching 2, runs the blossom algorithm directly on the sparse decoding graph. It grows regions around fired detectors, much as Union–Find grows clusters, but keeps the answer exactly minimum weight. Its authors report under a microsecond per round for a distance-17 surface code at 0.1% circuit noise, on one core [PUBLISHED, Higgott and Gidney, Quantum 9, 1600 (2025)].
On the laptop that built this sheet, the cost per shot (SI1000, , rounds ) tracks the number of fired detectors. Like Lecture 5’s 0.83 µs at , these are laptop timings and move by 10% or more between runs:
detectors
fired per shot
µs per shot
3
16
0.4
0.04
5
72
2.1
0.26
7
192
5.9
0.74
9
400
12.8
1.63
11
720
23.5
2.96
That is about 0.12–0.13 µs per fired detector from up (0.1 at , where little fires): linear in the defects, not in the graph.
What the weights buy
Same seeded samples throughout: , 5 rounds, SI1000 at , 50,000 shots, decoded several ways.
True weights:PyMatchingDecoder built at the true fails 388 times.
Wrong : decoders built for ,, and fail 380, 382, 397 and 429 times.
No weights: every edge set to weight 1 gives 642 failures, against 398 for pymatching loaded from the same DEM with its true weights.
Why is a wrong mostly harmless? Scaling every by shifts each weight by about . A path of edges then changes by . That only biases the choice between paths with different numbers of edges, which mostly cost nearly the same anyway. Uniform weights throw away real structure. The true weights here run from 3.65 to 7.54, so the likeliest and the least likely edge differ by a factor of about in probability. Lesson: get the graph and the relative weights right; the overall noise scale need not be exact.
(PyMatchingDecoder and pymatching loaded from a file build their graphs separately and differ by a few failures, 388 vs 398. Compare decoders within one construction.)
Two outputs: the flip and the correction
A decoder answers two different questions, and PyMatchingDecoder exposes both.
Did the logical flip?decode_batch_to_logical_flip(dets) returns one bit per shot and observable. Compare it with the sampled observables to count failures; run_decoding_on_circuit does exactly this, and it is all a memory experiment needs.
Which errors happened?decode_batch_to_full_correction(dets) returns one column per edge of dec.decoding_graph, a networkx-backed graph whose edge records hold each . You need the correction itself whenever a later step acts on it: a windowed decoder commits edges and passes their effect to the next window (Windowed and real-time decoding), a Pauli frame tracks physical corrections, and a failure is easiest to understand as a picture of the chain.
The two agree by construction: the parity of the chosen edges that lie in dec.logicals[0] is the predicted flip. The cloud decoders implement only the first output, so they cannot be windowed this way.
In the run below (,), 15,437 of 20,000 shots need no edge at all, 4,065 need one, 465 need two and 33 need three. At this size and noise, most syndromes come from a single fault.
In Deltakit
from deltakit.decode import PyMatchingDecoder. The class method construct_decoder_and_stim_circuit(noisy) returns the decoder and the circuit to sample from. decode_batch_to_logical_flip returns one bit per shot and observable. decode_batch_to_full_correction returns one column per graph edge, and its parity on the logical’s edges is the flip:
import numpy as npfrom deltakit.circuit.gates import PauliBasisfrom deltakit.decode import PyMatchingDecoderfrom deltakit.explorer.codes import ( RotatedPlanarCode, css_code_memory_circuit)from deltakit.explorer.qpu import QPU, SI1000Noisecode = RotatedPlanarCode(width=3, height=3)circ = css_code_memory_circuit( code, num_rounds=3, logical_basis=PauliBasis.Z)qpu = QPU(qubits=code.qubits, noise_model=SI1000Noise(p=1e-3))noisy = qpu.compile_and_add_noise_to_circuit( circ)dec, dcirc = PyMatchingDecoder.\ construct_decoder_and_stim_circuit(noisy)sampler = dcirc.compile_detector_sampler( seed=2026)dets, obs = sampler.sample( 20_000, separate_observables=True)flip = dec.decode_batch_to_logical_flip(dets)corr = dec.decode_batch_to_full_correction(dets)g = dec.decoding_graphon_L = [i for i, e in enumerate(g.edges) if e in dec.logicals[0]]par = corr[:, on_L].sum(axis=1) % 2print(corr.shape, len(on_L))print("parity == flip:", (par == flip[:, 0]).all())print("fails:", int((flip != obs).sum()))print("edges used:", np.bincount(corr.sum(axis=1)))
The graph has 55 edges, and 8 of them cross the logical.
The decoder’s circuit is not your circuitconstruct_decoder_and_stim_circuit keeps only the detectors the decoder uses: 16 of the 24 in this memory, because the -type ones go. Feeding it samples of your own circuit raises ValueError: `shots` array should have at least 16 columns (the number of detectors), and no more than 17 columns. Always sample from dcirc.
Matching needs graphlike errors
A mechanism that flips three or more detectors must first be split into edges. In a 6-round ⟦72,12,6⟧ bivariate bicycle memory (SI1000, ), 16,668 of 17,244 DEM errors flip three or more detectors. The surface code has 65% such errors, but Stim splits each into edges; here decompose_errors=True fails with “Failed to decompose errors into graphlike components with at most two symptoms”, so no PyMatchingDecoder can be built. Use BP-OSD instead (Belief propagation and BP-OSD).
Plain pymatching rejects a deltakit_stim DEMpymatching.Matching.from_detector_error_model(dem) wants upstream stim and raises TypeError. Write str(dem) to a file and call Matching.from_detector_error_model_file(path).
Related cards: Maximum likelihood vs minimum weight, From DEM to decoding graph, Union–Find decoding, Correlated matching and BeliefMatching, The memory-experiment pipeline.
QYou sample detectors from your noisy , 3-round circuit (24 detectors) and pass them to the decoder from PyMatchingDecoder.construct_decoder_and_stim_circuit. What happens?
AA ValueError: the decoder expects 16 or 17 columns. Its circuit keeps only the 16 -type detectors of a memory. Sample from the circuit it returns, which has the right detectors in the right order.
unit growth: every edge is 2 half-steps6.914.604.606.91round 1: each odd cluster grows half an edge each way149914
Union–Find grows clusters around defects until each holds an even number of them or touches the boundary, then peels each cluster’s spanning tree into a correction. Almost-linear time, a little less accurate than matching.
The algorithm
The input is the decoding graph and the set of fired detectors, called defects. A cluster is a connected set of nodes. It is odd if it holds an odd number of defects and does not contain the boundary.
Start. Every defect is its own cluster, so every cluster is odd.
Grow. Each odd cluster adds half an edge along every edge that leaves it. When an edge has been grown from both sides, or twice from one side, it is full, and the clusters at its ends merge. A cluster that reaches the boundary stops being odd: the boundary can absorb any leftover defect.
Repeat until no odd cluster is left.
Peel. Build a breadth-first spanning tree of each cluster’s full edges, rooted at the boundary if the cluster contains it. Visit nodes from the leaves inward. If a leaf is a defect, put its tree edge into the correction and toggle its parent’s defect status. Then delete the leaf.
Peeling always succeeds, because every finished cluster is even or holds the boundary. It is the linear-time erasure decoder: the grown clusters are treated as an erasure, and peeling picks any correction inside them.
Merging uses the union–find data structure with union by size and path compression. Each find then costs the inverse Ackermann function in amortised time, which is at most 4 for any graph you will ever build. Each edge is grown at most twice. So the whole decoder runs in time on nodes: Delfosse and Nickerson (Quantum 5, 595 (2021)) call it almost-linear. It is also local and simple, which is why hardware decoders descend from it.
Sparse blossom grows regions too, so why is Union–Find not exact? When two growing regions meet, sparse blossom records the pairing in an alternating tree and can later undo it, if a cheaper overall matching appears. Union–Find never revisits a merge: the first even cluster is final, and peeling picks any correction inside it. That missing bookkeeping is where its speed comes from, and also its errors.
What it gives up
Growth is a crude stand-in for distance. In the original unit version, every edge has the same length (two half-steps), whatever its probability. On the toric code with bit-flip noise, where all edges are equally likely, Delfosse and Nickerson reach 9.9% against 10.3% for matching. That number needs one refinement: the odd cluster with the smallest boundary grows first, which they call Weighted Growth. Growing all odd clusters at once, as Notebook 5 does, gives 9.2%. Circuit noise makes the edge weights very unequal, and unit growth then pays more. Beware a naming clash: in Notebook 5 and on this card, weighted growth means something else, an edge length of half-steps, so likely edges fill first.
Notebook 5’s implementation, on the same seeded SI1000 samples (rounds ; 100,000, 50,000 and 20,000 shots), gives these failure counts:
,
matching
UF unit
UF weighted
3,
344
434
359
5,
388
656
433
7,
77
214
95
Unit growth costs a factor of 1.26, 1.69 and then 2.78 against matching; weighted growth costs 1.04, 1.12 and 1.23. The unit gap clearly grows with (though also changes after the first row); the weighted gap is within its noise at and only suggestive beyond. Longer error chains offer more ways for cluster shapes to deviate from the lightest path.
Worked example: where unit growth goes wrong
The figure is a five-node line, ––––, with the boundary at both ends. The outer edges have , so weight . The inner edges have , so weight . Defects sit at and .
Unit growth. In round 1, each defect grows half of each of its two edges. In round 2, all four edges become full at once, and everything merges into one cluster that holds the boundary. Peeling roots a breadth-first tree at , as Notebook 5 does, so both defects hang from by their outer edges. (A depth-first tree ––– would peel to instead.) The correction is , with weight 13.81.
Weighted growth. The inner edges have length and the outer ones . After 9 rounds the inner edges are full while the outer ones are at 9/14. The cluster holds two defects, so it is even and growth stops. Peeling returns , with weight 9.19. That is PyMatching’s answer too.
The peeling step, in detail: the spanning tree of is the path ––, rooted at . Leaf is a defect, so joins the correction and toggles to a defect. Leaf is a defect, so joins and toggles back. The root is left clean, as it must be in an even cluster.
The two corrections differ by a factor of in probability. On a real decoding graph this happens at every place where a cheap long path competes with an expensive short one.
In Deltakit
There is no local Union–Find decoder in Deltakit 0.10.2. The nearest local tool is PyMatchingDecoder, which is exact minimum weight and fast enough for any simulation on this site. Riverlane’s hardware decoders are clustering decoders of this family:
Collision Clustering runs at MHz rates, on FPGA up to 881 qubits and on ASIC up to 1,057 qubits, in 0.06 mm² and 8 mW [PUBLISHED, Barber et al., Nat. Electron. 8, 84 (2025)].
The Local Clustering Decoder takes under 1 µs per round on FPGA and adapts to heralded leakage [PUBLISHED, Ziad et al., Nat. Commun. 16, 11048 (2025)].
Their cloud counterparts are CCDecoder and LCDecoder in deltakit.decode. Both refuse to start without a client:
CCDecoder: Currently, a `client` must be
provided to instantiate this class.
LCDecoder: Currently, a `client` must be
provided to instantiate this class.
With a token, they plug into run_decoding_on_circuit like any decoder. This block is not run:
“Union–Find” names a family, not one accuracy
Unit and weighted growth, the tie rules in peeling, and the hardware variants all differ in accuracy. Quote the variant and the noise model with any comparison, as in the table above.
Related cards: Matching and PyMatching, Windowed and real-time decoding, From DEM to decoding graph.
QTwo defects sit two inner edges apart ( each), and each is one edge () from the boundary. What does unit-growth Union–Find return, and what does matching return?
AUnit growth fills all four edges in the same round, so the merged cluster touches the boundary and peeling sends both defects there (weight 13.8). Matching joins them through the middle (weight 9.19), which is about 102 times more likely. Weighted growth recovers the matching answer.
Belief propagation passes likelihood messages between errors and checks; it is exact on trees. On a degenerate code it splits its belief between equivalent corrections and stalls. OSD then solves for the likeliest columns by elimination.
Message passing on the Tanner graph
Write for the check matrix: a row per check, a column per error mechanism (a qubit in code capacity, a DEM column under circuit noise). Mechanism starts from its prior log-likelihood ratio . Each iteration sends two kinds of message:
mechanism to check: , over the other checks of ;
check to mechanism, in the min-sum form of Notebook 7: , over the other mechanisms of , with .
The exact product-sum rule uses in place of the minimum; min-sum approximates it cheaply, and tempers its overconfidence. After each iteration the posterior gives a hard decision , and BP stops when . An iteration costs time linear in the number of Tanner-graph edges and parallelises completely. On a tree, BP returns exact marginals.
Quantum codes break it in two ways. Short cycles feed messages back to their sender. Degeneracy is worse: corrections that differ by a stabilizer are equally good, and BP cannot choose. The bivariate bicycle codes of Lecture 7 have no 4-cycles: no two checks share two qubits, so both ⟦72,12,6⟧ and ⟦144,12,12⟧ have girth 6. Their failures below are degeneracy at work.
Worked example: a stabilizer split in half
Take code-capacity noise on the ⟦72,12,6⟧ code, decoded with . Its first stabilizer acts on qubits 1, 2, 18 in the block and 39, 42, 48 in the block. Apply to the half. The half has the same syndrome (9 checks fire), the same weight 3, and differs by a stabilizer, so both are perfect corrections.
Run Notebook 7’s min-sum BP at , prior LLR 4.60. By symmetry, all six qubits carry the same LLR at every iteration:
it.
1
2
29
30
LLR
−4.02
6.75
−8.79
12.72
The swings peak at −11.32 (iteration 7) and 15.88 (iteration 8).
Odd iterations flip all six qubits, a stabilizer with zero syndrome; even ones flip none. BP votes for both halves or neither, with growing conviction, and never converges. A single error, with no rival, converges in one iteration.
OSD: let linear algebra finish
Ordered statistics decoding (Panteleev and Kalachev, Quantum 5, 585 (2021)) uses BP only for a ranking. Sort the mechanisms by LLR, most likely flipped first. Keep the first linearly independent columns and solve by Gaussian elimination, all other mechanisms set to zero. The result always reproduces the syndrome. OSD-0 stops there. Higher orders, such as the combination sweep of Roffe et al., also flip a few of the remaining low-reliability mechanisms and keep the likeliest solution.
Notebook 7 feeds OSD-0 the last iterate. There the six true candidates have LLR , above every other qubit (4.40 to 8.37), so OSD ranks them last. It returns a weight-11 correction (with Notebook 7’s tie order; breaking ties the other way gives weight 9, also wrong) that satisfies the syndrome and differs from the error by a logical: a failure. Fed iterate 29, or the mean of all 30 iterates (1.94 on the six, at least 4.87 elsewhere), OSD-0 returns weight 3 in the right class.
On Notebook 7’s random shots (3,000 per point), this counts failures among the shots that reached OSD:
,
to OSD
last
it. 29
mean
72, 0.04
240
182
178
154
144, 0.04
187
62
59
31
144, 0.06
775
383
380
338
Averaging is a quick variant tried here, not a published decoder. The point is that OSD is only as good as the ranking it is given.
How much does OSD add at all? On ⟦144,12,12⟧ at , BP converges on 93.8% of Notebook 7’s shots; BP alone fails 190 times and BP+OSD 65. At BP converges on only 20.0%, and OSD cuts 2,438 failures to 1,958. On ⟦72,12,6⟧ the gain is smaller (329 to 271 at ), because more of its failures come from shots where BP converged to the wrong class: 89 at , against 3 for the larger code. OSD never sees those shots.
Cost and successors
Under circuit noise these codes leave no alternative to BP. Each qubit sits in three checks, so a single flip already trips three detectors, while matching needs every fault split into edges of at most two. A 6-round ⟦72,12,6⟧ memory with SI1000 noise at has 432 detectors and 17,244 mechanisms, and 97% of them flip three or more. Stim cannot split them, and PyMatchingDecoder raises a ValueError (Matching and PyMatching). The surface code has 65% such mechanisms, but Stim splits every one into edges.
Gaussian elimination costs in the number of mechanisms, too slow for a microsecond syndrome cycle when a circuit-level DEM has thousands of columns. Decoded with BP-OSD under circuit noise, the bivariate bicycle family reaches a threshold of about 0.7% (Nature; the arXiv v2 abstract says 0.8%) [PUBLISHED, Bravyi et al., Nature 627, 778 (2024)]. Relay-BP drops OSD and chains BP runs with disordered memory strengths, some negative, which damp oscillations like the one above and break their symmetry. Its authors report that it significantly outperforms BP+OSD with combination-sweep order 10 on bivariate bicycle codes under circuit noise and is comparable to matching on surface codes [PREPRINT, Müller et al., checked 2026-11-09].
In Deltakit
from deltakit.decode import BPOSDecoder is a cloud decoder (Lecture 5 lists them all). Without client= it raises NotImplementedError. With one, it implements only decode_batch_to_logical_flip, which is enough for run_decoding_on_circuit. Locally, BivariateBicycleCode gives the check matrices, and this block checks the two facts the example rests on:
A valid correction is not a correct one
OSD always returns a correction with the right syndrome. In the example it has weight 11 and contains a logical. Only the logical observable tells you whether decoding worked.
Girth 6 does not make BP converge
Removing 4-cycles leaves degeneracy untouched: BP oscillates forever on this weight-3 error, although the Tanner graph has girth 6.
Related cards: Bivariate bicycle codes and the gross code, From DEM to decoding graph, Correlated matching and BeliefMatching, Matching and PyMatching.
QBP oscillates on a weight-3 error of the ⟦72,12,6⟧ code. Its last iterate gives the six qubits of one stabilizer LLR and every other qubit between 4.4 and 8.4. What does OSD-0 return, and does it fail?
AOSD ranks the six last, so it solves the syndrome with other columns: a weight-11 correction that satisfies the syndrome but differs from the error by a logical operator. A logical failure. Fed iterate 29 or the mean of the iterates, it returns weight 3 and succeeds.
Matching splits a error, or any fault that trips detectors of both types, into independent edges and overcharges it. Correlated matching and belief-matching restore the link by reweighting edges before matching.
What decomposition throws away
Take the , 3-round memory under SI1000 noise at , with all 24 detectors kept. Its detector error model has 221 mechanisms. By the number of detectors they flip:
detectors flipped
1
2
3
4
mechanisms
24
84
76
37
143 of the 221 flip both -type and -type detectors. Matching needs edges, so decompose_errors=True cuts each hyperedge into graphlike pieces, and the decoder then treats the pieces as independent. Nothing in the graph says that an -type edge and a -type edge came from the same CNOT fault.
The cost is clearest in code capacity. Under depolarizing noise, each qubit suffers , or with probability . The part of the error ( or ) has marginal probability , and so does the part. Matching weights every edge , which is 3.37 at , and charges a two of them, 6.73. The true weight of a , like that of an , is . So matching treats each as 14.8 times less likely than it is.
Bookkeeping suffers too. Between two -type detectors of that circuit (9 and 13, one round apart), the mechanisms that flip both add up, by XOR, to . The graph built from the full decomposed model gives that edge ; the decomposition assigned the rest to other edges. PyMatchingDecoder keeps only the 16 -type detectors, and its edge gets the full , but it knows nothing of the side.
Two ways to put the correlations back
Correlated matching (in the spirit of Fowler 2013) matches one graph first. Every chosen edge raises the probability of the edges in the other graph that share a mechanism with it; then the other graph is matched. In the depolarizing example, a qubit with an correction has , weight 0; everywhere else the weight stays at 4.04.
Belief-matching (Higgott et al.) runs belief propagation on the full hypergraph, where hyperedges are no problem (Belief propagation and BP-OSD). Each mechanism’s posterior marginal is folded into the edges it decomposes into, the weights are reset to for that shot, and matching finishes the job. BP supplies the correlations; matching guarantees a correction that fits the syndrome, which BP alone does not. Under circuit-level noise on the surface code, the authors report a 0.94% threshold for belief-matching and for belief-find, its Union–Find version, against 0.82% for plain matching [PUBLISHED, Higgott et al., PRX 13, 031007 (2023)]. The price is a BP run per shot before every matching.
How do marginals become weights? Suppose BP gives mechanism the posterior marginal , and decomposes into the edge set . The rule used in the experiment below combines, by XOR, every mechanism that contains edge :
In code capacity, the part of qubit collects the and mechanisms there. A mechanism that BP believes in makes all its edges cheap at once, in both graphs; that is the link the plain graph lost. BP sees every detector, so a pair of -type defects can lower the weight of the -type edge that the same fault would also produce. Why not stop at BP, or use BP-OSD? On the surface code, BP alone stalls on the degenerate loops the code is full of, and matching resolves exactly those.
Worked example: depolarizing code capacity
Rotated surface code, ,, each with probability . All decoders end in PyMatching:
independent (indep.): match the two parts separately with ;
two-pass: match the part, then the part with weights 0 or 4.04 as above;
belief-matching (BM): product-sum BP (30 iterations) with three mechanisms per qubit, then match each part with weights from its marginals.
At , summing over all errors gives exact failure rates:
indep.
two-pass
BM
ML
0.05
0.0338
0.033–0.044
0.0319
0.0293
0.10
0.1138
0.111–0.126
0.1127
0.1019
0.15
0.2154
0.211–0.226
0.2059
0.1980
The two-pass numbers depend on which of several equally light corrections PyMatching returns. Relabelling the qubits (12 labellings) moves them over these ranges, while indep., BM and ML do not move.
At and , on the same 20,000 seeded errors for each decoder, the failure counts are:
,
indep.
two-pass
BM
5, 0.05
340
377
216
5, 0.10
1928
1947
1465
7, 0.05
169
166
81
7, 0.10
1583
1539
1010
Belief-matching halves the failures at ,, and the gain grows with . On paired counts BM beats indep. by 7.5σ to 17σ in every row. The two-pass reweighting barely helps. At , it is worse: on the same errors it fails alone 118 times and indep. alone 81 times (paired ), because it trusts an matching that may be wrong. It shows the principle only; published correlated decoders use the gate-level error model. At every decoder stays well above ML.
In Deltakit
from deltakit.decode import BeliefMatchingDecoder is a cloud decoder implementing belief-matching. It takes the full noisy circuit, untrimmed; without client= it raises NotImplementedError. This local block counts how many detectors each mechanism flips, for the full circuit and for the circuit PyMatchingDecoder returns:
from collections import Counterfrom deltakit.circuit.gates import PauliBasisfrom deltakit.decode import PyMatchingDecoderfrom deltakit.explorer.codes import ( RotatedPlanarCode, css_code_memory_circuit)from deltakit.explorer.qpu import QPU, SI1000Noisecode = RotatedPlanarCode(width=3, height=3)circ = css_code_memory_circuit( code, num_rounds=3, logical_basis=PauliBasis.Z)qpu = QPU(qubits=code.qubits, noise_model=SI1000Noise(p=1e-3))noisy = qpu.compile_and_add_noise_to_circuit( circ)_, dcirc = PyMatchingDecoder.\ construct_decoder_and_stim_circuit(noisy)for c in (noisy.as_stim_circuit(), dcirc): dem = c.detector_error_model() n = Counter( sum(t.is_relative_detector_id() for t in e.targets_copy()) for e in dem.flattened() if e.type == "error") print(c.num_detectors, dict(sorted(n.items())))
24 {1: 24, 2: 84, 3: 76, 4: 37}
16 {1: 16, 2: 39}
Dropping the -type detectors makes every mechanism graphlike: the correlations are gone, not handled. The cloud call, not run here:
One edge, two probabilities
The same pair of detectors gets in the full decomposed graph and in PyMatchingDecoder’s graph. Edge weights depend on how the model was decomposed and trimmed. Compare decoders on one construction.
A correlated decoder needs the correlated model
Belief-matching can only use correlations that the detector error model records. Give it the full noisy circuit. The circuit PyMatchingDecoder returns has already dropped the -type detectors, and every correlation with them.
Related cards: Matching and PyMatching, Belief propagation and BP-OSD, From DEM to decoding graph, Maximum likelihood vs minimum weight.
QDepolarizing noise, , decoded by matching the and parts separately with weight ,. What weight does a single get, and what should it get?
ATwo edges of 3.37, so 6.73. Its true weight is , the same as an or a . Matching treats the as about 15 times less likely than it is, so it misses corrections built from s.
012345678spins on checks, factors on qubits81, 26, 7054334
ML decoding needs class probabilities: sums over every error in a class. For a planar code with independent flips, each sum is a 2D Ising partition function. A sweep contracts it exactly in time ; a boundary MPS approximates it.
The class sum is a partition function
Take code-capacity noise: independent flips with probability on qubits, perfect -check readout. For an error with the observed syndrome, the probability of its class is
where means “multiply by the -th stabilizer”. The other class is for a logical , and ML returns the larger (Maximum likelihood vs minimum weight). Each qubit lies in at most two checks, so each factor couples at most two spins. Writing with turns into a random-bond Ising model on the Nishimori line, the mapping of Dennis et al.. The error only sets the signs of the couplings.
As a tensor network, every spin is an index and every qubit a small tensor on one or two indices. Exact ML decoding of a general stabilizer code is #P-hard (Iyer and Poulin). For this planar network it is not.
Exact contraction by a sweep
Order the checks from left to right and eliminate the spins one by one. At each moment you carry a table over the frontier: the spins already introduced whose qubits are not all summed. A table on spins has entries, so a class sum costs about . For the rotated code the widest frontier holds 4, 5, 6, 7 and 8 spins at , 7, 9, 11 and 13, about . At the four checks form a chain (figure), and the table is a 2-vector.
Checks on the batched numpy sweep:
Against brute force: at and , agrees with the explicit sum over all stabilizers to and .
Against Lecture 5: at and , summing over all 4,096 syndromes gives class probabilities that total 1. The failure rates are 0.123897 for ML and 0.124416 for PyMatching, with 181 syndromes decided differently. Lecture 5 got the same by enumerating errors; the sweep takes 0.01 s for all 8,192 contractions.
Speed: with two contractions per shot, the sweep takes 0.003 ms at and under 0.2 ms at .
Worked example: how the gap grows with distance
The same seeded errors are decoded by exact ML and by PyMatching. Failures as matching / ML, with 40,000 shots per point except 20,000 at and 13 for :
5
4997 / 4987
2279 / 2282
7
5008 / 4958
1964 / 1941
9
5094 / 4823
1597 / 1519
11
2558 / 2373
1384 / 1316
13
2621 / 2413
1098 / 1048
At , close to the threshold, matching’s excess grows from 0.2% at to 8.6% at . Near the threshold, the number of slightly heavier errors in a class weighs as much as the lightest one, and matching ignores it. At it stays near 5% from on: 5.1%, 5.2% and 4.8%, each uncertain by 1 to 1.6 points on paired counts. At ML even loses, 2,282 to 2,279: the two decoders disagree on only 17 shots, and ML is optimal on average, not on every finite sample.
Pairing is also the right way to measure such gaps. Both decoders see the same errors, so only the shots where exactly one fails carry information. At ,, matching alone fails on 801 shots and ML alone on 530; the 4,293 shots where both fail cancel. The gap of 271 then has a standard deviation of about , a 7.4σ effect. Two independent runs of the same size would give about 93 (binomial), and only 2.9σ.
Approximate contraction and beyond 2D
The frontier grows like , so exact sweeps cost per qubit. Bravyi, Suchara and Vargo store the frontier as a matrix product state with bond dimension , which gives approximate ML in time . They also give an exact algorithm, valid only for independent bit and phase flips. Why does a small suffice? At ,, cut the widest frontier vector (8 spins) in half and keep singular values. The discarded weight has a median of 0.12 at , at and at .
Chubb extends approximate contraction to any 2D code and Pauli noise, in time . Measurement errors add a time direction, and the network becomes 3D, where contraction behaves far worse. Piveteau, Chubb and Renes nonetheless decode circuit-level noise this way and beat matching on the rotated surface code [PUBLISHED, PRX Quantum 5, 040303 (2024)]. These decoders are far too slow for real time; their job is to be the accuracy reference.
In Deltakit
Deltakit has no maximum-likelihood or tensor-network decoder. The nearest tool is PyMatchingDecoder (deltakit.decode), which is minimum weight. The block below writes the chain with the qubit labels of the figure and checks the transfer matrices against the brute-force sum:
import itertoolsimport numpy as npp = 0.1HX = [[5, 8], [1, 2, 4, 5], # X checks, [3, 4, 6, 7], [0, 3]] # in chain orderLX = [6, 7, 8] # an X logicaldef t(b): # weight of one qubit return p if b % 2 else 1 - pdef brute(e): # 2^4 group elements tot = 0.0 for s in itertools.product([0, 1], repeat=4): f = e.copy() for j in range(4): if s[j]: f[HX[j]] ^= 1 tot += np.prod([t(b) for b in f]) return totdef chain(e): # transfer matrices v = np.array([1.0, 0.0]) for j, g in enumerate(HX): nxt = HX[j + 1] if j < 3 else [] prv = HX[j - 1] if j else [] M = np.ones((2, 2)) for a in (0, 1): for b in (0, 1): for q in g: if q in nxt: continue s = e[q] + b + a * (q in prv) M[a, b] *= t(s) v = v @ M return v.sum()e = np.zeros(9, dtype=int)e[[3, 4]] = 1 # X on qubits 3, 4f = e.copy()f[LX] ^= 1 # same syndromefor c in (e, f): print(f"{brute(c):.6e} {chain(c):.6e}")
Each qubit is counted in the last check that contains it, so depends on the previous spin and the current spin .
Exact ML is a code-capacity luxury
Polynomial-time exact ML needs a planar Ising model: independent and flips and perfect checks. The sweep here is exact but exponential in ; it only looks cheap up to . Depolarizing noise, measurement errors and circuit noise call for approximate contraction, with and the contraction order as new sources of error.
Related cards: Maximum likelihood vs minimum weight, Matching and PyMatching, Correlated matching and BeliefMatching.
QAt , (code capacity, noise), exact ML fails on 2,413 of 20,000 shots and matching on 2,621. Is ML right on every shot where matching is right?
ANo. ML is wrong on 410 shots where matching is right, and matching is wrong on 618 where ML is right. ML maximises the success probability of each syndrome, so it wins on average, not shot by shot.
05001000one global matching: 7450138919312820376857498747
Syndrome rounds keep arriving. A decoder slower than the hardware builds a backlog that grows exponentially across gates. Windows decode a few rounds at a time: commit the oldest, keep about buffer rounds for chains that continue.
Throughput, latency and the backlog
A memory experiment is decoded after the last round. A computation cannot wait: a gate by magic-state injection needs the decoded Pauli frame before the next step can be chosen. Two numbers matter:
throughput: rounds decoded per second, compared with rounds produced. Write for the decoding time per round over the round time;
latency: the delay from the last round a decision needs to the decision.
A toy model shows why decides everything. Rounds arrive every µs, and the program runs rounds between gates. Let be the number of rounds the decoder must finish before gate . Clearing them takes round-times. The logical qubits wait, but error correction cannot pause: more syndrome rounds arrive during the wait, and more follow before the next gate, so with :
100 gates take
0.5
20
20
2.2 ms
0.9
68.6
100
10.1 ms
1.1
185
18.3 s
2
s
For the backlog settles at . For it is , exponential in the number of gates; at the run outlasts the universe. Skoric et al. make the same backlog argument. Latency cannot rescue ; it only sets the constant wait once .
Sliding windows: commit and buffer
A sliding window decodes rounds as one problem. The first rounds form the commit region, the last the buffer. Edges that leave the window toward the future become boundary edges, since the window cannot see where they end. Edges into the past are dropped: their effect is already in the syndrome. After matching:
Commit every chosen edge whose earliest detector lies in the commit region, and apply it to the logical observable.
Update the syndrome: a committed edge that ends in a later round flips that detector, which the next window then sees as a defect.
Slide to . The buffer is decoded again, now as part of the next commit region.
The experiment in the figure runs this with PyMatching on a memory, 25 rounds, SI1000 at . The decoding graph has 312 detectors and 1,421 edges. On 20,000 seeded shots, one global PyMatchingDecoder fails 745 times. With commit :
buffer
windows
failures
0
6
1389
1
5
931
2
5
820
3
5
768
5
5
749
8
4
747
Every shot ends with an empty syndrome, so the windows always produce a valid correction; without a buffer it is often in the wrong class. A chain that starts in the commit region and runs on into rounds the window cannot see gets cut at the window edge and committed half-done. With , a chain long enough to escape is about as unlikely as a logical failure.
The gain is the cost model. A window of rounds is a matching problem of fixed size, however long the computation runs, and its answer for the commit region is final once the window is done. The price is extra work, since every buffer round is decoded twice, and a latency of at least rounds before a commit.
Parallel windows and hardware
A sliding window is sequential, so its throughput is that of one decoder. Parallel window decoding splits time into blocks. A first layer decodes alternate windows simultaneously, each with buffers on both sides, and commits their cores. A second layer then decodes the seams between them, with the committed corrections as boundary conditions. Throughput grows with the number of cores, with no noticeable loss of logical fidelity for the surface code [PUBLISHED, Skoric et al., Nat. Commun. 14, 7040 (2023)]. Tan et al. (PRX Quantum 4, 040344 (2023)) independently parallelise in time in a similar way.
On hardware, real-time decoding now works. A distance-5 surface code on Google’s Willow processor ran with a real-time decoder for up to a million cycles of 1.1 µs, with an average latency of 63 µs, and stayed below threshold [PUBLISHED, Google Quantum AI, Nature 638, 920 (2025)]. A 63 µs latency over 1.1 µs cycles is fine: throughput kept up, and the latency is paid once per decision. Riverlane’s FPGA decoders take under a microsecond per round (Union–Find decoding).
In Deltakit
Deltakit 0.10.2 has no windowed decoder; issue #325 asks for one (Lecture 9). Such a decoder needs an inner decoder that returns the correction, not just the logical flip, because committing means knowing which edges were used. PyMatchingDecoder.decode_batch_to_full_correction provides that; the cloud decoders implement only decode_batch_to_logical_flip, so they cannot be wrapped this way. Deltakit does have the graph surgery, in deltakit.core.decoding_graphs. annotate_edges_with_window_ids gives each edge the smallest window id of its detectors, and get_window_id_transfer_graph lists which windows feed which:
from deltakit.circuit.gates import PauliBasisfrom deltakit.core.decoding_graphs import ( annotate_edges_with_window_ids, dem_to_hypergraph_and_logicals, get_window_id_transfer_graph)from deltakit.decode import PyMatchingDecoderfrom deltakit.explorer.codes import ( RotatedPlanarCode, css_code_memory_circuit)from deltakit.explorer.qpu import QPU, SI1000Noisecode = RotatedPlanarCode(width=3, height=3)circ = css_code_memory_circuit( code, num_rounds=6, logical_basis=PauliBasis.Z)qpu = QPU(qubits=code.qubits, noise_model=SI1000Noise(p=1e-3))noisy = qpu.compile_and_add_noise_to_circuit( circ)_, dcirc = PyMatchingDecoder.\ construct_decoder_and_stim_circuit(noisy)dem = dcirc.detector_error_model( decompose_errors=True)hg, _ = dem_to_hypergraph_and_logicals(dem)annotate_edges_with_window_ids( hg, lambda c: int(c[-1]) // 3)ids = [r["window_id"] for r in hg.edge_records.values()]counts = {w: ids.count(w) for w in set(ids)}print(dict(sorted(counts.items())))tg = get_window_id_transfer_graph(hg)print(sorted(tg.edges))
{0: 48, 1: 48, 2: 7}
[(0, 1), (1, 2)]
induce_subhypergraph(hg, nodes) cuts out one window. connect_dangling_to_boundary_hypergraph(hg, sub) then folds every edge that leaves it into the node’s boundary edge, combining probabilities by XOR. In the window of this graph, one node’s boundary probability rises from 0.0098 to 0.0182. Unlike the sliding window above, it folds edges into the past too, so committed history must be handled separately.
Latency is not throughput
A 63 µs latency is harmless at 1.1 µs per round if the decoder keeps pace on average. A decoder with 1 µs latency that needs 1.1 µs per round is not: its backlog grows without bound.
Related cards: Matching and PyMatching, Union–Find decoding, From DEM to decoding graph.
QA decoder needs 1.1 µs per round on hardware that produces a round every 1.0 µs. Between gates the program runs 10 rounds. Is a lower decoding latency enough to fix this?
ANo. With the rounds to clear before each gate grow as : about 185 before gate 10 and before gate 100 (counting from gate 0). Only throughput (faster or parallel decoding) keeps the backlog bounded; latency then sets the fixed wait per gate.
Estimate by . The plug-in bar breaks at small : it crosses zero, and at it vanishes. Use likelihood intervals instead. Zero failures give only a bound, .
What is being estimated
Each shot of a memory experiment is one Bernoulli trial: either the decoder’s correction leaves the logical observable flipped, or it does not. Shots from one seeded Stim sampler are independent and identically distributed. Two runs that share a seed are not independent of each other (see the trap on Logical error per round). So failures in shots is a binomial count, and
The relative error depends on the number of failures, not shots: 100 failures give 10%, whatever was. calculate_lep_and_lep_stddev returns and the plug-in error , with substituted for . The bar is the Wald interval.
Why the plug-in bar fails
The Wald interval assumes that is roughly Gaussian, which needs about ten failures and ten successes. Below that it misbehaves in two ways.
It crosses zero. One failure in 10,000 shots gives .
It vanishes at . Then , and the bar claims certainty exactly when you know least. Deltakit raises ValueError instead.
The three intervals of the figure, in units of for :
Wald
likelihood,
Wilson,
0
refused
[0, 2.00]
[0, 4.00]
1
[−1.00, 3.00]
[0.05, 4.50]
[0.17, 5.83]
3
[−0.46, 6.46]
[0.72, 7.91]
[1.00, 9.00]
Coverage measures the damage: the probability that the interval contains the true , summed over the exact binomial distribution of . Take :
true
expected failures
Wald
likelihood
Wilson
2
0.86
0.85
0.95
3
0.80
0.94
0.97
10
0.93
0.94
0.96
100
0.95
0.96
0.95
The nominal level is 95% for all three. Coverage is jagged in because is discrete. At two expected failures the likelihood interval loses the outcome, which has probability , because its upper end falls just short of the true value. By 100 expected failures all three agree.
Likelihood intervals
The binomial likelihood is . A likelihood interval keeps every whose likelihood is at least of the maximum:
Near the peak, , so matches a -sigma bar. is the analogue and the one. The likelihood is skewed toward large , so the interval reaches further up than down and never goes below 0.
For the likelihood ratio is . The upper end is therefore , which is exactly the one-sided bound at confidence . Setting gives : the rule of three, a 95% upper bound of .
Wilson and exact intervals
The textbook alternative is the score interval of Wilson (1927). It keeps every that passes the test , with the true inside the square root. Solving the quadratic in gives an interval centred at , pulled toward , which never goes negative. Its upper end is , about at .
The Clopper–Pearson interval inverts the exact binomial tails instead. Its coverage is at least the nominal level for every , and it pays for that in width. At the level (95.45%) it gives for and an upper bound of for .
Which one to quote? Deltakit’s asymmetric pipeline, from calculate_lep_asymmetric to calculate_lambda_asymmetric, works with likelihood intervals, so use those for anything you fit. For a single headline bound, Clopper–Pearson is the conservative standard. Either way, state the method and the level next to the number.
Worked example: three fresh runs
SI1000, , rounds , PyMatching, seed 2026, 10,000 shots each
: 9 failures, . Wald gives , the likelihood interval at gives , and Wilson gives .
: 0 failures. Wald refuses. The likelihood interval is , or at Deltakit’s default .
at : also 0 failures, so the interval is identical. A zero count carries no information except , and these two runs cannot tell the noise levels apart.
To reach a target relative error , you need about failures, so shots. The , memory fails about 250 times per million shots (228 to 254 over four seeds of a million shots; Lecture 6’s 400,000-shot run has 87, about 220 per million). It needs about 390,000 shots for 10% and 4.4 million for 3%. A logical error of needs shots for 10%. That is why small logical errors are extrapolated through rather than sampled directly.
Comparing two estimates
To ask whether two LEPs differ, compare their logarithms. For counts and with ,: again set by failures, not shots. In Notebook 6 at , and fail 9,495 and 9,932 times in 200,000 shots. The log ratio is , a difference. The pair gives , only . This is the arithmetic behind the threshold crossings and their error bars (Thresholds).
In Deltakit
Both helpers live in deltakit.explorer.analysis. calculate_lep_asymmetric(fails, shots, *, max_likelihood_factor=1000.0) takes sequences and returns three arrays: low, best and high.
import mathfrom deltakit.explorer import analysis as ann = 10_000for f in (9, 0): # d = 5 and d = 7, p = 1e-3 lo, best, hi = an.calculate_lep_asymmetric( [f], [n], max_likelihood_factor=math.e**2) print(f, f"[{lo[0]:.1e}, {hi[0]:.1e}]")p, s = an.calculate_lep_and_lep_stddev( fails=9, shots=n)print(f"Wald: {p:.1e} ± {2 * s:.1e}")try: an.calculate_lep_and_lep_stddev( fails=0, shots=n)except ValueError: print("Wald: refuses 0 failures")
The asymmetric helper is vectorised: pass the counts of all distances at once and index the three arrays. Its max_likelihood_factor is the above. Pass sequences or Python ints: a bare NumPy scalar such as np.int64(9) raises TypeError: len() of unsized object, while a list or array of them works. The per-round fit and the default fit take symmetric error bars like the Wald pair, so they inherit its small- problems; calculate_lambda_asymmetric takes the likelihood interval ends instead. Give every point at least a few tens of failures before fitting.
The default is not a 99% interval
The source comment on DEFAULT_MAX_LIKELIHOOD_FACTOR calls “roughly a 99% interval”. Its Gaussian equivalent is , which is 99.98% two-sided. For it is the one-sided 99.9% bound, . With many failures the default bar is about 1.9 times wider than a bar, and with none it is 3.5 times wider. Pass max_likelihood_factor explicitly and quote next to the number.
Bounds are not measurements
Do not feed to a fit as if it were a measured . Neither fit can use a zero. calculate_lambda_asymmetric raises ValueError. The default calculate_lambda_and_lambda_stddev is worse: it silently drops that distance and fits the rest, with only NumPy warnings. Run more shots at that distance until it fails a few tens of times.
Related cards: Logical error per round turns these totals into a per-round rate. The error-suppression factor Λ and Thresholds are built from the same counts.
QA run gives 0 failures in 10,000 shots, and calculate_lep_and_lep_stddev raises ValueError. What do you report?
AAn upper bound. With the plug-in error is zero, so Deltakit refuses. calculate_lep_asymmetric gives : at , or at (the rule of three). The same bound holds whatever the true noise is, because it depends only on .
A run of rounds fails with , where . Fit against : the slope gives and the intercept gives the SPAM term . One run with adds to .
The model: bulk rounds and two ends
A memory run has three parts: state preparation, rounds of stabiliser measurement, and a final readout of the data qubits. Model the bulk as independent rounds, each flipping the logical with probability . Lump both ends into one extra flip with probability (SPAM, for state preparation and measurement). The logical comes out wrong when an odd number of these flips occur. For independent flips with probabilities ,, so
This is a straight line in : its slope gives and its intercept gives . Inverting one run instead gives
The error of a single run falls only as . is a boundary correction, not a probability. It comes out negative when the two ends of the run fail less often than the bulk rounds they replace. A useful reading is : the number of extra bulk rounds that the two ends are worth.
What Deltakit fits
compute_logical_error_per_round(num_rounds, leps, lep_stds, *, force_include_single_round=False) lives in deltakit.explorer.analysis. It works in four steps.
Clean. It drops and any LEP above 0.5, with a warning. Above 0.5 the logarithm is undefined, and near 0.5 it is mostly noise: a run that long has nearly forgotten its logical state. It also drops ,silently, unless force_include_single_round=True. The source justifies this with boundary effects and points to the supplement of Google Quantum AI 2023.
Fit. A weighted least-squares line (SciPy curve_fit, absolute from your error bars). The source says it follows the Methods of arXiv 2505.09684. Its Methods fit , the same log-linear idea without the factor 2. The form used here is that of Google Quantum AI 2023.
Map back. and , with propagated errors.
Shortcut. With only one usable round count, it sets and warns that it is “assuming that SPAM error is negligible”. That is exactly the rounds shortcut.
It also warns when the largest LEP is below 0.2, or when . It returns LogicalErrorProbabilityPerRoundData, with fields leppr, leppr_stddev, spam_error and spam_error_stddev.
Worked example: SPAM changes sign with
SI1000, ,, PyMatching, seed
(1,000,000 shots per ): and , so .
(2,000,000 shots per ): and , so .
Single runs with : () and ().
The two-distance ratio : 6.09 from the single runs, against 5.42 from the slopes.
Cost: the whole probe, both distances with every round count, ran in 21 seconds on a laptop.
So at the two ends add the equivalent of 0.19 bulk rounds, while at they remove 0.35 rounds. These runs measure only that net effect; they do not say which fault paths cause it. The intercept is also much less precise than the slope: at and at , against 0.4% and 0.7% for .
The ratio follows directly from the two biases: . The bias has a fixed pattern: is positive at and negative at and 7 (at about , resolved only at a million shots), which steepens the line. Lecture 6’s three-distance data show the same thing. There the shortcut gives (400,000 shots per distance) and the slope fit (200,000 shots per run). At a million shots with seeds 11 and 12, the shortcut gives 5.81 and 5.87 and the slope 5.40 and 5.41 (one seed for every ; a separate seed per gives 5.43 and 5.46). More shots only tighten the error bar around the wrong value.
Choosing the round counts
For , a run of rounds gives , from and . Longer runs therefore buy precision per shot, though each shot costs more. The two fit parameters need different runs. Long runs pin the slope, and short runs pin the intercept. Refitting without the two shortest runs ( to 40 only) moves by 0.08% but from to . A good design spreads the round counts geometrically, from 2 or 3 up to the point where approaches 0.2. Deltakit can pick the round counts for you:
Here simulator(r) must return (fails, shots). The helper doubles until the LEP passes 0.25, steps back if the last run passed 0.45, and returns arrays of rounds, fails and shots. At and , with 20,000 shots per call, it ran (LEP 0.008 to 0.33). The fit gave . Doubling gives the geometric spread of round counts that the slope and the intercept both need, without any tuning. The docstring’s own example passes a keyword geometric_factor, which the function does not have.
In Deltakit
The counts are the runs of the worked example, one seeded StimDecoderManager run per round count:
from deltakit.explorer import analysis as anrounds = [2, 3, 5, 10, 20, 40]fails = [745, 1050, 1955, 3928, 8270, 16545]n = 2_000_000 # shots per round count, d = 5lep, std = [], []for f in fails: p, s = an.calculate_lep_and_lep_stddev( fails=f, shots=n) lep.append(p) std.append(s)fit = an.compute_logical_error_per_round( rounds, lep, std)e, se = fit.leppr, fit.leppr_stddevprint(f"eps = {e:.3e} ± {se:.1e}")print(f"SPAM = {fit.spam_error:+.1e}")one = (1 - (1 - 2 * lep[2]) ** (1 / 5)) / 2print(f"r=5 alone: {one:.3e}")
The call also prints a warning that the largest LEP (0.008) is below 0.2. That is advice about shot efficiency, not a sign of a bad fit. Reaching 0.4 at would take thousands of rounds.
One seed for every round count correlates the pointsStimDecoderManager passes its seed to Stim’s sampler. Two circuits with the same seed draw identical noise for the rounds they share, within the first batch of shots. At in a 100,000-shot batch, the first-round detectors of the and runs agree in every shot. 457 of the 588 failures at also fail at (correlation 0.55). The fit assumes independent points, so its error bars are not what they claim. Seed each round count separately, for example seed + r.
is dropped without a word
A one-round run is not on the line: at , its single-run estimate is , against about for longer runs. With one round, the only round touches both ends, so the split into bulk rounds and two separate ends no longer applies. Deltakit removes it unless forced. Forcing it in moved from to , while moved by 1.5%.
Related cards: Logical error probability and its uncertainty supplies the error bars. The error-suppression factor Λ consumes , and QuOps and resource prediction turns it into budgets.
QYou fit at from one run each with rounds , then run ten times more shots. Does the gap to the slope-fit close?
ANo. Each single run estimates , and changes sign between and . That bias does not shrink with shots: at a million shots the shortcut still gives against 5.4 from the slope.
The threshold is where the curves for different cross: below it, larger codes fail less. It depends on the noise model, the decoder and per-shot or per-round counting. Being below it is necessary, not sufficient.
What the crossing means
Below threshold, the cheapest logical failure needs about faults, so falls like and adding distance helps. Above it, the number of failure paths grows faster with than their probability shrinks, so adding distance hurts. The crossing of the curves for and estimates the boundary between the two regimes.
Dennis et al. 2002 made this sharp. Optimal decoding of the surface code maps onto a disordered statistical-mechanics model, and the threshold is its phase transition. Near a transition, finite-size scaling predicts
so all curves pass through one point only as . At small the pairwise crossings drift.
That a threshold exists at all is the threshold theorem, proved in the late 1990s by Aharonov and Ben-Or, by Knill, Laflamme and Zurek, and by Kitaev. For local, weakly correlated noise there is a below which any circuit can be run to any target accuracy with only polylogarithmic overhead. The proven constants are far below the numerical ones, so in practice a threshold is something you measure, not something you derive.
Do not confuse the threshold with the pseudo-threshold of a single code, the at which (break-even against one bare qubit).
Three settings, three numbers
Each layer of realism adds failure paths, and the threshold drops. Phenomenological noise adds faulty syndrome bits, so matching runs on a three-dimensional space-time graph instead of a two-dimensional one, and errors can hide in time. Circuit-level noise adds faults inside the syndrome circuit itself. One fault on a measurement qubit can spread to two data qubits (a hook error), and readout, reset and idling all fail too.
setting
what is noisy
threshold (decoder)
code capacity
data qubits only
10.3% (matching)
phenomenological
data and syndrome bits
2.9% (matching)
circuit level
every gate, idle, reset, readout
0.57% (matching)
The first two rows come from the zero-temperature critical points computed by Wang, Harrington & Preskill 2003: for the random-bond Ising model and for the random-plaquette gauge model. Optimal decoding does slightly better: their abstract cites from earlier numerical studies, the critical point on the Nishimori line. The circuit-level figure is the per-step threshold for depolarising noise in Fowler et al. 2012. Only that row models the circuit, and only for its own noise model.
Worked example: the SI1000 sweep of Notebook 6
SI1000, Z memory, rounds , PyMatching, StimDecoderManager(seed=2026, batch_size=100_000)
Each entry is the number of logical failures in 200,000 shots.
1494
602
259
2617
1511
759
4173
2834
1746
5614
4586
3541
7440
7066
6021
9495
9932
9690
11488
13250
14284
13740
16938
19622
18872
25421
32590
Interpolating linearly in gives the crossings: for and for . The crossing drifts upward with , so the smallest pair understates the threshold. Note that is SI1000’s two-qubit error. Its readout flips at , so at the crossing every measurement is wrong 2% of the time.
How sure is a crossing?
Near threshold the curves are almost parallel, so a small error in the counts moves the crossing a lot. Each cell has about 10,000 failures, so is known to about at each grid point and to about at the interpolated crossing. Across the bracketing interval it changes by only 0.72 to 0.85 per unit of , so the crossing is known to about 1.5%.
A parametric bootstrap agrees. It redraws every cell from a binomial with the measured rate (4,000 replicas, cells treated as independent). The crossing is and the crossing . The drift between them, , is 3.8 bootstrap standard errors, and the larger pair crosses later in over 99.9% of replicas. Notebook 6 sampled every cell with one seed; over 60 seeds the drift averages , so this sweep sits about high, but the sign holds for 98% of seeds. So the drift is a real finite-size effect, not noise. More shots will not remove it; larger distances will.
Per shot or per round?
The table compares -round blocks, so the larger code also runs longer. With , the per-shot curves cross where . That is a per-round of for and for : the code is still suppressing errors per round there. So the per-shot crossing sits below the per-round one, and the gap closes only as .
A fresh sweep measures the gap. It used slope fits over with 50,000 shots per run and a separate seed per . Per round, cross near and near : 1.4 to 1.7 times the per-shot values, and drifting the other way. Converting the Notebook 6 table point by point does not show this crossing. Each point there still carries its SPAM term, and those per-round curves have not crossed by :, 2.85 and for . The fresh single-run values cross later too, near for . Always state which convention a threshold uses.
Below threshold is not useful yet
Being below threshold only means . The cost depends on how far below. Slope fits over 5 to 40 rounds (200,000 shots per run) give:
for per round
qubits per patch
5.46
21
881
2.64
35
2,449
1.77
61
7,441
The distance scales like and the qubit count like . At three-quarters of the per-shot threshold, a patch costs 8.4 times more than at a quarter of it.
In Deltakit
Deltakit has no threshold function. Run a seeded StimDecoderManager sweep, as in the table, and locate the crossings yourself. For the per-round version, fit each point with compute_logical_error_per_round (see Logical error per round).
import numpy as npps = np.array([3.0, 3.5, 4.0, 4.5]) * 1e-3f = {3: [5614, 7440, 9495, 11488], 5: [4586, 7066, 9932, 13250], 7: [3541, 6021, 9690, 14284]}def cross(a, b): g = np.log(np.divide(f[a], f[b])) i = np.flatnonzero(np.diff(np.sign(g)))[0] t = g[i] / (g[i] - g[i + 1]) lp = np.log(ps) return np.exp(lp[i] + t * (lp[i + 1] - lp[i]))for a, b in [(3, 5), (5, 7), (3, 7)]: print(f"d={a}/{b}: {cross(a, b):.2e}")
d=3/5: 3.76e-03
d=5/7: 4.12e-03
d=3/7: 3.95e-03
A threshold without its conditions means nothing
“The surface code threshold is 1%” leaves out four choices: the noise model, the decoder, the distances compared, and per-shot or per-round counting. SI1000’s and Fowler’s use different noise models, so neither number transfers to the other. Quote all four with the number, for example “SI1000, PyMatching, , per shot: ”.
Related cards: The error-suppression factor Λ measures the distance below threshold. Logical error per round gives the per-round curves, and Logical error probability and its uncertainty gives the error bars on each point.
QYour rounds curves for and cross at . At , is a patch worse per round than a patch?
ANot necessarily. A rounds run of lasts 7 rounds, against 5 for , so the per-shot curves cross where , while still wins per round. With slope fits the per-round crossing sits near , and at the slope fits give .
is the factor by which the logical error per round falls when :. means below threshold. Fit it on per-round errors, never on total LEP.
Why the exponent is
For odd , the cheapest logical failure is a chain of faults. Each fault costs a factor of about , so the leading term is
This is the scaling form in Fowler et al. 2012. Writing and gives the formula on the face. The two-point version is simply . Experiments with only two distances quote that ratio directly.
Read as a statement about orders of magnitude. Compare like with like. Our slope-fit gives at , and the per-round crossings of the curves sit near – (Thresholds). The per-shot crossings of Notebook 6, –, use another convention. Path counting and boundary effects still shift the prefactor, so treat as an estimate of , not a measurement.
What the fit takes as input
The input is , the logical error per round. An -round memory run gives a total . If rounds fail independently, a logical flip survives only when an odd number of rounds fail:
A single folds state-preparation and readout error into . The better practice is to run several values of at each and fit the slope; that is compute_logical_error_per_round, on the card Logical error per round. This card uses one run with per distance. That shows how the fit works, but it biases upward; the trap after the worked example puts a number on it.
Deltakit’s default fit (LambdaFitMethod.LIN) works as follows:
It regresses on by weighted least squares, with NumPy weights , so each squared residual counts .
Then and .
The covariance is unscaled: the error bars come from your input only, not from the scatter about the line. Curvature in the data therefore never widens lambda_std.
It warns when and the smallest distance is below 5.
The docstring’s only reference is Fig. S15 of the Nature supplement of Google Quantum AI 2024 (Nature 638, 920), ‘The crossover regime’. In a Pauli simulation, error suppression saturates when but continues when , matching the 1.5 in the warning. The arXiv supplement numbers its figures differently.
Worked example: SI1000 at
Three distances, 400,000 shots each, rounds , PyMatching
Failures: 1409, 368 and 87, giving = , and . The consecutive ratios are and . These agree within errors, so a single is a fair summary. The fit gives and .
The rounds shortcut overstates
With one run per distance, each carries its own share of preparation and readout error. In this model that share is positive at and negative at and 7 (at about , resolved only at a million shots), which steepens the line. Fitting the slope over 5, 10, 20 and 40 rounds instead gives and (200,000 shots, Lecture 6). At a million shots, with seeds 11 and 12, the slope fit gives and (one seed for every ; a separate seed per gives 5.43 and 5.46), while the shortcut still gives and . Plan with the slope fit.
For scale, Willow’s memory reported [PUBLISHED, Nature 638, 920; Google Quantum AI 2024]. That is hardware noise with its own decoders, so it is not comparable with a simulated model. belongs to a code, circuit, noise model and decoder taken together.
In Deltakit
The failure counts come from one seeded run per distance: StimDecoderManager(dcirc, decoder, seed=SEED, batch_size=100_000).run_batch_shots(400_000), where dcirc is the circuit returned by PyMatchingDecoder.construct_decoder_and_stim_circuit (see Matching and PyMatching). Each point takes a few seconds on a laptop. The fit itself lives in deltakit.explorer.analysis:
Two conventions for (Deltakit 0.10.2)LambdaData.lambda0 means . The QuOps helpers instead assume , so pass the reciprocal. A QuOp here is one -round block, and the helper returns for that block.
quops = an.predict_quops_at_distancefor d in (11, 15): good = quops(1 / L0, L, d) bad = quops(L0, L, d) print(f"d={d}: {good:,.0f} (not {bad:,.0f})")need = an.predict_distance_for_quopsprint(need(1 / L0, L, 1e6), need(L0, L, 1e6))
Passing lambda0 unchanged understates QuOps by about . For a million QuOps it then asks for (881 qubits) where (449 qubits) is enough.
From to a qubit count
The main use of is budgeting. Inverting the scaling law gives the smallest distance that reaches a target error per round :
rounded up to the next odd integer. With the fit above:
needs , which is 721 physical qubits for one rotated surface-code patch ();
needs , which is 1,457 qubits.
Check the second case forwards: at the model gives , just under the target. The slope-fit asks for more: (881 qubits) and (1,681 qubits). The shortcut’s bias alone would under-provision the first target by 160 qubits.
Distance scales like
The required is inversely proportional to . Doubling from 2 to 4 therefore roughly halves the distance and cuts the qubit count by about four. That is why hardware groups chase rather than raw physical error rates. To see which noise source to improve first, use the Error budgets card. These are extrapolations from three small distances, so treat them as planning numbers, not guarantees; the trap below says why.
When to trust a and its extrapolation
Ratios before fits. Check that consecutive ratios agree within their errors before you compress them into one number.
Enough failures at the largest . 87 failures gives about on . With zero failures, calculate_lep_asymmetric still gives an upper bound, but neither fit can use it: calculate_lambda_asymmetric raises ValueError, and calculate_lambda_and_lambda_stddev silently drops that distance and fits the others. Run more shots until the largest fails.
Scaling regime. Use at least three distances. often sits outside the regime where the formula holds.
A fit is not a guarantee at large
Extrapolation assumes the same error mechanisms at every size. Willow’s repetition-code runs up to hit a floor from rare correlated error events, about once per hour or roughly cycles [PUBLISHED, Nature 638, 920; Google Quantum AI 2024]. A memory simulation with independent Pauli noise can never show such a floor.
Related cards: Logical error per round, Thresholds, QuOps and resource prediction. This card does not establish thresholds; that is the Thresholds card’s job.
An error budget splits among noise sources: at , so . It ranks which error to reduce a little, not what removing a source buys.
What is being split
Write as a function of the noise parameters, for example a gate error and a readout flip. Below threshold , so scaling every parameter by scales by about . In other words, is roughly homogeneous of degree one. Euler’s theorem then gives exactly, and the gradient is the same anywhere along the ray through .
Google Quantum AI 2021 take a slightly different route in the supplement section “Error Budgeting: Constructing a Linear Model Relating Component Errors to Inverse of Lambda”. They model with . For such a quadratic, the gradient at the midpoint reproduces the endpoint exactly: . Both views lead to
Read as a sensitivity: lowering by a small fraction lowers by about . In that experiment the simulated budget accounted for about 85% of the measured , and the authors attribute the rest to effects outside the model. That gap is what plot_error_budget draws as “excess”.
What get_error_budget computes
The function lives in deltakit.explorer.analysis.error_budget. It runs in five steps.
It moves to the point .
For each parameter , it picks num_points_per_parameters values inside your bounds (log-spaced by default) and holds the others at . That makes noise points for parameters and values each.
At each point and each distance and round count, it builds a rotated surface-code Z memory and applies your noise_model(circuit, x). It decodes with PyMatching on the circuit from construct_decoder_and_stim_circuit, sampled by a StimDecoderManagerwithout a seed. It then fits , then , then .
It fits a weighted polynomial of degree fitting_degree (default 3) to against and differentiates it at .
It returns contributions (absolute values) and contribution_stddevs.
lambda_estimate is documented as an “estimation of Λ”, but it is the sum of the contributions, which is .
Worked example: reading a budget
ToyNoise with two knobs: two-qubit depolarising (single-qubit, idle and reset at ) and readout flip , distances 3 and 5, 10 rounds each, 300,000 shots per task. Lecture 6 found and ; an identical rerun gave 0.182 and 0.073. The gate takes about 72% of the budget.
The sensitivities are for the gate and for readout. Per unit of error, the gate does eight times more damage, and it also has the larger share, so improve gates first. A seeded check with the same estimator and a million shots per distance gives at . Halving lowers it to 0.132, a drop of 0.078 where the budget predicts 0.090. Halving lowers it by 0.019 where the budget predicts 0.033. Halving both gives 0.102, so : close to homogeneous.
The readout direction is less tidy. Along it the seeded runs give , 0.191 and 0.210 at , and : flat within the error bars up to the midpoint, then rising. A single slope taken at the midpoint cannot describe such a curve, so the budget’s readout prediction misses at both ends. The gate direction is closer to linear: there the predicted drop, 0.090, is within 0.012 of the measured 0.078.
A second operating point
A budget describes one operating point, and the ranking can flip elsewhere. Take a readout-heavy device, . Two unseeded budget runs give readout about 0.29 and gate at most 0.015, summing to 0.30. The seeded runs agree: (). Halving readout lowers it to 0.175, and halving the gate only to 0.31. Here the budget ranks correctly, and the advice is the opposite of the advice at .
So use a budget in three steps. Rank the sources at the current point. Simulate the end point of the change you plan, because a contribution is not a saving. After a hardware change, recompute the budget at the new point.
In Deltakit
The budget call has no seed and draws progress bars, so it is shown but not run here (8 s at these settings):
A seeded check of its predictions, using the same estimator (; 10 rounds; one run each, so ). Each call samples one 10-round memory and converts its LEP to a per-round rate; the ratio of the two rates is :
Contributions are not what removing a source buys
With readout set to zero, the budget predicts , but the run gives 0.195. With the gate error set to zero, it predicts 0.029 and the run gives 0.087. The function is not additive: , while . The budget is also local: at above, the gate’s sensitivity falls from 90 to near zero (gate and , each ).
Bounds, cost and seeds
Bounds must bracket , not (the docstring says ). Bounds around raise ValueError: Expected a=0.0012 < c=np.float64(0.001) < b=0.004.
Cost. The defaults are 10 points per parameter and max_shots=10_000_000. The lep_target_rse=1e-4 stop needs about failures, so in practice every task runs to max_shots. Two knobs at two distances then mean 21 noise points, 42 tasks and up to shots. Lecture 6’s settings need .
No seed. Repeat runs differ; quote each with its error.
Related cards: The error-suppression factor Λ defines the quantity being split. Logical error per round supplies , and QuOps and resource prediction turns a better into qubits.
QA budget gives readout a contribution of 0.066 out of . A vendor promises perfect readout. What should you expect?
ANot . A contribution is , a statement about small changes. Seeded runs with the readout flip set to zero give : along the readout direction is flat up to the midpoint and only then rises, so a slope taken at the midpoint overstates what removing readout buys. Simulate the end point before promising what an upgrade buys.
A QuOp is one -round block of a distance- patch, and QuOps of that block. Deltakit’s helpers turn into QuOps or into a distance; a patch costs qubits. Pass them 1/ld.lambda0.
What a QuOp counts
Deltakit counts quantum operations (QuOps) as the number of -round blocks a patch survives, on average, before its first logical error. Why rounds: a lattice-surgery operation measures its stabilisers for about rounds, so that error chains running in time are as long as those running in space (Horsman et al. 2012). With the per-round model of The error-suppression factor Λ,
The middle formula is the odd-flip sum from Logical error per round. The source attributes it to Section VI.B of the supplement of Google Quantum AI 2024. For ,, so each step multiplies QuOps by about , a little less than because the block also gets longer.
QuOps is a memory figure of merit. It ignores magic-state supply, routing, decoder latency and any error source that is not in the fit. Treat it as an upper bound on what one patch can do.
The three helpers
All three live in deltakit.explorer.analysis.
predict_quops_at_distance(lambda0, lambda_, distance) returns . Its only check is that is odd.
predict_distance_for_quops(lambda0, lambda_, num_quops, max_distance=999) searches the odd from 1 upward. It returns the first with num_quops, and raises if num_quops or .
predict_quops_interval(lambda_data, distance) propagates confidence bounds from calculate_lambda_asymmetric. It needs those bounds: a symmetric LambdaData raises ValueError.
Their lambda0 argument means . That is the reciprocal of the lambda0 that LambdaData returns (trap 8 on the Λ card). Passing it unchanged understates QuOps by , which is 895 for the slope fit.
The physical cost of one rotated surface-code patch is data qubits plus measurement qubits, in all. QuOps grow exponentially in , so qubits grow only like .
Each extra decade of QuOps costs about in distance: 2.7 for the slope fit. The staircase in the figure climbs a little faster, 2.9 per decade between and 33, because each block also gets longer. A QuOps target is also stricter than a per-round target of the same size. The Λ card sizes a patch for per round and gets from the slope fit. QuOps needs , because one QuOp is rounds long and .
Worked example: what the shortcut’s bias costs
Lecture 6’s SI1000 counts at ,
Slope fit over 5 to 40 rounds: ,. Rounds shortcut on separate runs: ,.
target
slope fit
shortcut
slope fit, lambda0 not inverted
, 449 qubits
, 449
, 1,057
, 1,249
, 1,057
, 2,177
, 2,177
, 1,921
, 3,361
The shortcut overestimates both and . The two errors cancel inside the measured range, , but not beyond it: at the shortcut promises 2.2 times more QuOps. Both fits still clear there. At the larger targets the shortcut asks for one step less.
The target is a count over the whole machine. For patches that each run blocks, you need , so the target is , not . Take 100 patches and blocks each, in all. The slope fit picks : 124,900 physical qubits and 0.22 expected failures. The shortcut picks and saves 19,200 qubits. Under the slope model, that machine expects 1.1 failures instead.
Error bars on QuOps
predict_quops_interval has the same convention problem built in: it passes lambda_data.lambda0 straight to the helper. Feed it calculate_lambda_asymmetric with for the slope fit, and at it returns [1,417, 1,758, 2,256] instead of about . The fix is to invert and swap its bounds with dataclasses.replace, as in the snippet below. That gives .
Even fixed, the band is wide. The docstring says the widest QuOps comes “from the largest Λ together with the smallest Λ₀”, so the helper pairs the corners of two separate intervals. But the fitted slope and offset are strongly anticorrelated, with correlation . Propagating the full covariance gives to (a ratio of 1.30) instead of 1.59. At the two ratios are 1.64 and 2.00. The corner rule is conservative, which is the safe direction.
In Deltakit
The fit repeats Logical error per round on Lecture 6’s counts (200,000 shots per run):
from deltakit.explorer import analysis as anfails = {3: [1199, 2273, 4489, 8626], 5: [177, 394, 832, 1630], 7: [30, 63, 129, 273]}eps, std = [], []for fs in fails.values(): lep, sd = zip(*( an.calculate_lep_and_lep_stddev( fails=f, shots=200_000) for f in fs)) fit = an.compute_logical_error_per_round( [5, 10, 20, 40], list(lep), list(sd)) eps.append(fit.leppr) std.append(fit.leppr_stddev)ld = an.calculate_lambda_and_lambda_stddev( [3, 5, 7], eps, std)L, L0 = ld.lambda_, 1 / ld.lambda0 # invert!quops = an.predict_quops_at_distanceneed = an.predict_distance_for_quopsfor d in (11, 15, 21): print(f"d={d}: {quops(L0, L, d):.3g} QuOps")for t in (1e6, 1e9, 1e12): d = need(L0, L, t) q = 2 * d * d - 1 print(f"{t:.0e}: d={d}, {q:,} qubits")
The interval helper, as shipped and with inverted:
import dataclassesfrom deltakit.explorer.analysis import ( ConfidenceInterval)lo = [e - s for e, s in zip(eps, std)]hi = [e + s for e, s in zip(eps, std)]asym = an.calculate_lambda_asymmetric( [3, 5, 7], eps, lo, hi)b = asym.lambda0_intervalfixed = dataclasses.replace( asym, lambda0=1 / asym.lambda0, lambda0_interval=ConfidenceInterval( low=1 / b.high, best=1 / asym.lambda0, high=1 / b.low))for x in (asym, fixed): q = an.predict_quops_interval(x, 15) print(*(f"{v:,.0f}" for v in (q.low, q.best, q.high)))
1,417 1,758 2,256
1,258,622 1,572,737 2,004,861
Floating point limits the helpers past QuOps
The helpers compute in double precision. At the design () that is already 0.2% off. Once drops below , rounds to 1 (at it is already 8% off). For the slope fit this happens at :predict_quops_at_distance raises ZeroDivisionError, and predict_distance_for_quops returns 41 for every target above . The exact answer for is . Use expm1 and log1p by hand for large targets.
max_distance is exclusive
The search stops beforemax_distance. With max_distance=15 it fails for a target even though the answer is 15, and the message says it searched “[1, 15]”. Leave the default, or pass an odd bound above the answer.
Related cards: The error-suppression factor Λ gives the fit and trap 8. Logical error per round supplies , and Error budgets says which noise source to improve for a larger .
QYou need 100 logical patches, each running -round blocks. The rounds fit picks , the slope fit . What does the smaller patch cost you?
AIt saves physical qubits. Under the unbiased slope fit, though, expects 1.1 failures in the blocks, against 0.22 at . A 15% bias in became a fivefold rise in expected failures.
deltakit_stim: Stim fork (+ leakage)deltakit.circuitdeltakit.coredeltakit.decode+ PyMatchingdeltakit.explorerdeltakit_compile+ xDSLdeltakit_visualisedeltakit.* names: aliasesRiverlane cloud6 decoder classesclient=uv pip install deltakit pulls in all seven
One install, seven packages. Four have deltakit.* names (circuit, core, decode, explorer); the Stim fork, compiler and visualiser import as deltakit_stim, deltakit_compile, deltakit_visualise. Only six cloud decoders leave your machine.
What one install brings
deltakit 0.10.2 is a meta-package: it contains almost no code and requires six distributions, each within a version range (Version pins), which pull in a seventh, deltakit-stim. Each distribution installs a top-level module whose name swaps the hyphen for an underscore:
import name
holds (version)
deltakit_circuit
gates, circuits, noise (0.9.2)
deltakit_core
decoding graphs (0.9.2)
deltakit_decode
matching, run loops (0.9.2)
deltakit_explorer
codes, QPUs, analysis (0.9.4)
deltakit_stim
the Stim fork (0.2.7)
deltakit_compile
logical programs (0.1.0)
deltakit_visualise
views of the IR (0.4.0)
The meta-package adds a thin deltakit namespace on top. Its deltakit/circuit/__init__.py is in effect one line, from deltakit_circuit import *, and the same holds for core and explorer. The decode one also imports the six cloud decoder classes from deltakit-explorer (Local or cloud). So deltakit.circuit.Circuitisdeltakit_circuit.Circuit, the same class object. There is no alias for the other three, and deltakit itself exports one name, Client, the cloud client from deltakit-explorer. That is why types print with underscores (deltakit_circuit._circuit.Circuit) even when you imported them with a dot.
Who depends on whom
The figure is the runtime dependency graph between Deltakit packages, read from the installed metadata; third-party needs such as NumPy are left out. At the bottom sits deltakit-stim, the only Deltakit package that circuit and core need. Decode adds circuit, core and PyMatching (2.4.0 here). Explorer adds decode and, among others, galois, gql and requests. On a separate branch, deltakit-compile needs deltakit-stim and xDSL (>=0.66,<0.69), and deltakit-visualise needs the compiler and narrows xDSL to 0.66.x, the version installed here.
Two consequences matter in practice. First, the decoding stack and the compiler meet only in deltakit-stim: the compiler emits Stim text, and the decoding stack can read it (deltakit-compile and logical assembly). Second, upstream stim, sinter and ldpc are not dependencies, so they are not installed. Code from Stim tutorials that says import stim fails until you change it to import deltakit_stim as stim.
Python versions differ too: the four deltakit.* packages and the fork accept Python 3.11 to 3.15, while deltakit-compile and deltakit-visualise stop at 3.14. On 3.15, pip therefore installs a development snapshot of the compiler instead of 0.1.0. A Python 3.12 environment, which this primer uses, satisfies all of them.
Where each call of the first experiment lives
Lecture 0’s memory experiment touches every package of the left-hand stack. Reading the imports against the map:
RotatedPlanarCode and css_code_memory_circuit come from deltakit.explorer.codes, and QPU with SI1000Noise from deltakit.explorer.qpu. The explorer is the user-facing layer: codes, hardware models and analysis.
The circuit they produce is a deltakit.circuit.Circuit, with gates and noise channels from the same package.
PyMatchingDecoder and StimDecoderManager come from deltakit-decode, which builds its matching graph with deltakit.core.decoding_graphs and hands it to PyMatching.
The samples themselves are drawn by deltakit_stim, whatever wrapper you call.
calculate_lep_and_lep_stddev and the Λ fit are back in deltakit.explorer.analysis.
So a traceback that ends in deltakit_decode is a decode problem even if your code only imported from deltakit.explorer.
To find the home of any name, ask the class itself. BPOSDecoder.__module__ is 'deltakit_explorer._cloud_decoders', although you imported it from deltakit.decode, and RotatedPlanarCode.__module__ is 'deltakit_explorer.codes._planar_code._rotated_planar_code'. The leading part names the package, which is also the repository whose tracker gets the bug report.
Local or cloud
Everything runs on your machine except six decoder classes: MWPMDecoder, CCDecoder, BeliefMatchingDecoder, BPOSDecoder, ACDecoder and LCDecoder. They are defined in deltakit_explorer._cloud_decoders and re-exported from deltakit.decode, next to the one local decoder, PyMatchingDecoder (from deltakit_decode._mwpm_decoder). Constructing a cloud class without client= raises NotImplementedError: Currently, a `client` must be provided to instantiate this class. before any network traffic. So “it imports from deltakit.decode” says nothing about where it runs. A bug in a cloud wrapper belongs to deltakit-explorer.
Version pins
The meta-package does not pin exact versions. It asks for ranges: circuit, core and decode >=0.9.2,<0.10, explorer >=0.9.4,<0.10, compile >=0.1.0,<0.2 and visualise >=0.4.0,<0.5. Installing deltakit==0.10.2 next month can therefore bring newer patch releases of the parts. To reproduce a page exactly, install from the course’s lock file, or compare your versions with the printout below.
Installing with uv
The course pins the versions above in its lock file; make lab builds that environment (Lecture 0). For a project of your own, uv does the same in two commands:
uv init --python 3.12 qec-play && cd qec-playuv add "deltakit==0.10.2"
The first import deltakit in a fresh environment is slow while caches are built; later imports are quick.
In Deltakit
importlib.metadata reads the installed versions, and importlib.util.find_spec tells you whether a module name resolves without importing it:
import importlib.metadata as mdfrom importlib.util import find_specimport deltakit.circuitimport deltakit_circuitfor d in ["circuit", "core", "decode", "explorer", "stim", "compile", "visualise"]: v = md.version(f"deltakit-{d}") print(f"deltakit-{d:<10}{v}")same = (deltakit.circuit.Circuit is deltakit_circuit.Circuit)print("one Circuit class:", same)for m in ["deltakit.compile", "deltakit_compile", "stim"]: print(f"{m:<17}", find_spec(m) is not None)
Three names that look right and are notimport deltakit.compile, import deltakit.stim and import stim all fail in this environment. Use deltakit_compile and deltakit_stim. Installing upstream stim next to the fork to “fix” an import gives you two families of Circuit and DEM classes that do not mix. PyMatching’s Matching.from_detector_error_model accepts only the upstream one (see The deltakit-stim fork).
Importable is not localfrom deltakit.decode import BPOSDecoder succeeds offline. Only the constructor tells you that it needs a token and a network.
Two version numbersdeltakit.__version__ is "0.10.2", the meta-package’s version. The code you run is deltakit-decode 0.9.2, deltakit-explorer 0.9.4 and so on. When you report a bug, give the version of the package it lives in, from importlib.metadata.version, not the meta-package’s.
Where to read further
The Deltakit repository holds the meta-package and the contributor guide; each package has its own repository and issue tracker (Contributing to Deltakit and the community fund). The Deltakit documentation covers the API. The next card, The memory-experiment pipeline, walks one experiment through these packages, naming the object passed at each step.
QAfter pip install deltakit, which of these imports work: deltakit.decode, deltakit.compile, deltakit_compile, stim?
Adeltakit.decode and deltakit_compile. The meta-package adds deltakit.* aliases for circuit, core, decode and explorer only. The compiler and the Stim fork are imported by their own names, and upstream stim is not installed at all.
The types, read off with type(obj), are RotatedPlanarCode and QPU from deltakit-explorer, Circuit from deltakit-circuit (for both the ideal and the noisy circuit), PyMatchingDecoder from deltakit-decode, and a deltakit_stimCircuit and CompiledDetectorSampler. The code and circuit objects are Deltakit’s own. The moment you sample, you are in Stim (Sampling with Stim).
What each step decides
Code to circuit.css_code_memory_circuit(code, num_rounds, logical_basis) fixes the schedule: resets, rounds of stabilizer measurements, a final data readout, plus the DETECTOR and OBSERVABLE_INCLUDE annotations (Detectors and observables). No noise yet.
Circuit to noisy circuit. A QPU holds the qubits and a noise model. compile_and_add_noise_to_circuit first rewrites the circuit into the QPU’s native gates, then inserts the channels. Change the noise model here and nowhere else (Circuit noise models).
Noisy circuit to decoder.PyMatchingDecoder.construct_decoder_and_stim_circuit builds the detector error model and the matching graph, and returns a second circuit: the Stim circuit the decoder was built for. It drops detectors that cannot inform the observable. For a memory those are the -check detectors, so 24 become 16.
Sampling.compile_detector_sampler(seed=SEED) makes a Pauli-frame simulator (Gidney 2021), and sample returns detection events and true observable flips as separate arrays.
Decoding and counting. The decoder maps each row of detection events to a predicted flip. A shot fails when the prediction differs from the truth in any observable.
Where the seeds go
Two different seeds make a run reproducible, and neither one is enough on its own.
The sampler seed. Pass it to compile_detector_sampler(seed=…) or to StimDecoderManager(…, seed=…). It fixes the stream of random numbers. The manager also cuts the run into batches, and the cut matters: one batch of 100,000 shots gives 344 failures, ten batches of 10,000 give 356. The default batch_size is 10,000, so leaving it out changes the count. Both numbers are fine statistically, but they are different bits.
The string-hash seed. One layer of the generated circuit, the first data-qubit reset with its noise, is built from a Python frozenset. Its order, and hence which qubit gets which random number, follows PYTHONHASHSEED. The pages, notebooks and research scripts all run with PYTHONHASHSEED=0. Under PYTHONHASHSEED=1 the same run gives 340 instead of 344 (Lecture 0, Lecture 9). python -I silently ignores the variable; use python -P if you need isolation.
Some convenience functions take no seed at all. They are fine for exploring, but never quote a number from them. If a rerun of the block below does not give 344, check three things in order: the hash seed, the batch size, and the package versions (The Deltakit package map).
Swapping one piece
Because each step hands on one object, you can change one step and keep the rest:
Another code.RepetitionCode, UnrotatedPlanarCode and BivariateBicycleCode also feed css_code_memory_circuit. Matching may then fail at the decoder step: PyMatching cannot decode the bivariate bicycle codes (Bivariate bicycle codes and the gross code).
Another basis.logical_basis=PauliBasis.X gives an memory. The decoder again keeps 16 of the 24 detectors, now the -type ones.
Another noise model. Give the QPU an SD6Noise or ToyNoise model instead of SI1000Noise. Nothing upstream or downstream changes.
Another decoder. The six cloud decoders slot into the same place but need a client (The Deltakit package map).
Another circuit source. A circuit compiled by deltakit-compile enters at the noise step: wrap it with Circuit.from_stim_circuit and pass it to the QPU. Repair its observable first (deltakit-compile and logical assembly).
Reading the counts
decode_batch_to_logical_flip returns one row per shot and one column per observable. A shot fails if any column differs from the true flip, which is what np.any(pred != obs, axis=1) counts. With a single observable, that is a plain comparison. calculate_lep_and_lep_stddev then returns the failure fraction and its binomial standard error. That error assumes independent shots, which the sampler provides; a seed changes which shots you get, not their independence.
Worked example
The seeded run of Lecture 0 and Notebook 0, done by hand: distance 3, three rounds, SI1000 noise at , seed 2026, 100,000 shots. The noisy circuit has 24 detectors and the returned one 16. The detection-event rate is 0.0252 per detector per shot. Of the 100,000 shots, 344 fail, so
with standard error
That is the error of the whole three-round experiment, not per round (Logical error per round). Running the same chain at and , with as many rounds as the distance, is how the Λ card gets its slope.
In Deltakit
The chain, written out with the sampler instead of the manager so that every object is visible:
The manager and the hand-written loop agree because they draw the same 100,000 shots from the same seed in one batch.
The decoder’s circuit is not yours
Feed it samples from noisy.as_stim_circuit() and decoding raises a ValueError about 24 columns where 16 to 17 are expected. Sample from dcirc.
Related cards: The Deltakit package map, Detector error models, Logical error probability and its uncertainty, The error-suppression factor Λ.
QYou build the decoder from the noisy circuit noisy, then sample from noisy.as_stim_circuit() instead of from the circuit returned with the decoder. What happens for the d = 3, 3-round Z memory?
ADecoding fails with a ValueError: the samples have 24 columns but the decoder expects 16. The decoder kept only the detectors it uses. Always sample from the circuit it returns.
Write a program on logical patches with LogAsmBuilder, compile it with LogicalAssembler and StimExportPipelineConfig, get Stim text. The compiler finds every detector itself. Version 0.1.0 compiles memory-style programs only.
Logical assembly
A fault-tolerant computer runs two programs at once. The logical program says what happens to encoded qubits: prepare, measure in some basis, measure a product of Paulis across qubits, apply a transversal gate. The physical program is the circuit that does it: thousands of gates on data and ancilla qubits, with checks repeated every round. Logical assembly is the layer between them. Each instruction acts on a patch, a block of physical qubits holding one logical qubit at a fixed place on the chip. Lattice surgery (Horsman et al. 2012) and the Pauli-product view of computation (Litinski 2019) make that instruction set small. deltakit-compile turns such a program into a Stim circuit with every detector in place.
Two builders
The front end has two levels, and a program may use both.
CircuitBuilder (deltakit_compile.frontend.common) writes physical gates on a register: add_arg(QubitReg(n)), then gate("RZ", q) for a -basis reset, gate("H", q[0]), gate("CX", (q[0], q[1])), measure("Z", q). declare_observable().include([...]) marks measurements as an observable. build("name") returns a circuit you can call on a register.
LogAsmBuilder (deltakit_compile.frontend.logasm) writes the logical program. declare_patch takes either a QubitReg(n), for hand-written circuits run through call_circuit, or a RotatedPlanarPatch(width, height, location=(x, y)). A patch then has prepare(basis), measure_stabilisers(min_rounds), measure(basis) and transversal(gate). The builder adds multi_pauli_measure for lattice surgery and for_, if_, while_ for control flow. add_return names the outputs, and build_program() returns a LogAsmProgram.
Calling a built circuit, as in bell(reg), runs nothing. It records a call in the program, and the first compiler stage inlines it, so one circuit can be called on several registers. Printing a LogAsmProgram shows its IR. Patch instructions appear as operations such as log_asm.prepare<Z>, one per line, each consuming the patch value the previous one produced (xDSL dialects in deltakit-compile).
From program to Stim text
LogicalAssembler(config).compile(program) runs the pass pipeline and returns a CompilationResult with three fields: program (a string), module (the final IR) and auxiliary_outputs (a dict, empty in our runs). What program contains depends on the export configuration. With LogicalAssemblerConfig(export_config=StimExportPipelineConfig()) it is Stim text. With the default configuration it is the final physical IR, starting builtin.module {. Lecture 8 also sets verify_between_passes=True, which re-checks the IR after every pass; the default is False.
The compiler writes the detectors, so you never type a DETECTOR line. It follows the stabilizer flows of the circuit and declares a set of detectors that generates every product of measurements fixed when there is no noise. Observables are the exception: they appear only where you declared one.
Why a compiler, not a circuit generator
css_code_memory_circuit in deltakit-explorer also produces a memory circuit with detectors, so why compile? The generator knows one experiment: its detector logic is written by hand for “prepare, repeat rounds, read out”, and a new protocol needs new hand-written logic. The compiler knows rules instead. Detectors come from stabilizer flows, so any program it can lower gets detectors, including ones nobody planned for. A new logical instruction needs a new lowering, not new detector bookkeeping. Version 0.1.0 delivers this for memories and hand-written circuits only.
We built and compiled each instruction in our probes:
instruction
in 0.1.0
call_circuit on a register
compiles
call_circuit on a patch
builds, not lowered
patch prepare, measure
compiles, no observable
measure_stabilisers(1)
compiles
measure_stabilisers(3)
builds, ValueError
multi_pauli_measure
builds, not lowered
transversal
builds, not lowered
for_, if_, while_
does not build
So version 0.1.0 compiles memories and hand-written circuits on plain registers. “Not lowered” means the program parses and prints but stops at lowering with NotImplementedError (for a circuit called on a patch: CastOp is not yet supported); control flow raises it while the program is still being built. move, grow, rotate and step behave like transversal, and CircuitBuilder.repeat like control flow.
In Deltakit
A Bell pair written as a hand-written circuit, called once and compiled to Stim:
CompilationResult
R 0 1
TICK
H 0
TICK
CNOT 0 1
TICK
M 0 1
TICK
DETECTOR rec[-2] rec[-1]
Read the output as Stim does. R 0 1 resets both qubits, CX has been renamed CNOT, and TICKs separate the layers. rec[-2] and rec[-1] are the two most recent measurement results, here qubits 0 and 1. Nobody asked for that detector. Each bit of a Bell pair is random, but their parity is fixed, and the compiler found it. Delete the H and it emits two detectors, rec[-2] and rec[-1], since each qubit then stays in on its own. There is no OBSERVABLE_INCLUDE in either run, because none was declared.
Traps
The logical can become a detector
A patch with prepare("Z"), three calls of measure_stabilisers(1) and measure("Z") compiles to 17 qubits, 33 measurements, 25 detectors and 0 observables. The final readout is deterministic without noise, so it is declared a detector like any other. Lecture 8 shows the repair and the failure counts before and after.
A declared observable can still leak
Declaring an observable does not stop the detector finder from also emitting the logical readout itself as a detector (DETECTOR rec[-1] in Lecture 8’s repetition memory). The observable is then the XOR of all detectors, and a decoder reads it straight off the syndrome. Lecture 8’s compiled repetition memory scores 0 failures in 100,000 shots at , and 4,397 once that last detector is dropped. Compare the detector count with a hand-built circuit before you trust a compiled one.
One round per callmeasure_stabilisers(3) builds, then fails during compilation with ValueError: The input SSA value must be used by a stab.CircuitOp, stab.StatePermuteOp, or qstruct.YieldOp. Called with no argument it asks for rounds and fails the same way. Loop over measure_stabilisers(1) instead.
Stim needs the export config. Without StimExportPipelineConfig, res.program is IR text, and stim.Circuit(res.program) fails with ValueError: Gate not found: 'builtin'.
The output is noiseless. To sample it, wrap it with Circuit.from_stim_circuit from deltakit.circuit and pass it through a QPU, as in The memory-experiment pipeline. Lecture 8 does exactly this.
Compiled is not hand-built. Repaired, and given the same noise, seed and decoder, the compiled patch fails 405 times per 100,000 shots at , where Lecture 0’s circuit fails 344. The visible difference is the final readout, split over two layers with idle noise in between; Lecture 8 does not claim it is the only one. At shots the gap holds (4,130 vs 3,578). Both circuits have the same 72 two-qubit gates and 33 measurements; the compiled one has 20 TICK layers to 18.
Compile time grows fast. The three-round patch takes 1.0 s here; Lecture 8 reports about half a minute for five rounds at .
The deltakit-compile repository is Apache-2.0, and its tests are the most reliable record of what each instruction is meant to do. Related cards: Lattice surgery, xDSL dialects in deltakit-compile, Detectors and observables.
QA d = 3 patch is prepared in Z, measured for three rounds and read out in Z. The compiled Stim circuit has 25 detectors and no OBSERVABLE_INCLUDE. Where did the logical outcome go?
AInto the last detector. Without noise the readout of a patch prepared in is deterministic, an flow, so the compiler declares it a detector. With no observable, a decoder has nothing to predict and every run scores zero failures; add an observable but keep that detector, and the decoder reads the logical straight off the syndrome. Turn that detector into the observable before counting failures.
Merge two patches along a seam, measure the merged patch for about rounds, split. The product of the new seam checks is . Two-qubit logical measurements with only nearest-neighbour gates, paid for in rounds.
What it does
Surface-code patches cannot run a transversal CNOT between each other on a planar chip, because the matching qubits are not neighbours. Lattice surgery (Horsman et al. 2012) gets the same effect with local operations only. It merges two patches into one larger patch and keeps measuring for a while, then splits them. The merge measures a logical Pauli product, such as , without measuring or alone. Two such products, plus an ancilla patch that is prepared and measured on its own, give a logical CNOT. Litinski’s “game of surface codes” (2019) takes this further and writes whole algorithms as sequences of multi-patch Pauli measurements plus magic states.
Why the seam measures
Take two distance-3 rotated patches whose logicals run vertically, so a column of s is a representative of . Place them side by side with one empty column between them. The facing boundaries carry weight-2 checks, and their boundary columns hold and .
Bridge. Put three fresh qubits in the gap and prepare each in .
Merge. Measure the stabilizers of the single patch now covering all 21 data qubits. Two things change on the seam. The old weight-2 boundary checks grow to weight 4 by taking in bridge qubits. Since , their values do not change, so they still give detectors at once. Four checks are new, and all are -type: two of weight 4 between the columns and two of weight 2 on the top and bottom edges.
Product. Each new check alone gives a random , since the bridge started in an eigenstate. Their product does not. Every bridge qubit lies in exactly two of the four checks, so its cancels. Every boundary qubit lies in exactly one. The product is therefore on the left boundary column times on the right one: .
Rounds. Repeat the merged stabilizer measurements for about rounds, then take as the product of the seam checks’ values.
Split. Measure the bridge qubits in . The patches are separate again. The outcomes fix a known Pauli correction on the patches, applied in software.
Measuring needs the other boundaries to face each other: rotate a patch, or stack the patches vertically.
Why about rounds
In a memory, one round of checks is not enough, because a misread check looks exactly like a data error. Repeating the round times means a wrong answer needs a chain of about faults, in time as well as space. The merge has the same problem with a sharper edge. The seam checks are new, so their first values are individually random and give no detector to compare against; only their product, , is fixed, and a single misread seam check flips it. Repeating the merged measurement for about rounds protects just as the memory protects the logical state. A lattice-surgery operation therefore costs about code cycles, and Litinski’s game counts time in steps of cycles for exactly this reason.
Worked example: what one merge costs
A merged patch is a rotated planar code, so RotatedPlanarCode(width=2d+1, height=d) counts its qubits:
two patches
merged
extra
3
34
41
7
5
98
109
11
7
194
209
15
The extra qubits are the bridge data qubits and new ancillas, in all. For , that is three bridge qubits and the four seam checks of the figure. The space is cheap. The time is what you pay: about rounds on all physical qubits.
From products to a CNOT
Two merges make a logical CNOT, which is how a compiler would use this instruction. Take control , target and an ancilla patch prepared in :
Measure with a merge along one seam (outcome ).
Measure with a merge along a seam where the ancilla’s boundary faces the target (outcome ).
Measure the ancilla alone in (outcome ).
The result is a CNOT from to up to Pauli corrections fixed by , and , which a decoder-aware control system tracks in software. Each merge costs about rounds, so one CNOT costs about rounds plus the single-patch steps. In a deltakit-compile program these are two multi_pauli_measure calls with different patch orientations, which is exactly where the trap below bites.
In Deltakit
LogAsmBuilder.multi_pauli_measure(operand_patches, bridges=None, *, pauli_bases, rounds=None) expresses the merge. It needs at least two patches. Without bridges it places a bridge patch itself, and without rounds it uses the smallest patch side:
from deltakit_compile.frontend.logasm import ( LogAsmBuilder, RotatedPlanarPatch)lb = LogAsmBuilder()a = lb.declare_patch( RotatedPlanarPatch(3, 3, location=(0, 0)))b = lb.declare_patch( RotatedPlanarPatch(3, 3, location=(4, 0)))a.prepare("Z")b.prepare("Z")lb.add_return(lb.multi_pauli_measure( [a, b], pauli_bases=["Z", "Z"]))prog = lb.build_program()for op in prog.module.walk(): kind = op.name.removeprefix("log_asm.") if kind == op.name: continue if kind == "patch_dec": t = op.results[0].type s, xy = t.size_data, t.placement_data info = f"{s} at {xy}" elif kind == "multi_pauli_meas": bs = [str(p)[-2] for p in op.basis.data] n = op.rounds.data info = "".join(bs) + f", {n} rounds" else: info = str(op.properties["basis"])[-2] print(f"{kind:<16}", info)
patch_dec (3, 3) at (0.0, 0.0)
patch_dec (3, 3) at (4.0, 0.0)
prepare Z
prepare Z
patch_dec (1, 3) at (3.0, 0.0)
prepare X
multi_pauli_meas ZZ, 3 rounds
measure X
multi_pauli_measure added the bridge while the program was being built, before any compilation: a patch at , prepared in and measured in after a three-round merge, as in the figure. In 0.1.0 the program builds but does not compile. Lowering it raises NotImplementedError: MultiPauliMeasOp is not yet supported. So this card shows the instruction, not a compiled circuit, and the qubit counts above come from the equivalent rotated planar code rather than from a compiled merge.
The layout decides what the seam can measure
In 0.1.0 the bridge’s basis comes from the geometry alone. Two side-by-side patches with vertical logicals get an -prepared bridge whether you ask for ["Z", "Z"] or ["X", "X"], and the requested bases are only recorded. Nothing checks the pair yet, because there is no lowering. Choose orientations so that the facing boundaries carry the logical you want to measure.
Related cards: deltakit-compile and logical assembly, The rotated surface code and its boundaries, Logical error per round.
QYou call multi_pauli_measure with pauli_bases=["X", "X"] on two side-by-side patches whose logicals run vertically. What does the program describe?
AA merge, not an one. The builder places an -prepared bridge between the facing boundaries, which carry , and only records the requested XX; nothing checks the pair in 0.1.0. Stack the patches (the bridge is then prepared in ) or rotate one.
deltakit-compile is an xDSL compiler. A program is one IR module mixing dialects (log_asm, plaquette, qref, stab, qec, stim, …); 45 passes lower it stage by stage until only stim operations remain.
IR, dialect, pass, lowering
A compiler does not jump from source to machine code in one step. It rewrites the program through several intermediate representations (IRs), each closer to the hardware. MLIR (Lattner et al. 2020) made one design popular, and xDSL implements it in Python. deltakit-compile is built on xDSL 0.66.
Operation. One line of IR, such as %q1 = log_asm.prepare<Z> (%q0): a name, operands, results, and properties in angle brackets.
SSA value. Every value (%q1) is defined once and never reassigned. In log_asm most instructions on a patch consume the patch’s current value and return a new one (a final measure returns only the bit), so the data flow, and with it the order of operations on that patch, is explicit. The physical qref dialect is different: a gate there acts in place on a qubit reference. Fund-proposal issue #415 proposes an SSA dialect for physical gates (Lecture 9).
Dialect. A named family of operations, attributes and types at one level of abstraction. One module may mix several.
Pass. A rewrite of the whole module. Canonicalize (local simplifications) and cse (common-subexpression elimination) are generic clean-ups that run between the real work.
Lowering. A pass that replaces operations of a higher dialect with those of a lower one. When no high-level operation is left, the program has moved down a level.
The dialects, from the source
LogicalAssembler.make_context() loads 16 dialects. Five come from xDSL and MLIR: arith, builtin, func, scf and tensor. deltakit-compile tags selected operations of four of them (arith, func, scf, tensor) as free of quantum effects; scf loops and branches instead take on the effects of their bodies. The other eleven are its own:
dialect (level)
sample ops
log_asm_api (builder calls)
call, circuit_dec
log_asm (patches)
prepare, multi_pauli_meas
sobs (patch observables)
locate_observable
plaquette (surface-code checks)
plaquette, round
qcore (qubit registers)
alloc_qubit
qref (physical gates)
gate, measure, reset
qstruct (circuit structure)
circuit, parallel
stab (stabilizer flows)
circuit, state.make
qec (detectors)
detector, observable_include
stim (Stim instructions)
tick, detector
deltakit-stim (leakage)
leakage, relax
Two more, ncstim and tables, are defined in the package but not loaded. The patch dialect is called log_asm, although its file is logical_assembly.py.
Reading a printed module
Printing a program shows its IR. Here is the lattice-surgery program of the Lattice surgery card, with the long patch types replaced by …:
The angle brackets hold properties: the basis, or the rounds and Pauli bases of the merge. The merge takes the two patch values and, as a second group, the bridge %qreg_5. It returns a classical result, %cexpr of type i1, plus the two patches after the merge; the bridge is then measured on its own. The elided types carry the geometry, for example !log_asm.patch.rot_planar<size=(3, 3), location=(0.0, 0.0), orient=v_z>. multi_pauli_measure read the size, place and orientation from these types to declare and place the bridge (%qreg_4) while the program was being built, before any pass ran.
Four stages, 45 passes
The default pipeline with Stim export runs 45 passes in four stages, with four extra canonicalize passes around them. The figure counts the operations of each dialect after each stage for a patch with prepare("Z"), three calls of measure_stabilisers(1) and measure("Z"):
Logical assembly (7 passes). Inline every called circuit, merge duplicates, and turn the builder’s register bookkeeping into qcore. For a hand-written Bell circuit, the 29 builder-level operations (12 log_asm_api, 10 tensor, 7 arith) disappear, leaving 10 qcore, 4 qref and 3 qstruct operations (the next canonicalize trims qcore to 3). A patch program is already in log_asm and passes through unchanged.
Patch lowering (12 passes). Place observables (sobs), expand each patch instruction into plaquettes, schedule their two-qubit gates, then emit qref gates inside qstruct circuits. The plaquette count peaks at 195 and then drops to zero, leaving 122 qref operations. Only rotated planar patches are supported.
Stabiliser flows (13 passes). Convert each circuit into stab, verify and generate flows, merge them across the program and find detectors. Out come 25 qec.detector operations. An observable declaration from stage 2 survives too, but it leaves no trace in the Stim text.
Stim export (9 passes). Match each gate’s unitary to a named Stim gate, insert TICKs, flatten registers into integer qubit indices, and lower to the stim dialect: 111 operations (17 qubit allocations, 17 coordinates, 24 Clifford gate instructions, 4 resets, 4 measurements, 20 ticks, 25 detectors), printed as Stim text.
With the default export configuration, which prints the physical IR instead, the pipeline has 35 passes.
StimExportPipelineConfig
This config selects stage 4. It has two fields: name and unitaries_to_named_gates_precision, default . The second is the largest elementwise difference allowed when the compiler matches a gate’s unitary to a named Stim gate. Leave it alone unless you write gates as raw unitaries. Passing it as LogicalAssemblerConfig(export_config=StimExportPipelineConfig()) is what makes compile(...).program Stim text. export_config is one of five fields of LogicalAssemblerConfig, next to stabiliser_flow_config, verify_between_passes, api_to_logasm_config and circuit_builder_to_logasm_config. Patch lowering is set on the pipeline object instead (patch_lowering_config), and a QPU-specialisation stage is still a commented-out TODO in passes/logical_assembly/pipeline.py.
In Deltakit
The registered dialects and the lowering passes, read from the pipeline itself:
from textwrap import fillfrom deltakit_compile.frontend import ( logical_assembler as la)from deltakit_compile.passes.stim.stim_export \ import pipeline as sxctx = la.LogicalAssembler.make_context()names = sorted(d.name for d in ctx.loaded_dialects)print(len(names), "dialects:")print(fill(", ".join(names), 46))exp = sx.StimExportPipelineConfig()cfg = la.LogicalAssemblerConfig( export_config=exp)pipe = la.LogicalAssemblerFromApiPipelinepasses = pipe.from_configuration(cfg).get_passes()low = [p.name for p in passes if "-to-" in p.name]print(len(passes), "passes,", len(low), "named x-to-y:")print(fill(", ".join(low), 46, break_on_hyphens=False))
A pass list is not a contract
Pass names and counts are internal to version 0.1.0 and will change. Count them from get_passes() rather than quoting 45.
To watch the stages yourself, apply the passes one at a time with p.apply(ctx, module) to a clone of program.module, and count op.name.split(".")[0] after each. That is how the figure’s numbers were made. Related cards: deltakit-compile and logical assembly, Lattice surgery, Detectors and observables.
QIn deltakit-compile, which dialect is the patch-level instruction set, and which file defines it?
AThe dialect is log_asm (ops such as log_asm.prepare and log_asm.multi_pauli_meas), defined in dialects/logical_assembly.py. The file name is not the dialect name, so search for Dialect("log_asm" rather than for logical_assembly.
One guide governs every Deltakit repo: file in the right tracker, ask before starting, use Conventional Commits, sign the CLA, disclose substantial AI use. The community fund pays up to 4k USD; the next round closes 2 Dec 2026.
Where things live
Deltakit is Apache-2.0 and split over several GitHub repositories. Deltakit/deltakit holds the meta-package, the documentation and the rules for all of them in docs/CONTRIBUTING.md. Each package has its own repository, such as deltakit-explorer or deltakit-compile. The guide asks for bug reports and requests in the affected package’s repository. Cross-package and documentation issues go to the meta-repository. Everything below paraphrases the guide as read on GitHub on 2026-11-09, as Lecture 9 does.
git clone \ https://github.com/<you>/deltakit-explorercd deltakit-explorergit remote add upstream \ https://github.com/Deltakit/deltakit-exploreruv sync --group testuv run --group test pytestjust check # lint, security and testsuv sync --python 3.13 \ --resolution lowest-direct --group testuv run --no-sync pytest
just is optional; each recipe is shorthand for an equivalent uv command. The last two lines reproduce the CI job the guide names: Python 3.13 with the lowest dependency versions your bounds allow (CI also tests Python 3.11 to 3.15, each with the highest and the lowest versions). Code that needs a newer NumPy must raise its lower bound, or CI fails where your laptop passed. The meta-repository also has a pre-commit configuration for a set of common checks (uv run pre-commit install); deltakit-explorer has none.
Issues, PRs and review
Titles and commits follow Conventional Commits, with two exceptions for issues: bug reports start bug: and requests start request:. The PR that resolves them uses fix:, feat: or perf:. Releases are generated from these prefixes, so they matter.
Picking up work.good first issue and help wanted are open to anyone. For anything else, describe your approach in a comment and wait to be assigned. Between volunteers, the maintainers weigh the quality of the approach first and then who came first. An assignee who does not answer an update request within a week may be unassigned.
Writing an issue. A maintainer’s rule of thumb (#325, 2026-08-19, via Lecture 9): at most three paragraphs, about 300 words, two or three images and citations, with extra detail folded away.
Review. Do not rebase or force-push while a PR is under review; add commits instead. Leave reviewers’ inline comments for them to resolve. A bot asks for a Contributor License Agreement on your first PR. Push in batches rather than one small commit at a time, since every push reruns CI.
What gets reviewed first
On an assigned issue, the assignee’s PR is reviewed first, and other PRs may wait until the assignment ends. On an unassigned issue, maintainers may start with the first PR that is ready: not a draft, linked to its issue, passing CI, with the CLA signed. Opening a PR first does not by itself give priority. Duplicates are closed with a link to the one that goes ahead, and their authors are invited to review it. For a first contribution, that means: comment on the issue, wait for a reply, keep the change small, and open the PR only when it is ready.
The AI-use policy
“Use of AI tools” covers every repository in the organisation and every contributor, maintainers included. AI tools are allowed. The argument for rules: a plausible PR is now cheap to produce but no cheaper to review, and the guide borrows LLVM’s word extractive for contributions that move the checking onto maintainers. Its golden rule is that a contribution should be worth more than the time it takes to review. It also says why this project is strict: quantum error correction experiments “may fail quietly”, and people publish numbers computed with Deltakit.
The rules that follow:
You are accountable. Understand every line before asking for review, answer review questions yourself, and trim verbose output.
Disclose substantial use in the PR: tool, model, what it changed, how you verified it. An Assisted-by line in a commit message is welcome but optional. Grammar or translation help needs no disclosure. Substantial undisclosed use counts as a breach.
Credit no tool as an author: only people can sign the CLA. Licence duties still apply to generated code.
Do not commit personal agent files: CLAUDE.md, .claude/, .cursor/, .aider*, chat transcripts. New AI automation, such as a review bot, needs code-owner approval first.
The Deltakit Community Fund
The Deltakit Community Fund is run jointly by the Unitary Foundation and Riverlane. Its page, read on 2026-11-09, says:
Award: up to 4k USD plus mentorship from both teams, for one to two quarters.
Projects: an unassigned issue labelled community-fund-proposal (a proposal, not an accepted project), or your own idea opened as a new issue, which other applicants may then propose on too; apply through the page’s form. On 2026-11-09 four such issues were open, three of them opened by maintainers.
Dates: the 2027 Q1 round closes on 2 December 2026, results come on 11 December (#343 tracks the schedule) and work starts in January 2027. Later rounds open in February, May and August 2027.
Rules: after a rejection, wait a quarter before reapplying. People in countries subject to US export controls under the EAR (including Country Groups D:1 and D:5) or to US financial sanctions administered by OFAC are excluded.
The page lists no judging criteria. The guide adds that the scope of an assigned fund issue is reserved while the project runs, and that fund contributions are prioritised when duplicates overlap in scope.
In Deltakit
Each installed wheel records where its issues go:
import importlib.metadata as mdGH = "https://github.com/Deltakit/"for name in ["explorer", "stim", "compile", "visualise"]: meta = md.metadata(f"deltakit-{name}") for entry in meta.get_all("Project-URL"): label, url = entry.split(", ", 1) if url.endswith("/issues"): print(f"{name:<10}{label:<12}", url.removeprefix(GH))
The metadata and the guide disagree: the wheels send most reports to the meta-repository, while the guide asks for the package’s own tracker. The guide is the rule; treat the metadata URLs as a fallback that may lag behind it.
An assigned fund issue is taken
A community-fund-proposal issue with an assignee is a funded project in progress. Its scope is reserved until the project ends, and other PRs on it may not be reviewed in the meantime.
Related cards: The Deltakit package map, xDSL dialects in deltakit-compile.
QA coding agent drafted the tests in your Deltakit PR. What must the PR say, and what must stay out of the commits?
AThe PR description names the tool and model, what it changed and how you checked it (“Used LLMs” is not enough). The tool is not credited as an author, and agent files such as CLAUDE.md or .claude/ are not committed. You must still understand every line and answer review questions yourself.