CUDA-Q QEC C++ API
Code
-
class code : public cudaqx::extension_point<code, const heterogeneous_map&>
Base class for quantum error correcting codes in CUDA-Q.
This class provides the core interface and functionality for implementing quantum error correcting codes in CUDA-Q. It defines the basic operations that any QEC code must support and provides infrastructure for syndrome measurement and error correction experiments.
To implement a new quantum error correcting code:
Create a new class that inherits from code
Implement the protected virtual methods:
Define quantum kernels for each required logical operation (these are the fault tolerant logical operation implementations)
Register the operations in your constructor using the operation_encodings map on the base class
Register your new code type using CUDAQ_EXT_PT_REGISTER_TYPE
Example implementation:
__qpu__ void x_kernel(patch p); __qpu__ void z_kernel(patch p); class my_code : public qec::code { protected: std::size_t get_num_data_qubits() const override { return 7; } std::size_t get_num_ancilla_qubits() const override { return 6; } std::size_t get_num_ancilla_x_qubits() const override { return 3; } std::size_t get_num_ancilla_z_qubits() const override { return 3; } public: my_code(const heterogeneous_map& options) : code() { // Can use user-specified options, e.g. auto d = options.get<int>("distance"); operation_encodings.insert(std::make_pair(operation::x, x_kernel)); operation_encodings.insert(std::make_pair(operation::z, z_kernel)); // Register other required operations... // Define the default stabilizers! m_stabilizers = qec::stabilizers({"XXXX", "ZZZZ"}); } CUDAQ_EXTENSION_CUSTOM_CREATOR_FUNCTION( my_code, static std::unique_ptr<qec::code> create(const heterogeneous_map &options) { return std::make_unique<my_code>(options); } ) }; CUDAQ_EXT_PT_REGISTER_TYPE(my_code)
Supported quantum operations for error correcting codes
Subclassed by cudaq::qec::repetition::repetition, cudaq::qec::steane::steane, cudaq::qec::surface_code::surface_code
Public Types
-
using one_qubit_encoding = cudaq::qkernel<void(patch)>
Type alias for single qubit quantum kernels.
-
using two_qubit_encoding = cudaq::qkernel<void(patch, patch)>
Type alias for two qubit quantum kernels.
-
using stabilizer_round = cudaq::qkernel<std::vector<cudaq::measure_result>(patch, const std::vector<std::size_t>&, const std::vector<std::size_t>&)>
Type alias for stabilizer measurement kernels. The two vector arguments are the flattened X and Z stabilizer schedule matrices (see get_stabilizer_schedule_x/z()): entry 0 = no support, entry k >= 1 = interaction at timestep k.
-
using encoding = std::variant<one_qubit_encoding, two_qubit_encoding, stabilizer_round>
Type alias for quantum operation encodings.
Public Functions
-
virtual std::size_t get_num_data_qubits() const = 0
Get the number of physical data qubits needed for the code.
- Returns:
Number of data qubits
-
virtual std::size_t get_num_ancilla_qubits() const = 0
Get the total number of ancilla qubits needed.
- Returns:
Total number of ancilla qubits
-
virtual std::size_t get_num_ancilla_x_qubits() const = 0
Get number of ancilla qubits needed for X stabilizer measurements.
- Returns:
Number of X-type ancilla qubits
-
virtual std::size_t get_num_ancilla_z_qubits() const = 0
Get number of ancilla qubits needed for Z stabilizer measurements.
- Returns:
Number of Z-type ancilla qubits
-
virtual std::size_t get_num_x_stabilizers() const = 0
Get number of X stabilizer that can be measured.
- Returns:
Number of X-type stabilizers
-
virtual std::size_t get_num_z_stabilizers() const = 0
Get number of Z stabilizer that can be measured.
- Returns:
Number of Z-type stabilizers
-
cudaqx::tensor<uint8_t> get_parity() const
Get the full parity check matrix H = (Hx | Hz)
- Returns:
Tensor representing the parity check matrix
-
cudaqx::tensor<uint8_t> get_parity_x() const
Get the X component of the parity check matrix.
- Returns:
Tensor representing Hx
-
cudaqx::tensor<uint8_t> get_parity_z() const
Get the Z component of the parity check matrix.
- Returns:
Tensor representing Hz
-
inline virtual cudaqx::tensor<uint8_t> get_stabilizer_schedule_x() const
Get the X-stabilizer schedule matrix passed to the code’s stabilizer_round kernel. Same shape and support pattern as get_parity_x(); entry 0 means no support, entry k >= 1 means the ancilla-data interaction executes at timestep k, so a code can encode an optimized (e.g. hook-error-aware) gate order.
- Returns:
Tensor of scheduled interactions; the default implementation returns get_parity_x() unchanged (every interaction at timestep 1, i.e. ascending qubit-index order).
-
inline virtual cudaqx::tensor<uint8_t> get_stabilizer_schedule_z() const
Get the Z-stabilizer schedule matrix passed to the code’s stabilizer_round kernel. See get_stabilizer_schedule_x().
- Returns:
Tensor of scheduled interactions; the default implementation returns get_parity_z() unchanged.
-
cudaqx::tensor<uint8_t> get_pauli_observables_matrix() const
Get Lx stacked on Lz.
- Returns:
Tensor representing pauli observables
-
cudaqx::tensor<uint8_t> get_observables_x() const
Get the Lx observables.
- Returns:
Tensor representing Lx
-
cudaqx::tensor<uint8_t> get_observables_z() const
Get the Lz observables.
- Returns:
Tensor representing Lz
-
inline const std::vector<cudaq::spin_op_term> &get_stabilizers() const
Get the stabilizer generators.
- Returns:
Reference to stabilizers
Public Static Functions
-
static std::unique_ptr<code> get(const std::string &name, const std::vector<cudaq::spin_op_term> &stabilizers, const heterogeneous_map options = {})
Factory method to create a code instance with specified stabilizers.
- Parameters:
name – Name of the code to create
stabilizers – Stabilizer generators for the code
options – Optional code-specific configuration options
- Returns:
Unique pointer to created code instance
-
struct patch
Represents a logical qubit patch for quantum error correction.
This type is for CUDA-Q kernel code only.
This structure defines a patch of qubits used in quantum error correction codes. It consists of data qubits and ancilla qubits for X and Z stabilizer measurements.
-
class repetition : public cudaq::qec::code
Implementation of the repetition quantum error correction code.
Public Functions
-
repetition(const heterogeneous_map&)
Constructs a repetition code instance.
-
repetition(const heterogeneous_map&)
-
class steane : public cudaq::qec::code
Steane code implementation.
Public Functions
-
steane(const heterogeneous_map&)
Constructor for the Steane code.
-
steane(const heterogeneous_map&)
-
enum cudaq::qec::surface_code::surface_role
enumerates the role of a grid site in the surface codes stabilizer grid
Values:
-
enumerator amx
-
enumerator amz
-
enumerator empty
-
enumerator amx
-
enum class cudaq::qec::surface_code::sc_orientation
Surface-code orientation: controls which Pauli type (X or Z) occupies the bulk interior and which boundaries are X-type vs Z-type.
Geometry names follow the NVIDIA/Ising-Decoding naming convention (https://github.com/NVIDIA/Ising-Decoding): Ising’s
code_rotationconvention uses first character = bulk syndrome type, second character = rotated_type. By geometry: XV and ZH place X-type stabilizers on the left/right boundaries (Z on top/bottom); XH and ZV place X-type on top/bottom (Z on left/right). XV vs ZH (and XH vs ZV) differ in the bulk X/Z checkerboard.Observable convention: get_spin_op_observables() returns the valid logical pair for the orientation. XV/ZH use X obs along the top row and Z obs along the left column; XH/ZV swap them (X along the left column, Z along the top row). See get_spin_op_observables() for details.
Values:
-
enumerator XV
-
enumerator XH
-
enumerator ZV
-
enumerator ZH
-
enumerator XV
-
struct vec2d
describes the 2d coordinate on the stabilizer grid
-
class stabilizer_grid
Generates and keeps track of the 2d grid of stabilizers in the rotated surface code. Following same layout convention as in: https://arxiv.org/abs/2311.10687 Grid layout is arranged from left to right, top to bottom (row major storage) grid_length = 4 example:
Each entry on the grid can be an X stabilizer, Z stabilizer, or empty, as is needed on the edges. The diagrams below show the default ZH orientation. Other orientations assign X/Z roles according to sc_orientation. The grid length of 4 corresponds to a distance 3 surface code, which results in:(0,0) (0,1) (0,2) (0,3) (1,0) (1,1) (1,2) (1,3) (2,0) (2,1) (2,2) (2,3) (3,0) (3,1) (3,2) (3,3)
e(0,0) e(0,1) Z(0,2) e(0,3) X(1,0) Z(1,1) X(1,2) e(1,3) e(2,0) X(2,1) Z(2,2) X(2,3) e(3,0) Z(3,1) e(3,2) e(3,3)
This is seen through the
print_stabilizer_grid()member function. To get rid of the empty sites, theprint_stabilizer_coords()function is used:Z(0,2) X(1,0) Z(1,1) X(1,2) X(2,1) Z(2,2) X(2,3) Z(3,1)
and to get the familiar visualization of the distance three surface code, the
print_stabilizer_indicesresults in:Z0 X0 Z1 X1 X2 Z2 X3 Z3
The data qubits are located at the four corners of each of the weight-4 stabilizers. They are also organized with index increasing from left to right, top to bottom:
d0 d1 d2 d3 d4 d5 d6 d7 d8
Public Functions
-
stabilizer_grid(uint32_t distance, sc_orientation orientation = sc_orientation::ZH)
Construct the grid from the code’s distance.
-
stabilizer_grid()
Empty constructor.
-
sc_orientation get_orientation() const
Get the orientation used to construct this stabilizer grid.
-
void print_stabilizer_grid() const
Print a 2d grid of stabilizer roles.
-
void print_stabilizer_coords() const
Print a 2d grid of stabilizer coords.
-
void print_stabilizer_indices() const
Print a 2d grid of stabilizer indices.
-
void print_data_grid() const
Print a 2d grid of data qubit indices.
-
void print_stabilizer_maps() const
Print the coord <–> indices maps.
-
void print_stabilizers() const
Print the stabilizers in sparse pauli format.
-
std::vector<cudaq::spin_op_term> get_spin_op_stabilizers() const
Get the stabilizers as a vector of cudaq::spin_op_terms.
-
cudaqx::tensor<uint8_t> get_cnot_schedule_x() const
Get the CNOT schedule matrix for the X stabilizers.
Note
The per-plaquette CNOT order is chosen per the grid’s orientation so that mid-round ancilla faults (“hook errors”), which propagate onto the data qubits of the remaining CNOTs, land perpendicular to the same-type logical operator instead of along it, following the standard zigzag schedule of https://arxiv.org/abs/1404.3747. Rows are ordered to match the rows of to_parity_matrix() / code::get_parity_x().
- Returns:
Tensor with the same shape and support pattern as the X block of the parity check matrix (num_x_stabilizers x distance^2). Entry 0 means the ancilla does not touch that data qubit; entry k in [1, 4] means the ancilla-data CNOT executes at timestep k of the stabilizer round.
-
cudaqx::tensor<uint8_t> get_cnot_schedule_z() const
Get the CNOT schedule matrix for the Z stabilizers.
Note
See get_cnot_schedule_x() for the hook-error rationale and row ordering.
- Returns:
Tensor with the same shape and support pattern as the Z block of the parity check matrix (num_z_stabilizers x distance^2). Entry 0 means the ancilla does not touch that data qubit; entry k in [1, 4] means the data-ancilla CNOT executes at timestep k of the stabilizer round.
-
std::vector<std::size_t> get_cnot_schedule_pairs_x() const
Get the X-stabilizer CNOT schedule as a flat list of (stabilizer index, data index) pairs, ordered by timestep within each stabilizer — the replay format for kernels that take an explicit CNOT pair list. Stabilizer indices match the rows of get_cnot_schedule_x().
-
std::vector<std::size_t> get_cnot_schedule_pairs_z() const
Z-stabilizer counterpart of get_cnot_schedule_pairs_x().
-
std::vector<cudaq::spin_op_term> get_spin_op_observables() const
Get the observables as a vector of cudaq::spin_op_terms.
Note
Returns the correct logical pair for the grid’s orientation. For XV and ZH the X observable runs along the top row of data qubits and the Z observable along the left column; for XH and ZV the assignment is swapped (X along the left column, Z along the top row) to match their boundary types. The returned X/Z observables commute with the stabilizers and anticommute with each other for every orientation.
- Returns:
The X logical observable first, followed by the Z logical observable.
Public Members
-
uint32_t distance = 0
The distance of the code determines the number of data qubits per dimension.
-
uint32_t grid_length = 0
length of the stabilizer grid for distance = d data qubits, the stabilizer grid has length d+1
-
std::vector<surface_role> roles
flattened vector of the stabilizer grid sites roles’ grid idx -> role stored in row major order
-
std::vector<vec2d> data_coords
data index -> 2d coord data qubits are in an offset 2D coord system from stabilizers
-
std::vector<std::vector<size_t>> x_stabilizers
Each element is an X stabilizer specified by the data qubits it has support on In surface code, can have weight 2 or weight 4 stabs So {x,z}_stabilizer[i].size() == 2 || 4.
-
std::vector<std::vector<size_t>> z_stabilizers
Each element is an Z stabilizer specified by the data qubits it has support on.
-
stabilizer_grid(uint32_t distance, sc_orientation orientation = sc_orientation::ZH)
-
class surface_code : public cudaq::qec::code
surface_code implementation
Public Functions
-
surface_code(const heterogeneous_map&)
Constructor for the surface_code.
-
virtual cudaqx::tensor<uint8_t> get_stabilizer_schedule_x() const override
Get the hook-error-aware X-stabilizer CNOT schedule matrix. See stabilizer_grid::get_cnot_schedule_x().
-
virtual cudaqx::tensor<uint8_t> get_stabilizer_schedule_z() const override
Get the hook-error-aware Z-stabilizer CNOT schedule matrix. See stabilizer_grid::get_cnot_schedule_z().
Public Members
-
stabilizer_grid grid
Extension creator function for the surface_code.
Grid to keep track of topological arrangement of qubits.
-
surface_code(const heterogeneous_map&)
Detector Error Model
-
struct detector_error_model
A detector error model (DEM) for a quantum error correction circuit. A DEM can be created from a QEC circuit and a noise model. It contains information about which errors flip which detectors. This is used by the decoder to help make predictions about observables flips.
Shared size parameters among the matrix types.
detector_error_matrix: num_detectors x num_error_mechanisms [d, e]error_rates: num_error_mechanismsobservables_flips_matrix: num_observables x num_error_mechanisms [k, e]
Note
The C++ API for this class may change in the future. The Python API is more likely to be backwards compatible.
Public Functions
-
std::size_t num_detectors() const
Return the number of rows in the detector_error_matrix.
-
std::size_t num_error_mechanisms() const
Return the number of columns in the detector_error_matrix, error_rates, and observables_flips_matrix.
-
std::size_t num_observables() const
Return the number of rows in the observables_flips_matrix.
-
void canonicalize_for_rounds(uint32_t num_syndromes_per_round, bool remove_zero_syndrome_errors = false)
Put the detector_error_matrix into canonical form for round-based decoding: topologically order the columns and merge columns that share the same detector AND observable signature, composing their rates so the canonicalized model matches the input.
Note
Canonicalization does not preserve cross-column exclusivity structure: each output column is given a fresh unique error id and is treated as independent, so any
error_idscorrelation in the input model is discarded.- Parameters:
num_syndromes_per_round – Number of syndromes per round, used to order columns by the rounds their detectors span; 0 disables the per-round key.
remove_zero_syndrome_errors – If false (default), zero-syndrome columns that still flip an observable (undetectable logical errors) are retained so the observable-flip probability is preserved; if true, all columns with no detector signature are dropped (appropriate when the DEM is consumed only for round-based decoding).
-
void canonicalize_for_rounds_with_boundary(uint32_t num_syndromes_per_round, uint32_t num_boundary_syndromes, bool remove_zero_syndrome_errors)
Boundary-aware variant of canonicalize_for_rounds for memory-experiment DEMs whose first and last detector layers (the boundaries) are narrower than the interior layers.
- Parameters:
num_syndromes_per_round – Interior-layer width (syndromes per interior round).
num_boundary_syndromes – Width of the leading and trailing boundary layers: the first and last
num_boundary_syndromesrows form the boundary rounds and each intermediate block ofnum_syndromes_per_roundrows is an interior round.remove_zero_syndrome_errors – Same meaning as in the scalar overload.
- Throws:
std::invalid_argument – if
num_syndromes_per_roundis 0 ornum_boundary_syndromes>num_syndromes_per_round.
Public Members
-
cudaqx::tensor<uint8_t> detector_error_matrix
The detector error matrix is a specific kind of circuit-level parity-check matrix where each row represents a detector, and each column represents an error mechanism. The entries of this matrix are H[i,j] = 1 if detector i is triggered by error mechanism j, and 0 otherwise.
-
std::vector<double> error_rates
The list of weights has length equal to the number of columns of
detector_error_matrix, which assigns a likelihood to each error mechanism.
-
cudaqx::tensor<uint8_t> observables_flips_matrix
The observables flips matrix is a specific kind of circuit-level parity- check matrix where each row represents a Pauli observable, and each column represents an error mechanism. The entries of this matrix are O[i,j] = 1 if Pauli observable i is flipped by error mechanism j, and 0 otherwise.
-
std::optional<std::vector<std::size_t>> error_ids
Error mechanism ID. From a probability perspective, each error mechanism ID is independent of all other error mechanism ID. For all errors with the same ID, only one of them can happen. That is - the errors containing the same ID are correlated with each other.
-
struct decoder_context
Lazy handle returned by
decoder_context_from_memory_circuit.Stores the raw (uncanonicalized) circuit analysis. Call a component method to canonicalize exactly the stabilizer type needed and obtain a
decoder_inputs:x_component()— X-stabilizer detectors onlyz_component()— Z-stabilizer detectors onlyfull_component()— both stabilizer types, boundary-aware
Public Functions
-
std::size_t num_measurements() const
Total number of measurements per shot (column count of m2d/m2o).
-
decoder_inputs x_component() const
Canonicalize X-stabilizer detectors; return decoder_inputs.
-
decoder_inputs z_component() const
Canonicalize Z-stabilizer detectors; return decoder_inputs.
-
decoder_inputs full_component() const
Canonicalize both stabilizer types with boundary awareness; return decoder_inputs.
-
detector_error_model cudaq::qec::dem_from_memory_circuit(const code &code, operation statePrep, std::size_t numRounds, cudaq::noise_model &noise, bool decompose_errors = false)
Given a memory circuit setup, generate a DEM.
- Parameters:
code – QEC Code to sample
statePrep – Initial state preparation operation
numRounds – Number of stabilizer measurement rounds
noise – Noise model to apply
decompose_errors – If true, hyperedge error mechanisms are decomposed into pairs of two-detector edges by Stim before returning.
- Returns:
Detector error model
-
detector_error_model cudaq::qec::x_dem_from_memory_circuit(const code &code, operation statePrep, std::size_t numRounds, cudaq::noise_model &noise, bool decompose_errors = false)
Given a memory circuit setup, generate a DEM for X stabilizers.
- Parameters:
code – QEC Code to sample
statePrep – Initial state preparation operation
numRounds – Number of stabilizer measurement rounds
noise – Noise model to apply
decompose_errors – If true, hyperedge error mechanisms are decomposed into pairs of two-detector edges by Stim before returning.
- Returns:
Detector error model
-
detector_error_model cudaq::qec::z_dem_from_memory_circuit(const code &code, operation statePrep, std::size_t numRounds, cudaq::noise_model &noise, bool decompose_errors = false)
Given a memory circuit setup, generate a DEM for Z stabilizers.
- Parameters:
code – QEC Code to sample
statePrep – Initial state preparation operation
numRounds – Number of stabilizer measurement rounds
noise – Noise model to apply
decompose_errors – If true, hyperedge error mechanisms are decomposed into pairs of two-detector edges by Stim before returning.
- Returns:
Detector error model
-
decoder_context cudaq::qec::decoder_context_from_memory_circuit(const code &code, operation statePrep, std::size_t numRounds, cudaq::noise_model &noise, bool decompose_errors = false)
Run a memory-circuit analysis and return a lazy handle.
Executes
dem_from_kernelonce and stores the raw result. Callx_component(),z_component(), orfull_component()on the returned handle to canonicalize exactly the stabilizer type needed.
-
detector_error_model cudaq::qec::dem_from_stim_text(const std::string &dem_text, bool use_decomp_suggestions = false)
Parse the Stim DEM string
dem_textinto detector/observable flip matrices and error rates. DEM-native decoders should consume raw DEM text instead. By default (use_decomp_suggestions= false) the ‘^’ separators are ignored and each error instruction produces a single column. Ifuse_decomp_suggestionsis true, error mechanisms that carry an explicit graphlike decomposition (components separated by ‘^’) are expanded into one column per component, each inheriting the probability of the parent instruction.error_idsis always left as nullopt. Note that this is a lossy approximation of the original DEM.
Dynamic DEM
Types for constructing a dynamic detector error model (DEM). See the Dynamic Detector Error Models and the Decoding with a Dynamic DEM example.
-
struct dem_chunks_spec
Multi-phase DEM decomposition with arbitrary named phases.
Standard memory experiment (linear chain A → B×N → C): connections = [{init,bulk}, {bulk,bulk}, {bulk,final}] seam = {next_round, prev_round} num_rounds = T (omit for streaming — num_rounds unknown at config time)
dem_chunks_from_spec() calls phase_sequence() to materialise the full ordered chunk list. num_rounds is only needed for that call: phase_sequence() throws when a self-loop is present and num_rounds is absent. For a linear chain (no self-loop) phase_sequence() derives the length from the connections.
Public Functions
-
uint64_t measurements_of(const dem_chunk_spec &phase) const
The measurement count of
phase'sround: its num_measurements, else measurements_per_round.- Throws:
std::invalid_argument – if neither is set.
-
uint64_t num_observables() const
The number of O_sparse rows every phase a connection names carries; 0 when no connection names a phase.
- Throws:
std::invalid_argument – if two of those phases disagree.
-
uint64_t detectors_of(const dem_chunk_spec &phase, const std::string &context = "dem_chunk") const
The detector rows
phase'sround contributes when closed: its to_seam band and interior rows. Builds the phase’s chunk on each call.- Parameters:
phase – The DEM chunk phase whose detector rows are counted.
context – Prefix for error messages, as for dem_chunk_from_spec().
- Throws:
std::invalid_argument – if the phase is inconsistent.
-
bool has_D_sparse() const
Whether the phases supply D, rather than leaving dem_chunks_to_d_sparse() to apply the memory convention.
phases_supply_D_sparse when set, else inferred from any phase carrying rows. Replaces the
!D_sparse.empty()test, which cannot tell an absent mapping from a present one whose phase contributes no rows.
-
bool is_empty() const
True when no phases or connections have been set.
-
bool has_repeating_phase() const
True when any connection is a self-loop.
-
bool has_readout() const
True when any phase carries m2o_sparse, so the spec reads observables.
-
uint64_t minimum_rounds() const
Shortest chain the connections admit: one round per non-self connection, plus the round the last one lands on. A repeating phase can be visited once, so this is the round count a streaming spec expands to when nothing else pins it, and the smallest window a caller may ask that spec for.
-
phase_id repeating_phase() const
Return the phase_id of the self-connected (repeating) phase.
- Throws:
std::invalid_argument – if there is no or more than one self-loop.
-
repeating_span repeating_rounds() const
Where the repeating phase sits in phase_sequence(), found from the shortest chain, so nothing proportional to num_rounds is built.
- Throws:
std::invalid_argument – as phase_sequence() and repeating_phase().
-
phase_layout layout() const
The phase layout of a shot of any length, from the shortest chain; num_rounds is not consulted. Copies the spec on each call.
- Throws:
std::invalid_argument – as phase_sequence() and repeating_phase().
-
std::vector<phase_id> phase_sequence() const
Expand connections + num_rounds into an ordered phase_id list.
With a self-loop (repeating phase) and num_rounds = T: result = [A, B, B, …(T-2 times)…, B, C] Without a self-loop, the sequence length is derived from the connections and num_rounds is not consulted.
- Throws:
std::invalid_argument – if a self-loop is present and num_rounds is absent, or if the connection graph is not a valid linear chain: a phase with more than one non-self outgoing edge, or a cycle among the non-self edges, is rejected.
-
const dem_chunk_spec &get_phase(phase_id id) const
Return the spec for the phase with the given id.
- Throws:
std::invalid_argument – if no such phase exists.
-
void validate() const
Validate phase specs, connection graph, and seam widths.
Also checks that every connection names a phase with a spec, the phases agree on the observable count, observable_names has one unique name per observable, and no repeating phase carries m2o_sparse, which has one row per observable inside its round: its measurement count with D_sparse, else its detectors.
- Throws:
std::invalid_argument – on the first violation.
Public Members
-
std::optional<uint64_t> measurements_per_round
Measurements each round adds to the stream, for phases carrying D_sparse rows; a phase’s num_measurements overrides it.
-
std::optional<bool> phases_supply_D_sparse
Whether the phases supply D, where the emptiness of their D_sparse rows cannot say so on its own. Carries no rows itself: it only settles how has_D_sparse() reads the ones the phases carry.
Unset infers it: any phase carrying rows means the spec supplies D, which is what every spec written before this field did and what a memory experiment needs. Set it only where emptiness is ambiguous — true declares that the phases supply D even where one of them contributes no detector rows at all, false keeps the dem_chunks_to_d_sparse() memory convention even though rows are present. See has_D_sparse().
-
std::vector<std::string> observable_names
Optional observable names, one per O_sparse row.
-
struct phase_layout
The phases of a shot’s rounds before, of, and after the repeating phase.
-
struct repeating_span
Rounds of phase_sequence() before, of, and after the repeating phase.
-
uint64_t measurements_of(const dem_chunk_spec &phase) const
-
struct phase_spec_entry
-
struct phase_connection
Directed edge in the phase graph.
A self-connection (from_phase == to_phase) marks the repeating phase in a linear chain.
-
struct seam_connection
Which seam of one phase contracts against which seam of the next.
-
struct dem_chunk_spec
One DEM phase/chunk as flat index lists.
Two mutually exclusive forms:
Shorthand: H_sparse at chunk level. The expander assigns this single H to every seam named in the connection (all seams share the same H rows). Valid for CSS memory experiments where prev_round.H == next_round.H.
Full per-seam: seam_specs populated directly with per-seam H_sparse and O_sparse. Required when seams carry different H rows (non-memory gadgets).
O_sparse at chunk level maps to extended_dem::O (the decoder observable).
Public Functions
-
bool is_empty() const
True when nothing has been set.
-
void expand(const std::vector<seam_id> &ids)
Expand H_sparse shorthand into seam_specs using the provided IDs.
No-op when seam_specs is already populated. The shorthand H_sparse is assigned to every seam in ids with an empty O_sparse.
- Parameters:
ids – Seam IDs to create entries for (e.g. {next_round, prev_round})
-
void validate(const std::string &context) const
Check internal consistency.
Validates num_faults, error_rates, mutual exclusion of H_sparse / seam_specs, and all H_sparse / O_sparse index lists.
- Parameters:
context – Prefix for error messages.
- Throws:
std::invalid_argument – on the first violation.
Public Members
-
std::vector<std::int64_t> H_sparse
Shorthand: shared H for all seams. Mutually exclusive with seam_specs.
-
std::vector<seam_spec_entry> seam_specs
Full per-seam form. Mutually exclusive with H_sparse.
-
std::vector<std::int64_t> O_sparse
Chunk-level observable rows → extended_dem::O.
-
std::vector<std::int64_t> D_sparse
Optional measurement-to-detector rows in the -1-terminated encoding, one per detector this chunk contributes when closed: its to_seam rows, then its interior rows. Indices count the previous round’s measurements first and then this round’s own: index j is the previous round’s measurement j when j is below that round’s measurement count, and otherwise this round’s measurement j minus that count. Either every phase of a dem_chunks_spec carries rows or none does; with none, D follows the memory-experiment convention of dem_chunks_to_d_sparse().
The window is those two rounds and no further back, which bounds what a measurement-free phase can sit between. Such a phase — a transversal Clifford, a state preparation — may form its own detectors from the round before it, but it then leaves that round unreachable to the phase after it, whose window starts at its own first measurement. A chain that must difference across such a gadget cannot say so here.
-
std::optional<uint64_t> num_measurements
Measurements this phase’s round adds to the stream, when it differs from dem_chunks_spec::measurements_per_round (a final data readout, say). Like that field, it applies when the phases carry D_sparse rows; without them a round adds one measurement per detector.
-
std::vector<std::int64_t> m2o_sparse
Optional readout map, -1-terminated: one row per observable, listing the measurements of this phase’s own round whose parity this round adds to the observable’s raw value (the XOR over every round that reads it); an empty row adds nothing. A repeating phase may not carry it. The round has its measurement count when the phases carry D_sparse rows, else one measurement per detector.
-
bool is_empty() const
-
struct seam_spec_entry
-
struct dem_seam_spec
Per-seam sparse spec: rows for one named seam boundary.
H_sparse and O_sparse use the -1-terminated row encoding: [0, 1, 5, -1, 1, 2, 6, -1] describes two rows.
-
struct seam_id
Lightweight identifier for a named seam or phase.
The value is the FNV1a-32 hash of the name string, computed at compile time. Two seam_ids are equal iff they were constructed from the same name. The same string always produces the same ID, so no registry is required for identity comparison. A name registry is available via register_name() and name() for human-readable diagnostics and error messages.
Public Functions
-
std::string name() const
Return the registered name, or “seam:<hex>” if not registered.
Public Static Functions
-
static void register_name(seam_id id, std::string_view name)
Register a display name for diagnostics. Same name is a no-op; a different name for the same id throws (FNV1a-32 collision).
-
static seam_id from_name(std::string_view name)
Inverse of name(): “seam:<hex>” is the id it spells, left unregistered so the placeholder does not claim the id; any other name is hashed and registered.
- Throws:
std::invalid_argument – on a collision, as register_name().
-
std::string name() const
-
using cudaq::qec::phase_id = seam_id
Same type as seam_id; separate alias for readability at call sites that refer to phase identities rather than seam identities.
-
namespace seam_name
-
namespace phase_name
-
dem_chunks_spec cudaq::qec::memory_dem_chunks_from_decoder_inputs(const decoder_inputs &inputs, std::size_t extraction_rounds, std::size_t measurements_per_round, std::size_t final_measurements)
Split a characterized memory circuit into reusable DEM phases.
The input records contain
extraction_roundsgroups ofmeasurements_per_roundbits followed byfinal_measurementsdata readout bits. Each detector is assigned to the round containing its latest measurement. Its D row may read that round and its immediate predecessor only. Detector numbering must already be round-major. Each independent fault must touch a detector and span at most two consecutive detector rounds. Up to 64 observables are supported.Consecutive phases matching the middle round are collapsed into one bulk phase with a self-loop. At least two matching rounds are required as evidence of repetition. Prefix and suffix transients are retained separately. Rates must agree within a relative tolerance of 1e-9 for phases to be considered equal. Faults with identical detector and observable signatures are merged using independent XOR probabilities.
The returned spec carries the original horizon: extraction_rounds + 1, including the distinct final readout round. A caller may replace num_rounds to repeat the validated bulk phase over another horizon, subject to the spec’s minimum_rounds(). Characterizing a bounded representative circuit and then retargeting the result avoids building a long dense DEM. This structural comparison is not a proof of repetition for arbitrary circuit families; callers must establish that their circuit repeats.
The input matrices and measurement maps are validated before indexing. Measurement-map rows must be sorted and unique. Shared error_ids are rejected: dem_chunks does not preserve cross-column exclusivity. The raw measurement-to-observable map is validated but is not included in the returned spec, whose O maps faults, not raw measurements.
- Throws:
std::invalid_argument – for invalid dimensions, mappings, probabilities, locality, missing repetition, unsupported correlated columns, or a phase with no faults. Zero-fault phases require separate support in extended_dem and are not fabricated by adding dummy faults.
std::overflow_error – when a dimension exceeds the index format.
Detector Error Model (DEM) Sampling
CPU sampling (host tensors):
-
std::tuple<cudaqx::tensor<uint8_t>, cudaqx::tensor<uint8_t>> cudaq::qec::dem_sampler::cpu::sample_dem(const cudaqx::tensor<uint8_t> &check_matrix, std::size_t numShots, const std::vector<double> &error_probabilities)
Sample measurements from a check matrix (CPU, per-mechanism probs)
- Parameters:
check_matrix – Binary matrix [num_checks × num_error_mechanisms]
numShots – Number of measurement shots
error_probabilities – Per-error-mechanism probabilities
- Returns:
(checks [numShots × num_checks], errors [numShots × num_mechanisms])
-
std::tuple<cudaqx::tensor<uint8_t>, cudaqx::tensor<uint8_t>> cudaq::qec::dem_sampler::cpu::sample_dem(const cudaqx::tensor<uint8_t> &check_matrix, std::size_t numShots, const std::vector<double> &error_probabilities, unsigned seed)
Sample measurements from a check matrix with seed (CPU)
GPU sampling (device pointers, requires cuStabilizer):
-
bool cudaq::qec::dem_sampler::gpu::sample_dem(const uint8_t *d_check_matrix, size_t num_checks, size_t num_error_mechanisms, const double *d_error_probabilities, size_t num_shots, unsigned seed, uint8_t *d_checks_out, uint8_t *d_errors_out, std::uintptr_t stream_handle = 0)
GPU DEM sampling with caller-provided device pointers.
The function composes (all GPU memory is allocated and freed internally per call):
pack_check_matrix_rowwise (dense uint8 → bitpacked uint32)
custabilizerSampleProbArraySparseCompute (sparse Bernoulli sampling)
custabilizerGF2SparseDenseMatrixMultiply (syndrome = errors * H^T)
unpack_syndromes_gpu (bitpacked uint32 → uint8)
csr_to_dense_fused (CSR errors → dense uint8)
- Parameters:
d_check_matrix – Device pointer [num_checks × num_error_mechanisms]
num_checks – Number of checks (rows of H)
num_error_mechanisms – Number of error mechanisms (columns of H)
d_error_probabilities – Device pointer [num_error_mechanisms]
num_shots – Number of samples
seed – RNG seed
d_checks_out – Device pointer [num_shots × num_checks] (OUTPUT)
d_errors_out – Device pointer [num_shots × num_error_mechanisms] (OUT)
stream_handle – Optional CUDA stream handle (uintptr_t cast), 0 for default stream
- Returns:
true on success, false if cuStabilizer is unavailable
Legacy convenience wrappers (delegate to cpu::sample_dem; prefer the
dem_sampler::cpu::sample_dem overloads above):
-
std::tuple<cudaqx::tensor<uint8_t>, cudaqx::tensor<uint8_t>> cudaq::qec::dem_sampling(const cudaqx::tensor<uint8_t> &check_matrix, std::size_t numShots, const std::vector<double> &error_probabilities)
Sample a detector error model on CPU (legacy API).
- Parameters:
check_matrix – Binary matrix [num_checks x num_error_mechanisms]
numShots – Number of independent Monte-Carlo shots
error_probabilities – Per-error-mechanism Bernoulli probabilities
- Returns:
Tuple of (checks, errors)
-
std::tuple<cudaqx::tensor<uint8_t>, cudaqx::tensor<uint8_t>> cudaq::qec::dem_sampling(const cudaqx::tensor<uint8_t> &check_matrix, std::size_t numShots, const std::vector<double> &error_probabilities, unsigned seed)
Sample a detector error model on CPU (legacy API, seeded).
- Parameters:
check_matrix – Binary matrix [num_checks x num_error_mechanisms]
numShots – Number of independent Monte-Carlo shots
error_probabilities – Per-error-mechanism Bernoulli probabilities
seed – RNG seed for reproducibility
- Returns:
Tuple of (checks, errors)
Decoder Interfaces
-
enum class cudaq::qec::decode_result_type : std::uint8_t
The primary result basis requested from a decoder.
Values:
-
enumerator errors
Primary result is an error frame.
-
enumerator observables
Primary result is an observable frame.
-
enumerator errors
-
enum class cudaq::qec::decoder_auxiliary_result_type : std::uint8_t
Standardized auxiliary outputs a decoder may be requested to return. Values are independent flags and may be combined.
Values:
-
enumerator none = 0
-
enumerator residual_detectors = 1u << 0
Residual detector values in
opt_results["residual_detectors"].
-
enumerator none = 0
-
struct decoder_output_request
Immutable primary and auxiliary output contract for a decoder.
-
enum class cudaq::qec::decoder_model_source : std::uint8_t
Authoritative representation from which a decoder model originates.
A chunked DEM is the compact source: a decoder that consumes chunks reads them through
dem_chunks(), and the handle carries the closed matrices only when built withfrom_dem_chunks_closed(). A further source is added the same way, with a new enumerator plus its typed constructor and accessor, changing neither thedecoder_initobject layout nor the decoder factory signature.Values:
-
enumerator matrices
-
enumerator stim_dem
-
enumerator dem_chunks
-
enumerator matrices
-
struct decoder_inputs
Finalized decoder inputs: a canonicalized DEM and measurement maps.
-
class decoder_init
Stable, owning input contract shared by offline and server decoders.
This is a small immutable value handle. Copies share the same model state; the decoder factory takes the handle by value and the decoder base retains it. Source-specific data is authoritative and the common matrix accessors expose its projection, stored when the handle is constructed. A chunked source built by
from_dem_chunks()has none (seehas_matrices()). Model matrices are stored sparsely instead of composing detector_error_model, whose matrix fields are dense tensors.Public Functions
-
explicit decoder_init(sparse_binary_matrix detector_error_matrix)
Construct an H-only matrix model.
-
explicit decoder_init(std::string) = delete
Raw Stim DEM text enters through from_stim_dem(), which parses and projects it. Deleted so the older spelling fails here rather than through overload resolution somewhere less obvious.
-
decoder_init(sparse_binary_matrix detector_error_matrix, std::optional<sparse_binary_matrix> observable_flips_matrix, std::vector<double> error_rates = {}, std::optional<sparse_binary_matrix> measurement_to_detectors = std::nullopt, std::optional<std::vector<std::size_t>> error_ids = std::nullopt)
Construct a materialized matrix model.
- Parameters:
detector_error_matrix – H, with shape detectors x error mechanisms.
observable_flips_matrix – O, with shape observables x error mechanisms. Supplying it establishes an observable model; its row count is retained even when a row has no nonzeros, so a zero-row O is a supplied model rather than an absent one.
error_rates – Optional rate per error mechanism.
measurement_to_detectors – Optional D, with shape detectors x raw measurements.
error_ids – Optional correlation ID per error mechanism.
-
explicit decoder_init(detector_error_model model, std::optional<sparse_binary_matrix> measurement_to_detectors = std::nullopt)
Construct from the existing materialized detector-error model.
-
decoder_init(decoder_init&&) noexcept
Move construction leaves the source valid only for destruction or assignment.
-
decoder_init &operator=(decoder_init&&) noexcept
Move assignment leaves the source valid only for destruction or assignment.
-
decoder_model_source source() const noexcept
The authoritative representation. Consumers that only need to know whether raw DEM text is available should ask has_stim_dem(); this discriminator is what a future compact source would extend.
-
const sparse_binary_matrix &detector_error_matrix() const
Return the stored common H projection.
- Throws:
std::logic_error – if
has_matrices()is false.
-
bool has_observable_model() const noexcept
Whether this model supplies an observable mapping at all.
Distinct from
num_observables() == 0: a supplied O with zero rows is an observable model, an H-only input is not. Construction-time validation of an observable-output request depends on this distinction. A chunked source has one when its chunks carry observables, matrices or not.
-
const sparse_binary_matrix &observable_flips_matrix() const
Return the stored common O projection.
- Throws:
std::logic_error – if this model supplies no observable mapping, or
has_matrices()is false.
-
const std::vector<double> &error_rates() const
- Throws:
std::logic_error – if
has_matrices()is false.
-
const sparse_binary_matrix *measurement_to_detectors() const noexcept
Return D, or nullptr when input syndromes are already detectors.
-
decoder_init decoder_init_without_d() const
Return the same inputs without D, for a decoder that is fed detectors rather than a raw measurement stream. Everything else, including the authoritative source, is preserved.
-
decoder_init without_observables() const
Return the same inputs without an observable model, for a decoder that must report errors rather than observables. Chunks lose their observable rows and keep their form; a Stim source, whose text names the observables, becomes a matrix source.
-
decoder_init canonicalize_H() const
Return the same inputs with H in GF(2)-canonical CSC form.
Sorts indices within each compressed group and XOR-merges duplicates, leaving column identity, ordering and dimensions unchanged. O and D are passed through untouched, and the authoritative source is retained. Consumers that need a canonical H should ask for it here rather than rebuilding a matrix-authoritative handle by hand.
-
const std::string &stim_dem() const
- Throws:
std::logic_error – if the authoritative source is not a Stim DEM.
-
const dem_chunks_spec &dem_chunks() const
- Throws:
std::logic_error – if the authoritative source is not chunked.
-
bool has_matrices() const noexcept
Whether H, O and the error rates are available. False only for a chunked source built by
from_dem_chunks(), whose matrix accessors throw std::logic_error.
-
std::size_t num_detectors() const noexcept
Dimensions are stored as source metadata so these accessors never need to request H or O. For matrix sources they intentionally duplicate the O(1) matrix shape values in preparation for compact source alternatives.
Public Static Functions
-
static decoder_init from_stim_dem(std::string stim_dem_text, std::optional<sparse_binary_matrix> measurement_to_detectors = std::nullopt)
Construct from authoritative raw Stim DEM text.
Matrix accessors expose the common lossy projection produced by
dem_from_stim_text; DEM-native decoders should consumestim_dem().
-
static decoder_init from_dem_chunks(dem_chunks_spec spec, std::optional<sparse_binary_matrix> measurement_to_detectors = std::nullopt)
Construct from an authoritative chunked DEM, without its closed model.
For a decoder that consumes
dem_chunks(). The dimensions are those ofdem_close_allover the spec’s chunks, computed from its phases alone, and nothing proportional to the shot’s error mechanisms is stored. The matrix accessors throw; a decoder that needs them takesfrom_dem_chunks_closed()instead. Projecting an error frame onto observables does not need them:dem_chunks_to_o_chunked()reads the mapping straight out ofdem_chunks().- Parameters:
spec – Chunked DEM; a repeating phase needs
num_rounds.measurement_to_detectors – Optional D, one row per detector.
- Throws:
std::invalid_argument – If the spec does not validate or expand, or D has the wrong row count.
-
static decoder_init from_dem_chunks_closed(dem_chunks_spec spec, std::optional<sparse_binary_matrix> measurement_to_detectors = std::nullopt)
Construct from an authoritative chunked DEM together with its closed model.
As
from_dem_chunks(), and H, O and the error rates are the modeldem_close_allcloses the chunks to, built sparsely here. Any decoder accepts this handle; a chunk-native one still readsdem_chunks().- Throws:
std::invalid_argument – As
from_dem_chunks().
-
explicit decoder_init(sparse_binary_matrix detector_error_matrix)
-
void cudaq::qec::register_decoder_native_model_source(std::string decoder_name, decoder_model_source source)
Declare that the decoder registered under
decoder_namereadssourcenatively, so its matrices need not be built.Declare only a source whose matrices are too costly to build unconditionally — a chunked DEM, whose closure grows with the round count. A decoder reading a source that projects cheaply, as chromobius does, declares nothing. Call from the static initializer that registers the decoder, under the same name; declarations accumulate and are never removed.
-
bool cudaq::qec::decoder_needs_model_matrices(const std::string &decoder_name, decoder_model_source source)
Whether to build H, O and the error rates for
decoder_namewhen its model comes fromsource.The type-level counterpart of
decoder_init::has_matrices(), answered before any handle exists. True unless the decoder declared it readssourcenatively, so an unknown name is given matrices. Warns once on a declaration naming no registered decoder.
-
std::vector<std::int64_t> cudaq::qec::d_sparse(const cudaq::M2DSparseMatrix &m2d)
Flatten an M2DSparseMatrix into the
-1-terminated sparse vector a realtime decoder config expects for itsD_sparse.
-
enum class cudaq::qec::round_type
The shape of one round, as named by the decoding server’s syndrome mapping table. Lives here so the server and the decoder share one enum.
Values:
-
enumerator BULK
Mid-circuit syndrome-extraction round.
-
enumerator FINAL
Last round of a shot; its detector set differs from a bulk round.
-
enumerator BULK
-
enum class cudaq::qec::cancellation_level : std::uint8_t
Requested stop level, ordered by severity.
Values:
-
enumerator none = 0
No stop requested.
-
enumerator soft = 1
Stop the nodes that poll for soft stops.
-
enumerator hard = 2
Stop every node.
-
enumerator none = 0
-
class cancellation_token
Read-only view of a
cancellation_source’s shared cancellation state.Public Functions
-
cancellation_token() noexcept = default
A token that never reports a stop.
-
inline bool stop_possible() const noexcept
False if the token was default-constructed.
-
inline bool stop_requested(cancellation_level min_level = cancellation_level::soft) const noexcept
True if a stop of at least
min_levelhas been requested. The default reports any stop.
-
cancellation_token() noexcept = default
-
class cancellation_source
Owns the cancellation state observed by the
cancellation_tokens obtained from it. The state outlives the source for as long as any token referencing it exists.Public Functions
-
inline bool request(cancellation_level lvl) noexcept
Request at least
lvl. Never lowers the current level.- Returns:
true if this call raised the level, otherwise false.
-
inline bool request_soft_stop() noexcept
Request a soft stop (see
cancellation_level::soft).
-
inline bool request_hard_stop() noexcept
Request a hard stop (see
cancellation_level::hard).
-
inline cancellation_level level() const noexcept
The currently requested level.
-
inline cancellation_token get_token() const noexcept
A token observing this source’s state.
-
inline bool request(cancellation_level lvl) noexcept
-
class decoder : public cudaqx::extension_point<decoder, decoder_init, std::optional<decoder_output_request>, const cudaqx::heterogeneous_map&>
The
decoderbase class should be subclassed by specific decoder implementations. Theheterogeneous_mapprovides a placeholder for arbitrary constructor parameters that can be unique to each specific decoder.Public Functions
-
decoder(decoder_init inputs, decoder_output_request requested_output = decoder_output_request{decode_result_type::errors})
Constructor.
- Parameters:
inputs – Stable model and measurement inputs. Taken by value so the factory can move its immutable handle into the decoder.
requested_output – The primary and auxiliary output contract this instance produces, fixed for its lifetime.
-
virtual decoder_result decode(const std::vector<float_t> &syndrome) = 0
Decode a single syndrome.
- Parameters:
syndrome – A vector of syndrome measurements where the floating point value is the probability that the syndrome measurement is a |1>. The length of the syndrome vector should be equal to
syndrome_size.- Throws:
std::invalid_argument – if the decoder does not accept a syndrome of this length. Implementations must check the length before indexing the syndrome;
check_syndrome_size()does this for the common case.- Returns:
A result satisfying the instance’s construction-time output contract. The
resultfield contains the primary output, and requested auxiliary outputs are stored inopt_results. A decoder that cannot satisfy the contract rejects construction.
-
virtual decoder_result decode(const cudaqx::tensor<uint8_t> &syndrome)
Decode a single syndrome.
- Parameters:
syndrome – An order-1 tensor of syndrome measurements where a 1 bit represents that the syndrome measurement is a |1>. The length of the syndrome vector should be equal to
syndrome_size.- Returns:
A result satisfying the instance’s construction-time output contract.
-
virtual std::optional<decoder_result> decode(const cudaqx::tensor<uint8_t> &syndrome, cancellation_token tok)
Decode a single syndrome (tensor form), cooperatively cancellable via
tok. Converts and delegates todecode(vector, cancellation_token).- Parameters:
syndrome – An order-1 tensor of syndrome measurements where a 1 bit represents that the syndrome measurement is a |1>. The length of the syndrome vector should be equal to
syndrome_size.tok – The cancellation token to use.
- Returns:
decoder_result, or std::nullopt if a stop was honored before any result was available.
-
virtual std::future<decoder_result> decode_async(const std::vector<float_t> &syndrome)
Decode a single syndrome.
- Parameters:
syndrome – A vector of syndrome measurements where the floating point value is the probability that the syndrome measurement is a |1>.
- Returns:
A future containing a result satisfying the instance’s construction-time output contract.
-
inline virtual std::optional<decoder_result> decode(const std::vector<float_t> &syndrome, cancellation_token tok)
Decode a single syndrome, cooperatively cancellable via
tok. The default implementation ignorestokand delegates to decode(syndrome), i.e. a decoder is non-cancellable unless it overrides this overload. A decoder that can polltokshould override this and return std::nullopt oncetok.stop_requested()answers true (seecancellation_token).- Parameters:
syndrome – A vector of syndrome measurements where the floating point value is the probability that the syndrome measurement is a |1>.
tok – The cancellation token to use.
- Returns:
decoder_result, or std::nullopt if a stop was honored before any result was available.
-
virtual std::vector<decoder_result> decode_batch(const std::vector<std::vector<float_t>> &syndrome)
Decode multiple independent syndromes (may be done in serial or parallel depending on the specific implementation)
- Parameters:
syndrome – A vector of
Nsyndrome measurements where the floating point value is the probability that the syndrome measurement is a |1>.- Returns:
One result per input satisfying the instance’s construction-time output contract.
-
virtual std::vector<decoder_result> decode_batch(const std::vector<std::vector<float_t>> &syndrome, std::optional<cudaqx::heterogeneous_map> &batch_opt_results)
Decode multiple independent syndromes, additionally returning results that describe the batch as a whole rather than any single shot.
Per-shot data belongs in
decoder_result::opt_results. This overload exists for data that is naturally batch-wide: returning it once as flat batch-indexed arrays is more efficient to produce and to consume than splitting it into one small map entry per shot.The default implementation forwards to the single-argument overload and leaves
batch_opt_resultsempty, so decoders that have no batch-level data need not override this. Decoders that override either overload should pull both into scope withusing decoder::decode_batch;to avoid overload hiding.- Parameters:
syndrome – A vector of
Nsyndrome measurements where the floating point value is the probability that the syndrome measurement is a |1>.batch_opt_results – Output parameter receiving batch-level results, or left unset if the decoder produces none.
- Returns:
One result per input satisfying the instance’s construction-time output contract.
-
virtual std::optional<std::vector<decoder_result>> decode_batch(const std::vector<std::vector<float_t>> &syndrome, cancellation_token tok)
Decode multiple independent syndromes, cooperatively cancellable via
tok. The default implementation ignorestokand delegates to decode_batch(syndrome), mirroring the single-syndrome default above.- Parameters:
syndrome – A vector of
Nsyndrome measurements where the floating point value is the probability that the syndrome measurement is a |1>.tok – The cancellation token to use.
- Returns:
One result per shot, or std::nullopt if a stop was honored before the batch completed.
-
inline decode_result_type get_result_type() const noexcept
The primary result basis this instance was constructed to produce.
-
inline decoder_auxiliary_result_type get_auxiliary_result_type() const noexcept
The auxiliary outputs this instance was constructed to produce.
-
inline const decoder_output_request &get_output_request() const noexcept
The complete construction-time primary and auxiliary contract.
-
uint32_t get_num_msyn_per_decode() const
Get the number of measurement syndromes per decode call, i.e. the measurement count of the model’s measurement-to-detector map. Zero when the model supplies no such map, because its syndromes are already detectors.
-
inline int get_cuda_device_id() const
The CUDA device this decoder was pinned to at construction via the “cuda_device_id” parameter, or -1 when no pin was requested. Construction pins the constructing thread persistently (the thread that creates a decoder is the thread expected to drive its decode calls).
-
void set_decoder_id(uint32_t decoder_id)
Set the decoder id.
-
uint32_t get_decoder_id() const
Get the decoder id.
-
virtual bool enqueue_syndrome(const uint8_t *syndrome, std::size_t syndrome_length)
Enqueue a syndrome for decoding (pointer version)
- Returns:
True if enough syndromes have been enqueued to trigger a decode.
-
virtual bool enqueue_syndrome(const std::vector<uint8_t> &syndrome)
Enqueue a syndrome for decoding (vector version)
- Returns:
True if enough syndromes have been enqueued to trigger a decode.
-
virtual bool enqueue_syndrome(const uint8_t *syndrome, std::size_t syndrome_length, round_type type)
Enqueue one round, tagged with its shape. The base drops the tag and forwards, so a fixed-length decoder is unaffected; one that decides its length at run time overrides this to learn where a shot ends.
-
virtual const uint8_t *get_obs_corrections() const
Get the current observable corrections.
-
std::size_t get_num_observables() const
Get the number of observables.
-
virtual void clear_corrections()
Clear any stored corrections.
-
virtual void reset_decoder()
Reset the decoder, clearing all per-shot memory and corrections.
-
inline virtual bool supports_graph_dispatch() const
Returns true if this decoder supports graph-based realtime dispatch via capture_decode_graph().
-
inline virtual void *capture_decode_graph(int reserved_sms = 0)
Capture a CUDA graph for realtime dispatch.
Returns a pointer to a cudaq::qec::realtime::graph_resources struct (caller must include realtime/graph_resources.h to interpret it). Returns nullptr if graph dispatch is not supported. The decoder retains ownership of the returned pointer.
-
inline virtual void release_decode_graph(void *graph_resources)
Release graph resources previously returned by capture_decode_graph().
-
virtual ~decoder() = default
Destructor.
-
virtual std::string get_version() const
Get the version of the decoder. Subclasses that are not part of the standard GitHub repo should override this to provide a more tailored version string.
- Returns:
A string containing the version of the decoder
Public Static Functions
-
static std::unique_ptr<decoder> get(const std::string &name, decoder_init inputs, const cudaqx::heterogeneous_map ¶m_map = cudaqx::heterogeneous_map())
Construct a registered decoder by name.
Note
When no result type is supplied, the plugin chooses its documented default. PyMatching defaults to error-frame output.
- Parameters:
name – The registered decoder name.
inputs – Stable decoder model inputs. Supplying an observable model does not select observable output.
param_map – Optional decoder-specific parameters.
-
static std::unique_ptr<decoder> get(const std::string &name, decoder_init inputs, decoder_output_request output, const cudaqx::heterogeneous_map ¶m_map = cudaqx::heterogeneous_map())
Construct a registered decoder with an explicit output contract.
Protected Functions
-
inline const decoder_init &get_inputs() const noexcept
The immutable construction inputs owned by this decoder.
-
void project_errors_to_observables(const float_t *errors, float_t *observables, std::size_t observables_size) const
Project an error frame onto observables through the model’s O.
A decoder that internally computes an error frame but was constructed for observable output calls this before returning. The projection lives here so it is implemented once rather than per plugin.
- Throws:
std::runtime_error – if no observable mapping is available.
-
inline void check_syndrome_size(std::size_t size) const
Reject a syndrome whose length is not
syndrome_size.Inline and non-virtual so that plugins built against older headers keep the same layout, vtable and imported symbols.
- Parameters:
size – The length of the syndrome passed to decode.
- Throws:
std::invalid_argument – if
sizediffers fromsyndrome_size.
-
void initialize_streaming_layout(std::size_t num_syndromes_per_round, std::vector<std::size_t> detector_layer_offsets)
Declare that this decoder consumes its realtime input as a stream of detector layers rather than one full syndrome per decode.
Everything the realtime path can derive from the model — D, the measurement buffer, the detector buffers, the corrections buffer — is sized by the base constructor from
decoder_init. Layer geometry is the exception: it is a property of how the decoder consumes rounds, not of the model, and the base cannot ask a subclass for it while the subclass is still being constructed. A streaming decoder therefore hands it over here, from its own constructor.- Parameters:
num_syndromes_per_round – Width of the widest detector layer, which bounds the per-layer buffers.
detector_layer_offsets – Offsets
[0, w0, w0+w1, ...];back()must equal the model’s detector count.
- Throws:
std::logic_error – if called more than once. This is construction state, not a reconfiguration point: re-entering it on a live decoder would reset its buffers mid-stream.
Protected Attributes
-
std::size_t block_size = 0
For a classical
[n,k]code, this isn.
-
std::size_t syndrome_size = 0
For a classical
[n,k]code, this isn-k
-
int cuda_device_id_ = -1
CUDA device id consumed from the construction parameters by decoder::get(); -1 = unpinned. See get_cuda_device_id().
-
decoder(decoder_init inputs, decoder_output_request requested_output = decoder_output_request{decode_result_type::errors})
-
struct decoder_result
Decoder results.
Public Members
-
bool converged = false
Whether or not the decoder converged.
-
std::vector<float_t> result
Primary result values in the instance’s construction-time output basis. Error results have length
block_size; observable results have lengthget_num_observables().
-
std::optional<cudaqx::heterogeneous_map> opt_results
Requested standardized auxiliary outputs and optional decoder-specific metadata, stored in a heterogeneous map. Standardized keys are documented by
decoder_auxiliary_result_type.For equality comparison, this field is treated as a boolean flag - two decoder_results are considered equal only if both have empty opt_results (either std::nullopt or an empty map). If either result has non-empty opt_results, they are considered not equal.
-
bool converged = false
Decoding Task Graph
A decoding_task_graph is a decoder pipeline of nodes wired by edges. Build
one with from_spec (one decoder in a window), combine (two decoders
whose corrections are XORed) or from_topology (any nodes and edges). Run it
on complete shots with run and run_batch, or stream rounds with
enqueue_syndrome. See the Decoding Task Graphs, its
Reference section, and the
Getting Started with a Decoding Task Graph.
I/O types
-
struct measurement_results
Raw per-shot measurement record from the QPU.
-
struct detection_events
Aggregated detection events: s = D * m (mod 2). Stored as float_t so it can be passed directly to decoder::decode().
-
struct logical_outcome
Final observable correction. The role (L_raw, L_flip, or L_obs) is carried by the graph topology, not the type.
Public Members
-
std::vector<uint8_t> bits
length = num_observables
-
bool converged = false
forwarded from error_pattern
-
std::vector<uint8_t> bits
-
struct error_pattern
Predicted error vector from a decoder.
Public Members
-
std::optional<cudaqx::heterogeneous_map> opt_results
Plugin-specific diagnostics, to be forwarded from decoder_result.
-
std::optional<cudaqx::heterogeneous_map> opt_results
-
detection_events cudaq::qec::apply_d_sparse(const measurement_results &m, const std::vector<std::vector<uint32_t>> &d_sparse)
Dets: aggregate measurements into detection events via D_sparse (XOR). d_sparse[i] lists the measurement indices that XOR to form detector i.
-
logical_outcome cudaq::qec::apply_o_sparse(const error_pattern &e, const std::vector<std::vector<uint32_t>> &o_sparse)
Obs_flips: project an error pattern onto observable flips via O_sparse. o_sparse[i] lists the fault-column indices whose flip toggles observable i. Assumes the error pattern is in decode_to_errs form (result per fault column).
-
logical_outcome cudaq::qec::xor_logical(const logical_outcome &a, const logical_outcome &b)
GF(2) XOR of two logical outcomes (L_raw ⊕ L_flip → L_obs).
Graph
-
struct task_graph_edge
A directed edge of a task graph, as data: node ids and port names.
Two endpoints are implicit rather than nodes:
measurementsas the source of the raw shot, andoutputas the sink. Port names default so the common case stays terse; a node declaring several ports (anxornode’saandb) names them.Public Members
-
std::string from_node
node id, or “measurements”
-
std::string from_output = "output"
named output on from_node
-
std::string to_node
node id, or “output”
-
std::string to_input = "input"
named input on to_node
-
std::int64_t index_offset = 0
Consumer instance k reads producer instance k + index_offset, between nodes that join their inputs by index. Zero or negative.
-
std::string from_node
-
struct task_graph_node_config
Build inputs for one node of a task graph.
kindis a registered node-kind name rather than an enumerator, and kind-specific settings ride innode_params, so a new kind never edits this struct. registered_task_graph_node_kinds() lists what is available.Move-only: it may carry an already-built decoder.
Public Members
-
std::string kind = default_task_graph_node_kind
Registered node kind, e.g. “streaming”, “sliding_window”, “single_window”, “xor”.
-
cudaqx::heterogeneous_map node_params
The kind’s own parameters: window_size, step_size, guards, …
-
std::size_t max_in_flight = 1
Copies of this node that may fire at once in asynchronous streaming, each on its own record. Above one, the kind must keep no state across deliveries (
task_graph_node::supports_fire_pool) and build its inner decoder fromdecoder_type, since every copy needs one.
-
std::optional<dem_chunks_spec> dem
DEM for this node. When absent,
d_sparse/o_sparsebelow supply the matrices directly.
-
std::vector<experimental::ingest_window> windows
The layers of a kind that takes windows: each names an output port and its window request. Experimental, as the request type is.
-
std::vector<std::vector<uint32_t>> d_sparse
Pre-expanded matrices, used when
demis absent. Rows are CSR:d_sparsemaps measurements to detectors,o_sparsefault columns to observables, andh_sparsedetectors to the fault columns that trigger them.h_sparseis optional and only a kind that maps a predicted error back into detector space needs it; the others are the flat form’s usual pair. Flat matrices still describe one fixed-T window with no per-round column layout, so this does not make the flat form a substitute fordemin a windowed topology.
-
std::string decoder_type
Inner decoder plugin name and its constructor parameters. Ignored by a kind that wraps no decoder.
-
std::string stim_dem
Stim DEM text to build the inner decoder from, instead of this node’s H. For a decoder whose model needs what the text carries and the matrices do not:
detectorcoordinate annotations have no home indetector_error_model, so a decoder that reads them can only be built from the text. The node’s own D/O still come fromdem/d_sparse— the text describes the decoder, the chunks describe the window. Requires an inner decoder that projects to observables itself, since the text’s fault columns are not this node’s.
-
std::unique_ptr<decoder> decoder_instance
Already-built inner decoder, taking precedence over
decoder_type. The flat form needs this: a decoder is built from H and the error rates, neither of which is recoverable from D and O.
-
std::optional<task_graph_ensemble_spec> ensemble
The members and join of a node of kind
ensemble, which from_topology() lowers in place; the fields above are ignored for it.
-
std::string kind = default_task_graph_node_kind
-
struct task_graph_ensemble_spec
The members and join of a node of kind
ensemble(task_graph_node_config::ensemble): member subgraphs run concurrently and one answer is kept. from_topology() lowers the node into anensemble_fanout,ensemble_join, and the members. Every member node input that accepts acandidate_sinkis wired to the ensemble’s candidate sink and every one that accepts acancellation_tokento its cancellation token. A member whose edges reachoutput(alogical_outcome) has that value pushed into the sink.The pattern node has one input,
input, and one output,output. Whatever feedsinput(a shot, or a streaming producer’s windows of measurements or detection events) is passed to every member.Public Members
-
std::string join_strategy
A registered selection strategy (see selection_strategy.h) and its parameters, validated against that strategy’s schema.
-
struct member
-
std::string join_strategy
-
struct candidate
A candidate answer, the id of the node that produced it and, when the producer can rank its own answer, a cost (lower is better).
-
class candidate_sink
Shared candidate queue. Copies share one storage.
push()is thread-safe. It allocates a node, takes a mutex when the candidate may be the cheapest so far, and then runs the observer on the pushing thread.Public Functions
-
inline candidate_sink()
-
inline void push(logical_outcome solution, std::string producer_id = {}, std::optional<double> cost = std::nullopt) const
Queue a candidate and show it to the round’s observer. A costed candidate becomes the best so far only when strictly cheaper, so ties keep the earlier one; uncosted candidates never do.
-
inline candidate_sink()
-
class selection_strategy
One instance serves one run: the fan-out builds a new one from the registered factory each time it arms a run, so overlapping runs never share a strategy.
begin()is called once, when the run is armed, and takes the cancellation source and candidate sink by reference, so that the strategy can request stops and poll candidates. On the pushing member’s thread and possibly concurrently,offer()is called for every push, where a value commits the run to it and hard-stops the other members; a strategy commits at most once per run and ignores every candidate after that.finish()once every member has finished and nothing committed, where a value commits andstd::nulloptis a miss.Public Functions
-
virtual ~selection_strategy() = default
-
inline virtual void begin(cancellation_source, candidate_sink)
-
virtual std::optional<logical_outcome> offer(const candidate &c) = 0
-
inline virtual std::optional<logical_outcome> finish()
-
virtual ~selection_strategy() = default
-
using cudaq::qec::selection_strategy_factory = std::function<std::unique_ptr<selection_strategy>(const cudaqx::heterogeneous_map&)>
-
class selection_strategy_registration
One registration, released when destroyed: the factory is removed if it is still the current one under its name, so a module that holds this at namespace scope unregisters its strategy before its code is unloaded. The parameter schema stays, as every registered schema does.
-
selection_strategy_registration cudaq::qec::register_selection_strategy(std::string name, decoding::config::decoder_schema params, selection_strategy_factory factory)
Register (or replace) the strategy
name: its parameter schema, registered underselection_strategy_schema_name(name), and the factory that builds it from parameters validated against that schema.
-
std::vector<std::string> cudaq::qec::registered_selection_strategies()
Names of the registered strategies, sorted.
-
constexpr const char *cudaq::qec::default_task_graph_node_kind = "sliding_window"
The kind a node gets when its
typenames a decoder plugin instead of a kind, because such a node is a window over that decoder. Also the default for task_graph_node_config::kind, so the two cannot disagree.
-
std::vector<std::string> cudaq::qec::registered_task_graph_node_kinds()
Canonical names of all registered kinds, for diagnostics and schema export.
-
class edge_value_type
Identity of an edge-value type: the C++ payload type. Callers obtain one from a type via of<T>() or from a registered name; several names may refer to one type, and ports declared through any of them wire together.
Public Functions
-
explicit edge_value_type(std::string_view name)
The type registered under
name. Throws std::invalid_argument when no such name is registered.
Public Static Functions
-
template<typename T>
static inline constexpr edge_value_type of() The identity of payload type
T.
-
explicit edge_value_type(std::string_view name)
-
std::vector<edge_value_type> cudaq::qec::registered_edge_value_types()
Ids of all registered edge-value types, for diagnostics.
-
enum class cudaq::qec::task_graph_streaming_status
Operational state of a streaming graph or one of its named outputs.
Values:
-
enumerator pending
-
enumerator available
-
enumerator complete
-
enumerator failed
-
enumerator pending
-
enum class cudaq::qec::task_graph_closure
Whether a shot’s window solutions were checked against their detectors and held: not_checked unless every window reaching the output checks its solution (verify_residual); else closed when every solution satisfied its window, and open when one did not.
Values:
-
enumerator not_checked
-
enumerator closed
-
enumerator open
-
enumerator not_checked
-
struct task_graph_output_progress
Progress of one named graph output.
generationis a monotonic publication watermark. It advances when every contributor to this output has published its next update. When every contributor reports the rounds it has committed, it advances instead whenever the output’s coverage grows. Consuming corrections preserves this watermark but changesstatustopending; generation alone never implies that a value is currently readable.Public Members
-
task_graph_closure closure = task_graph_closure::not_checked
The shot’s closure over the windows that reach this output, so far.
-
std::vector<std::uint8_t> released
Logical output only: 1 per bit once that logical measurement is final (its readout has arrived and every correction that can flip it is committed). Empty for a correction output.
-
task_graph_closure closure = task_graph_closure::not_checked
-
struct task_graph_streaming_result
Graph-owned streaming result.
valuescontains all named outputs at their declared offsets. Synchronous graphs return a live graph-owned view that must not be read concurrently with graph activity. Async-streaming graphs return a stable reader snapshot after synchronizing the accepted prefix. Copy either form to retain a historical result across later graph calls.operation_completedis an edge-triggered indication that the latest synchronized public enqueue advanced the aggregate barrier; level-triggered readability is determined bystatus: onlyavailableorcompleteis readable (and either necessarily has a nonzero generation). Consuming corrections changes status topendingbut deliberately preserves generation as a monotonic publication watermark for detecting the next update. Generation alone must therefore never be used as a readiness test.result_revisionadvances whenever any output or graph status changes.completed_operationscounts public enqueue operations that advanced the aggregate result, even when several complete before the next read. An asynchronous graph counts them as a synchronous one would. Only reset_decoder() advances shot_epoch.A logical output, when present, comes last in
values; the aggregate generation, status and closure cover the correction outputs only.Public Functions
-
const uint8_t *logical_measurements(std::size_t first, std::size_t count) const
Logical measurements [
first,first+count) of the logical output, the last, or null unless every one is released. Null too without a logical output, or for an empty range or one past it. Every logical read applies this one release check.
Public Members
-
std::uint64_t completed_operations = 0
Aggregate-completing public enqueue operations in this shot epoch.
-
task_graph_closure closure = task_graph_closure::not_checked
The outputs’ closures combined: closed only when every output’s is.
-
const uint8_t *logical_measurements(std::size_t first, std::size_t count) const
-
struct task_graph_options
Construction-time execution policy for a decoding task graph.
Public Members
-
bool async_streaming = false
Process streaming records on the graph’s persistent coordinator thread. Records then overlap: a later record runs ahead on nodes that finished the earlier ones, up to 16 records in flight, or the queue’s capacity if smaller.
-
std::size_t async_queue_capacity = 32
Maximum public enqueue operations queued or executing: how far the producer may run ahead of the graph. Must be nonzero when asynchronous. A windowed graph admits queued rounds together, so a deeper queue lets it catch up in larger batches, but a graph that falls behind returns FINAL’s result only after draining it. 32 keeps that backlog to tens of microseconds while still batching; each slot holds one enqueue.
-
int async_coordinator_cpu = -1
CPU reserved for the asynchronous coordinator, or -1 to inherit the constructing thread’s affinity. This pins only the coordinator; decoder pool workers retain their separately configured affinity.
-
std::size_t async_spin_pause_iters = 0
Pause iterations before an active coordinator parks for more input. Zero disables spinning.
-
std::optional<std::size_t> async_num_workers
Pool threads that run node fires in an asynchronous graph, not counting the coordinator. Unset sizes the pool from the graph: its parallel width, including every fire pool’s copies, or, with an indexed node, every copy that may fire at once (an indexed node’s single copy too) plus the worker its fires leave free, capped by hardware concurrency. Must be at least one when set. Synchronous graphs ignore it.
-
std::vector<int> async_worker_cpus
CPUs those threads are pinned to, round-robin (Linux only). Empty inherits the process’s affinity. A CPU listed twice or shared with
async_coordinator_cpuis an error; one shared with another decoder’s asynchronous graph is a warning. Synchronous graphs ignore it.
-
bool async_streaming = false
-
class decoding_task_graph
Decode pipeline as a composable, testable object.
Owns one or more decoder plugins and the D/O matrices that connect raw measurement bits to detector events and observables.
Streaming interface:
enqueue_syndromesupplies raw measurement chunks to streaming-capable source nodes. Window nodes accumulate them; native-streaming nodes forward each public call to their inner decoder. Published node outputs then flow through the streaming DAG.
One-shot execution:
run()walks the internal node/edge DAG for one full shot.
Asynchronous execution:
run_async()returns one future for the shot. Independent ready nodes in a multi-node DAG may execute concurrently.
Batch execution:
run_batch()walks the graph once for each supplied shot.
The decoders are stateful: do not call into the same graph from two threads, collect one
run_asyncbefore starting the next, and do not overlap streaming with one-shot calls. Overlap is detected rather than serialised — an overlapping call throwsstd::logic_error. An async-streaming graph instead has one internal coordinator that dispatches records to pool workers; its public streaming calls provide copied input and coherent snapshots. Records overlap, a bounded number at once, but each node still sees them in order and every value a record moves between nodes is buffered per record.Public Functions
-
decoding_task_graph(std::unique_ptr<decoder> dec, std::vector<std::vector<uint32_t>> d_sparse, std::vector<std::vector<uint32_t>> o_sparse, task_graph_options options = {})
Construct from an already-built decoder and D/O in nested-row form.
Uses a fixed-T window: the full D matrix is applied once per decode, and the accumulation buffer is exactly
d_sparsecolumn-width bytes.- Parameters:
dec – Inner decoder plugin.
d_sparse – Measurement-to-detector map (CSR row form).
o_sparse – Observable-flip map (CSR row form).
options – Construction-time execution policy.
-
bool enqueue_syndrome(const uint8_t *syndrome, std::size_t len)
Accumulate one round of measurement syndromes.
Returns true when any window fired (D → decode → O). For independently progressing outputs this does not mean that an aggregate result is ready; inspect streaming_result() for output and operation status. For fixed-T, a window fires once when its full buffer is filled. For sliding-window, it fires every
striderounds once the buffer is full.Any chunking works: the graph meters a chunk to each node’s remaining room, so one call may drive several fires.
get_num_msyn_per_round()is the chunk to prefer, not a limit. Unlikedecoder::enqueue_syndrome, which still ignores a chunk that does not fit, nothing is dropped here.With construction-time asynchronous streaming enabled, a BULK call returns false after copying its input into the bounded queue; call streaming_result() to wait for accepted input and inspect completion. If the queue is full, this call waits only until one slot is available. A FINAL call waits for all accepted input and the final flush before returning.
- Throws:
std::logic_error – if the graph’s streaming routes or effective output schedules are incompatible. Batch execution remains valid.
-
bool enqueue_syndrome(const uint8_t *syndrome, std::size_t len, round_type type)
Same, carrying the round’s shape. A
FINALround commits whatever a guarded window is still withholding, so the tail of a shot is not lost. Returns true if a window fired or a tail was committed.FINALends the shot: further rounds are warned about and dropped until clear_corrections() or reset_decoder(), because the rounds it committed are the ones the next window’s core would commit and corrections accumulate by XOR.- Throws:
std::invalid_argument – if a
FINALround is empty: it carries the shot’s final measurements.
-
const uint8_t *get_obs_corrections() const
Host-accessible corrections buffer (num_observables bytes).
During synchronous streaming, this is a current-value read between calls to
enqueue_syndrome(): an output appears as soon as its node fires, and one whose node has not fired yet reads as zero — indistinguishable from a genuine zero. For an async-streaming graph it waits for records accepted before the call, then returns a coherent coordinator snapshot without closing the session or flushing it. It never aliases state the coordinator mutates. Its pointer remains valid only until the next result accessor or mutating graph call; copy the bytes if they must outlive either.- Throws:
std::logic_error – If streaming is unsupported or, for a synchronous graph, another graph operation is in flight.
-
const uint8_t *get_logical_measurements() const
Host-accessible logical measurements buffer (get_num_logical_measurements() bytes): the raw logical readout with the corrections applied, from the graph’s logical output. Null until all are released (by FINAL at the latest) and after the shot is consumed; otherwise as get_obs_corrections().
- Throws:
std::logic_error – If the graph has no logical output, streaming is unsupported or, for a synchronous graph, another graph operation is in flight.
-
const uint8_t *get_logical_measurements(std::size_t first, std::size_t count) const
Logical measurements [
first,first+count), or null until all of them are released.- Throws:
std::out_of_range – If the range is empty or runs past get_num_logical_measurements(); otherwise as get_logical_measurements().
-
const task_graph_streaming_result &streaming_result() const
Return values and per-output publication state from the latest streaming operation. A zero-valued output is distinguishable from an unavailable one through its status and generation. Coverage is the half-open round range incorporated by the latest generation. The returned reference is a live view for synchronous graphs. For async-streaming graphs, each call waits for records accepted before the call, then refreshes a stable reader-owned snapshot; copy it before another result accessor call if a historical snapshot is required.
- Throws:
std::logic_error – If streaming is unsupported or, for a synchronous graph, another graph operation is in flight.
-
void clear_corrections()
Consume the current corrections without starting a new result epoch.
This zeroes values and marks aggregate and output statuses
pending, but preserves sliding-window overlap, coverage, and generation watermarks so streaming can continue and the next publication can be detected. Use reset_decoder() instead to start a clean shot epoch. For an asynchronous graph, this first drains all accepted records without flushing guarded tails.- Throws:
std::logic_error – If another graph operation is in flight, or the graph has a logical output and its shot has not ended.
std::runtime_error – If asynchronous processing failed.
-
void reset_decoder()
Reset all per-shot state (accumulation buffer, corrections) on every node. For an asynchronous graph, this first cancels queued records and waits for any currently executing decoder call to return.
- Throws:
std::logic_error – If another graph operation is in flight.
-
std::size_t get_num_msyn_per_decode() const
Total syndrome bytes per full window (= buffer capacity). This is what the first decode of a shot consumes; a slid window then fires every
striderounds. Nodes reading the stream may hold windows of different sizes, in which case this is the largest, i.e. the bytes needed before every one of them has fired.
-
std::size_t get_num_msyn_per_round() const
Common syndrome-byte unit used by the graph’s streaming schedules. This is the preferred chunk size, not an enqueue limit; for variable-width native rounds it may be a common divisor of caller-visible round sizes. A window that does not slide also accepts
get_num_msyn_per_decode()per call.
-
std::size_t get_num_observables() const
Number of observables (= corrections buffer length), excluding the logical output.
-
std::size_t get_num_logical_measurements() const
Number of logical measurements; 0 without a logical output.
-
bool supports_streaming() const noexcept
Whether the compiled graph supports incremental streaming execution. A false result does not affect run(), run_all(), or other batch APIs.
-
std::size_t async_thread_count() const noexcept
Threads an asynchronous graph owns: its coordinator and the pool workers that run fires. Zero for a synchronous graph.
-
const std::string &streaming_incompatibility_reason() const noexcept
Empty when supports_streaming() is true; otherwise the first deterministic build-time reason streaming execution is unavailable.
-
const std::vector<std::string> &output_names() const
Which bits are which: one name per output, in the order get_obs_corrections() concatenates them and run_all() returns them. Each is the sink edge’s
to_input, or its producer’s name when left at the default. Excludes the logical output. Fixed at build.
-
logical_outcome run(const measurement_results &m) const
Walk the node/edge DAG for one shot: detect(m) then execute each node.
Does not touch the streaming accumulation buffer, except in a graph whose nodes decode only a stream, such as a windowed one: that graph runs the shot through its stream, from a reset graph, in rounds with FINAL on the last, and leaves it reset.
convergedis then whether every window reaching the output converged.- Throws:
std::logic_error – if such a graph holds a shot in progress, or a completed shot not yet consumed with clear_corrections(): run() would discard it.
std::logic_error – if more than one edge reaches
output: a multi-output program reduced to its first output is a different program, so it is refused rather than answered. Use run_all(). The logical output is not counted.
-
std::vector<logical_outcome> run_all(const measurement_results &m) const
run() for any number of outputs: one outcome per correction output, in output_names() order.
-
std::future<logical_outcome> run_async(const measurement_results &m) const
Run one full shot asynchronously.
The shot is copied before this function returns, so
mneed not outlive the call. Single-node graphs apply D synchronously and use the decoder’s own async path. Multi-node graphs execute dependency-ready nodes concurrently on a bounded persistent worker pool. Each node owns its decoder instance, so independent instances may decode concurrently. The graph’s single-flight contract prevents concurrent entry into the same node instance.- Parameters:
m – Raw measurement bits for one complete shot.
- Throws:
std::logic_error – If another graph operation is already in flight or the graph does not have exactly one output.
std::runtime_error – If graph nodes request different CUDA devices. Node execution failures are stored in the returned future and rethrown by
std::future::get().
- Returns:
A future containing the graph’s single logical outcome.
-
std::vector<logical_outcome> run_batch(const std::vector<measurement_results> &shots) const
Multi-record version: run() for each element in order.
-
const sparse_binary_matrix &d_matrix() const
Measurement-to-detector matrix (CSR). Rows = detectors, cols = measurements.
-
const sparse_binary_matrix &o_matrix() const
Observable-flip matrix (CSR). Rows = observables, cols = fault columns. Throws for combined graphs (no single O matrix).
-
std::optional<int> cuda_device_id() const
The CUDA device every GPU-affine node agrees on, or nullopt if none has GPU affinity. A caller must pin to this device before a node’s decoder runs CUDA kernels of its own, same as detail_affinity::pin_decode_device already requires for a plain decoder.
- Throws:
std::runtime_error – if GPU-affine nodes disagree on device — one thread can’t pin to two devices for one shot. Pin every GPU-affine node in a graph to the same cuda_device_id.
-
bool supports_graph_dispatch() const
True if this graph’s one streaming node supports graph dispatch. Always false for a multi-node (combine()) graph.
-
void *capture_graph(int reserved_sms = 0)
Capture the graph’s single streaming node’s full decode pipeline (D-apply -> decode -> O-apply) into a CUDA graph. Same void* convention as decoder::capture_decode_graph() (avoids <cuda_runtime.h> here); caller casts to cudaq::qec::realtime::graph_resources* and owns it.
- Throws:
std::logic_error – if called on a multi-node graph, or a single-node graph whose node does not supports_graph_dispatch() — callers are expected to check supports_graph_dispatch() first, so this is a misuse guard, not the primary gate.
-
void release_graph(void *graph_resources)
Release graph resources previously returned by capture_graph().
-
decoder *inner_decoder() const
This graph’s inner decoder, when it has exactly one streaming node that wraps one; nullptr for a multi-node graph or a node kind that wraps no decoder. Exposed for the realtime session to assign the decoder_id DEVICE-mode capture needs (see capture_graph()).
Public Static Functions
-
static std::unique_ptr<decoding_task_graph> from_spec(const dem_chunks_spec &spec, const std::string &decoder_type, const cudaqx::heterogeneous_map ¶ms = {}, task_graph_options options = {})
Build from a
dem_chunks_specand a named decoder plugin.When
spec.num_roundsis set, builds a fixed-T window. When absent (streaming), builds a sliding window (stride = 1) sized to the minimum rounds required by the spec’s phase structure.- Parameters:
spec – Phase/connection spec describing the DEM structure.
decoder_type – Registry name of the inner decoder.
params – Additional constructor parameters for the decoder.
options – Construction-time execution policy.
-
static std::unique_ptr<decoding_task_graph> from_topology(std::vector<task_graph_node_config> nodes, std::vector<task_graph_edge> edges = {}, task_graph_options options = {})
Build an arbitrary topology: nodes of any registered kind, wired by explicit edges.
Each node’s D and O come from its own
dem(expanded to the round count itswindow_sizeasks for) or from its flatd_sparse/o_sparse.edgesmay be omitted for a single-node graph, which is wiredmeasurements -> node -> output. Nodes must be given in topological order; an edge that runs backwards is rejected. Each node’s registered parameter schema is applied here, including default materialization, so YAML and programmatic construction have the same parameter contract.optionsselects the graph’s streaming execution policy.- Throws:
std::invalid_argument – for an unregistered kind, a node missing what its kind requires, a dangling edge endpoint, an unknown port name, a reserved node id, an unconnected or multiply connected input, incompatible port value types, an unsupported graph output, or incompatible statically known edge-value shapes.
std::runtime_error – for an unknown, incorrectly typed, missing, or cross-field-invalid node parameter.
-
static std::unique_ptr<decoding_task_graph> combine(std::unique_ptr<decoding_task_graph> left, std::unique_ptr<decoding_task_graph> right, task_graph_options options = {})
Combine two single-node graphs into a three-node DAG that XORs their logical outcomes. Both input graphs are consumed.
Streaming: both branches must have the same effective firing and commit schedule. An incompatibility is recorded on the combined graph: its complete one-shot and batch DAG remains usable, while
enqueue_syndrome()throwsstd::logic_error.- Throws:
std::invalid_argument – if either graph is null, is not a single-node graph, or produces a different observable width.
Built-in Decoders
NVIDIA QLDPC Decoder
- class nv_qldpc_decoder
The
nv-qldpc-decoderplugin provides GPU-accelerated decoders for quantum low-density parity-check (QLDPC) codes. Every configuration runs belief propagation (BP) on the GPU. The options select how the BP output is used:as a hard decision (BP or Relay-BP);
as a calibrated error probability for each error mechanism, computed with a Trajectory-Calibrated BP (TCBP) model;
as the column ordering for an ordered-statistics decoding (OSD) post-processor: OSD-0, exhaustive search, combination sweep or Jittered OSD Beam Search (JOBS).
The
cudaq_qec.plugins.nv_qldpcmodule provides named presets for common configurations. See “Presets” below.An [[n,k,d]] quantum error correction (QEC) code encodes k logical qubits into an n qubit data block, with a code distance d. Quantum low-density parity-check (QLDPC) codes are characterized by sparse parity-check matrices (or Tanner graphs), corresponding to a bounded number of parity checks per data qubit.
Requires a CUDA-Q compatible GPU. See the CUDA-Q GPU Compatibility List for a list of valid GPU configurations.
References:
Note
It is required to create decoders with the
get_decoderAPI from the CUDA-Q QEC extension points API, such asimport cudaq_qec as qec import numpy as np H = np.array([[1, 0, 0, 1, 0, 1, 1], [0, 1, 0, 1, 1, 0, 1], [0, 0, 1, 0, 1, 1, 1]], dtype=np.uint8) # sample 3x7 PCM O = np.array([[1, 1, 1, 0, 0, 0, 0]], dtype=np.uint8) opts = dict() # see below for options # H may also be a scipy.sparse matrix (CSR, CSC, COO, or any # other scipy.sparse format), which avoids a full dense rows×cols # allocation for large PCMs. Any format is normalised to CSR # internally; no call to .toarray() or .todense() is needed. nvdec = qec.get_decoder('nv-qldpc-decoder', H, O=O, output='observables', **opts)
std::size_t block_size = 7; std::size_t syndrome_size = 3; cudaqx::tensor<uint8_t> H, O; std::vector<uint8_t> H_vec = {1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1}; H.copy(H_vec.data(), {syndrome_size, block_size}); std::vector<uint8_t> O_vec = {1, 1, 1, 0, 0, 0, 0}; O.copy(O_vec.data(), {1, block_size}); cudaqx::heterogeneous_map nv_custom_args; nv_custom_args.insert("use_osd", true); // See below for options std::vector<double> error_rates(block_size, 0.001); cudaq::qec::decoder_init inputs( cudaq::qec::sparse_binary_matrix(H), cudaq::qec::sparse_binary_matrix(O), error_rates); auto nvdec = cudaq::qec::get_decoder( "nv-qldpc-decoder", std::move(inputs), cudaq::qec::decode_result_type::observables, nv_custom_args);
Note
The
"nv-qldpc-decoder"implements thecudaq_qec.Decoderinterface for Python and thecudaq::qec::decoderinterface for C++, so it supports all the methods in those respective classes.- Parameters:
H – Parity-check matrix with shape
(syndrome_size, block_size).O – Optional observable matrix with shape
(num_observables, block_size). It is model data and does not select the result basis. Python accepts it as a keyword adapter; C++ supplies it throughcudaq::qec::decoder_init.output – Result basis,
"errors"or"observables"in Python andcudaq::qec::decode_result_typein C++. When omitted, the decoder returns error frames even ifOis present.error_rate_vec – Optional probability per error mechanism, with length
block_size. Python accepts it as a keyword adapter; C++ supplies it throughcudaq::qec::decoder_init. It overrides the scalarerror_rateparameter.
Decoder pipeline
The decoder runs BP first. The BP result is either returned directly or used to order the columns of the parity-check matrix for an OSD post-processor. When a TCBP model is supplied, the decoder computes a calibrated error probability for each mechanism from the BP LLR history. These probabilities are either returned as the result (
use_osd=false) or used as the OSD column ordering (osd_init_method="tcbp").
The following table lists the supported configurations, the presets that select them and the options that distinguish them.
Configuration
Presets
Options
BP hard decision
bp60,relay-bpuse_osd=false(relay-bp:composition=1)TCBP error probabilities
tcbptcbp_model,use_osd=falseFinal-LLR ordering with OSD-0 or combination sweep
bp60-osd0,bp60-osd-cs1000use_osd=true,osd_method1 or 3Minimum-LLR ordering with OSD-0, combination sweep or JOBS
bp10-minllr-osd0,bp10-minllr-osd-cs1000,bp10-minllr-jobsosd_init_method="min_llr",osd_method1, 3 or 4TCBP ordering with combination sweep or JOBS
tcbp-osd-cs1000,tcbp-jobs,tcbp-jobs-sc,tcbp-jobs-sc-gaptcbp_model,osd_init_method="tcbp",osd_method3 or 4- Parameters:
params – Heterogeneous map of decoder options. The options are grouped below by pipeline stage. Every option is optional unless its description says otherwise.
Device and execution
Options that select the device, the floating-point precision, the batch sizes and repeatability.
cuda_device_id(int): Zero-based CUDA device ordinal on which to construct the decoder and run every decode. Must be>= 0and less than the number of visible GPUs. When omitted, the decoder is not pinned to a specific device and runs on the default device (GPU 0). Introduced in 0.7.0.use_sparsity(bool): Whether or not to use a sparse matrix solvern_threads(int): Number of CUDA threads to use for the GPU decoder (defaults to smart selection based on parity matrix size)proc_float(string): The processing float type to use. Defaults to “fp64”. Valid values are “fp32” and “fp64”. Introduced in 0.5.0.repeatable(bool): Whether to make the BP algorithm (and Relay BP algorithm if enabled) bit-for-bit repeatable. Defaults to False. You must setclip_valueto a non-zero value to use this option. Setting this option to True makes it run approximately 5-10% slower, but you are guaranteed to get repeatable results, which is often useful for both timing and detailed syndrome analysis. Introduced in 0.6.0.bp_seed(int): Seed for random number generation used inbp_method=3orbp_method=5(disordered memory BP), or incomposition=1(sequential relay). Optional parameter, defaults to 42 if not provided. Introduced in 0.5.0.bp_batch_size(int): Number of syndromes that will be decoded in parallel for the BP decoder (defaults to 1)osd_batch_size(int): Number of syndromes that will be decoded in parallel by the host OSD (defaults to the number of concurrent threads supported by the hardware). Not applicable withosd_method=4, which searches the wholebp_batch_sizechunk on the device; setting both is an error.
Belief propagation
Options for the BP stage, which runs in every configuration.
bp_methodvalues 2 through 5 requireuse_sparsity=true.scale_factorapplies only to the min-sum methods.error_rate(double): Probability of an error (in 0-1 range) on a block data bit (defaults to 0.001)max_iterations(int): Maximum number of BP iterations to perform (defaults to 30)iter_per_check(int): Number of iterations between BP convergence checks (defaults to 1, and max ismax_iterations). Introduced in 0.4.0.clip_value(float): Value to clip the BP messages to. Should be a non-negative value (defaults to 0.0, which disables clipping). Introduced in 0.4.0.bp_method(int): Core BP algorithm to use (defaults to 0). Introduced in 0.4.0, expanded in 0.5.0 and 0.7.0:0: sum-product
1: min-sum (introduced in 0.4.0)
2: min-sum+mem (uniform memory strength, requires
use_sparsity=True. Introduced in 0.5.0)3: min-sum+dmem (disordered memory strength, requires
use_sparsity=True. Introduced in 0.5.0)4: sum-product+mem (uniform memory strength, requires
use_sparsity=True. Introduced in 0.7.0)5: sum-product+dmem (disordered memory strength, requires
use_sparsity=True. Introduced in 0.7.0)
scale_factor(float): The scale factor to use for min-sum. Defaults to 1.0. When set to 0.0, the scale factor is dynamically computed based on the number of iterations. Introduced in 0.4.0.
Memory BP and Relay-BP
Options for BP with memory (
bp_methodvalues 2 through 5) and for Relay-BP (composition=1). All of them requireuse_sparsity=true.composition(int): Iteration strategy (defaults to 0). Introduced in 0.5.0:0: Standard (single run)
1: Sequential relay (multiple gamma legs). Requires:
bp_method=3(min-sum+dmem) orbp_method=5(sum-product+dmem),use_sparsity=True, andsrelay_config. Support forbp_method=5was added in 0.7.0.
gamma0(float): Memory strength parameter. Required forbp_method=2(min-sum+mem) andbp_method=4(sum-product+mem), and forcomposition=1(sequential relay). Introduced in 0.5.0; extended in 0.7.0 forbp_method=4.gamma_dist(vector<float>): Gamma distribution interval [min, max] for disordered memory strength. Required forbp_method=3(min-sum+dmem) orbp_method=5(sum-product+dmem) ifexplicit_gammasnot provided. Introduced in 0.5.0; extended in 0.7.0 forbp_method=5.explicit_gammas(vector<vector<float>>): Explicit gamma values for each variable node. Forbp_method=3orbp_method=5withcomposition=0, provide a 2D vector where each row hasblock_sizecolumns. Forcomposition=1(Sequential relay), providenum_setsrows (one per relay leg). Overridesgamma_distif provided. Introduced in 0.5.0; extended in 0.7.0 forbp_method=5.srelay_config(heterogeneous_map): Sequential relay configuration (required forcomposition=1). Contains the following parameters. Introduced in 0.5.0:pre_iter(int): Number of pre-iterations to run before relay legsnum_sets(int): Number of relay sets (legs) to runstopping_criterion(string): When to stop relay legs:“All”: Run all legs
“FirstConv”: Stop relay after first convergence
“NConv”: Stop after N convergences (requires
stop_nconvparameter)
stop_nconv(int): Number of convergences to wait for before stopping (required only whenstopping_criterion="NConv")
Note
Starting in version 0.6.0, convergence during the
pre_iterphase counts as a successful convergence towards the stopping criteria. Prior to 0.6.0, convergence during pre-iterations did not count.gamma_ensemble_size(int): Number of parallel gamma trajectories (“lanes”) run per sequential-relay BP iteration. Allowed values are 1, 2, 4, and 8 (defaults to 1, which disables the ensemble). Each lane explores a distinct gamma set drawn fromgamma_dist(orexplicit_gammas). The constructor requiresnum_sets >= gamma_ensemble_sizeso the N per-lane gamma-set offsets stay pairwise distinct. Introduced in 0.7.0.Design semantics (race-to-fastest): the ensemble is optimized for decode latency. The kernel runs the N lanes in parallel and applies the user-supplied
stopping_criterionacross the ensemble: the first lane to satisfy the criterion stops the others. The winning lane is the converged lane with the lowest-weight correction (sum of error-rate LLRs over bits decoded as 1). If no lane converges across allnum_setslegs the decoder falls back to lane 0’s last-leg marginals. The speedups are maximized for the long-tail (p99) syndromes: easy syndromes converge in the first leg either way, while hard syndromes that would otherwise walk through many sequential legs get them raced in parallel instead.Warm-up (`pre_iter`) semantics: with the ensemble, the search diversity comes entirely from the relay legs, because each lane runs its own sequence of gamma sets. The
pre_iterwarm-up is the opposite: every lane would run it with the same uniformgamma0value, so the kernel computes it once (on one lane) and broadcasts the warmed-up marginals to every lane before the legs start. The warm-up helps convergence by settling the messages before the disordered gammas are applied and by letting easy syndromes converge early (which counts toward the stopping criterion), at the cost of delaying the start of the legs by the warm-up iterations. Ensemble speedups are therefore maximized whenpre_iteris small or zero.The gamma ensemble is supported on the sparse GPU single-decode path with
composition=1andbp_method=3(min-sum + dmem) orbp_method=5(sum-product + dmem). Passinggamma_ensemble_size > 1with any otherbp_methodor with the CPU or dense GPU path raisesstd::invalid_argumentat construction. The batched relay path (decode_batch()) and the realtime / graph-dispatch path (capture_decode_graph()) do not yet support ensembles and raise at call time; support forgamma_ensemble_size > 1withcapture_decode_graph()is intended in a future release.
Trajectory-Calibrated BP (TCBP)
TCBP computes, for each error mechanism, a calibrated probability that the mechanism occurred. It uses the marginal LLR of the mechanism at every BP iteration and a TCBP model.
cudaq_qec.plugins.nv_qldpc.init_tcbp_modelfits the model once per code family from the detector error matrix. Noise learning uses the same model. TCBP requiresuse_sparsity=trueandcomposition=0.tcbp_model(bytes or str): TCBP model returned bycudaq_qec.plugins.nv_qldpc.init_tcbp_model, or the path of a file that contains it. Supplying this option enables TCBP. In Python, pass the model as a writable 1-Duint8NumPy array (np.array(bytearray(model), dtype=np.uint8)). In the YAML schema, and therefore for real-time decoding, only the file path is accepted. Thebp_method,max_iterations,clip_valueandproc_floatof the decoder must equal the values the model was fitted with. Ifopt_results.bp_llr_historyis set, it must equalmax_iterations.tcbp_strict(bool): If true, atcbp_modelthat was fitted on a detector error model with a different structure is a construction error. If false (default), the decoder prints a notice once and uses the model, so a model fitted at another physical error rate or code distance of the same code family can be used. Settingtcbp_strictwithouttcbp_modelis a construction error.
The result depends on
use_osd:use_osd=false:decode()anddecode_batch()return the calibrated error probability of each mechanism. For shots on which BP converges, the result is the BP posterior probability andconvergedis true.use_osd=truewithosd_init_method="tcbp": the calibrated probabilities determine the OSD column ordering, and the result is the OSD correction. Supplyingtcbp_modelwithuse_osd=trueand any otherosd_init_methodis a construction error.
import numpy as np import cudaq_qec as qec from cudaq_qec.plugins import nv_qldpc model = nv_qldpc.init_tcbp_model(H) # once per code family; bytes # H may be a dense uint8 array or any scipy sparse matrix (never densified) # optional: fit on the code's nominal error rates instead of the default draw # (the rates must vary across mechanisms; see error_rate_vec below) # model = nv_qldpc.init_tcbp_model(H, error_rate_vec=nominal) tcbp = np.array(bytearray(model), dtype=np.uint8) bp = dict(use_sparsity=True, max_iterations=10, clip_value=15.0, bp_method=0, proc_float="fp32", error_rate_vec=rates) soft = qec.get_decoder("nv-qldpc-decoder", H, tcbp_model=tcbp, use_osd=False, **bp) # P(error) per mechanism hard = qec.get_decoder("nv-qldpc-decoder", H, tcbp_model=tcbp, use_osd=True, osd_init_method="tcbp", **bp)
Fitting a TCBP model. In Python,
cudaq_qec.plugins.nv_qldpc.init_tcbp_model(H, return_report=False, **options)fits a TCBP model on the GPU and returns it asbytes. Withreturn_report=Trueit returns(model, report).His the detector error matrix, with one row per detector and one column per error mechanism, as a 2-Duint8array or ascipy.sparsematrix. The function samples errors fromHat the training rates, runs BP on them and fits the model to the result. It needs no data from a device. Fitting took between 9 and 24 seconds per circuit on one GB200 for the circuits of Accuracy and Latency of TCBP+JOBS.Options of
init_tcbp_model:min_p,max_p(float): Bounds of the training error rates. The function draws one rate for each mechanism, log-uniformly betweenmin_pandmax_p(defaults to 1e-4 and 1e-2). Requires 0 <min_p<max_p< 0.5.error_rate_vec(array of float): One training rate per mechanism, each greater than 0 and less than 0.5, used in place of the drawn rates. The rates must vary across mechanisms: the largest must be at least 1.5 times the smallest, and a uniform vector is rejected. Cannot be combined withmin_pormax_p.seed(int): Seed for the training rates, the sampling and the fit (defaults to 1).shots(int): Number of sampled shots used for the fit. With 0 (default), the function chooses the number so that the shots contain about 5 million sampled errors in total: 5,000,000 divided by the sum of the training rates, which is the expected number of errors per shot. The result is limited to the range from 16,384 to 1,048,576. A further 15% of that number is sampled as held-out shots.steps(int): Number of fitting steps (defaults to 25000).device_memory_budget_bytes(int): Device memory that the fit may use. With 0 (default), the fit may use half of the device memory that is free when the function is called.verbosity(int): With 0 (default), the function prints nothing. With a positive value, it prints the report when the fit ends.bp_method,max_iterations,clip_value,proc_float: BP settings that the model is fitted for (default to 0, 10, 15.0 and “fp32”).bp_methodmust be 0 or 1, andmax_iterationsmust be between 2 and 32. A decoder that uses the model must be constructed with the same values.
The report is a dictionary. Its main entries are:
bce_model,brier_model,ece_model: cross-entropy, Brier score and expected calibration error of the model’s probabilities on held-out shots. Lower is better.bce_baseline,brier_baseline,ece_baseline: the same metrics without the model.prob_regression_flag: true if the model is worse than the baseline on the held-out shots.converged: true if the fit converged.shots_used,holdout_shots,steps_run,seed,wall_s: size, seed and wall time of the fit.budget_bytes,device_highwater_mib: the device memory budget that was applied and the peak device memory that the fit used.
cudaq_qec.plugins.nv_qldpc.inspect(model)returns the report stored in a model, together with the dimensions ofHand fingerprints of its structure and of the training rates. The timing and memory entries are not stored in the model, soinspectreturns them as 0.The following example fits a model, checks the report, saves the model to a file and constructs a decoder from the file:
model, report = nv_qldpc.init_tcbp_model(H, return_report=True) assert not report["prob_regression_flag"] with open("code_family.tcbp", "wb") as f: f.write(model) dec = qec.get_decoder("nv-qldpc-decoder", H, error_rate_vec=rates, **nv_qldpc.preset("tcbp-jobs", tcbp_model="code_family.tcbp"))
Recommendations:
Fit one model per code family with the default options, and reuse it at the other physical error rates and code distances of the family. This is the recommended starting point.
Fit a new model when
bp_method,max_iterations,clip_valueorproc_floatchanges.Check
prob_regression_flagafter every fit.If the error rates of the circuit lie outside the range from
min_ptomax_p, setmin_pandmax_pso that the range covers them.For decoding, any training rates can be used, including rates passed as
error_rate_vec. A model that is passed tolearn_noisemust not be fitted on the rates of the device whose noise is being learned, because the learned rates would then not be an independent estimate.Save the model to a file to reuse it.
To obtain byte-identical models from repeated fits, pass the same
seedand an explicitdevice_memory_budget_bytes.
Column ordering
osd_init_methodselects the values that order the columns of the parity-check matrix for the OSD post-processor. Preset names start with the ordering:bp60-*(final LLR),bp10-minllr-*(minimum LLR) andtcbp-*(TCBP).osd_init_method(string): Which LLRs initialize the OSD column ordering when BP fails to converge (defaults to “final_llr”). Introduced in 0.8.0.“final_llr”: the final-iteration marginal LLRs.
“min_llr”: the per-column minimum marginal LLR over all BP iterations, so columns that were at any iteration confident that an error occurred sort first. Requires
use_osd, the sparse GPU implementation (use_sparsity=true), andcomposition=0.“tcbp”: the TCBP error probabilities. Requires
tcbp_model, in addition to the requirements of “min_llr”.
OSD post-processing: OSD-0, exhaustive and combination sweep
Options for the OSD post-processor, which runs on the shots for which BP does not converge.
osd_methodselects OSD-0, exhaustive search, combination sweep or JOBS. The options specific to JOBS are listed in the next section.use_osd(bool): Whether or not to use an OSD post processor if the initial BP algorithm fails to converge on a solutionosd_method(int): 1=OSD-0, 2=Exhaustive, 3=Combination Sweep, 4=JOBS (defaults to 1). Ignored unlessuse_osdis true. JOBS (Jittered OSD Beam Search) is described in the next section and was introduced in 0.9.0.osd_order(int): OSD postprocessor order (defaults to 0). Ref: Decoding Across the Quantum LDPC Code LandscapeFor
osd_method=2(Exhaustive), the number of possible permutations searched after OSD-0 grows by 2^osd_order.For
osd_method=3(Combination Sweep), this is the λ parameter. All weight 1 permutations and the first λ bits worth of weight 2 permutations are searched after OSD-0. This is (syndrome_length - block_size + λ * (λ - 1) / 2) additional permutations.For other
osd_methodvalues, this is ignored.
osd_sparsify(bool): Run OSD on a prefix of the ordered columns instead of all of them (defaults to false). The prefix is sized from K*, the smallest number of leading columns (in theosd_init_methodordering) whose span contains the syndrome; the OSD solution and the higher-order sweep then only involve those columns, which makes OSD much faster when K* is small compared to the number of columns. Requiresuse_osd.osd_sparsify_pad(float >= 1): Withosd_sparsify, OSD uses the first ceil(osd_sparsify_pad* K*) columns, clamped to the number of columns (defaults to 8.0). Mutually exclusive withosd_sparsify_exact. Except withosd_method=4, settingosd_sparsify_padorosd_sparsify_exactwithoutosd_sparsify=trueis a construction error.osd_sparsify_exact(int >= 1): Withosd_sparsify, OSD uses exactly this many leading columns, which bounds the per-shot OSD work. A shot whose K* exceeds it cannot be solved inside the window: it receives an all-zero correction and a warning is printed (one perdecode(), one with the number of affected shots perdecode_batch()). Nothing in the result marks such a shot; to find them, requestopt_results.kstarand look forkstar > osd_sparsify_exact.
OSD post-processing: JOBS
JOBS (Jittered OSD Beam Search,
osd_method=4) is an OSD post-processor that runs on the GPU. For each shot, it searchesjobs_drawscolumn orderings and returns the lowest-cost correction that it finds. The cost of a correction is the sum of the prior log-likelihood ratios of its error mechanisms. The options in this section requireuse_osd=trueandosd_method=4. Setting any of them otherwise is a construction error. For measured accuracy and latency, see Accuracy and Latency of TCBP+JOBS.jobs_draws(int >= 1): Number of column orderings (“draws”) searched per round for each shot (defaults to 16). Introduced in 0.9.0.jobs_rounds(int >= 1): Maximum number of rounds ofjobs_drawsdraws per shot (defaults to 1). The search of a shot stops after the first round that does not lower its cost. Introduced in 0.9.0.jobs_beam_width(int, 1..64): Number of states the beam search keeps per step (defaults to 32). Introduced in 0.9.0.jobs_beam_depth(int >= 0): Maximum number of beam search steps (defaults to 40). With 0, no beam search runs and each draw returns its OSD-0 solution. Introduced in 0.9.0.jobs_beam_patience(int >= 1): Number of consecutive beam search steps without improvement after which the search of a draw stops (defaults to 8). Introduced in 0.9.0.jobs_draw_noise(float > 0): Scale of the Gumbel noise added to the ordering scores of every draw except draw 0 (defaults to 1.0). Introduced in 0.9.0.jobs_search_converged(bool): If true, JOBS also searches the shots for which BP converged and returns the lower-cost of the BP correction and the JOBS correction (defaults to false).convergedstill reports whether BP converged. Withosd_init_method="final_llr",opt_results.bp_llr_history, if set, must equalmax_iterations. Introduced in 0.9.0.
The search has the following steps:
Draw 0 uses the
osd_init_methodordering. Every other draw adds Gumbel noise, scaled byjobs_draw_noise, to the ordering scores and sorts the columns again.Each draw computes an OSD-0 solution on the first W columns of its own ordering, where W = ceil(
osd_sparsify_padx K*). K* is the smallest number of leading columns of draw 0 whose span contains the syndrome, so every draw of a shot uses the same W.A beam search starts from each OSD-0 solution and looks for lower-cost corrections that satisfy the syndrome. It keeps
jobs_beam_widthstates per step. It stops afterjobs_beam_depthsteps, or afterjobs_beam_patiencesteps without improvement.If
jobs_roundsis greater than 1, further rounds of draws run while a round lowers the cost of the shot.
By default, JOBS runs only on the shots for which BP does not converge. Set
jobs_search_convergedto search every shot.Requirements and limits:
JOBS requires
use_osd=true,use_sparsity=trueandcomposition=0.Every error rate must be at most 0.5. A larger rate is a construction error.
Starting in 0.9.1,
Hcan have more than 8192 detectors (rows). The maximum detector count is limited by the memory of the GPU. A model that is too large for the device is a construction error.jobs_beam_widthcan be at most 64. A larger value is a construction error that reports the value.JOBS always restricts the search to the K* window, so
osd_sparsifyis not needed.osd_orderis ignored. Settingosd_sparsify=false,osd_batch_sizeorosd_sparsify_exactis a construction error.
Device memory: the decoder allocates all device memory for the search at construction, sized for
bp_batch_sizexjobs_drawsconcurrent searches. If the free device memory is insufficient, the decoder reduces the number of concurrent searches at the largest window sizes and prints a warning. Results are unchanged, and throughput can be lower. Construction fails only if the minimum configuration does not fit. The error message reports the number of bytes required.Repeatability: the noise is seeded from the syndrome, so
decode()anddecode_batch()search the same draws, and repeated calls return identical results.opt_results.kstarreports K* of draw 0.The following example constructs a JOBS decoder with the default search options:
dec = qec.get_decoder("nv-qldpc-decoder", H, error_rate_vec=rates, use_sparsity=True, max_iterations=10, clip_value=15.0, use_osd=True, osd_method=4, osd_init_method="min_llr", bp_batch_size=2048) # defaults: jobs_draws=16, jobs_beam_width=32, jobs_beam_depth=40, # jobs_beam_patience=8, jobs_draw_noise=1.0, osd_sparsify_pad=8
JOBS gap. With
opt_results.jobs_gap, the decoder returns two additional values per shot:jobs_gap: the cost of the lowest-cost correction found in a different observable class, minus the cost of the returned correction, in nats. The observable class of a correction is the set of observables that it flips.jobs_gap_class: the observable class of that competing correction, as an integer bit mask in which bitois set if the correction flips observableo, or -1 if none was found.
The gap is computed only over the corrections that the search evaluated. It is therefore an approximation of the complementary gap and not the exact value. The gap is
+infwhen the search found no correction in another class. It is also+inffor shots on which JOBS did not run, that is, shots for which BP converged whenjobs_search_convergedis false. A small gap indicates a shot that is more likely to be decoded incorrectly, so the gap can be used for post-selection.jobs_gaprequires a decoder constructed with an observable matrix that has at most 12 observables. For k observables, the option addsbp_batch_sizex 2^k x 4 bytes to the device memory of the search.The following example requests the JOBS gap and keeps the shots whose gap is at least 5 nats:
dec = qec.get_decoder("nv-qldpc-decoder", H, O=O, error_rate_vec=rates, use_sparsity=True, max_iterations=10, clip_value=15.0, use_osd=True, osd_method=4, osd_init_method="min_llr", bp_batch_size=2048, opt_results=dict(jobs_gap=True)) res = dec.decode_batch(syndromes) gap = np.array([o["jobs_gap"] for o in res.opt_results]) keep = gap >= 5.0
Optional results
Additional outputs that the decoder returns with each result.
opt_results(heterogeneous_map): Optional results to return. This field can be left empty if no additional results are desired. Choices are:bp_llr_history(int): Return the lastbp_llr_historyiterations of the BP LLR history. Minimum value is 0 and maximum value is max_iterations. The actual number of returned iterations might be fewer thanbp_llr_historyif BP converges before the requested number of iterations. Introduced in 0.4.0. Note: Not supported forcomposition=1.num_iter(bool): If true, return the number of BP iterations run. Introduced in 0.5.0.kstar(bool): If true, return K* per shot: the smallest number of leading columns of the OSD ordering whose span contains the syndrome; -1 when OSD did not run because BP converged (withjobs_search_converged, converged shots are searched and report the K* of that search). Withosd_sparsify_exact, a value aboveosd_sparsify_exactmarks a shot the window could not solve. Requiresuse_osd.jobs_gap(bool): If true, return per shot the JOBS gap (jobs_gap, nats) and the competing observable class (jobs_gap_class, int; -1 when none). See “JOBS gap” in the JOBS section. Requiresosd_method=4and a decoder constructed with observables (at most 12).relay_solutions(bool or int): Record every relay convergence (“solution”), not just the winning one.Truerecords all of them; a positive integer caps the number of records kept per shot (convergences beyond the cap still increment the per-shot total but are not stored). Requirescomposition=1(sequential relay) on the sparse GPU path (use_sparsity=True); other backends reject the option at construction. Not yet supported withgamma_ensemble_size > 1. Compatible withuse_osd=True(OSD post-processes non-converged shots and does not affect the records). Introduced in 0.8.0.Each record holds the cumulative BP iteration count at which the convergence occurred, the LLR weight of its hard decision (the sum of error-rate LLRs over bits decoded as 1), and the hard decision itself, bit-packed 32 bits per little-endian word. The hard decision follows the explicitly selected result basis: the correction vector for error output, or its observable flips for observable output.
The records describe a batch as a whole, so
decode_batch()returns them through its batch-level results (theBatchDecoderResult.batch_opt_resultsattribute in Python; the optionalbatch_opt_resultsoutput parameter in C++) as flat arrays under the keysrelay_solutions_width,relay_solutions_max_records,relay_solutions_counts,relay_solutions_totals,relay_solutions_iters,relay_solutions_weight, andrelay_solutions_result. (decode()returns the same keys throughDecoderResult.opt_results, with scalarrelay_solutions_count/relay_solutions_total.) Thecudaq_qec.relay_solutionsPython module post-processes the records:unpack()reconstructs the per-shot record axes, andstop_nconv_sweep()replays an entire RelayBP-Nstop_nconvsweep — logical error rate, mean iterations, and iteration percentiles for every N — from a single recording run. See Sweeping Relay BP Stopping Criteria From a Single Run for a usage and performance walkthrough.
Presets
The
cudaq_qec.plugins.nv_qldpcmodule defines named presets for the configurations in the table above.preset(name, **overrides)returns the options of a preset as a dictionary, withoverridesapplied. Pass the dictionary toget_decoderas keyword arguments.Preset
BP
Column ordering
Post-processor
bp60sum-product, 60 iterations
n/a
none (BP hard decision)
bp60-osd0sum-product, 60 iterations
final LLR
OSD-0
bp60-osd-cs1000sum-product, 60 iterations
final LLR
combination sweep,
osd_order=1000bp10-minllr-osd0sum-product, 10 iterations
minimum LLR
OSD-0
bp10-minllr-osd-cs1000sum-product, 10 iterations
minimum LLR
combination sweep,
osd_order=1000bp10-minllr-jobssum-product, 10 iterations
minimum LLR
JOBS
relay-bpRelay-BP (
bp_method=3), 80 pre-iterations, 300 relay legsn/a
none (BP hard decision)
tcbpsum-product, 10 iterations
n/a
none (TCBP error probabilities)
tcbp-osd-cs1000sum-product, 10 iterations
TCBP
combination sweep,
osd_order=1000tcbp-jobssum-product, 10 iterations
TCBP
JOBS
tcbp-jobs-scsum-product, 10 iterations
TCBP
JOBS with
jobs_search_convergedtcbp-jobs-sc-gapsum-product, 10 iterations
TCBP
JOBS with
jobs_search_convergedandopt_results.jobs_gapAll presets set
use_sparsity=true,proc_float="fp32"andrepeatable=true. All presets exceptrelay-bpalso setbp_method=0andclip_value=15.0.Notes:
Presets do not set error rates. Pass
error_rate_vecorerror_ratetoget_decoder.The
tcbp*presets require atcbp_modeloverride. The override accepts the bytes returned byinit_tcbp_model, auint8array or a file path.The
tcbp*presets use the BP settings thatinit_tcbp_modelfits with by default. To use a differentbp_method,max_iterations,clip_valueorproc_float, fit the model with those settings and pass the same values as overrides.tcbp-jobs-sc-gaprequires a decoder constructed with an observable matrix that has at most 12 observables.
Options that are commonly overridden:
bp_batch_size: number of shots decoded in parallel.osd_sparsify=Trueandosd_sparsify_pad: restrict OSD-0 and the combination sweep to the K* window, which reduces their cost. The window is off by default for these methods, andosd_sparsify_paddefaults to 8.0. JOBS always uses the window.jobs_draws,jobs_beam_width,jobs_beam_depth,jobs_beam_patienceandjobs_draw_noise: amount of search that JOBS performs.gamma0,gamma_distandsrelay_config: Relay-BP parameters.bp_method=1: min-sum BP in place of sum-product (scale_factorapplies).
The following example constructs a decoder from an OSD preset with the K* window enabled and a pad of 4.0 in place of the default 8.0, and a second decoder from a TCBP+JOBS preset that returns the JOBS gap:
import numpy as np import cudaq_qec as qec from cudaq_qec.plugins import nv_qldpc dec = qec.get_decoder("nv-qldpc-decoder", H, error_rate_vec=rates, bp_batch_size=2048, **nv_qldpc.preset("bp10-minllr-osd-cs1000", osd_sparsify=True, osd_sparsify_pad=4.0)) model = nv_qldpc.init_tcbp_model(H) # once per code family dec = qec.get_decoder("nv-qldpc-decoder", H, O=O, error_rate_vec=rates, bp_batch_size=2048, **nv_qldpc.preset("tcbp-jobs-sc-gap", tcbp_model=model)) res = dec.decode_batch(syndromes) gap = np.array([o["jobs_gap"] for o in res.opt_results])
NVIDIA Fusion Decoder
- class nv_fusion_decoder
A multi-threaded minimum-weight perfect matching (MWPM) decoder based on the NV Fusion Brickwall algorithm. It is in essence a combination of fusion blossom with sparse blossom: the detector matching graph is partitioned into temporal blocks that are solved independently and then fused across their boundaries (fusion blossom), while each individual block is solved by PyMatching’s sparse blossom implementation. Blocks and the fuses between them form a dependency DAG that is dispatched to a worker pool as syndrome data arrives, so the decoder is designed to maximize parallel processing utilization and reach minimal latency in a streaming, realtime decoding environment. Offline batch decoding is supported through the same scaffold.
Thread count is set by
num_threads, which defaults to1; pass0to size the pool from the hardware. That pool parallelizes the blocks and fuses within one shot; it does not make a decoder callable from several threads at once.Important
One decoder decodes one shot at a time. Both
decode()and the realtime enqueue path keep per-shot state on the decoder – syndrome routing, block and fuse matching state, and the herald flags – so two threads sharing a decoder corrupt each other. Use one decoder per thread.This applies to
decode_async(), which runsdecode()on a new thread: keeping two futures outstanding on the same decoder is not supported.decode_batch()is sequential and therefore safe.Concurrent
decode()calls on one nv-fusion decoder raisestd::logic_errorrather than interleaving, so the misuse surfaces as an exception instead of a wrong answer.The decoder is graphlike: every error mechanism must touch exactly one (boundary edge) or two (bulk edge) detectors. Constructing from
H, that is a constraint on its columns; constructing from a DEM, Stim’s^decomposition suggestions are applied first, so a hyperedge is accepted only when the DEM suggests a graphlike decomposition for it. Block size is set byblock_leaf_size, blocks overlap so that fusing adjacent pairs propagates information across their shared boundary, and the observable corrections that come out are XOR-accumulated into a running Pauli frame.Important
A single-leaf schedule is one block with no fuses, and is exact monolithic MWPM. Any fused schedule is a windowed approximation: the brickwall has two fuse layers, so each block’s corrections are decided within a window of at most four leaves (two for the first and last blocks) rather than against the whole shot. An error chain longer than that window can be matched differently than monolithic MWPM would match it, and the result is not always flagged – the heralded-failure check fires on unresolved virtual-boundary matches, which an undersized window does not reliably produce.
Sizing the leaf from the code distance is what keeps the window large enough for this to be safe; see
block_leaf_sizebelow.References:
Note
It is required to create decoders with the
get_decoderAPI from the CUDA-Q QEC extension points API, such asimport cudaq_qec as qec import numpy as np # Two boundary edges carrying one observable each, plus a timelike # edge between the detectors carrying none. H = np.array([[1, 0, 1], # rows = detectors [0, 1, 1]], dtype=np.uint8) O = np.array([[1, 0, 0], # rows = observables [0, 1, 0]], dtype=np.uint8) # int32, one round index per detector opts = {"detector_round": np.array([0, 1], dtype=np.int32)} decoder = qec.get_decoder('nv-fusion-decoder', H, O=O, output='observables', **opts) decoder.decode([1.0, 0.0]) # -> [1.0, 0.0]
#include "cudaq/qec/decoder.h" // Two boundary edges carrying one observable each, plus a // timelike edge between the detectors carrying none. cudaqx::tensor<uint8_t> H, O; std::vector<uint8_t> H_vec = {1, 0, 1, // rows = detectors 0, 1, 1}; std::vector<uint8_t> O_vec = {1, 0, 0, // rows = observables 0, 1, 0}; H.copy(H_vec.data(), {2, 3}); O.copy(O_vec.data(), {2, 3}); cudaqx::heterogeneous_map opts; opts.insert("detector_round", std::vector<int32_t>{0, 1}); cudaq::qec::decoder_init inputs( cudaq::qec::sparse_binary_matrix(H), cudaq::qec::sparse_binary_matrix(O)); auto decoder = cudaq::qec::get_decoder( "nv-fusion-decoder", std::move(inputs), cudaq::qec::decode_result_type::observables, opts); decoder->decode({1.0, 0.0}); // -> {1.0, 0.0}
Note
The
"nv-fusion-decoder"implements thecudaq_qec.Decoderinterface for Python and thecudaq::qec::decoderinterface for C++, so it supports all the methods in those respective classes.- Parameters:
H – Parity-check matrix (sparse binary matrix or dense
tensor<uint8_t>), shape(num_detectors, num_error_mechanisms). Each column must have exactly one or two non-zero rows (graphlike error mechanisms). Pass Stim DEM text in this position instead to construct from an authoritative DEM, which carriesH,O, and error rates.O – Optional observable matrix with shape
(num_observables, num_error_mechanisms). It is model data and does not select the result basis. Python accepts it as a keyword adapter; C++ supplies it throughcudaq::qec::decoder_init.output – Result basis,
"errors"or"observables"in Python andcudaq::qec::decode_result_typein C++. SupplyingOor DEM text does not select observable output.error_rate_vec – Optional physical error probability per error mechanism, with length
H.num_cols()and values in(0, 0.5]. Python accepts it as a keyword adapter; C++ supplies it throughcudaq::qec::decoder_init. The H construction path uses it to compute log-likelihood-ratio edge weights; otherwise unit weights are used. A DEM already carries its own probabilities.params –
Heterogeneous map of parameters:
Note
These are the C++ and Python parameters. The realtime YAML surface is narrower:
decoder_custom_argsaccepts onlynum_threads,block_leaf_size,fusion_strategyanderror_rate_vec, and rejects any other key. A YAML configuration supplies the matrices and the temporal layout through the top-levelH_sparse,O_sparseandD_sparsefields instead.Temporal layout (one of the following is required, unless a DEM supplies detector coordinates):
detector_round(vector<int32_t>): Per-detector temporal round index, lengthH.num_rows(). Maps each parent detector to its round in 0-based integer coordinates. Takes highest priority over all automatic derivation paths.Dincudaq::qec::decoder_init: Sparse measurement-to-detector map with shape(num_detectors, num_measurements). The decoder infers the per-detector round from the column stride of the two-entry (timelike) rows. Rows with more than two entries are treated as terminal boundary detectors placed in the last round. The realtime configuration’s top-levelD_sparsefield is normalized into this model input.
The three sources are consulted in that order: an explicit
detector_roundfirst, then DEM coordinates, thenD. A DEM therefore takes precedence overD, and one missing a detector coordinate fails rather than falling back to it. Without a DEM and with neither input given, construction is rejected.Blocking and threading:
block_leaf_size(uint64): Number of temporal rounds per leaf block. Smaller values reduce per-block latency but increase fuse overhead; larger values amortize fuse cost at the expense of latency. An explicit value is always honored as given; if it is below the measured code distance and the schedule fuses more than one block, construction logs a warning, because such a leaf cannot contain a logical error chain and inflates the logical error rate without raising a heralded failure.When omitted, the schedule is selected automatically:
192 rounds or fewer – a single leaf spanning the shot, which is exact monolithic MWPM.
More than 192 rounds – a fused schedule with a leaf of
2 * d, wheredis the code distance measured from the matching graph as the shortest undetectable logical error. This bounds tail latency, which under a single leaf grows linearly with the number of rounds.Distance not measurable (a model with no observables, or none admitting an undetectable logical error) – a single leaf at any shot length, since fusing on an unverified leaf height inflates the logical error rate silently.
Warning
The second case trades exactness for latency, and it is the default. A shot longer than 192 rounds is decoded by the windowed approximation described above, not by monolithic MWPM. A leaf of
2 * dputs four times the margin over the smallest leaf measured to be safe (0.5 * d), and over d=5..21 on rotated surface and repetition codes it reproduced single-leaf corrections shot for shot – but that is a measured result on those codes and noise models, not a guarantee for every code.To keep exact monolithic MWPM at any shot length, set
block_leaf_sizeto the shot’s full round count explicitly.This differs from earlier releases, where omitting
block_leaf_sizealways produced a single leaf.num_threads(uint64): Number of CPU threads to use during scaffold construction and parallel fuse operations. Defaults to1.
Fusion schedule:
fusion_strategy(str): Fusion schedule to use. Only"brickwall"(the default) is supported;"balanced-tree"and"linear-tree"are reserved and rejected. The former"sliding-window"value is also rejected, because"brickwall"now rolls on its own (see below).
Rolling:
When the model allows it,
"brickwall"decodes the shot with a rolling window: head blocks laid as the finite schedule lays them, a ring that recycles its oldest pair of blocks as the stream advances, and a tail pair, all joined by ordinary layer-2 seams. Memory and scaffold size are then bounded by the ring rather than the shot length. The observables are identical to a finite brickwall with the same blocks laid out across the whole shot, so rolling costs no accuracy.Error output rolls too. Each block keeps the matching edges wholly inside it, away from its cuts, and what that leaves unexplained is rematched in windows of two block pairs that slide up the shot, so the repair’s memory does not grow with the shot. The result always reproduces the syndrome, and flips exactly the observables the rolling decode predicts, so its logical error rate is the rolling decode’s. It is not necessarily the monolithic matching: the selected columns can differ by an error that flips no detector and no observable, and their total weight is typically within a few percent of it. A shot whose repair finds no such correction is reported as heralded.
It rolls when all of these hold, and otherwise builds one finite scaffold over the whole shot:
for error output,
rolling_error_outputis notfalse;the schedule is fused, i.e.
block_leaf_sizeis set, or it is omitted and the automatic2 * dleaf applies (more than 192 rounds with a measurable distance);one ring revolution fits between a minimal head and the tail, so with the defaults the shot needs more than
32 * drounds;the rounds are contiguous from 0, every bulk round has the same number of detectors, and every bulk error mechanism recurs one block pair (
2 * block_leaf_sizerounds) later on the same detectors (by position within their round), observables and weight;no error mechanism reaches from the head past the ring’s first revolution, or from the rest of the bulk into the tail.
The decoder logs at info level whether it rolled, and if not, why.
Constructed from
cudaq::qec::decoder_init::from_dem_chunks()(or a realtime configuration’sdem_chunks), the decoder rolls without ever building the shot’s flat model: it closes the chunks over a representative number of rounds, independent ofnum_rounds, and extends that model to the shot by whole ring revolutions of the bulk chunk. The corrections are those of the same chunks closed over the whole shot. When the model does not roll, the decoder closes the chunks itself for the finite scaffold. A realtime configuration hands nv-fusion the chunks without their closed model; a C++ caller that needs the matrices for another use constructs the inputs withcudaq::qec::decoder_init::from_dem_chunks_closed()instead.rolling_ring_blocks(uint64): Blocks in the ring, eachblock_leaf_sizerounds tall. Defaults to12; even and at least6. Not accepted in a realtime YAML configuration, which uses the default.rolling_boundary_leaf_size(uint64): Leaf height of the tail’s two blocks, and the least for the head’s. Defaults to the ring’s leaf. Likeblock_leaf_size, a value below the measured code distance logs a warning. Not accepted in a realtime YAML configuration, which uses the default.rolling_error_output(bool): Whether error output rolls. Defaults totrue;falsekeeps the finite scaffold, whose error output is the monolithic matching of the whole shot. Not accepted in a realtime YAML configuration, which always decodes to observables.rolling_error_margin(uint64): Rounds either side of each cut between blocks whose block corrections rolling error output rematches. Defaults to a quarter ofblock_leaf_size, at least 1, which keeps the middle half of each block’s corrections. It must be below half ofblock_leaf_size: every round of a block lies within that of a cut, so a larger margin would rematch the whole shot, and the decoder falls back to the finite window instead (as it does for a leaf under 4 rounds).1keeps more of the blocks’ corrections and decodes faster, at a percent or two more weight with the automatic2 * dleaf. Not accepted in a realtime YAML configuration.
The ring carries a whole number of revolutions, and the head grows to take up the remainder. The head is
block_leaf_sizeblocks from round 0, the last pair splitting what is left, so it commits pair by pair as the ring does.
Decode result format:
decode()returns aDecoderResultwhere:result— the explicitly selected result basis. Observable output has lengthnum_observablesand each entry indicates a predicted logical flip. Error output has lengthblock_sizeand each entry indicates whether the corresponding H column was selected as a matching edge.converged—Trueif the fuse pass raised no herald flag. AFalsevalue indicates a suspect or ambiguous match; the correction is still populated and may be used. For rolling error output it is alsoFalsewhen no tail logical brings the errors onto the rolling observables; the errors are then the stitched matching alone, which explains the syndrome but may flip other observables.opt_results— heterogeneous map with key:heralded(bool): Raw herald flag from the brickwall fuse pass, corresponding toconverged = not heralded.
Realtime streaming:
The decoder supports the base-class realtime API (
enqueue_syndrome,get_obs_corrections,reset_decoder,clear_corrections). The realtime path accepts raw per-round measurement bits rather than pre-differenced detector bits; the decoder accumulates measurements internally and computes detector events viaD_sparseas each detector round’s measurements become complete. Observable corrections are XOR-accumulated into a running Pauli frame and exposed viaget_obs_corrections().Task-graph streaming uses the optional
streaming_correction_providercapability: BULK publications read committed corrections without sealing the shot, and FINAL, which carries the shot’s last measurements, completes deferred work. Reaching the configured template length therefore does not split a longer task-graph shot. Final coverage uses the actual number of physical rounds, not the template length or the terminal payload’s byte width. Direct callers retain the existing configured-length behavior ofget_obs_corrections().Note
Dmust be supplied incudaq::qec::decoder_initbefore the first call toenqueue_syndrome(). The realtime layer normalizes its top-levelD_sparseconfiguration into that model input.Note
Observable corrections accumulate across shots. Call
clear_corrections()orreset_decoder()between shots to reset the Pauli frame.reset_decoder()also rewinds the streaming session;clear_corrections()does not.
Sliding Window Decoder
- class sliding_window
The Sliding Window Decoder is a wrapper around a standard decoder that introduces two key differences:
1. Sliding Window Decoding: The decoding process is performed incrementally, one window at a time. The window size is specified by the user. This allows decoding to begin before all syndromes have been received, potentially reducing overall latency in multi-round QEC codes.
2. Partial Syndrome Support: Unlike standard decoders, the
decodefunction (and its variants likedecode_batch) can accept partial syndromes. If partial syndromes are provided, the return vector will be empty, the decoder will not complete the processing and remain in an intermediate state, awaiting future syndromes. The return vector is only non-empty once enough data has been provided to match the original syndrome size (calculated from the Parity Check Matrix).The cancellable
decodeanddecode_batchoverloads forward the token to the inner decoders. They return the same empty result while a block is incomplete, andstd::nulloptif an inner decoder honors a stop; the partial block is dropped and the next round starts a new one.reset_decoder()also drops a partial block.Sliding window decoders are advantageous in QEC codes subject to circuit-level noise across multiple syndrome extraction rounds. These decoders permit syndrome processing to begin before the complete syndrome measurement sequence is obtained, potentially reducing the overall decoding latency. However, this approach introduces a trade-off: the reduction in latency typically comes at the cost of increased logical error rates. Therefore, the viability of sliding window decoding depends critically on the specific code parameters, noise model, and latency requirements of the system under consideration.
Sliding window decoding imposes only a single structural constraint on the parity check matrices: each syndrome extraction round must produce a constant number of syndrome measurements. Notably, the decoder makes no assumptions about temporal correlations or periodicity in the underlying noise process.
Streaming Syndrome Interface
For realtime applications, the decoder provides an
enqueue_syndrome()method that accepts syndrome data one round at a time. This allows the host to feed syndrome measurements as they arrive without waiting for all rounds to complete. The decoder automatically manages internal buffering and triggers window decodes at appropriate boundaries.References: Toward Low-latency Iterative Decoding of QLDPC Codes Under Circuit-Level Noise
Note
It is required to create decoders with the
get_decoderAPI from the CUDA-Q QEC extension points API, such asimport cudaq import cudaq_qec as qec import numpy as np cudaq.set_target('stim') num_rounds = 5 code = qec.get_code('surface_code', distance=num_rounds) noise = cudaq.NoiseModel() noise.add_all_qubit_channel("x", cudaq.Depolarization2(0.001), 1) statePrep = qec.operation.prep0 dem = qec.dem_from_memory_circuit(code, statePrep, num_rounds, noise) inner_decoder_params = {'use_osd': True, 'max_iterations': 50} opts = { 'error_rate_vec': np.array(dem.error_rates), 'window_size': 1, 'num_syndromes_per_round': code.get_num_z_stabilizers() + code.get_num_x_stabilizers(), 'num_boundary_syndromes': code.get_num_z_stabilizers(), 'inner_decoder_name': 'single_error_lut', 'inner_decoder_params': inner_decoder_params, } swdec = qec.get_decoder('sliding_window', dem.detector_error_matrix, **opts)
#include "cudaq/qec/code.h" #include "cudaq/qec/decoder.h" #include "cudaq/qec/experiments.h" #include "common/NoiseModel.h" int main() { // Generate a Detector Error Model. int num_rounds = 5; auto code = cudaq::qec::get_code( "surface_code", cudaqx::heterogeneous_map{{"distance", num_rounds}}); cudaq::noise_model noise; noise.add_all_qubit_channel("x", cudaq::depolarization2(0.001), 1); auto statePrep = cudaq::qec::operation::prep0; auto dem = cudaq::qec::dem_from_memory_circuit(*code, statePrep, num_rounds, noise); // Use the DEM to create a sliding window decoder. auto inner_decoder_params = cudaqx::heterogeneous_map{{"use_osd", true}, {"max_iterations", 50}}; auto opts = cudaqx::heterogeneous_map{ {"window_size", 1}, {"num_syndromes_per_round", code->get_num_z_stabilizers() + code->get_num_x_stabilizers()}, {"num_boundary_syndromes", code->get_num_z_stabilizers()}, {"inner_decoder_name", "single_error_lut"}, {"inner_decoder_params", inner_decoder_params}}; auto swdec = cudaq::qec::get_decoder("sliding_window", cudaq::qec::decoder_init{dem}, opts); return 0; }
Note
The
"sliding_window"decoder implements thecudaq_qec.Decoderinterface for Python and thecudaq::qec::decoderinterface for C++, so it supports all the methods in those respective classes.- Parameters:
H – Parity check matrix (tensor format)
params –
Heterogeneous map of parameters:
error_rate_vec(vector<double>): Vector of lengthblock_sizecontaining the probability of each error. Python accepts this as a keyword. C++ supplies it throughcudaq::qec::decoder_init(for example, by constructing it from the DEM as above), not the heterogeneous parameter map. It is sliced to each window before the inner decoder is constructed.window_size(int): The number of rounds of syndrome data in each window. (Defaults to 1.)step_size(int): The number of rounds to advance the window by each time. (Defaults to 1.)num_syndromes_per_round(int): The number of syndromes per round. (Must be provided.)num_boundary_syndromes(int): The number of detectors in the first and last (boundary) round of the memory experiment. (Defaults to 0, meaning all layers havenum_syndromes_per_rounddetectors.) For a single-basis DEM fromz_dem_from_memory_circuit()(respectivelyx_dem_from_memory_circuit()), every layer hascode.get_num_z_stabilizers()(respectivelycode.get_num_x_stabilizers()) detectors, so this may be left at its default. For a full DEM fromdem_from_memory_circuit(),num_syndromes_per_roundiscode.get_num_z_stabilizers() + code.get_num_x_stabilizers()while the boundary rounds only carry the stabilizer type fixed by the state prep, so set this tocode.get_num_z_stabilizers()for Z-basis preps (prep0/prep1) orcode.get_num_x_stabilizers()for X-basis preps (prepp/prepm).straddle_start_round(bool): When forming a window, should error mechanisms that span the start round and any preceding rounds be included? (Defaults to False.)straddle_end_round(bool): When forming a window, should error mechanisms that span the end round and any subsequent rounds be included? (Defaults to True.)inner_decoder_name(string): The name of the inner decoder to use.inner_decoder_params(Python dict or C++heterogeneous_map): A dictionary of parameters to pass to the inner decoder.
TensorRT Decoder
- class trt_decoder
A GPU-accelerated quantum error correction decoder based on NVIDIA TensorRT. This decoder leverages TensorRT’s optimized inference engine to perform fast neural network-based decoding of quantum error correction syndromes.
The TRT decoder supports loading pre-trained neural network models in ONNX format or directly loading pre-built TensorRT engine files for maximum performance. It automatically optimizes the model for the target GPU architecture. The network is strongly typed, so TensorRT preserves the data types and quantization encoded in the ONNX model.
Neural network-based decoders can be trained to perform syndrome decoding for specific quantum error correction codes and noise models. The TRT decoder provides a high-performance inference engine for these models, with automatic CUDA graph optimization for reduced latency.
Requires a CUDA-capable GPU and TensorRT installation. See the CUDA-Q GPU Compatibility List for a list of valid GPU configurations.
Warning
Breaking change:
engine_output_formatis required. It declares the semantic layout of the TensorRT model’s output and is validated againstH,O, and any configured global decoder. Existing callers must add the value matching the model they load.Note
It is required to create decoders with the
get_decoderAPI from the CUDA-Q QEC extension points API, such asimport cudaq_qec as qec import numpy as np # H defines the error-frame width and must match the model output. H = np.array([[1, 0, 0, 1, 0, 1, 1], [0, 1, 0, 1, 1, 0, 1], [0, 0, 1, 0, 1, 1, 1]], dtype=np.uint8) # Option 1: Load from ONNX model (builds TRT engine) trt_dec = qec.get_decoder('trt_decoder', H, onnx_load_path='model.onnx', engine_output_format='errors', engine_save_path='model.engine') # Option 2: Load pre-built TRT engine (faster startup) trt_dec = qec.get_decoder('trt_decoder', H, engine_load_path='model.engine', engine_output_format='errors')
#include "cudaq/qec/decoder.h" std::size_t block_size = 7; std::size_t syndrome_size = 3; cudaqx::tensor<uint8_t> H; // H defines the error-frame width and must match the model output. std::vector<uint8_t> H_vec = {1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1}; H.copy(H_vec.data(), {syndrome_size, block_size}); // Option 1: Load from ONNX model (builds TRT engine) cudaqx::heterogeneous_map params1; params1.insert("onnx_load_path", "model.onnx"); params1.insert("engine_output_format", std::string("errors")); params1.insert("engine_save_path", "model.engine"); auto trt_dec1 = cudaq::qec::get_decoder("trt_decoder", H, params1); // Option 2: Load pre-built TRT engine (faster startup) cudaqx::heterogeneous_map params2; params2.insert("engine_load_path", "model.engine"); params2.insert("engine_output_format", std::string("errors")); auto trt_dec2 = cudaq::qec::get_decoder("trt_decoder", H, params2);
Note
The
"trt_decoder"implements thecudaq_qec.Decoderinterface for Python and thecudaq::qec::decoderinterface for C++, so it supports all the methods in those respective classes.Note
The TensorRT engine performs inference, but
His still model data. Its column count defines the error-frame width, validates anengine_output_format="errors"engine, and supplies the detector model to an optional global decoder.Hand the optionalOmust therefore describe the code and index ordering used to train the engine.Note
Batch Processing: The TRT decoder automatically handles batch size optimization. Models trained with batch_size > 1 will receive zero-padded inputs when using
decode()on a single syndrome. When usingdecode_batch(), provide syndromes in multiples of the model’s batch size for optimal performance.- Parameters:
H – Parity check matrix for the code and error-mechanism ordering used by the TensorRT model.
params –
Heterogeneous map of parameters:
Required:
engine_output_format(string): Semantic layout of one model output. This describes the engine tensor independently of the decoder result contract. Accepted values are:"errors": one error-frame value per column ofH."residual_detectors": residual detector values consumed by the requiredglobal_decoder."observables": one value per row ofO."observables_and_residual_detectors": an observable prefix followed by residual detectors. Withglobal_decoder, the residuals are decoded and combined with the observable prefix. Alternatively, a C++decoder_output_requestmay requestobservablesas the primary result andresidual_detectorsas an auxiliary output; the prefix is then returned inresultand the residuals inopt_results["residual_detectors"].
Required model source (choose one):
onnx_load_path(string): Path to ONNX model file. The decoder will build a TensorRT engine from this model. Cannot be used together withengine_load_path.engine_load_path(string): Path to pre-built TensorRT engine file. Provides faster initialization since the engine is already optimized. Cannot be used together withonnx_load_path.
Optional:
engine_save_path(string): Path to save the built TensorRT engine. Only applicable when usingonnx_load_path. Saving the engine allows for faster initialization in subsequent runs by usingengine_load_path.precision(string): TensorRT build policy (defaults to"best")."best"preserves TensorRT’s default TF32 policy,"tf32"explicitly enables TF32, and"noTF32"disables it. The legacy values"fp16","bf16","int8", and"fp8"remain accepted for configuration compatibility, but are ignored because the network is strongly typed. To use those types or quantization, encode them in the ONNX model before loading it.memory_workspace(size_t): Memory workspace size in bytes for TensorRT engine building (defaults to 1GB = 1073741824 bytes). Larger workspaces may allow TensorRT to explore more optimization strategies.use_cuda_graph(bool): Enable CUDA graph optimization for improved performance (defaults to True). CUDA graphs capture inference operations and replay them with reduced kernel launch overhead, providing ~20% speedup. The optimization is applied automatically on the first decode call. Automatically disabled for models with dynamic shapes or multiple optimization profiles. Set to False to force traditional execution path.batch_size(automatic): The decoder automatically detects the model’s batch size from the first input dimension. For models with batch_size > 1, thedecode()method automatically zero-pads single syndromes to fill the batch. Thedecode_batch()method requires the number of syndromes to be an integral multiple of the model’s batch size.global_decoder(string): Name of a second-stage “global” decoder to chain after the TensorRT model (composite decoding). It is required for"residual_detectors". For"observables_and_residual_detectors", it is required unless the output contract requests observable primary output and theresidual_detectorsauxiliary output. The TRT model acts as a first-stage predecoder whose residual output is passed to the named global decoder (for example"pymatching"or"chromobius"). It may be omitted for output formats that need no second stage. See the realtime decoding API for configuring composite decoding from YAML. Introduced in 0.7.0. A cancellation token passed todecodeordecode_batchreaches only this global decoder; TensorRT inference itself is not interruptible.global_decoder_params(map): Parameters forwarded to theglobal_decoder. The accepted keys follow the parameter schema of the named global decoder. This is optional; when omitted, the named global decoder is constructed with an empty parameter map. Introduced in 0.7.0.cuda_device_id(int): Zero-based CUDA device ordinal on which to construct the decoder and run every decode. Must be>= 0and less than the number of visible GPUs. When omitted, the decoder is not pinned to a specific device and runs on the default device (GPU 0). Introduced in 0.7.0.
PyMatching Decoder
- class pymatching
A minimum-weight perfect matching (MWPM) decoder for matchable quantum error correction codes (such as the surface code), built on the open-source PyMatching library. It is a CPU decoder: each syndrome bit becomes a detector node, and each error (column of the parity-check matrix) with one or two set entries becomes a (boundary) edge whose weight is derived from the error prior.
Warning
Breaking change: Supplying an observable matrix
Ono longer selects observable output.Ois model data and may be used even when the requested result is an error frame. PyMatching returns errors whenoutputis omitted. Passoutput="observables"in Python orcudaq::qec::decode_result_type::observablesin C++ to request observable flips explicitly.Note
To use the decoder, use the
get_decoderAPI with a parity-check matrix as the decoder input:import cudaq_qec as qec import numpy as np # Parity check matrix. Each column (error mechanism) must have one # or two set entries so the graph is matchable. H = np.array([[1, 1, 0], [0, 1, 1]], dtype=np.uint8) O = np.array([[1, 0, 1]], dtype=np.uint8) # O does not change the default: this decoder returns an error # frame with one entry per column of H. error_dec = qec.get_decoder( "pymatching", H, O=O, error_rate_vec=[0.1, 0.1, 0.1], merge_strategy="smallest_weight") # Request observable flips explicitly. observable_dec = qec.get_decoder( "pymatching", H, O=O, output="observables", error_rate_vec=[0.1, 0.1, 0.1], merge_strategy="smallest_weight")
#include "cudaq/qec/decoder.h" cudaqx::tensor<uint8_t> H; const std::vector<uint8_t> h_data{1, 1, 0, 0, 1, 1}; H.copy(h_data.data(), {2, 3}); cudaqx::tensor<uint8_t> O; const std::vector<uint8_t> o_data{1, 0, 1}; O.copy(o_data.data(), {1, 3}); cudaqx::heterogeneous_map params; params.insert("merge_strategy", std::string("smallest_weight")); std::vector<double> error_rates{0.1, 0.1, 0.1}; cudaq::qec::decoder_init inputs( cudaq::qec::sparse_binary_matrix(H), cudaq::qec::sparse_binary_matrix(O), error_rates); // O is present, but omitting the result type still requests the // PyMatching default: an error frame. auto error_dec = cudaq::qec::get_decoder( "pymatching", inputs, params); // Observable output is explicit and fixed at construction. auto observable_dec = cudaq::qec::get_decoder( "pymatching", inputs, cudaq::qec::decode_result_type::observables, params);
Note
The
"pymatching"decoder implements thecudaq_qec.Decoderinterface for Python and thecudaq::qec::decoderinterface for C++, so it supports all the methods in those respective classes.- Parameters:
H – Parity check matrix. Each column must have one or two set entries (matchable graph). In Python, a
scipy.sparsematrix or a dense NumPyuint8array may be passed.params –
Decoder model inputs and heterogeneous parameters:
error_rate_vec(vector<double>): Per-error prior probabilities, one per column ofH(lengthblock_size). Python accepts this as a keyword. C++ supplies it throughcudaq::qec::decoder_init, not the heterogeneous parameter map. Each value must lie in(0, 0.5]and sets the matching edge weight-log(p / (1 - p)). When omitted, all edge weights default to1.0.merge_strategy(string): How to combine parallel edges that map to the same pair of detectors. One of"disallow"(default for theH-only path),"independent","smallest_weight","keep_original", or"replace".O(tensor, optional): Anum_observables x block_sizebinary matrix used to project error frames into observable flips. Its presence does not select the result basis. Request observable output explicitly withoutput="observables"in Python orcudaq::qec::decode_result_type::observablesin C++. When observable output is requested,merge_strategydefaults to"independent"to match PyMatching’s detector-error-model construction. SupplyingOwhile requesting error output leaves the default as"disallow".
Chromobius Decoder
- class chromobius
A decoder for color codes built on the open-source Chromobius Möbius decoder. Unlike the matrix-based decoders, Chromobius is detector-error-model native: it is constructed directly from Stim detector-error-model (DEM) text and predicts logical observable flips directly.
Note
To use the decoder, use the
get_decoderAPI with the Stim DEM text as the decoder input:import cudaq_qec as qec with open("color_code.dem") as f: dem_text = f.read() dec = qec.get_decoder("chromobius", dem_text) corrections = dec.decode(syndrome) # predicted observable flips
#include "cudaq/qec/decoder.h" std::string dem_text = /* Stim detector error model text */; cudaqx::heterogeneous_map params; auto dec = cudaq::qec::get_decoder("chromobius", dem_text, params);
Note
Chromobius is DEM-native: constructing it from a parity-check matrix is rejected with an error. Use
get_decoder("chromobius", dem_text, params). The DEM must describe a color code whose errors carry the color/basis annotations that Chromobius decomposes.Note
The
"chromobius"decoder implements thecudaq_qec.Decoderinterface for Python and thecudaq::qec::decoderinterface for C++. The wrapper currently returns observable flips as a 64-bit mask, so at most 64 logical observables are supported;decode()returns one bit per observable.- Parameters:
dem_text – Stim detector error model, as text. Detectors become the decoder syndrome bits; observables become the returned
block_sizecorrection bits.params –
- Heterogeneous map of parameters (all optional and boolean),
forwarded to the Chromobius decoder configuration:
drop_mobius_errors_involving_remnant_errors(bool)ignore_decomposition_failures(bool)include_coords_in_mobius_dem(bool)return_weight(bool): When true, the match weight is returned in the decode result’sopt_resultsunder the key"weight".write_mobius_match_to_stderr(bool)
Realtime Decoding
The Realtime Decoding API enables low-latency error correction on quantum hardware by allowing CUDA-Q quantum kernels to interact with decoders during circuit execution. This API is designed for use cases where corrections must be calculated and applied within qubit coherence times.
The realtime decoding system supports simulation environments for local testing and hardware integration (e.g., on Quantinuum’s Helios QPU).
Core Decoding Functions
These functions can be called from within CUDA-Q quantum kernels (__qpu__ functions) to interact with realtime decoders.
-
void cudaq::qec::decoding::enqueue_syndromes(std::uint64_t decoder_id, const std::vector<cudaq::measure_result> &syndromes, std::uint64_t tag = 0)
Enqueue syndromes for decoding.
- Parameters:
decoder_id – The ID of the decoder to use.
syndromes – The syndromes to enqueue.
tag – Which round this is (the wire’s
counter).
-
void cudaq::qec::decoding::enqueue_syndromes_mapped(std::uint64_t decoder_id, const std::vector<cudaq::measure_result> &syndromes, std::uint64_t tag, std::uint64_t syndrome_mapping_id)
Enqueue syndromes, naming the syndrome_mapping row this round belongs to.
A device kernel carries one argument count per name, so naming a row takes its own kernel. Any further variant needs a name that differs before the first
., where the registry splits a key.- Parameters:
decoder_id – The ID of the decoder to use.
syndromes – The syndromes to enqueue.
tag – Which round this is (the wire’s
counter).syndrome_mapping_id – Which syndrome_mapping row describes the round: its shape, and eventually its per-virtual-port layout.
tagsays which round, this says what kind. 0 is the pass-through BULK row; a row declaredtype: finalends the shot.
-
std::vector<bool> cudaq::qec::decoding::get_corrections(std::uint64_t decoder_id, std::uint64_t return_size, bool reset = false)
Get the corrections for a given decoder.
- Parameters:
decoder_id – The ID of the decoder to use.
return_size – The number of bits to return (in bits). This is expected to match the number of observables in the decoder.
reset – Whether to reset the decoder corrections after retrieving them.
- Returns:
The corrections (detected bit flips) for the given decoder, based on all of the decoded syndromes since the last time any corrections were reset.
-
std::vector<bool> cudaq::qec::decoding::get_logical_measurements(std::uint64_t decoder_id, std::uint64_t first, std::uint64_t return_size, bool reset = false)
Get logical measurements for a given decoder: the raw logical readout with the decoder’s corrections applied. Only a task graph with a logical output, one a
logical_readoutnode feeds, has them. Each is ready once its readout has arrived and every correction that can flip it is committed; all are by the FINAL round.- Parameters:
decoder_id – The ID of the decoder to use.
first – The first logical measurement to return.
return_size – The number of logical measurements to return.
reset – Whether to reset the decoder corrections after retrieving them. Allowed only after the FINAL round. A reset read of either this or get_corrections consumes the shot for both, so read the logical measurements before a get_corrections that resets.
- Returns:
Logical measurements [first, first + return_size).
Configuration API
The configuration API enables setting up decoders before circuit execution. Decoders are configured using YAML files or programmatically constructed configuration objects.
-
struct graph_resources
Resources returned by decoder::capture_decode_graph().
The decoder plugin captures a CUDA graph internally and populates this struct. The device-side graph scheduler (DeviceGraphRingConsumer / DeviceGraphTransceiver) launches graph_exec from the GPU dispatch kernel; function_id names the RPC the graph serves.
-
enum class cudaq::qec::decoding::config::DecoderDispatch
Dispatch shape for a decoder session — HOW its RPCs are executed, not which wire the bytes arrive on (the wire is a server-level transport provider, selected independently). host: requests are dispatched on the CPU (HOST_CALL); works with any transport provider (dev, CI, no GPU required). device_graph: requests are dispatched on the GPU by the self-relaunching device-graph scheduler (DeviceGraphTransceiver); requires a decoder with a captured decode graph and a provider whose rings are GPU-visible (e.g. GpuRoceTransceiver/DOCA). YAML key:
dispatch: host|device_graph.Values:
-
enumerator host
-
enumerator device_graph
-
enumerator host
-
class decoder_custom_args_t
Decoder-specific constructor arguments, stored as a
cudaqx::heterogeneous_map— the form every decoder’s constructor consumes. YAML conversion and key validation are driven by the parameter schema the decoder registered (see cudaq/qec/decoder_config_schema.h), so out-of-tree decoders participate without any framework changes. The framework-ownederror_rate_vecmodel input is also accepted here as a legacy YAML alias, but is removed before plugin construction.Public Functions
-
bool operator==(const decoder_custom_args_t &other) const
Deep equality over the canonical custom-args value kinds.
-
bool operator==(const decoder_custom_args_t &other) const
-
struct decoder_config
Configuration structure for decoder options.
Public Functions
-
const std::string &effective_decoder_type() const
The decoder type used for schema lookup and custom-args handling. Returns task_graph->inner_type when task_graph is set (type must be absent in that case), otherwise returns type.
-
std::string describe_decoder_type() const
Decoder names shown to a user, which is not always the one schema lookup wants: a
nodes-form graph keeps its decoders on the nodes, so effective_decoder_type() is empty there while this joins what the nodes name. Falls back to the node kinds for a graph whose nodes take no decoder, so a log line always names something.
-
cudaqx::heterogeneous_map decoder_custom_args_to_heterogeneous_map() const
Return the parameter map a decoder’s constructor should receive: the stored custom args with the legacy error-rate alias removed and schema-declared defaults materialized (see materialize_default_args in cudaq/qec/decoder_config_schema.h) when a schema is registered for the effective decoder type, so programmatically built configs get the same normalization the YAML parse path applies.
-
std::vector<double> effective_error_rate_vec() const
Return the model error rates from either the canonical C++ field or the legacy
decoder_custom_args.error_rate_vecYAML spelling. The legacy key is configuration compatibility data and is never included in the parameter map handed to a decoder plugin.- Throws:
std::runtime_error – if rates are supplied in both locations, or more than once in nested decoder custom arguments.
-
void validate_custom_args() const
Validate
decoder_custom_argsagainst the parameter schema registered for the effective decoder type: unknown keys, missing required keys, and the schema’s own validate hook (if any). Throws std::runtime_error on the first violation. YAML parsing applies the same checks automatically; call this to vet a configuration built programmatically before using it.
Public Members
-
DecoderDispatch dispatch = DecoderDispatch::host
Dispatch shape for this decoder’s RPCs. Defaults to host. Set to device_graph for decoders where syndrome bits are DMA’d directly to GPU VRAM and decoded by a captured CUDA graph (e.g. nv_qldpc_decoder with RelayBP).
-
std::optional<int> cuda_device_id
CUDA device this decoder is pinned to at construction (see the “cuda_device_id” decoder parameter). Placement knob common to any GPU-accelerated decoder, hence at this level rather than inside the per-decoder custom args. Unset = unpinned.
-
uint64_t block_size = 0
The fields below describe the DEM three alternative ways, and exactly one of them applies:
Flat form: H_sparse plus block_size, syndrome_size, O_sparse, D_sparse and optional error_rate_vec, all sized for the whole experiment.
Chunk form: dem_chunks (which carries phases, connections, seam, and num_rounds internally). The flat fields are derived by expanding the phases, and must be omitted.
DEM form: stim_dem or stim_dem_path, the Stim model text itself, inline or by file. The decoder derives its dimensions, observable mapping and error rates from it. H_sparse, O_sparse and error_rate_vec must be omitted; D_sparse is still required, while block_size and syndrome_size are optional checked assertions.
Throughout a configuration, a
*_pathkey names a file and a key without the suffix carries its contents inline:stim_dem_pathis read from disk, whilestim_demis the model text itself. Astim_demwith no spaces, tabs or line breaks instead names a data_artifacts Stim DEM entry: any such value is taken as a name, which is safe because Stim model text always contains them. Parsing resolves the name; a configuration built in code is resolved where its models are built.Chunk form stays authoritative: decoder construction hands the chunks to the decoder, alone for one that declared it reads chunks natively (decoder_init::from_dem_chunks(); see register_decoder_native_model_source()) and with their closed model for any other (decoder_init::from_dem_chunks_closed()). expand_dem_chunks() is the explicit derivation of the equivalent flat form. DEM form stays authoritative: the model text is what the decoder is built from.
-
std::string stim_dem_path
Path to an authoritative Stim detector error model. Relative paths are resolved against the configuration file’s directory, or the process working directory for a programmatic or raw-string configuration.
-
std::string stim_dem
The same model’s text inline; at most one of the two is set.
-
std::string stim_dem_artifact
The data_artifacts entry
stim_demnames, if it names one; stim_dem or stim_dem_path is then a copy of that entry’s text or path.
-
std::vector<std::int64_t> D_sparse
Maps raw measurements to detectors. Orthogonal to the model source and required by both.
-
std::vector<double> error_rate_vec
Error probability per H column. Input YAML also accepts the established
decoder_custom_args.error_rate_vecspelling, and emitted YAML uses that spelling to preserve the researcher-facing wire format.
-
std::optional<cudaq::qec::dem_chunks_spec> dem_chunks
Optional per-phase DEM for a streaming, repeated-round decomposition. H_sparse above describes the whole experiment as one flat matrix; these phases describe one round each so the round count can be chosen at run time. num_rounds lives inside dem_chunks_spec. See cudaq::qec::dem_chunks_from_spec() for expansion to a chunk sequence.
A configuration that also has a nonempty H_sparse is flat, and that matrix is the one decoders are built from. Form selection keys off H_sparse.empty(). Nonempty H_sparse is exactly the state expand_dem_chunks() leaves behind, allowing round-trip through YAML.
-
std::string dem_chunks_artifact
The data_artifacts entry
dem_chunksnames, if it names one rather than holding the block; dem_chunks is then a copy of that entry’s template.
-
struct task_graph_spec
Decoder task graph topology. When set,
typemust be absent and eitherdem_chunksor the flat matrices supply the DEM.Two forms, mutually exclusive:
Single node, named by
typeandinner_type.decoder_custom_argsare forwarded to the inner decoder.typeis a node kind, in any spelling the registry accepts: “sliding_window” for a window that advances one round per decode, or “single_window” for one window over a fixed round count (which needs that count:H_sparseordem_chunks.num_rounds).nodesandedges, describing an arbitrary topology. A node names a registered node kind or a decoder plugin (see registered_task_graph_node_kinds()), carries that kind’s parameters inline, and may override the DEM.edgesmay be omitted for a single node, which is wiredmeasurements -> node -> output.
Public Members
-
std::string type
single-node form: node kind
-
std::string inner_type
single-node form: inner decoder registry name
-
cudaq::qec::task_graph_options options
Construction-time streaming execution policy. Async mode is opt-in.
-
std::vector<cudaq::qec::task_graph_edge> edges
The graph’s wires, in the same form from_topology() takes, so the configuration is the topology rather than a parallel description of it. YAML writes an endpoint as
nodeornode.portand omits the port when it is the default one task_graph_edge fills in.
-
struct column_range
A range of DEM fault columns a node owns,
[lo, hi]inclusive.
-
struct node_spec
Public Functions
-
std::string resolved_kind() const
The node kind this node builds:
typeresolved to its canonical name when it names a registered kind, otherwise the default kind, becausetypethen named a decoder plugin instead.
-
std::string resolved_decoder_type() const
The inner decoder plugin:
inner_type, ortypewhen that named a plugin rather than a node kind. Empty for a kind wrapping no decoder.
Public Members
-
std::string type
A registered node kind (canonical or aliased spelling), or a decoder plugin name, in which case the kind defaults to “sliding_window”.
-
std::string inner_type
Inner decoder plugin name, when
typenamed a node kind.
-
decoder_custom_args_t decoder_custom_args
The inner decoder’s constructor arguments, from either the
inner:block or a node-leveldecoder_custom_args:.
-
decoder_custom_args_t node_params
The node kind’s own parameters: window_size, step_size, guards, … Parsed against the schema registered for the resolved kind.
-
std::optional<cudaq::qec::dem_chunks_spec> dem_chunks
DEM for this node alone; falls back to the entry-level DEM.
-
std::string dem_chunks_artifact
The data_artifacts entry
dem_chunksnames, if it names one; the field above is then a copy of that entry’s template.
-
std::vector<cudaq::qec::experimental::ingest_window> windows
An ingest node’s layers, sorted by name: each names an output port and the window request published on it. Their order carries no meaning; parsing YAML sorts them by name, so keep a hand-built list sorted for it to round-trip equal. Experimental, as the request type is.
-
std::vector<std::int64_t> H_sparse
This node’s own matrices, in the entry-level flat form and the same -1-separated row encoding. Use them for a detector map that follows no round structure; a node takes these or
dem_chunks, never both.D_sparseandO_sparseare required together.block_sizeandsyndrome_sizegiveH_sparseits shape, which sparse rows do not carry.H_sparsealso builds this node’s inner decoder, along with itsdecoder_custom_args, so a node with its ownDandOneeds either anH_sparseor astim_dem.
-
std::string stim_dem
Stim DEM text to build the inner decoder from, in place of this node’s H — the YAML spelling of the string alternative of
decoder_init, for a decoder whose model needs annotations the matrices cannot carry. The text is inline, as everywhere else in this library: callers pass DEM contents, never a path. The node’s own D/O still come from its DEM, so the text describes the decoder and the chunks describe the window.
-
std::string stim_dem_path
The same model as
stim_dem, named by file rather than inlined, for callers who keep DEMs on disk. Read and folded intostim_dembefore the graph builder runs, so nothing downstream distinguishes the two spellings; setting both on one node is an error rather than a precedence.
-
std::string stim_dem_artifact
The data_artifacts entry
stim_demnames, if it names one; one of the two fields above is then a copy of that entry’s text or path.
-
std::uint64_t max_in_flight = 1
Copies of the node that may fire at once in asynchronous streaming; see
task_graph_node_config::max_in_flight.
-
std::string partition_label
Which DEM columns this node owns, as a label (“local”, “boundary”) or explicit ranges. Parsed, validated, and emitted; not yet honored at construction, which rejects a partitioned node.
-
struct ensemble_spec
The members and join of a node of type
ensemble, written as its own keys: member subgraphs raced against each other, one answer kept (the YAML spelling ofcudaq::qec::task_graph_ensemble_spec). The node fields above are ignored; the builder lowers the node.-
struct member
-
struct member
-
std::string resolved_kind() const
-
const std::string &effective_decoder_type() const
-
struct transport_shape_override
Transport override applied to the rings of one dispatch shape (see the
device_graphmember oftransport_config).Public Members
-
std::string provider
Provider name (e.g. udp, cpu_roce, gpu_roce) or /path/to/lib.so. A bare name resolves to the CUDA-Q realtime provider library whose soname is “libcudaq-realtime-bridge-” + name + “.so”, with ‘_’ in the name mapping to ‘-’ to match the shipped hyphenated sonames (so gpu_roce loads libcudaq-realtime-bridge-gpu-roce.so). Empty = inherit the section default.
-
std::vector<std::string> args
Extra provider arguments appended for this shape’s rings.
-
std::string provider
-
struct transport_config
Server-level transport section: the WIRE is deployment configuration and lives OUTSIDE the decoders list. Transports differ between rings only by dispatch shape (a device_graph ring must be GPU-pollable), so the only override is shape-keyed — decoder entries carry no transport information.
transport: provider: udp args: [—slot-size=256] device_graph: provider: udp # “gpu_roce” on an HSB rig args: [—pinned-rings]
Resolution per ring: shape override (device_graph rings) > this section’s provider/args. The standalone server permits a CLI fallback only for non-GPU-RoCE, host-only configurations whose YAML names no provider. A configuration containing device_graph dispatch or using GPU RoCE must define its provider and arguments in YAML (the deployment file is the source of truth for GPU-visible rings).
Public Functions
-
inline transport_shape_override resolve_device_graph() const
Resolve the provider and ordered arguments for a device-graph ring. The shape-specific provider overrides the section provider, while its arguments are appended to the section arguments.
-
inline transport_shape_override resolve_device_graph() const
-
struct syndrome_mapping_config
One row of the server’s syndrome mapping table.
A caller names a row per round through the
syndrome_mapping_idfield of an enqueue request. The row says what shape that round has, and per virtual port which round-relative detector indices the port’s bits scatter into.The shape is what carries end-of-shot: a decoder that decides its length at run time cannot see the end in the syndrome stream alone, because the last round’s fault set differs from a bulk round’s. Naming a
finalrow conveys it, with nothing added to the wire.syndrome_mapping: - id: 0 type: bulk vps: [[]] # one virtual port, pass-through - id: 1 type: final vps: [[]]
Public Functions
-
void validate() const
Throw std::runtime_error if the row is not well formed.
Public Members
-
uint64_t id = 0
Row key; the value a caller places in an enqueue request.
-
std::string type = "bulk"
Round shape: “bulk” (mid-circuit) or “final” (last round of a shot).
-
std::vector<std::vector<uint64_t>> vps = {{}}
Per virtual port, the round-relative detector indices that port’s bits scatter into. An empty list is the pass-through identity: the fragment becomes the round at whatever length it arrived, which is what lets a caller batch a whole round into one message.
Defaults to one pass-through port; only that is accepted today, so a row need not name it. See validate().
-
void validate() const
-
class multi_decoder_config
Public Functions
-
void validate_syndrome_mapping() const
Throw std::runtime_error if the syndrome mapping table is malformed: an unknown round shape, a duplicate row key, or a row that validate() refuses. Called by from_yaml_str() and again where the table is built, so a programmatically assembled config cannot skip it.
-
void validate_custom_args() const
Validate every decoder’s custom args (see decoder_config::validate_custom_args).
Public Members
-
std::vector<data_artifact> data_artifacts
Named data, sorted by name, that decoders and nodes reference. References are resolved when the configuration is parsed.
-
transport_config transport
Optional server-level transport section. The standalone server’s CLI defaults may fill an empty section only for non-GPU-RoCE, host-only configurations.
-
std::vector<syndrome_mapping_config> syndrome_mapping
Optional syndrome mapping table. When empty the server installs a single pass-through
bulkrow under id 0, which is what every configuration written before this section existed gets.
-
void validate_syndrome_mapping() const
-
int cudaq::qec::decoding::config::configure_decoders(multi_decoder_config &config)
Configure the decoders (
multi_decoder_configvariant). This function configures both local decoders, and if running on remote target hardware, will submit the configuration to the remote target for further processing.- Parameters:
config – The configuration to use.
- Returns:
0 on success, non-zero on failure.
-
int cudaq::qec::decoding::config::configure_decoders(multi_decoder_config &config, const std::filesystem::path &base_dir)
Configure the decoders, resolving relative model paths (such as
stim_dem_path) againstbase_dir. The overload above uses the process working directory as it stands when resolution starts.- Returns:
0 on success, non-zero on failure.
-
int cudaq::qec::decoding::config::configure_decoders_from_file(const char *config_file)
Configure the decoders from a file. This function configures both local decoders, and if running on remote target hardware, will submit the configuration to the remote target for further processing.
- Parameters:
config_file – The file to read the configuration from.
- Returns:
0 on success, non-zero on failure.
-
int cudaq::qec::decoding::config::configure_decoders_from_str(const char *config_str)
Configure the decoders from a string. This function configures both local decoders, and if running on remote target hardware, will submit the configuration to the remote target for further processing.
- Parameters:
config_str – The string to read the configuration from.
- Returns:
0 on success, non-zero on failure.
-
void cudaq::qec::decoding::config::finalize_decoders()
Finalize the decoders. This function finalizes local decoders.
-
std::optional<cudaq::qec::detector_error_model> cudaq::qec::decoding::config::expand_dem_chunks(decoder_config &config)
Rewrite a chunk-form configuration into the equivalent flat form, filling block_size, syndrome_size, H_sparse, O_sparse, D_sparse and error_rate_vec from
dem_chunksexpandednum_roundstimes. Decoder construction does not need this: it keeps the chunk form (see decoder_init::from_dem_chunks_closed()).Does nothing to a configuration that is already flat (one whose
H_sparseis nonempty, or which carries nodem_chunksat all), so it is safe to call unconditionally. An empty H_sparse with dem_chunks present is still treated as chunk form.- Throws:
std::runtime_error – if
num_roundsis missing, or if the phases cannot be expanded to that many rounds.- Returns:
The closed DEM the flat fields were derived from, so a caller that also wants its per-fault priors does not have to expand a second time. Empty when the configuration was already flat.
Helper Functions
Realtime decoding requires converting matrices to sparse format for efficient decoder configuration. The following utility functions are essential:
cudaq::qec::pcm_to_sparse_vec()for converting a dense PCM to a sparse PCM.cudaq::qec::pcm_from_sparse_vec()for converting a sparse PCM to a dense PCM.cudaq::qec::d_sparse()for converting anM2DSparseMatrix(obtained from acudaq::qec::decoder_inputscomponent) into the-1-terminated sparse vector a decoder config expects forD_sparse.Usage in realtime decoding:
auto ctx = cudaq::qec::decoder_context_from_memory_circuit( code, statePrep, numRounds, noise); auto inputs = ctx.z_component(); // or x_component() / full_component() config.H_sparse = cudaq::qec::pcm_to_sparse_vec(inputs.dem.detector_error_matrix); config.O_sparse = cudaq::qec::pcm_to_sparse_vec(inputs.dem.observables_flips_matrix); config.D_sparse = cudaq::qec::d_sparse(inputs.m2d);
See also Parity Check Matrix Utilities for additional PCM manipulation functions.
Realtime Pipeline API
The realtime pipeline API provides the reusable host-side runtime for
low-latency QEC pipelines that combine GPU inference with optional CPU
post-processing. The published reference is generated from
cudaq/qec/realtime/pipeline.h.
Note
This API is experimental and subject to change.
Configuration
-
struct core_pinning
CPU core affinity settings for pipeline threads.
Public Members
-
int dispatcher = -1
Core for the host dispatcher thread. -1 disables pinning.
-
int consumer = -1
Core for the consumer (completion) thread of the internal ring. -1 disables pinning.
-
int worker_base = -1
Base core for worker threads. Workers pin to base, base+1, etc. -1 disables pinning.
-
int dispatcher = -1
-
struct pipeline_stage_config
Configuration for a single pipeline stage.
Public Members
-
int num_workers = 8
Number of GPU worker threads (max 64).
-
int num_slots = 32
Number of ring buffer slots.
-
size_t slot_size = 16384
Size of each ring buffer slot in bytes.
-
core_pinning cores
CPU core affinity settings.
-
void *external_ringbuffer = nullptr
When non-null, the pipeline uses this caller-owned ring buffer (cudaq_ringbuffer_t*) instead of allocating its own. The caller is responsible for lifetime. ring_buffer_injector is unavailable in this mode (the FPGA/emulator owns the producer side).
The ring’s host views must be set and its RX/TX strides must match the transport’s slot size.
Slot ownership: the transport publishes a frame by storing the RX slot’s host address into rx_flags. From the moment the dispatcher takes that request until its response is published, the slot (its rx_flag, TX slot and request state) belongs to the pipeline; publish() hands it back by storing 0 into rx_flags. A transport that publishes into a page only once its rx_flag is 0 (the GpuRoce transceiver) therefore never presents two requests from one slot at a time. The page bytes are not covered by that: the GpuRoce transceiver re-arms a page’s receive as soon as it publishes a frame, so they stay valid only until num_slots more frames have arrived. The pipeline takes what it needs at dispatch, and stages read cpu_stage_context::request_id and ptp_timestamp rather than the RX slot. Responses are written through cpu_stage_context::response_buffer (the TX slot) and published by storing the TX slot’s host address into tx_flags, which the transport consumes and clears itself; a slot whose previous response the transport has not taken yet is not dispatched. The completion handler runs on the publishing thread in this mode.
-
int num_workers = 8
GPU Stage
-
struct gpu_worker_resources
Per-worker GPU resources returned by the gpu_stage_factory.
Each worker owns a captured CUDA graph, a dedicated stream, and optional pre/post launch callbacks for DMA staging or result extraction.
Public Members
-
cudaGraphExec_t graph_exec = nullptr
Instantiated CUDA graph for this worker.
-
cudaStream_t stream = nullptr
Dedicated CUDA stream for graph launches.
-
void (*pre_launch_fn)(void *user_data, void *slot_dev, cudaStream_t stream) = nullptr
Optional callback invoked before graph launch (e.g. DMA copy).
-
void *pre_launch_data = nullptr
Opaque user data passed to
pre_launch_fn.
-
void (*post_launch_fn)(void *user_data, void *slot_dev, cudaStream_t stream) = nullptr
Optional callback invoked after graph launch.
-
void *post_launch_data = nullptr
Opaque user data passed to
post_launch_fn.
-
uint32_t function_id = 0
RPC function ID that this worker handles.
-
void *user_context = nullptr
Opaque user context passed to cpu_stage_callback.
-
cudaGraphExec_t graph_exec = nullptr
-
using cudaq::qec::realtime::experimental::gpu_stage_factory = std::function<gpu_worker_resources(int worker_id)>
Factory called once per worker during start().
- Param worker_id:
Zero-based worker index assigned by the pipeline.
- Return:
GPU resources for the given worker. Any handles, callbacks, and user data returned here must remain valid until the pipeline stops.
CPU Stage
-
struct cpu_stage_context
Context passed to the CPU stage callback for each completed GPU workload.
The callback reads
gpu_output, performs post-processing (e.g. MWPM decoding), and writes the result intoresponse_buffer.Public Members
-
int worker_id
Index of the worker thread invoking this callback.
-
int origin_slot
Ring buffer slot that originated this request.
-
uint64_t request_id
Request id of this request, taken from the RPC header at dispatch (the injector’s 64-bit id on the internal ring).
-
uint64_t ptp_timestamp
PTP timestamp of this request, taken from the RPC header at dispatch. Use these two fields rather than re-reading the RX slot: on an external ring the transport may overwrite the page one ring lap after it was published.
-
const void *gpu_output
Pointer to GPU inference output (nullptr in poll mode).
-
size_t gpu_output_size
Size of GPU output in bytes.
-
void *response_buffer
Host pointer to the TX slot of
origin_slot:write the RPCResponse header followed by the payload here before returning a byte count or, after DEFERRED_COMPLETION, before calling realtime_pipeline::complete_deferred(). On the internal ring this is the RX slot itself, so read the request fields before writing.
-
size_t max_response_size
Capacity of
response_bufferin bytes (the TX slot stride).
-
void *user_context
Opaque user context from gpu_worker_resources::user_context.
-
int worker_id
-
using cudaq::qec::realtime::experimental::cpu_stage_callback = std::function<size_t(const cpu_stage_context &ctx)>
CPU stage callback type.
- Param ctx:
Poll-mode view of the current worker state and response buffer.
- Return:
Number of bytes written into
ctx.response_buffer. Return 0 if no GPU result is ready yet (poll again). Return DEFERRED_COMPLETION to release the worker immediately while deferring slot completion to a later complete_deferred() call.
-
static constexpr size_t cudaq::qec::realtime::experimental::DEFERRED_COMPLETION = SIZE_MAX
Sentinel return value from cpu_stage_callback: release the worker but do NOT publish the slot’s response. The caller is responsible for calling realtime_pipeline::complete_deferred(slot) once the deferred work (e.g. a separate decode thread) has written the response into cpu_stage_context::response_buffer.
Completion
-
struct completion
Metadata for a completed (or errored) pipeline request.
Public Members
-
uint64_t request_id
Original request ID from the RPC header.
-
int slot
Ring buffer slot that held this request.
-
bool success
False when the graph launch for this request failed, or when the dispatcher dropped the request (bad framing in an internal-ring slot the injector filled); no response is published for a dropped request.
-
int cuda_error
cudaError_t of a failed cudaGraphLaunch (0 on success and for a dropped request). The TX slot then holds an RPCResponse whose status carries the same code.
-
uint64_t request_id
-
using cudaq::qec::realtime::experimental::completion_callback = std::function<void(const completion &c)>
Callback invoked for each completed request: on the consumer thread for the internal ring, on the thread that publishes the response for an external ring (a worker thread, the complete_deferred() caller, or the dispatcher after a failed launch), and on the dispatcher thread for a request it dropped.
- Param c:
Metadata for the completed or errored request.
Ring Buffer Injector
-
class ring_buffer_injector
Writes RPC-framed requests into the pipeline’s ring buffer, simulating FPGA DMA deposits.
Created via realtime_pipeline::create_injector(). The parent realtime_pipeline must outlive the injector. Not available when the pipeline is configured with an external ring buffer.
Public Functions
-
~ring_buffer_injector()
Destroy the injector state.
-
ring_buffer_injector(ring_buffer_injector&&) noexcept
Move-construct an injector.
-
ring_buffer_injector &operator=(ring_buffer_injector&&) noexcept
Move-assign an injector.
-
bool try_submit(uint32_t function_id, const void *payload, size_t payload_size, uint64_t request_id)
Try to submit a request without blocking.
- Parameters:
function_id – RPC function identifier.
payload – Pointer to the payload data.
payload_size – Size of the payload in bytes.
request_id – Caller-assigned request identifier.
- Throws:
std::invalid_argument – If the pipeline is started and no worker serves
function_id.- Returns:
True if accepted, false if all slots are busy (backpressure) or the pipeline is stopping or stopped.
-
void submit(uint32_t function_id, const void *payload, size_t payload_size, uint64_t request_id)
Submit a request, spinning until a slot becomes available.
- Throws:
std::invalid_argument – If the pipeline is started and no worker serves
function_id.- Parameters:
function_id – RPC function identifier.
payload – Pointer to the payload data.
payload_size – Size of the payload in bytes.
request_id – Caller-assigned request identifier.
-
~ring_buffer_injector()
Pipeline
-
class realtime_pipeline
Orchestrates GPU inference and CPU post-processing for low-latency realtime QEC decoding.
The pipeline manages a ring buffer, its own host dispatcher thread (which polls the ring’s RX flags and launches the per-worker CUDA graphs), per-worker GPU streams with captured CUDA graphs, optional CPU worker threads for post-processing (e.g. PyMatching), and completion reporting. It supports both an internal ring buffer (for software testing via ring_buffer_injector, harvested by a consumer thread) and an external ring buffer (for FPGA RDMA, where the transport consumes the responses).
Public Functions
-
explicit realtime_pipeline(const pipeline_stage_config &config)
Construct a pipeline and allocate ring buffer resources.
Note
Construction allocates the backing ring buffer or binds the caller-provided external ring so ringbuffer_bases can be queried before start.
- Parameters:
config – Stage configuration (slots, slot size, workers, etc.).
-
~realtime_pipeline()
Stop the pipeline if needed and release owned resources.
-
void set_gpu_stage(gpu_stage_factory factory)
Register the GPU stage factory. Must be called before start().
- Parameters:
factory – Callback that returns gpu_worker_resources per worker.
-
void set_cpu_stage(cpu_stage_callback callback)
Register the CPU worker callback. Must be called before start().
- Parameters:
callback – Function invoked by each worker thread to poll for and process completed GPU workloads. If not set, the pipeline operates in GPU-only mode: completion is signaled from a host callback (cudaLaunchHostFunc) enqueued on the worker stream after the graph, and the graph or post_launch_fn owns the TX slot content (the pipeline writes no RPCResponse). GPU-only mode requires the internal ring.
-
void set_completion_handler(completion_callback handler)
Register the completion callback. Must be called before start().
- Parameters:
handler – Function invoked for each completed or errored request (see completion_callback for the calling thread).
-
void start()
Build the worker resources and spawn the dispatcher, worker, and consumer threads.
Note
The factory’s streams and graphs must belong to the CUDA device current on the thread calling start(); the pipeline’s threads select that device.
- Throws:
std::logic_error – If the GPU stage factory was not registered.
std::logic_error – If GPU-only mode (no CPU stage) is combined with an external ring buffer: nothing would frame an RPCResponse in the TX slot for the transport to send.
std::logic_error – If the pipeline was stopped before: a pipeline is single use, construct a new one instead.
-
void stop()
Signal shutdown, join all threads, free resources.
Note
Safe to call multiple times. Subsequent calls are no-ops once the pipeline has fully stopped, and the pipeline cannot be started again.
-
ring_buffer_injector create_injector()
Create a software injector for testing without FPGA hardware.
- Throws:
std::logic_error – if the pipeline uses an external ring buffer.
- Returns:
A ring_buffer_injector bound to this pipeline’s ring buffer.
-
void complete_deferred(int slot)
Signal that deferred processing for a slot is complete.
Call from any thread after the cpu_stage callback returned DEFERRED_COMPLETION and the deferred work has finished writing the response into the slot’s TX area (cpu_stage_context::response_buffer). Publishes the TX slot’s host address into tx_flags; on an external ring the completion handler runs on the calling thread and the RX slot is handed back to the transport (see pipeline_stage_config::external_ringbuffer).
- Parameters:
slot – Ring buffer slot index to complete.
-
ring_buffer_bases ringbuffer_bases() const
Return the host and device base addresses of the RX data ring.
Note
In external-ring mode these pointers are the caller-provided ring addresses. In internal mode they refer to the owned mapped ring buffer.
- Returns:
Struct containing both base pointers.
-
struct ring_buffer_bases
Host and device base addresses of the RX data ring.
-
struct Stats
Pipeline throughput and backpressure statistics.
Public Members
-
uint64_t submitted
Total requests submitted to the ring buffer.
-
uint64_t completed
Total requests that completed (success or error).
-
uint64_t dispatched
Total requests handed to a worker (graph launch attempted); dropped requests (bad magic, unknown function id) are not counted.
-
uint64_t backpressure_stalls
Cumulative producer backpressure stalls.
-
uint64_t submitted
-
explicit realtime_pipeline(const pipeline_stage_config &config)
Parity Check Matrix Utilities
The utilities below create, convert, inspect, and transform parity-check
matrices (PCMs). CUDA-Q QEC supports dense matrices as
cudaqx::tensor<std::uint8_t> and sparse matrices as
sparse_binary_matrix. Decoder entry points accept either representation
and store the PCM internally as a sparse matrix.
sparse_binary_matrix stores a binary matrix in compressed sparse column
(CSC) or compressed sparse row (CSR) layout without storing values for its
nonzero entries. Input indices are preserved as supplied. Use
cudaq::qec::sparse_binary_matrix::canonicalize() when duplicate
indices should be combined over GF(2) and each compressed row or column should
be sorted. Canonicalization preserves the matrix layout. The matrix uses
std::uint32_t indices, so each dimension and the number of stored entries
must fit in that type.
Sparse utility overloads operate without materializing the full input as a
dense tensor. Use
cudaq::qec::generate_random_pcm_sparse() when a generated PCM would
be impractical to allocate densely. The dense generator remains available and
rejects dimensions whose products overflow std::size_t.
-
enum class cudaq::qec::sparse_binary_matrix_layout
Storage layout for the sparse PCM: Compressed Sparse Column (CSC) or Compressed Sparse Row (CSR). All non-zero entries are assumed to be 1; values are not stored.
Values:
-
enumerator csc
-
enumerator csr
-
enumerator csc
-
class sparse_binary_matrix
Sparse parity-check matrix in either CSC or CSR form.
Input index lists are stored as given: not required to be sorted or GF(2)-unique. Consumers that require cuSPARSE-style compressed groups can call
validate_sorted_unique_indices; consumers that need GF(2)-collapsed per-group indices can callcanonicalizeon entry.index_typeisuint32_t, so each dimension andnnzmust fit in~4×10^9.Public Functions
-
sparse_binary_matrix(const cudaqx::tensor<std::uint8_t> &dense, sparse_binary_matrix_layout layout = sparse_binary_matrix_layout::csc)
Construct from a rank-2 dense PCM (any non-zero treated as 1). Intentionally not
explicitso call sites that takesparse_binary_matrixaccept a densecudaqx::tensorunchanged.
-
inline const std::vector<index_type> &ptr() const
For CSC: ptr has length num_cols+1; for CSR: ptr has length num_rows+1.
-
inline const std::vector<index_type> &indices() const
For CSC: row indices; for CSR: column indices.
-
void validate_sorted_unique_indices(const char *context = "sparse_binary_matrix") const
Throw if each compressed column/row does not have strictly increasing indices. This rejects duplicate entries in the stored layout.
-
sparse_binary_matrix canonicalize() const
Return a GF(2)-canonical copy: each compressed column/row has its indices sorted ascending, and duplicate indices are XOR-merged. An index that appears k times is kept iff k is odd. The output has the same layout as the input and is idempotent under further
canonicalizecalls.Use this when a PCM source, such as a DEM decomposition, may emit duplicate indices within a compressed group and the caller wants GF(2) duplicate-collapse semantics before passing the matrix to consumers that require at most one entry per row/column.
-
sparse_binary_matrix to_csc() const
Return a copy of this matrix in CSC layout. No-op if already CSC.
-
sparse_binary_matrix to_csr() const
Return a copy of this matrix in CSR layout. No-op if already CSR.
-
cudaqx::tensor<std::uint8_t> to_dense() const
Convert to a dense PCM tensor (rows x columns). Non-zero entries are set to 1.
-
std::vector<std::vector<index_type>> to_nested_csc() const
Nested CSC: outer vector has size num_cols; inner vector for column j lists row indices of non-zeros in that column.
-
std::vector<std::vector<index_type>> to_nested_csr() const
Nested CSR: outer vector has size num_rows; inner vector for row i lists column indices of non-zeros in that row.
Public Static Functions
-
static sparse_binary_matrix from_csc(index_type num_rows, index_type num_cols, std::vector<index_type> col_ptrs, std::vector<index_type> row_indices)
Construct a sparse PCM in CSC form.
- Parameters:
num_rows – Number of rows.
num_cols – Number of columns.
col_ptrs – Column pointer array (length num_cols + 1); column j has indices in
row_indices[col_ptrs[j] .. col_ptrs[j+1]-1].row_indices – Row indices of non-zeros (length nnz).
-
static sparse_binary_matrix from_csr(index_type num_rows, index_type num_cols, std::vector<index_type> row_ptrs, std::vector<index_type> col_indices)
Construct a sparse PCM in CSR form.
- Parameters:
num_rows – Number of rows.
num_cols – Number of columns.
row_ptrs – Row pointer array (length num_rows + 1); row i has indices in
col_indices[row_ptrs[i] .. row_ptrs[i+1]-1].col_indices – Column indices of non-zeros (length nnz).
-
static sparse_binary_matrix from_nested_csc(index_type num_rows, index_type num_cols, const std::vector<std::vector<index_type>> &nested)
Construct from nested CSC:
nested[j] is the list of row indices for column j;nested.size()must equalnum_cols.
-
static sparse_binary_matrix from_nested_csr(index_type num_rows, index_type num_cols, const std::vector<std::vector<index_type>> &nested)
Construct from nested CSR:
nested[i] is the list of column indices for row i;nested.size()must equalnum_rows.
-
sparse_binary_matrix(const cudaqx::tensor<std::uint8_t> &dense, sparse_binary_matrix_layout layout = sparse_binary_matrix_layout::csc)
-
cudaqx::tensor<uint8_t> cudaq::qec::to_parity_matrix(const std::vector<cudaq::spin_op_term> &stabilizers, stabilizer_type type = stabilizer_type::XZ)
Convert stabilizers to a parity check matrix
- Returns:
Tensor representing the parity check matrix
-
cudaqx::tensor<uint8_t> cudaq::qec::to_parity_matrix(const std::vector<std::string> &words, stabilizer_type type = stabilizer_type::XZ)
-
std::vector<std::vector<std::uint32_t>> cudaq::qec::dense_to_sparse(const cudaqx::tensor<uint8_t> &pcm)
Return a sparse representation of the PCM.
- Parameters:
pcm – The PCM to convert to a sparse representation.
- Returns:
A vector of vectors that sparsely represents the PCM. The size of the outer vector is the number of columns in the PCM, and the i-th element contains an inner vector of the row indices of the non-zero elements in the i-th column of the PCM.
-
cudaqx::tensor<uint8_t> cudaq::qec::generate_random_pcm(std::size_t n_rounds, std::size_t n_errs_per_round, std::size_t n_syndromes_per_round, int weight, std::mt19937_64 &&rng)
Generate a random PCM with the given parameters.
The PCM has shape
(n_rounds * n_syndromes_per_round) × (n_rounds * n_errs_per_round).- Parameters:
n_rounds – The number of rounds in the PCM.
n_errs_per_round – The number of errors per round in the PCM.
n_syndromes_per_round – The number of syndromes per round in the PCM.
weight – The column weight of the PCM.
rng – The random number generator to use (e.g. std::mt19937_64(your_seed))
- Returns:
A random PCM with the given parameters.
-
sparse_binary_matrix cudaq::qec::generate_random_pcm_sparse(std::size_t n_rounds, std::size_t n_errs_per_round, std::size_t n_syndromes_per_round, int weight, std::mt19937_64 &&rng)
Same distribution as generate_random_pcm, but constructs a CSC sparse_binary_matrix directly without allocating a dense rank-2 tensor. Intended for large PCMs whose dense form would be impractical or impossible to allocate.
-
std::vector<std::int64_t> cudaq::qec::generate_timelike_sparse_detector_matrix(std::uint32_t num_syndromes_per_round, std::uint32_t num_rounds, bool include_first_round = false)
Generate a sparse detector matrix for a given number of syndromes per round and number of rounds. Timelike here means that each round of syndrome bits are xor’d against the preceding round.
- Parameters:
num_syndromes_per_round – The number of syndromes per round.
num_rounds – The number of rounds.
include_first_round – Whether to include the first round in the detector matrix.
- Returns:
The detector matrix format is CSR-like, with -1 values indicating the end of a row.
-
std::vector<std::int64_t> cudaq::qec::generate_timelike_sparse_detector_matrix(std::uint32_t num_syndromes_per_round, std::uint32_t num_rounds, std::vector<std::int64_t> first_round_matrix)
Generate a sparse detector matrix for a given number of syndromes per round and number of rounds. Timelike here means that each round of syndrome bits are xor’d against the preceding round. The first round is supplied by the user, to allow for a mixture of detectors and non-detectors.
- Parameters:
num_syndromes_per_round – The number of syndromes per round.
num_rounds – The number of rounds.
first_round_matrix – User specified detector matrix for the first round.
- Returns:
The detector matrix format is CSR-like, with -1 values indicating the end of a row.
-
std::tuple<cudaqx::tensor<uint8_t>, std::uint32_t, std::uint32_t> cudaq::qec::get_pcm_for_rounds(const cudaqx::tensor<uint8_t> &pcm, std::uint32_t num_syndromes_per_round, std::uint32_t start_round, std::uint32_t end_round, bool straddle_start_round = false, bool straddle_end_round = false, std::uint32_t num_boundary_syndromes = 0)
Get a sub-PCM for a range of rounds. It is recommended (but not required) that you call sort_pcm_columns() before calling this function.
- Parameters:
pcm – The PCM to get a sub-PCM for.
num_syndromes_per_round – The number of syndromes per round.
start_round – The start round (0-based).
end_round – The end round (0-based).
straddle_start_round – Whether to include columns that straddle the start_round (defaults to false)
straddle_end_round – Whether to include columns that straddle the end_round (defaults to false)
num_boundary_syndromes – Width of the narrower first/last boundary rounds for a non-uniform [B | K*S | B] detector layout (0 == uniform).
- Returns:
A tuple with the new PCM with the columns in the range [start_round, end_round], the first column included, and the last column included.
-
std::tuple<cudaqx::tensor<uint8_t>, std::uint32_t, std::uint32_t> cudaq::qec::get_pcm_for_rounds(const sparse_binary_matrix &pcm, std::uint32_t num_syndromes_per_round, std::uint32_t start_round, std::uint32_t end_round, bool straddle_start_round = false, bool straddle_end_round = false, bool pcm_is_canonical = false, std::uint32_t num_boundary_syndromes = 0)
Same semantics as the overload taking a dense tensor
pcm, but reads frompcmassparse_binary_matrixso the full dense PCM is not required (only the returned sub-matrix is dense). Parameter meanings match the dense overload.Warning
When
pcm_is_canonicalistruethe precondition is not checked.select_pcm_columns_for_round_rangereads.front()/.back()of each CSC column to derive first/last round; those are only the true min/max row if the column list is sorted-unique. Passing a non-canonical PCM with this flag (e.g. a raw DEM decomposition, a hand-built sparse matrix with duplicate or unsorted indices, or a canonical CSR that the caller forgot to re-canonicalize after conversion) silently produces wrong round assignments. If unsure, leave the flagfalse.- Parameters:
pcm – The PCM to get a sub-PCM for.
num_syndromes_per_round – The number of syndromes per round.
start_round – The start round (0-based).
end_round – The end round (0-based).
straddle_start_round – Whether to include columns that straddle the start_round (defaults to false)
straddle_end_round – Whether to include columns that straddle the end_round (defaults to false)
pcm_is_canonical – If true, the caller asserts
pcmhas sorted-unique per-group indices (i.e. is the output ofsparse_binary_matrix::canonicalizeor was constructed canonically). In that case the per-call canonicalization step is skipped — useful for callers likesliding_windowthat canonicalize once at construction and then call this function in a per-window loop on the same matrix. Defaultfalsepreserves the original “canonicalize on entry” behavior.num_boundary_syndromes – Width of the narrower first/last boundary rounds for a non-uniform [B | K*S | B] detector layout (0 == uniform).
- Returns:
A tuple with the new PCM with the columns in the range [start_round, end_round], the first column included, and the last column included.
-
std::vector<std::uint32_t> cudaq::qec::get_sorted_pcm_column_indices(const std::vector<std::vector<std::uint32_t>> &row_indices, std::uint32_t num_syndromes_per_round = 0)
Return a vector of column indices that would sort the PCM columns in topological order.
This function tries to make a matrix that is close to a block diagonal matrix from its input. Columns are first sorted by the index of the first non-zero entry in the column, and if those match, then they are sorted by the index of the last non-zero entry in the column. This ping pong continues for the indices of the second non-zero element and the second-to-last non-zero element, and so forth.
- Parameters:
row_indices – For each column, a vector of row indices that have a non-zero value in that column.
num_syndromes_per_round – The number of syndromes per round. (Defaults to 0, which means that no secondary per-round sorting will occur.)
-
std::vector<std::uint32_t> cudaq::qec::get_sorted_pcm_column_indices(const std::vector<std::vector<std::uint32_t>> &row_indices, std::uint32_t num_syndromes_per_round, std::uint32_t num_boundary_syndromes)
Boundary-aware overload of the above: the first and last
num_boundary_syndromesrows form the boundary rounds and each interior round spansnum_syndromes_per_roundrows. throws std::invalid_argument ifnum_syndromes_per_roundis zero ornum_boundary_syndromes>num_syndromes_per_round.
-
std::vector<std::uint32_t> cudaq::qec::get_sorted_pcm_column_indices(const cudaqx::tensor<uint8_t> &pcm, std::uint32_t num_syndromes_per_round = 0)
Return a vector of column indices that would sort the PCM columns in topological order.
- Parameters:
pcm – The PCM to sort.
num_syndromes_per_round – The number of syndromes per round. (Defaults to 0, which means that no secondary per-round sorting will occur.)
-
std::pair<cudaqx::tensor<uint8_t>, std::vector<std::uint32_t>> cudaq::qec::pcm_extend_to_n_rounds(const cudaqx::tensor<uint8_t> &pcm, std::size_t num_syndromes_per_round, std::uint32_t n_rounds)
Extend a PCM to the given number of rounds.
- Parameters:
pcm – The PCM to extend.
num_syndromes_per_round – The number of syndromes per round.
n_rounds – The number of rounds to extend the PCM to.
- Returns:
A pair of the new PCM and the list of column indices from the original PCM that were used to form the new PCM.
-
cudaqx::tensor<uint8_t> cudaq::qec::pcm_from_sparse_string(const std::string &sparse_str, std::size_t num_rows, std::size_t num_cols)
Return a PCM from a sparse representation.
- Parameters:
sparse_str – The sparse representation of the PCM.
num_rows – The number of rows in the PCM.
num_cols – The number of columns in the PCM.
- Returns:
A PCM tensor.
-
cudaqx::tensor<uint8_t> cudaq::qec::pcm_from_sparse_vec(const std::vector<std::int64_t> &sparse_vec, std::size_t num_rows, std::size_t num_cols)
Return a PCM from a sparse representation.
- Parameters:
sparse_vec – The sparse representation of the PCM, where -1 separates rows.
num_rows – The number of rows in the PCM.
num_cols – The number of columns in the PCM.
- Returns:
A PCM tensor.
-
bool cudaq::qec::pcm_is_sorted(const cudaqx::tensor<uint8_t> &pcm, std::uint32_t num_syndromes_per_round = 0)
Check if a PCM is sorted.
- Parameters:
pcm – The PCM to check.
num_syndromes_per_round – The number of syndromes per round.
- Returns:
True if the PCM is sorted, false otherwise.
-
bool cudaq::qec::pcm_is_sorted(const std::vector<std::vector<std::uint32_t>> &sparse_pcm, std::uint32_t num_syndromes_per_round, std::uint32_t num_boundary_syndromes)
Boundary-aware overload of pcm_is_sorted: the first and last
num_boundary_syndromesrows form the boundary rounds and each interior round spansnum_syndromes_per_roundrows (a [B | K*S | B] layout).- Parameters:
sparse_pcm – The sparse PCM to check (in the same format as dense_to_sparse())
num_syndromes_per_round – The interior-round width.
num_boundary_syndromes – The width of the first/last boundary rounds.
- Returns:
True if the PCM is sorted for this boundary layout, false otherwise.
-
std::string cudaq::qec::pcm_to_sparse_string(const cudaqx::tensor<uint8_t> &pcm)
Return a sparse representation of the PCM as a string.
- Parameters:
pcm – The PCM to convert to a sparse representation.
- Returns:
A string that represents the PCM in a sparse format.
-
std::string cudaq::qec::pcm_to_sparse_string(const sparse_binary_matrix &pcm)
Sparse overload of pcm_to_sparse_string. Duplicate stored entries are canonicalized with GF(2) cancellation before serialization.
-
std::vector<std::int64_t> cudaq::qec::pcm_to_sparse_vec(const cudaqx::tensor<uint8_t> &pcm)
Return a sparse representation of the PCM.
- Parameters:
pcm – The PCM to convert to a sparse representation.
- Returns:
A vector of integers that represents the PCM in a sparse format, where -1 separates rows.
-
std::vector<std::int64_t> cudaq::qec::pcm_to_sparse_vec(const sparse_binary_matrix &pcm)
Sparse overload of pcm_to_sparse_vec. Duplicate stored entries are canonicalized with GF(2) cancellation before serialization.
-
cudaqx::tensor<uint8_t> cudaq::qec::reorder_pcm_columns(const cudaqx::tensor<uint8_t> &pcm, const std::vector<std::uint32_t> &column_order, uint32_t row_begin = 0, uint32_t row_end = std::numeric_limits<uint32_t>::max())
Reorder the columns of a PCM according to the given column order. Note: this may return a subset of the columns in the original PCM if the
column_orderdoes not contain all of the columns in the original PCM.- Parameters:
pcm – The PCM to reorder.
column_order – The column order to use for reordering.
row_begin – The first row to include in the reordering. Leave at the default value to include all rows.
row_end – The last row to include in the reordering. Leave at the default value to include all rows.
- Returns:
A new PCM with the columns reordered according to the given column order.
-
sparse_binary_matrix cudaq::qec::reorder_pcm_columns(const sparse_binary_matrix &pcm, const std::vector<std::uint32_t> &column_order, uint32_t row_begin = 0, uint32_t row_end = std::numeric_limits<uint32_t>::max())
Sparse overload of reorder_pcm_columns. Returns CSC.
-
cudaqx::tensor<uint8_t> cudaq::qec::shuffle_pcm_columns(const cudaqx::tensor<uint8_t> &pcm, std::mt19937_64 &&rng)
Randomly permute the columns of a PCM.
- Parameters:
pcm – The PCM to permute.
rng – The random number generator to use (e.g. std::mt19937_64(your_seed))
- Returns:
A new PCM with the columns permuted randomly.
-
sparse_binary_matrix cudaq::qec::shuffle_pcm_columns(const sparse_binary_matrix &pcm, std::mt19937_64 &&rng)
Sparse overload of shuffle_pcm_columns.
-
std::pair<cudaqx::tensor<uint8_t>, std::vector<double>> cudaq::qec::simplify_pcm(const cudaqx::tensor<uint8_t> &pcm, const std::vector<double> &weights, std::uint32_t num_syndromes_per_round = 0)
Simplify a PCM by removing duplicate columns and 0-weight columns, and combine the probability weight vectors accordingly.
- Parameters:
pcm – The PCM to simplify.
weights – The probability weight vectors to combine.
num_syndromes_per_round – The number of syndromes per round. (Defaults to 0, which means that no secondary per-round sorting will occur.)
- Returns:
A new PCM with the columns sorted in topological order, and the probability weight vectors combined accordingly.
-
cudaqx::tensor<uint8_t> cudaq::qec::sort_pcm_columns(const cudaqx::tensor<uint8_t> &pcm, std::uint32_t num_syndromes_per_round = 0)
Sort the columns of a PCM in topological order.
- Parameters:
pcm – The PCM to sort.
num_syndromes_per_round – The number of syndromes per round. (Defaults to 0, which means that no secondary per-round sorting will occur.)
- Returns:
A new PCM with the columns sorted in topological order.
Logger
The QEC logger API currently lives in cudaq::qec::detail and is used by
the CUDA_QEC_* macros exposed in cudaq/qec/logger.h.
-
enum class cudaq::qec::detail::log_level
Severity levels supported by the QEC logger.
Values:
-
enumerator trace
-
enumerator debug
-
enumerator info
-
enumerator warn
-
enumerator error
-
enumerator trace
-
enum class cudaq::qec::detail::forward_drop_policy
Queue backpressure policy for forwarded records.
Values:
-
enumerator drop_newest
-
enumerator drop_oldest
-
enumerator drop_newest
-
struct forwarded_log_record
Log payload forwarded to an optional background callback.
-
constexpr std::size_t cudaq::qec::detail::realtime_forwarder_default_message_capacity = 512
Default forwarded message payload capacity in bytes.
-
struct forwarder_config
Runtime configuration for asynchronous forwarding.
Public Members
-
std::function<void(forwarded_log_record&&)> callback
Callback executed on the forwarder worker thread.
The record is passed as an rvalue: the worker owns a fresh, per-record instance that is discarded after the callback returns, so a callback may move out of it (e.g.
std::move(record)to re-queue it) to avoid copying the heap-allocatedfile_name/messagestrings. Read-only callbacks takingconst ForwardedLogRecord &remain valid.
-
std::size_t queue_capacity = 1024
Bounded queue capacity (records), clamped to at least 1.
-
std::size_t message_capacity = realtime_forwarder_default_message_capacity
Max forwarded message bytes copied on producer path.
Values are clamped to [1, realtime_forwarder_max_message_capacity].
-
forward_drop_policy drop_policy = forward_drop_policy::drop_newest
Overflow policy when the forwarder queue is saturated.
-
std::function<void(forwarded_log_record&&)> callback
-
struct forwarder_stats
Runtime counters for asynchronous forwarding behavior.
Public Members
-
std::uint64_t enqueued_records = 0
Records successfully enqueued to the forwarder queue.
-
std::uint64_t dropped_records = 0
Records dropped due to queue saturation/overflow policy.
-
std::uint64_t truncated_records = 0
Records whose message payload was truncated to fit capacity.
-
std::uint64_t forward_failures = 0
Callback invocations that threw exceptions.
-
std::uint64_t enqueued_records = 0
-
bool cudaq::qec::detail::should_log(const log_level level)
Return true if the given level is currently enabled.
-
void cudaq::qec::detail::set_forwarder(forwarder_config config)
Install or replace the optional async forwarding callback.
-
void cudaq::qec::detail::set_forwarder()
Enable forwarding with a default worker callback to stdout/stderr.
-
std::size_t cudaq::qec::detail::get_forwarder_message_capacity()
Return active forwarded-message capacity in bytes.
-
forwarder_stats cudaq::qec::detail::get_forwarder_stats()
Return a snapshot of forwarding counters.
Common
-
enum class cudaq::qec::operation
Enum describing all supported logical operations.
Values:
-
enumerator x
Logical X gate.
-
enumerator y
Logical Y gate.
-
enumerator z
Logical Z gate.
-
enumerator h
Logical Hadamard gate.
-
enumerator s
Logical S gate.
-
enumerator cx
Logical controlled-X gate.
-
enumerator cy
Logical controlled-Y gate.
-
enumerator cz
Logical controlled-Z gate.
-
enumerator stabilizer_round
Stabilizer measurement round.
-
enumerator prep0
Prepare logical |0⟩ state.
-
enumerator prep1
Prepare logical |1⟩ state.
-
enumerator prepp
Prepare logical |+⟩ state.
-
enumerator prepm
Prepare logical |-⟩ state.
-
enumerator x
-
std::tuple<cudaqx::tensor<uint8_t>, cudaqx::tensor<uint8_t>> cudaq::qec::sample_code_capacity(const cudaqx::tensor<uint8_t> &H, std::size_t numShots, double error_probability)
Sample syndrome measurements with code capacity noise.
- Parameters:
H – Parity check matrix of a QEC code
numShots – Number of measurement shots
error_probability – Probability of bit flip on data
- Returns:
Tuple containing syndrome measurements and data qubit measurements
-
std::tuple<cudaqx::tensor<uint8_t>, cudaqx::tensor<uint8_t>> cudaq::qec::sample_code_capacity(const cudaqx::tensor<uint8_t> &H, std::size_t numShots, double error_probability, unsigned seed)
Sample syndrome measurements with code capacity noise.
- Parameters:
H – Parity check matrix of a QEC code
numShots – Number of measurement shots
error_probability – Probability of bit flip on data
seed – RNG seed for reproducible experiments
- Returns:
Tuple containing syndrome measurements and data qubit measurements
-
std::tuple<cudaqx::tensor<uint8_t>, cudaqx::tensor<uint8_t>> cudaq::qec::sample_code_capacity(const code &code, std::size_t numShots, double error_probability)
Sample syndrome measurements with code capacity noise.
- Parameters:
code – QEC Code to sample
numShots – Number of measurement shots
error_probability – Probability of bit flip on data
- Returns:
Tuple containing syndrome measurements and data qubit measurements
-
std::tuple<cudaqx::tensor<uint8_t>, cudaqx::tensor<uint8_t>> cudaq::qec::sample_code_capacity(const code &code, std::size_t numShots, double error_probability, unsigned seed)
Sample syndrome measurements with code capacity noise.
- Parameters:
code – QEC Code to sample
numShots – Number of measurement shots
error_probability – Probability of bit flip on data
seed – RNG seed for reproducible experiments
- Returns:
Tuple containing syndrome measurements and data qubit measurements
-
std::tuple<cudaqx::tensor<uint8_t>, cudaqx::tensor<uint8_t>> cudaq::qec::sample_memory_circuit(const code &code, std::size_t numShots, std::size_t numRounds = 1)
Sample syndrome measurements starting from |0⟩ state.
- Parameters:
code – QEC Code to sample
numShots – Number of measurement shots
numRounds – Number of stabilizer measurement rounds
- Returns:
Tuple of (syndromeTensor, dataResults), equivalent to the
operation::prep0overload ofsample_memory_circuit.
-
std::tuple<cudaqx::tensor<uint8_t>, cudaqx::tensor<uint8_t>> cudaq::qec::sample_memory_circuit(const code &code, std::size_t numShots, std::size_t numRounds, cudaq::noise_model &noise)
Sample syndrome measurements from |0⟩ state with noise.
- Parameters:
code – QEC Code to sample
numShots – Number of measurement shots
numRounds – Number of stabilizer measurement rounds
noise – Noise model to apply
- Returns:
Tuple of (syndromeTensor, dataResults), equivalent to the
operation::prep0overload ofsample_memory_circuit.
-
std::tuple<cudaqx::tensor<uint8_t>, cudaqx::tensor<uint8_t>> cudaq::qec::sample_memory_circuit(const code &code, operation statePrep, std::size_t numShots, std::size_t numRounds = 1)
Sample syndrome measurements from the memory circuit.
- Parameters:
code – QEC Code to sample
statePrep – Initial state preparation operation
numShots – Number of measurement shots
numRounds – Number of stabilizer measurement rounds
- Returns:
Tuple of (syndromeTensor, dataResults), equivalent to the
operation::prep0overload ofsample_memory_circuit.
-
std::tuple<cudaqx::tensor<uint8_t>, cudaqx::tensor<uint8_t>> cudaq::qec::sample_memory_circuit(const code &code, operation statePrep, std::size_t numShots, std::size_t numRounds, cudaq::noise_model &noise)
Sample syndrome measurements with circuit-level noise.
- Parameters:
code – QEC Code to sample
statePrep – Initial state preparation operation
numShots – Number of measurement shots
numRounds – Number of stabilizer measurement rounds
noise – Noise model to apply
- Returns:
Tuple of (syndromeTensor, dataResults).
syndromeTensorhas shape(numShots, numDetectors):numFixedboundary detectors (the stabilizer type matchingstatePrep’s basis, since only that type is deterministic at the circuit’s endpoints), then one detector block per each of thenumRounds - 1inter-round transitions, thennumFixedmore boundary detectors.dataResultshas shape(numShots, numDataQubits).
-
std::tuple<cudaqx::tensor<uint8_t>, cudaqx::tensor<uint8_t>> cudaq::qec::x_sample_memory_circuit(const code &code, operation statePrep, std::size_t numShots, std::size_t numRounds, cudaq::noise_model &noise)
Sample syndrome measurements with circuit-level noise, keeping only the X stabilizer syndromes.
- Parameters:
code – QEC Code to sample
statePrep – Initial state preparation operation
numShots – Number of measurement shots
numRounds – Number of stabilizer measurement rounds
noise – Noise model to apply
- Returns:
Tuple of (syndromeTensor, dataResults), same layout as
sample_memory_circuitbut restricted to X-stabilizer detector values.
-
std::tuple<cudaqx::tensor<uint8_t>, cudaqx::tensor<uint8_t>> cudaq::qec::z_sample_memory_circuit(const code &code, operation statePrep, std::size_t numShots, std::size_t numRounds, cudaq::noise_model &noise)
Sample syndrome measurements with circuit-level noise, keeping only the Z stabilizer syndromes.
- Parameters:
code – QEC Code to sample
statePrep – Initial state preparation operation
numShots – Number of measurement shots
numRounds – Number of stabilizer measurement rounds
noise – Noise model to apply
- Returns:
Tuple of (syndromeTensor, dataResults), same layout as
sample_memory_circuitbut restricted to Z-stabilizer detector values.