DEM sampling — Monte Carlo sampling from detector error models
This example samples synthetic error and syndrome data from a detector error model, then walks through the GPU-accelerated and CPU paths and the supported input types. For the sampling model itself, see DEM sampling.
Example
import numpy as np
import cudaq_qec as qec
# Define a check matrix for a [3,1] repetition code.
# Rows = checks (stabilizers), columns = error mechanisms.
H = np.array([[1, 1, 0], [0, 1, 1]], dtype=np.uint8)
# Independent error probability for each mechanism.
error_probs = np.array([0.05, 0.10, 0.05])
num_shots = 10
# Sample syndromes and errors from the detector error model.
# backend="auto" (default) tries GPU first, then falls back to CPU.
syndromes, errors = qec.dem_sampling(H, num_shots, error_probs, seed=42)
print(f"Check matrix H ({H.shape[0]} checks x {H.shape[1]} mechanisms):")
print(H)
print(f"\nError probabilities: {error_probs}")
print(f"\nSampled errors ({errors.shape}):\n{errors}")
print(f"\nSampled syndromes ({syndromes.shape}):\n{syndromes}")
# Verify: syndromes should equal (errors @ H^T) mod 2.
expected = (errors @ H.T) % 2
assert np.array_equal(syndromes, expected), "Mismatch!"
print("\nVerification passed: syndromes == (errors @ H^T) mod 2")
# Reproducibility: the same seed yields the same results.
s1, e1 = qec.dem_sampling(H, num_shots, error_probs, seed=123)
s2, e2 = qec.dem_sampling(H, num_shots, error_probs, seed=123)
assert np.array_equal(e1, e2)
print("Reproducibility check passed: same seed -> same output")
# Force the GPU backend explicitly. It raises RuntimeError when no GPU (or
# cuStabilizer) is available, so guard it for portability; backend="auto"
# instead falls back to CPU automatically.
try:
syndromes_gpu, errors_gpu = qec.dem_sampling(H,
num_shots,
error_probs,
seed=42,
backend="gpu")
print(f"\nGPU backend result shapes: syndromes {syndromes_gpu.shape}, "
f"errors {errors_gpu.shape}")
except RuntimeError as err:
print(
f"\nGPU backend unavailable ({err}); backend='auto' falls back to CPU.")
# Force the CPU backend explicitly.
syndromes_cpu, errors_cpu = qec.dem_sampling(H,
num_shots,
error_probs,
seed=42,
backend="cpu")
print(f"\nCPU backend result shapes: syndromes {syndromes_cpu.shape}, "
f"errors {errors_cpu.shape}")
// DEM Sampling — sample errors and syndromes from a detector error model.
//
// Compile and run with:
// nvq++ -lcudaq-qec dem_sampling.cpp
// ./a.out
#include <cstdint>
#include <iostream>
#include <vector>
#include "cudaq/qec/dem_sampling.h"
int main() {
// [3,1] repetition code check matrix:
// H = | 1 1 0 |
// | 0 1 1 |
std::vector<uint8_t> H_data = {1, 1, 0, 0, 1, 1};
size_t num_checks = 2;
size_t num_mechanisms = 3;
cudaqx::tensor<uint8_t> H({num_checks, num_mechanisms});
H.copy(H_data.data(), H.shape());
std::vector<double> error_probs = {0.05, 0.10, 0.05};
size_t num_shots = 10;
unsigned seed = 42;
// CPU sampling
auto [syndromes, errors] =
cudaq::qec::dem_sampler::cpu::sample_dem(H, num_shots, error_probs, seed);
std::cout << "Syndromes [" << syndromes.shape()[0] << " x "
<< syndromes.shape()[1] << "]:\n";
for (size_t shot = 0; shot < num_shots; shot++) {
for (size_t c = 0; c < num_checks; c++)
std::cout << static_cast<int>(syndromes.at({shot, c})) << " ";
std::cout << "\n";
}
std::cout << "\nErrors [" << errors.shape()[0] << " x " << errors.shape()[1]
<< "]:\n";
for (size_t shot = 0; shot < num_shots; shot++) {
for (size_t e = 0; e < num_mechanisms; e++)
std::cout << static_cast<int>(errors.at({shot, e})) << " ";
std::cout << "\n";
}
// Verify: syndromes == (errors * H^T) mod 2
bool ok = true;
for (size_t shot = 0; shot < num_shots && ok; shot++) {
for (size_t c = 0; c < num_checks && ok; c++) {
uint8_t expected = 0;
for (size_t e = 0; e < num_mechanisms; e++)
expected ^= errors.at({shot, e}) & H.at({c, e});
if (syndromes.at({shot, c}) != expected)
ok = false;
}
}
std::cout << "\nVerification: " << (ok ? "PASSED" : "FAILED") << "\n";
return ok ? 0 : 1;
}
Compile and run with
nvq++ -lcudaq-qec dem_sampling.cpp
./a.out
GPU Acceleration
When a CUDA-capable GPU is available, dem_sampling keeps the sampling and
syndrome computation on-device, which is significantly faster than per-shot CPU
sampling, especially for large numbers of shots and sparse error models (low
probabilities):
Sparse Bernoulli sampling — Errors are generated directly in compressed sparse row (CSR) format. For low error probabilities the CSR representation is compact, and the sampler skips mechanisms with zero probability entirely rather than evaluating a Bernoulli trial for every mechanism in every shot.
GF(2) sparse-dense matrix multiply — Syndromes are computed as \(\text{errors} \times H^T \pmod{2}\) using a sparse-dense multiply over GF(2). The check matrix \(H^T\) is stored in a bitpacked layout, reducing memory bandwidth by 8x compared to one byte per entry.
On-device packing and unpacking — \(H\) is transposed and bitpacked on the GPU in a single kernel. Syndromes are unpacked from the bitpacked result, and the dense error matrix is produced from the CSR representation via a fused zero-and-scatter kernel.
The CPU path uses std::bernoulli_distribution per mechanism per shot
followed by a dense dot product for the syndrome.
Input Types and Backend Selection
The backend parameter controls where sampling runs:
"auto"(default) — try GPU first, fall back to CPU."gpu"— require GPU; raiseRuntimeErrorif unavailable."cpu"— always use the CPU path.
The Python binding accepts several input types, each routed through a different code path:
NumPy arrays (most common) — When the GPU is available the bindings automatically allocate device memory, copy inputs host-to-device, run cuStabilizer, and copy results back as NumPy
uint8arrays. Withbackend="cpu"the GPU path is skipped entirely. No user action is required beyond passing standarduint8andfloat64arrays.PyTorch CUDA tensors — The GPU path reads input device pointers directly via
data_ptr()and writes outputs intotorch.emptytensors on the same device, avoiding any host-device copies. This is the fastest path when inputs are already on the GPU. PyTorch is an optional dependency; install withpip install torch.PyTorch CPU tensors — With
backend="gpu"the tensors are automatically moved to CUDA (via.to(device)) before sampling. Withbackend="auto"CPU tensors are rejected with an error; convert them to NumPy with.numpy()first.
The C++ API exposes two namespaces:
cudaq::qec::dem_sampler::cpu::sample_dem— takes acudaqx::tensorcheck matrix and astd::vector<double>of probabilities; returns(syndromes, errors)as tensors.cudaq::qec::dem_sampler::gpu::sample_dem— takes raw device pointers and writes results into caller-provided device buffers; returnsfalseif cuStabilizer is not available at runtime.
The gpu overload works with device pointers that you allocate, populate,
and free yourself. Guard the call behind a device-count check and fall back to
the cpu overload when it returns false:
#include "cudaq/qec/dem_sampling.h"
#include <cuda_runtime.h>
// H: [num_checks x num_mechanisms] uint8, probs: [num_mechanisms] double.
uint8_t *d_H, *d_syndromes, *d_errors;
double *d_probs;
cudaMalloc(&d_H, num_checks * num_mechanisms);
cudaMalloc(&d_probs, num_mechanisms * sizeof(double));
cudaMalloc(&d_syndromes, num_shots * num_checks);
cudaMalloc(&d_errors, num_shots * num_mechanisms);
cudaMemcpy(d_H, h_data, num_checks * num_mechanisms, cudaMemcpyHostToDevice);
cudaMemcpy(d_probs, prob_data, num_mechanisms * sizeof(double),
cudaMemcpyHostToDevice);
bool ok = cudaq::qec::dem_sampler::gpu::sample_dem(
d_H, num_checks, num_mechanisms, d_probs, num_shots, /*seed=*/42,
d_syndromes, d_errors);
if (!ok) {
// cuStabilizer unavailable at runtime — use the cpu overload instead.
}
// Copy d_syndromes / d_errors back to host, then cudaFree each buffer.
See Also
dem_sampling— Python API referencedem_sampler— C++ API reference