CUDA-Q QEC Python API

Code

class cudaq_qec.Code

Represents a quantum error correction code

get_observables_x(self: cudaq_qec.Code) numpy.ndarray[numpy.uint8]

Get the Pauli X observables of the code

get_observables_z(self: cudaq_qec.Code) numpy.ndarray[numpy.uint8]

Get the Pauli Z observables of the code

get_parity(self: cudaq_qec.Code) numpy.ndarray[numpy.uint8]

Get the parity check matrix of the code

get_parity_x(self: cudaq_qec.Code) numpy.ndarray[numpy.uint8]

Get the X-type parity check matrix of the code

get_parity_z(self: cudaq_qec.Code) numpy.ndarray[numpy.uint8]

Get the Z-type parity check matrix of the code

get_pauli_observables_matrix(self: cudaq_qec.Code) numpy.ndarray[numpy.uint8]

Get a matrix of the Pauli observables of the code

get_stabilizers(self: cudaq_qec.Code) list[cudaq.SpinOperatorTerm]

Get the stabilizer generators of the code

Detector Error Model

cudaq_qec.dem_from_memory_circuit(code: cudaq_qec.Code, op: cudaq_qec.operation, numRounds: int, noise: Optional[cudaq.NoiseModel] = None) cudaq::qec::detector_error_model

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 optional and defaults to no noise.

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.

Returns:

A detector error model.

cudaq_qec.x_dem_from_memory_circuit(code: cudaq_qec.Code, op: cudaq_qec.operation, numRounds: int, noise: Optional[cudaq.NoiseModel] = None) cudaq::qec::detector_error_model

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 optional and defaults to no noise.

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.

Returns:

A detector error model.

cudaq_qec.z_dem_from_memory_circuit(code: cudaq_qec.Code, op: cudaq_qec.operation, numRounds: int, noise: Optional[cudaq.NoiseModel] = None) cudaq::qec::detector_error_model

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 optional and defaults to no noise.

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.

Returns:

A detector error model.

Decoder Interfaces

class cudaq_qec.Decoder

Represents a decoder for quantum error correction

decode(self: cudaq_qec.Decoder, syndrome: list[float]) cudaq_qec.DecoderResult

Decode the given syndrome to determine the error correction

decode_async(self: cudaq_qec.Decoder, syndrome: list[float]) cudaq_qec.AsyncDecoderResult

Asynchronously decode the given syndrome

decode_batch(self: cudaq_qec.Decoder, syndrome: list[list[float]]) list[cudaq_qec.DecoderResult]

Decode multiple syndromes and return the results

get_block_size(self: cudaq_qec.Decoder) int

Get the size of the code block

get_syndrome_size(self: cudaq_qec.Decoder) int

Get the size of the syndrome

get_version(self: cudaq_qec.Decoder) str

Get the version of the decoder

class cudaq_qec.DecoderResult

A class representing the results of a quantum error correction decoding operation.

This class encapsulates both the convergence status and the actual decoding result.

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.

Built-in Decoders

NVIDIA QLDPC Decoder

class cudaq_qec.nv_qldpc_decoder

A general purpose Quantum Low-Density Parity-Check Decoder (QLDPC) decoder based on GPU accelerated belief propagation (BP). Since belief propagation is an iterative method, decoding can be improved with a second-stage post-processing step. Optionally, ordered statistics decoding (OSD) can be chosen to perform the second stage of decoding.

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: Decoding Across the Quantum LDPC Code Landscape

Note

It is required to create decoders with the get_decoder API from the CUDA-QX 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
opts = dict() # see below for options
# Note: H must be in row-major order. If you use
# `scipy.sparse.csr_matrix.todense()` to get the parity check
# matrix, you must specify todense(order='C') to get a row-major
# matrix.
nvdec = qec.get_decoder('nv-qldpc-decoder', H, **opts)
std::size_t block_size = 7;
std::size_t syndrome_size = 3;
cudaqx::tensor<uint8_t> H;

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});

cudaqx::heterogeneous_map nv_custom_args;
nv_custom_args.insert("use_osd", true);
// See below for options

auto nvdec = cudaq::qec::get_decoder("nv-qldpc-decoder", H, 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 (tensor format)

  • params

    Heterogeneous map of parameters:

    • use_sparsity (bool): Whether or not to use a sparse matrix solver

    • error_rate (double): Probability of an error (in 0-1 range) on a block data bit (defaults to 0.001)

    • error_rate_vec (double): Vector of length “block size” containing the probability of an error (in 0-1 range) on a block data bit (defaults to 0.001). This overrides error_rate.

    • max_iterations (int): Maximum number of BP iterations to perform (defaults to 30)

    • n_threads (int): Number of CUDA threads to use for the GPU decoder (defaults to smart selection based on parity matrix size)

    • 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 (defaults to 1). Ignored unless use_osd is true.

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

    • 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 for OSD (defaults to the number of concurrent threads supported by the hardware)

    • 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): The BP method to use. 0 for sum-product, 1 for min-sum. Defaults to 0. Introduced in 0.4.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.

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

Tensor Network Decoder

class cudaq_qec.plugin.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.

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: “float32”)

  • 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

Common

cudaq_qec.sample_memory_circuit(*args, **kwargs)

Overloaded function.

  1. sample_memory_circuit(code: cudaq_qec.Code, numShots: int, numRounds: int, noise: Optional[cudaq.NoiseModel] = 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: Optional[cudaq.NoiseModel] = None) -> tuple

Sample the memory circuit of the code with a specific initial operation

cudaq_qec.sample_code_capacity(*args, **kwargs)

Overloaded function.

  1. sample_code_capacity(code: cudaq_qec.Code, numShots: int, errorProb: float, seed: Optional[int] = None) -> tuple

Sample syndrome measurements with code capacity noise.

  1. sample_code_capacity(H: numpy.ndarray[numpy.uint8], numShots: int, errorProb: float, seed: Optional[int] = None) -> tuple

Sample syndrome measurements with code capacity noise.

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.get_pcm_for_rounds(H: numpy.ndarray[numpy.uint8], num_syndromes_per_round: int, start_round: int, end_round: int, straddle_start_round: bool = False, straddle_end_round: bool = False) 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.

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[numpy.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[numpy.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[numpy.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.reorder_pcm_columns(H: numpy.ndarray[numpy.uint8], column_order: numpy.ndarray[numpy.uint32]) 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 representing the parity check matrix

  • column_order – A NumPy array containing the column order

Returns:

A NumPy array containing the reordered parity check matrix

See also

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

cudaq_qec.shuffle_pcm_columns(H: numpy.ndarray[numpy.uint8], 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 representing the parity check matrix

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

Returns:

A NumPy array containing the shuffled parity check matrix

See also

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

cudaq_qec.simplify_pcm(H: numpy.ndarray[numpy.uint8], weights: numpy.ndarray[numpy.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[numpy.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.