CUDA-Q QEC Python API

Code

class cudaq_qec.Code(*args, **kwargs)

Represents a quantum error correction code

contains_operation

Return true if this code contains the given operation encoding

get_num_ancilla_qubits

Total number of ancilla qubits required by the code.

get_num_ancilla_x_qubits

Number of X-type ancilla qubits used for X stabilizer measurements.

get_num_ancilla_z_qubits

Number of Z-type ancilla qubits used for Z stabilizer measurements.

get_num_data_qubits

Total number of physical data qubits required by the code.

get_num_x_stabilizers

Number of X-type stabilizers.

get_num_z_stabilizers

Number of Z-type stabilizers.

get_observables_x

Get the Pauli X observables of the code

get_observables_z

Get the Pauli Z observables of the code

get_operation_one_qubit

Get a CUDA-Q Python kernel for a one-qubit logical operation.

Returns:

A valid CUDA-Q Python kernel object.

get_operation_two_qubit

Get a CUDA-Q Python kernel for a two-qubit logical operation.

Returns:

A valid CUDA-Q Python kernel object.

get_parity

Get the parity check matrix of the code

get_parity_x

Get the X-type parity check matrix of the code

get_parity_z

Get the Z-type parity check matrix of the code

get_pauli_observables_matrix

Get a matrix of the Pauli observables of the code

get_stabilizer_round

Get a CUDA-Q Python kernel for a stabilizer round logical operation.

Returns:

A valid CUDA-Q Python kernel object.

get_stabilizer_schedule_x

Get the X-stabilizer schedule matrix passed to the code’s stabilizer_round kernel. Entry 0 = no support, entry k >= 1 = interaction at timestep k; defaults to the X-type parity check matrix (every interaction at timestep 1).

get_stabilizer_schedule_z

Get the Z-stabilizer schedule matrix passed to the code’s stabilizer_round kernel. Entry 0 = no support, entry k >= 1 = interaction at timestep k; defaults to the Z-type parity check matrix (every interaction at timestep 1).

get_stabilizers

Get the stabilizer generators of the code

Surface code layout

The rotated surface code exposes a grid helper for stabilizer and data-qubit indexing. In Python it is available as cudaq_qec.stabilizer_grid (call cudaq_qec.stabilizer_grid(distance)). The C++ type is cudaq::qec::surface_code::stabilizer_grid (API).

class cudaq_qec.stabilizer_grid(*args, **kwargs)
property data_coords

(self) -> list[cudaq_qec.vec2d]

property data_indices

(self) -> dict

property distance

(self) -> int

format_data_grid
format_stabilizer_coords
format_stabilizer_grid
format_stabilizer_indices
format_stabilizers
get_cnot_schedule_pairs_x

Return the X-stabilizer CNOT schedule as a flat list of (stabilizer index, data index) pairs ordered by timestep within each stabilizer.

get_cnot_schedule_pairs_z

Return the Z-stabilizer CNOT schedule as a flat list of (stabilizer index, data index) pairs ordered by timestep within each stabilizer.

get_cnot_schedule_x

Return the X-stabilizer CNOT schedule matrix as a numpy array whose rows match the sorted parity-matrix rows. Entry 0 = no support, k >= 1 = CNOT timestep, ordered so that ancilla (hook) errors land perpendicular to the logical operators.

get_cnot_schedule_z

Return the Z-stabilizer CNOT schedule matrix as a numpy array whose rows match the sorted parity-matrix rows. Entry 0 = no support, k >= 1 = CNOT timestep, ordered so that ancilla (hook) errors land perpendicular to the logical operators.

get_spin_op_observables

Return the logical observables as [X, Z] cudaq::spin_op_term entries

get_spin_op_stabilizers

Return the stabilizers as a list of cudaq::spin_op_term

property grid_length

(self) -> int

property orientation

(self) -> cudaq_qec.sc_orientation

property roles

(self) -> list[cudaq_qec.surface_role]

property x_stab_coords

(self) -> list[cudaq_qec.vec2d]

property x_stab_indices

(self) -> dict

property x_stabilizers

(self) -> list[list[int]]

property z_stab_coords

(self) -> list[cudaq_qec.vec2d]

property z_stab_indices

(self) -> dict

property z_stabilizers

(self) -> list[list[int]]

Detector Error Model

class cudaq_qec.DetectorErrorModel(*args, **kwargs)

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.

canonicalize_for_rounds

Canonicalize the detector error model for a given number of rounds.

Columns sharing the same detector and observable signature are merged, with rates composed to match the input model. By default, zero-syndrome columns that still flip an observable (undetectable logical errors) are retained so the model’s observable-flip probability is preserved. Set remove_zero_syndrome_errors=True to drop all columns with no detector signature, which is appropriate when the canonicalized DEM is consumed only for round-based decoding.

Canonicalization does not preserve cross-column exclusivity structure: each output column is given a fresh unique error id and treated as independent of every other column, so any error_ids correlation in the input model is discarded.

canonicalize_for_rounds_with_boundary

Boundary-aware canonicalization for memory-experiment DEMs whose first and last detector layers (the boundaries) are narrower than the interior layers. The first num_boundary_syndromes detector rows form the initial round, each subsequent block of num_syndromes_per_round rows is an interior round, and the trailing num_boundary_syndromes rows form the final round. This makes the round-based column ordering respect the true rounds even when the boundary width differs from the interior width.

remove_zero_syndrome_errors behaves as in canonicalize_for_rounds. Raises ValueError if num_syndromes_per_round is zero or num_boundary_syndromes exceeds num_syndromes_per_round.

property 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.

property 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.

property error_rates

The list of weights has length equal to the number of columns of the detector error matrix, which assigns a likelihood to each error mechanism.

num_detectors

The number of detectors in the detector error model

num_error_mechanisms

The number of error mechanisms in the detector error model

num_observables

The number of observables in the detector error model

property 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.

class cudaq_qec.DecoderContext

Lazy handle returned by decoder_context_from_memory_circuit.

Stores the raw circuit analysis. Each *_component method canonicalizes exactly the requested stabilizer type and returns a (dem, m2d, m2o) tuple.

full_component

Canonicalize both stabilizer types with boundary awareness; return (dem, m2d, m2o).

dem is the canonicalized DetectorErrorModel, m2d and m2o are lists of lists of measurement indices.

property num_measurements

Total number of measurements per shot.

x_component

Canonicalize X-stabilizer detectors; return (dem, m2d, m2o).

dem is the canonicalized DetectorErrorModel, m2d and m2o are lists of lists of measurement indices.

z_component

Canonicalize Z-stabilizer detectors; return (dem, m2d, m2o).

dem is the canonicalized DetectorErrorModel, m2d and m2o are lists of lists of measurement indices.

Note

The x_component(), z_component(), and full_component() methods each return a (dem, m2d, m2o) tuple:

  • dem (DetectorErrorModel) — canonicalized detector error model

  • m2d (list[list[int]]) — measurement-to-detector map; m2d[d] lists the measurement indices whose XOR forms detector d

  • m2o (list[list[int]]) — measurement-to-observable map

Pass m2d to d_sparse() to produce the D_sparse vector for a realtime decoder config.

cudaq_qec.dem_from_memory_circuit(code: cudaq_qec.Code, op: cudaq_qec.operation, numRounds: int, noise: cudaq.NoiseModel | None = None, decompose_errors: bool = False) → cudaq_qec.DetectorErrorModel

Generate a detector error model from a memory circuit.

This function generates a detector error model from a memory circuit. The memory circuit is specified by the code, the initial state preparation operation, and the number of stabilizer measurement rounds. The noise model is required.

Parameters:
  • code – The code to generate the detector error model for.

  • op – The initial state preparation operation.

  • numRounds – The number of stabilizer measurement rounds.

  • noise – The noise model to apply to the memory circuit.

  • decompose_errors – If True, hyperedge error mechanisms are decomposed into pairs of two-detector edges by Stim before returning.

Returns:

A detector error model.

cudaq_qec.x_dem_from_memory_circuit(code: cudaq_qec.Code, op: cudaq_qec.operation, numRounds: int, noise: cudaq.NoiseModel | None = None, decompose_errors: bool = False) → cudaq_qec.DetectorErrorModel

Generate a detector error model from a memory circuit in the X basis.

This function generates a detector error model from a memory circuit in the X basis. The memory circuit is specified by the code, the initial state preparation operation, and the number of stabilizer measurement rounds. The noise model is required.

Parameters:
  • code – The code to generate the detector error model for.

  • op – The initial state preparation operation.

  • numRounds – The number of stabilizer measurement rounds.

  • noise – The noise model to apply to the memory circuit.

  • decompose_errors – If True, hyperedge error mechanisms are decomposed into pairs of two-detector edges by Stim before returning.

Returns:

A detector error model.

cudaq_qec.z_dem_from_memory_circuit(code: cudaq_qec.Code, op: cudaq_qec.operation, numRounds: int, noise: cudaq.NoiseModel | None = None, decompose_errors: bool = False) → cudaq_qec.DetectorErrorModel

Generate a detector error model from a memory circuit in the Z basis.

This function generates a detector error model from a memory circuit in the Z basis. The memory circuit is specified by the code, the initial state preparation operation, and the number of stabilizer measurement rounds. The noise model is required.

Parameters:
  • code – The code to generate the detector error model for.

  • op – The initial state preparation operation.

  • numRounds – The number of stabilizer measurement rounds.

  • noise – The noise model to apply to the memory circuit.

  • decompose_errors – If True, hyperedge error mechanisms are decomposed into pairs of two-detector edges by Stim before returning.

Returns:

A detector error model.

cudaq_qec.decoder_context_from_memory_circuit(code: cudaq_qec.Code, op: cudaq_qec.operation, numRounds: int, noise: cudaq.NoiseModel | None = None, decompose_errors: bool = False) → cudaq_qec.DecoderContext

Run a memory-circuit analysis and return a lazy DecoderContext handle.

Executes dem_from_kernel once and stores the raw result. Canonicalization is deferred: call x_component(), z_component(), or full_component() on the returned handle to canonicalize exactly the stabilizer type needed.

Parameters:
  • code – The code to characterize.

  • op – The initial state preparation operation.

  • numRounds – The number of stabilizer measurement rounds.

  • noise – The noise model to apply to the memory circuit.

  • decompose_errors – If True, hyperedge error mechanisms are decomposed into pairs of two-detector edges by Stim before returning.

Returns:

A DecoderContext handle; call a component method to obtain the canonicalized (dem, m2d, m2o) tuple.

cudaq_qec.dem_from_stim_text(dem_text: str, use_decomp_suggestions: bool = False) → cudaq_qec.DetectorErrorModel

Parse a Stim detector error model string into a DetectorErrorModel.

Parameters:
  • dem_text – A Stim detector error model string.

  • use_decomp_suggestions – If error mechanism separated by ^ are decomposed

cudaq_qec.d_sparse(m2d: collections.abc.Sequence[collections.abc.Sequence[int]]) → list[int]

Flatten a measurement-to-detector map into the -1-terminated sparse vector a realtime decoder config expects for its D_sparse.

m2d is a list of lists: m2d[d] contains the measurement indices whose XOR forms detector d. Each detector’s indices are emitted in order, followed by -1.

This is a standalone helper for consumers who hold an m2d map (e.g., extracted from a decoder_inputs returned by a component method) and want to build the D_sparse vector without going through a DecoderContext.

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.

class cudaq_qec.DemChunksSpec(*args, **kwargs)

Multi-phase DEM decomposition with arbitrary named phases.

Standard memory experiment (linear chain init → bulk×N → final):

connections = [{init,bulk}, {bulk,bulk}, {bulk,final}] seam = {next_round, prev_round} num_rounds = T (None for streaming — round count unknown at config time)

dem_chunks_from_spec() calls phase_sequence() to materialise the full chunk list. num_rounds is required for that call when a self-loop is present; for streaming leave it as None and process bulk chunks as they arrive.

property connections

List of PhaseConnection (phase graph edges).

detectors_of

Return the detector rows the phase’s round contributes when closed: its incoming seam band and interior rows.

get_phase

Return the DemChunkSpec for the phase with the given PhaseId. Raises ValueError if no such phase exists.

has_D_sparse

True when 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 the rows.

has_repeating_phase

True when any connection is a self-loop.

is_empty

True when no phases or connections have been set.

measurements_of

Return the measurement count of the phase’s round, which is its num_measurements when set and measurements_per_round otherwise. Raises ValueError if neither is set.

property measurements_per_round

Measurements each round adds to the stream, for phases carrying D_sparse rows. A phase’s num_measurements overrides it.

minimum_rounds

Shortest chain the connections admit, visiting a repeating phase once. This is what a streaming spec expands to when nothing else pins the round count, and the smallest window it can supply.

num_observables

Return the number of O_sparse rows every phase a connection names carries. Raises ValueError if two phases disagree.

property num_rounds

Total rounds to materialise (None for streaming). Required by phase_sequence() when a self-loop is present.

property observable_names

Optional observable names, one per O_sparse row.

phase_sequence

Expand connections into an ordered list of PhaseIds. Requires num_rounds when a self-loop is present.

property phases

List of PhaseSpecEntry.

property phases_supply_D_sparse

Whether the phases carry D_sparse rows, where their emptiness cannot say so on its own. None infers it from any phase carrying rows. True declares that the phases supply D even where one contributes no rows; False keeps the memory convention even though rows are present.

repeating_phase

Return the PhaseId of the self-connected phase.

property seam

SeamConnection used between all adjacent phases.

validate

Raise ValueError if the spec is inconsistent.

class cudaq_qec.PhaseSpecEntry(*args, **kwargs)

A (PhaseId, DemChunkSpec) pair.

property id

PhaseId of this phase.

property spec

DemChunkSpec for this phase.

class cudaq_qec.PhaseConnection(*args, **kwargs)

Directed edge in the phase graph.

property from_phase

(self) -> cudaq_qec._pycudaqx_qec_the_suffix_matters_cudaq_qec.SeamId

is_self

True when from_phase == to_phase (marks the repeating phase).

property to_phase

(self) -> cudaq_qec._pycudaqx_qec_the_suffix_matters_cudaq_qec.SeamId

class cudaq_qec.SeamConnection(*args, **kwargs)

Which seam of one phase contracts against which seam of the next.

property from_seam

Seam contracting forward out of a phase.

property to_seam

Seam contracting backward into the next phase.

class cudaq_qec.DemChunkSpec(*args, **kwargs)

One DEM phase/chunk as flat index lists.

Two mutually exclusive forms: H_sparse at chunk level (memory experiments, all seams share the same H rows), or seam_specs with per-seam H_sparse/O_sparse for non-memory circuits. O_sparse at chunk level → ExtendedDem.O (decoder observable).

property D_sparse

Optional measurement-to-detector rows, -1-terminated, one per detector this chunk contributes when closed. Indices count the previous round’s measurements first, then this round’s own. Either every phase carries rows or none does; with none, D follows the memory convention of dem_chunks_to_d_sparse().

property H_sparse

Shared H rows for all seams, -1 terminated (memory shorthand).

property O_sparse

Observable rows (-1 terminated).

property error_rates

One prior per fault column.

expand

Expand H_sparse shorthand into seam_specs for the given ids.

is_empty

True iff no field has been set.

property m2o_sparse

Optional readout map, -1-terminated, one row per observable listing the measurements of this phase’s own round whose parity is the observable’s raw value. Only the last phase may carry it.

property num_faults

Fault columns; all matrices have this width.

property num_measurements

Measurements this phase’s round adds to the stream, when it differs from DemChunksSpec.measurements_per_round (a final data readout, say). None to use the spec-wide value.

property seam_specs

Per-seam specs as a list of SeamSpecEntry (non-memory form).

validate

Raise ValueError on the first inconsistency.

class cudaq_qec.SeamSpecEntry(*args, **kwargs)

A (SeamId, DemSeamSpec) pair.

property id

SeamId of this seam.

property spec

DemSeamSpec for this seam.

class cudaq_qec.DemSeamSpec(*args, **kwargs)

Per-seam sparse spec for one named seam boundary.

property H_sparse

Syndrome rows, -1 terminated.

property O_sparse

Logical-frame rows, -1 terminated (non-memory).

class cudaq_qec.SeamId(*args, **kwargs)

Identifier for a named seam or phase. Constructed from a string name; two SeamIds are equal iff constructed from the same string.

property value

FNV1a-32 hash of the name string.

cudaq_qec.seam_name = <module 'cudaq_qec._pycudaqx_qec_the_suffix_matters_cudaq_qec.seam_name'>

Standard seam names for memory experiments.

prev_round — incoming syndrome seam next_round — outgoing syndrome seam

cudaq_qec.phase_name = <module 'cudaq_qec._pycudaqx_qec_the_suffix_matters_cudaq_qec.phase_name'>

Standard phase names for memory experiments: init, bulk, final

Decoder Interfaces

class cudaq_qec.Decoder(*args, **kwargs)

Represents a decoder for quantum error correction

decode

Decode the given syndrome to determine the error correction

decode_async

Asynchronously decode the given syndrome

decode_batch

Overloaded function.

  1. decode_batch(self, syndrome: ndarray[shape=(*, *), order='C']) -> cudaq_qec.BatchDecoderResult

Decode multiple syndromes (a 2-D array, one syndrome per row) and return the results

  1. decode_batch(self, syndrome: collections.abc.Sequence[collections.abc.Sequence[float]]) -> cudaq_qec.BatchDecoderResult

Decode multiple syndromes and return the results

get_block_size

Get the size of the code block

get_syndrome_size

Get the size of the syndrome

get_version

Get the version of the decoder

Decoding Task Graph

A cudaq_qec.DecodingTaskGraph is a decoder pipeline of nodes wired by edges. See the Decoding Task Graphs, its Reference section, and the Getting Started with a Decoding Task Graph.

class cudaq_qec.DecodingTaskGraph

Composable decode pipeline backed by a general node/edge DAG.

Factories bound here:

from_spec: single decoder in a window-accumulation node. from_topology: any topology of TaskGraphNodeConfig nodes and edges. combine: two independent decoders whose logical outcomes are XOR’d.

A topology can also be described in configuration: set decoder_config.task_graph (see task_graph_spec) and let configure_decoders build it.

One-shot graph execution:

run(m) -> LogicalOutcome run_all(m) -> [LogicalOutcome] # one per correction output

Batch graph execution:

run_batch([m]) -> [LogicalOutcome]

Streaming interface (per-round accumulation):

enqueue_syndrome(syndrome) -> bool # True when window fired enqueue_syndrome(syndrome, type) -> bool # fired, or tail committed get_obs_corrections() -> bytes # corrections buffer get_logical_measurements(first, count) -> bytes | None # released clear_corrections() reset_decoder()

With TaskGraphOptions.async_streaming enabled, BULK enqueue calls return False after copying input; streaming_result() waits for accepted input and returns its completion state. Records overlap: a later record runs ahead on nodes that finished the earlier ones. Tagging the last round round_type.FINAL commits what a guarded window withheld; it is the only way to end a stream.

clear_corrections

Consume published corrections while preserving sliding-window overlap and publication generations.

combine = <nanobind.nb_func object>
enqueue_syndrome

Overloaded function.

  1. enqueue_syndrome(self, syndrome: bytes) -> bool

Accumulate syndrome bytes into the window buffer.

Synchronously, returns True when any window fired. With async streaming enabled, returns False after queueing BULK input; use streaming_result() to determine result readiness. An untagged round is a BULK round: it never ends the stream, so a guarded window’s trailing rounds stay withheld. Raises RuntimeError when the graph does not support streaming.

  1. enqueue_syndrome(self, syndrome: bytes, type: cudaq_qec.round_type) -> bool

Accumulate syndrome bytes, tagged with the round’s shape.

A FINAL round ends the shot, committing whatever a guarded window is still withholding. Further rounds are dropped with a warning until clear_corrections() or reset_decoder(). Raises ValueError for an empty FINAL round, which must carry the shot’s final measurements, and RuntimeError when the graph does not support streaming.

from_spec = <nanobind.nb_func object>
from_topology = <nanobind.nb_func object>
get_logical_measurements

Return logical measurements [first, first + count) (default: all from first): the raw logical readout with the corrections applied. None until all of them are released, and after the shot is consumed. Raises RuntimeError when the graph has no logical output, and IndexError for a range past get_num_logical_measurements().

get_num_logical_measurements

Number of logical measurement bytes; 0 without a logical output.

get_num_msyn_per_decode

Syndrome bytes consumed per full window.

get_num_msyn_per_round

Syndrome bytes in one round, the chunk size enqueue_syndrome expects.

get_num_observables

Number of observable correction bytes.

get_obs_corrections

Return the host-accessible corrections buffer.

For an async-streaming graph, waits for records accepted before this call without closing or flushing the session.

output_names

One name per correction output, indexing run_all() and naming the segments get_obs_corrections() concatenates.

reset_decoder

Reset all per-shot state on every node.

run

Walk the node/edge DAG for one shot → LogicalOutcome. Does not touch the streaming accumulation buffer. Raises on a graph with more than one output; use run_all().

run_all

Walk the DAG for one shot → one LogicalOutcome per correction output, in output_names() order.

run_batch

run() for each MeasurementResults in shots. Single-output graphs only; loop run_all() for the rest.

streaming_incompatibility_reason

Empty when streaming is supported; otherwise the first build-time incompatibility.

streaming_result

Snapshot of values and per-output streaming progress. With async streaming, waits for input accepted before this call. Status and generation distinguish unavailable outputs from genuine zeros.

supports_streaming

Whether incremental streaming execution is supported.

class cudaq_qec.TaskGraphNodeConfig(*args, **kwargs)

One node of a topology handed to DecodingTaskGraph.from_topology().

id and kind name the node and its registered kind; the kind decides which of the rest are required. The model comes from exactly one of dem, the d_sparse/o_sparse/h_sparse triple, or stim_dem. The inner decoder is named by decoder_type and configured by params, while node_params configures the node itself (window_size, residual_from).

property d_sparse

(self) -> list[list[int]]

property decoder_type

(self) -> str

property dem

(self) -> cudaq_qec._pycudaqx_qec_the_suffix_matters_cudaq_qec.DemChunksSpec | None

property ensemble

The members and join of a node of kind ‘ensemble’, for which the fields above are ignored. Assigning consumes the spec.

property h_sparse

(self) -> list[list[int]]

property id

(self) -> str

property kind

(self) -> str

property max_in_flight

(self) -> int

property node_params

(self) -> dict

property o_sparse

(self) -> list[list[int]]

property params

(self) -> dict

property stim_dem

(self) -> str

property windows

(self) -> list[cudaq_qec.experimental.ingest_window]

class cudaq_qec.TaskGraphEnsembleSpec(*args, **kwargs)

Member subgraphs raced against each other, one answer kept; set on TaskGraphNodeConfig.ensemble of a node of kind ‘ensemble’. join_strategy names a selection strategy (‘first’, ‘deadline’) and join_params its parameters. add_member() consumes its node configs.

add_member

Append a member, given its node configs (consumed) and the edges among them, naming the ensemble’s input ‘input’ and the member’s answer ‘output’.

property join_params

(self) -> dict

property join_strategy

(self) -> str

property num_members

(self) -> int

class cudaq_qec.TaskGraphOptions(*args, **kwargs)

Construction-time task-graph execution policy.

property async_coordinator_cpu

(self) -> int

property async_num_workers

Pool threads for an asynchronous graph; None sizes the pool from the graph.

property async_queue_capacity

(self) -> int

property async_spin_pause_iters

(self) -> int

property async_streaming

(self) -> bool

property async_worker_cpus

CPUs for the pool threads, round-robin; empty inherits the process’s affinity.

class cudaq_qec.TaskGraphStreamingResult
property closure

(self) -> cudaq_qec._pycudaqx_qec_the_suffix_matters_cudaq_qec.TaskGraphClosure

property completed_operations

(self) -> int

property error

(self) -> str

property generation

(self) -> int

property operation_completed

(self) -> bool

property outputs

(self) -> list[cudaq_qec._pycudaqx_qec_the_suffix_matters_cudaq_qec.TaskGraphOutputProgress]

property result_revision

(self) -> int

property shot_epoch

(self) -> int

property status

(self) -> cudaq_qec._pycudaqx_qec_the_suffix_matters_cudaq_qec.TaskGraphStreamingStatus

property values

(self) -> list[int]

class cudaq_qec.TaskGraphOutputProgress
property closure

(self) -> cudaq_qec._pycudaqx_qec_the_suffix_matters_cudaq_qec.TaskGraphClosure

property coverage_begin_round

(self) -> int

property coverage_end_round

(self) -> int

property generation

(self) -> int

property name

(self) -> str

property released

For the logical output, 1 per bit once that logical measurement is final; empty for a correction output.

property status

(self) -> cudaq_qec._pycudaqx_qec_the_suffix_matters_cudaq_qec.TaskGraphStreamingStatus

property value_offset

(self) -> int

property value_width

(self) -> int

class cudaq_qec.TaskGraphStreamingStatus(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)
class cudaq_qec.TaskGraphClosure(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)
class cudaq_qec.DecoderResult(*args, **kwargs)

Single-shot decoder result.

Returned by decoder.decode(...). Carries the convergence flag, the decoded correction chain, and optional decoder-specific metadata.

Like BatchDecoderResult, this is conceptually output-only — user code should not need to construct or mutate one. Unlike BatchDecoderResult, the no-arg constructor and writable fields are preserved here because Python decoder plugins implementing a decode override use the construct-then-mutate pattern:

res = DecoderResult() res.converged = True res.result = np.arange(…) return res

Tightening this construction surface would break every existing Python decoder plugin and is deferred to a future change.

property converged

Boolean flag indicating if the decoder converged to a solution.

True if the decoder successfully found a valid correction chain, False if the decoder failed to converge or exceeded iteration limits.

property opt_results

Optional additional results from the decoder stored in a heterogeneous map.

This field may be empty if no additional results are available.

property result

The decoded correction chain or recovery operation.

Contains the sequence of corrections that should be applied to recover the original quantum state. The format depends on the specific decoder implementation.

Returns a 1-D NumPy array of the configured QEC floating point dtype (float64 in standard wheels). A fresh array is allocated per access — the underlying storage is a std::vector<float_t> and the data is copied out on read.

Accepts any sequence of floats on assignment; this is the path Python decoder plugins use in their decode overrides (see class docstring).

class cudaq_qec.BatchDecoderResult(*args, **kwargs)

Batched decoder result.

Produced by decoder.decode_batch(...). This type is output-only: it carries decoder output back to the caller and is not parsed by decoders. User code should not need to construct one — call decoder.decode_batch(...) and read the result.

Python decoder plugins implementing a decode_batch override may use the constructor to produce one. result should be a 2-D NumPy array of the configured QEC floating point dtype (float64 in standard wheels); converged should be a 1-D NumPy bool array; opt_results is a list of per-shot dicts or None entries; batch_opt_results is an optional dict of batch-level results. The constructor coerces result and converged to C-contiguous storage of the expected dtype (via np.ascontiguousarray), copying when the input doesn’t already satisfy those invariants. Wrong rank (e.g. 1-D result) is rejected with TypeError.

An empty batch (zero syndromes) yields result.shape == (0, 0) and converged.shape == (0,). The per-shot width is unknown without running a decode and depends on decoder mode, so result.shape[1] is only meaningful when the batch is non-empty.

Access patterns, fastest to slowest:

  1. Vectorized: read result, converged, or opt_results directly. The properties return the underlying NumPy arrays and Python list with no copy. This is the recommended path for batch processing.

  2. Slicing: batch[a:b] returns another BatchDecoderResult that shares data with the parent. NumPy basic slicing — including stepped slices like batch[::2] — returns views, so no data is copied. The opt results list slice creates a new Python list, but its entries are shared references.

  3. Integer indexing / iteration: batch[i] or for r in batch: yields a DecoderResult copy of one shot. This compatibility surface exists for code written against the previous list[DecoderResult] return type. Each access copies the row out into a fresh per-shot buffer because DecoderResult’s underlying storage (std::vector<float_t>) cannot alias into the batch’s packed NumPy array — the layouts are incompatible. Avoid in hot loops; prefer pattern 1.

property batch_opt_results

A dict of batch-level optional results, or None.

Unlike opt_results, this describes the batch as a whole rather than any single shot: its arrays are indexed by position in the batch. Most decoders produce None here. It is the fast path for data that would otherwise cost one Python dict and several small arrays per shot.

Because its arrays are indexed by position in the full batch, slicing a BatchDecoderResult drops this field rather than carrying it through misaligned.

property converged

A one-dimensional NumPy bool array indicating convergence per shot.

property opt_results

A list of per-shot optional result dictionaries, or None entries.

property result

A two-dimensional NumPy array of decoder outputs, with one row per shot.

This is the fast path for batch consumers. Its dtype is the configured QEC floating point type.

class cudaq_qec.AsyncDecoderResult

A future-like object that holds the result of an asynchronous decoder call. Call get() to block until the result is available.

get

Return the decoder result (blocking until ready)

ready

Return True if the asynchronous decoder result is ready, False otherwise

Note

NumPy result arrays — As of 0.7.0, the result field of cudaq_qec.DecoderResult (and the per-shot results returned by cudaq_qec.BatchDecoderResult and cudaq_qec.AsyncDecoderResult) is a 1-D NumPy array rather than a Python list. Indexing and iteration are unchanged, but code that relied on the result being a list specifically (for example isinstance(res, list) or list-only methods) should be updated.

cudaq_qec.get_decoder(arg0: str, arg1: object, /, **kwargs) → object | cudaq_qec.Decoder

Get a decoder by name.

H may be:

  • A scipy sparse matrix (CSR, CSC, COO, or any scipy.sparse format): the preferred input — no dense allocation occurs, and any format is normalised to CSR internally before building the C++ sparse storage.

  • A dense 2D NumPy uint8 array in row-major order: a full dense cudaqx::tensor is built first, then converted to CSC sparse storage. For large PCMs this can allocate as much memory as rows * cols.

  • A Stim detector error model string: native C++ decoders receive the raw DEM text via decoder_init; Python-registered decoders receive the DEM-derived PCM plus O and error_rate_vec defaults.

Native decoders select their result basis with output="errors" or output="observables". When omitted, the plugin’s documented default applies; PyMatching defaults to errors. Matrix O and error_rate_vec keyword adapters are normalized into decoder_init. Supplying O never selects the output mode.

For Python-registered decoders (cudaq.qec.decoder decorator), H is passed through to __init__ unchanged (NumPy array or scipy sparse matrix). DEM string inputs are parsed first as described above. Call Decoder.__init__(self, H) so nanobind can store the PCM internally without building a dense rows x cols allocation.

Note

scipy.sparse interop — cudaq_qec.get_decoder() and cudaq_qec.Decoder accept a scipy.sparse matrix (CSR, CSC, COO, or any other scipy.sparse format) as the parity-check matrix H. This is the preferred form for large PCMs because no dense rows x cols allocation is made — the matrix is normalised to CSR internally. Dense NumPy uint8 arrays remain supported. The PCM utilities cudaq_qec.reorder_pcm_columns(), cudaq_qec.shuffle_pcm_columns(), and cudaq_qec.pcm_to_sparse_vec() also accept SciPy sparse matrices without creating a dense cudaqx::tensor. Reordering and shuffling a sparse input returns a scipy.sparse.csc_matrix; a dense input continues to return a NumPy array.

scipy is an optional dependency; if it is not installed, pass a dense NumPy array instead.

Built-in Decoders

NVIDIA QLDPC Decoder

class cudaq_qec.nv_qldpc_decoder

The nv-qldpc-decoder plugin 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_qldpc module 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_decoder API from the CUDA-Q QEC extension points API, such as

import 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 the cudaq_qec.Decoder interface for Python and the cudaq::qec::decoder interface 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 through cudaq::qec::decoder_init.

  • output – Result basis, "errors" or "observables" in Python and cudaq::qec::decode_result_type in C++. When omitted, the decoder returns error frames even if O is present.

  • error_rate_vec – Optional probability per error mechanism, with length block_size. Python accepts it as a keyword adapter; C++ supplies it through cudaq::qec::decoder_init. It overrides the scalar error_rate parameter.

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").

Block diagram of the nv-qldpc decoder pipeline: BP front end, TCBP calibrated scores, column ordering, OSD post-processing, and the four results.

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-bp

use_osd=false (relay-bp: composition=1)

TCBP error probabilities

tcbp

tcbp_model, use_osd=false

Final-LLR ordering with OSD-0 or combination sweep

bp60-osd0, bp60-osd-cs1000

use_osd=true, osd_method 1 or 3

Minimum-LLR ordering with OSD-0, combination sweep or JOBS

bp10-minllr-osd0, bp10-minllr-osd-cs1000, bp10-minllr-jobs

osd_init_method="min_llr", osd_method 1, 3 or 4

TCBP ordering with combination sweep or JOBS

tcbp-osd-cs1000, tcbp-jobs, tcbp-jobs-sc, tcbp-jobs-sc-gap

tcbp_model, osd_init_method="tcbp", osd_method 3 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 >= 0 and 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 solver

  • n_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 set clip_value to 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 in bp_method=3 or bp_method=5 (disordered memory BP), or in composition=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 with osd_method=4, which searches the whole bp_batch_size chunk on the device; setting both is an error.

Belief propagation

Options for the BP stage, which runs in every configuration. bp_method values 2 through 5 require use_sparsity=true. scale_factor applies 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 is max_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_method values 2 through 5) and for Relay-BP (composition=1). All of them require use_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) or bp_method=5 (sum-product+dmem), use_sparsity=True, and srelay_config. Support for bp_method=5 was added in 0.7.0.

  • gamma0 (float): Memory strength parameter. Required for bp_method=2 (min-sum+mem) and bp_method=4 (sum-product+mem), and for composition=1 (sequential relay). Introduced in 0.5.0; extended in 0.7.0 for bp_method=4.

  • gamma_dist (vector<float>): Gamma distribution interval [min, max] for disordered memory strength. Required for bp_method=3 (min-sum+dmem) or bp_method=5 (sum-product+dmem) if explicit_gammas not provided. Introduced in 0.5.0; extended in 0.7.0 for bp_method=5.

  • explicit_gammas (vector<vector<float>>): Explicit gamma values for each variable node. For bp_method=3 or bp_method=5 with composition=0, provide a 2D vector where each row has block_size columns. For composition=1 (Sequential relay), provide num_sets rows (one per relay leg). Overrides gamma_dist if provided. Introduced in 0.5.0; extended in 0.7.0 for bp_method=5.

  • srelay_config (heterogeneous_map): Sequential relay configuration (required for composition=1). Contains the following parameters. Introduced in 0.5.0:

    • pre_iter (int): Number of pre-iterations to run before relay legs

    • num_sets (int): Number of relay sets (legs) to run

    • stopping_criterion (string): When to stop relay legs:

      • “All”: Run all legs

      • “FirstConv”: Stop relay after first convergence

      • “NConv”: Stop after N convergences (requires stop_nconv parameter)

    • stop_nconv (int): Number of convergences to wait for before stopping (required only when stopping_criterion="NConv")

    Note

    Starting in version 0.6.0, convergence during the pre_iter phase 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 from gamma_dist (or explicit_gammas). The constructor requires num_sets >= gamma_ensemble_size so 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_criterion across 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 all num_sets legs 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_iter warm-up is the opposite: every lane would run it with the same uniform gamma0 value, 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 when pre_iter is small or zero.

    The gamma ensemble is supported on the sparse GPU single-decode path with composition=1 and bp_method=3 (min-sum + dmem) or bp_method=5 (sum-product + dmem). Passing gamma_ensemble_size > 1 with any other bp_method or with the CPU or dense GPU path raises std::invalid_argument at 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 for gamma_ensemble_size > 1 with capture_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_model fits the model once per code family from the detector error matrix. Noise learning uses the same model. TCBP requires use_sparsity=true and composition=0.

  • tcbp_model (bytes or str): TCBP model returned by cudaq_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-D uint8 NumPy array (np.array(bytearray(model), dtype=np.uint8)). In the YAML schema, and therefore for real-time decoding, only the file path is accepted. The bp_method, max_iterations, clip_value and proc_float of the decoder must equal the values the model was fitted with. If opt_results.bp_llr_history is set, it must equal max_iterations.

  • tcbp_strict (bool): If true, a tcbp_model that 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. Setting tcbp_strict without tcbp_model is a construction error.

The result depends on use_osd:

  • use_osd=false: decode() and decode_batch() return the calibrated error probability of each mechanism. For shots on which BP converges, the result is the BP posterior probability and converged is true.

  • use_osd=true with osd_init_method="tcbp": the calibrated probabilities determine the OSD column ordering, and the result is the OSD correction. Supplying tcbp_model with use_osd=true and any other osd_init_method is 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 as bytes. With return_report=True it returns (model, report). H is the detector error matrix, with one row per detector and one column per error mechanism, as a 2-D uint8 array or a scipy.sparse matrix. The function samples errors from H at 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 between min_p and max_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 with min_p or max_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_method must be 0 or 1, and max_iterations must 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 of H and fingerprints of its structure and of the training rates. The timing and memory entries are not stored in the model, so inspect returns 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_value or proc_float changes.

  • Check prob_regression_flag after every fit.

  • If the error rates of the circuit lie outside the range from min_p to max_p, set min_p and max_p so 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 to learn_noise must 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 seed and an explicit device_memory_budget_bytes.

Column ordering

osd_init_method selects 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) and tcbp-* (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), and composition=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_method selects 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 solution

  • osd_method (int): 1=OSD-0, 2=Exhaustive, 3=Combination Sweep, 4=JOBS (defaults to 1). Ignored unless use_osd is 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 Landscape

    • For 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_method values, 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 the osd_init_method ordering) 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. Requires use_osd.

  • osd_sparsify_pad (float >= 1): With osd_sparsify, OSD uses the first ceil(osd_sparsify_pad * K*) columns, clamped to the number of columns (defaults to 8.0). Mutually exclusive with osd_sparsify_exact. Except with osd_method=4, setting osd_sparsify_pad or osd_sparsify_exact without osd_sparsify=true is a construction error.

  • osd_sparsify_exact (int >= 1): With osd_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 per decode(), one with the number of affected shots per decode_batch()). Nothing in the result marks such a shot; to find them, request opt_results.kstar and look for kstar > 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 searches jobs_draws column 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 require use_osd=true and osd_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 of jobs_draws draws 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). converged still reports whether BP converged. With osd_init_method="final_llr", opt_results.bp_llr_history, if set, must equal max_iterations. Introduced in 0.9.0.

The search has the following steps:

  1. Draw 0 uses the osd_init_method ordering. Every other draw adds Gumbel noise, scaled by jobs_draw_noise, to the ordering scores and sorts the columns again.

  2. Each draw computes an OSD-0 solution on the first W columns of its own ordering, where W = ceil(osd_sparsify_pad x 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.

  3. A beam search starts from each OSD-0 solution and looks for lower-cost corrections that satisfy the syndrome. It keeps jobs_beam_width states per step. It stops after jobs_beam_depth steps, or after jobs_beam_patience steps without improvement.

  4. If jobs_rounds is 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_converged to search every shot.

Requirements and limits:

  • JOBS requires use_osd=true, use_sparsity=true and composition=0.

  • Every error rate must be at most 0.5. A larger rate is a construction error.

  • Starting in 0.9.1, H can 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_width can 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_sparsify is not needed. osd_order is ignored. Setting osd_sparsify=false, osd_batch_size or osd_sparsify_exact is a construction error.

Device memory: the decoder allocates all device memory for the search at construction, sized for bp_batch_size x jobs_draws concurrent 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() and decode_batch() search the same draws, and repeated calls return identical results. opt_results.kstar reports 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 bit o is set if the correction flips observable o, 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 +inf when the search found no correction in another class. It is also +inf for shots on which JOBS did not run, that is, shots for which BP converged when jobs_search_converged is 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_gap requires a decoder constructed with an observable matrix that has at most 12 observables. For k observables, the option adds bp_batch_size x 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 last bp_llr_history iterations of the BP LLR history. Minimum value is 0 and maximum value is max_iterations. The actual number of returned iterations might be fewer than bp_llr_history if BP converges before the requested number of iterations. Introduced in 0.4.0. Note: Not supported for composition=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 (with jobs_search_converged, converged shots are searched and report the K* of that search). With osd_sparsify_exact, a value above osd_sparsify_exact marks a shot the window could not solve. Requires use_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. Requires osd_method=4 and a decoder constructed with observables (at most 12).

    • relay_solutions (bool or int): Record every relay convergence (“solution”), not just the winning one. True records 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). Requires composition=1 (sequential relay) on the sparse GPU path (use_sparsity=True); other backends reject the option at construction. Not yet supported with gamma_ensemble_size > 1. Compatible with use_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 (the BatchDecoderResult.batch_opt_results attribute in Python; the optional batch_opt_results output parameter in C++) as flat arrays under the keys relay_solutions_width, relay_solutions_max_records, relay_solutions_counts, relay_solutions_totals, relay_solutions_iters, relay_solutions_weight, and relay_solutions_result. (decode() returns the same keys through DecoderResult.opt_results, with scalar relay_solutions_count / relay_solutions_total.) The cudaq_qec.relay_solutions Python module post-processes the records: unpack() reconstructs the per-shot record axes, and stop_nconv_sweep() replays an entire RelayBP-N stop_nconv sweep — 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_qldpc module defines named presets for the configurations in the table above. preset(name, **overrides) returns the options of a preset as a dictionary, with overrides applied. Pass the dictionary to get_decoder as keyword arguments.

Preset

BP

Column ordering

Post-processor

bp60

sum-product, 60 iterations

n/a

none (BP hard decision)

bp60-osd0

sum-product, 60 iterations

final LLR

OSD-0

bp60-osd-cs1000

sum-product, 60 iterations

final LLR

combination sweep, osd_order=1000

bp10-minllr-osd0

sum-product, 10 iterations

minimum LLR

OSD-0

bp10-minllr-osd-cs1000

sum-product, 10 iterations

minimum LLR

combination sweep, osd_order=1000

bp10-minllr-jobs

sum-product, 10 iterations

minimum LLR

JOBS

relay-bp

Relay-BP (bp_method=3), 80 pre-iterations, 300 relay legs

n/a

none (BP hard decision)

tcbp

sum-product, 10 iterations

n/a

none (TCBP error probabilities)

tcbp-osd-cs1000

sum-product, 10 iterations

TCBP

combination sweep, osd_order=1000

tcbp-jobs

sum-product, 10 iterations

TCBP

JOBS

tcbp-jobs-sc

sum-product, 10 iterations

TCBP

JOBS with jobs_search_converged

tcbp-jobs-sc-gap

sum-product, 10 iterations

TCBP

JOBS with jobs_search_converged and opt_results.jobs_gap

All presets set use_sparsity=true, proc_float="fp32" and repeatable=true. All presets except relay-bp also set bp_method=0 and clip_value=15.0.

Notes:

  • Presets do not set error rates. Pass error_rate_vec or error_rate to get_decoder.

  • The tcbp* presets require a tcbp_model override. The override accepts the bytes returned by init_tcbp_model, a uint8 array or a file path.

  • The tcbp* presets use the BP settings that init_tcbp_model fits with by default. To use a different bp_method, max_iterations, clip_value or proc_float, fit the model with those settings and pass the same values as overrides.

  • tcbp-jobs-sc-gap requires 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=True and osd_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, and osd_sparsify_pad defaults to 8.0. JOBS always uses the window.

  • jobs_draws, jobs_beam_width, jobs_beam_depth, jobs_beam_patience and jobs_draw_noise: amount of search that JOBS performs.

  • gamma0, gamma_dist and srelay_config: Relay-BP parameters.

  • bp_method=1: min-sum BP in place of sum-product (scale_factor applies).

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])

Relay Solutions Post-Processing

Post-processing for the nv-qldpc-decoder relay_solutions records.

When the decoder is configured with opt_results={"relay_solutions": True} (sequential relay, composition=1), every relay convergence is recorded and returned through BatchDecoderResult.batch_opt_results as flat arrays. This module reconstructs, offline, what the decoder would have returned for any stop_nconv setting, so a single recording run answers the whole RelayBP-N sweep.

Public API:

unpack(batch_opt_results, num_shots) -> RelaySolutionRecords stop_nconv_sweep(results, obs_truth, percentiles=…, n_values=None, observables=None) -> StopNConvSweep

Requirements on the recording run (documented, not detectable from the data): the sweep is only meaningful if the run did not itself stop early, i.e. srelay_config={"stopping_criterion": "All"} and relay_solutions=True (uncapped). A capped run (relay_solutions=<int>) is detected and rejected for any N beyond the cap.

cudaq_qec.relay_solutions.unpack(batch_opt_results, num_shots)

Reshape the flat relay_solutions_* arrays.

Accepts either the batched key set (relay_solutions_counts/totals, from decode_batch) or the single-shot one (relay_solutions_count/ total, from decode, with num_shots == 1).

cudaq_qec.relay_solutions.stop_nconv_sweep(results, obs_truth, *, percentiles, n_values=None, observables=None)

Reconstruct LER and iteration statistics for a range of stop_nconv.

For each N, each shot’s prediction is the minimum-weight record among its first min(N, count) convergences (weight ties resolve to the earliest record), and its iteration count is the cumulative count at the Nth convergence – or the shot’s full-schedule num_iter when it produced fewer than N convergences, exactly what stop_nconv=N would have run. Shots that never converged are scored with the decoder’s returned (fallback) result, which is identical for every N.

Parameters:
  • results – The BatchDecoderResult of a recording run. Beyond the records themselves, per-shot num_iter is read from results.opt_results when any shot exhausts the schedule within the sweep range, and results.result supplies the fallback prediction for never-converged shots.

  • obs_truth – (num_shots, k) 0/1 array of actual observable flips.

  • percentiles – Iteration percentile(s) to report, in (0, 100]. A scalar yields iters_percentiles of shape (n_N,); a list yields (n_p, n_N).

  • n_values – Iterable of stop_nconv values to sweep; defaults to 1..max_records.

  • observables – (k, width) 0/1 observables matrix. Required when the decoder ran without one (records are corrections); must be omitted when it ran with one (records already are observable classes).

Returns:

A StopNConvSweep.

class cudaq_qec.relay_solutions.RelaySolutionRecords(width: int, max_records: int, counts: ndarray, totals: ndarray, iters: ndarray, weight: ndarray, packed: ndarray)

The relay_solutions_* arrays with the record axes reconstructed.

Rows beyond a shot’s own record count are padding: iteration count -1, weight +inf, packed bits all zero.

bits(shot, record)

One record’s hard decision as a 0/1 vector of length width.

counts: ndarray

(num_shots,) records stored per shot

iters: ndarray

(num_shots, R) cumulative iterations at each record

max_records: int

the record axis (R) of the padded arrays

packed: ndarray

(num_shots, R, W) int32 words, 32 bits per word

totals: ndarray

(num_shots,) convergences seen per shot (uncapped)

weight: ndarray

(num_shots, R) LLR weight of each record

width: int

bits per record (block_size, or num_obs when O was given)

class cudaq_qec.relay_solutions.StopNConvSweep(n: ndarray, ler: ndarray, num_errors: ndarray, avg_iters: ndarray, iters_percentiles: ndarray, percentiles: ndarray, num_shots: int, num_unconverged: int, frac_exhausted: ndarray)

Per-N results of a stop_nconv sweep. Arrays are indexed by n.

avg_iters: ndarray

(n_N,) mean iterations run

frac_exhausted: ndarray

(n_N,) shots with fewer than N convergences

iters_percentiles: ndarray

iteration percentiles; (n_N,) for a scalar percentiles input, (n_p, n_N) for a list (np.percentile convention)

ler: ndarray

(n_N,) logical error rate

n: ndarray

(n_N,) the stop_nconv values swept

num_errors: ndarray

(n_N,) raw logical error counts

num_unconverged: int

shots with zero recorded convergences

percentiles: ndarray

the percentile values requested

NVIDIA Fusion Decoder

class cudaq_qec.relay_solutions.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 to 1; pass 0 to 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 runs decode() 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 raise std::logic_error rather 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 by block_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_size below.

References:

Note

It is required to create decoders with the get_decoder API from the CUDA-Q QEC extension points API, such as

import 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 the cudaq_qec.Decoder interface for Python and the cudaq::qec::decoder interface 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 carries H, 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 through cudaq::qec::decoder_init.

  • output – Result basis, "errors" or "observables" in Python and cudaq::qec::decode_result_type in C++. Supplying O or 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 through cudaq::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_args accepts only num_threads, block_leaf_size, fusion_strategy and error_rate_vec, and rejects any other key. A YAML configuration supplies the matrices and the temporal layout through the top-level H_sparse, O_sparse and D_sparse fields 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, length H.num_rows(). Maps each parent detector to its round in 0-based integer coordinates. Takes highest priority over all automatic derivation paths.

    • D in cudaq::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-level D_sparse field is normalized into this model input.

    The three sources are consulted in that order: an explicit detector_round first, then DEM coordinates, then D. A DEM therefore takes precedence over D, 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, where d is 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 * d puts 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_size to the shot’s full round count explicitly.

      This differs from earlier releases, where omitting block_leaf_size always produced a single leaf.

    • num_threads (uint64): Number of CPU threads to use during scaffold construction and parallel fuse operations. Defaults to 1.

    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_output is not false;

    • the schedule is fused, i.e. block_leaf_size is set, or it is omitted and the automatic 2 * d leaf 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 * d rounds;

    • 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_size rounds) 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’s dem_chunks), the decoder rolls without ever building the shot’s flat model: it closes the chunks over a representative number of rounds, independent of num_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 with cudaq::qec::decoder_init::from_dem_chunks_closed() instead.

    • rolling_ring_blocks (uint64): Blocks in the ring, each block_leaf_size rounds tall. Defaults to 12; even and at least 6. 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. Like block_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 to true; false keeps 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 of block_leaf_size, at least 1, which keeps the middle half of each block’s corrections. It must be below half of block_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). 1 keeps more of the blocks’ corrections and decodes faster, at a percent or two more weight with the automatic 2 * d leaf. 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_size blocks 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 a DecoderResult where:

  • result — the explicitly selected result basis. Observable output has length num_observables and each entry indicates a predicted logical flip. Error output has length block_size and each entry indicates whether the corresponding H column was selected as a matching edge.

  • converged — True if the fuse pass raised no herald flag. A False value indicates a suspect or ambiguous match; the correction is still populated and may be used. For rolling error output it is also False when 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 to converged = 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 via D_sparse as each detector round’s measurements become complete. Observable corrections are XOR-accumulated into a running Pauli frame and exposed via get_obs_corrections().

Task-graph streaming uses the optional streaming_correction_provider capability: 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 of get_obs_corrections().

Note

D must be supplied in cudaq::qec::decoder_init before the first call to enqueue_syndrome(). The realtime layer normalizes its top-level D_sparse configuration into that model input.

Note

Observable corrections accumulate across shots. Call clear_corrections() or reset_decoder() between shots to reset the Pauli frame. reset_decoder() also rewinds the streaming session; clear_corrections() does not.

Sliding Window Decoder

class cudaq_qec.relay_solutions.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 decode function (and its variants like decode_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 decode and decode_batch overloads forward the token to the inner decoders. They return the same empty result while a block is incomplete, and std::nullopt if 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_decoder API from the CUDA-Q QEC extension points API, such as

import 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 the cudaq_qec.Decoder interface for Python and the cudaq::qec::decoder interface 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 length block_size containing the probability of each error. Python accepts this as a keyword. C++ supplies it through cudaq::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 have num_syndromes_per_round detectors.) For a single-basis DEM from z_dem_from_memory_circuit() (respectively x_dem_from_memory_circuit()), every layer has code.get_num_z_stabilizers() (respectively code.get_num_x_stabilizers()) detectors, so this may be left at its default. For a full DEM from dem_from_memory_circuit(), num_syndromes_per_round is code.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 to code.get_num_z_stabilizers() for Z-basis preps (prep0/prep1) or code.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 cudaq_qec.relay_solutions.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_format is required. It declares the semantic layout of the TensorRT model’s output and is validated against H, 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_decoder API from the CUDA-Q QEC extension points API, such as

import 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 the cudaq_qec.Decoder interface for Python and the cudaq::qec::decoder interface for C++, so it supports all the methods in those respective classes.

Note

The TensorRT engine performs inference, but H is still model data. Its column count defines the error-frame width, validates an engine_output_format="errors" engine, and supplies the detector model to an optional global decoder. H and the optional O must 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 using decode_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 of H.

      • "residual_detectors": residual detector values consumed by the required global_decoder.

      • "observables": one value per row of O.

      • "observables_and_residual_detectors": an observable prefix followed by residual detectors. With global_decoder, the residuals are decoded and combined with the observable prefix. Alternatively, a C++ decoder_output_request may request observables as the primary result and residual_detectors as an auxiliary output; the prefix is then returned in result and the residuals in opt_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 with engine_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 with onnx_load_path.

    Optional:

    • engine_save_path (string): Path to save the built TensorRT engine. Only applicable when using onnx_load_path. Saving the engine allows for faster initialization in subsequent runs by using engine_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, the decode() method automatically zero-pads single syndromes to fill the batch. The decode_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 the residual_detectors auxiliary 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 to decode or decode_batch reaches only this global decoder; TensorRT inference itself is not interruptible.

    • global_decoder_params (map): Parameters forwarded to the global_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 >= 0 and 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.

Tensor Network Decoder

class cudaq_qec.plugins.decoders.tensor_network_decoder.TensorNetworkDecoder

A general class for tensor network decoders for quantum error correction codes.

This decoder constructs a tensor network representation of a quantum code using its parity check matrix, logical observables, and noise model. The tensor network is based on the Tanner graph of the code and can be contracted to compute the probability that a logical observable has flipped, given a syndrome.

The decoder supports both single-syndrome and batch decoding, and can run on CPU or GPU (using cuTensorNet if available).

The Tensor Network Decoder is a Python-only implementation and it requires Python 3.11 or higher. C++ APIs are not available for this decoder.

Due to the additional dependencies of the Tensor Network Decoder, you must specify the optional pip package when installing CUDA-Q QEC in order to use this decoder. Use pip install cudaq-qec[tensor-network-decoder] in order to use this decoder.

The Tensor Network Decoder has the same GPU support as the Quantum Low-Density Parity-Check Decoder. However, if you are using the V100 GPU (SM70), you will need to pin your cuTensor version to 2.2 by running pip install cutensor_cu12==2.2. Note that this GPU is not supported by the Tensor Network Decoder.

Note

It is recommended to create decoders using the cudaq_qec plugin API:

import cudaq_qec as qec
import numpy as np

# Example: [3,1] repetition code
H = np.array([[1, 1, 0],
        [0, 1, 1]], dtype=np.uint8)
logical_obs = np.array([[1, 1, 1]], dtype=np.uint8)
noise_model = [0.1, 0.1, 0.1]

decoder = qec.get_decoder("tensor_network_decoder", H, logical_obs=logical_obs, noise_model=noise_model)

syndrome = [0.0, 1.0]
result = decoder.decode(syndrome)

Tensor Network Structure

The tensor network constructed by this decoder is based on the Tanner graph of the code, extended with noise and logical observable tensors. The structure is illustrated below:

      open/output index < logical observable
          --------
             |
s1      s2   |     s3   < syndromes               : product of 2D vectors [1 , 1-2pi] (pi is the probability detector i flipped)
|       |    |     |                        ----|
c1      c2  l1     c3   < checks / logical      | : delta tensors
|     / |   | \    |                            |
H   H   H   H  H   H    < Hadamard matrices     | TANNER (bipartite) GRAPH
  \ |   |  /   |  /                             |
    e1  e2     e3       < errors                | : delta tensors
    |   |     /                            -----|
     \ /     /
    P(e1, e2, e3)       < noise / error model     : classical probability density

ci, ej, lk are delta tensors represented sparsely as indices.
Parameters:
  • H – Parity check matrix (numpy.ndarray), shape (num_checks, num_qubits)

  • logical_obs – Logical observable matrix (numpy.ndarray), shape (1, num_qubits)

  • noise_model – Noise model, either a list of probabilities (length = num_qubits) or a quimb.tensor.TensorNetwork

  • check_inds – (optional) List of check index names

  • error_inds – (optional) List of error index names

  • logical_inds – (optional) List of logical index names

  • logical_tags – (optional) List of logical tags

  • contract_noise_model – (bool, optional) Whether to contract the noise model at initialization (default: True)

  • dtype – (str, optional) Data type for tensors (default: “float64”)

  • device – (str, optional) Device for tensor operations (“cpu”, “cuda”, or “cuda:X”, default: “cuda”)

Methods

decode(syndrome)

Decode a single syndrome by contracting the tensor network.

Parameters:

syndrome – List of float values (soft-decision probabilities) for each check.

Returns:

DecoderResult with the probability that the logical observable flipped.

decode_batch(syndrome_batch)

Decode a batch of syndromes.

Parameters:

syndrome_batch – numpy.ndarray of shape (batch_size, num_checks)

Returns:

List of DecoderResult objects with the probability that the logical observable has flipped for each syndrome.

optimize_path(optimize=None, batch_size=-1)

Optimize the contraction path for the tensor network.

Parameters:
  • optimize – Optimization options or None

  • batch_size – (int, optional) Batch size for optimization (default: -1, no batching)

Returns:

Optimizer info object

PyMatching Decoder

class cudaq_qec.relay_solutions.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 O no longer selects observable output. O is model data and may be used even when the requested result is an error frame. PyMatching returns errors when output is omitted. Pass output="observables" in Python or cudaq::qec::decode_result_type::observables in C++ to request observable flips explicitly.

Note

To use the decoder, use the get_decoder API 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 the cudaq_qec.Decoder interface for Python and the cudaq::qec::decoder interface 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.sparse matrix or a dense NumPy uint8 array may be passed.

  • params –

    Decoder model inputs and heterogeneous parameters:

    • error_rate_vec (vector<double>): Per-error prior probabilities, one per column of H (length block_size). Python accepts this as a keyword. C++ supplies it through cudaq::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 to 1.0.

    • merge_strategy (string): How to combine parallel edges that map to the same pair of detectors. One of "disallow" (default for the H-only path), "independent", "smallest_weight", "keep_original", or "replace".

    • O (tensor, optional): A num_observables x block_size binary matrix used to project error frames into observable flips. Its presence does not select the result basis. Request observable output explicitly with output="observables" in Python or cudaq::qec::decode_result_type::observables in C++. When observable output is requested, merge_strategy defaults to "independent" to match PyMatching’s detector-error-model construction. Supplying O while requesting error output leaves the default as "disallow".

Chromobius Decoder

class cudaq_qec.relay_solutions.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_decoder API 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 the cudaq_qec.Decoder interface for Python and the cudaq::qec::decoder interface 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_size correction 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’s opt_results under 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 (@cudaq.kernel decorated functions) to interact with realtime decoders.

cudaq_qec.qec.enqueue_syndromes(decoder_id, syndromes, tag)

Enqueue syndrome measurements for decoding.

Parameters:
  • decoder_id – Unique identifier for the decoder instance (matches configured decoder ID)

  • syndromes – List of syndrome measurement results from stabilizer measurements

  • tag – Which round this is; identifies the round for logging and ordering

Example:

import cudaq
import cudaq_qec as qec
from cudaq_qec import patch

@cudaq.kernel
def measure_and_decode(logical: patch, decoder_id: int):
    syndromes = measure_stabilizers(logical)
    qec.enqueue_syndromes(decoder_id, syndromes, 0)
cudaq_qec.qec.enqueue_syndromes_mapped(decoder_id, syndromes, tag, syndrome_mapping_id)

Enqueue syndrome measurements, naming the syndrome_mapping row this round belongs to.

A separate function rather than an optional argument on cudaq_qec.qec.enqueue_syndromes(), because a device kernel carries one argument count per name.

Parameters:
  • decoder_id – Unique identifier for the decoder instance

  • syndromes – List of syndrome measurement results from stabilizer measurements

  • tag – Which round this is

  • syndrome_mapping_id – Which syndrome_mapping row describes this round. tag says which round it is, this says what kind. 0 is the pass-through bulk row present in every configuration; naming a row declared type: final ends the shot, committing whatever a guarded window is still withholding. An id no row declares is rejected.

Example:

import cudaq
import cudaq_qec as qec

# decoders: ...
# syndrome_mapping:
#   - {id: 1, type: final}

@cudaq.kernel
def shot(decoder_id: int, num_rounds: int):
    q = cudaq.qvector(4)
    for r in range(num_rounds):
        syndromes = mz(q)
        if r + 1 == num_rounds:
            qec.enqueue_syndromes_mapped(decoder_id, syndromes, r, 1)
        else:
            qec.enqueue_syndromes(decoder_id, syndromes, r)
cudaq_qec.qec.get_corrections(decoder_id, return_size, reset)

Retrieve calculated corrections from the decoder.

Parameters:
  • decoder_id – Unique identifier for the decoder instance

  • return_size – Number of correction bits to return (typically equals number of logical observables)

  • reset – Whether to reset accumulated corrections after retrieval

Returns:

List of boolean values indicating detected bit flips for each logical observable

Example:

@cudaq.kernel
def apply_corrections(logical: patch, decoder_id: int):
    corrections = qec.get_corrections(decoder_id, 1, False)
    if corrections[0]:
        x(logical.data)  # Apply transversal X correction
cudaq_qec.qec.get_logical_measurements(decoder_id, first, return_size, reset)

Retrieve logical measurements from the decoder: the raw logical readout with the decoder’s corrections applied. Only a task graph with a logical output has them; a parallel_window pattern with output: corrections_and_logical wires one (see Logical Measurements). Each is released once its readout has arrived and every correction that can flip it is committed; a mid-circuit readout can be released mid-shot, and all are by the type: final syndrome_mapping row that ends the shot. A read of measurements not yet released fails: the decoding server answers NOT_READY. A read with reset consumes the shot for this call and get_corrections alike, so read the logical measurements before a get_corrections that resets.

Parameters:
  • decoder_id – Unique identifier for the decoder instance

  • first – The first logical measurement to return

  • return_size – Number of logical measurements to return, from first

  • reset – Whether to consume the shot after retrieval, as get_corrections does; only once the shot has ended, since the logical measurements apply every correction it commits

Returns:

List of boolean values, logical measurements [first, first + return_size)

Example:

@cudaq.kernel
def read_logical(decoder_id: int, num_rounds: int) -> bool:
    q = cudaq.qvector(4)
    for r in range(num_rounds - 1):
        qec.enqueue_syndromes(decoder_id, mz(q), r)
    qec.enqueue_syndromes_mapped(decoder_id, mz(q), num_rounds - 1, 1)
    return qec.get_logical_measurements(decoder_id, 0, 1, True)[0]
cudaq_qec.qec.reset_decoder(decoder_id)

Reset decoder state, clearing all queued syndromes and accumulated corrections.

Parameters:

decoder_id – Unique identifier for the decoder instance to reset

Example:

@cudaq.kernel
def run_experiment(decoder_id: int):
    qec.reset_decoder(decoder_id)  # Reset at start of each shot
    # ... perform experiment ...

Configuration API

The configuration API enables setting up decoders before circuit execution. Decoders are configured using YAML files or programmatically constructed configuration objects.

Decoder Parameters

Decoder-specific parameters (decoder_config.decoder_custom_args) are plain dicts. The set of accepted keys, their types, and which are required are defined by the parameter schema each decoder registers – including out-of-tree decoder plugins. Use cudaq_qec.decoder_param_schema(name) to inspect a decoder’s parameters and cudaq_qec.registered_decoder_schemas() to list all decoders with registered schemas.

For example, model error rates may be assigned to the top-level decoder_config.error_rate_vec field, while the pymatching decoder’s custom merge_strategy is one of "disallow", "independent", "smallest_weight", "keep_original", or "replace". Emitted YAML retains the established spelling under decoder_custom_args. Input YAML accepts either location, but rejects a configuration that supplies both:

config.type = "pymatching"
config.error_rate_vec = [0.1, 0.1, 0.1]
config.decoder_custom_args = {
    "merge_strategy": "smallest_weight",
}

The corresponding YAML keeps the error rates in the compatibility location:

decoder_custom_args:
  error_rate_vec: [0.1, 0.1, 0.1]
  merge_strategy: smallest_weight

The trt_decoder accepts onnx_load_path or engine_load_path (mutually exclusive), required engine_output_format ("errors", "residual_detectors", "observables", or "observables_and_residual_detectors"), engine_save_path, precision ("best", "tf32", or "noTF32"; legacy "fp16", "bf16", "int8", and "fp8" values are accepted but ignored for strongly typed networks), memory_workspace (bytes), batch_size, use_cuda_graph, and an optional global decoder attached via global_decoder plus global_decoder_params (a nested dict whose keys follow the schema of the named global decoder).

cudaq_qec.decoder_param_schema(decoder_name)

Return the registered parameter schema for a decoder as a list of descriptors (key, kind, required, and, for nested sections, subschema or discriminator), or None when the decoder has not registered one.

cudaq_qec.registered_decoder_schemas()

Names of all decoders (and nested parameter sections) with registered parameter schemas.

cudaq_qec.decoder_config_json_schema()

Return a JSON Schema (draft 2020-12) document, as a string, that validates multi_decoder_config YAML files. Generated from the decoder parameter schemas registered in this installation (including loaded third-party decoder plugins), for use with standard tools such as check-jsonschema, the python jsonschema package, or editor YAML language servers. Schema validation hooks are not representable in JSON Schema, so a passing document may still be rejected when parsed.

decoder_config.validate_custom_args()

Validate decoder_custom_args against the parameter schema registered for this decoder type: unknown keys, missing required keys, and the schema’s own validation hook. Raises RuntimeError on the first violation. YAML parsing applies the same checks automatically; call this to vet a configuration built programmatically before using it. Also available on multi_decoder_config to validate every decoder at once.

Deprecated Typed Configuration Classes

The typed configuration classes from earlier releases (nv_qldpc_decoder_config, trt_decoder_config, pymatching_config, chromobius_config, multi_error_lut_config, and the qecrt.config-level single_error_lut_config, sliding_window_config, and srelay_bp_config) remain available as deprecated compatibility shims. They emit a DeprecationWarning on construction and will be removed in a future release; existing code that builds one and passes it to decoder_config.set_decoder_custom_args (or assigns it to decoder_config.decoder_custom_args) continues to work unchanged. Note that reading decoder_custom_args now always returns a plain dict, never a typed object. New code should assign dicts directly, as shown above.

Configuration Functions

cudaq_qec.configure_decoders(config)

Configure decoders from a multi_decoder_config object.

Parameters:

config – multi_decoder_config object containing decoder specifications

Returns:

0 on success, non-zero error code on failure

cudaq_qec.configure_decoders_from_file(config_file)

Configure decoders from a YAML file.

Parameters:

config_file – Path to YAML configuration file

Returns:

0 on success, non-zero error code on failure

cudaq_qec.configure_decoders_from_str(config_str)

Configure decoders from a YAML string.

Parameters:

config_str – YAML configuration as a string

Returns:

0 on success, non-zero error code on failure

cudaq_qec.finalize_decoders()

Finalize and clean up decoder resources. Should be called before program exit.

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(pcm)

Convert a parity check matrix (PCM) to sparse vector representation for decoder configuration.

Parameters:

pcm – Dense binary matrix as numpy array (e.g., dem.detector_error_matrix or dem.observables_flips_matrix)

Returns:

Sparse vector (list of integers) where -1 separates rows

Usage in realtime decoding:

config.H_sparse = qec.pcm_to_sparse_vec(dem.detector_error_matrix)
config.O_sparse = qec.pcm_to_sparse_vec(dem.observables_flips_matrix)
cudaq_qec.pcm_from_sparse_vec(sparse_vec, num_rows, num_cols)

Convert sparse vector representation back to a dense parity check matrix.

Parameters:
  • sparse_vec – Sparse representation (from YAML or decoder config)

  • num_rows – Number of rows in the output matrix

  • num_cols – Number of columns in the output matrix

Returns:

Dense binary matrix as numpy array

cudaq_qec.d_sparse(m2d)

Flatten a measurement-to-detector map into the -1-terminated sparse vector a realtime decoder config expects for its D_sparse.

Parameters:

m2d – List of lists of measurement indices. m2d[d] contains the measurement indices whose XOR forms detector d. Obtain this from the second element of the tuple returned by DecoderContext.x_component(), DecoderContext.z_component(), or DecoderContext.full_component().

Returns:

-1-terminated sparse vector suitable for decoder_config.D_sparse

Usage in realtime decoding:

ctx = qec.decoder_context_from_memory_circuit(code, statePrep, num_rounds, noise)
dem, m2d, m2o = ctx.z_component()  # or x_component() / full_component()
config.D_sparse = qec.d_sparse(m2d)

See also Parity Check Matrix Utilities for additional PCM manipulation functions.

Common

cudaq_qec.sample_memory_circuit(code: cudaq_qec.Code, numShots: int, numRounds: int, noise: cudaq.NoiseModel | None = None) → tuple
cudaq_qec.sample_memory_circuit(code: cudaq_qec.Code, op: cudaq_qec.operation, numShots: int, numRounds: int, noise: cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.NoiseModel | None = None) → tuple

Overloaded function.

  1. sample_memory_circuit(code: cudaq_qec.Code, numShots: int, numRounds: int, noise: cudaq.NoiseModel | None = None) -> tuple

Sample the memory circuit of the code

  1. sample_memory_circuit(code: cudaq_qec.Code, op: cudaq_qec.operation, numShots: int, numRounds: int, noise: cudaq.NoiseModel | None = None) -> tuple

Sample the memory circuit of the code with a specific initial operation. Returns (syndromes, data): syndromes has numFixed boundary detectors (basis matching op), then one block per inter-round transition, then numFixed more boundary detectors.

cudaq_qec.x_sample_memory_circuit(code: cudaq_qec.Code, op: cudaq_qec.operation, numShots: int, numRounds: int, noise: cudaq.NoiseModel | None = None) → tuple

Sample the memory circuit of the code with a specific initial operation, keeping only the X stabilizer syndromes (same detector layout as sample_memory_circuit, restricted to X stabilizers).

cudaq_qec.z_sample_memory_circuit(code: cudaq_qec.Code, op: cudaq_qec.operation, numShots: int, numRounds: int, noise: cudaq.NoiseModel | None = None) → tuple

Sample the memory circuit of the code with a specific initial operation, keeping only the Z stabilizer syndromes (same detector layout as sample_memory_circuit, restricted to Z stabilizers).

Note

Syndrome measurement layout — sample_memory_circuit returns a tuple (syndromes, data). The syndromes tensor has shape (num_shots, num_detectors) with columns laid out as [ B  S  S  …  S  B ]:

  • B (boundary block) = code.get_num_z_stabilizers() for Z-basis preparations (prep0/prep1), or code.get_num_x_stabilizers() for X-basis preparations (prepp/prepm).

  • S (inter-round block) = num_z_stabilizers + num_x_stabilizers detectors per round transition (num_rounds - 1 blocks total).

  • Total: num_detectors = 2*B + (num_rounds - 1)*S.

The data tensor has shape (num_shots, block_size) and holds the final data-qubit measurements used to verify logical-state preservation.

cudaq_qec.sample_code_capacity(code: cudaq_qec.Code, numShots: int, errorProb: float, seed: int | None = None) → tuple
cudaq_qec.sample_code_capacity(H: numpy.ndarray[dtype=uint8], numShots: int, errorProb: float, seed: int | None = None) → tuple

Sample syndrome measurements with code capacity noise.

Detector Error Model (DEM) Sampling

cudaq_qec.dem_sampling(check_matrix, num_shots: int, error_probabilities, seed: Optional[int] = None, backend: str = 'auto') → Tuple[object, object]

Sample errors and syndromes from a Detector Error Model.

Parameters:
  • check_matrix – Binary matrix [num_checks x num_error_mechanisms], as a NumPy uint8 array or PyTorch CUDA tensor.

  • num_shots – Number of independent Monte-Carlo shots.

  • error_probabilities – 1-D array of length num_error_mechanisms with independent Bernoulli probabilities for each mechanism. Accepts NumPy float64 array or PyTorch CUDA tensor.

  • seed – Optional RNG seed for reproducibility.

  • backend – Backend selection policy: - “auto” (default): try GPU, fall back to CPU. - “cpu”: force CPU implementation. - “gpu”: force GPU implementation and raise if unavailable.

Returns:

(syndromes, errors) where

syndromes: uint8 array/tensor [num_shots x num_checks] errors: uint8 array/tensor [num_shots x num_error_mechanisms]

The GPU path uses cuStabilizer for accelerated sampling. When PyTorch CUDA tensors are provided, outputs are returned as CUDA tensors. Otherwise, outputs are NumPy arrays.

PyTorch CPU tensors are moved to CUDA under backend="gpu" (raising a GPU-unavailable error if there is no GPU) but rejected under "auto"/"cpu"; convert to NumPy first for the CPU path. PyTorch is an optional dependency; install with pip install torch.

Parity Check Matrix Utilities

cudaq_qec.generate_random_pcm(n_rounds: int, n_errs_per_round: int, n_syndromes_per_round: int, weight: int, seed: int = 0) → object

Generate a random parity check matrix.

This function creates a random parity check matrix for quantum error correction with specified parameters controlling the structure and randomness.

Parameters:
  • n_rounds – Number of measurement rounds in the error correction protocol

  • n_errs_per_round – Number of error mechanisms per round

  • n_syndromes_per_round – Number of syndrome measurements per round

  • weight – The weight parameter controlling the sparsity of the matrix

  • seed – Random seed for reproducibility (0 for random seed)

See also

cudaq::qec::generate_random_pcm(): The underlying C++ implementation of this function.

Returns:

A NumPy array containing the generated parity check matrix

cudaq_qec.generate_timelike_sparse_detector_matrix(num_syndromes_per_round: int, num_rounds: int, include_first_round: bool) → list[int]

Generate a sparse detector matrix for a given number of syndromes per round and number of rounds. Time-like here means that each round of syndrome measurement bits are xor’d against the preceding round.

Parameters:
  • num_syndromes_per_round – The number of syndrome measurements per round

  • num_rounds – The number of rounds to generate the sparse detector matrix for

  • include_first_round – Whether to include the first round of syndrome measurements

Returns:

The detector matrix format is CSR-like, with -1 values indicating the end of each row.

cudaq_qec.get_pcm_for_rounds(H: numpy.ndarray[dtype=uint8], num_syndromes_per_round: int, start_round: int, end_round: int, straddle_start_round: bool = False, straddle_end_round: bool = False, num_boundary_syndromes: int = 0) → tuple

Get a sub-PCM for a range of rounds.

This function returns a sub-parity check matrix for a range of rounds.

Parameters:
  • H – A NumPy array representing the parity check matrix

  • num_syndromes_per_round – The number of syndrome measurements per round

  • start_round – The starting round

  • end_round – The ending round

  • straddle_start_round – Whether to allow error mechanisms that straddle the start round (i.e. include prior rounds, too). This defaults to false.

  • straddle_end_round – Whether to allow error mechanisms that straddle the end round (i.e. include future rounds, too). This defaults to false.

  • num_boundary_syndromes – The number of syndrome measurements in the boundary layers

Returns:

A tuple containing the sub-parity check matrix and the first and last column indices of the sub-PCM relative to the original PCM.

See also

cudaq::qec::get_pcm_for_rounds(): The underlying C++ implementation of this function.

cudaq_qec.get_sorted_pcm_column_indices(H: numpy.ndarray[dtype=uint8], num_syndromes_per_round: int = 0) → list[int]

Get the sorted column indices of a parity check matrix.

This function returns the column indices of a parity check matrix in topological order.

Parameters:
  • H – A NumPy array representing the parity check matrix

  • num_syndromes_per_round – The number of syndrome measurements per round

Returns:

A NumPy array containing the sorted column indices

See also

cudaq::qec::get_sorted_pcm_column_indices(): The underlying C++ implementation of this function.

cudaq_qec.pcm_extend_to_n_rounds(H: numpy.ndarray[dtype=uint8], num_syndromes_per_round: int, n_rounds: int) → tuple

Extend a parity check matrix to a given number of rounds.

This function extends a parity check matrix to a given number of rounds.

Parameters:
  • H – A NumPy array representing the parity check matrix

  • num_syndromes_per_round – The number of syndrome measurements per round

  • n_rounds – The number of rounds to extend the parity check matrix to

Returns:

A tuple containing the extended parity check matrix and the list of column indices from the original PCM that were used to form the new PCM.

See also

cudaq::qec::pcm_extend_to_n_rounds(): The underlying C++ implementation of this function.

cudaq_qec.pcm_is_sorted(H: numpy.ndarray[dtype=uint8], num_syndromes_per_round: int = 0) → bool

Check if a parity check matrix is sorted.

This function checks if a parity check matrix is sorted in topological order.

Parameters:
  • H – A NumPy array representing the parity check matrix

  • num_syndromes_per_round – The number of syndrome measurements per round

Returns:

A boolean indicating if the parity check matrix is sorted

See also

cudaq::qec::pcm_is_sorted(): The underlying C++ implementation of this function.

cudaq_qec.pcm_to_sparse_vec(pcm: object) → list[int]

Return a sparse representation of the PCM.

Parameters:

pcm – A NumPy array or scipy sparse matrix.

cudaq_qec.reorder_pcm_columns(H: object, column_order: collections.abc.Sequence[int]) → object

Reorder the columns of a parity check matrix.

This function reorders the columns of a parity check matrix according to the given column order.

Parameters:
  • H – A NumPy array or scipy sparse matrix

  • column_order – A NumPy array containing the column order

Returns:

A NumPy array, or a scipy CSC matrix when H is scipy sparse.

See also

cudaq::qec::reorder_pcm_columns(): The underlying C++ implementation of this function.

cudaq_qec.shuffle_pcm_columns(H: object, seed: int = 0) → object

Shuffle the columns of a parity check matrix.

This function shuffles the columns of a parity check matrix.

Parameters:
  • H – A NumPy array or scipy sparse matrix

  • seed – Random seed for reproducibility (0 for random seed)

Returns:

A NumPy array, or a scipy CSC matrix when H is scipy sparse.

See also

cudaq::qec::shuffle_pcm_columns(): The underlying C++ implementation of this function.

cudaq_qec.simplify_pcm(H: numpy.ndarray[dtype=uint8], weights: numpy.ndarray[dtype=float64], num_syndromes_per_round: int) → tuple

Simplify a parity check matrix.

This function simplifies a parity check matrix by removing duplicate columns and 0-weight columns.

Parameters:
  • H – A NumPy array representing the parity check matrix

  • weights – A NumPy array containing the weights of the columns

  • num_syndromes_per_round – The number of syndrome measurements per round

Returns:

A tuple containing the simplified parity check matrix and the weights

See also

cudaq::qec::simplify_pcm(): The underlying C++ implementation of this function.

cudaq_qec.sort_pcm_columns(H: numpy.ndarray[dtype=uint8], num_syndromes_per_round: int = 0) → object

Sort the columns of a parity check matrix.

This function sorts the columns of a parity check matrix in topological order.

Parameters:
  • H – A NumPy array representing the parity check matrix

  • num_syndromes_per_round – The number of syndrome measurements per round

Returns:

A NumPy array containing the sorted parity check matrix

See also

cudaq::qec::sort_pcm_columns(): The underlying C++ implementation of this function.