Skip to main content

Crate stabilizer_qec

Crate stabilizer_qec 

Source
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: Circuit reads 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::append with Targets, +, *); Circuit::detector_error_model builds 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); DetectorSampler samples 64 shots to a word, reproducibly from a seed on any number of threads; MeasurementConverter turns 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: BpDecoder and BpOsdDecoder, equal to ldpc’s. All Send + Sync.
  • Beyond Clifford, and beyond the CPU (2.0): Circuit::stabilizer_rank_sampler runs Clifford+T circuits (I[T], tagged rotations) exactly, Circuit::coherent_sampler and 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; the gpu feature 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; the highs feature adds the ILP circuit distance.
  • Codes: memory_circuit (rotated and XZZX surface codes), stream_memory and stream_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’s FlipDecoder (src_cpp/flip.hpp): each pass flips every bit with more unsatisfied checks than satisfied ones, in column order, and (every pfreq-th pass) flips a tied bit with probability ½. ldpc’s BpFlipDecoder runs 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’s stabilizer_qec.fusion_blossom is 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 for merged rounds, 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, as ldpc’s UnionFindDecoder and the second stage of its BeliefFindDecoder (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) and HERALD_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_lut and multi_error_lut. Lookup-table decoders, as CUDA-Q QEC’s single_error_lut and multi_error_lut (libs/qec/lib/decoders/lut.cpp): every set of at most depth faults, 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’s mbp_decoder. Memory belief propagation over GF(4) (MBP): ldpc’s mbp_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’s stabilizer_qec.mwpf is its Python API.
pecos_sparse
PECOS’s sparse stabilizer simulator (its C++ SparseSim). PECOS’s sparse stabilizer simulator (SparseSim, its C++ sparsesim.cpp that Cython wraps as cySparseSim), 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_bp 0.2.2 instantiates its min-sum decoder: f32, f64, the integers i8 to i64, 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’s tensor_network_decoder contracts 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§

bind_trait_fusion_visualizer
bind_trait_mwpf_visualizer
lock_write

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.
BeliefMatching
Belief-matching (Higgott et al. 2023), as the beliefmatching package 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 k of a row in byte k / 8 at position k % 8 (numpy’s packbits(..., bitorder="little"), Stim’s b8 format).
BivariateBicycleCode
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’s BpDecoder bit 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’s BpLsdDecoder but for ties among equally likely columns (and the order ldpc merges 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.
BpLsdDecoder
BP+LSD on a check matrix given by its columns, as ldpc’s BpLsdDecoder (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’s BpOsdDecoder but 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.
BpOsdDecoder
BP+OSD on a check matrix given by its columns, as ldpc’s BpOsdDecoder.
BpOsdOutcome
A BP+OSD run’s result.
BpOutcome
A BP run’s result.
Circuit
A stabilizer circuit in Stim’s circuit language.
CircuitErrorLocation
One place a fault arises (Stim’s CircuitErrorLocation). Its Display is Stim’s text.
CoherentOptions
Options for Circuit::coherent_sampler.
CoherentSampler
Weighted shots of a circuit with coherent errors. Made by Circuit::coherent_sampler.
ColorMatching
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 chromobius package’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_model builds 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).
DetectorErrorModel
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.
DetectorSampler
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.
ExactSampler
Exact shots from the state vector. Made by Circuit::exact_sampler.
ExplainedError
A fault class of a circuit’s error model and the places in the circuit it arises (see Circuit::explain_errors). Its Display is Stim’s text.
Gauging
The gauging ancilla system that measures a gross-code logical X (see BivariateBicycleCode::gauging).
GeneratedNoise
The noise of Circuit::generated: Stim’s four strengths, each zero (left out) unless set.
JointSampler
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.
MeasurementConverter
Raw measurement records to detection events and observable flips, as stim m2d: each detector and observable compared with a noiseless reference run. Made by Circuit::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_bp gives the same corrections on the same check matrix (see RelayBpDecoder). Shot k of a batch draws its memory strengths from the seed and k, so results do not depend on the thread count. Give it the undecomposed model.
RelayBpDecoder
Relay-BP on a check matrix given by its columns, as IBM’s relay_bp RelayDecoderF64: the same corrections, iteration counts and convergence for the same options. As there, the random memory strengths continue from one decode to the next.
RelayOptions
How Relay-BP runs: its legs, their memory strengths and when it stops.
RelayOutcome
A Relay-BP run’s result.
Samples
Shots of detection events and of observable flips, one row per shot.
SearchDecoder
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_decoder package’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.
SearchOptions
The search decoder’s settings; the defaults are Tesseract’s.
StabilizerRankSampler
Shots of a Clifford+T circuit from the stabilizer-rank sampler. Made by Circuit::stabilizer_rank_sampler.
StreamResult
A streamed memory’s outcome (see stream_memory).
TargetWithCoords
A target of an explained error with its coordinates (empty for none). Its Display is Stim’s text: D3[coords 1,2,0], or the bare target without coordinates.
UnionFind
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.
WeightedSamples
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_layer and commits the corrections in commit_start..commit_end.
WindowMatching
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.
WindowOptions
A window decoder’s schedule.

Enums§

Basis
A measurement or preparation basis.
BpMethod
How belief propagation updates its messages.
DetectorOrder
How the search decoder generates detector orders.
DiagramKind
A kind of Circuit::diagram, after Stim’s.
GrossOperator
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.
SurfaceCode
A surface code.
Target
A target of an instruction, for Circuit::append.
WindowMode
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 in basis, held for rounds rounds 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 p of rounds rounds (a million is fine), Z basis, its windows’ graphs built once from a short template. shots is rounded up to a multiple of 64; the same seed gives the same failures on any number of threads (0 is every core).

Type Aliases§

Result
The crate’s result type.