Decoders

In quantum error correction, decoders are responsible for interpreting measurement outcomes (syndromes) to identify and correct quantum errors. We measure a set of stabilizers that give us information about what errors might have happened. The pattern of these measurements is called a syndrome, and the decoder’s task is to determine what errors most likely caused that syndrome.

The relationship between errors and syndromes is captured mathematically by the parity check matrix. Each row of this matrix represents a stabilizer measurement, while each column represents a possible error. When we multiply an error pattern by this matrix, we get the syndrome that would result from those errors.

For examples that construct, sample, and decode with detector error models (DEMs), see Working with Detector Error Models.

Getting Started with the NVIDIA QLDPC Decoder

The following sections describe built-in decoders that consume parity check matrices and detector error models. Each is selected by name through cudaq_qec.get_decoder() and targets a different regime, trading off speed, accuracy, and the class of codes it supports. We begin with the most general.

Starting with CUDA-Q QEC v0.2, a GPU-accelerated decoder is included with the CUDA-Q QEC library. The library follows the CUDA-Q decoder Python and C++ interfaces (namely cudaq_qec.Decoder for Python and cudaq::qec::decoder for C++), but as documented in the API sections (NVIDIA QLDPC Decoder for Python and NVIDIA QLDPC Decoder for C++), there are many configuration options that can be passed to the constructor.

Belief Propagation Methods

The nv-qldpc-decoder supports several belief-propagation algorithms – sum-product, min-sum, and memory-based variants, plus Sequential Relay BP – selected via bp_method and composition, with optional BP+OSD post-processing. For the complete list of methods, parameters, and defaults, see the nv-qldpc-decoder entries in the C++ and Python API reference.

Usage Example

The following example shows how to exercise the decoder using non-trivial pre-generated test data. The test data was generated using scripts originating from the GitHub repo for BivariateBicycleCodes [1]; it includes parity check matrices (PCMs) and test syndromes to exercise a decoder.

The example demonstrates:

  1. Basic decoder configuration with OSD post-processing

  2. All BP methods including Sequential Relay BP

  3. Batched decoding for improved performance


import numpy as np
from scipy.sparse import csr_matrix
import cudaq_qec as qec
import json
import time

# For fetching data
import requests
import bz2
import os

# Note: running this script will automatically download data if necessary.

### Helper functions ###


def parse_csr_mat(j, dims, mat_name):
    """
    Parse a CSR-style matrix from a JSON file using SciPy's sparse matrix utilities.
    """
    assert len(dims) == 2, "dims must be a tuple of two integers"

    # Extract indptr and indices from the JSON.
    indptr = np.array(j[f"{mat_name}_indptr"], dtype=int)
    indices = np.array(j[f"{mat_name}_indices"], dtype=int)

    # Check that the CSR structure is consistent.
    assert len(indptr) == dims[0] + 1, "indptr length must equal dims[0] + 1"
    assert np.all(
        indices < dims[1]), "All column indices must be less than dims[1]"

    # Create a data array of ones.
    data = np.ones(indptr[-1], dtype=np.uint8)

    # Build and return the sparse matrix directly — no dense allocation.
    return csr_matrix((data, indices, indptr), shape=dims, dtype=np.uint8)


def parse_H_csr(j, dims):
    """
    Parse a CSR-style parity check matrix from an input file in JSON format"
    """
    return parse_csr_mat(j, dims, "H")


def parse_obs_csr(j, dims):
    """
    Parse a CSR-style observable matrix from an input file in JSON format"
    """
    return parse_csr_mat(j, dims, "obs_mat").toarray()


### Main decoder loop ###


def run_decoder(filename, num_shots, run_as_batched):
    """
    Load a JSON file and decode "num_shots" syndromes.
    """
    t_load_begin = time.time()
    with open(filename, "r") as f:
        j = json.load(f)

    dims = j["shape"]
    assert len(dims) == 2

    # Read the Parity Check Matrix
    H = parse_H_csr(j, dims)
    syndrome_length, block_length = dims
    t_load_end = time.time()

    print(f"{filename} parsed in {1e3 * (t_load_end-t_load_begin)} ms")

    error_rate_vec = np.array(j["error_rate_vec"])
    assert len(error_rate_vec) == block_length
    obs_mat_dims = j["obs_mat_shape"]
    obs_mat = parse_obs_csr(j, obs_mat_dims)
    assert dims[1] == obs_mat_dims[0]
    file_num_trials = j["num_trials"]
    num_shots = min(num_shots, file_num_trials)
    print(
        f'Your JSON file has {file_num_trials} shots. Running {num_shots} now.')

    # osd_method: 0=Off, 1=OSD-0, 2=Exhaustive, 3=Combination Sweep
    osd_method = 1

    # When osd_method is:
    #  2) there are 2^osd_order additional error mechanisms checked.
    #  3) there are an additional k + osd_order*(osd_order-1)/2 error
    #     mechanisms checked.
    # Ref: https://arxiv.org/pdf/2005.07016
    osd_order = 0

    # Maximum number of BP iterations before attempting OSD (if necessary)
    max_iter = 50

    nv_dec_args = {
        "max_iterations": max_iter,
        "error_rate_vec": error_rate_vec,
        "use_sparsity": True,
        "use_osd": osd_method > 0,
        "osd_order": osd_order,
        "osd_method": osd_method
    }

    if run_as_batched:
        # Perform BP processing for up to 1000 syndromes per batch. If there
        # are more than 1000 syndromes, the decoder will chunk them up and
        # process each batch sequentially under the hood.
        nv_dec_args['bp_batch_size'] = min(1000, num_shots)

    try:
        nv_dec_gpu_and_cpu = qec.get_decoder("nv-qldpc-decoder", H,
                                             **nv_dec_args)
    except Exception as e:
        print(
            'The nv-qldpc-decoder is not available with your current CUDA-Q ' +
            'QEC installation.')
        exit(0)
    decoding_time = 0
    bp_converged_flags = []
    num_logical_errors = 0

    # Batched API
    if run_as_batched:
        syndrome_list = []
        obs_truth_list = []
        for i in range(num_shots):
            syndrome = j["trials"][i]["syndrome_truth"]
            obs_truth = j["trials"][i]["obs_truth"]
            syndrome_list.append(syndrome)
            obs_truth_list.append(obs_truth)
        t0 = time.time()
        results = nv_dec_gpu_and_cpu.decode_batch(syndrome_list)
        t1 = time.time()
        decoding_time += t1 - t0
        for r, obs_truth in zip(results, obs_truth_list):
            bp_converged_flags.append(r.converged)
            dec_result = np.array(r.result, dtype=np.uint8)

            # See if this prediction flipped the observable
            predicted_observable = obs_mat.T @ dec_result % 2
            print(f"predicted_observable: {predicted_observable}")

            # See if the observable was actually flipped according to the truth
            # data
            actual_observable = np.array(obs_truth, dtype=np.uint8)
            print(f"actual_observable:    {actual_observable}")

            if np.sum(predicted_observable != actual_observable) > 0:
                num_logical_errors += 1

    # Non-batched API
    else:
        for i in range(num_shots):
            syndrome = j["trials"][i]["syndrome_truth"]
            obs_truth = j["trials"][i]["obs_truth"]

            t0 = time.time()
            results = nv_dec_gpu_and_cpu.decode(syndrome)
            bp_converged = results.converged
            dec_result = results.result
            t1 = time.time()
            trial_diff = t1 - t0
            decoding_time += trial_diff

            dec_result = np.array(dec_result, dtype=np.uint8)
            bp_converged_flags.append(bp_converged)

            # See if this prediction flipped the observable
            predicted_observable = obs_mat.T @ dec_result % 2
            print(f"predicted_observable: {predicted_observable}")

            # See if the observable was actually flipped according to the truth
            # data
            actual_observable = np.array(obs_truth, dtype=np.uint8)
            print(f"actual_observable:    {actual_observable}")

            if np.sum(predicted_observable != actual_observable) > 0:
                num_logical_errors += 1

    # Count how many shots the decoder failed to correct the errors
    print(f"{num_logical_errors} logical errors in {num_shots} shots")
    print(
        f"Number of shots that converged with BP processing: {np.sum(np.array(bp_converged_flags))}"
    )
    print(
        f"Average decoding time for {num_shots} shots was {1e3 * decoding_time / num_shots} ms per shot"
    )


def demonstrate_bp_methods():
    """
    Demonstrate different BP methods available in nv-qldpc-decoder.
    Shows configurations for: sum-product, min-sum, memory BP, 
    disordered memory BP, and sequential relay BP.
    """
    # Simple 3x7 parity check matrix for demonstration
    H_list = [[1, 0, 0, 1, 0, 1, 1], [0, 1, 0, 1, 1, 0, 1],
              [0, 0, 1, 0, 1, 1, 1]]
    H = np.array(H_list, dtype=np.uint8)

    print("=" * 60)
    print("Demonstrating BP Methods in nv-qldpc-decoder")
    print("=" * 60)

    # Method 0: Sum-Product BP (default)
    print("\n1. Sum-Product BP (bp_method=0, default):")
    try:
        decoder_sp = qec.get_decoder("nv-qldpc-decoder",
                                     H,
                                     bp_method=0,
                                     max_iterations=30)
    except Exception as e:
        print(
            'The nv-qldpc-decoder is not available with your current CUDA-Q ' +
            'QEC installation.')
        exit(0)
    print("   Created decoder with sum-product BP")

    # Method 1: Min-Sum BP
    print("\n2. Min-Sum BP (bp_method=1):")
    decoder_ms = qec.get_decoder("nv-qldpc-decoder",
                                 H,
                                 bp_method=1,
                                 max_iterations=30,
                                 scale_factor=1.0)
    print("   Created decoder with min-sum BP")

    # Method 2: Min-Sum with uniform Memory (Mem-BP)
    print("\n3. Mem-BP (bp_method=2, uniform memory strength):")
    decoder_mem = qec.get_decoder("nv-qldpc-decoder",
                                  H,
                                  bp_method=2,
                                  max_iterations=30,
                                  use_sparsity=True,
                                  gamma0=0.5)
    print("   Created decoder with Mem-BP (gamma0=0.5)")

    # Method 3: Min-Sum with Disordered Memory (DMem-BP)
    print("\n4. DMem-BP (bp_method=3, disordered memory strength):")
    # Option A: Using gamma_dist (random gammas in range)
    decoder_dmem = qec.get_decoder("nv-qldpc-decoder",
                                   H,
                                   bp_method=3,
                                   max_iterations=30,
                                   use_sparsity=True,
                                   gamma_dist=[0.1, 0.5],
                                   bp_seed=42)
    print("   Created decoder with DMem-BP (gamma_dist=[0.1, 0.5])")

    # Option B: Using explicit_gammas (specify exact gamma for each variable)
    block_size = H.shape[1]
    explicit_gammas = [[0.1 + 0.05 * i for i in range(block_size)]]
    decoder_dmem_explicit = qec.get_decoder("nv-qldpc-decoder",
                                            H,
                                            bp_method=3,
                                            max_iterations=30,
                                            use_sparsity=True,
                                            explicit_gammas=explicit_gammas)
    print("   Created decoder with DMem-BP (explicit gammas)")

    # Method 4: Sequential Relay BP (composition=1)
    print("\n5. Sequential Relay BP (composition=1):")
    print("   Requires bp_method=3 and srelay_config")

    # Configure relay parameters
    srelay_config = {
        'pre_iter': 5,  # Run 5 iterations with gamma0 before relay legs
        'num_sets': 3,  # Use 3 relay legs
        'stopping_criterion': 'FirstConv'  # Stop after first convergence
    }

    # Option A: Using gamma_dist for relay legs
    decoder_relay = qec.get_decoder("nv-qldpc-decoder",
                                    H,
                                    bp_method=3,
                                    composition=1,
                                    max_iterations=50,
                                    use_sparsity=True,
                                    gamma0=0.3,
                                    gamma_dist=[0.1, 0.5],
                                    srelay_config=srelay_config,
                                    bp_seed=42)
    print("   Created decoder with Relay-BP (gamma_dist, FirstConv stopping)")

    # Option B: Using explicit gammas for each relay leg
    num_relay_legs = 3
    explicit_relay_gammas = [
        [0.1 + 0.02 * i for i in range(block_size)],  # First relay leg
        [0.2 + 0.03 * i for i in range(block_size)],  # Second relay leg
        [0.3 + 0.04 * i for i in range(block_size)]  # Third relay leg
    ]

    srelay_config_all = {
        'pre_iter': 10,
        'num_sets': 3,
        'stopping_criterion': 'All'  # Run all relay legs
    }

    decoder_relay_explicit = qec.get_decoder(
        "nv-qldpc-decoder",
        H,
        bp_method=3,
        composition=1,
        max_iterations=50,
        use_sparsity=True,
        gamma0=0.3,
        explicit_gammas=explicit_relay_gammas,
        srelay_config=srelay_config_all)
    print("   Created decoder with Relay-BP (explicit gammas, All legs)")

    # Option C: NConv stopping criterion
    srelay_config_nconv = {
        'pre_iter': 5,
        'num_sets': 10,
        'stopping_criterion': 'NConv',
        'stop_nconv': 3  # Stop after 3 convergences
    }

    decoder_relay_nconv = qec.get_decoder("nv-qldpc-decoder",
                                          H,
                                          bp_method=3,
                                          composition=1,
                                          max_iterations=50,
                                          use_sparsity=True,
                                          gamma0=0.3,
                                          gamma_dist=[0.1, 0.6],
                                          srelay_config=srelay_config_nconv,
                                          bp_seed=42)
    print("   Created decoder with Relay-BP (NConv stopping after 3)")

    print("\n" + "=" * 60)
    print("All decoder configurations created successfully!")
    print("=" * 60)


if __name__ == "__main__":
    # Demonstrate different BP methods (introduced in v0.5.0)
    print("\n### PART 1: BP Methods Demonstration ###\n")
    demonstrate_bp_methods()

    # Full decoding with test data
    print("\n\n### PART 2: Full Decoding Example with Test Data ###\n")

    # See other test data options in https://github.com/NVIDIA/cudaq-qec/releases/tag/0.2.0
    filename = 'osd_1008_8785_0.001.json'
    bz2filename = filename + '.bz2'
    if not os.path.exists(filename):
        url = f"https://github.com/NVIDIA/cudaq-qec/releases/download/0.2.0/{bz2filename}"

        print(f'Downloading data from {url}')

        # Download the file
        response = requests.get(url, stream=True)
        response.raise_for_status()  # Raise an error if download fails
        with open(bz2filename, "wb") as f:
            for chunk in response.iter_content(chunk_size=8192):
                f.write(chunk)

        print(f'Decompressing {bz2filename} into {filename}')

        # Decompress the file
        with bz2.BZ2File(bz2filename, "rb") as f_in, open(filename,
                                                          "wb") as f_out:
            f_out.write(f_in.read())

        print(f"Decompressed file saved as {filename}")

    num_shots = 100
    run_as_batched = True
    run_decoder(filename, num_shots, run_as_batched)

Footnotes

TCBP and JOBS

Decoding with TCBP and JOBS fits a TCBP model, decodes a batch of detector samples, and reads per-shot confidence information.

Exact Maximum Likelihood Decoding with NVIDIA Tensor Network Decoder

Where belief propagation trades exactness for speed, the tensor network decoder computes the exact maximum-likelihood correction — valuable as an accuracy baseline against which the faster decoders can be measured.

Starting with CUDA-Q QEC v0.4.0, a GPU-accelerated Maximum Likelihood Decoder is included with the CUDA-Q QEC library. The library follows the CUDA-Q decoder Python interface, namely cudaq_qec.Decoder. At this time, we only support the Python interface for the decoder, which is available at Tensor Network Decoder. As documented in the API sections Tensor Network Decoder, there are many configuration options that can be passed to the constructor. The decoder requires Python 3.11 or higher.

In the following example, we show how to use the TensorNetworkDecoder class from the cudaq_qec library to decode a circuit-level noise problem derived from a Stim surface code circuit.

"""
Example usage of tensor_network_decoder from cudaq-qec.

This script demonstrates how to instantiate and use the tensor network decoder
to decode a circuit level noise problem derived from a Stim surface code experiment.

This example requires the `cudaq-qec` package and the optional tensor-network-decoder dependencies.
To install the required dependencies, run:

pip install cudaq-qec[tensor-network-decoder]

Additionaly, in this example, you will need `stim` and `beliefmatching` packages:
pip install stim beliefmatching

"""
import cudaq_qec as qec
import numpy as np

import platform
if platform.machine().lower() in ("arm64", "aarch64"):
    print(
        "Warning: stim is not supported on manylinux ARM64/aarch64. Skipping this example..."
    )
    sys.exit(0)

import stim

from beliefmatching.belief_matching import detector_error_model_to_check_matrices


def parse_detector_error_model(detector_error_model):
    matrices = detector_error_model_to_check_matrices(detector_error_model)

    out_H = np.zeros(matrices.check_matrix.shape)
    matrices.check_matrix.astype(np.float64).toarray(out=out_H)
    out_L = np.zeros(matrices.observables_matrix.shape)
    matrices.observables_matrix.astype(np.float64).toarray(out=out_L)

    return out_H, out_L, [float(p) for p in matrices.priors]


def main():
    circuit = stim.Circuit.generated("surface_code:rotated_memory_z",
                                     rounds=3,
                                     distance=3,
                                     after_clifford_depolarization=0.001,
                                     after_reset_flip_probability=0.01,
                                     before_measure_flip_probability=0.01,
                                     before_round_data_depolarization=0.01)

    detector_error_model = circuit.detector_error_model(decompose_errors=True)

    H, logicals, noise_model = parse_detector_error_model(detector_error_model)

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

    num_shots = 5
    sampler = circuit.compile_detector_sampler()
    detection_events, observable_flips = sampler.sample(
        num_shots, separate_observables=True)

    res = decoder.decode_batch(detection_events)

    print("Tensor network prediction: ", [r.result[0] > 0.5 for r in res])
    print("Actual observable flips: ", [bool(o[0]) for o in observable_flips])


if __name__ == "__main__":
    main()

Output:

The decoder returns the probability that the logical observable has flipped for each syndrome. This can be used to assess the performance of the code and the decoder under different error scenarios.

See Also:

  • cudaq_qec.plugins.decoders.tensor_network_decoder

Deploying AI Decoders with TensorRT

The decoders above are algorithmic. CUDA-Q QEC can also deploy a learned decoder — a neural network trained on a specific code and noise model.

Starting with CUDA-Q QEC v0.5.0, a GPU-accelerated TensorRT-based decoder is included with the CUDA-Q QEC library. The TensorRT decoder (trt_decoder) enables users to leverage custom AI models for quantum error correction, providing a flexible framework for deploying trained models with optimized inference performance on NVIDIA GPUs.

Unlike traditional algorithmic decoders, neural network decoders can be trained on specific error models and code structures, potentially achieving superior performance for certain noise regimes. The TensorRT decoder supports loading models in ONNX format. Its strongly typed network preserves the data types and quantization encoded in the model; its precision option controls only the TensorRT TF32 build policy.

This tutorial demonstrates the complete workflow for training a simple multi-layer perceptron (MLP) to decode surface code syndromes using PyTorch and Stim, exporting the model to ONNX format, and deploying it with the TensorRT decoder for accelerated inference.

Overview of the Training-to-Deployment Pipeline

The workflow consists of three main stages:

  1. Data Generation: Use Stim to generate synthetic quantum error correction data by simulating surface code circuits with realistic noise models. This produces detector measurements (syndromes) and observable flips (logical errors) that serve as training data.

  2. Model Training: Train a neural network (in this case, an MLP) using PyTorch to learn the mapping from syndromes to logical error predictions. The model is trained with standard deep learning techniques including dropout regularization, learning rate scheduling, and validation monitoring.

  3. ONNX Export and Deployment: Export the trained PyTorch model to ONNX format, which can then be loaded by the TensorRT decoder for optimized GPU inference in production QEC workflows.

Training a Neural Network Decoder with PyTorch and Stim

The following example shows how to generate training data using Stim’s built-in surface code generator, train an MLP decoder with PyTorch, and export the model to ONNX format. For instructions on installing PyTorch, see Installing PyTorch.


import sys
import platform
if platform.machine().lower() in ("arm64", "aarch64"):
    print(
        "Warning: stim is not supported on manylinux ARM64/aarch64. Skipping this example..."
    )
    sys.exit(0)

import stim
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import TensorDataset, DataLoader

# --------------------------
# Parameters
# --------------------------
distance = 3  # Surface code distance (simpler for demo)
num_rounds = 3  # Rounds of stabilizer measurements
num_train_samples = 5000  # Training samples (more data)
num_val_samples = 1000  # Validation samples
num_test_samples = 1000  # Test samples
hidden_dim = 128  # Larger model capacity
error_prob = 0.005  # Balanced error rate for better learning

# --------------------------
# Build the surface code circuit
# --------------------------
# Use the built-in Stim surface code generator with noise
circuit = stim.Circuit.generated("surface_code:rotated_memory_x",
                                 distance=distance,
                                 rounds=num_rounds,
                                 after_clifford_depolarization=error_prob,
                                 after_reset_flip_probability=error_prob,
                                 before_measure_flip_probability=error_prob,
                                 before_round_data_depolarization=error_prob)

# Convert to detector error model
dem = circuit.detector_error_model()
with open("surface_code_decoder.dem", "w") as dem_file:
    dem_file.write(str(dem))
num_detectors = dem.num_detectors
num_data_qubits = circuit.num_qubits - num_detectors

print(f"Num data qubits: {num_data_qubits}, Num detectors: {num_detectors}")

# --------------------------
# Sample training, validation, and test data
# --------------------------
sampler = circuit.compile_detector_sampler()


def sample_data(num_samples):
    """Sample detector outcomes and observable flips."""
    X_data = []
    Y_data = []

    detector_samples, observable_samples = sampler.sample(
        num_samples, separate_observables=True)

    for i in range(num_samples):
        detectors = torch.tensor(detector_samples[i], dtype=torch.float32)
        observable = torch.tensor(observable_samples[i], dtype=torch.float32)
        X_data.append(detectors)
        Y_data.append(observable)

    return torch.stack(X_data), torch.stack(Y_data)


print(f"Sampling {num_train_samples} training samples...")
X_train, Y_train = sample_data(num_train_samples)

print(f"Sampling {num_val_samples} validation samples...")
X_val, Y_val = sample_data(num_val_samples)

print(f"Sampling {num_test_samples} test samples...")
X_test, Y_test = sample_data(num_test_samples)

num_observables = Y_train.shape[1]
print(f"Num observables: {num_observables}")


# --------------------------
# Improved Torch NN decoder with dropout and deeper architecture
# --------------------------
class SurfaceCodeDecoder(nn.Module):

    def __init__(self, input_dim, output_dim, hidden_dim=128, dropout=0.3):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(input_dim, hidden_dim * 2),  # 256
            nn.ReLU(),
            nn.Dropout(dropout),
            nn.Linear(hidden_dim * 2, hidden_dim),  # 128
            nn.ReLU(),
            nn.Dropout(dropout),
            nn.Linear(hidden_dim, hidden_dim // 2),  # 64
            nn.ReLU(),
            nn.Dropout(dropout),
            nn.Linear(hidden_dim // 2, output_dim),
            nn.Sigmoid())

    def forward(self, x):
        return self.net(x)


model = SurfaceCodeDecoder(input_dim=num_detectors,
                           output_dim=num_observables,
                           hidden_dim=hidden_dim,
                           dropout=0.3)
optimizer = optim.Adam(model.parameters(), lr=5e-4)  # Lower learning rate
scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer,
                                                 mode='min',
                                                 factor=0.5,
                                                 patience=20)
criterion = nn.BCELoss()

# Create DataLoaders for batch training
train_dataset = TensorDataset(X_train, Y_train)
val_dataset = TensorDataset(X_val, Y_val)
train_loader = DataLoader(train_dataset, batch_size=128, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=128, shuffle=False)


def compute_accuracy(predictions, targets, threshold=0.5):
    """Compute binary accuracy."""
    pred_binary = (predictions > threshold).float()
    correct = (pred_binary == targets).float().mean()
    return correct.item()


# --------------------------
# Train NN with validation
# --------------------------
epochs = 1000  # Train longer for better convergence
best_val_acc = 0.0
print("\nTraining started...")
print("=" * 70)

for epoch in range(epochs):
    # Training step with batches
    model.train()
    train_loss_total = 0.0
    train_correct = 0
    train_total = 0

    for batch_X, batch_Y in train_loader:
        optimizer.zero_grad()
        train_output = model(batch_X)
        train_loss = criterion(train_output, batch_Y)
        train_loss.backward()
        optimizer.step()

        train_loss_total += train_loss.item() * batch_X.size(0)
        train_correct += ((train_output > 0.5).float() == batch_Y).sum().item()
        train_total += batch_Y.numel()

    train_loss_avg = train_loss_total / len(train_loader.dataset)
    train_acc = train_correct / train_total

    # Validation step with batches
    model.eval()
    val_loss_total = 0.0
    val_correct = 0
    val_total = 0

    cum_ler = 0.0

    with torch.no_grad():

        for batch_X, batch_Y in val_loader:
            val_output = model(batch_X)
            val_loss = criterion(val_output, batch_Y)

            val_output_binary = (val_output > 0.5)
            ler = val_output_binary ^ (batch_Y > 0.5)
            # print(f"loss: {loss.sum().item() / loss.numel()}")
            cum_ler += ler.sum().item()
            # print(f"val_output_binary: {val_output_binary} ler: {ler} batch_Y: {batch_Y} ")

            # print(f"logical_error_rate (pred): {val_output.sum().item() / val_output.numel()}")
            # print(f"logical_error_rate (raw): {batch_Y.sum().item() / batch_Y.numel()}")

            val_loss_total += val_loss.item() * batch_X.size(0)
            val_correct += ((val_output > 0.5).float() == batch_Y).sum().item()
            val_total += batch_Y.numel()

    # print(f"logical_error_rate (raw): {batch_Y.sum().item() / batch_Y.numel()}")
    # print(f"cum_ler: {cum_ler / len(val_loader.dataset)}")

    val_loss_avg = val_loss_total / len(val_loader.dataset)
    val_acc = val_correct / val_total

    # Learning rate scheduling
    scheduler.step(val_loss_avg)

    # Save best model
    if val_acc > best_val_acc:
        best_val_acc = val_acc
        torch.save(model.state_dict(), "surface_code_decoder_best.pth")

    # Print progress every 10 epochs
    if (epoch + 1) % 10 == 0:
        print(
            f"Epoch {epoch+1:3d}/{epochs} | "
            f"Train Loss: {train_loss_avg:.4f} | Train Acc: {train_acc:.4f} | "
            f"Val Loss: {val_loss_avg:.4f} | Val Acc: {val_acc:.4f}")

print("=" * 70)
print(f"Training complete! Best validation accuracy: {best_val_acc:.4f}")

# --------------------------
# Load best model and evaluate on test set
# --------------------------
print("\nLoading best model and evaluating on test set...")
model.load_state_dict(torch.load("surface_code_decoder_best.pth"))
model.eval()

with torch.no_grad():
    test_output = model(X_test)
    test_loss = criterion(test_output, Y_test)
    test_acc = compute_accuracy(test_output, Y_test)

    # Additional metrics
    test_pred_binary = (test_output > 0.5).float()

    # Count logical errors
    total_actual_errors = Y_test.sum().item()
    total_predicted_errors = test_pred_binary.sum().item()
    correct_predictions = (test_pred_binary == Y_test).sum().item()
    total_predictions = Y_test.numel()

print("=" * 70)
print("TEST SET RESULTS:")
print("=" * 70)
print(f"Test Loss:                    {test_loss.item():.4f}")
print(f"Test Accuracy:                {test_acc:.4f} ({test_acc*100:.2f}%)")
print(
    f"Correct predictions:          {correct_predictions}/{total_predictions}")
print(f"Actual logical errors:        {int(total_actual_errors)}")
print(f"Predicted logical errors:     {int(total_predicted_errors)}")
print("=" * 70)

# --------------------------
# Export to ONNX
# --------------------------
print("\nExporting model to ONNX...")
torch.onnx.export(model,
                  X_train[:1],
                  "surface_code_decoder.onnx",
                  input_names=["detectors"],
                  output_names=["observable_probs"],
                  opset_version=17)
print("ONNX model saved as surface_code_decoder.onnx")
print("Detector error model saved as surface_code_decoder.dem")
print("PyTorch weights saved as surface_code_decoder_best.pth")

Using the TensorRT Decoder in CUDA-Q QEC

Once you have a trained ONNX model, you can load it with the TensorRT decoder for accelerated inference. The decoder can be used in both C++ and Python workflows. Keep the .dem file emitted by the training example beside the model: it fixes the detector and observable dimensions and the error-mechanism ordering that the model was trained against.

Loading from ONNX (with automatic TensorRT optimization):

import cudaq_qec as qec
import numpy as np

with open("surface_code_decoder.dem") as dem_file:
    dem_text = dem_file.read()
dem = qec.dem_from_stim_text(dem_text)

# The training model predicts logical observables, so both the engine
# tensor format and the public decoder result are explicit.
decoder = qec.get_decoder(
    "trt_decoder",
    dem_text,
    onnx_load_path="surface_code_decoder.onnx",
    engine_output_format="observables",
    output="observables")

# Decode a syndrome
syndrome = np.zeros(dem.num_detectors(), dtype=np.float32)
result = decoder.decode(syndrome)
print(f"Predicted observable: {result.result}")
#include "cudaq/qec/decoder.h"
#include "cuda-qx/core/heterogeneous_map.h"

#include <fstream>
#include <iterator>
#include <string>
#include <utility>
#include <vector>

int main() {
    std::ifstream dem_file("surface_code_decoder.dem");
    std::string dem_text((std::istreambuf_iterator<char>(dem_file)),
                         std::istreambuf_iterator<char>());
    auto inputs = cudaq::qec::decoder_init::from_stim_dem(dem_text);
    const auto syndrome_size = inputs.num_detectors();

    cudaqx::heterogeneous_map params;
    params.insert("onnx_load_path", "surface_code_decoder.onnx");
    params.insert("engine_output_format", std::string("observables"));

    // The training model predicts logical observables, so request that
    // result basis explicitly.
    auto decoder = cudaq::qec::get_decoder(
        "trt_decoder", std::move(inputs),
        cudaq::qec::decode_result_type::observables, params);

    std::vector<cudaq::qec::float_t> syndrome(syndrome_size, 0.0);
    auto result = decoder->decode(syndrome);

    return 0;
}

Loading a pre-built TensorRT engine (for fastest initialization):

If you’ve already converted your ONNX model to a TensorRT engine using the provided utility script, you can load it directly:

with open("surface_code_decoder.dem") as dem_file:
    dem_text = dem_file.read()

decoder = qec.get_decoder(
    "trt_decoder",
    dem_text,
    engine_load_path="surface_code_decoder.trt",
    engine_output_format="observables",
    output="observables")

Converting ONNX Models to TensorRT Engines

For production deployments where initialization time is critical, you can pre-build a TensorRT engine from your ONNX model using the trtexec command-line tool that comes with TensorRT:

# Build with FP16 precision
trtexec --onnx=surface_code_decoder.onnx \
        --saveEngine=surface_code_decoder.trt \
        --fp16

# Build with best precision for your GPU
trtexec --onnx=surface_code_decoder.onnx \
        --saveEngine=surface_code_decoder.trt \
        --best

# Build with specific input shape (optional, for optimization)
trtexec --onnx=surface_code_decoder.onnx \
        --saveEngine=surface_code_decoder.trt \
        --fp16 \
        --shapes=detectors:1x24

Pre-built engines offer several advantages:

  • Faster initialization: Engine loading is significantly faster than ONNX parsing and optimization

  • Reproducible optimization: The same optimization decisions are made every time

  • Version control: Engines can be versioned alongside code for reproducible deployments

Dependencies and Requirements

The TensorRT decoder requires:

  • TensorRT: Version 10.13.3.9 or higher

  • CUDA: Version 12.0 or higher for x86 and 13.0 for ARM.

  • GPU: NVIDIA GPU with compute capability 6.0+ (Pascal architecture or newer)

For training:

  • PyTorch: Version 2.0+ recommended

  • Stim: For quantum circuit simulation and data generation

See Also

Matching-Based Decoding with PyMatching

For codes whose errors pair up into a matching graph, a dedicated matching decoder is often the simplest and fastest choice. Starting with CUDA-Q QEC v0.7.0, CUDA-Q QEC bundles a minimum-weight perfect matching (MWPM) decoder built on the open-source PyMatching library, suitable for matchable codes such as the surface code. It is selected by name through cudaq_qec.get_decoder() and takes a parity-check matrix whose columns each have one or two set entries:

import cudaq_qec as qec
import numpy as np

H = np.array([[1, 1, 0],
              [0, 1, 1]], dtype=np.uint8)

dec = qec.get_decoder("pymatching", H,
                      error_rate_vec=[0.1, 0.1, 0.1],
                      merge_strategy="smallest_weight")
result = dec.decode(syndrome)

Per-error priors are supplied via error_rate_vec (values in (0, 0.5]), and parallel edges are combined according to merge_strategy. See the PyMatching Decoder API for the full list of options.

Color-Code Decoding with Chromobius

Matching applies to surface-code-like codes; color codes call for a decoder built around their structure. Starting with CUDA-Q QEC v0.7.0, CUDA-Q QEC bundles a color-code decoder built on the open-source Chromobius Möbius decoder. Unlike the matrix-based decoders, Chromobius is detector-error-model native: it is constructed from Stim detector-error-model (DEM) text rather than a parity-check matrix, and predicts logical observable flips directly.

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

Constructing Chromobius from a parity-check matrix is rejected with an error. See the Chromobius Decoder API for the available options.