Expand description
§stabilizer_qec
A quantum error-correction simulator and decoder: circuits and detector error models in Stim’s
formats, a bit-parallel sampler, exact and correlated matching, belief-matching, BP and BP+OSD,
window decoding, IBM’s bivariate bicycle codes and lattice surgery. It is the engine behind the
stabilizer-qec Python package and the
interactive explainer, and it agrees with Stim, PyMatching,
ldpc and beliefmatching on every check in its test suite.
use stabilizer_qec::{memory_circuit, Basis, DemOptions, Matching, Noise, SurfaceCode};
// A distance-5 surface-code memory under circuit noise, sampled and decoded.
let circuit = memory_circuit(SurfaceCode::Rotated, 5, 5, Noise::Sd6 { p: 0.004 }, Basis::Z)?;
let samples = circuit.detector_sampler(7)?.sample(10_000, 0); // 0 threads: every core
let dem = circuit.detector_error_model(&DemOptions::new().decompose_errors(true))?;
let predictions = Matching::with_correlations(&dem)?.decode_batch(&samples.detectors, 0)?;
let failures = (0..10_000).filter(|&s| predictions[s].flips(0) != samples.observables.get(s, 0)).count();
assert!(failures < 1_000);- Circuits:
Circuitreads Stim’s circuit language (every Clifford gate, all three bases, Pauli products, every noise channel, measurement feedback,REPEAT, tags, Pauli observables) and prints it back, or is built in code (Circuit::appendwithTargets,+,*);Circuit::detector_error_modelbuilds the error model Stim’s analyzer builds, fault for fault, its loops folded as Stim folds them (a d = 11 memory of 10,000 rounds in a tenth of a second);DetectorSamplersamples 64 shots to a word, reproducibly from a seed on any number of threads;MeasurementConverterturns raw records into detection events. - Decoders on an error model:
Matching(exact, sparse blossom; plain or correlated, as fast as PyMatching),BeliefMatching,BpOsd,WindowMatching. On a check matrix:BpDecoderandBpOsdDecoder, equal toldpc’s. AllSend + Sync. - Beyond Clifford, and beyond the CPU (2.0):
Circuit::stabilizer_rank_samplerruns Clifford+T circuits (I[T], tagged rotations) exactly,Circuit::coherent_samplerand the joint sampler reweight the Pauli twirl of coherent errors (I_ERROR[R_Z(theta=…)]) by the interference it leaves out, with the exact gates kept exact; thegpufeature runs the frame sampler and min-sum BP as wgpu compute shaders, bit for bit the CPU lane sampler’s and the f32 decoder’s results; thehighsfeature adds the ILP circuit distance. - Codes:
memory_circuit(rotated and XZZX surface codes),stream_memoryandstream_circuit(a million rounds of a memory, or of any circuit with a loop, window-decoded as they stream),BivariateBicycleCode(the gross code, its automorphisms’ logical action, and the gauging measurement of its logicals),lattice_surgery(Z⊗Z and X⊗X merges, a logical CNOT).
Shots are BitTables, bit-packed as Stim’s b8 format. Every fallible call returns
Error; none panics on bad input.
§Stability
Semantic versioning from 1.0: the items in this documentation keep compiling, with the same
meaning, through every 2.x release (checked by cargo-semver-checks in CI). The engine’s own
modules are public so the Python bindings, the site and the tools can reach them, but they are
hidden from this documentation and carry no such promise. The Python bindings sit behind the
python feature, off by default. The minimum supported Rust is 1.87.
Modules§
- bp32
- Min-sum belief propagation in single precision, the parallel schedule, written so a GPU can
run the same operations in the same order (
gpu/bp.wgsl) and give the same bits. This CPU executor is the reference the GPU is held to;bp(f64, product-sum and min-sum, every schedule) stays the decoder of record. - cpp_
random - C++’s random engines and
std::shuffle, as each standard library implements them. - flip
- Bit flipping (Gallager’s algorithm), as
ldpc’sFlipDecoder(src_cpp/flip.hpp): each pass flips every bit with more unsatisfied checks than satisfied ones, in column order, and (everypfreq-th pass) flips a tied bit with probability ½.ldpc’sBpFlipDecoderruns it before BP, BP decoding what it leaves. - fusion
- Fusion Blossom: exact matching by a primal-dual blossom on the decoding graph, serial or
partitioned and fused (Python’s
stabilizer_qec.fusion_blossom). Fusion Blossom: exact minimum-weight perfect matching by a primal-dual blossom algorithm on the decoding graph itself, serial or partitioned into units solved on threads and fused along their boundaries (Wu and Zhong, arXiv 2305.08307). Python’sstabilizer_qec.fusion_blossomis its Python API. - lanes
- The lane sampler: the batch sampler’s ops flattened into a stream of 32-bit words and run
32 shots per word with every random draw an integer compared with a threshold, so a GPU
can run the very same stream (
gpu) and give the very same bits. This CPU executor is the reference the GPU is held to. - lattice_
surgery - Lattice surgery on rotated surface-code patches (Horsman, Fowler, Devitt and Van Meter
2012), each operation one circuit with SD6 noise at
p: patches prepared, held, merged across a seam formergedrounds, split, held and read out. Distances are odd, at least 3. - ldpc_uf
ldpc’s union-find decoder on any check matrix. Union-find decoding on any check matrix, asldpc’sUnionFindDecoderand the second stage of itsBeliefFindDecoder(src_cpp/union_find.hpp).- leakage
- Deltakit’s leakage dialect: lowering, writing back, and the circuit without leakage.
Deltakit’s leakage dialect (Riverlane’s fork of Stim):
LEAKAGE(p),RELAX(p)andHERALD_LEAKAGE_EVENT(p), read as tagged instructions that Stim runs, and the circuit without any leakage. - lookup
- Lookup-table decoders, as CUDA-Q QEC’s
single_error_lutandmulti_error_lut. Lookup-table decoders, as CUDA-Q QEC’ssingle_error_lutandmulti_error_lut(libs/qec/lib/decoders/lut.cpp): every set of at mostdepthfaults, by size and then in lexicographic order of fault indices, entered under the syndrome it sets off, the first set for each syndrome kept. Decoding is one lookup; a syndrome no set explains is not decoded. - mbp
- Memory belief propagation over GF(4), as
ldpc’smbp_decoder. Memory belief propagation over GF(4) (MBP):ldpc’smbp_decoder(src_cpp/mbp.hpp), after Kuo and Lai, “Exploiting degeneracy in belief propagation decoding of quantum codes” (npj Quantum Information 8, 111, 2022). - mwpf
- MWPF: hypergraph minimum-weight parity factor decoding (Python’s
stabilizer_qec.mwpf). MWPF: hypergraph minimum-weight parity factor decoding, a primal-dual algorithm over invalid subgraphs that finds a parity factor and a lower bound on the optimum’s weight (Wu et al., arXiv 2508.04969), with union-find and single-hair relaxers as its plugins. Python’sstabilizer_qec.mwpfis its Python API. - pecos_
sparse - PECOS’s sparse stabilizer simulator (its C++
SparseSim). PECOS’s sparse stabilizer simulator (SparseSim, its C++sparsesim.cppthat Cython wraps ascySparseSim), in Rust. - predecoder
- The AI pre-decoder: a 3D convolutional network over the detectors’ grid, before a global decoder. The AI pre-decoder: a fully convolutional 3D network over the detectors’ space-time grid, in front of a global decoder, in the shape of NVIDIA’s (Chamberland, Olle, Li, Thornton and Baratta, arXiv 2604.12841).
- relay_
num - The number types Relay-BP runs in.
The numbers Relay-BP can run in, as IBM’s
relay_bp0.2.2 instantiates its min-sum decoder:f32,f64, the integersi8toi64, and 64-bit fixed point with 0 to 31 fractional bits (fixed::FixedI64<Frac>). - tn_ml
- Exact maximum-likelihood decoding by contraction (CUDA-Q QEC’s
tensor_network_decoder). Exact maximum-likelihood decoding by contraction, the quantity CUDA-Q QEC’stensor_network_decodercontracts its Tanner-graph network for: for a check matrix, a logical observable, independent error priors and a soft syndrome (each check’s probability of having fired), - user_
graph - PyMatching’s
UserGraph(user_graph.cc, PyMatching 2.4): a matching graph built by hand. Nodes, edges carrying sets of fault ids, weights and error probabilities, boundary nodes, and the five ways a parallel edge merges. It decodes on this crate’s sparse blossom, built with PyMatching’s own discretisation, so the weights it minimises are PyMatching’s to the bit: integer weights as they are, otherwise scaled so the heaviest edge is 2^24 − 1, rounded, and doubled; a negative weight’s edge pre-applied (its endpoints toggled, its fault ids flipped, its weight counted) and matched at its absolute weight; edges to boundary nodes made boundary edges, the lightest kept where several meet one node.
Macros§
Structs§
- Automorphism
- An automorphism of a bivariate bicycle code: the shift x^a y^b of both halves of the data, with or without the ZX-duality, and what it does to the logical qubits.
- Belief
Matching - Belief-matching (Higgott et al. 2023), as the
beliefmatchingpackage decodes: BP on the model’s hypergraph; where BP’s own correction explains the shot it is used, otherwise matching on weights −ln p from BP’s posteriors. The model must be decomposed. - BitTable
- A table of bits, one row per shot, bit-packed as Stim packs them: each row a whole number of
bytes, bit
kof a row in bytek / 8at positionk % 8(numpy’spackbits(..., bitorder="little"), Stim’sb8format). - Bivariate
Bicycle Code - One of IBM’s bivariate bicycle codes (Bravyi et al., Nature 627, 778, 2024), with the paper’s depth-8 syndrome cycle.
- BpDecoder
- Belief propagation on a check matrix given by its columns (the checks each column touches),
flooding schedule, its arithmetic reproducing
ldpc’sBpDecoderbit for bit. - BpLsd
- BP+LSD on a detector error model (Hillmann et al., 2024): belief propagation, and where it
does not converge, localized statistics decoding, which grows a cluster around each
detection event by BP’s posteriors, merges clusters that touch, and solves each alone.
Corrections equal to
ldpc’sBpLsdDecoderbut for ties among equally likely columns (and the orderldpcmerges three or more clusters in, which it takes from pointer hashes). Faster than BP+OSD on large codes: its eliminations are cluster-sized. Give it the undecomposed model. - BpLsd
Decoder - BP+LSD on a check matrix given by its columns, as
ldpc’sBpLsdDecoder(flooding schedule). - BpOptions
- Belief-propagation settings.
- BpOsd
- BP+OSD on a detector error model (Roffe et al.): each fault a column with its prior,
corrections equal to
ldpc’sBpOsdDecoderbut for ties among equally likely columns. For codes whose faults flip three or more detectors, such as the bivariate bicycle codes: give it the undecomposed model. - BpOsd
Decoder - BP+OSD on a check matrix given by its columns, as
ldpc’sBpOsdDecoder. - BpOsd
Outcome - A BP+OSD run’s result.
- BpOutcome
- A BP run’s result.
- Circuit
- A stabilizer circuit in Stim’s circuit language.
- Circuit
Error Location - One place a fault arises (Stim’s
CircuitErrorLocation). ItsDisplayis Stim’s text. - Coherent
Options - Options for
Circuit::coherent_sampler. - Coherent
Sampler - Weighted shots of a circuit with coherent errors. Made by
Circuit::coherent_sampler. - Color
Matching - Colour-code decoding by matching, Chromobius’s construction (Gidney and Jones, 2023): each
detector doubled into the two sub-graphs that leave out a colour other than its own, every
fault split into basic faults drawn as edges of that doubled (Möbius) graph, a minimum-
weight matching of it found by this crate’s matcher, and the matching lifted back to the
code by carrying colour charge around its cycles. Predictions equal to the
chromobiuspackage’s but for ties between equally light matchings. - CssCode
- A CSS code given by its checks, with a memory experiment correct for any of them: every X check measured and then every Z check, each in layers no qubit is used twice in. Built from check matrices, as the hypergraph product of two classical codes, or as the triangular colour code.
- DemOptions
- How
Circuit::detector_error_modelbuilds a model. - DemSampler
- Shots drawn from a detector error model’s faults. Made by
DetectorErrorModel::sampler. - DemSamples
- A detector error model’s shots: detection events, observable flips, and the faults that fired (one bit per fault, in the model’s order).
- Detector
Error Model - A detector error model in Stim’s format: independent faults, each with a probability, the
detectors it flips and the observables it flips. Parse one from Stim’s text, or build one
with
Circuit::detector_error_model. - Detector
Sampler - Detection events and observable flips, 64 shots to a machine word. Made by
Circuit::detector_sampler. - Error
- Why a call failed: the input was not something the engine can take, with a message saying what and where.
- Exact
Sampler - Exact shots from the state vector. Made by
Circuit::exact_sampler. - Explained
Error - A fault class of a circuit’s error model and the places in the circuit it arises (see
Circuit::explain_errors). ItsDisplayis Stim’s text. - Gauging
- The gauging ancilla system that measures a gross-code logical X (see
BivariateBicycleCode::gauging). - Generated
Noise - The noise of
Circuit::generated: Stim’s four strengths, each zero (left out) unless set. - Joint
Sampler - Weighted shots of a Clifford+T circuit with coherent errors. Made by
Circuit::joint_sampler. - LsdOptions
- How BP+LSD’s localized statistics decoding grows and solves its clusters.
- Matching
- Exact minimum-weight perfect matching on a decomposed detector error model, by sparse blossom, as PyMatching decodes: edges weighted ln((1 − p)/p), the observables of the lightest correction returned. Correlated matching adds PyMatching 2.4’s second pass.
- Measurement
Converter - Raw measurement records to detection events and observable flips, as
stim m2d: each detector and observable compared with a noiseless reference run. Made byCircuit::measurement_converter. - Prediction
- A decoder’s answer for one shot.
- RelayBp
- Relay-BP on a detector error model (Müller et al., IBM, 2025): min-sum BP with memory, run
in legs that each draw fresh memory strengths and start from the last leg’s posteriors; the
lightest of the first few converged corrections wins. No elimination: fast and simple
enough for hardware, and on the gross code about as accurate as BP+OSD. IBM’s
relay_bpgives the same corrections on the same check matrix (seeRelayBpDecoder). Shotkof a batch draws its memory strengths from the seed andk, so results do not depend on the thread count. Give it the undecomposed model. - Relay
BpDecoder - Relay-BP on a check matrix given by its columns, as IBM’s
relay_bpRelayDecoderF64: the same corrections, iteration counts and convergence for the same options. As there, the random memory strengths continue from one decode to the next. - Relay
Options - How Relay-BP runs: its legs, their memory strengths and when it stops.
- Relay
Outcome - A Relay-BP run’s result.
- Samples
- Shots of detection events and of observable flips, one row per shot.
- Search
Decoder - A search for the most likely error, Tesseract’s A* (Beni, Higgott and Shutty, Google, 2025),
for any detector error model: sets of faults expanded cheapest first by their weight plus an
admissible estimate of explaining the detectors still lit, each grown only through its first
lit detector in a detector order, under a beam and a queue bound, once per order. Its
answers, fault for fault, are the
tesseract_decoderpackage’s on the same platform (ties between equally promising states are broken as the platform’s C++ library breaks them). With no beam, no queue bound and revisits allowed it is exact. - Search
Options - The search decoder’s settings; the defaults are Tesseract’s.
- Stabilizer
Rank Sampler - Shots of a Clifford+T circuit from the stabilizer-rank sampler. Made by
Circuit::stabilizer_rank_sampler. - Stream
Result - A streamed memory’s outcome (see
stream_memory). - Target
With Coords - A target of an explained error with its coordinates (empty for none). Its
Displayis Stim’s text:D3[coords 1,2,0], or the bare target without coordinates. - Union
Find - Weighted union-find decoding (Delfosse and Nickerson, with Huang, Newman and Brown’s weighted growth) on the same graph matching uses: clusters around the detection events grow edge weight by edge weight until their events can pair inside them, and a spanning tree of each is peeled for the correction. Linear time in practice, its logical error rate a little above matching’s; the standard baseline (this engine’s matcher, near-linear too, is about twice as fast). The model’s faults must flip at most two detectors each, or be decomposed.
- Weighted
Samples - Weighted shots: detection events, observable flips and each shot’s weight. A rate is Σ w·(event) / Σ w.
- Window
- A window of a window decoder: it decodes rounds
first_layer..end_layerand commits the corrections incommit_start..commit_end. - Window
Matching - Window decoding (Skoric et al.; Tan et al.): the model cut into overlapping windows of rounds, each matched alone and committing only its middle. The model’s detectors need a time coordinate (their last), as Stim’s generated circuits give them.
- Window
Options - A window decoder’s schedule.
Enums§
- Basis
- A measurement or preparation basis.
- BpMethod
- How belief propagation updates its messages.
- Detector
Order - How the search decoder generates detector orders.
- Diagram
Kind - A kind of
Circuit::diagram, after Stim’s. - Gross
Operator - A weight-12 logical X of the gross code whose measurement is built (see
BivariateBicycleCode::logical_measurement_circuit). - Noise
- Circuit noise.
- OsdMethod
- How BP+OSD’s ordered-statistics step searches when BP does not converge.
- Pauli
- A single-qubit Pauli.
- Surface
Code - A surface code.
- Target
- A target of an instruction, for
Circuit::append. - Window
Mode - The order a window decoder runs its windows in.
Functions§
- memory_
circuit - A surface-code memory experiment: a patch of distance
distance(2 to 11) prepared inbasis, held forroundsrounds of syndrome extraction (at most 10,000), and read out; detectors on every check and one observable. - stream_
circuit - Any circuit with a loop, sampled round by round and window-decoded as it streams, its
windows’ graphs from a template of its folded error model: the middle windows of a short
version of the loop serve every window of the long one. As
stream_memory, for circuits of your own (Stim’s generated ones among them): their detectors need a time coordinate. - stream_
memory - A memory too long to model whole, sampled round by round and window-decoded as it streams:
an SD6 memory at strength
pofroundsrounds (a million is fine), Z basis, its windows’ graphs built once from a short template.shotsis rounded up to a multiple of 64; the sameseedgives the same failures on any number ofthreads(0 is every core).
Type Aliases§
- Result
- The crate’s result type.