Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

PRISM-Q

An open-source quantum circuit simulator written in Rust, with Python bindings.

Start here

Bell pair

#![allow(unused)]
fn main() {
use prism_q::CircuitBuilder;

let result = CircuitBuilder::new(2).h(0).cx(0, 1).run(42).unwrap();
let probs = result.probabilities.unwrap();
// |00> = 0.5, |11> = 0.5
}

The same circuit from Python:

import prism_q

bell = prism_q.CircuitBuilder(2).h(0).cx(0, 1).build()
print(prism_q.simulate(bell).seed(42).run().probabilities)  # [0.5 0.  0.  0.5]

Simulation

A two-qubit Bell pair and a thousand-qubit Clifford circuit go through the same entry point, which picks a backend from the circuit's structure. Circuits pass through a multi-pass gate fusion pipeline, and the inner loops use AVX2, FMA and BMI2 (NEON on ARM64). Input is OpenQASM 3.0 with backward-compatible 2.0 syntax, and a circuit exports back to OpenQASM 3.0.

  • Nine CPU backends: statevector, stabilizer, factored stabilizer, sparse, MPS, product state, tensor network (on expectation and marginal queries) and factored, picked automatically, plus an exact density matrix selected by name.
  • Compiled shot samplers that do not rebuild the statevector for every shot, including the noisy and detector sampling paths.
  • Four Clifford+T engines (stabilizer rank, stochastic and deterministic Pauli propagation, and Pauli path) for circuits a dense statevector cannot hold.
  • Noise models built from rules or a device calibration table, with leakage, drift and timed idle noise, and a native QEC program path with detector sampling and decoding.
  • An optional CUDA path for statevector, stabilizer and density-matrix execution, and an optional MPI-distributed statevector for registers larger than one host's memory.
  • Python bindings with NumPy output.

Reference and tools

Installation

cargo add prism-q                          # Rayon parallelism + faer SVD (default)
cargo add prism-q --no-default-features    # single-threaded, minimal dependencies
pip install prism-q                        # Python bindings

cargo add writes the current release into Cargo.toml; to pin a version by hand, take it from crates.io.

Python

PyPI carries abi3 wheels for Python 3.11 and newer on Linux x86_64 and aarch64 (manylinux), macOS arm64 and Windows x64. Other platforms build from the source distribution, which needs a Rust toolchain. The Linux and Windows wheels carry the CUDA paths, which load the NVIDIA driver and NVRTC at run time; the cuda12 extra installs NVRTC from PyPI:

pip install "prism-q[cuda12]"

Without a driver or NVRTC the package runs on the CPU and only GpuContext(...) raises. Python Bindings covers the package. The getting-started pages show each step in Rust and in Python.

Feature flags

FeatureDefaultEnables
parallelyesRayon parallel kernels (≥15 qubits) and the faer SVD path for MPS
gpunoOptional CUDA backend (see the GPU guide)
distributednoStatevector partitioning across ranks (see Capabilities)
distributed-mpinodistributed plus the MPI transport
unstable-pulsenoGate compile from a pulse-level transmon model, outside the stability promise (see Noise Models)

Keep parallel on for performance

The published benchmarks were taken with parallel enabled. Without it, runs from 15 qubits up use single-threaded kernels and are not comparable to the baselines.

Building from source

git clone https://github.com/AbeCoull/prism-q
cd prism-q
cargo build --release

Running the test suite

cargo nextest run --features parallel                          # unit and integration tests
cargo test --doc --features parallel                           # doctests
cargo clippy --all-targets --features parallel -- -D warnings  # lint

These need only a Rust toolchain; use cargo test --features parallel if cargo-nextest is unavailable. The contributing guide covers the GPU, distributed and MPI arms. Its --all-features runs add distributed-mpi, which also needs a system MPI installation and libclang.

Next: build Your First Circuit.

Your First Circuit

Build a circuit with CircuitBuilder, or parse it from OpenQASM text. Each example is in Rust, then Python.

With the builder

CircuitBuilder chains gate calls and runs the result. A Bell pair, (|00⟩ + |11⟩) / √2:

#![allow(unused)]
fn main() {
use prism_q::CircuitBuilder;

let result = CircuitBuilder::new(2)
    .h(0)
    .cx(0, 1)
    .run(42)                       // seed = 42
    .expect("simulation failed");

let probs = result.probabilities.expect("no probabilities");
for i in 0..probs.len() {
    let p = probs.get(i);
    if p > 1e-10 {
        println!("|{i:02b}> = {p:.4}");
    }
}
// |00> = 0.5000
// |11> = 0.5000
}
from prism_q import CircuitBuilder, simulate

bell = CircuitBuilder(2).h(0).cx(0, 1).build()
print(simulate(bell).seed(42).run().probabilities)   # [0.5 0.  0.  0.5]
A Hadamard on q[0] followed by a controlled X from q[0] to q[1].
H creates a superposition; CX correlates the two qubits. Open full SVG.

Measurement defaults to the Z basis. measure_in_basis(qubit, axis, bit) measures along X, Y or Z, and measure_pauli_product(&terms, bit) records the parity of a Pauli string such as X0 Z1. Both lower onto gates every backend runs. A basis measurement leaves the qubit in the Z eigenstate of the recorded bit instead of rotating back, and a Pauli product accumulates its parity on one extra qubit past the declared register:

#![allow(unused)]
fn main() {
use prism_q::{CircuitBuilder, PauliAxis, PauliTerm};

let circuit = CircuitBuilder::new_with_classical(2, 2)
    .h(0)
    .cx(0, 1)
    .measure_in_basis(0, PauliAxis::X, 0)
    .measure_pauli_product(&[PauliTerm::z(0), PauliTerm::z(1)], 1)
    .build();
assert_eq!(circuit.num_qubits, 3);
}
circuit = (
    CircuitBuilder(2, 2)
    .h(0)
    .cx(0, 1)
    .measure_in_basis(0, "X", 0)
    .measure_pauli_product([(0, "Z"), (1, "Z")], 1)
    .build()
)
assert circuit.num_qubits == 3

From OpenQASM

The same Bell pair in OpenQASM 3.0:

#![allow(unused)]
fn main() {
use prism_q::circuit::openqasm;
use prism_q::simulate;

let qasm = r#"
    OPENQASM 3.0;
    include "stdgates.inc";
    qubit[2] q;
    h q[0];
    cx q[0], q[1];
"#;

let circuit = openqasm::parse(qasm).expect("failed to parse QASM");
let result = simulate(&circuit).seed(42).run().expect("simulation failed");
}
from prism_q import parse_qasm

circuit = parse_qasm("""
OPENQASM 3.0;
include "stdgates.inc";
qubit[2] q;
h q[0];
cx q[0], q[1];
""")
result = simulate(circuit).seed(42).run()

run_qasm(qasm, seed) parses and simulates in one call, in both languages. The OpenQASM Support guide lists the supported subset.

Qubit ordering

q[0] is the least significant bit, so x q[0] produces state index 1, not 2. A state index formatted with {i:b}, as above, reads most significant qubit first. Shot bitstrings from bitstring and Python count keys run the other way, with classical bit 0 leftmost.

Next: sample measurement outcomes in Shots and Sampling.

Shots and Sampling

Probabilities are the exact distribution. Shots are sampled outcomes, as hardware reports them, and a fixed seed makes them deterministic.

Sampling shots

#![allow(unused)]
fn main() {
use prism_q::circuit::openqasm;
use prism_q::simulate;

let qasm = r#"
    OPENQASM 3.0;
    include "stdgates.inc";
    qubit[2] q;
    bit[2] c;
    h q[0];
    cx q[0], q[1];
    c[0] = measure q[0];
    c[1] = measure q[1];
"#;
let circuit = openqasm::parse(qasm).expect("failed to parse QASM");

let result = simulate(&circuit).seed(42).shots(1024).expect("shots failed");
print!("{result}");   // ShotsResult implements Display
}

In Python, shots returns a (shots, bits) bool array, and counts() folds it into a histogram:

from prism_q import CircuitBuilder, simulate

circuit = CircuitBuilder(2, 2).h(0).cx(0, 1).measure_all().build()
result = simulate(circuit).seed(42).shots(1024)
print(result.shots.shape)   # (1024, 2)
print(result.counts())      # {'00': ..., '11': ...}

Pass rand::random() as the seed in Rust, or any fresh integer in Python, for nondeterministic sampling.

Counts and marginals

At large shot counts, ask for aggregates instead of raw shots:

#![allow(unused)]
fn main() {
// Frequency histogram: bitstring -> count
let counts = simulate(&circuit).seed(42).sample_counts(100_000).unwrap();

// Per-qubit (P(0), P(1)) pairs, without the full joint distribution
let marginals = simulate(&circuit).seed(42).marginals().unwrap();
}
counts = simulate(circuit).seed(42).sample_counts(100_000).counts()
marginals = simulate(circuit).seed(42).marginals().marginals

Sampling scales past the statevector

On a Clifford circuit, sample_counts and shots route through the compiled samplers, which propagate measurements through the circuit instead of rebuilding the state for every shot, so Clifford circuits sample at thousands of qubits. Other circuits with terminal measurements sample from one final state. See Compiled Samplers.

Noisy sampling

Attach a NoiseModel to sample under depolarizing or readout noise:

#![allow(unused)]
fn main() {
use prism_q::{simulate, BackendKind, NoiseModel};

let noise = NoiseModel::uniform_depolarizing(&circuit, 0.001);
let result = simulate(&circuit)
    .backend(BackendKind::Statevector)
    .noise(&noise)
    .seed(42)
    .shots(1024)
    .unwrap();
}
from prism_q import BackendKind, NoiseModel

noise = NoiseModel.uniform_depolarizing(circuit, 0.001)
result = (
    simulate(circuit)
    .backend(BackendKind.statevector())
    .noise(noise)
    .seed(42)
    .shots(1024)
)

The Noise guide covers noise models, and the QEC guide covers detector sampling.

Next: how PRISM-Q picks a representation, in Choosing a Backend.

Choosing a Backend

By default PRISM-Q inspects the circuit and picks a backend. Name one when you know something the dispatcher cannot infer, or to benchmark a specific representation.

Let it choose

#![allow(unused)]
fn main() {
use prism_q::simulate;

let result = simulate(&circuit).seed(42).run().unwrap();   // BackendKind::Auto
}

Auto reads the circuit's structure and the statevector memory cap. A circuit with no entangling gates runs as a product state and a Clifford circuit on a stabilizer tableau. Past the memory cap, a circuit that keeps few basis states goes to the sparse backend and the rest to MPS at bond 256. Below it, a circuit with partly independent registers runs factored and everything else on the dense statevector. The decision tree draws these steps with their thresholds.

Some routes sit outside the tree:

  • A Clifford circuit of 16 or more qubits that splits into independent blocks goes to FactoredStabilizer.
  • Shots on a Clifford circuit go to the CompiledStabilizer sampler, which compiles the measurement record once and draws every shot from it.
  • On a Clifford+T circuit with few T gates, shots can take the stabilizer-rank sampler, and marginals at 12 qubits and above take deterministic Pauli propagation.
  • Expectation and marginal queries go to the tensor network when its planned contraction stays inside the peak bound.

Probabilities always come from the tree. The memory cap is half of physical memory, about 29 qubits on a 16 GiB host, unless PRISM_MAX_SV_QUBITS sets it.

Choose explicitly

#![allow(unused)]
fn main() {
use prism_q::{simulate, BackendKind};

let result = simulate(&circuit)
    .backend(BackendKind::Stabilizer)
    .seed(42)
    .run()
    .unwrap();
}

From Python, pass a BackendKind constructor such as BackendKind.stabilizer() to .backend(...).

Symptom to backend

If your circuit...UseWhy
Is Clifford only (H, S, CX, CZ, ...)StabilizerO(n²), scales to thousands of qubits
Is Clifford only and splits into independent blocksFactoredStabilizerOne tableau per block
Has no entangling gatesProductStateO(n), one state per qubit
Is dense and fits the memory capStatevectorExact, fastest for the general case
Stays concentrated in few basis statesSparseO(k) in nonzero amplitudes
Has low entanglement but many qubitsMps { max_bond_dim }Polynomial memory in bond dimension
Splits into independent registersFactoredSimulates blocks separately, merges lazily
Has low treewidth and you need an expectation or marginalTensorNetworkContracts only what the query reads
Needs exact noisy probabilities or expectationsDensityMatrixEvolves the mixed state once, 4ⁿ entries
Is Clifford + a few T gatesSee Clifford+TBeats a dense statevector

ProductState rejects entanglement

ProductState errors on any entangling gate. Auto selects it only for circuits that have none; choose it explicitly only for a circuit that stays a product state throughout.

Scaling

BackendMemoryCeiling
StatevectorThe memory cap: half of physical memory, about 29 qubits on 16 GiB
StabilizerThousands of qubits
Factored Stabilizer per clusterThousands of qubits
Sparse nonzeroLarge , small
MPSLarge , bounded
ProductUnbounded
Tensor NetworkSet by contraction orderPeak intermediate under PRISM_MAX_TN_PEAK_QUBITS; dense readout under PRISM_MAX_PROB_QUBITS
Factored worst caseLargest merged block
Density MatrixHalf the statevector cap, about 14 qubits on 16 GiB

Every cap derives from one detected memory budget. The distributed feature adds an exact statevector sharded across MPI ranks (Distributed Statevector and MPI). The Capability and Support Matrix has CPU and GPU support per backend, and the architecture reference has the internals.

Next: work through a task end to end in the Tutorials.

Tutorials

Each tutorial goes from an empty file to a number you can check in a few minutes. Code is Python first, with Rust where the two differ in more than syntax. CI runs every Python and Rust block on these pages.

TutorialYou end with
Simulate and SampleGHZ probabilities, shot counts, and a backend picked by hand
Variational Circuits and GradientsAn optimized Ising energy from adjoint gradients, and a batched parameter sweep
Noisy SimulationGHZ fidelity under gate noise, readout error and a device calibration, then leakage and drift
A QEC Memory ExperimentDecoded logical error rates for a repetition code at three distances
Dynamic CircuitsTeleportation with mid-circuit measurement and feed-forward, and a subroutine that decodes a measured bit
Large and Structured Circuits1000-qubit Clifford sampling, a Clifford+T expectation, and an MPS run with its error bound

Install the package first:

pip install prism-q

Each tutorial has a script in bindings/python/examples/, and the Rust programs in examples/ cover the same ground:

python bindings/python/examples/qec_memory.py
cargo run --release --example qec_memory

Simulate and Sample

Goal: build a three-qubit GHZ circuit, read its exact distribution, sample it as hardware would, and run it on a backend you pick.

Build and run

from prism_q import CircuitBuilder, simulate

ghz = CircuitBuilder(3).h(0).cx(0, 1).cx(1, 2).build()
outcome = simulate(ghz).seed(42).run()
print(outcome.probabilities)       # [0.5 0.  0.  0.  0.  0.  0.  0.5]
print(outcome.metadata.backend)    # Stabilizer

probabilities is a NumPy array over the 2**3 basis states, with qubit 0 as the least significant bit of the index. Half the weight sits on |000> and half on |111>.

metadata.backend names the engine that ran: the default BackendKind.auto() saw only Clifford gates and picked a stabilizer tableau.

Sample shots

Hardware returns measurement records, not amplitudes. Add classical bits, measure, and sample:

measured = CircuitBuilder(3, 3).h(0).cx(0, 1).cx(1, 2).measure_all().build()
counts = simulate(measured).seed(42).sample_counts(1000).counts()
print(sorted(counts.items()))      # [('000', 485), ('111', 515)]

shots = simulate(measured).seed(42).shots(5).shots
print(shots.shape, shots.dtype)    # (5, 3) bool

The same seed gives the same counts on every run. Character i of a count key is classical bit i, so keys read with bit 0 on the left:

flipped = CircuitBuilder(3, 3).x(0).measure_all().build()
print(simulate(flipped).seed(42).sample_counts(10).counts())   # {'100': 10}

Choose a backend

A BackendKind overrides the automatic choice. The answer is the same; the representation, and so the cost, changes:

from prism_q import BackendKind

for kind in [BackendKind.statevector(), BackendKind.mps(16), BackendKind.sparse()]:
    result = simulate(ghz).backend(kind).seed(42).run()
    print(result.metadata.backend, result.probabilities[[0, 7]])
# Statevector [0.5 0.5]
# Mps [0.5 0.5]
# Sparse [0.5 0.5]

A backend that cannot hold the circuit raises. The product-state backend keeps one state per qubit and declines anything entangling:

from prism_q import PrismError

try:
    simulate(ghz).backend(BackendKind.product_state()).seed(42).run()
except PrismError as exc:
    print(exc.kind)                # incompatible_backend

Choosing a Backend explains how automatic dispatch picks, with a table from circuit shape to backend.

In Rust

#![allow(unused)]
fn main() {
use prism_q::{BackendKind, CircuitBuilder, bitstring, simulate};

let ghz = CircuitBuilder::new(3).h(0).cx(0, 1).cx(1, 2).build();
let outcome = simulate(&ghz).seed(42).run()?;
let probs = outcome.probabilities.expect("no probabilities");
assert!((probs.get(0b000) - 0.5).abs() < 1e-12);

let measured = CircuitBuilder::new_with_classical(3, 3)
    .h(0)
    .cx(0, 1)
    .cx(1, 2)
    .measure_all()
    .build();
let counts = simulate(&measured).seed(42).sample_counts(1000)?;
for (key, n) in &counts.counts {
    println!("{}: {n}", bitstring(key, counts.num_classical_bits));
}

let sv = simulate(&ghz).backend(BackendKind::Statevector).seed(42).run()?;
println!("{:?}", sv.metadata.backend);
Ok::<(), prism_q::PrismError>(())
}

Next: Variational Circuits and Gradients.

Variational Circuits and Gradients

Goal: minimize the energy of a four-site transverse-field Ising chain with a two-layer ansatz, using exact gradients, then evaluate a batch of parameter points in one call.

Mark the parameters

param(slot) marks the gate just appended as trainable in that slot; several gates may share a slot.

import numpy as np
from prism_q import CircuitBuilder

n = 4
builder = CircuitBuilder(n)
for q in range(n):
    builder.ry(0.1, q).param(q)
for q in range(n - 1):
    builder.cx(q, q + 1)
for q in range(n):
    builder.ry(0.1, q).param(n + q)

circuit = builder.build()
params = builder.parameters()                # Parameters: 8 slots
print(params.num_slots, params.links()[:2])  # 8 [(0, 0), (1, 1)]

params binds new angles into the circuit and tells the gradient which instruction feeds which slot.

The observable

A Hamiltonian is a list of (coefficient, [(qubit, axis), ...]) terms, here H = -sum Z_i Z_{i+1} - 0.5 sum X_i. PauliObservable parses it once and caches the grouping of commuting terms for reuse inside a loop.

from prism_q import PauliObservable

hamiltonian = PauliObservable(
    [(-1.0, [(q, "Z"), (q + 1, "Z")]) for q in range(n - 1)]
    + [(-0.5, [(q, "X")]) for q in range(n)]
)
print(hamiltonian.num_terms, hamiltonian.num_groups)   # 7 2

Adjoint and parameter-shift gradients

expectation_gradient uses the adjoint method: one forward and one backward pass at any parameter count. expectation_gradient_shift uses the parameter-shift rule, two extra circuit runs per parameter, and works on backends with no adjoint pass. Both return an ExpectationGradient, which unpacks as (value, gradient), one gradient entry per slot.

from prism_q import simulate

value, adjoint = simulate(circuit).seed(42).expectation_gradient(hamiltonian, params)
_, shifted = simulate(circuit).seed(42).expectation_gradient_shift(hamiltonian, params)
print(round(value, 6))                            # -3.206449
print(np.allclose(adjoint, shifted, atol=1e-10))  # True

Optimize

Plain gradient descent. PreparedCircuit settles fusion and backend selection once, so each step only binds the new angles and replays them.

from prism_q import BackendKind, PreparedCircuit

prepared = PreparedCircuit(circuit, params, BackendKind.statevector())
theta = np.full(params.num_slots, 0.1)
for step in range(100):
    energy, gradient = prepared.expectation_gradient(theta, hamiltonian, seed=42)
    theta -= 0.2 * gradient
print(round(energy, 6))                         # -3.377401

The exact ground energy is -3.4270. Two layers of ry rotations get within 1.5% of it; a third layer closes more of the gap.

Sweep many points at once

The *_many calls take a (points, num_slots) array and cross into Rust once; up to 16 qubits, rows split across cores (14 for gradients).

rng = np.random.default_rng(42)
points = rng.uniform(-np.pi, np.pi, size=(256, params.num_slots))
results = prepared.expectation_many(points, hamiltonian, seed=42)
energies = np.array([r.mean for r in results])
print(energies.shape, round(energies.min(), 4))  # (256,) -2.5401

expectation_gradient_many returns a (points,) array of values and a (points, num_slots) array of gradients:

values, gradients = prepared.expectation_gradient_many(points[:8], hamiltonian, seed=42)
print(values.shape, gradients.shape)  # (8,) (8, 8)

run_many does the same for full runs, and expectation_many with a list of Pauli strings returns a (points, observables) array. Pass the backend explicitly when the template angles are not typical: with every rotation at zero the template reads as Clifford, and automatic dispatch would pick a stabilizer backend that then rejects the bound circuit.

In Rust

build_parametric returns the circuit and its Parameters together, and the gradient terminals take a PauliObservable and the Parameters directly.

#![allow(unused)]
fn main() {
use prism_q::{CircuitBuilder, PauliObservable, PauliTerm, PreparedCircuit};

let n = 4;
let mut builder = CircuitBuilder::new(n);
for q in 0..n {
    builder.ry(0.1, q).param(q);
}
for q in 0..n - 1 {
    builder.cx(q, q + 1);
}
for q in 0..n {
    builder.ry(0.1, q).param(n + q);
}
let (circuit, params) = builder.build_parametric();

let hamiltonian = PauliObservable::from_terms(
    (0..n - 1)
        .map(|q| (-1.0, vec![PauliTerm::z(q), PauliTerm::z(q + 1)]))
        .chain((0..n).map(|q| (-0.5, vec![PauliTerm::x(q)]))),
)?;

let mut theta = vec![0.1; params.num_slots()];
let mut prepared = PreparedCircuit::new(circuit, params)?;
for _ in 0..100 {
    let step = prepared.expectation_gradient(&theta, &hamiltonian, 42)?;
    for (t, g) in theta.iter_mut().zip(&step.gradient) {
        *t -= 0.2 * g;
    }
}

// One row per binding; each row has one gradient entry per slot.
let batch = [theta.clone(), vec![0.0; theta.len()]];
let rows = prepared.expectation_gradient_many(&batch, &hamiltonian, 42)?;
assert_eq!(rows[0].gradient.len(), theta.len());
Ok::<(), prism_q::PrismError>(())
}

examples/gradients.rs adds the parameter-shift check and the batched sweep.

Next: Noisy Simulation.

Noisy Simulation

Goal: degrade a GHZ state with gate noise and readout error, from hand-written rules and then from a device calibration table, and compare sampled and exact answers. The figure of merit is the GHZ fraction, the share of shots reading 000 or 111.

from prism_q import CircuitBuilder, simulate

circuit = CircuitBuilder(3, 3).h(0).cx(0, 1).cx(1, 2).measure_all().build()


def ghz_fraction(counts):
    return (counts.get("000", 0) + counts.get("111", 0)) / sum(counts.values())


ideal = simulate(circuit).seed(42).sample_counts(10_000).counts()
print(ghz_fraction(ideal))                    # 1.0

Noise from rules

NoiseBuilder attaches channels by rule, each pairing a GateFilter that picks gates with a NoiseChannel. build(circuit) lowers the rules onto the circuit and validates the result.

from prism_q import GateFilter, NoiseBuilder, NoiseChannel

noise = (
    NoiseBuilder()
    .after_gates(GateFilter.all().arity(1), NoiseChannel.depolarizing(0.001))
    .after_gates_joint(GateFilter.all().named("cx"), NoiseChannel.two_qubit_depolarizing(0.02))
    .uniform_readout_error(0.01, 0.02)
    .build(circuit)
)
noisy = simulate(circuit).seed(42).noise(noise).sample_counts(10_000).counts()
print(round(ghz_fraction(noisy), 4))          # 0.9273

after_gates adds a one-qubit channel on each target of a matching gate. after_gates_joint adds one channel across all of a gate's targets, here two-qubit depolarizing after every cx. uniform_readout_error(p01, p10) flips each bit as a measurement writes it; p01 is the chance a measured 0 reads as 1. The Python guide lists the other rules: crosstalk, over-rotation, idle noise, and noise after resets or before measurement.

A model is tied to the circuit it was built from; build a new one for another circuit.

Noise from a device calibration

DeviceCalibration reads what a calibration page reports: t1, t2 and readout rates per qubit, a duration and error per gate family, and optional per-pair overrides. to_noise_model turns it into thermal relaxation over each gate's duration, depolarizing error per gate, and readout error per measured qubit.

from prism_q import DeviceCalibration

calibration = DeviceCalibration.parse(
    """
    qubit 0 t1=120e-6 t2=80e-6 p01=0.02 p10=0.03
    qubit 1 t1=95e-6 t2=110e-6 p01=0.01 p10=0.02
    qubit 2 t1=60e-6 t2=50e-6 p01=0.02 p10=0.04
    gate1q time=35e-9 error=3e-4
    gate2q time=300e-9 error=8e-3
    gate2q 1 2 time=450e-9 error=2e-2
    """
)
device = calibration.to_noise_model(circuit)
sampled = simulate(circuit).seed(42).noise(device).sample_counts(10_000).counts()
print(round(ghz_fraction(sampled), 4))        # 0.9028

Times are in seconds. The last line overrides the two-qubit family on pair (1, 2), in either order. DeviceCalibration.superconducting_transmon(n), trapped_ion(n) and neutral_atom(n) are presets with illustrative magnitudes for a technology class, not a measured device.

Exact answers from the density matrix

The density-matrix backend evolves the mixed state itself, so run() returns exact probabilities under the model with no shot noise. It stores 4**n entries and never runs by default; select it by name. Measurements and readout error are left off here to read the state before measurement:

from prism_q import BackendKind

unmeasured = CircuitBuilder(3).h(0).cx(0, 1).cx(1, 2).build()
exact = (
    simulate(unmeasured)
    .backend(BackendKind.density_matrix())
    .noise(calibration.to_noise_model(unmeasured))
    .seed(42)
    .run()
    .probabilities
)
print(round(exact[0] + exact[7], 4))          # 0.9712

The gap to the sampled 0.90 is mostly readout error, which acts only on reported bits.

Leakage and drift

Leakage and drift both carry state from one gate to the next within a shot, so they run as one trajectory per shot. A leakage channel moves a qubit out of the computational space: a leaked qubit ignores gates and reads 1, and leaked marks which qubits leaked in each shot:

leaky = (
    NoiseBuilder()
    .after_gates_joint(GateFilter.all().named("cx"), NoiseChannel.leakage_transport(0.05))
    .after_gates(GateFilter.all(), NoiseChannel.leakage(0.01))
    .build(circuit)
)
result = simulate(circuit).backend(BackendKind.statevector()).seed(42).noise(leaky).shots(1000)
print(result.leaked.shape)                    # (1000, 3)

Drift is a parameter that holds still within a shot and wanders between shots. Here schedule gives the gates durations in seconds, scheduled_idle relaxes each qubit over its idle time from its (t1, t2), and quasi_static_detuning draws a frequency offset per qubit for every shot from widths set by t2*:

from prism_q import DriftDistribution, GateTimes

timed = (
    NoiseBuilder()
    .schedule(GateTimes(35e-9, 300e-9).with_measure(1e-6))
    .scheduled_idle([(120e-6, 80e-6), (95e-6, 110e-6), (60e-6, 50e-6)])
    .quasi_static_detuning(DriftDistribution.from_t2_star([40e-6, 55e-6, 30e-6]))
    .build(circuit)
)
drifting = (
    simulate(circuit)
    .backend(BackendKind.statevector())
    .seed(42)
    .noise(timed)
    .sample_counts(10_000)
    .counts()
)

The density-matrix backend declines both, since a mixture evolved one channel at a time cannot carry that state. The Python noise guide lists the other leakage channels, correlated drift between neighbouring qubits, and over-rotation drift.

In Rust

#![allow(unused)]
fn main() {
use prism_q::{CircuitBuilder, GateFilter, NoiseBuilder, NoiseChannel, simulate};

let circuit = CircuitBuilder::new_with_classical(3, 3)
    .h(0)
    .cx(0, 1)
    .cx(1, 2)
    .measure_all()
    .build();
let noise = NoiseBuilder::new()
    .after_gates(GateFilter::all().arity(1), NoiseChannel::Depolarizing { p: 0.001 })
    .after_gates_joint(
        GateFilter::all().named("cx"),
        NoiseChannel::TwoQubitDepolarizing { p: 0.02 },
    )
    .uniform_readout_error(0.01, 0.02)
    .build(&circuit)?;
let counts = simulate(&circuit).noise(&noise).seed(42).sample_counts(10_000)?;
let good = counts.counts.get(&vec![0b000]).unwrap_or(&0)
    + counts.counts.get(&vec![0b111]).unwrap_or(&0);
assert!(good > 9_000);
Ok::<(), prism_q::PrismError>(())
}

Rust count keys are packed words with classical bit 0 in the lowest bit, so 000 and 111 are vec![0b000] and vec![0b111]. examples/noise.rs adds the calibration and density-matrix steps.

Next: A QEC Memory Experiment.

A QEC Memory Experiment

Goal: protect one bit in a distance-d repetition code for d rounds of noisy syndrome extraction, decode the detector record, and report the logical error rate at three distances.

The code stores a logical 0 in d data qubits, with an ancilla between each pair measuring their parity Z_i Z_{i+1}. Before every round each data qubit flips with probability p. A logical error is a majority of data qubits flipped at the end, which the decoder must infer from parity changes alone.

Build the program

In a QecProgram, every measure_z returns the index of the record it writes, and detectors and observables are parities over records. Data qubits take the even indices, ancillas the odd ones.

from prism_q import Gate, QecBasis, QecNoise, QecProgram, QecRecordRef


def repetition_memory(distance, rounds, p, shots):
    data = [2 * i for i in range(distance)]
    ancillas = [2 * i + 1 for i in range(distance - 1)]
    qp = QecProgram(2 * distance - 1)
    qp.set_options(shots, seed=42)
    for q in data + ancillas:
        qp.reset(QecBasis.Z, q)

    previous = None
    for _ in range(rounds):
        qp.noise(QecNoise.x_error(p), data)
        for a in ancillas:
            qp.push_gate(Gate.cx(), [a - 1, a])
            qp.push_gate(Gate.cx(), [a + 1, a])
        current = []
        for a in ancillas:
            current.append(qp.measure_z(a))
            qp.reset(QecBasis.Z, a)
        for i, record in enumerate(current):
            refs = [QecRecordRef.absolute(record)]
            if previous is not None:
                refs.append(QecRecordRef.absolute(previous[i]))
            qp.detector(refs)
        previous = current

    final = [qp.measure_z(q) for q in data]
    for i, record in enumerate(previous):
        qp.detector([QecRecordRef.absolute(r) for r in (final[i], final[i + 1], record)])
    qp.observable_include(0, [QecRecordRef.absolute(final[0])])
    return qp

There are three kinds of detector. In the first round an ancilla outcome is compared with the noiseless value 0, so the detector is that one record. In later rounds it is the change since the previous round. After the last round the data qubits are measured and each final detector checks their parity against the last ancilla outcome. Every detector reads 0 when nothing went wrong.

The observable is data qubit 0. Each ancilla is reset after measurement, since a noisy program may not reuse a measured qubit before a reset (a noiseless one may).

Sample and decode

detector_error_model() derives from the noise annotations which detectors and observables each error flips, and with what probability. The built-in union-find decoder needs the graphlike form, where each mechanism flips at most two detectors.

from prism_q import UnionFindDecoder

qp = repetition_memory(distance=5, rounds=5, p=0.05, shots=20_000)
model = qp.detector_error_model().decompose_graphlike()
print(qp.num_detectors, model.num_mechanisms)   # 24 25

result = qp.run()
predicted = UnionFindDecoder(model).decode(result.detectors)
failures = (predicted[:, 0] != result.observables[:, 0]).sum()
print(result.detectors.shape)                    # (20000, 24)
print(failures / result.total_shots)             # 0.00545

result.detectors and result.observables are bool arrays with one row per shot. decode returns predicted observable flips in the shape of observables; a shot fails when the prediction disagrees with what happened.

Compare distances

for distance in (3, 5, 7):
    qp = repetition_memory(distance, rounds=distance, p=0.05, shots=20_000)
    model = qp.detector_error_model().decompose_graphlike()
    result = qp.run()
    predicted = UnionFindDecoder(model).decode(result.detectors)
    decoded = (predicted[:, 0] != result.observables[:, 0]).mean()
    raw = result.logical_error_rates()[0]
    print(f"d={distance}: raw {raw:.4f}, decoded {decoded:.4f}")
# d=3: raw 0.1362, decoded 0.0235
# d=5: raw 0.2084, decoded 0.0054
# d=7: raw 0.2647, decoded 0.0008

logical_error_rates() counts shots whose observable flipped with no correction, so the raw rate grows with distance: more rounds, more chances for qubit 0 to flip. The decoded rate falls four to sevenfold per step in distance, as expected below threshold.

model.to_text() writes the model in the common detector error model text format, for an external matching or belief-propagation decoder. The QEC guide covers the text program format, postselection, and the other QEC noise channels.

In Rust

The Rust builder has the same shape, with Result returns. Decoding works on the packed shot records directly:

#![allow(unused)]
fn main() {
use prism_q::{UnionFindDecoder, parse_qec_program, run_qec_program};

let program = parse_qec_program(
    "R 0 1 2 3 4
     X_ERROR(0.05) 0 2 4
     CX 0 1 2 1 2 3 4 3
     MR 1 3
     DETECTOR rec[-2]
     DETECTOR rec[-1]
     M 0 2 4
     DETECTOR rec[-3] rec[-2] rec[-5]
     DETECTOR rec[-2] rec[-1] rec[-4]
     OBSERVABLE_INCLUDE(0) rec[-3]",
)?;
let model = program.detector_error_model()?.decompose_graphlike()?;
let decoder = UnionFindDecoder::from_model(&model)?;
let result = run_qec_program(&program)?;
let predicted = decoder.decode_packed(&result.detectors)?;
let failures = (0..result.total_shots)
    .filter(|&shot| predicted.get_bit(shot, 0) != result.observables.get_bit(shot, 0))
    .count();
assert!(failures < result.total_shots / 10);
Ok::<(), prism_q::PrismError>(())
}

That is one round at distance 3 in the text format. examples/qec_memory.rs builds the multi-round program with QecProgram methods and prints the same table.

Next: Dynamic Circuits.

Dynamic Circuits

Goal: teleport a qubit using mid-circuit measurement and feed-forward, reuse a measured qubit with reset, branch on an outcome with if/else, and decode an outcome in a subroutine, all written in OpenQASM 3.

Teleportation

Qubit 0 holds ry(1.2)|0> and qubits 1 and 2 share a Bell pair. Measuring qubits 0 and 1 and applying x and z to qubit 2 on those outcomes moves the state onto qubit 2, which then measures 1 with probability sin(0.6)**2.

import math
from prism_q import parse_qasm, simulate

theta = 1.2
teleport = parse_qasm(f"""
OPENQASM 3.0;
include "stdgates.inc";
qubit[3] q;
bit[3] c;
ry({theta}) q[0];
h q[1];
cx q[1], q[2];
cx q[0], q[1];
h q[0];
c[0] = measure q[0];
c[1] = measure q[1];
if (c[1]) x q[2];
if (c[0]) z q[2];
c[2] = measure q[2];
""")

shots = simulate(teleport).seed(42).shots(100_000).shots
print(round(shots[:, 2].mean(), 4))           # 0.3208
print(round(math.sin(theta / 2) ** 2, 4))     # 0.3188

The sampled rate is 0.002 from the exact one; one standard error at 100,000 shots is 0.0015. shots is a (shots, bits) bool array, so column 2 is classical bit c[2].

A circuit with feed-forward has no single final state, so use shots() and sample_counts(). run() follows one sampled branch: classical_bits holds that shot's outcomes and probabilities the state it ended in. state_vector() declines any circuit that measures, resets or branches.

Reset and if/else

reset returns a measured qubit to |0> for reuse. An if body can hold any supported statement, and else takes the other branch:

branch = parse_qasm("""
OPENQASM 3.0;
include "stdgates.inc";
qubit[2] q;
bit[3] c;
h q[0];
c[0] = measure q[0];
reset q[0];
if (c[0]) {
  x q[1];
} else {
  h q[1];
}
c[1] = measure q[1];
c[2] = measure q[0];
""")

counts = simulate(branch).seed(42).sample_counts(1000).counts()
print(sorted(counts.items()))   # [('000', 270), ('010', 245), ('110', 485)]

Read the keys with c[0] on the left. Half the shots measured 1 first and took the x branch, so they read 110. The other half took h, which leaves c[1] a fair coin: 000 or 010. c[2] is always 0 because of the reset.

Conditions can also test a parity, if (c[0] ^ c[1]), and switch with case arms lowers to the same guards. parse_qasm declines while, since a loop that exits on a measurement has no fixed instruction list. parse_qasm_dynamic reads it, with break and continue, and simulate_program runs the result once per shot. A shot that passes a million blocks stops with a step-limit error unless max_steps raises the bound. The OpenQASM guide lists what the dynamic parser reads.

Subroutines and classical values

Under parse_qasm_dynamic, a def can compute a value from a measured bit, typed variables hold it, and assignments write classical bits. Here decode turns the first outcome into an int, an if on that value undoes the flip, and the last line writes a check bit:

from prism_q import parse_qasm_dynamic, simulate_program

program = parse_qasm_dynamic("""
OPENQASM 3.0;
include "stdgates.inc";
qubit q;
bit[3] c;
def decode(bit b) -> int {
  if (b) return 1;
  return 0;
}
h q;
c[0] = measure q;
int correction = decode(c[0]);
if (correction == 1) x q;
c[1] = measure q;
c[2] = correction == int(c[0]);
""")

counts = simulate_program(program).seed(42).sample_counts(1000).counts()
print(sorted(counts))   # ['001', '101']

c[0] is a fair coin. The correction always returns the qubit to |0>, so c[1] reads 0 and c[2] is always 1. Subroutines lists the result types and the forms that decline.

In Rust

The same OpenQASM source parses with openqasm::parse. CircuitBuilder also has reset, conditional, and guarded for building these circuits directly:

#![allow(unused)]
fn main() {
use prism_q::circuit::openqasm;
use prism_q::{bitstring, simulate};

let branch = openqasm::parse(
    r#"
    OPENQASM 3.0;
    include "stdgates.inc";
    qubit[2] q;
    bit[3] c;
    h q[0];
    c[0] = measure q[0];
    reset q[0];
    if (c[0]) { x q[1]; } else { h q[1]; }
    c[1] = measure q[1];
    c[2] = measure q[0];
    "#,
)?;
let counts = simulate(&branch).seed(42).sample_counts(1000)?;
let mut keys: Vec<String> = counts
    .counts
    .keys()
    .map(|key| bitstring(key, counts.num_classical_bits))
    .collect();
keys.sort();
assert_eq!(keys, ["000", "010", "110"]);
Ok::<(), prism_q::PrismError>(())
}

examples/dynamic_circuits.rs runs both circuits. The subroutine program goes through openqasm::parse_dynamic and simulate_program in the same way.

Next: Large and Structured Circuits.

Large and Structured Circuits

Goal: run three circuits too wide for a dense statevector, each on the engine its structure allows, and read from the result metadata whether the answer is exact.

A dense statevector holds 2**n complex amplitudes at 16 bytes each, so 30 qubits take 16 GiB. Past that, circuit structure decides what can run.

Clifford circuits: thousands of qubits

A circuit of only Clifford gates (H, S, CX, CZ and the Paulis) runs on a stabilizer tableau in polynomial time, and automatic dispatch picks it.

from prism_q import CircuitBuilder, simulate

n = 1000
builder = CircuitBuilder(n, n).h(0)
for q in range(n - 1):
    builder.cx(q, q + 1)
ghz = builder.measure_all().build()

counts = simulate(ghz).seed(42).sample_counts(1000)
print(counts.metadata.backend)          # CompiledStabilizer
print(len(counts.counts()))             # 2

The two outcomes are all zeros and all ones. CompiledStabilizer is the sampler that compiles the measurement record once and draws every shot from it.

Clifford plus a few T gates

One T gate takes a circuit out of the stabilizer formalism, but a few can still be handled exactly. This chain applies h t h to every sixth qubit, ten T gates in all, then entangles the register with a CX ladder:

def kicked_chain(n, measure):
    builder = CircuitBuilder(n, n if measure else 0)
    for q in range(0, n, 6):
        builder.h(q).t(q).h(q)
    for q in range(n - 1):
        builder.cx(q, q + 1)
    if measure:
        builder.measure_all()
    return builder.build()


chain = kicked_chain(60, measure=False)
print(chain.t_count(), chain.is_clifford_only())   # 10 False

Each h t h leaves its qubit with <Z> = cos(pi/4), and the ladder makes Z on the last qubit the parity of all of them, so <Z59> = cos(pi/4)**10 = 1/32. Deterministic Pauli propagation computes that exactly by pushing the observable backwards through the circuit:

from prism_q import BackendKind

values = (
    simulate(chain)
    .backend(BackendKind.deterministic_pauli())
    .seed(42)
    .expectation([[(59, "Z")]])
)
print(round(values.values[0], 6), values.metadata.is_exact)   # 0.03125 True

Shots on the measured version go to the stabilizer-rank engine unprompted. It tracks a sum of stabilizer states that grows with the T count, not the width:

shots = simulate(kicked_chain(60, measure=True)).seed(42).shots(2000)
print(shots.metadata.backend, shots.metadata.is_exact)   # StabilizerRank True
print(round(shots.shots[:, 59].mean(), 4))              # 0.4855, expected 31/64 = 0.4844

The Clifford+T guide covers the four Clifford+T engines and their limits.

Low entanglement: matrix product states

A two-layer hardware-efficient ansatz on 60 qubits is neither Clifford nor small, but its entanglement stays low. Asked for Z on every qubit, automatic dispatch sends it to a matrix product state with a bond cap of 256. Asked for one local observable, it contracts that observable's light cone on the tensor network instead, which is exact and cheaper.

from prism_q import circuits

wide = circuits.hardware_efficient_ansatz(60, 2)
result = simulate(wide).seed(42).expectation([[(q, "Z")] for q in range(60)])
meta = result.metadata
print(meta.backend, meta.is_exact, meta.fidelity_lower_bound)   # Mps True None
print(meta.bond.peak, meta.bond.cap, meta.bond.saturated)       # 4 256 False

The MPS engine can truncate, but this run did not: the widest bond needed was 4, under the cap of 256, so no cut dropped weight and the result reports itself exact. With the cap forced down to 2, the bond saturates:

tight = simulate(wide).backend(BackendKind.mps(2)).seed(42).expectation(
    [[(0, "Z")]]
)
print(round(result.values[0], 4), round(tight.values[0], 4))   # 0.3301 0.4464
print(tight.metadata.bond.saturated)                           # True

A saturated bond means truncation may have moved the answer. Here it moved it by 0.12, and the fidelity bound drops to 0.0, the worst case it can certify.

Refusing approximate answers

require_exact() turns a route that could truncate into an error naming it:

from prism_q import PrismError

try:
    simulate(wide).seed(42).require_exact().expectation([[(q, "Z")] for q in range(60)])
except PrismError as exc:
    print(exc.kind)                 # incompatible_backend

The check uses the circuit and the requested backend, before anything runs, so it rejects the ansatz above even though its MPS run cut nothing. The 1000-qubit Clifford sample passes under automatic dispatch. The Clifford+T shots pass only with .backend(BackendKind.stabilizer_rank()), because automatic dispatch cannot promise the exact route in advance. Deterministic Pauli propagation is always rejected, since it truncates once the term count passes its budget.

In Rust

#![allow(unused)]
fn main() {
use prism_q::{BackendKind, CircuitBuilder, Exactness, simulate};

let n = 1000;
let mut builder = CircuitBuilder::new_with_classical(n, n);
builder.h(0);
for q in 0..n - 1 {
    builder.cx(q, q + 1);
}
let ghz = builder.measure_all().build();
let counts = simulate(&ghz).seed(42).require_exact().sample_counts(1000)?;
assert_eq!(counts.counts.len(), 2);
assert_eq!(counts.metadata.exactness, Exactness::Exact);

let wide = prism_q::circuits::hardware_efficient_ansatz(60, 2, 42);
let observables = vec![vec![prism_q::PauliTerm::z(0)]];
let result = simulate(&wide)
    .backend(BackendKind::Mps { max_bond_dim: 256 })
    .seed(42)
    .expectation_values_reported(&observables)?;
let bond = result.metadata.bond.expect("an MPS run reports its bond");
assert!(!bond.saturated());
Ok::<(), prism_q::PrismError>(())
}

Next: draw any of these circuits with the Drawing Circuits guide, or read how dispatch decides in Simulation Engine and Dispatch.

Python Bindings

The PyO3 extension prism_q._prism_q is re-exported by the pure Python prism_q package. Simulation runs in Rust with the GIL released, so the wrapper adds no cost per gate.

Wheels are abi3 for Python 3.11 and newer, one per platform: Linux x86_64 and aarch64 (manylinux), macOS arm64 and Windows x64. Other platforms build from the source distribution, which needs a Rust toolchain.

Install

pip install prism-q

NumPy is the only runtime dependency. The Linux and Windows wheels also carry the CUDA paths (see GPU backends), which need an NVIDIA driver and NVRTC, the CUDA runtime compiler. The cuda12 extra installs NVRTC from PyPI:

pip install "prism-q[cuda12]"

Neither is loaded at import: without them the package runs on the CPU and only GpuContext(...) raises. The macOS wheel has no CUDA paths.

Building from a source checkout needs maturin:

pip install maturin
maturin develop --manifest-path bindings/python/Cargo.toml

parallel is on by default; gpu and distributed-mpi are optional. --features gpu adds the CUDA paths to a source build and compiles without a CUDA toolkit. No wheel carries the sharded statevector (Distributed backend), so distributed-mpi always means a source build.

Quick start

from prism_q import CircuitBuilder, simulate

circuit = CircuitBuilder(2, 2).h(0).cx(0, 1).measure_all().build()
counts = simulate(circuit).seed(42).shots(1000).counts()
print(counts)          # {'00': 507, '11': 493}

q[0] is the least significant qubit

x q[0] produces state index 1, not 2. In a counts key, character i is classical bit i with bit 0 leftmost. A Bell pair gives '00' and '11', which look the same either way, but CircuitBuilder(2, 2).x(0).measure_all() gives '10', not '01'.

The rest of the guide

PageCovers
Circuits and ParametersCircuitBuilder, classical control, OpenQASM export and drawing, parameter sweeps, dynamic programs
Running Simulationsthe terminal methods, result metadata, route inspection, memory caps, backend selection, GPU and MPI backends, batches
Observables and Gradientsexpectation values, exact noisy expectations, adjoint gradients
Noise and Shotsnoise models and rules, leakage, timed and drifting noise, compiled samplers
Quantum Error CorrectionQecProgram, memory experiments, detector error models, decoders, feedforward, packed records
Advanced State Handlingstart states and mixtures, entropy and overlap, Clifford tableau hand-off, mid-circuit saves
Errors, Typing and NamesPrismError, type stubs, how Python names map to the Rust API

The tutorials walk through whole tasks, and Python API lists every Rust function with a Python counterpart.

Pickling and multiprocessing

Circuit, Gate, Parameters, NoiseChannel, NoiseModel, QecProgram, PauliObservable, ClassicalCondition, QecRecordRef, QecNoise, SaveSpec, and QecBasis pickle, so they cross multiprocessing, concurrent.futures, Ray, and Dask boundaries. The payload is a versioned binary encoding with every float as its IEEE bits, so an unpickled value is identical to the original, and a Parameters set keeps the edit guard it was pinned with.

import pickle

from prism_q import CircuitBuilder, simulate

circuit = CircuitBuilder(2, 2).h(0).cx(0, 1).measure_all().build()
restored = pickle.loads(pickle.dumps(circuit))
assert pickle.dumps(restored) == pickle.dumps(circuit)
assert simulate(restored).seed(1).shots(100).counts() == simulate(circuit).seed(1).shots(
    100
).counts()

A payload from a newer format version raises PrismError naming the version. Of the results, only ExpectationResult and ExpectationGradient pickle. Builders, other results, samplers, backends, and contexts do not; return arrays or counts from a worker instead.

Threads

Parallel kernels run on one pool for the whole process, sized to every logical core. Set RAYON_NUM_THREADS before the first simulation to cap it; the pool is built once and ignores later changes. To run some calls at another width, call through a ThreadPool:

from prism_q import ThreadPool, simulate

pool = ThreadPool(2)
outcome = pool.install(lambda: simulate(circuit).seed(42).run())

install(fn, *args, **kwargs) calls fn on one of the pool's workers, blocks, and passes its result or exception through. Every parallel kernel reached from fn runs on those workers. fn runs on another OS thread and does not see the caller's thread-local state. Pool width changes results only where thread count does, per the threading contract.

Circuits and Parameters

Building circuits

Every CircuitBuilder gate method returns the builder; build() returns the Circuit.

from prism_q import CircuitBuilder

circuit = (
    CircuitBuilder(3, 3)
    .h(0)
    .cx(0, 1)
    .rz(0.5, 2)
    .cphase(0.25, 1, 2)
    .measure_all()
    .build()
)
GroupMethods
Single qubitid, x, y, z, h, s, sdg, t, tdg, sx, sxdg
Rotationsrx(theta, q), ry(theta, q), rz(theta, q), p(theta, q), u(theta, phi, lam, q)
Two qubitcx(control, target), cy(control, target), cz(q0, q1), ch(control, target), swap(q0, q1), iswap(q0, q1), cphase(theta, control, target)
Controlled rotationscrx(theta, control, target), cry(theta, control, target), crz(theta, control, target)
Two-qubit rotationsrxx(theta, q0, q1), ryy(theta, q0, q1), rzz(theta, q0, q1)
Three qubitccx(control0, control1, target), cswap(control, q0, q1)
Multi-qubit rotationpauli_rotation(theta, factors)
Hamiltonian evolutiontrotter(hamiltonian, t, steps=1, order=2)
Arbitrary unitarycu(matrix, control, target), mcu(matrix, controls, target), gate(gate, targets)
Non-unitarymeasure(qubit, bit), measure_all(), measure_in_basis(qubit, axis, bit), measure_pauli_product(factors, bit), reset(qubit), barrier(qubits)
Classical controlconditional(condition, gate, targets), guarded(condition, body, else_body=None)
Parametersparam(slot), parameters(), parameter_links(), build_parametric()

pauli_rotation(theta, factors) appends exp(-i * theta * P / 2) for the Pauli string P given as (qubit, axis) factors with axis one of "X", "Y", "Z"; omit identity factors. A weight-1 string lowers to rx, ry, or rz and a two-qubit ZZ string to rzz, so fusion and Clifford recognition still see them. Circuit.add_pauli_rotation is the imperative spelling.

builder = CircuitBuilder(4)
builder.pauli_rotation(0.4, [(0, "X"), (1, "Y"), (3, "Z")]).param(0)

trotter(hamiltonian, t, steps=1, order=2) approximates exp(-i H t) with steps steps of length t / steps, each term c P appended as the pauli_rotation exp(-i c P dt). order is 1 for Lie-Trotter, 2 for the symmetric formula, or an even 2k for the Suzuki formula of that order, costing 5 ** (k - 1) second-order substeps. The Hamiltonian is a term list, as the expectation terminals take, or a PauliObservable; identity terms drop out as a global phase. Circuit.add_trotter is the imperative spelling.

from prism_q import CircuitBuilder, PauliObservable, simulate

ising = PauliObservable([(1.0, [(0, "Z"), (1, "Z")]), (0.5, [(0, "X")]), (0.5, [(1, "X")])])
evolved = CircuitBuilder(2).h(0).h(1).trotter(ising, 1.0, steps=8, order=2).build()
energy = simulate(evolved).seed(42).expectation(ising).mean
assert abs(energy - 1.0) < 1e-2  # <H> is conserved up to the Trotter error

Standard gates lower as the OpenQASM parser lowers them, so a builder circuit matches the parsed one instruction for instruction: crx, cy and the other controlled gates become one controlled-unitary, rxx and ryy become Pauli rotations that .param(slot) can bind, u becomes one fused matrix, and iswap and cswap expand to Clifford gates and a Toffoli.

cu and mcu take a 2x2 matrix as nested sequences of complex numbers. Out-of-range or repeated qubits raise PrismError at build time.

Three other routes produce a Circuit:

from prism_q import Circuit, circuits, parse_qasm

qasm_source = "OPENQASM 3.0; qubit[2] q; h q[0]; cx q[0], q[1];"
manual = Circuit(2, 2)                    # imperative, add_gate / add_measure / add_reset
ghz = circuits.ghz(10)                    # prebuilt corpus
parsed = parse_qasm(qasm_source)          # OpenQASM 3.0, with 2.0 accepted

The circuits submodule mirrors the Rust builders documented in Circuit Builders: qft, ghz, w_state, random, hardware_efficient_ansatz, clifford_heavy, clifford_random_pairs, qaoa, single_qubit_rotation, clifford_t, quantum_volume, cz_chain, phase_estimation, independent_bell_pairs, independent_random_blocks, and local_clifford_blocks. Seeded builders default to seed 42.

A Circuit reports its own shape: num_qubits, num_classical_bits, gate_count(), t_count() (T and T-dagger gates), depth() (layers with each operation as early as its qubits allow, a measurement one layer and a barrier none), is_clifford_only(), and measurement_map(), the (qubit, classical_bit) pair of each measurement in order.

assert ghz.gate_count() == 10 and ghz.t_count() == 0 and ghz.is_clifford_only()

Measuring in other bases

measure_in_basis(qubit, axis, bit) rotates axis onto Z and measures, recording the +1 eigenvalue as 0. The qubit is left in the Z eigenstate, not the axis one. measure_pauli_product(factors, bit) measures a product such as X0 X1 without measuring its factors. The first call appends one ancilla past the register to collect the parity, so the circuit is one qubit wider. A second call resets that ancilla, which takes the circuit off the compiled sampling route.

from prism_q import CircuitBuilder, simulate

bell = CircuitBuilder(2, 2).h(0).cx(0, 1)
bell.measure_pauli_product([(0, "X"), (1, "X")], 0)
bell.measure_pauli_product([(0, "Z"), (1, "Z")], 1)
checked = bell.build()
print(checked.num_qubits)                              # 3
print(simulate(checked).seed(1).shots(100).counts())   # {'00': 100}

Classical control

A ClassicalCondition tests measured bits at runtime. ClassicalCondition.bit(b, value=True) reads one bit, parity(bits, expected=True) the XOR of several, and register_equals(offset, size, value) and register_not_equals read size bits as an integer with bit offset least significant. ~condition is the negation.

conditional(condition, gate, targets) applies one gate when the condition holds:

from prism_q import ClassicalCondition, Gate

teleport = CircuitBuilder(3, 3).ry(0.8, 0).h(1).cx(1, 2).cx(0, 1).h(0)
teleport.measure(0, 0).measure(1, 1)
teleport.conditional(ClassicalCondition.bit(1), Gate.x(), [2])
teleport.conditional(ClassicalCondition.bit(0), Gate.z(), [2])
teleport.ry(-0.8, 2).measure(2, 2)
received = simulate(teleport.build()).seed(5).shots(500)
assert not received.shots[:, 2].any()

guarded(condition, body, else_body=None) calls body with a fresh CircuitBuilder of the same width and turns what it appends, measurements and resets included, into a region that runs when the condition holds. else_body builds the region for the other shots:

coin = CircuitBuilder(2, 2).h(0).measure(0, 0)
coin.guarded(
    ClassicalCondition.bit(0),
    lambda then: then.x(1),
    lambda otherwise: otherwise.z(1),
)
coin.measure(1, 1)
print(simulate(coin.build()).seed(3).shots(1000).counts())   # {'00': 507, '11': 493}

The else region rereads the condition after the first region runs, so a body that measures into a bit the condition reads cannot take an else_body (PrismError). A body cannot widen the circuit, which rules out measure_pauli_product and measure_all. Regions nest. A noise model for a circuit with regions carries slots for the body gates, and their events fire only on shots that take the branch. NoiseModel.empty(circuit) sizes the model to those slots too: index i below the instruction count is top-level instruction i, and the body slots follow in region order.

Exporting and drawing circuits

to_qasm() writes OpenQASM 3.0 that parse_qasm reads back to the same instructions, inline angles exact:

from prism_q import CircuitBuilder, parse_qasm

circuit = (
    CircuitBuilder(3, 3)
    .h(0)
    .cx(0, 1)
    .pauli_rotation(0.3, [(0, "X"), (1, "Y"), (2, "Z")])
    .measure_all()
    .build()
)
text = circuit.to_qasm()
assert parse_qasm(text).to_qasm() == text
portable = circuit.to_qasm(expand_pauli_rotations=True)

A multi-letter Pauli rotation keeps its rxyz(0.3) spelling, which only PRISM-Q parses. expand_pauli_rotations=True lowers it to basis changes around a CNOT ladder that other toolchains read. Guarded regions export as if blocks. Save points and dense unitaries on three or more qubits have no OpenQASM spelling and raise PrismError with kind == "export_unsupported".

print(circuit) draws the text wire diagram. draw() takes fold_width, show_idle_wires, show_barriers, max_qubits, and max_moments. Past 64 qubits or 500 moments it returns summary() instead (gate counts, connectivity, depth profile). heatmap() draws gate density by qubit and moment.

print(circuit)
print(circuit.draw(fold_width=80, show_idle_wires=False))
with open("circuit.svg", "w", encoding="utf-8") as f:
    f.write(circuit.to_svg(dark_mode=True, show_legend=True))

to_svg() writes a standalone SVG. Its keyword options cover the theme (dark_mode, or auto_theme to embed both and follow the viewer's color scheme), animate, compact, the show_legend, show_stats_header, and show_topology layers, truncation (max_qubits, max_moments, and ellipsis=(first, last) to keep only the leading and trailing moments), and geometry in SVG units (wire_spacing, moment_width, gate_height, gate_min_width, font_size, control_radius, and padding as (left, top, right, bottom)). to_svg_heatmap() renders the density heatmap. In Jupyter a circuit displays as a static diagram in the page theme, cut to 64 wires and 200 moments.

Parameter sweeps

Parameters names the angle slots a variational loop rebinds. PreparedCircuit holds the circuit across bindings, so fusion and backend selection happen once, not per point. The variational tutorial runs an optimization loop on it.

from prism_q import CircuitBuilder, PreparedCircuit

builder = CircuitBuilder(4)
for q in range(4):
    builder.ry(0.1, q).param(q)
for q in range(3):
    builder.cx(q, q + 1)

prepared = PreparedCircuit(builder.build(), builder.parameters())
for values in [[0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8]]:
    outcome = prepared.run(values, seed=42)

run(values, seed=42) returns the RunOutcome that simulate(...).run() would. expectation(values, observables) reads Simulation.expectation() on the bound circuit without dispatching or fusing again: a list of Pauli strings returns a float64 ndarray, one value per string, and a PauliObservable returns the ObservableExpectation. bind(values) returns the bound Circuit.

run_many and expectation_many take a (points, num_slots) array and cross into Rust once. expectation_many returns a (points, observables) array for a list of strings and one ObservableExpectation per point for a PauliObservable. Up to 16 qubits the rows split across cores, as in run_batch; each result matches the single call with the same seed.

from prism_q import PauliObservable

points = [[0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8]]
hamiltonian = [(1.0, [(0, "Z")]), (0.5, [(0, "Z"), (1, "Z")])]
energies = prepared.expectation_many(points, PauliObservable(hamiltonian), seed=42)

A term list is parsed, and its terms regrouped into qubit-wise commuting sets, on every call. PauliObservable parses once and keeps the grouping after first use. Every Hamiltonian argument accepts one, the gradients included, so build it outside the loop:

h = PauliObservable(hamiltonian)
for values in points:
    mean = prepared.expectation(values, h, seed=42).mean

expectation_gradient(values, h) and expectation_gradient_shift(values, h) return the ExpectationGradient that Simulation.expectation_gradient() and its shift twin give on the bound circuit with the held Parameters. The _many forms return a (points,) array of values and a (points, num_slots) array of gradients; rows split across cores up to 14 qubits.

values, gradients = prepared.expectation_gradient_many(points, h, seed=42)

Automatic dispatch reads the template, so build it at angles typical of the sweep. A template with all rotations at zero reads as Clifford and picks a backend that then rejects the bound circuit. An explicit backend as the third argument avoids this:

from prism_q import BackendKind

circuit, params = builder.build(), builder.parameters()
prepared = PreparedCircuit(circuit, params, BackendKind.statevector())

reuses_fusion_plan reports whether the recorded fused structure is replayed. Only speed depends on it.

builder.parameters() returns the slots recorded by param(slot). Parameters.all_rotations(circuit) gives every bindable gate its own slot in circuit order, and Parameters(n) plus link(instruction, slot) declares slots up front. Gates sharing a slot all receive its angle.

parse_qasm_parametric returns a template and the named slots declared by OpenQASM input statements, in declaration order:

from prism_q import BackendKind, PreparedCircuit, parse_qasm_parametric

template, parameters = parse_qasm_parametric("""
OPENQASM 3.0;
input float[64] theta;
qubit[2] q;
ry(theta) q[0];
cx q[0], q[1];
ry(theta) q[1];
""")
assert parameters.slot_of("theta") == 0
qasm_sweep = PreparedCircuit(template, parameters, BackendKind.statevector())
outcomes = qasm_sweep.run_many([[0.2], [0.7]], seed=42)

Input angles start at zero, so bind the template before simulating and give PreparedCircuit an explicit backend. Each input must be a whole angle argument of a supported gate at top level; expressions such as 2 * theta and inputs inside control flow raise PrismError. parse_qasm still rejects unbound inputs.

MethodReturns
bind(template, values)template with the linked angles overwritten
values(circuit)the angle each slot currently holds
validate(circuit)nothing; raises if a link no longer points at a bindable gate
with_names(names)a copy naming the slots, matching OpenQASM input declarations
name_of(slot), slot_of(name)the name and slot of a named set, else None
unread_slots()declared slots no instruction reads, whose values are discarded

A wrong-length value vector, a non-finite angle, and a link pointing at a gate that carries no angle all raise PrismError.

Dynamic programs

A Circuit is a finite instruction list and cannot hold a loop that repeats until a measurement comes up. parse_qasm_dynamic reads OpenQASM with while, break, continue, and runtime classical values, and returns a DynamicProgram: circuits joined by branches on classical expressions, run once per shot. simulate_program returns the same ShotsResult and CountsResult as a circuit run. The dynamic circuits tutorial has a worked subroutine.

from prism_q import parse_qasm_dynamic, simulate_program

program = parse_qasm_dynamic("""
    OPENQASM 3.0;
    qubit[1] q;
    bit[1] c;
    h q[0];
    c[0] = measure q[0];
    while (c[0]) {
        reset q[0];
        h q[0];
        c[0] = measure q[0];
    }
""")
counts = simulate_program(program).seed(42).sample_counts(1000).counts()
assert counts == {"0": 1000}

An OpenQASM extern calls a Python function. Pass a mapping of callables as externs= to parse_qasm, parse_qasm_parametric or parse_qasm_dynamic. Each receives bool, int or float arguments and returns one of those. A call over a measured bit runs during the shot, taking the GIL:

program = parse_qasm_dynamic(
    """
    OPENQASM 3.0;
    extern flip(bit) -> bool;
    qubit[2] q;
    bit[2] c;
    h q[0];
    c[0] = measure q[0];
    if (flip(c[0])) x q[1];
    c[1] = measure q[1];
    """,
    externs={"flip": lambda bit: not bit},
)
shots = simulate_program(program).seed(42).shots(100).shots
assert (shots[:, 1] != shots[:, 0]).all()

DynamicProgramBuilder builds the same structure directly. Conditions, assigned values, and rotation angles are OpenQASM expression strings over declared variables and classical bits, c[i] for one bit and c for the whole register read as an unsigned integer, or plain bool, int, and float constants. begin_while and begin_if open a block that end() closes, and begin_else, break_loop, and continue_loop work as their OpenQASM keywords do. Variable types are "bool", "int[n]", "uint[n]", "float[n]", and "angle"; integers wrap at their declared width, and float[16] and float[32] round to half and single precision.

from prism_q import DynamicProgramBuilder, Gate, simulate_program

b = DynamicProgramBuilder(2, 2)
b.declare("theta", "float", 0.0)
b.add_gate(Gate.h(), [0]).add_measure(0, 0)
b.begin_while("retry", "c[0] && theta < 1.0")
b.assign("theta", "theta + 0.25")
b.add_reset(0).add_gate(Gate.h(), [0]).add_measure(0, 0)
b.end()
b.add_rotation("ry", [1], "theta").add_measure(1, 1)
program = b.build()
shots = simulate_program(program).seed(7).shots(500)

A shot that runs more blocks than its bound, one million by default, raises PrismError with kind == "step_limit" and the loop's name. .max_steps(n) changes the bound:

b = DynamicProgramBuilder(1, 0)
b.begin_while("forever", True).add_gate(Gate.x(), [0]).end()
simulate_program(b.build()).max_steps(100).shots(1)  # raises

.noise(rules) takes a NoiseBuilder, not a NoiseModel: a model is laid out against one circuit and a program holds one per block. The rules compile against every block and runtime rotation, and each shot runs one noisy trajectory. Readout error flips the returned record, not the bits a branch reads. Leak flags and quasi-static draws last the whole shot, so a qubit leaked in one block stays leaked in the next. The density matrix and an over-rotation rule matching a runtime rotation raise incompatible_backend.

from prism_q import GateFilter, NoiseBuilder, NoiseChannel

rules = NoiseBuilder().after_gates(
    GateFilter.all().named("h"), NoiseChannel.amplitude_damping(0.4)
)
noisy = simulate_program(program).noise(rules).seed(42).shots(1000)

A program without runtime control flow runs as its circuit, with the same seeded shots. The statevector, stabilizer, sparse, MPS, product state, factored, tensor network and density matrix backends run dynamic programs. The stabilizer rank and Pauli propagation engines keep no state per shot and raise incompatible_backend.

Running Simulations

Running a simulation

simulate(circuit) returns a Simulation: configure it with .seed(), .backend(), and .noise(), then call a terminal method. The default seed is 42. A seed reproduces a result within a release; Seeded output lists the releases that changed what a seed draws.

from prism_q import BackendKind, simulate

sim = simulate(circuit).seed(7).backend(BackendKind.statevector())
outcome = sim.run()
TerminalReturnsHonors .noise()Honors .initial_state()
run()RunOutcome: classical bits and the full probability arraydensity matrix onlyyes
shots(n)ShotsResult: per-shot measurement recordsyeswithout .noise()
sample_counts(n)CountsResult: frequency histogramyeswithout .noise()
marginals()MarginalsResult: per-qubit (p0, p1) with .metadata; indexes and iterates as the list of pairsdensity matrix onlyyes
state_vector()complex128 amplitudesnoyes
probabilities_of(qubits)float64 joint distribution over a subset, qubits[0] the lowest bitdensity matrix onlyyes
reduced_density_matrix(qubits)ReducedDensityMatrix: .matrix over a subset with qubits[0] the lowest bit, .purity, .metadatadensity matrix onlyyes
entanglement_entropy(subsystem)EntropyResult: von Neumann entropy of the cut in nats, with .schmidt_valuesdensity matrix onlyyes
expectation(obs)ExpectationResult for a list of observables: .values per observable, .std_errors from a sampling route, .metadata naming the backend; ObservableExpectation for a PauliObservable: the weighted mean with its variance, group variances and standard errordensity matrix onlyyes
observable_variance(obs)ObservableVariance: <H^2> - <H>^2 beside the meandensity matrix onlyyes
expectation_gradient(h, params)ExpectationGradient: .value and .gradient via the adjoint methodnono
expectation_gradient_shift(h, params)ExpectationGradient via the parameter-shift ruledensity matrix or pauli_path()yes
overlap(other)OverlapResult: .fidelity, |<a|b>|^2 against a second Simulation, with .left and .right metadatanoyes

Advanced State Handling has examples of the entropy, overlap and reduced state terminals. Under auto() a wide shallow circuit may be answered by tensor contraction instead of the state vector, and only expectation().metadata says which ran.

expectation_gradient_shift() gives the same gradient as expectation_gradient() at two extra circuit runs per parameter. It is the only route on a backend with no adjoint pass or with a noise model attached. Under noise each evaluation reads the exact mixture, and the shift stays exact because the channels do not depend on the shifted angle.

overlap() takes a second Simulation, so each side keeps its own backend, seed and start state. Both circuits must have the same width and be unitary.

shots() and sample_counts() average trajectories on any backend holding a per-shot pure state. Rows marked "density matrix only" read the exact mixed state and need .backend(BackendKind.density_matrix()), which auto dispatch never selects. The mixture is evolved once and every terminal reads it, so probabilities are seed independent and observables carry no sampling error. With .noise() attached, that route rejects mid-circuit measurement and classical conditioning, since the mixture holds every measurement branch at once. Without a noise model the density matrix backend runs them as the statevector does: each measurement samples and collapses, so run() returns one branch's probabilities and sample_counts() draws a fresh branch per shot.

Terminals that cannot honor a model raise PrismError naming the reason. state_vector() honors .backend(...) and declines on a backend holding no pure state.

ShotsResult and CountsResult both expose counts(), a dict keyed by bitstring. ShotsResult.shots is a bool array of shape (shots, bits); call .tolist() for nested lists.

Amazon Braket programs

parse_braket(source) reads Braket's dialect and returns a BraketProgram: its circuit, parameters, noise model, and the results its #pragma braket result lines request. evaluate() returns one dict per request with type and value, in Braket's basis order, where qubit 0 is the most significant bit:

from prism_q import parse_braket

source = """OPENQASM 3.0;
qubit[2] q;
h q[0];
cnot q[0], q[1];
#pragma braket result probability all
#pragma braket result expectation z(q[0]) @ z(q[1])
"""
program = parse_braket(source)
exact = program.evaluate()
sampled = program.evaluate(shots=1000)

At the default shots=0 every value is exact and sample is declined. Above zero the values come from a measurement record, and state_vector, amplitude and density_matrix are declined. The Amazon Braket guide covers the pragmas.

Memory caps

A run over a cap raises PrismError with kind "resource_limit", whose attributes Errors lists. Caps derive from a memory budget of half of physical memory. Limits sets the budget or any single cap, per request with Simulation.limits() or for the rest of the process with set_default_limits(). A request value beats the process default, which beats the PRISM_MAX_* environment variables; a new default applies from the next call:

from prism_q import Limits, set_default_limits

tenant = Limits(memory_budget_bytes=4 << 30)
outcome = simulate(circuits.ghz(20)).limits(tenant).seed(42).run()

set_default_limits(Limits(max_statevector_qubits=26))
set_default_limits(Limits())  # back to the environment and detection

Every Limits field is a keyword argument that defaults to None, meaning the layer below decides: memory_budget_bytes; the qubit caps max_statevector_qubits, max_density_matrix_qubits, max_probability_qubits (a dense probability array), max_export_qubits (a dense state vector export), max_sparse_qubits, max_factored_merge_qubits, max_stabilizer_cluster_qubits, max_mps_workspace_qubits and max_tn_peak_qubits; max_tn_slices (default 1024), the slices a tensor network contraction may sum over; auto_mps_bond_dim (default 256), the bond cap of the MPS that automatic dispatch falls back to; and max_qec_reference_qubits (default 20), the widest EXP_VAL program the analytical ladder cannot lower that run_qec_program runs on the reference runner. default_limits() returns the process default.

Distributions too wide to write down

A circuit whose qubits fall into independent groups is answered per group, and RunOutcome builds the dense vector only when probabilities is read. Fifteen independent Bell pairs span 30 qubits: 8 GB dense, or 15 arrays of four entries.

outcome = simulate(circuits.independent_bell_pairs(15)).seed(42).run()

outcome.num_basis_states            # 2 ** 30, and nothing was materialized
for qubits, probs in outcome.probabilities_factored():
    print(qubits, probs)            # [0, 1] [0.5 0. 0. 0.5], ...

Each block is (qubits, probs) with qubits ascending and probs indexed by those qubits packed in order, qubits[0] least significant. A basis state's probability is the product of one entry per block, which is what probabilities computes.

probabilities_factored() returns None for a dense distribution, the common case: the decomposed route needs the widest group several qubits narrower than the register, so two Bell pairs stay dense. num_basis_states is None when the backend exposed no distribution.

Result metadata

RunOutcome, ShotsResult, and CountsResult carry a metadata object describing the route that produced them.

circuit = CircuitBuilder(2).h(0).rx(0.3, 1).cx(0, 1).build()
result = simulate(circuit).seed(42).run()
print(result.metadata.backend)               # 'Statevector'
print(result.metadata.engine)                # None unless samplers share the backend
print(result.metadata.is_exact)              # True
print(result.metadata.fidelity_lower_bound)  # None when exact
print(result.metadata.placement)             # 'host' or 'device'
print(result.metadata.bond)                  # None unless the MPS ran
print(result.metadata.blocks)                # per-block engines when 'Decomposed'

is_exact is False when the engine can discard state weight or estimate by sampling. An MPS reports the run instead: one whose cuts discarded nothing past rounding reports is_exact == True at any bond cap.

An MPS run also reports bond, a BondReport: peak (the widest bond any cut kept), cap (the configured maximum), and saturated (peak >= cap). A run whose peak stayed under the cap truncated nothing on the cap's account.

Automatic dispatch sends a circuit past the statevector cap to the sparse map when its state never holds more than 128 basis states, and to an MPS with a bounded bond otherwise. The MPS route is the default and the result says so; .require_exact() rejects it with a PrismError naming the engine it would have used.

big_circuit = circuits.hardware_efficient_ansatz(40, 2)
simulate(big_circuit).seed(42).require_exact().marginals()  # raises

Inspecting a terminal before it runs

Simulation.plan(Query) reports the route a terminal would take and leaves the request ready to run. The query can change the route: an expectation may use an exact scalar tensor contraction where a run over the full state would pick a bounded MPS.

from prism_q import CircuitBuilder, Query, simulate

circuit = CircuitBuilder(2, 2).h(0).cx(0, 1).measure(0, 0).measure(1, 1).build()
request = simulate(circuit).seed(42)
plan = request.plan(Query.counts(1000))
assert plan.would_fail is None
result = request.sample_counts(1000)
assert result.metadata.reason == plan.rule

Plan.backend, engine, placement, and rule describe the selected route. RunMetadata.reason gives its snake_case decision name after execution. A bounded SPD attempt or soft GPU initialization can take a runtime fallback, listed in Plan.fallbacks; the result names the fallback when it happens. A fallback's own would_fail says nothing about the primary route.

Plan.exactness is "exact", "approximate", or "estimated". bound_reported says whether an approximate route reports a bound, and samples gives an estimator's sample count. require_exact() rejects an approximate fallback only if execution needs it.

would_fail is a PrismError instance for a predictable resource or capability failure; malformed query inputs raise PrismError directly. alternatives lists explicit backend selections rejected by the validation execution uses, without ranking accepted backends by speed.

peak_memory holds bytes and kind. Known bounds cover the state and terminal buffer payload, not circuit or fusion storage, allocator overhead, or process memory. Other routes return {"bytes": None, "kind": "unknown"}. Inspection may run bounded sparse support or tensor contraction planning probes but does not execute the terminal.

Query constructors are run(), shots(n), counts(n), marginals(), expectation(observables), observable(hamiltonian), state_vector(), reduced_density_matrix(qubits), and entropy(qubits). The gradient constructors, gradient(hamiltonian, parameters) and gradient_shift(hamiltonian, parameters), take the same Hamiltonian and Parameters as the execution terminals. A shift plan's evaluations lists its baseline, then the plus and minus evaluations in link order. The top-level backend names the baseline; child reports keep any different route chosen for another evaluation, including prepared backend reuse.

Selecting a backend

BackendKind.auto(), the default, picks a backend from circuit structure. An explicit one overrides it.

ConstructorNotes
auto()Structure-driven dispatch. See Choosing a Backend.
statevector()Dense amplitudes, the general path
stabilizer(), factored_stabilizer()Clifford-only circuits
stabilizer_rank()Clifford+T, requires at least one T gate
sparse()Sparse states, for circuits that stay concentrated
product_state()No entangling gates
factored()Partially independent subsystems
tensor_network()Contraction over a network
tensor_network_bounded(tolerance)The tensor network with bond truncation, discarding at most tolerance of each cut's squared weight; approximate
mps(max_bond_dim=256)Truncates at the bond dimension; is_exact says whether a cut dropped weight
density_matrix()Exact mixed states, never chosen by auto()
stochastic_pauli(num_samples=1000)Sampled Pauli propagation
deterministic_pauli(epsilon=0.0, max_terms=65536)Truncated Pauli propagation
deterministic_pauli_budget(max_terms=65536)Pauli propagation holding a fixed term count
pauli_path(epsilon=1e-8, max_terms=65536)Heisenberg Pauli propagation through the attached noise model, for expectation values only; never chosen by auto(), and max_terms=0 keeps every term
auto_gpu(context), statevector_gpu(context), stabilizer_gpu(context), density_matrix_gpu(context)CUDA device paths, see GPU backends

The density matrix backend stores 4^n amplitudes, so its qubit ceiling is about half the statevector cap. Exceeding it raises PrismError naming the cap. statevector_distributed(context) reaches the sharded backend (Distributed backend).

GPU backends

The GPU constructors take a GpuContext, an opaque handle to one CUDA device and its compiled kernels. Construction compiles the kernel module, so build one and share it across simulations.

from prism_q import BackendKind, GpuContext, circuits, simulate

context = GpuContext(0)
outcome = simulate(circuits.qft(16)).backend(BackendKind.auto_gpu(context)).seed(42).run()
print(outcome.probabilities)

A missing or unusable device raises PrismError from GpuContext(device_id), with no fallback. After construction, routing is soft, as in the Rust API. statevector_gpu keeps circuits below its crossover on the host, auto_gpu routes each block on its own, and a block whose device allocation fails runs on the host instead of erroring. A host result is not a failure signal.

density_matrix_gpu(context) has no crossover and no host fallback, and auto_gpu never selects it. A width whose 4^n buffer exceeds free device memory raises before allocating. context.device_name reports the device's product name.

The macOS wheel and a default source build carry no CUDA support. There the constructors still exist and GpuContext(...) raises PrismError naming the missing build feature, not an AttributeError. The GPU guide covers driver and NVRTC loading, the kernel cache, and the crossover defaults with the environment variables that move them.

gpu_info() opens a device and reports its name, or the reason it cannot be used:

info = prism_q.gpu_info()
print(info)   # GpuInfo(available=True, device="NVIDIA GeForce GTX 1080 Ti")

Two cheaper predicates stop short of compiling the kernels:

GpuContext.is_supported()   # was this build compiled with CUDA support
GpuContext.is_available()   # ... and does the driver open a device

Distributed backend

The distributed statevector shards the dense state across MPI ranks. Python reaches it through a DistributedContext, which attaches to an MPI that is already running. The extension never calls MPI_Init or MPI_Finalize. mpi4py does both, at import and at interpreter exit, and a handle that finalized MPI when dropped would break every later MPI call in the process.

from mpi4py import MPI  # starts MPI; import before touching the context
from prism_q import BackendKind, DistributedContext, circuits, simulate

context = DistributedContext()
outcome = (
    simulate(circuits.qft(24))
    .backend(BackendKind.statevector_distributed(context))
    .seed(42)
    .run()
)
print(context.rank, context.size, outcome.probabilities[:4])

Run it with mpiexec -n 4 python script.py. The rank count must be a power of two, and every rank needs enough local qubits after the shard bits are taken. The distributed guide has the memory layout, the tuning variables and what runs sharded.

The contract is SPMD, and enforced. Four ranks are four interpreters running the same source, and all of them enter every collective inside the backend, so a script that branches before the call

if comm.rank == 0:
    result = simulate(circuit).backend(...).run()   # deadlocks

hangs the job: rank 0 blocks in a collective the others never enter. Every rank calls run with the same circuit and seed, and only the handling of the returned value may branch on rank. Two checks at run entry, one collective each, turn the common violations into errors: ranks disagreeing about the register shape, the seed, or the tuning knobs, and ranks handed different circuits.

Two cases raise on purpose.

A world of one rank raises. MPI-2 and later let a singleton MPI_Init succeed, so a script launched without mpiexec would get a correct answer at the speed of one host, with no sign that nothing was distributed. BackendKind.statevector_distributed(context, allow_single_rank=True) allows it.

Constructing the context without MPI running raises instead of starting MPI, so a forgotten from mpi4py import MPI is reported where it happened.

The thread level mpi4py negotiated must be at least MPI_THREAD_FUNNELED: Rayon workers run beside MPI in the same process, and every MPI call stays on the thread that constructed the context. mpi4py requests MPI_THREAD_MULTIPLE by default; lowering it (mpi4py.rc.thread_level = 'single' or mpi4py.rc.threads = False) makes the constructor raise. Below MPI_THREAD_MULTIPLE, a simulation call from a Python thread other than the constructing one raises before it reaches MPI, and at MPI_THREAD_FUNNELED the constructor itself raises off the thread that imported mpi4py.

The published wheels have no MPI support: mpi-sys runs bindgen against a system MPI at build time, and the extension must link the same MPI implementation and ABI as mpi4py and the launcher. Two implementations in one process corrupt state silently, so this is a source build:

maturin develop --manifest-path bindings/python/Cargo.toml --features distributed-mpi

DistributedContext.is_supported() reports MPI support as GpuContext.is_supported() does CUDA.

Sub-communicators, per-rank device placement, and distributed paths other than the statevector backend are out of scope: the context is the world communicator.

Running many small circuits

run_batch takes a list and crosses into Rust once, reusing one backend across circuits of the same width that draw no randomness.

from prism_q import circuits, run_batch

batch = [circuits.hardware_efficient_ansatz(4, 2, seed=s) for s in range(3)]
outcomes = run_batch(batch, seed=42)

Results match running each circuit alone with the same seed; a failing batch raises the first failure in list order. Up to 16 qubits the circuits split across cores, one per core, with the GIL released: a 200-point sweep of a two-layer ansatz ran 3.2x to 4.8x faster than a loop on a four-core host from 4 to 12 qubits, and 5.5x and 1.9x faster than the batch run one circuit at a time at 14 and 16 qubits. From 17 qubits up each circuit uses every core itself, and the batch saves only the crossing into Rust, about 2.4 microseconds a call.

Observables and Gradients

Expectation values

An observable is a Pauli string or a list of (qubit, axis) factors. In a string, character i acts on qubit i, so "ZIX" is Z0 ⊗ I1 ⊗ X2: the leftmost character is qubit 0, the order count keys use. A short string leaves the remaining qubits as identity, and a string longer than the register raises PrismError. The factor form names only non-identity qubits, so [(0, "Z"), (2, "X")] is the same observable and the shorter spelling on a wide register. Both forms mix in one list, and Hamiltonian terms take either as (coefficient, observable).

expectation() is the one expectation terminal. A list of observables returns an ExpectationResult: .values holds one ⟨ψ|P|ψ⟩ per observable as a float64 array, .std_errors the standard errors of a sampling route (else None), and .metadata the route that served them. The result also indexes, slices to a float64 array, has a length, converts with np.asarray as its .values, and pickles with its metadata.

A PauliObservable returns an ObservableExpectation for the weighted sum. mean is <H>. group_variances holds Var(H_g) for each commuting group and variance their sum, the variance of an estimate drawing one shot per group, or None on a route without grouping. std_error is set only when a sampling route estimated the terms. Weighted terms must be wrapped in PauliObservable([...]). A bare (coefficient, observable) list raises TypeError, as does a single factor list such as [(0, "Z")], which is written [[(0, "Z")]]. The circuit must be unitary, except on the density matrix below. observable_variance(hamiltonian) returns <H^2> - <H>^2 with the mean.

from prism_q import CircuitBuilder, PauliObservable, simulate

circuit = CircuitBuilder(2).h(0).cx(0, 1).build()
observables = ["Z", "ZZ", [(0, "X"), (1, "X")]]
values = simulate(circuit).seed(42).expectation(observables).values
energy = simulate(circuit).seed(42).expectation(PauliObservable([(1.0, "ZZ"), (0.5, "XI")])).mean

On BackendKind.density_matrix() the circuit and any attached noise model evolve the density matrix, and the values are exact Tr(rho P), with none of the variance of averaging trajectories. A reset evolves as a channel there, while a circuit with a measurement raises PrismError, so strip measurements first:

model = NoiseModel.empty(circuit)
model.add_event(0, NoiseChannel.amplitude_damping(0.3), [0])
dm = BackendKind.density_matrix()
exact = simulate(circuit).seed(42).noise(model).backend(dm).expectation([[(0, "Z")]]).values

Compare with a tolerance

Analytic means are not bit-stable across separate invocations. Hash-ordered term accumulation can move the last ulp, so compare against 1e-12 rather than asserting exact equality.

Gradients

The variational tutorial uses these gradients to optimize an Ising energy.

expectation_gradient computes ⟨H⟩ and its exact gradient over the bound parameters by the adjoint method, at a cost independent of the parameter count. Mark parameters with param(slot) while building; build_parametric() returns the circuit with the Parameters the gradient takes.

import numpy as np
from prism_q import CircuitBuilder, simulate

builder = CircuitBuilder(2)
builder.ry(0.3, 0).param(0)
builder.cx(0, 1)
builder.rz(0.7, 1).param(1)
circuit, params = builder.build_parametric()

hamiltonian = [(1.0, [(0, "Z")]), (0.5, [(0, "Z"), (1, "Z")])]
result = simulate(circuit).seed(42).expectation_gradient(hamiltonian, params)
energy, gradient = result.value, result.gradient

The result is an ExpectationGradient holding value and a float64 gradient with one entry per slot. It unpacks, indexes and slices as the pair (value, gradient), and pickles. A Hamiltonian term is (coefficient, observable). Gates sharing a slot accumulate their gradients. param() accepts only differentiable gates (rx, ry, rz, rzz, p, pauli_rotation), and the circuit must be unitary.

Noise and Shots

Noise Models describes what each rule and channel does, and the Noisy Simulation tutorial works through a GHZ state under gate noise, readout error and a device calibration.

Noise

A NoiseModel is built from a circuit and sized to it; attaching it to a different circuit raises PrismError.

from prism_q import CircuitBuilder, NoiseChannel, NoiseModel, simulate

circuit = CircuitBuilder(2, 2).h(0).cx(0, 1).measure_all().build()
model = NoiseModel.uniform_depolarizing(circuit, 0.01)
counts = simulate(circuit).seed(42).noise(model).sample_counts(4000).counts()

NoiseModel.uniform_depolarizing(circuit, p) and NoiseModel.with_amplitude_damping(circuit, gamma) cover the common cases. NoiseBuilder attaches channels by rule and validates the model at build(circuit):

from prism_q import GateFilter, NoiseBuilder

noise_rules = (
    NoiseBuilder()
    .after_gates(GateFilter.all().arity(1), NoiseChannel.depolarizing(0.001))
    .after_gates_joint(
        GateFilter.all().named("cx"), NoiseChannel.two_qubit_depolarizing(0.01)
    )
    .uniform_readout_error(0.01, 0.02)
)
rule_model = noise_rules.build(circuit)

Fluent methods update the same builder or filter. A rule copies its filter and channel, so later filter edits leave it unchanged, and build leaves the builder reusable. GateFilter() and GateFilter.all() start unrestricted; named, arity, on_qubits and on_targets add restrictions. on_qubits selects an unordered set of targets, while on_targets([0, 1]) matches the full ordered target list and excludes cx(1, 0). Build against the original circuit, since fusion changes gate names.

The rules are after_gates, after_gates_joint, crosstalk, over_rotation, on_idle_qubits, after_resets, before_measurements, readout_error and uniform_readout_error, with the effects and event ordering listed under Rules.

For explicit slots, start from NoiseModel.empty(circuit) and add events:

model = NoiseModel.empty(circuit)
model.add_event(0, NoiseChannel.amplitude_damping(0.05), [0])
model.add_event(1, NoiseChannel.two_qubit_depolarizing(0.02), [0, 1])
model.with_readout_error(0.01, 0.01)
model.validate()

A device calibration table lowers onto a circuit in one call. DeviceCalibration.parse reads the text form in Device calibration; the presets carry illustrative magnitudes for a technology class, not a measured device:

from prism_q import DeviceCalibration

calibration = DeviceCalibration.superconducting_transmon(circuit.num_qubits)
model = calibration.to_noise_model(circuit)

Channels are pauli(px, py, pz), depolarizing(p), amplitude_damping(gamma), phase_damping(gamma), thermal_relaxation(t1, t2, gate_time, excited_population=0.0), two_qubit_depolarizing(p), custom(kraus) for an explicit list of 2x2 Kraus operators, custom_2q(kraus) for 4x4 operators on two qubits, the leakage channels below, and quasi_static(axis, weights). custom_2q indexes with the first target as the high bit. quasi_static rotates about "x", "y" or "z" by sum(w * z[source]) over (source, w) pairs, with z standard normal draws made once per shot, and the drift rules below lower onto it.

num_qubits is the number of targets an event with the channel names. validate() checks probabilities and Kraus completeness. is_pauli_only() is true only for single-qubit Pauli channels with no readout error. A model with readout error or two_qubit_depolarizing reports False yet still runs on the stabilizer samplers, which apply readout to the record and draw the pair channel jointly over its 15 branches.

A two-qubit Kraus channel models correlated noise, here ZZ dephasing:

import numpy as np

p = 0.02
zz_dephasing = NoiseChannel.custom_2q(
    [np.sqrt(1 - p) * np.eye(4), np.sqrt(p) * np.diag([1, -1, -1, 1])]
)
model = NoiseModel.empty(circuit)
model.add_event(1, zz_dephasing, [0, 1])
model.validate()

It runs exactly on the density matrix and by trajectories on the statevector, sparse, factored, and MPS backends. The stabilizer samplers decline it.

Leakage

leakage(p), seepage(p) and the two-qubit leakage_transport(p) give each trajectory a leak flag per qubit. A leaked qubit ignores gates, a gate pairing it with others applies a uniformly random Pauli to them, measuring it reports 1, and a reset or a seepage (to a uniformly random basis state) clears it. ShotsResult.leaked, the erasure herald, is a (num_shots, num_qubits) bool array marking qubits that leaked at any point of the shot, or None without leakage:

leaky = (
    NoiseBuilder()
    .after_gates_joint(GateFilter.all().arity(2), NoiseChannel.leakage_transport(0.1))
    .after_gates(GateFilter.all(), NoiseChannel.leakage(0.01))
    .after_gates(GateFilter.all(), NoiseChannel.seepage(0.1))
    .build(circuit)
)
result = simulate(circuit).backend(BackendKind.statevector()).seed(42).noise(leaky).shots(1000)
assert result.leaked.shape == (1000, circuit.num_qubits)

Leakage needs a per-shot trajectory, so the density matrix backend rejects it. QEC programs take QecNoise.leak(p), seep(p) and leak_transport(p) (text form LEAK(p), SEEP(p), LEAK_TRANSPORT(p)), sampled as heralded erasures with one QecSampleResult.heralds column per LEAK target. Leakage and Leakage as heralded erasure describe the two models.

Timed and correlated noise

NoiseBuilder.schedule(GateTimes(one_qubit, two_qubit)) schedules the circuit as soon as possible, durations in seconds. with_gate(name, t), with_pair(a, b, t), with_measure(t) and with_reset(t) refine it, and an "id" entry turns identity gates into delays. These rules read the schedule or draw once per shot:

RuleEffect
scheduled_idle(coherence)Thermal relaxation over each qubit's idle time in every layer, from its (t1, t2); replaces on_idle_qubits
quasi_static_detuning(drift)A per-shot frequency offset per qubit in rad/s, applied as a Z phase over each layer's duration
over_rotation_drift(filter, sigma)One per-shot fractional angle error shared by matching rx, ry, rz, p gates
over_rotation_drift_per_qubit(filter, drift)One per-shot fractional angle error per target qubit

A DriftDistribution is a zero-mean Gaussian over per-qubit offsets, built by independent(sigmas), from_t2_star(t2_star) (widths sqrt(2) / t2_star), or from_covariance(matrix). with_neighbour_correlation(coupling, rho) correlates the two qubits of each coupling edge. Drawn offsets have exactly the requested covariance, and a matrix that is not positive semidefinite raises at build:

drift = DriftDistribution.from_t2_star([40e-6, 55e-6]).with_neighbour_correlation(
    [(0, 1)], 0.5
)
timed = (
    NoiseBuilder()
    .schedule(GateTimes(35e-9, 300e-9).with_measure(1e-6))
    .scheduled_idle([(100e-6, 80e-6), (90e-6, 70e-6)])
    .quasi_static_detuning(drift)
    .build(circuit)
)
counts = simulate(circuit).seed(42).noise(timed).sample_counts(1000).counts()

Drift makes every shot a different unitary, so models with it run per-shot trajectories; models without it keep the shared evolution paths. DeviceCalibration.to_scheduled_noise_model(circuit) is to_noise_model plus scheduled_idle timed by the table's own gate_times().

Compiled sampling

simulate(circuit).shots(n) compiles a Clifford circuit's measurements into a parity sampler on every call. CompiledSampler keeps the compiled form across draws and adds reductions that stream shots in bounded chunks instead of holding them:

from prism_q import CircuitBuilder, CompiledSampler

ghz = CircuitBuilder(3, 3).h(0).cx(0, 1).cx(1, 2).measure_all().build()
sampler = CompiledSampler(ghz, seed=7)
shots = sampler.sample(1000)                    # (1000, 3) bool
counts = sampler.sample_counts(10**9)           # closed form at small rank
marginals = sampler.marginals(10**6)            # P(record reads 1)
parities = sampler.parity_expectations([[0, 1], [0, 1, 2]], 10**6)
correlators = sampler.correlators([(0, 2)], 10**6)

Columns, count keys, and indices are measurement records in circuit order: record j is the j-th measurement, and circuit.measurement_map()[j] names its qubit and classical bit. shots() reports classical bits instead. Calls continue one seeded stream: successive calls draw fresh shots, and a new sampler with the same seed replays them. rank counts the independent random bits behind the record, and exact_counts() enumerates all 2 ** rank outcomes up to rank 25. sample_packed(n) returns records eight to a byte in the QecSampleResult.packed_measurements() layout.

parity_expectations(rows, n) estimates <(-1)^parity> for each row of record indices, the expectation of the Z-type Pauli product those records measure; correlators(pairs, n) is the two-record case.

noise=model compiles a Pauli noise model, readout error included, into the sampler, and rank and exact_counts() are then None. The circuit must be Clifford with terminal measurements and no reset or classical condition. Other input raises PrismError naming the reason.

from prism_q import ErrorChainComplex, NoiseModel, noisy_marginals_analytical

model = NoiseModel.uniform_depolarizing(ghz, 0.01)
noisy = CompiledSampler(ghz, seed=7, noise=model)
estimate = noisy.marginals(10**6)
exact = noisy_marginals_analytical(ghz, model)
logical_classes = ErrorChainComplex(ghz, model).homology_dim

noisy_marginals_analytical(circuit, model) returns the exact probability that each classical bit reads 1 under Pauli noise, without sampling or a rank limit. ErrorChainComplex(circuit, model) exposes the GF(2) chain complex behind it: homology_dim counts the independent logical error classes, boundary_dim the independent errors that leave the state unchanged and that no final measurement detects, and noisy_marginals(noiseless) maps noiseless record marginals to noisy ones.

Quantum Error Correction from Python

QecProgram holds a program in the native QEC IR: detectors, logical observables, postselection and Pauli noise annotations around Clifford gates and measurements. The QEC guide describes the model and its runners, and the QEC memory tutorial decodes a repetition code at three distances.

Memory experiments

from prism_q import QecBasis, QecCircuitNoise, QecProgram

qp = QecProgram.surface_memory(3, 3, QecBasis.Z, QecCircuitNoise.uniform(0.002))
qp.set_options(shots=10_000, seed=42)
res = qp.run()
raw_rate = res.logical_error_rates()[0]

repetition_memory(distance, rounds, noise=None) builds a Z memory on the repetition code, surface_memory(distance, rounds, basis=QecBasis.Z, noise=None) one on the rotated surface code, and color_memory(...), with the same arguments, one on the triangular 6.6.6 color code at odd distance. Each carries detectors with coordinates and logical observable 0. QecCircuitNoise sets four rates, all keyword arguments defaulting to 0: after_clifford_depolarization, before_measure_flip_probability, after_reset_flip_probability and before_round_data_depolarization. QecCircuitNoise.uniform(p) sets all four to p, and noise=None gives the noiseless program.

set_options(shots, seed=42, chunk_size=None, keep_measurements=True, detector_reference="noiseless") configures run(). "raw" reports each detector's plain parity instead of its flip against the noiseless reference run (Detector reference).

Building a program

QecProgram(num_qubits) starts empty, from_text parses the text form that to_text writes, and from_stim reads Stim circuit files (Reading Stim circuit files). Operations append in order:

MethodAppends
push_gate(gate, targets)a Clifford gate
reset(basis, qubit)a reset in QecBasis.X, Y or Z
measure(basis, qubit), measure_z(qubit), measure_x(qubit)a measurement; returns its record index
measure_pauli_product(terms)an MPP over (basis, qubit) terms; returns its record index
detector(records, coords=None)a detector over QecRecordRef records; returns its index
detector_lookback(distances)a detector over records counted back from the latest, 1 being rec[-1]
observable_include(observable, records)records into a logical observable
postselect(records, expected)a filter that discards shots whose parity differs
noise(channel, targets)a QecNoise annotation
expectation_value(terms, coefficient=1.0)an EXP_VAL estimate, below
feedforward(records, expected, body)a correction, below

QecRecordRef.absolute(index) names a record by its index and QecRecordRef.lookback(d) by its distance back. QecNoise has x_error(p), y_error(p), z_error(p), depolarize1(p), depolarize2(p), pauli_channel_1(px, py, pz), pauli_channel_2(probabilities) over the 15 non-identity pairs, and the leakage channels leak(p), seep(p) and leak_transport(p).

from prism_q import Gate, QecNoise, QecRecordRef

check = QecProgram(3)
check.set_options(shots=1000, seed=7)
check.noise(QecNoise.x_error(0.05), [0, 2])
check.push_gate(Gate.cx(), [0, 1])
check.push_gate(Gate.cx(), [2, 1])
check.measure_z(1)
check.detector_lookback([1])
check.measure_pauli_product([(QecBasis.Z, 0), (QecBasis.Z, 2)])
check.detector_lookback([1, 2])
data = check.measure_z(0)
check.observable_include(0, [QecRecordRef.absolute(data)])
print(check.to_text())

The ancilla and the MPP measure the same Z0 Z2 parity, so the second detector never fires, while the first fires on the 9.5 percent of shots where exactly one data qubit flipped.

Results

run() returns a QecSampleResult. detectors, observables and measurements are NumPy bool_ arrays with one row per shot. logical_error_rates() and survivor_rate() come with logical_error_rate_wilson_intervals(z_score) and survivor_rate_wilson_interval(z_score), whose default z_score gives a two-sided 95 percent interval. total_shots, accepted_shots and discarded_shots count postselection, logical_errors the failures per observable, and heralds holds one column per LEAK target, or None.

expectation_value(terms, coefficient=1.0) appends the text format's EXP_VAL op over (basis, qubit) terms. Estimates arrive in op order as QecSampleResult.expectation_values, a list of QecObservableEstimate with mean, variance and num_shots, or None for a program without one. observable_expectations has the same shape for the logical observables when a weighted or analytical T strategy produced them:

prog = QecProgram(2)
prog.set_options(shots=1000, seed=1)
prog.push_gate(Gate.h(), [0])
prog.push_gate(Gate.cx(), [0, 1])
prog.expectation_value([(QecBasis.Z, 0), (QecBasis.Z, 1)])
zz = prog.run().expectation_values[0].mean   # 1.0

Compiling once for repeated sampling

run() compiles the program on every call. compile_sampler() compiles once and returns a QecCompiledSampler with the program's seed, chunk size and detector reference:

sampler = qp.compile_sampler()
detectors, observables = sampler.sample(10_000)
batch = sampler.sample_result(1000, seed=7)

sample(shots, *, seed=None, bit_packed=True, separate_observables=True) returns a (detectors, observables) pair of (shots, ceil(n / 8)) byte arrays in the packed_detectors() layout below. bit_packed=False gives bool arrays, and separate_observables=False one array whose columns are the detectors followed by the observables. It counts every shot, whether or not postselection accepts it.

sample_result returns a full QecSampleResult. seed=None continues one stream that starts at the program's seed, and an explicit seed draws what run() draws at that seed. Sampling releases the GIL, and calls on one sampler from several threads run one at a time. Measurement records are dropped unless compile_sampler(keep_measurements=True) asks for them. A program that needs the per-shot or analytical runners (EXP_VAL, non-Clifford gates) raises PrismError from compile_sampler.

Detector error models and decoders

detector_error_model() derives the program's DetectorErrorModel. probabilities() (float64), detector_matrix(), and observable_matrix() (bool, detectors or observables by mechanisms) feed check-matrix decoder constructors. detector_coords() holds per-detector coordinates, and decompose_graphlike() returns the form matching decoders need, at most two detectors per mechanism. to_text() writes the common detector error model text format for file-based decoders:

dem = qp.detector_error_model()
H, p, L = dem.detector_matrix(), dem.probabilities(), dem.observable_matrix()
with open("memory_d3.dem", "w") as f:
    f.write(dem.to_text())

UnionFindDecoder is a built-in union-find decoder over a graphlike model, so a memory experiment needs no external decoder. decode takes the (shots, num_detectors) bool detector array and returns the (shots, num_observables) predicted observable flips:

decoder = prism_q.UnionFindDecoder(dem.decompose_graphlike())
predicted = decoder.decode(res.detectors)
failures = (predicted[:, 0] != res.observables[:, 0]).sum()

MatchingDecoder (exact minimum-weight perfect matching, graphlike models) and BpOsdDecoder (belief propagation with ordered statistics, any model) share that surface. Every decoder also has logical_error_rate(detectors, observables), the fraction of shots with any observable mispredicted, on bool or packed arrays as long as both arguments match. decode_packed takes the packed_detectors() layout below and returns flips in that layout. BpOsdDecoder takes keyword options max_iterations, bp_method ("min_sum" or "product_sum"), min_sum_scaling, osd_method ("osd0", "cs", or "exhaustive"), and osd_order:

matching = prism_q.MatchingDecoder(dem.decompose_graphlike())
bposd = prism_q.BpOsdDecoder(dem, osd_method="cs", osd_order=10)
rates = [d.logical_error_rate(res.detectors, res.observables) for d in (matching, bposd)]

Feedforward

feedforward(records, expected, body) applies the gates and resets of body, a second QecProgram holding the correction, only in shots where the parity over records equals expected. A body of only Pauli gates (X, Y, Z, identity) runs on the compiled path of run(), where the correction becomes a fixed set of record flips. Any other body breaks the single affine map that sampler applies to every shot, so the program runs through run_reference(), the per-shot statevector path, at O(shots * 2^n). That suits small programs.

from prism_q import Gate, QecProgram, QecRecordRef

prog = QecProgram(2)
prog.set_options(shots=1000, seed=1)
prog.push_gate(Gate.h(), [0])
prog.push_gate(Gate.cx(), [0, 1])
flag = prog.measure_z(0)
fix = QecProgram(2)
fix.push_gate(Gate.x(), [1])
prog.feedforward([QecRecordRef.absolute(flag)], True, fix)
prog.measure_z(1)
assert not prog.run().measurements[:, 1].any()
assert not prog.run_reference().measurements[:, 1].any()

Packed records

packed_detectors(), packed_observables(), and packed_measurements() return the same records eight to a byte, as (shots, ceil(n / 8)) uint8 arrays: record j of a shot is bit j % 8 of byte j // 8, and the unused high bits of the last byte are zero. That is an eighth of the bool arrays' memory, and np.unpackbits restores them:

import numpy as np

packed = res.packed_detectors()
detectors = np.unpackbits(packed, axis=1, count=qp.num_detectors, bitorder="little")
assert (detectors.astype(bool) == res.detectors).all()

Advanced State Handling

Starting from a state other than |0...0>

.initial_state(amplitudes) replaces the all-zero start. It takes any sequence of complex numbers, a complex128 NumPy array included, with qubit 0 the least significant bit of the index.

import math
import numpy as np
from prism_q import CircuitBuilder, simulate

theta = math.pi / 8
start = np.array([math.cos(theta), math.sin(theta)], dtype=np.complex128)
circuit = CircuitBuilder(1).h(0).build()
probs = simulate(circuit).initial_state(start).seed(42).run().probabilities

The vector must have 2 ** num_qubits entries and unit norm. A wrong length, a non-finite entry, or a norm off unity raises PrismError. An unnormalized vector is not rescaled.

A start state also narrows the route. The dispatch shortcuts (tableau, product state, subsystem decomposition, Pauli propagation) hold only from |0...0>, since a Clifford circuit yields a stabilizer state only from one. So auto() resolves to the statevector. The GPU and distributed statevectors and density_matrix() are the only other backends that accept a start state, and any other choice raises PrismError naming itself.

Terminals carry it where the terminal table says so. expectation_gradient() rejects it, as do shots() and sample_counts() with a noise model, since trajectory replay reinitializes a pure state per shot. Under noise, read the exact mixture with run(), marginals(), or expectation() on density_matrix().

Starting from a mixture

.initial_density_matrix(rho) starts the density matrix backend from a mixed state: a square complex128 NumPy array or a sequence of rows, in the layout reduced_density_matrix() returns over the whole register (row major, 2 ** n by 2 ** n, qubit 0 the least significant bit of both indices). A noisy run can be paused, its mixture stored, and resumed later:

from prism_q import BackendKind, CircuitBuilder, NoiseModel, simulate

first = CircuitBuilder(2).h(0).cx(0, 1).build()
second = CircuitBuilder(2).rx(0.3, 0).cz(0, 1).build()
dm = BackendKind.density_matrix()
rho = (
    simulate(first)
    .backend(dm)
    .noise(NoiseModel.uniform_depolarizing(first, 0.02))
    .reduced_density_matrix(range(first.num_qubits))
    .matrix
)
probs = (
    simulate(second)
    .backend(dm)
    .noise(NoiseModel.uniform_depolarizing(second, 0.02))
    .initial_density_matrix(rho)
    .run()
    .probabilities
)

The matrix must have 4 ** num_qubits entries, be Hermitian to 1e-12 per entry, and have unit trace to 1e-9, and a failed check raises PrismError naming it. Positive semidefiniteness is not checked. Only density_matrix() and its GPU sibling accept a mixture. Every other backend, auto() included, raises PrismError naming itself. The terminal table applies unchanged. A mixture clears an earlier .initial_state(), and the reverse.

Entropy, overlap and reduced states

bell = CircuitBuilder(2).h(0).cx(0, 1).build()
cut = simulate(bell).entanglement_entropy([0])
print(cut.entropy, cut.schmidt_values)          # 0.6931... [0.7071 0.7071]
print(simulate(bell).reduced_density_matrix([0]).purity)   # 0.5
plus = CircuitBuilder(2).h(0).h(1).build()
print(simulate(bell).overlap(simulate(plus)).fidelity)     # 0.5

entanglement_entropy(subsystem) returns the von Neumann entropy of the cut in nats and schmidt_values, the Schmidt coefficients in descending order with squares summing to 1. schmidt_values is None where the backend holds the entropy without the spectrum, as a stabilizer cut past the export cap does. The cut must leave qubits on both sides. reduced_density_matrix(qubits) returns .matrix with qubits[0] the lowest bit, its .purity, and .qubits. overlap(other) compares two pure states and reports only fidelity, |<a|b>|^2, since a tableau keeps no global phase and truncation moves one. .left and .right carry each side's route.

Handing a Clifford state to a second run

StabilizerBackend holds a tableau across calls. run(circuit) resets it to the circuit's width and runs the circuit, and apply(circuit) runs a circuit on the held state without resetting it. export_tableau() returns the rows as a uint64 array of bit-packed words and a bool array of row signs, and import_tableau(num_qubits, words, phases, num_classical_bits) starts a backend from that pair. The pair serves as a checkpoint for a Clifford prefix that is expensive to replay.

from prism_q import StabilizerBackend

clifford_prefix = CircuitBuilder(4).h(0).cx(0, 1).cx(1, 2).s(3).build()
measurement_suffix = CircuitBuilder(4, 8).h(3).measure_all().build()
prep = StabilizerBackend(seed=42)
prep.run(clifford_prefix)
words, phases = prep.export_tableau()

resumed = StabilizerBackend(seed=42)
resumed.import_tableau(clifford_prefix.num_qubits, words, phases, num_classical_bits=8)
bits = resumed.apply(measurement_suffix)

The import checks only the lengths and that each destabilizer anticommutes with its stabilizer partner, so feed it an export. The random stream restarts from the importing backend's seed, so a resumed run matches an uninterrupted one only when neither drew before the split.

Mid-circuit saves

A save point records the state where it sits, so a circuit can be inspected part way through without splitting it and running twice.

from prism_q import CircuitBuilder, Gate, SaveSpec, simulate

builder = CircuitBuilder(4)
for q in range(4):
    builder.h(q)
circuit = builder.build()
circuit.add_save(SaveSpec.StateVector, "after_hadamards")
circuit.add_gate(Gate.cx(), [0, 1])

outcome = simulate(circuit).seed(42).run()
for record in outcome.saves:
    print(record["label"], record["kind"], record["value"].shape)

Each record is a dictionary with label, kind, and value. SaveSpec.StateVector and SaveSpec.DensityMatrix come back as complex128 arrays, the density matrix flat and row major over 2**n rows. SaveSpec.Probabilities comes back as float64. Records arrive in the order their points were reached, and labels need not be unique.

A save is a barrier across the whole register, so no gate is fused or reordered across it. Only run returns the records: shots, marginals and the other terminals decline a circuit with a save point instead of dropping what it recorded. So do routes that hold no state to read, and OpenQASM export, which has no save syntax.

Errors, Typing and Names

Errors

Every failure, from backend limits to unsupported operations and invalid arguments, raises prism_q.PrismError with the Rust error's message:

import prism_q

huge = prism_q.circuits.ghz(40)
try:
    simulate(huge).backend(prism_q.BackendKind.density_matrix()).expectation([[(0, "Z")]])
except prism_q.PrismError as exc:
    print(exc)   # backend `density_matrix` is incompatible: circuit has ... qubits

PrismError.kind names the Rust variant, such as "parse", "backend_unsupported" or "step_limit", so a caller can branch without matching the message. A run over a memory cap raises kind "resource_limit" with the numbers attached: resource names the unit ("qubits", "amplitudes", "entries", "elements" or "bytes of device memory"), required and limit are integers in that unit, and env_var names the variable that overrides the cap, or is None. knob names the Limits field that overrides it, and limit_source says which layer set it: "detected", "env", "process_default" or "request". On every other kind those six attributes are None.

Typing

Type stubs (prism_q/_prism_q.pyi) and a py.typed marker give mypy and Pyright the full surface.

Names

Python names follow the Rust ones in Python conventions: a Rust constructor such as CircuitBuilder::new_with_classical is the class call, a builder consumed by value is a method chain on a mutable object, and a result field is a property. Two names differ: simulate() returns a Simulation where Rust has the Simulate typestate builder (and simulate_program() a ProgramSimulation), and the circuits generators drop the _circuit suffix. bindings/python/parity.toml records, for every public Rust function, method and result field, the Python name that reaches it or why it stays in Rust only; a test keeps the record complete as the Rust API grows. Python API lists the free functions.

Three classes have taken their Rust names: Decoder is now UnionFindDecoder, QecResult is QecSampleResult, and RecordRef is QecRecordRef. The old names no longer resolve, and pickles written under them no longer load.

Capability and Support Matrix

Which CPU and GPU architectures each backend supports, what each answers past the dense memory cap, and which limits decline by name. CPU backends are portable Rust. A SIMD kernel (AVX2/FMA/BMI2 on x86-64, NEON on ARM64) is selected at runtime where one exists, and a scalar path runs otherwise.

Legend

MarkMeaning
YesSupported
SIMDSupported with a dedicated SIMD-accelerated kernel on this architecture
ScalarRuns on the portable path, with no dedicated SIMD kernel
NoNot available for this backend
RoadmapNot implemented yet; the roadmap carries it and says what it waits on

Backend support by architecture

The ten CPU backends implement the Backend trait, and the feature-gated distributed statevector is an eleventh, covered by the Distributed column. Roadmap here marks a ROCm port of the existing CUDA kernels. A backend without a CUDA kernel has nothing to port, so its ROCm cell is No. The roadmap carries no distributed execution for any backend but the statevector; multi-GPU and distributed GPU work is under Not yet supported.

Backendx86-64AVX2/FMA/BMI2ARM64NEONCUDA (NVIDIA)ROCm (AMD)Distributed
StatevectorYesSIMDYesSIMDYesRoadmapYes
StabilizerYesSIMDYesSIMDYesRoadmapNo
Factored StabilizerYesSIMDYesSIMDNoNoNo
SparseYesScalarYesScalarNoNoNo
MPSYesSIMDYesSIMDOptional SVDNoNo
Product StateYesScalarYesScalarNoNoNo
Tensor NetworkYesScalarYesScalarNoNoNo
FactoredYesSIMDYesSIMDNoNoNo
Density MatrixYesSIMDYesSIMDYesNoNo
MPOYesScalarYesScalarNoNoNo

The four Clifford+T engines are not Backend implementations; they serve probability, shot and observable queries through their own routes (see Clifford+T Simulation).

Enginex86-64AVX2/FMA/BMI2ARM64NEONCUDA (NVIDIA)ROCm (AMD)Distributed
Stabilizer RankYesSIMDYesSIMDNoNoNo
Stochastic PauliYesScalarYesScalarNoNoNo
Deterministic PauliYesScalarYesScalarNoNoNo
Pauli PathYesScalarYesScalarNoNoNo

Notes:

  • AVX2/FMA/BMI2: the x86-64 tier is chosen at runtime, AVX2+FMA, then FMA, then the SSE2 baseline, with an AVX-512 tier first when PRISM_AVX512=1 is set on a CPU that has it. See Threading, SIMD, and Memory Layout.
  • NEON: a SIMD backend's NEON kernel mirrors its x86-64 path.
  • CUDA: the optional gpu feature. The statevector, stabilizer and density matrix have device kernels, MPS supports opt-in cuSOLVER SVD offload at high bond dimension, and every other backend runs on CPU. The density matrix runs on the device only when selected explicitly (BackendKind::DensityMatrixGpu). See the GPU Backend guide.
  • Distributed: the optional distributed and distributed-mpi features. The statevector splits the state across MPI ranks with exact results, gates, measurement, reset and multi-shot sampling included, without gathering the dense state. Noisy shots run every trajectory channel in lockstep, one shot at a time on every rank. Use simulate(&circuit).distributed(context). .initial_state(...) starts a run from an injected amplitude vector: every rank receives the full 2^n vector and keeps only its own slice.

Dense multi-qubit unitaries

Gate::unitary takes a caller-supplied 2^k x 2^k matrix and lowers it into the existing gate set wherever a variant carries it. Only a dense matrix on three or four qubits becomes Gate::Unitary, and the table covers that form alone.

BackendDense Gate::Unitary
Statevector (CPU)Native, one gather-scatter pass over the state
Statevector (CUDA)Native, apply_unitary_nq kernel over the device buffer
FactoredNative, on the merged block holding the targets
Density Matrix (CPU)Native, U rho U^dagger on the doubled register
Density Matrix (CUDA)Native, U rho U^dagger via apply_unitary_nq on the doubled device register
MPSNative, through the same swap network a multi-controlled gate uses
Tensor NetworkNative, as one k-leg tensor
SparseNative, sparse block action on stored basis amplitudes up to 128 qubits
MPODeclines, 3+ qubit dense unitaries have no Pauli transfer kernel
Product StateDeclines, it entangles its targets
Stabilizer, Factored StabilizerDecline, not Clifford
Stabilizer Rank, Stochastic Pauli, Deterministic Pauli, Pauli PathDecline, no Clifford+T lowering
Distributed statevectorNative once the targets are relabelled local; declines when they cannot be, since no exchange path carries a dense k-qubit gate

Every decline is a BackendUnsupported naming the backend and the gate. The gate has no OpenQASM spelling either: exporting a circuit that holds one raises ExportUnsupported.

Shot and observable queries above the dense cap

simulate(...).shots(n), .sample_counts(n) and .expectation_values(...) answer from a dense 2^n vector unless the backend has its own path. System memory caps the dense route (roughly 29 qubits on a 16 GiB host; see Limits::max_statevector_qubits or PRISM_MAX_SV_QUBITS). Backends marked Native answer without it and are bounded only by their own representation. Which engine Auto picks for each terminal is in routes the tree does not show.

BackendShots and countsExpectation values
SparseNative, CDF over the stored amplitudesNative, O(k) over the amplitude map
MPSNative, sequential conditional samplingNative, one contraction over each observable's span between shared identity environments
FactoredNative, one draw per sub-stateNative, product over the blocks
Product StateNative, one Bernoulli draw per qubitNative, one closed-form factor per qubit
Distributed StatevectorNative, a CDF on each rank plus one scalar per rankNative, a sandwich on each rank plus one Allreduce
StatevectorDense (streams from amplitudes, no probability vector)Dense
Stabilizer, Factored StabilizerCompiled Clifford samplerSparse Pauli Dynamics, exact
Stochastic, Deterministic Pauli, Pauli PathNot applicableNative Pauli propagation
Tensor NetworkDense below PRISM_MAX_PROB_QUBITS, then native conditional sampling, one doubled-network contraction per qubit per shotNative, one doubled-network contraction per observable over its backward light cone
Density MatrixDenseNative, Tr(rho P) per observable
MPONative, sequential conditional Born samplingNative, real Pauli basis contraction across the chain

Native sampling is deterministic from the seed alone: the same seed and shot count give the same bitstrings at any thread count. It does not match the dense route shot for shot, since that route consumes its randomness on a different schedule; the distributions agree.

Every backend the crate ships has an observable path. One added later without it declines with BackendUnsupported naming the engine, not the route that selected it.

simulate(...).marginals() escapes the dense output cap when the circuit routes straight to an observable path, so a Clifford circuit with measurements reads its marginals off the tableau at any width. The routing rules list the cases that fall back to the dense distribution.

Under a noise model run() and marginals() answer from the exact mixture, so both reject a model that carries readout error: readout acts on the measurement record, not the state, and is indexed by classical bit where a marginal is indexed by qubit. shots and sample_counts apply it.

Expectation terminals need a unitary circuit, except on BackendKind::DensityMatrix and its device sibling, which evolve a reset as a channel, with or without a noise model. The run honours .limits(), .require_exact() and a start state, and reports the same metadata as the circuit without its resets. A measurement, conditional or Region is still rejected there.

On the distributed backend simulate(...).run(), the one terminal that needs the whole distribution, rejects a register past the dense cap before running.

What kind of answer a result is

Every result type carries a metadata field describing how it was produced:

FieldReads
backendThe engine that answered, after Auto routing
exactnessExact, or Approximate with a fidelity lower bound when the engine reports one
placementHost or Device
shotsShots drawn, None for an analytic result
bondPeak bond dimension against the cap, None unless MPS or MPO ran
blocksThe engine of each independent block when backend is Decomposed, ordered by each block's lowest qubit; empty otherwise

An MPS reports the run. When its cuts discarded no more than rounding, a summed squared weight of at most 1e-24 (one singular value at the default 1e-12 cutoff), the result is Exact at any bond cap; past that it is Approximate with the bound from the discarded weight. The sparse backend at a raised threshold and the bounded tensor network report the route instead: a run of theirs that dropped nothing is still Approximate, with a bound of 1.0.

For an MPS run, bond carries peak, the widest bond any cut kept over the run, and cap, the configured maximum; saturated() reads peak >= cap. A run whose peak stayed under the cap truncated nothing on the cap's account.

The bound describes the normalized state, which every read returns. A truncating MPS does not renormalize its chain, but expectation values, shot sampling, the probability vector and the exported statevector all rescale on read, so probabilities sum to 1 at any bond cap. The discarded weight the bound reports is error in that state, not weight missing from it. How the MPS computes the bound, and how a decomposed run merges its blocks' claims, is on Backends.

Two tensor-network kinds decide what happens at the tensor-network memory cap. Under BackendKind::TensorNetwork a contraction over the cap is sliced: legs are fixed, the network is contracted once per assignment and summed, and the answer stays Exact. Every slice repeats the whole contraction, so a query over the cap can take many times longer than one that fits. BackendKind::TensorNetworkBounded { tolerance } first factors an intermediate and keeps the new bond only as far as discarding tolerance of that cut's squared weight allows, then slices whatever is still over the cap. It reports Approximate, with a bound of 1 minus the discarded weights summed over the cuts of the worst single query, and require_exact() rejects it by name. A query is one shot of the sampling sweep, one observable together with the norm it is divided by, or one other contraction such as an export. Each truncates its own copy of the network, so the loss does not accumulate across shots or observables, though a later shot whose outcomes cut more can still lower the bound. Cuts made drawing mid-circuit measurements and resets count against every query.

Past the statevector cap Auto takes an MPS at a bounded bond dimension, unless an expectation or marginals terminal finds the exact tensor route cheaper, since refusing the MPS would leave an oversize circuit that is not sparse with no route at all. The result says so. simulate(...).require_exact() rejects it with an error naming the engine it would have used, and the engine page says when that check runs.

Simulate::expectation_values_reported returns a standard error per value on a route that estimates rather than evaluates. An evaluated route reports Exact and no interval, so a caller can tell "converged" from "not estimated" without comparing a float against zero.

Declared limits

A limit either declines by name or has no form to write; nothing here truncates an input and answers anyway.

LimitWhat it returns
Kraus sets reach two qubitsNo error. Kraus2q is the widest set in the channel enum and three or more qubits has no variant, so a wider set cannot be written. Model a wider interaction by composing the channels the enum carries, or on the density matrix directly
Readout error acts on the measurement recordInvalidParameter from run, marginals, expectation_values and observable_expectation, naming the terminals that do apply it. A marginal is indexed by qubit and readout by classical bit, so there is nothing to apply it to
EXP_VAL in a QEC program must be terminal and liveInvalidParameter naming the op that followed it, or the qubit measured since its last reset
Subset expansion conditional expectation reaches 16 independent postselection rowsSPD and tensor-network fallback decline past 16 linearly independent rows (BackendUnsupported) after GF(2) reduction; CAMPS handles arbitrary row counts in linear time via sequential MPS projection
A start mixture runs on the density matrixIncompatibleBackend from initial_density_matrix on every other backend, Auto included, since automatic dispatch never selects the density matrix. The 4^n buffer is checked before any allocation, Hermitian to 1e-12 per entry and unit trace to 1e-9, with InvalidParameter naming the failed check. Positive semidefiniteness is not checked, so a mixture with a negative eigenvalue evolves without complaint
Save points are returned by run aloneIncompatibleBackend naming the terminal and the number of save points. A shot loop runs the circuit many times and a marginal reduces it, so neither has a place to put one record per point
A save needs a route that holds a stateIncompatibleBackend naming the save and the route. The compiled samplers reorder measurements, the stabilizer-rank engine carries a weighted sum of branches, and the Pauli-propagation engines carry no state vector at all
A save has no OpenQASM spellingExportUnsupported naming the save and its label. The subset has no save syntax to export into
Noise inside a guarded body needs one state per shotIncompatibleBackend from the density matrix (any guard), the compiled noisy sampler (compiled noisy sampler) and ErrorChainComplex (error chain complex). Trajectories and the stabilizer replay fire a body's events on the shots that take the branch, and so does the noisy shot route on a Clifford circuit whose guards it rewrites to controlled Paulis
The error chain complex takes no guarded gatesIncompatibleBackend from ErrorChainComplex (error chain complex) for a circuit with a conditional. Whether the gate runs is decided per shot, and an error on its guard bit can decide it, so which measurements an earlier error reaches is not fixed. compile_measurements and compile_noisy decline conditionals for the same reason; the shot routes rewrite a guarded Pauli on a bit, a parity, or a register comparison reading one measured bit into Paulis controlled by the measured qubits and sample it compiled
The error chain complex needs named Clifford gates and single-qubit Pauli channelsIncompatibleBackend from ErrorChainComplex (error chain complex) for a gate outside the named Clifford set, which can turn one Pauli error into a sum of them (a rotation at a Clifford angle is not recognized), or for a damping, Kraus or two-qubit channel, which has no single error column. noisy_marginals_analytical returns the same errors
Schedule rules need a static scheduleIncompatibleBackend from NoiseBuilder::build when an idle, scheduled idle, detuning or before-measurement rule meets a circuit holding a region, whose duration depends on the branch

Backend width and memory caps live with the terminals that raise them, under Shot and observable queries above the dense cap. A cap overrun raises PrismError::ResourceLimit, whose knob names the Limits field that raises the cap and whose limit_source says whether detection, the environment, the process default or the request set it.

Not yet supported

TargetStatusNotes
ROCm (AMD GPU)Roadmap, needs hardwareNo AMD device kernels; the GPU path is CUDA-only
Distributed GPURoadmap, researchNo multi-node GPU execution; it follows multi-GPU on one host
Multi-GPURoadmap, needs hardwareA GPU context binds a single device; sharding one statevector across devices also needs peer access between them to stay ahead of the host path

Performance and SIMD

Internals are in Fusion Pipeline and Threading, SIMD, and Memory Layout.

Fusion, tiling and SIMD

  1. Fusion merges small gate passes into fewer, larger ones before execution, reducing memory traffic over the statevector. It is gated on qubit count and costs nothing when it does not apply.

  2. Cache tiling keeps batched gates on data that stays hot across a pass. At startup, the tile budget is min(L2 per core, LLC per logical CPU / 4), clamped to 256 KB to 1 MB (256 KB on the i7-6700K reference host, where 1 MB tiles ran 2x slower at 22 and 24 qubits).

    MultiFused runs targets fitting the budget on budget tiles (bits 0 to 13 at 256 KB), bits 14 to 16 on 2 MB tiles when they fit the last level cache, and higher targets untiled. Multi2q and MultiPauliRot gather contiguous 64-amplitude low runs plus up to eight high qubits into a 2^14 tile (MultiPauliRot counts only X/Y qubits, since external Z bits fix one sign per tile). Override with PRISM_TILE_KB, PRISM_MULTI_2Q_TILE_BITS, and PRISM_MULTI_2Q_LOW_BITS; budgets above 256 KB are derived rather than measured.

  3. SIMD vectorizes the inner complex arithmetic loop, picking the tier at runtime: AVX-512 (opt-in via PRISM_AVX512), AVX2+FMA, FMA or SSE2 on x86_64, NEON on aarch64, scalar elsewhere.

Removing arithmetic beats issuing it faster. A kernel whose operations an algebraic identity or operator structure eliminates hits the memory floor, while a vectorized kernel remains bounded by complex arithmetic issue.

Threading

Rayon parallel kernels engage at 15 qubits, below which pool overhead dominates, with MIN_PAR_ELEMS = 4096 per task. The pool defaults to all logical cores.

Control the thread pool

Set RAYON_NUM_THREADS to cap parallelism. Hyperthreading helps at 24+ qubits by hiding memory latency, but on a contended host it adds noise to benchmarks.

An application that already owns a Rayon pool can keep it: build a ThreadPool::with_threads(n) and run simulations inside install. The global pool is left unbuilt on that path.

Determinism

Unitary evolution and seeded terminal sampling on the dense backends are bitwise reproducible at any thread count; parallel reductions and the batched compiled sampler are not. Determinism states the contract per path.

Tuning environment variables

Every knob is read once per process, on first use, and cached. A value that fails to parse or falls below its minimum prints a stderr warning and is treated as unset. Any value switches a flag knob off.

Limits (also settable in code)

Each cap below is both a Limits field and an environment variable. Simulate::limits (Python Simulation.limits) overrides one request and set_default_limits sets the process default (request > process default > variable). memory_budget_bytes sets the shared budget (half of physical memory by default) and discards lower layer individual caps. auto_mps_bond_dim (default 256) has no variable.

Limits fieldVariableDefaultEffect
max_statevector_qubitsPRISM_MAX_SV_QUBITSdetectedStatevector qubit cap; see Backends
max_density_matrix_qubitsPRISM_MAX_DM_QUBITSfloor(cap_sv / 2)Density-matrix qubit cap, bounded by the statevector cap
max_probability_qubitsPRISM_MAX_PROB_QUBITSdetectedDense probability output cap
max_export_qubitsPRISM_MAX_EXPORT_QUBITSdetectedDense statevector export cap
max_sparse_qubitsPRISM_MAX_SPARSE_QUBITSdetectedSparse amplitude map cap (2^q entries)
max_factored_merge_qubitsPRISM_MAX_FACTORED_MERGE_QUBITSdetectedFactored merged block width
max_mps_workspace_qubitsPRISM_MAX_MPS_WORKSPACE_QUBITSdetectedMPS contraction workspace (2^q amplitudes)
max_tn_peak_qubitsPRISM_MAX_TN_PEAK_QUBITSdetectedLargest planned tensor-network intermediate (2^q elements)
max_tn_slicesPRISM_MAX_TN_SLICES1024Max tensor-network slices to fit the peak cap (1 disables slicing)
max_stabilizer_cluster_qubitsPRISM_MAX_STABILIZER_CLUSTER_QUBITSdetectedFactored stabilizer merged cluster width
max_qec_reference_qubitsPRISM_MAX_QEC_REFERENCE_QUBITS20Widest EXP_VAL program sent to the reference runner (not a memory cap)

Tuning (environment only)

VariableDefaultEffect
PRISM_MAX_DENSE_OUTCOME_BITSdetectedMeasured bit cap for dense terminal sampling
PRISM_QFT_TWIDDLE_CACHE_LIMIT_MB256Soft cap on cached QFT twiddle tables (0 disables caching)
PRISM_AVX512unset1 enables AVX-512 kernels (statevector, QFT, density-matrix 2q Kraus, stabilizer rows, compiled sampler) where avx512f and avx512vpopcntdq exist; verified under emulation, not yet timed on AVX-512 silicon
PRISM_GPU_MIN_QUBITS14Auto GPU crossover qubit count (gpu feature)
PRISM_STABILIZER_GPU_MIN_QUBITS1000Stabilizer GPU crossover qubit count
PRISM_GPU_BTS_MIN_SHOTS131072Shot threshold for compiled BTS sampling on device
PRISM_GPU_BTS_MIN_RANK4Compiled sampler rank threshold for device BTS sampling (min 1)
PRISM_GPU_BTS_MIN_WEIGHT_FACTOR2Parity weight factor for device BTS route (min 1)
PRISM_DIST_MIN_LOCAL_QUBITS10Minimum local qubits per rank before distribution (min 1)
PRISM_DIST_EXCHANGE_CHUNK536870912 (2^29)Amplitudes per rank exchange message (min 1)
PRISM_DIST_RELABEL10/false disables qubit relabeling in distributed backend
RAYON_NUM_THREADSall coresRayon thread count, read by Rayon
PRISM_NO_AVX2_2QunsetFlag: force the 128-bit FMA two-qubit kernel
PRISM_MIN_TILES_PER_CPU1Minimum tiles per hardware thread (0 keeps budget tile)
PRISM_TILE_KBdetectedTile budget in KB (power of two, 128 to 2048; 256 on 256 KB L2)
PRISM_MULTI_2Q_TILE_BITSdetectedLog2 of Multi2q tile amplitudes (13 to 18; 14 at 256 KB)
PRISM_MULTI_2Q_LOW_BITS6Log2 of contiguous low run in Multi2q tile (6 to tile bits minus 1)
PRISM_NO_AVX2_KRAUSunsetFlag: disable AVX2 and AVX-512 dense two-qubit Kraus kernels
PRISM_NO_REORDERunsetFlag: disable Fused2q reordering for Multi2q tiles
PRISM_NO_QFT_BLOCKunsetFlag: expand QftBlock and skip textbook QFT recognition

Benchmarking

Run benchmarks with --features parallel, one process at a time. Benchmark Methodology has the targets, the A/B gate and the comparison controls, and Performance the current numbers.

Benchmark Methodology

Performance holds the published timings, and Performance and SIMD covers the mechanisms being measured.

Measurement tiers

PurposeToolOutput
Published wall timings per circuit familytools/bench_suite.rsRewrites docs/performance/suite.json
Kernel and circuit family regression gateCriterion targets under benches/ and scripts/bench_ab.shCriterion estimates and an A/B report
Instruction counts on a shared CI runnerThe iai target under callgrindCounts per row compared against base
Cross-simulator matrixcomparison/matrix.pyRaw observations, CSV/JSON tables and docs/performance/

The published suite

cargo run --release --features parallel --example bench_suite builds four circuit families from prism_q::circuits, times each size under BackendKind::Auto, and rewrites docs/performance/suite.json with host, thread, compiler and version metadata.

FamilyGeneratorCircuitSizes
GHZghz_circuit(n)H on qubit 0, then a CX chain24, 28, 256, 1024, 4096
QFTqft_circuit(n)Textbook QFT (QftBlock runs as FFT on CPU/GPU statevectors)16, 20, 24, 26, 28
HEAhardware_efficient_ansatz(n, 5, seed)5 layers of random Ry/Rz and linear CX chain16, 20, 24, 26, 28
QVquantum_volume_circuit(n, n, seed)n layers of random paired SU(4) decomposed to CX and rotations16, 20, 24

Fixed parameters:

  • Seeds: 0xDEAD_BEEF for circuit generation, 42 for simulation.
  • Precision and build: Complex<f64> throughout, release profile (opt-level = 3, fat LTO, codegen-units = 1, panic = "abort") with parallel on all logical cores unless RAYON_NUM_THREADS caps the pool.
  • Timed region: simulate(&circuit).seed(42).run() (fusion, gate execution, and probability extraction where supported; stabilizer rows time the tableau alone). Circuit construction stays outside the timer.
  • Sampling: one untimed warmup, then up to 50 warm runs until a 2 s budget and at least 5 runs complete (scaled down to 1 for slow rows). Median is reported; sizes past the memory cap are recorded under skipped.

Criterion targets

TargetRowsFeature flags
bench_driverSingle-qubit and two-qubit gate kernels, measurement and reset, end to end OpenQASM parse and simulateparallel
circuitsCircuit families per backend (random, QFT, HEA, QAOA, Trotter, QV, W state, Clifford, depth/width sweeps), compiled samplers, prepared sweeps, marginals and RDMsparallel (bench-internal for internal groups)
bench_shots_perfShot and count sampling, packed QEC runnerparallel
qec_decoder, qec_t_strategiesUnion-Find decoding of detector batches; Clifford+T sampling strategiesparallel
svd_benchMPS decomposition kernelsparallel
bench_gpuDevice sweeps, Pauli expectations, statevector readbackparallel gpu (skipped without a device)
bench_distributedRank exchanges and sampling over thread loopbackparallel distributed bench-internal
iaiEight single-thread kernel rows counted in instructions under callgrind (Linux)parallel

Run cargo bench --bench <target> -- --list to inspect row names; benches/README.md lists groups, unresolvable rows and the iai gate. Key lookups:

  • Gate and fusion passes: bench_driver (single_qubit_gates, two_qubit_gates, controlled_gates) and circuits (density_matrix/fused_layers vs unitary_layers; disable passes with PRISM_NO_REORDER or PRISM_NO_QFT_BLOCK).
  • Circuit families and scaling: statevector/{random_d10,qft_textbook,qv,scalability_d5,depth_sweep_12q}, stabilizer/scaling, mps/random_d10, sparse/random_d10, tn/scalar_hea_l2.
  • Thread scaling: rerun any row under RAYON_NUM_THREADS=1,2,4,....
  • GPU and distributed: bench_gpu (or tools/bench_gpu_vs_cpu.rs with fusion off), bench_distributed, and scripts/test-mpi.sh --timed.

Reading a number

Criterion averages PRISM_BENCH_SAMPLES samples (default 30; bench-fast drops to 10 for CI triage). PRISM_BENCH_PLOTS enables HTML plots (off by default).

Two standalone cargo bench runs are not a comparison: identical code moved up to 10% between runs on the reference host from rebuilds, code layout and host load. Use scripts/bench_ab.sh, which builds the base and working tree side by side, runs them back to back, and checks each row against a same build control pair:

./scripts/bench_ab.sh --filter '^statevector/qft_textbook/' --ref main

PRs touching hot paths must clear REGRESSION_THRESHOLD (default 5%). Run one benchmark process at a time on an idle host.

Comparative benchmark matrix

comparison/matrix.py compares PRISM-Q against peer simulators under uniform controls: one canonical gate list (or .stim / DEM program) replayed through each native API, release builds with recorded compiler and package versions, matched thread budgets (with P-core affinity pinning when threads are at or below the host P-core count), matching outputs and explicit precision labels (Complex<f64> vs fp32 peers), and OS peak working set.

Workload coverage

CategoryFamiliesTypical sizesPeers
Dense fp64 and fp32rcs, qft, qv, hea, qaoa, tfim, adder16 to 28 qubitsAer (fp64/fp32), QuEST, Spinoza, qip, qsim
GPU statevectorrcs, qft, qv, hea, qaoa, tfim20 to 28 qubitsprismq:gpu, QuEST GPU, CPU reference
Stabilizer and high-shotclifford, ghz, bv100 to 10,000 qubits; up to 10M shots (stats)Stim (1t), Aer stabilizer
MPS and tensor networklowent, wstate, disjoint, rcs/tfim expval40 to 1,000 qubits; bond cap 64 and 256Aer MPS, Aer automatic, quimb TN, quimb MPS
Shot sampling and dynamicsampling, midcircuit, midcircuit_clifford12 to 24 qubits; 1 to 1M shotsAer, Aer fp32, qsim, Stim, Aer stabilizer
Python APIrcs, sampling, clifford, lowentRepresentative sizesprismq-py wheel against native Rust and Python peers
QEC sampling and decodingqec_surface, qec_rep, decode_surface, decode_repDistance 5 to 25; 10k to 1M shotsStim, PyMatching (1t) vs PRISM-Q MWPM and Union-Find
Noisy simulationnoisy_rcs, noisy_hea, noisy_tfim8 to 14q (DM), 10 to 40q (MPO/trajectories)Aer DM/SV/MPS, QuEST DM GPU
Variationalvar_hea (grad, sweep)12 to 24 qubits; TFIM and HeisenbergAer (parameter_binds), prismq-py (PennyLane Lightning omitted on Windows: wheel has no OpenMP or AVX2)
Near-Clifford and sparseclifford_t, sparse_ghz_t, sparse_walk20 to 48q (Clifford+T), 20 to 100q (sparse)Aer extended stabilizer, Aer SV/MPS/automatic

Scaling ladders climb each method toward the host ceiling: dense statevectors to 28 qubits (CPU and GPU), stabilizer to 10,000, MPS to 3,000, tensor networks to 1,024, and factored circuits to 10,000. Dense ladders force PRISM-Q's statevector with PRISM_MAX_SV_QUBITS matched to the harness 80% RAM cap so every rung stays exact. Each simulator stops when a rung times out, is refused for memory, or exceeds its cold call budget (ceiling_s), marking wider rungs skipped.

Protocol and validation

  • Process isolation and timing: one process per measurement, one cold call, then up to 5 warm calls (3 on ladders); the median warm call is reported. Simulator order is shuffled per row (seed 42). Format conversion stays outside the timer.
  • QFT recognition: shared QFT lists use the textbook gate expansion. PRISM-Q folds that sequence back into its block FFT as it does for user QFT circuits; a PRISM_NO_QFT_BLOCK=1 control row times gate by gate replay beside it.
  • Validation: dense outputs check total variation distance against Aer fp64 (cross-checked with QuEST where both ran) within 1e-8 (1e-5 for fp32). Sampled and stats rows check bit marginals and adjacent parities by Bonferroni-corrected exact binomial tests (alpha 1e-3) against a light cone reference (or another simulator where the cone is too wide); rows under 100 shots check deterministic bits only. Expectation values, adjoint gradients and parameter sweeps check elementwise error within 1e-8 against an exact NumPy reference (up to 12 qubits) or cross-check across peers. QEC sampling compares logical error and detector trigger rates statistically; QEC decoding checks MWPM exact agreement and Union-Find threshold bounds.
  • Not measured: Linux-only GPU peers (cuStateVec, Aer GPU, qsim GPU, lightning.gpu, CUDA-Q), ISA toggles (PRISM-Q has no scalar force flag), sampling or mid-circuit on QuEST, Spinoza and qip (dense noiseless adapters only), and Aer fp32 on CP with fusion or RZZ (crashes with an access violation). Spinoza decomposes RZZ into phase and controlled-phase gates.

Profiling

./scripts/flamegraph.sh "qft_textbook/16"     # unix (needs `cargo install flamegraph`)
.\scripts\flamegraph.ps1 "qft_textbook/16"    # windows

The bench profile keeps symbols and line tables while matching release optimizations.

OpenQASM Support

PRISM-Q parses a subset of OpenQASM 3.0 and the common 2.0 syntax into the Circuit IR. The subset lists what parses and what declines. Valid OpenQASM outside the subset returns UnsupportedConstruct naming the construct, never a panic or a silent drop.

Parsing and running

#![allow(unused)]
fn main() {
use prism_q::circuit::openqasm;
use prism_q::simulate;

let qasm_str = "OPENQASM 3.0; qubit[2] q; h q[0]; cx q[0], q[1];";
let circuit = openqasm::parse(qasm_str).expect("parse error");
let result = simulate(&circuit).seed(42).run().unwrap();
}

run_qasm(qasm, seed) parses and simulates in one call. The other entry points in openqasm differ in what they return:

FunctionReturns
parse, parse_with(source, dialect)A Circuit
parse_parametric, parse_parametric_with(source, dialect)The template Circuit and the Parameters its input declarations name (see Input parameters)
parse_parametric_with_inputs(source, inputs)The same, with values supplied for some input declarations by name
parse_dynamic, parse_dynamic_with_inputs(source, inputs)A DynamicProgram with loops and runtime classical values (see Dynamic programs)
parse_with_externs, parse_parametric_with_externs, parse_dynamic_with_externsThe same three, with functions for extern declarations (see Extern functions)
parse_braketA BraketProgram: circuit, parameters, result requests and noise (see Amazon Braket Programs)

Dialect::Native, the default, reads gpi, gpi2 and ms angles in turns; Dialect::Braket reads them in radians and accepts #pragma braket lines.

Exporting

#![allow(unused)]
fn main() {
use prism_q::circuit::qasm_export;

let circuit = prism_q::circuits::qft_circuit(4);
let qasm = qasm_export::to_qasm3(&circuit).expect("export error");
}

Re-parsing an export gives back the same instruction stream, with gate matrices equal to round-off and inline angles (rx, rz, rzz, p) exact. Qubits come out as one qubit[n] q register and classical bits as one bit[m] c, split only where a condition compares against a register narrower than the whole.

A circuit that has been through fusion does not export: fused blocks, tiled multi-gate passes and diagonal batches carry matrices with no OpenQASM spelling, and to_qasm3 returns ExportUnsupported naming the instruction index. Export before fusing, or export the template a PreparedCircuit binds. QftBlock and PauliRot are the exceptions: the first expands to its textbook Hadamard, controlled-phase and swap sequence, the second to its CNOT ladder. On the CPU statevector, an expanded QFT parsed back in runs as one block again (see QFT recognition).

Declarations and measurement

OPENQASM 3.0;
include "stdgates.inc";
qubit[3] q;          // OpenQASM 3.0 register
bit[3] c;
h q[0];
cx q[0], q[1];
c[0] = measure q[0]; // OQ3 measurement

OpenQASM 2.0 qreg q[3];, creg c[3]; and measure q[0] -> c[0]; also work.

A bit declaration may take a value: bit b = measure q[0]; measures into it, and bit[2] f = "00"; or bit b = 0; spell out the cleared register it starts as anyway. Bit strings are written most significant bit first. Under parse, an initializer with a set bit, or any assignment to a bit (c = 2;, c[0] = 1;, c <<= 1;), returns UnsupportedConstruct, since no instruction in the list writes a classical bit; parse_dynamic writes them.

Names may open with any Unicode letter, so gate cphase(θ) a, b { ... } and qubit γ; parse. A program declares at most 2^24 qubits and 2^24 classical bits, physical $k indices included; past that the parse fails with PrismError::Parse.

output bit[3] c; declares the register and marks it as the program's result, which changes nothing: every classical bit is reported either way.

Physical qubits

A program may name physical qubits directly instead of declaring a register:

OPENQASM 3.0;
bit[2] c;
h $0;
cx $0, $1;
c[0] = measure $0;
c[1] = measure $1;

The indices are absolute, so the register is as wide as the highest one named. A qubit or qreg declaration in the same program is rejected, since a physical index and a register offset would give 0 two meanings.

Slices and aliases

An index may be a single position, an inclusive range with an optional step in the middle, or an explicit set. A sliced register broadcasts as a whole one does. A negative index counts from the end: q[-1] is the last qubit and q[1:-1] runs from the second to the last.

OPENQASM 3.0;
qubit[6] q;
h q[0:2];         // q[0], q[1], q[2]
h q[0:2:5];       // q[0], q[2], q[4]
h q[5:-1:4];      // q[5], q[4]
h q[{1, 4}];      // q[1], q[4]
cx q[0:1], q[2:3];

let names qubits or bits in the order written, ++ joins operands, and an alias is itself sliceable, so a slice of an alias follows the alias's order, not the register's.

let ends = q[5] ++ q[0];
let pair = q[0:3];
h ends[0];        // q[5]
h pair[1:2];      // q[1], q[2]

Classical variables

int, uint, bool, float and angle declarations, with an optional width, fold at parse time, and the value reads anywhere a literal would: an index, a loop bound, a gate angle, a condition operand. const forbids reassignment.

OPENQASM 3.0;
qubit[4] q;
bit[4] c;
const int width = 4;
float theta = pi / 8;
int cursor = 0;
for int k in [0:width - 1] { rx(theta * k) q[k]; }
cursor += 2;
h q[cursor];

An int or uint is an exact integer that wraps at its width, 64 bits when none is given, and / or % between two integers truncates toward zero: 1 / 2 is 0, 1.0 / 2 is 0.5. A float[n] is an IEEE 754 float of 16, 32, 64 or 128 bits. float[16] and float[32] round to half and single precision, and float[128] holds a double, since nothing here computes in quad precision. Floats take + - * / and **; % takes integers, and mod(a, b) is the float remainder. An angle[n] holds the nearest multiple of 2 pi / 2^n, modulo 2 pi. Casts such as int[8](x), uint[2](c), bool(x) and angle[3](t) convert the same way, and a[i] on an integer reads one of its bits. A float cast to an integer drops its fraction and wraps at the integer's width, so int[8](1e30) is 0; past about 1.7e38 it saturates first, and NaN reads as 0. A float has no bit pattern to cast to bit[n]; cast it to uint first. An expression on its own, a == 2;, is evaluated and discarded.

A declaration inside a for body binds for one pass: the body's scope is dropped at the end of each iteration, while a write to a name declared outside the loop carries on to the next pass and past the loop.

An if, else or switch body opens a scope too and may declare and write its own variables. A measurement decides whether it runs, so a write to a variable declared outside it returns UnsupportedConstruct: the folded value would depend on what the measurement read. Holding such a value needs the control-flow graph parse_dynamic builds.

An array of any of those element types takes a size per dimension, fixed at parse time, and folds the same way. Elements read as a[i, j] or a[i][j] wherever a value would and take plain and compound assignment. A write inside a loop outlives the pass, which filling an array needs.

array[float[64], 2, 2] angles = {{0.1, 0.2}, {0.3, 0.4}};
array[int, 4] order;
for int k in [0:3] { order[k] = 3 - k; }
rx(angles[1, 0]) q[order[0]];   // rx(0.3) q[3]

sizeof(a) and sizeof(a, d) give the length of dimension d, 0 by default. A range in a subscript, a[1:3] or g[0, 1:2], names a slice that keeps the dimension, and a subscript with fewer indices than dimensions names a row. A slice or row reads as an array where one belongs: an initializer, the right side of an assignment to a slice or a whole array, and an array argument. ++ joins arrays along their first dimension. The shapes on both sides of an array assignment must match, and a mismatch is a Parse error. a[i:j] on an int or uint reads those bits as an unsigned value.

array[int[8], 2] first = {0, 1};
array[int[8], 3] second = {2, 3, 4};
array[int[8], 5] joined = first ++ second;
second[1:2] = first;              // second == {2, 0, 1}
def fill(mutable array[int[8], #dim = 1] out) {
  for int i in [0:sizeof(out) - 1] { out[i] = i; }
}
fill(joined[2:4]);                // joined == {0, 1, 0, 1, 2}

A def takes an array as readonly or mutable, with one size per dimension or a rank, #dim = n. The argument passes by reference, so a mutable parameter writes back to the caller's array or slice. The element type must match, and the shape must match the sizes or the rank. A compound assignment to a slice, a[0:1] += b, declines.

array[bit, n], array[complex, n] and array[duration, n] decline. A def body sees the program's const arrays and its array parameters, as it sees no other non-constant global.

Complex numbers

complex[float[n]], and bare complex for 64-bit components, fold at parse time like the other scalars. An imaginary literal is a number followed by im, with spaces or tabs allowed before the suffix. Complex values take + - * / and **, which returns the principal value, and compare with == and !=. exp and sqrt take a complex argument. real, imag, abs and arg read one as a real number, and a complex value reaches a gate angle only through them. A def takes and returns complex values.

complex[float[64]] a = 10.0 + 5.0im;
complex[float[64]] b = a ** (-2.0 - 7.0im);
rz(arg(b)) q[0];

A complex value where a real one belongs, and a cast from complex to a real type, are Parse errors. A complex value a measurement or a loop decides declines under parse_dynamic, which has no runtime type for one.

Timing

A simulation has no clock, so timing parses and has no effect. delay is the identity on the qubits it names, or on every qubit when it names none, and emits no instruction, so fusion merges across it. A box, with or without a duration, runs its body in place with no barrier at its edges, since a box only fixes when its contents run; names its body declares go out of scope with it.

OPENQASM 3.0;
qubit[2] q;
const duration pulse = 40ns;
duration settle = 2 * pulse + 1us;
stretch slack;
h q[0];
delay[settle] q[0];
delay[slack] q;
rz(settle / pulse) q[1];   // a ratio of durations is a number: 27
box[settle] {
  cx q[0], q[1];
}

Literals take dt, ns, us (or µs), ms and s, with or without spaces before the unit. Durations add, subtract, scale by a number, divide into a number and compare, all folded at parse time. A length is held as nanoseconds beside a count of dt, which stays its own unit since only a backend's sample period relates the two: 10ns + 2dt keeps both parts, (10ns + 2dt) / (5ns + 1dt) is 2 and 10ns + 2dt > 5ns holds, but 10ns / 2dt and 10ns > 2dt decline because their answer depends on the period.

Every gate takes no time. durationof({ ... }) is the length of its block under that model, without running it: the longest qubit timeline its delays build, where a multi-qubit gate, a barrier and a multi-qubit delay synchronise the qubits they name and a fixed-length box takes its length.

duration d = durationof({ delay[100ns] q[0]; cx q[0], q[1]; delay[50ns] q[1]; });  // 150ns

A stretch is its initializer, a lower bound, plus a growth that fills idle time. A box[d] whose body holds only gates, measurements, resets, barriers, delays, nop and nested boxes fixes the stretches its alignment determines uniquely; after the box their value reads like any duration. A stretch nothing fixes may still stand wherever a delay takes a length, and declines where its value would be read.

stretch s;
box[90ns] { delay[s] q[0]; x q[0]; delay[2 * s] q[0]; }
rz(s / 1ns) q[1];   // s resolved to 30ns

A box[d] whose delays run past d is a Parse error.

Supported gates

  • Standard names and aliases: id/i, x, y, z, h, s, sdg, t, tdg, sx, rx, ry, rz, p/phase, cx/CX/cnot, cy, cz, cp/cphase, crx, cry, crz, ch, swap, ccx/toffoli, cswap/fredkin, cu, cu1, cu3, u0, u1, u2, u3/u/U, c3sqrtx. The legacy qelib1.inc names follow that file's definitions: cu1 is cp, cu3(θ, φ, λ) is cu(θ, φ, λ, 0), u0 is the identity and c3sqrtx is sx under three controls.

  • Braket spellings: si, ti, v, vi, phaseshift, cphaseshift, cphaseshift00, cphaseshift01, cphaseshift10, cv, ccnot, prx, pswap, xy, xx, yy, zz. Most name a gate the list above carries; cphaseshift00/01/10, pswap and xy are their own matrices.

  • Qiskit and exporter names: sxdg, cs, csdg, csx, ccz, r, xx_plus_yy, xx_minus_yy, ecr, iswap, dcx, c3x, c4x, mcx, rccx, rc3x/rcccx.

  • Hardware-native: gpi, gpi2, ms, syc, sqrt_iswap, sqrt_iswap_inv. gpi, gpi2 and ms take angles in turns, matching IonQ's transpiler output. openqasm::parse_with(source, Dialect::Braket) reads them in radians, as Amazon Braket spells them.

  • Pauli rotations: r followed by one Pauli letter per qubit argument. rxx, ryy and rzz are the two-letter cases; rxyz(0.7) q[0], q[1], q[2]; is exp(-i * 0.7 * (X⊗Y⊗Z) / 2) with x on q[0]. rzz resolves to the native two-qubit rotation and a one-letter name to rx/ry/rz; wider strings build the native multi-qubit gate, which the statevector applies in one pass and every other backend receives as its CNOT-ladder lowering.

    The wider spelling is a PRISM-Q extension, not standard OpenQASM, and to_qasm3 emits it so a round trip keeps the gate. For output another toolchain reads, run circuit::expand_pauli_rotations before exporting.

gphase(theta) multiplies the state by e^(i theta). It is carried, not dropped: a state_vector result shows it, and under a control ctrl @ gphase(theta) q[0] is a phase gate on q[0].

User gate blocks define new gates; an empty body is the identity. A gate applied to whole registers broadcasts across them, and a gate length such as x[100ns] q; parses and is dropped.

Gate modifiers

ctrl @, negctrl @, inv @ and pow(k) @ chain in any order. ctrl(n) @ and negctrl(n) @ stand for n controls. Each control consumes one qubit from the front of the argument list, in the order the modifiers are written, and negctrl differs from ctrl only in firing on |0>.

A control applies to what the gate expands to, not to its name, since ctrl(U1 U2 ... Un) is ctrl(U1) ctrl(U2) ... ctrl(Un). That reaches a user gate body, a gate that lowers to a sequence, and swap, which becomes the Fredkin lowering rather than three controlled CNOTs. The two-qubit gates carried as a matrix (ecr, xy, pswap, cphaseshift00/01/10, ms, syc, sqrt_iswap, sqrt_iswap_inv, xx_plus_yy, xx_minus_yy) take a control through their eigenbasis: ctrl(V D V-dagger) is V ctrl(D) V-dagger, and a controlled diagonal costs one phase per entry at any control count. A def call declines, being a subroutine, and so does a call spanning more than four qubits, where the dense reduction stops.

pow(k) takes any real k. On a single-qubit gate it is the principal matrix power, read from the eigenvalues with each angle on (-pi, pi], so pow(0.5) @ x is sx and pow(1.0/3) applied three times is the gate again. The branch follows the eigenvalue, not the written angle: p(1.5*pi) and p(-0.5*pi) are the same matrix and take the same root. A whole number is repetition at any width, rejected past a million; a fraction on a wider call is the principal power of the matrix the whole call composes to, up to four qubits. inv @ and pow(k) @ commute with a control, so a chain reads the same either way.

The declines are listed under The subset.

Expressions

Expressions take + - * / %, **, the comparisons, &&, ||, !, and &, |, ^, ~, <<, >> with C precedence; the constants pi, tau and euler; and the OpenQASM builtins arcsin, arccos, arctan, ceiling, cos, exp, floor, log, mod, popcount, pow, sin, sqrt and tan. ** is right associative and binds tighter than unary minus, so -2 ** 2 is -4. The constants, true and false cannot be redeclared in the global scope; a gate or def parameter may shadow a constant. Line and block comments are accepted.

Statements, conditions and expressions nest at most 256 levels, an operator chain such as a + b + c counting one level per operator, and a deeper source fails with PrismError::Parse. The bound also covers the gate and def bodies a call expands, counted together with the blocks around it. Separately, gate and def calls nest at most 32 deep inside one another's bodies, which stops a recursive definition with a Parse error naming the gate or subroutine.

Conditions

An if guards a single statement or a braced body. A braced body admits any supported statement, measure and reset included, and may nest.

bit[2] c;
qubit[3] q;
c[0] = measure q[0];
if (c[0]) {
  x q[1];
  c[1] = measure q[1];
  if (c[1]) { reset q[2]; }
}

else, else if and switch with case and default arms lower to guards on the existing condition language. A condition may test a bit, a register against a value, or a parity such as if (c[0] ^ c[2]) or if ((c[0] ^ c[2]) == 0). Under parse, anything else over classical bits declines; parse_dynamic evaluates it at runtime, along with measured bits read as values, such as int x = c[0] + 2 * c[1]; or if (c[0] && !c[1]). Under parse, a bit read as a value anywhere but a guard returns UnsupportedConstruct.

Because the guards re-read the classical bits, else is rejected when the if body measures into a bit the condition reads, and switch when any arm measures into the switched register: such a source could take two arms of one choice. An else body may write freely, since nothing re-reads after it.

Subroutines

A def is inlined at each call. Classical arguments, bit and bit[n] included, pass by value: under parse a bit parameter can be read but not written, and under parse_dynamic assignments update a copy. Qubit parameters may name fixed-width registers such as qubit[2] anc, including slices the caller supplies, in order. Arguments may not overlap on a qubit. Signature widths resolve where the subroutine is declared.

A -> bit or -> bit[n] result lands on the bits the call is assigned to. The body returns a measurement with return measure q;, or ends with return r; for a bit it declared, which it may branch on first. parse_dynamic also returns a computed bit value or a bit parameter, and a returned local bit with a classical initializer needs it: it initializes the bit on every call, after copying the arguments.

OPENQASM 3.0;
qubit[3] q;
bit[3] c;
def mx(qubit a) -> bit {
  h a;
  return measure a;
}
def herald(qubit a, qubit flag) -> bit {
  bit r;
  r = measure a;
  if (r) x flag;
  return r;
}
def fix(bit b, qubit a) {
  if (b) z a;
}
c[0] = mx(q[0]);
c[1] = herald(q[1], q[2]);
fix(c[0], q[2]);

The call expands to exactly the inlined body's instructions, so c[1] = herald(q[1], q[2]); is c[1] = measure q[1]; if (c[1]) x q[2];.

Scalar results of type int, uint, bool, float, angle or duration fold at parse time when their values are known. Arguments and results convert to their declared widths before use. The body sees global constants from its declaration scope, not the caller's variables or registers. Calls may appear in initializers, assignments, gate arguments and return expressions:

qubit q;
def offset(int n) -> int[8] {
  if (n > 0) return n;
  return 0;
}
int n = offset(2) + offset(3);
rx(n) q;

A return exits the subroutine from inside any loop, box or conditional body; return; exits one with no result, and a scalar result may be discarded. Under parse the path a call takes must return its declared result; under parse_dynamic every reachable path must. A missing result is a Parse error.

Under parse_dynamic, numerical results and scalar locals may depend on measured bits. Nested calls keep their own arguments and results. Calls in while conditions run at each test, and calls on the right of && or || run only when needed.

qubit q;
bit[2] c;
def decode(bit b) -> int {
  if (b) return 1;
  return 0;
}
h q;
c[0] = measure q;
int correction = decode(c[0]);
rx(correction * pi) q;
c[1] = measure q;

Under parse_dynamic, a body may declare bits it does not return and measure into them, and a call may drop a bit result. Those bits are private: the blocks address them past the declared bits, DynamicProgram::num_private_bits counts them, and no shot reports them, so the shot width stays the declared width. Each call takes its own, and a runtime call writes a private bit's initializer, or zero, on every call:

qubit[2] q;
bit[1] c;
def herald(qubit a, qubit flag) {
  bit r;
  h a;
  r = measure a;
  if (r) x flag;
}
herald(q[0], q[1]);
c[0] = measure q[1];

parse declines these forms by name, since a Circuit reports every bit it holds. parse_dynamic declines a measurement into a bit parameter, and a private bit in a def inlined into a while body, whose passes would share it. Both decline a measurement returned as a scalar result, a stretch returned as a duration, runtime duration, fixed-width angle and complex values, and modifiers on runtime calls. parse also declines a scalar result that depends on a measurement and a call inside a measurement-dependent condition, both of which parse_dynamic takes. Under parse_dynamic, a bit argument or bit result read at runtime declines past 64 bits, the width a runtime value holds.

Input parameters

An input declaration names a parameter slot. openqasm::parse_parametric returns the template circuit with the Parameters that bind it, in declaration order and under the declared names; parse_parametric_with does the same under a chosen Dialect.

OPENQASM 3.0;
input float[64] theta;
input float[64] phi;
qubit[2] q;
h q[0];
rx(theta) q[0];
cx q[0], q[1];
rz(phi) q[1];
#![allow(unused)]
fn main() {
use prism_q::circuit::{openqasm, qasm_export::to_qasm3};
let qasm = "OPENQASM 3.0; input float[64] theta; input float[64] phi; qubit[2] q;
    h q[0]; rx(theta) q[0]; cx q[0], q[1]; rz(phi) q[1];";
let (template, params) = openqasm::parse_parametric(qasm)?;
let bound = params.bind(&template, &[0.41, 1.27])?;
let text = to_qasm3(&bound)?;   // angles written out, no `input` line
Ok::<(), prism_q::PrismError>(())
}

Several gates may read one input, the weight sharing Parameters already models: rx(theta) q; over a register links every gate it produces to one slot, and binding writes one angle to each.

parse rejects a program that declares an input, since it has no value to take and a zero would be a quiet wrong answer. Use parse_parametric, or PreparedCircuit for a sweep.

A gate angle may be affine in its inputs: rx(-theta / 2) and rz(2 * theta + pi) link their gates with that scale and offset, so binding writes scale * value + offset and a gradient picks up the factor scale. The template holds each angle at an input of zero.

A link reads one slot, so the parser emits one rotation per input an angle reads: rx(a + 2 * b) q; becomes rx(a) q; rx(2 * b) q;. A gate with no angle of its own is emitted as the rotations it equals, global phase included:

CallEmitted
U(theta, phi, lam), u3, u2, u1p(lam), ry(theta), p(phi)
r(theta, phi), prxrz(-phi), rx(theta), rz(phi)
cp(lam) a, b, cphase, cphaseshiftp(lam / 2) a, rz(lam / 2) b, rzz(-lam / 2) a, b
crz(theta) c, trz(theta / 2) t, rzz(-theta / 2) c, t
crx, crycrz between basis changes on the target
cu(theta, phi, lam, gamma)two cx around phase and ry gates
gphase(theta)p(theta), x, p(theta), x on one qubit
ctrl @ or negctrl @ on rx, ry, rz, p, U, gphasethe controlled row above

The same call with no input in it parses to the single gate it always did. Fusion folds the emitted rotations back into one block from 10 qubits.

An input reaches a gate through a for body, or as the argument of a gate or def whose body uses it in an angle; an angle parameter keeps it unwrapped, as a bound input angle is. A float[32] or fixed-width angle parameter would round it and declines.

These return UnsupportedConstruct naming the reason: an angle not affine in its inputs (sin(theta), theta * theta), an input on a gate built as one matrix and not listed above (xx_plus_yy, ms, pswap), inv @, pow @ or more than one control on a gate reading an input, a guarded body, and an input read as a classical value (an index, a loop bound, a declaration).

parse_parametric_with_inputs takes values for some inputs by name. A supplied input folds as a declaration of its type initialized to the value would, so input int[8] n; reads as a loop bound and input bit[2] mask; as bits. A supplied float or angle is a constant and takes no slot; the unsupplied ones keep theirs. An unsupplied input of any other type, a name supplied twice, and a name no input declares return InvalidParameter.

#![allow(unused)]
fn main() {
use prism_q::circuit::{dynamic::ClassicalValue, openqasm};
let qasm = "OPENQASM 3.0; input int[8] n; input float theta; qubit[4] q;
    for int i in [0:n] { rx(theta / 2) q[i]; }";
let (template, params) =
    openqasm::parse_parametric_with_inputs(qasm, &[("n", ClassicalValue::Int(3))])?;
let bound = params.bind(&template, &[0.8])?;
Ok::<(), prism_q::PrismError>(())
}

Extern functions

An extern declaration names a function the program calls and gives its types. The caller supplies the function: Externs::register binds a Rust closure to the name, and the _with_externs entry points take the registry. Python passes a mapping of callables as externs= to parse_qasm, parse_qasm_parametric and parse_qasm_dynamic.

#![allow(unused)]
fn main() {
use prism_q::circuit::dynamic::ClassicalValue;
use prism_q::circuit::openqasm::{self, Externs};

let mut externs = Externs::new();
externs.register("correction", |args| Ok(ClassicalValue::Float(args[0].to_float() * 0.1)));
let circuit = openqasm::parse_with_externs(
    "OPENQASM 3.0;
     extern correction(int[8]) -> float;
     qubit[1] q;
     rx(correction(3)) q[0];",
    &externs,
)?;
Ok::<(), prism_q::PrismError>(())
}

Each argument is stored through its declared type before the call, so int[8] passes 257 as 1. The function returns a Bool for bool and bit, an Int for int[n] and uint[n], and a Float for float[n] and angle, where an Int is promoted. A bit[n] of up to 64 bits passes and returns as the uint[n] its bits spell, so f(c[0:2]) and f(c[{0, 2, 1}]) pass a slice or an index set. The result is stored through the declared type. A call reads as a value anywhere one belongs, inside def bodies too, and as a statement its value is dropped.

A call whose arguments fold at parse time runs once, at parse time, under every entry point. Under parse_dynamic_with_externs, a call over a measured bit or a runtime variable lowers to ClassicalExpr::Extern and runs when a shot evaluates it, so its value may feed a condition, an assignment, a bit write or a runtime rotation angle:

extern decode(bit, bit) -> bool;
qubit[3] q;
bit[2] s;
s[0] = measure q[1];
s[1] = measure q[2];
if (decode(s[0], s[1])) x q[0];

Shots run on several threads, so a Rust function is Send + Sync. A Python callable takes the GIL for each call, and an exception it raises becomes the __cause__ of the PrismError the caller sees. A call nothing reads may not run, and how often a runtime call runs is otherwise unspecified, so a function should be pure.

An entry point without _with_externs, and a Python parse given no externs, declines every extern declaration with UnsupportedConstruct. Under the _with_externs entry points, these return InvalidParameter: a declaration with no function registered under its name, a result of the wrong kind, and any error the function returns or a Python callable raises. A function registered for no declaration is ignored. These return UnsupportedConstruct: an extern with no result type, a parameter or result of another type (bit[n] past 64 bits, angle[n], complex, duration, arrays), a call over an unsupplied input, and under parse a call over a measured value. A call with the wrong number of arguments, an extern declared inside a body, and a gate or def sharing an extern's name return Parse.

ExternCall::new builds a call for a DynamicProgramBuilder from a name, the parameter and result types, the function, and the argument expressions. build checks the argument count and the type widths.

Dynamic programs

openqasm::parse returns a Circuit, a finite instruction list, so it declines while and any classical value a measurement decides. openqasm::parse_dynamic reads both and returns a DynamicProgram: basic blocks of ordinary circuits joined by branches on classical expressions, run once per shot by simulate_program.

#![allow(unused)]
fn main() {
use prism_q::circuit::openqasm;
use prism_q::simulate_program;

let source = "
    OPENQASM 3.0;
    qubit[1] q;
    bit[1] c;
    uint[8] tries = 1;
    h q[0];
    c[0] = measure q[0];
    while (c[0]) {
        reset q[0];
        h q[0];
        c[0] = measure q[0];
        tries += 1;
        if (tries == 10) break;
    }";
let program = openqasm::parse_dynamic(source)?;
let shots = simulate_program(&program).seed(42).shots(1000)?;
Ok::<(), prism_q::PrismError>(())
}

Beyond what parse reads, parse_dynamic accepts:

  • while (condition) { ... }, with break and continue.
  • break, continue and end under a measured if or switch. A for still unrolls, and an exit a measurement decides jumps between its passes.
  • Any condition or switch target over classical bits, where parse takes only those a bit or register guard spells: c[0] && c[1] and c + 1 == 2 run here.
  • A classical bit read as a value (c[0]) and a bit register read as an unsigned integer (c), up to 64 bits.
  • A write to a variable under a measured if or switch, evaluated when the program runs.
  • A write to classical bits: bit[2] f = "11";, c = c + 1;, c[0] = c[1] ^ c[2];, c <<= 1;. A write takes an integer or a bool, and a bit register wider than 64 bits takes one only from a parse-time value.
  • A runtime value as the angle of rx, ry, rz, p or rzz.

A variable lives at runtime only when a measured bit or another runtime variable reaches it, or when a loop or a measured branch writes it from outside its scope. Every other variable folds as under parse, so a program parse accepts gives the same circuit under parse_dynamic and the same seeded shots. Runtime int and uint variables wrap at their declared width, and runtime floats round to their width. A runtime angle holds a double. Fixed-width runtime angle[n] declarations and casts return UnsupportedConstruct, since that precision is honoured only when the value folds at parse time.

A shot that runs more than a million blocks stops with PrismError::StepLimit naming its loop; SimulateProgram::max_steps sets another bound. The dynamic programs architecture page covers the block structure, the backends that run it, and its cost.

SimulateProgram::noise takes NoiseBuilder rules, compiles them against every block and runtime rotation, and runs one noisy trajectory per shot. The loop above with amplitude damping after each h:

#![allow(unused)]
fn main() {
use prism_q::circuit::openqasm;
use prism_q::simulate_program;
let program = openqasm::parse_dynamic(
    "OPENQASM 3.0; qubit[1] q; bit[1] c; h q[0]; c[0] = measure q[0];
     while (c[0]) { reset q[0]; h q[0]; c[0] = measure q[0]; }",
)?;
use prism_q::{GateFilter, NoiseBuilder, NoiseChannel};

let rules = NoiseBuilder::new().after_gates(
    GateFilter::all().named("h"),
    NoiseChannel::AmplitudeDamping { gamma: 0.4 },
);
let noisy = simulate_program(&program).noise(&rules).seed(42).shots(1000)?;
Ok::<(), prism_q::PrismError>(())
}

Dynamic declines

parse_dynamic returns UnsupportedConstruct for:

  • A runtime value where a parse-time constant belongs: a qubit index, a loop bound, a register size, a duration, and the angle of any gate but the five rotations above.
  • A runtime argument to a def written as a gate application, f(x) q;. Called as a function, f(x, q), the same def takes it.
  • A slice of a runtime int or uint read as a value. A slice or index set of a bit register, c[0:2] or c[{0, 2}], reads as the unsigned value of the bits it picks, the first lowest.
  • A builtin function (sin, sqrt and the rest) over a runtime value. Only operators, popcount and extern calls run at runtime.
  • A bit or qubit register declared inside a while body, and an array a loop or measurement writes.
  • A measurement straight into a variable. Measure into a bit and assign the bit.
  • An unsupplied float or angle input, since a dynamic program has no parameter binding. parse_dynamic_with_inputs takes a value for every input by name, as parse_parametric_with_inputs does, and a supplied bit input may set bits.

The subset

UnsupportedConstruct means the program is valid OpenQASM that this parser does not implement. Parse means the text is not accepted as written. The remaining variants name the specific mistake: UndefinedRegister, InvalidQubit, InvalidClassicalBit, GateArity.

ConstructStatusWhat a decline returns
OPENQASM 2.x and 3.x headersParsesAnother major version: UnsupportedConstruct naming the version. A header that is not a number: Parse
include "..."Accepted and ignoredNothing. The standard gates are built in, so an include adds no names; a gate it would have defined declines later by name
qubit, qreg, bit, cregParsesA bit initializer with a set bit, an assignment to a bit, or a bit read as a value outside a guard: UnsupportedConstruct under parse, written or read at runtime under parse_dynamic, where a slice or an index set reads as an unsigned value. A bit string whose length differs from the register, or a float written to bits: Parse
Physical qubits ($0)ParsesA qubit or qreg declaration in the same program: UnsupportedConstruct
int, uint, bool, float, angle, complex, constParsesAny other type: UnsupportedConstruct naming the type. A complex value where a real one belongs: Parse. A write under a runtime if or switch to a variable declared outside it: UnsupportedConstruct under parse, evaluated at runtime under parse_dynamic
arrayParses; folded at parse time, with slices, ++, sizeof and array argumentsAn element type other than int, uint, float, angle or bool, or a compound assignment to a slice: UnsupportedConstruct. An initializer or assignment of the wrong shape, an index out of range, an index set on an array, or more than 2^20 elements: Parse
box, box[d]Runs its body in place; box[d] resolves the stretches its alignment fixesA length that is not a duration or is negative, or delays that run past it: Parse
duration, stretch, delayParses; a delay is the identityA length that is not a duration (delay[10]) or is negative, and a duration where a number belongs: Parse. A ratio or comparison over a stretch no box[d] has resolved, or mixing dt with SI units where the sample period decides the answer, and a runtime value in a duration under parse_dynamic: UnsupportedConstruct
durationofFolds to the block's length with every gate taking no timeA block holding anything but gate calls, measure, reset, barrier, delay, nop and box, or timelines mixing dt with SI units: UnsupportedConstruct
input, outputParses; an unsupplied float or angle input is a slot that gate angles affine in it link toAn unsupplied input of another type: InvalidParameter. output of a type other than bit, an input on a gate with no lowering to rotations, or an unsupplied input anywhere but in an angle affine in it: UnsupportedConstruct
measure, resetParsesA register measure whose widths disagree: Parse
barrier;, barrier q; and barrier q[0], q[1];ParsesA bare barrier; spans every qubit declared so far, across registers
nopParses; emits nothing
Casts, int[8](x), bool(c)ParsesA width on bool, an integer width outside 1 to 64 bits, a float width other than 16, 32, 64 or 128, or a float cast to bit: Parse
Expression statements, a == 2;Evaluated and discarded; scalar subroutine calls are inlinedSee Subroutines for call limits
if, else, else ifParseselse at the head of a statement: UnsupportedConstruct. A condition over classical bits that no bit or register guard spells: UnsupportedConstruct under parse, evaluated at runtime under parse_dynamic. An else whose if body measures into a bit the condition reads: Parse
switch, case, defaultParsesAn arm that measures into the switched register, or more case labels than the region depth bound when a default is present: Parse. A target over classical bits that no register guard spells: UnsupportedConstruct
forUnrolls at parse timeA range in any form but [start:stop], [start:step:stop] or {a,b,c}: UnsupportedConstruct naming what it found. The bounds may be classical variables and def or extern calls
whileParses under parse_dynamicUnsupportedConstruct under parse: a loop that exits on a measurement has no finite instruction list
break, continueParses inside for and whileOutside a loop, or at the top level of a def or gate body: Parse. In a for under a measurement-dependent branch: UnsupportedConstruct under parse, lowered into the graph under parse_dynamic
endStops the program; nothing after it runsInside a gate body, called or not: Parse. Under a measurement-dependent branch: UnsupportedConstruct under parse, lowered into the graph under parse_dynamic
defInlines its body, with fixed-width qubit registers, bit results, and scalar results; parse_dynamic supports runtime numerical results, and bits a body measures into without returning, or a call drops, which no shot reportsSee Subroutines for the forms that decline, all UnsupportedConstruct. A result or argument of the wrong width, overlapping qubit arguments, qubits written after the call as on a gate (f(q[0]) q[1];, f q;), a missing result, or calls nested past 32 deep: Parse
returnExits a def, including nested branches and loopsOutside a def: UnsupportedConstruct. Under a measurement-dependent branch: UnsupportedConstruct under parse, lowered into the graph under parse_dynamic
gate blocksParses; an empty body is the identityCalls nested past 32 deep: Parse
A gate length, x[100ns] q;Parses; the length is dropped
defcalgrammar, cal, defcalParsed and skipped: a calibration says how a gate is pulsed, not what it doesA call to a gate only a defcal names: UnsupportedConstruct naming it
externCalls a registered function under the _with_externs entry points; see Extern functionsAny other entry point: UnsupportedConstruct. No registered function, or a result of the wrong kind: InvalidParameter. No result type, a type other than bool, bit, bit[n] up to 64 bits, int[n], uint[n], float[n] and angle, a call over an unsupplied input, or a call over a measured value under parse: UnsupportedConstruct. The wrong number of arguments: Parse
opaqueDeclinesUnsupportedConstruct
ctrl, negctrl, ctrl(n), negctrl(n), inv, pow(k)Parses, chainable in any orderSee Gate modifiers for the reach of each, and below for the declines
gphase(theta)Parses and is carried
#pragma braket ..., pragma braket ...Parses under Dialect::BraketAny other dialect, a braket pragma inside a braced body, or one this crate does not read: UnsupportedConstruct naming it
Any other pragma, and annotations (@ns.tag ...)Ignored, as the language asks of a pass that does not read them
A gate name the crate does not implementDeclinesUnsupportedConstruct naming it
A gate call at the wrong widthDeclinesGateArity naming the gate, the arity it wanted, and what it got
A gate call naming one qubit twice, as written (cx q[1], q[1];) or after register broadcast (cx q, q;)DeclinesParse naming the gate and the qubit

Modifier declines, all UnsupportedConstruct: ctrl @ on a def call, which is a subroutine rather than a gate; ctrl @ on a body that measures, resets or branches; a ctrl @ chain past 255 controls; pow(k) @ on a call spanning more than four qubits or carrying an instruction with no matrix; and inv @ on a body that is not a gate sequence. A whole-number pow past one million repetitions returns Parse naming the count.

Gate calls, loops and repetitions multiply, so a parse also stops with Parse once it expands past 2^24 units of work: an emitted instruction or classical write, one per qubit for a runtime rotation, or a statement or loop pass that emits none. Subroutine argument binding and copying its constant environment count too, and a pow repetition is checked against the bound before it is built.

Every decline above happens at parse time, so a program that parses is one the IR can hold. The backend it runs on may still decline the circuit, as Capabilities lists.

Amazon Braket programs

parse_braket reads Braket's result, noise, unitary and verbatim pragmas, and Simulate::braket_results answers the requests in Braket's conventions, both covered on Amazon Braket Programs.

Qubit ordering

q[0] is the least significant bit, so x q[0] produces state index 1, not 2.

Amazon Braket Programs

openqasm::parse_braket reads a program under Braket's dialect and returns a BraketProgram: the circuit, its input parameters, the result requests from #pragma braket result lines, and the noise model from #pragma braket noise lines. parse reads the native dialect, where a pragma is an unsupported construct. parse_with under Dialect::Braket reads the pragmas but returns only the circuit, so a result request survives only through parse_braket. The rest of the language is on OpenQASM Support.

OPENQASM 3.0;
qubit[2] q;
h q[0];
cnot q[0], q[1];
#pragma braket noise bit_flip(0.1) q[0]
#pragma braket result probability all
#pragma braket result expectation z(q[0]) @ z(q[1])

Pragmas

  • Result requests: state_vector, density_matrix, amplitude, probability, expectation, variance, sample. Observables are x, y, z, h, i and hermitian([[...]]), joined into tensor products with @. A target list may be all, omitted (the same thing), or named qubits. adjoint_gradient is declined: Braket serves it on SV1 only.
  • Noise channels: bit_flip, phase_flip, pauli_channel, depolarizing, amplitude_damping, generalized_amplitude_damping, phase_damping, two_qubit_depolarizing, two_qubit_dephasing, and kraus with explicit operators. Each attaches after the instruction it follows, so a pragma before every instruction is an error. Probabilities are checked against Braket's own bounds.
  • Inline unitaries: #pragma braket unitary([[...]]) q[0] on one or two targets. A wider matrix has no gate variant to carry it and says so. A target named twice returns Parse.
  • Verbatim boxes: #pragma braket verbatim followed by box { ... }. The body runs as written: verbatim directs a device compiler, and a simulator has nothing to honour. A box without the pragma runs the same way; the pragma without a box is rejected.

Matrix entries take Braket's complex notation: a real (0, -1.5), an imaginary (1im, -1im), or their sum (0.7 + 0.7im). A braket pragma stands at the top level; inside a braced body it returns UnsupportedConstruct.

Braket also spells gpi, gpi2 and ms in radians where the native dialect reads turns, and names several gates its own way; Supported gates lists them.

Computing the results

Simulate::braket_results evaluates the requests in Braket's conventions, which differ from the native terminals in one way: Braket writes qubit 0 as the most significant bit of a basis index, so x q[0] lands at index 2 of a two-qubit result, not index 1.

#![allow(unused)]
fn main() {
use prism_q::circuit::openqasm;
use prism_q::simulate;

let qasm_str = "OPENQASM 3.0; qubit[2] q; h q[0]; cnot q[0], q[1];
    #pragma braket result probability all
    #pragma braket result expectation z(q[0]) @ z(q[1])";
let program = openqasm::parse_braket(qasm_str).expect("parse error");
let values = simulate(&program.circuit)
    .seed(42)
    .braket_results(&program.results)
    .unwrap();
}

One traversal serves every expectation and variance request: the observables lower to weighted Pauli sums, the distinct strings across all of them are evaluated together, and each value is a weighted sum over that evaluation. h expands as (X + Z)/sqrt(2) and a Hermitian matrix by its Pauli decomposition, so no observable needs a second path.

An observable with no target list applies to each qubit separately and reports one value per qubit, so an expectation value is a list rather than a number. variance is the spread of the operator itself, <O^2> - <O>^2, not the grouped-measurement variance ObservableExpectation reports beside a mean. sample has no exact reading and is declined here.

Shot-based results

Simulate::braket_results_sampled answers the same requests from a measurement record, as Braket does above zero shots:

#![allow(unused)]
fn main() {
use prism_q::{circuit::openqasm, simulate};
let program = openqasm::parse_braket("OPENQASM 3.0; qubit[2] q; h q[0]; cnot q[0], q[1];
    #pragma braket result probability all
    #pragma braket result expectation z(q[0]) @ z(q[1])").unwrap();
let values = simulate(&program.circuit)
    .seed(42)
    .braket_results_sampled(&program.results, 1000)
    .unwrap();
}

Each observable is diagonalized and the rotation onto the computational basis is appended once, so one pass serves every sample, expectation and variance request. sample reports the eigenvalue each shot read, expectation its mean and variance its population variance. Pauli and h observables take a named rotation; a Hermitian matrix is diagonalized numerically, which needs a gate wide enough to carry the result, so it stops at two qubits.

Two observables reading one qubit in different bases cannot share a measurement and are rejected. The identity reads no basis, so it shares a qubit with anything. A probability request reads the computational basis and takes its own unrotated pass whenever a rotation was applied. state_vector, amplitude and density_matrix report the state itself and are declined above zero shots, as sample is at zero.

Drawing Circuits

A Circuit renders as a Unicode wire diagram for the terminal, as a heatmap of gate density for circuits too large to read gate by gate, or as self-contained SVG of either. Rendering reads the instruction list and simulates nothing.

Text diagrams

Display draws the circuit with default options:

#![allow(unused)]
fn main() {
use prism_q::CircuitBuilder;

let circuit = CircuitBuilder::new_with_classical(3, 3)
    .h(0)
    .cx(0, 1)
    .rz(0.25, 1)
    .cx(1, 2)
    .ry(0.5, 2)
    .cz(0, 1)
    .t(2)
    .measure_all()
    .build();
println!("{circuit}");
assert!(circuit.to_string().contains("Rz(0.2500)"));
}
q[0]: ─H──@───────────────────────@──────M0────
          │                       │
q[1]: ────X───Rz(0.2500)──@───────Z──────M1────
                          │
q[2]: ────────────────────X───Ry(0.5000)──T─M2─

Gates pack into moments, the columns, so gates on disjoint qubits share one. @ marks a control, X the target of a CX, and Mk a measurement into classical bit k. Angles print to four decimals, or as a fraction of π when they are one.

draw(&TextOptions) takes the layout options:

FieldDefaultEffect
fold_width120Line width in characters before the diagram folds into stacked sections
show_idle_wirestrueDraw qubits that no gate touches
show_barrierstrueDraw barrier instructions
max_qubitsNoneDraw at most this many wires and note how many were left out
max_momentsNoneDraw at most this many moments and note the truncation

A narrow fold splits the same circuit across sections, separated by a dashed rule:

#![allow(unused)]
fn main() {
use prism_q::{CircuitBuilder, TextOptions};

let circuit = CircuitBuilder::new_with_classical(3, 3)
    .h(0).cx(0, 1).rz(0.25, 1).cx(1, 2).ry(0.5, 2).cz(0, 1).t(2).measure_all().build();
let opts = TextOptions {
    fold_width: 40,
    ..TextOptions::default()
};
println!("{}", circuit.draw(&opts));
}
q[0]: ─H──@──────────────────
          │
q[1]: ────X───Rz(0.2500)──@──
                          │
q[2]: ────────────────────X──
╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌
q[0]: ─────@──────M0────
           │
q[1]: ─────Z──────M1────
q[2]: ─Ry(0.5000)──T─M2─

max_qubits and max_moments crop a larger circuit to its corner:

#![allow(unused)]
fn main() {
use prism_q::TextOptions;
use prism_q::circuits::ghz_circuit;

let opts = TextOptions {
    max_qubits: Some(3),
    max_moments: Some(4),
    ..TextOptions::default()
};
let text = ghz_circuit(8).draw(&opts);
assert!(text.contains("and 5 more qubits"));
}
q[0]: ─H──@──────────
          │
q[1]: ────X───@──────
              │
q[2]: ────────X───@──
  ... and 5 more qubits
  ... truncated at moment 4 of 8

Past 64 qubits or 500 moments, draw returns summary() instead: gate counts, connectivity, a depth profile, qubit activity, a heatmap, and a classification such as Clifford-only. summary() works on a circuit of any size.

Heatmaps

heatmap(&TextOptions) shows where the gates are, not what they are: one row per qubit, one column per moment, a filled cell where a gate acts. Rows and columns are bucketed to fit fold_width, and the legend gives the gate count each shade stands for. A hardware-efficient ansatz shows its CX ladder as a diagonal band:

#![allow(unused)]
fn main() {
use prism_q::TextOptions;
use prism_q::circuits::hardware_efficient_ansatz;

let text = hardware_efficient_ansatz(8, 3, 42).heatmap(&TextOptions::default());
assert!(text.starts_with("Gate density heatmap (8 qubits x 17 moments)"));
}
Gate density heatmap (8 qubits x 17 moments):
q[0]: █████ ███ █
q[1]: ████████████
q[2]: ██ ██████████
q[3]: ██  ██████████
q[4]: ██   ██████████
q[5]: ██    ██████████
q[6]: ██     ██████████
q[7]: ██      ███ ███ █
      0              16
  Legend: ' '=0  █=1

SVG

to_svg(&SvgOptions) returns a complete <svg> document as a String. to_svg_heatmap does the same for the heatmap and adds marginal activity bars and a color key. The bars sum activity by qubit and by moment, and an operation counts once on every qubit it touches, so a CX adds two to its moment total.

#![allow(unused)]
fn main() {
use prism_q::SvgOptions;
use prism_q::circuits::{ghz_circuit, hardware_efficient_ansatz};

let opts = SvgOptions {
    auto_theme: true,
    animate: false,
    ..SvgOptions::default()
};
std::fs::write("ghz_5.svg", ghz_circuit(5).to_svg(&opts)).unwrap();
std::fs::write(
    "hea_12_heatmap.svg",
    hardware_efficient_ansatz(12, 4, 0xDEAD_BEEF).to_svg_heatmap(&opts),
)
.unwrap();
}

A filled dot marks a control and a circled plus the target of a CX. q[0] is the least significant bit. Subscripts identify wires and rotation axes. Angles appear below gate names in radians, to at most three decimal places, with scientific notation for small values. Tooltips show the full angle when the SVG is opened directly or embedded inline but not when it is embedded as an image, so each figure below links its full SVG.

Wide figures scroll horizontally, or with the arrow keys once focused, and follow the book theme.

Five-qubit GHZ circuit: H on q[0], then a ladder of four controlled X gates.
Each CX extends entanglement to the next qubit. Open full SVG.
Gate activity across 12 qubits and 25 moments of a hardware-efficient ansatz, with activity totals along both axes.
Filled cells mark activity. The stepped pattern follows the CX ladders; bar labels give activity totals by qubit and moment. Open full SVG.

The SvgOptions fields fall into four groups. Lengths are in SVG user units.

GroupFieldsDefault
Themedark_mode, auto_themelight; auto_theme embeds both themes and follows prefers-color-scheme, overriding dark_mode
Annotationsshow_legend, show_stats_header, show_topologyall off: a legend of gate categories, a qubit, gate and depth line on top, and a qubit connectivity graph beside the circuit
Contentshow_idle_wires, show_barriers, max_qubits, max_moments, ellipsis_modeeverything drawn; ellipsis_mode: Some((first, last)) keeps the first and last moments with a gap between
Layoutwire_spacing, moment_width, gate_height, gate_min_width, padding_*, font_size, control_radius, compact64, 72, 46, 46, padding 64/32/24/32, 20 px, 4.2; compact shrinks spacing and fonts for dense embedding

animate is on by default and adds CSS animations, which a prefers-reduced-motion query switches off. Turn it off for static output.

#![allow(unused)]
fn main() {
use prism_q::SvgOptions;
use prism_q::circuits::qaoa_circuit;

let opts = SvgOptions {
    dark_mode: true,
    show_topology: true,
    ellipsis_mode: Some((3, 3)),
    ..SvgOptions::default()
};
let svg = qaoa_circuit(6, 3, 42).to_svg(&opts);
assert!(svg.starts_with("<svg"));
}

tools/gen_doc_diagrams.rs regenerates the circuit images on this site with fixed seeds:

cargo run --features parallel --example gen_doc_diagrams

Examples

Measurements add classical wires beneath the qubits: a double line is a classical bit, and a dashed arrow joins a measurement to the bit it writes.

A Bell pair followed by measurements of q[0] into c[0] and q[1] into c[1].
Each measurement writes to the corresponding classical bit. Open full SVG.

Barriers align authored layers. With show_barriers: false each boundary leaves a small gap and no marker:

Two aligned layers of Ry and Rz rotations followed by controlled X ladders on four qubits, separated by a gap.
The extra gap separates two layers, each with aligned Ry/Rz columns followed by a CX ladder. Open full SVG.

Use prism_q::circuit::expand_qft_blocks(&circuit).to_svg(&opts) to draw the gates inside a QFT block:

Four-qubit QFT expanded into Hadamards, controlled phase rotations, and final swaps.
Controlled phases decrease with qubit separation; the final swaps reverse qubit order. Open full SVG.

Clifford+T Simulation

Circuits that mix Clifford gates with a modest number of T gates sit between the polynomial stabilizer regime and the exponential statevector regime. Four engines cover them.

Which engine?

  • Exact shots or probabilities with T gates that reach at most 20 qubits, or shots from a register that splits into parts of at most 26: stabilizer rank (run_stabilizer_rank, run_stabilizer_rank_shots).
  • Many T gates, marginals only: stochastic Pauli propagation, SPP (run_spp).
  • Moderate T count, exact or bounded-error expectation values: deterministic Pauli propagation, SPD (run_spd).
  • Expectation values under a noise model: Pauli path (BackendKind::PauliPath).

Auto reaches three of them ahead of the dispatch tree:

  • Terminal shots go to stabilizer rank on a circuit of 16 qubits or more when the Clifford register (the form below) splits into parts the sampler takes and costs less than the dense run. The T count sets no limit of its own: 24 T gates on a 14-qubit register at 26 qubits take about 1 ms for 1024 shots against 1.5 s on the statevector. Past the statevector cap, a lowered one included, a register that splits takes the shots ahead of the MPS; one that does not goes to the dispatch tree. Shots with a mid-circuit measurement, a classical guard or a reset move their measurements to the end when they can and take the register under the same tests, the dense side priced as one run per outcome history the shots can reach. Past the statevector cap, a circuit whose measurements stay in place takes the weighted branches below up to 6 T gates; the rest go to the dispatch tree.
  • Marginals on a unitary Clifford+T circuit of 12 qubits or more go to SPD.
  • Expectation values on a Clifford circuit go to SPD.

SPP and Pauli path run only when selected. Routes the tree does not show has the exact conditions.

Accepted gate forms

All four engines take Clifford gates, T, Tdg, Rz, P and Rzz as they are. SPD and Pauli path branch on Rx, Ry and PauliRot too, and SPP on PauliRot. SPP lowers Rx and Ry, and stabilizer rank lowers all three, to Clifford conjugation around one Rz. A Fused matrix (the parser's u, u3, u2, r, gpi and gpi2) lowers to the named gate or Rz it equals up to a global phase, or else to its Rz-Ry-Rz Euler triple. A cu lowers when its target is diagonal or a Pauli up to phase (cy, cp, crz, cs) and is rejected otherwise, as are ccx and the other multi-controlled forms. The Pauli engines take any rotation angle. Stabilizer rank needs every lowered Z rotation on the pi/4 grid; Rz(pi/4), P(pi/4) and their odd multiples count as one T each, so is_clifford_plus_t and the automatic route treat them like T.

Stabilizer rank (src/sim/stabilizer_rank.rs)

Exact probability output is capped because it returns a dense vector of 2^n entries. Shot sampling is not bound by the statevector cap and takes one of two forms.

For terminal measurements of a unitary circuit, the state is a Clifford tableau C applied to |0> on most qubits and a dense register φ on the rest. A T gate on qubit q rotates about P = C† Z_q C. When P flips a qubit still in |0>, CX gates controlled on that qubit clear P from the other |0> qubits, fold into C, and move the qubit into the register, so the register grows by at most one qubit per T gate and holds at most 2^t amplitudes. Sampling reduces each measured C† Z_q C once: an outcome that flips a |0> qubit is a fair coin, and the rest are read from tables of register marginals. Shots fold each new register qubit's rotation into C as well, so it joins as a one-qubit state, and split the register into parts: the qubits that a T rotation over earlier register qubits links, joined where the measured rows anticommute part by part. Each part up to 26 qubits draws from its own table, small tables packed into one, and a wider part, or one past 24 whose cut prices lower, is cut in two sides of at most 20 that no rotation crosses, each shot correcting the draw over the row pairs that anticommute across the cut, at most 12. A cut with E such pairs costs each shot (E + 3) 2^E amplitude units, which Simulate::plan reports as units_per_shot before any table is built. A register that does not split that way, or holds more than 64 qubits, returns BackendUnsupported, and Auto plans the split from the tableau alone and sends such a circuit to the dispatch tree instead.

A circuit with mid-circuit measurements, guards or resets first moves its measurements to the end: a reset hands the qubit's later gates to a fresh qubit in |0>, a measured qubit used again copies its record onto a fresh qubit with a CX, and a guarded Pauli becomes the same Pauli controlled by the measured qubit. The rewritten circuit is unitary with terminal measurements and the same T count, so the register above samples it. A guard on a gate other than a Pauli, a guard comparing two measured bits, or a guarded body holding a measurement keeps the measurements in place.

Those circuits carry coherent weighted MPS branches instead. Clifford gates mutate each branch, T and Tdg split branches, and a measurement computes outcome probabilities from the weighted ensemble before projecting every branch onto the sampled outcome. Branch count, MPS bond growth and measurement count set how far this form scales; past 20 T gates, guarded ones included, the branch count would pass its cap and the run returns BackendUnsupported before the first shot.

The dense probability path reads its probabilities off the same Clifford register the terminal shots use. Branches of T = alpha*I + beta*Z that land on one basis state of the register merge into one coefficient, so a circuit holds 2^k terms, where k is the number of qubits the T gates reach and k <= min(n, t). The T count sets no limit. A register wider than 20 qubits falls back to one branch per T choice, capped at 2^20.

FunctionUse
run_stabilizer_rankExact probabilities (register width ≤ 20, n ≤ 25)
run_stabilizer_rank_approxApproximate under a coefficient budget (register width ≤ 20, n ≤ 25)
run_stabilizer_rank_shotsShot sampling past the statevector cap (register parts of at most 26 qubits, up to 64 in all)
stabilizer_overlap_sqInner product between stabilizer states

run_stabilizer_rank_approx runs the same register and, after each T, zeroes all but the budget's largest coefficients, ties kept in index order. The coefficients are orthonormal, so each cut drops a known norm d_j. The result reports:

  • discarded_weight: D = sum d_j. The exact state lies within D of the kept one.
  • kept_norm_sqr: N^2 = 1 - sum d_j^2, the kept norm before the probabilities are renormalized.
  • fidelity_bound(): F >= ((1 + N^2 - D^2) / (2N))^2, never below 1 - D^2. The returned distribution differs from the exact one by at most 2 sqrt(1 - F) in summed absolute difference. A single cut gives F = N^2 exactly.

On the 10-qubit benchmark circuits at budget 128 the floor is 0.880 at 16 T and 0.744 at 20 T. A register wider than 20 qubits is refused. Auto never selects this function, nor the exact expansion for probabilities: while the register fits, the exact route answers without error, and past it a statevector also fits.

Stochastic Pauli Propagation (src/sim/unified_pauli/spp.rs)

Backward-propagates measurement observables as Pauli strings. Clifford gates conjugate in O(1), and T gates branch stochastically into two weighted Pauli paths. A path costs O(d×n/64) whatever the T-count. Marginal probabilities come from Monte Carlo estimation.

#![allow(unused)]
fn main() {
use prism_q::{circuits::clifford_t_circuit, run_spp};
let circuit = clifford_t_circuit(8, 10, 0.1, 42);
let (num_samples, seed) = (1000, 42);
let result = run_spp(&circuit, num_samples, seed)?; // SppResult
Ok::<(), prism_q::PrismError>(())
}

Deterministic Sparse Pauli Dynamics (src/sim/unified_pauli/spd.rs)

Backward-propagates a weighted sum of Pauli strings stored in a HashMap. T gates branch X and Y terms deterministically, and identical strings merge. The result is exact for small T-counts and approximate with bounded error for larger ones.

#![allow(unused)]
fn main() {
use prism_q::{SpdTruncation, circuits::clifford_t_circuit, run_spd, run_spd_with};
let circuit = clifford_t_circuit(8, 10, 0.1, 42);
let (epsilon, max_terms) = (1e-8, 1 << 16);
let truncation = SpdTruncation::Budget { max_terms };
let result = run_spd(&circuit, epsilon, max_terms)?; // SpdResult
let result = run_spd_with(&circuit, &truncation)?;   // SpdResult, any policy
Ok::<(), prism_q::PrismError>(())
}

The builder takes both truncation policies too:

#![allow(unused)]
fn main() {
use prism_q::{BackendKind, PauliTerm, SpdTruncation, simulate};
use prism_q::circuits::clifford_t_circuit;
let circuit = clifford_t_circuit(8, 10, 0.1, 42);
let observables = vec![vec![PauliTerm::z(0)], vec![PauliTerm::z(0), PauliTerm::z(1)]];
let values = simulate(&circuit)
    .seed(42)
    .backend(BackendKind::DeterministicPauli {
        truncation: SpdTruncation::Budget { max_terms: 1 << 16 },
    })
    .expectation_values(&observables)?;
Ok::<(), prism_q::PrismError>(())
}

SpdTruncation::Threshold { epsilon, max_terms } drops terms below epsilon once the sum passes max_terms, and max_terms = 0 disables pruning for an exact run. With an epsilon too small to hold the growth, the sum climbs to the engine's internal ceiling and the run errors there rather than returning an over-truncated value.

SpdTruncation::Budget { max_terms } instead drops exactly enough of the smallest terms to return to the budget. It has no threshold to guess and never reaches the ceiling, so it suits runs where the term count is the binding constraint. A budget of zero is rejected.

Both report the discarded coefficient magnitude on the engine result, which bounds the error as |error| <= sum |discarded|. It is not a fidelity bound.

observable_expectation propagates a weighted PauliObservable as one sum, with each term's weight on its coefficient. max_terms caps that whole sum rather than each term, epsilon compares weighted coefficients (so a term weighted below epsilon can drop whole), and the bound applies to the weighted value. The same holds on PauliPath. A merged sum past the internal ceiling falls back to one propagation per term.

Pauli path propagation under noise (src/sim/unified_pauli/pauli_path.rs)

The same weighted Pauli sum, carried through a noise model. Select BackendKind::PauliPath { epsilon, max_terms } and attach a noise model; the engine answers expectation_values and observable_expectation and nothing else.

#![allow(unused)]
fn main() {
use prism_q::{BackendKind, NoiseModel, PauliTerm, simulate};
use prism_q::circuits::clifford_t_circuit;
let circuit = clifford_t_circuit(8, 10, 0.1, 42);
let observables = vec![vec![PauliTerm::z(0)], vec![PauliTerm::z(0), PauliTerm::z(1)]];
let noise = NoiseModel::uniform_depolarizing(&circuit, 0.01);
let values = simulate(&circuit)
    .seed(42)
    .backend(BackendKind::PauliPath { epsilon: 1e-8, max_terms: 1 << 16 })
    .noise(&noise)
    .expectation_values(&observables)?;
Ok::<(), prism_q::PrismError>(())
}

Only the truncation is approximate. Each channel applies as its exact adjoint on the Pauli basis, not as a twirl, so depolarizing, dephasing, thermal relaxation and amplitude damping reproduce the density matrix to machine precision at max_terms = 0. Amplitude damping is not unital, and the identity term its adjoint produces from Z is carried. A channel with no Pauli-basis form (custom Kraus, two-qubit Kraus, readout error) is rejected rather than approximated.

With a budget set, terms whose magnitude falls below epsilon are dropped once the sum exceeds the budget, and the total dropped magnitude bounds the error in the returned value. The bound is a worst case, and it holds because every remaining operation is a contraction in the Pauli 1-norm.

The term count, not the qubit count, decides whether the engine is usable. Every non-Clifford rotation in the observable's backward light cone can double the sum, and every channel shrinks it. Where noise wins, a circuit stays cheap at widths no dense representation reaches. Where it does not, the run hits the budget and reports a large discarded mass: use the density matrix or trajectory averaging instead.

The observable's weight moves that count more than width or depth, since the light cone opens from every letter it starts with. On a two-layer hardware-efficient ansatz under 1% depolarizing, Z on one qubit stays at 11 terms at 20 qubits or 100; Z on two adjacent qubits fills a 16384-term budget by 30 qubits; a Z on every qubit fills it at 20 and returns a discarded mass larger than the observable's own norm, which flags the answer as unusable instead of returning a wrong one quietly. Check the reported discarded mass against the precision needed before trusting a truncated run.

clifford_t_circuit builds random Clifford+T test circuits.

Hamiltonian Evolution

A Hamiltonian is a PauliObservable, H = sum c_j P_j, the same type the expectation terminals read. Evolving under it appends Pauli rotations to a circuit, so the result runs on any backend and fuses like any other gate.

Single rotations

Circuit::add_pauli_rotation(theta, factors) and CircuitBuilder::pauli_rotation append exp(-i theta P / 2) for one Pauli string P. A weight-1 string lands as rx, ry or rz, ZZ as rzz, and any other string as the native PauliRot, which the statevector applies in one pass and fusion batches at 16 qubits and above.

Trotter product formulas

Circuit::add_trotter and CircuitBuilder::trotter append a product-formula approximation of exp(-i H t): steps steps of length dt = t / steps, each term as the rotation exp(-i c_j P_j dt). TrotterOrder::First is the Lie-Trotter formula, Second the symmetric one, and Suzuki(k) the recursive formula of order 2k at 5^(k - 1) second-order substeps per step.

Identity terms are dropped, since they contribute only a global phase, and so are zero coefficients. Consecutive rotations of one string merge, so a second-order step over m terms emits 2m - 1 rotations and adjacent steps share their boundary rotation.

#![allow(unused)]
fn main() {
use prism_q::{CircuitBuilder, PauliObservable, PauliTerm, TrotterOrder, simulate};
let ising = PauliObservable::from_terms([
    (1.0, vec![PauliTerm::z(0), PauliTerm::z(1)]),
    (0.5, vec![PauliTerm::x(0)]),
    (0.5, vec![PauliTerm::x(1)]),
])?;
let evolved = CircuitBuilder::new(2)
    .h(0)
    .h(1)
    .trotter(&ising, 1.0, 8, TrotterOrder::Second)
    .build();
let energy = simulate(&evolved).seed(42).observable_expectation(&ising)?.mean;
assert!((energy - 1.0).abs() < 1e-2); // <H> is conserved up to the Trotter error
Ok::<(), prism_q::PrismError>(())
}

Wider Pauli strings export to OpenQASM as the r spelling PRISM-Q reads back (see Supported gates); run circuit::expand_pauli_rotations first for output another toolchain reads.

Noise Models

A NoiseModel attaches channels to the instructions of one circuit. The trajectory backends sample it shot by shot, the density matrix evolves it exactly, and on a Clifford circuit with Pauli noise the compiled samplers draw it with no state per shot. Noise internals covers how each route runs a model, the Noisy Simulation tutorial walks through one, and Noise and Shots is the Python version of this page.

Attaching a model

#![allow(unused)]
fn main() {
use prism_q::{simulate, BackendKind, NoiseModel};

let circuit = prism_q::CircuitBuilder::new_with_classical(3, 3).h(0).cx(0, 1).cx(1, 2).measure_all().build();
let noise = NoiseModel::uniform_depolarizing(&circuit, 0.001);
let result = simulate(&circuit)
    .backend(BackendKind::Statevector)
    .noise(&noise)
    .seed(42)
    .shots(1024)
    .unwrap();
}

A model holds a list of NoiseEvent { channel, qubits } per instruction slot, so it is sized to the circuit it was built from, and attaching it to another circuit is an error. Channels are Pauli, Depolarizing, AmplitudeDamping, PhaseDamping, ThermalRelaxation, TwoQubitDepolarizing, Custom and Custom2q Kraus sets, the leakage channels below, and QuasiStatic. Readout error sits beside the events and flips reported bits after sampling. On a Clifford circuit the noisy compiled sampler propagates each event's sensitivity row once and XORs the fired rows into every shot.

Rules

NoiseBuilder places channels by rule and checks the result at build(&circuit). GateFilter::all() matches every gate; named, arity, on_qubits and on_targets narrow it. on_qubits is an unordered set, while on_targets([0, 1]) matches the ordered target list and so skips cx(1, 0).

#![allow(unused)]
fn main() {
use prism_q::{GateFilter, NoiseBuilder, NoiseChannel};

let circuit = prism_q::CircuitBuilder::new_with_classical(3, 3).h(0).cx(0, 1).cx(1, 2).measure_all().build();
let noise = NoiseBuilder::new()
    .after_gates(GateFilter::all().arity(1), NoiseChannel::Depolarizing { p: 1e-3 })
    .after_gates_joint(
        GateFilter::all().named("cx"),
        NoiseChannel::TwoQubitDepolarizing { p: 1e-2 },
    )
    .crosstalk(
        GateFilter::all().named("cx"),
        [(0, 1), (1, 2)],
        NoiseChannel::Depolarizing { p: 1e-4 },
    )
    .uniform_readout_error(0.01, 0.02)
    .build(&circuit)?;
Ok::<(), prism_q::PrismError>(())
}
RuleEffect
after_gates(filter, channel)One single-qubit event per matching target
after_gates_joint(filter, channel)One event on the whole target list when its arity matches the channel
crosstalk(filter, coupling, channel)Spectator noise along undirected coupling edges; a two-qubit channel takes the gate target first
over_rotation(filter, relative)An extra relative * theta rotation after rx, ry, rz or p
on_idle_qubits(channel)One event per idle qubit per greedy circuit layer
after_resets(channel)One event on each reset qubit
before_measurements(channel)Damage to the measured state, which feedforward also reads
readout_error(bit, p01, p10)Readout rates for one classical bit, overriding uniform_readout_error; the bit flips when a measurement writes it, so a condition reads the noisy value

Events in one instruction slot follow rule order. Idle events attach to the highest-indexed instruction of their layer and pre-measurement events to the instruction before the measurement, so a measurement at instruction zero needs a barrier ahead of it. Gate rules skip conditional instructions. Build against the circuit as written, since fusion renames gates.

Device calibration

A DeviceCalibration holds what a calibration page reports: t1, t2 and readout rates per qubit, a duration and depolarizing error per gate family, and optional two-qubit entries per pair. to_noise_model(&circuit) lowers it onto a circuit. After every gate, each target gets a ThermalRelaxation channel with its own t1 and t2 over the family's duration, and a nonzero family error adds Depolarizing on a one-qubit target or TwoQubitDepolarizing on the pair. Each measurement takes its classical bit's readout error from the measured qubit. Gates on more than two qubits are rejected; decompose them first.

The text form has one record per line, key=value fields in any order, and # comments:

RecordFieldsNotes
qubit <n> ...t1, t2 in seconds; p01, p10 (default 0)one per qubit, indices 0..N in any order
gate1q ...time in seconds, errorexactly once
gate2q ...time, errorexactly once
gate2q <a> <b> ...time, erroroptional; replaces the family on that pair in either order

Values are checked on read (t2 <= 2 t1, probabilities in [0, 1], durations positive), and an error names the line and the field.

#![allow(unused)]
fn main() {
use prism_q::{simulate, BackendKind, DeviceCalibration};

let circuit = prism_q::CircuitBuilder::new_with_classical(2, 2).h(0).cx(0, 1).measure_all().build();
let calibration = DeviceCalibration::parse(
    "qubit 0 t1=120e-6 t2=80e-6 p01=0.02 p10=0.03
     qubit 1 t1=95e-6 t2=110e-6 p01=0.01 p10=0.02
     gate1q time=35e-9 error=3e-4
     gate2q time=300e-9 error=8e-3
     gate2q 0 1 time=250e-9 error=5e-3",
)
.unwrap();
let noise = calibration.to_noise_model(&circuit).unwrap();
let result = simulate(&circuit)
    .backend(BackendKind::DensityMatrix)
    .noise(&noise)
    .seed(42)
    .shots(1024)
    .unwrap();
}

prism_q::sim::calibration::presets has superconducting_transmon(n), trapped_ion(n) and neutral_atom(n): illustrative magnitudes for a technology class, the same on every qubit. A specific device needs the text form.

to_noise_model charges decoherence only to the qubits a gate touches. to_scheduled_noise_model(&circuit) also decays the qubits that wait, using the table's gate durations. The circuit is laid out as soon as possible in the greedy layers Circuit::depth counts, each layer as long as its longest gate, and at the end of each layer every qubit relaxes with its own t1 and t2 over the part of the layer it spent idle. gate_times() returns those durations as a GateTimes for a builder.

Leakage

A leakage channel moves a qubit out of the computational subspace. The trajectory engines carry it as a flag per qubit:

ChannelEffect
Leakage { p }An unleaked qubit leaks with probability p
Seepage { p }A leaked qubit returns with probability p, to a uniformly random basis state
LeakageTransport { p }Two-qubit: when exactly one qubit is leaked, the other leaks with probability p

Gates on a leaked qubit do not act, and a gate pairing it with unleaked qubits applies a uniformly random Pauli to each of those instead. Measuring a leaked qubit reports 1, a reset clears the flag, and every other channel skips it. ShotsResult::leaked holds, per shot, the qubits that leaked at any point: an erasure herald for a decoder.

#![allow(unused)]
fn main() {
use prism_q::{simulate, BackendKind, GateFilter, NoiseBuilder, NoiseChannel};

let circuit = prism_q::CircuitBuilder::new_with_classical(3, 3).h(0).cx(0, 1).cx(1, 2).measure_all().build();
let noise = NoiseBuilder::new()
    .after_gates_joint(GateFilter::all().arity(2), NoiseChannel::LeakageTransport { p: 0.1 })
    .after_gates(GateFilter::all(), NoiseChannel::Leakage { p: 1e-3 })
    .after_gates(GateFilter::all(), NoiseChannel::Seepage { p: 0.05 })
    .build(&circuit)
    .unwrap();
let result = simulate(&circuit)
    .backend(BackendKind::Statevector)
    .noise(&noise)
    .seed(42)
    .shots(1024)
    .unwrap();
let heralds = result.leaked.as_ref().unwrap();
assert_eq!(heralds[0].len(), 3);
}

A transport event reads the flags when it fires, so declare it before the leakage rule on the same gates to spread only the leakage the gate itself saw. The density matrix rejects leakage, since a mixture evolved event by event has no flag to carry. QEC programs model leakage as heralded erasure instead; see QEC.

Correlated and time-dependent noise

NoiseBuilder::schedule(GateTimes) times the circuit for the rules that act over elapsed time. GateTimes::new(one_qubit, two_qubit) takes family durations in seconds; with_gate(name, t) overrides one gate (an "id" entry turns identities into delays), with_pair(a, b, t) one qubit pair, and with_measure and with_reset the instructions that are not gates.

  • scheduled_idle(coherence) relaxes each qubit from its (t1, t2) over the idle part of every layer. It replaces on_idle_qubits; declaring both is an error.
  • quasi_static_detuning(drift) draws one frequency offset per qubit per shot, in radians per second, and turns each qubit about Z by its offset times every layer's duration. A qubit left for time t then dephases on average as exp(-(sigma t)^2 / 2).
  • over_rotation_drift(filter, sigma) draws one fractional angle error per shot, shared by every matching rx, ry, rz or p gate; over_rotation_drift_per_qubit(filter, drift) draws one per qubit.

A DriftDistribution is a zero-mean Gaussian over per-qubit offsets: independent(sigmas), from_t2_star(t2_star) for widths sqrt(2) / t2_star, a full from_covariance(matrix), or with_neighbour_correlation(coupling, rho) to correlate the qubits of each coupling edge. Each shot draws standard normals and correlates them through the covariance's Cholesky factor. build rejects a covariance that is not positive semidefinite.

#![allow(unused)]
fn main() {
use prism_q::{DriftDistribution, GateFilter, GateTimes, NoiseBuilder};

let circuit = prism_q::CircuitBuilder::new_with_classical(3, 3).rx(0.4, 0).cx(0, 1).cx(1, 2).measure_all().build();
let detuning = DriftDistribution::from_t2_star([40e-6, 55e-6, 30e-6])
    .with_neighbour_correlation([(0, 1), (1, 2)], 0.3);
let noise = NoiseBuilder::new()
    .schedule(GateTimes::new(35e-9, 300e-9).with_measure(1e-6))
    .scheduled_idle([(100e-6, 80e-6); 3])
    .quasi_static_detuning(detuning)
    .over_rotation_drift(GateFilter::all().named("rx"), 0.01)
    .build(&circuit)
    .unwrap();
}

The drift rules lower onto NoiseChannel::QuasiStatic events, which make each shot a different unitary, so they run on the per-shot trajectory engines only. A model without them keeps the shared evolution paths.

Exact noisy marginals

On a Clifford circuit with single-qubit Pauli noise, noisy_marginals_analytical returns the probability that each classical bit reads 1, in closed form from the parity matrix and the noise rates, with no sampling and no rank limit. Readout error is part of that closed form: a reported 1 is a measured 1 that did not flip or a measured 0 that did. Any other channel, and any channel naming two qubits, is rejected.

ErrorChainComplex::build exposes the GF(2) chain complex behind it, over noise locations, measurements and stabilizers. homology_dim counts the independent logical error classes, boundary_dim the errors that leave the state unchanged and that no final measurement detects, and noisy_marginals(noiseless) maps noiseless record marginals to noisy ones.

#![allow(unused)]
fn main() {
use prism_q::{CircuitBuilder, ErrorChainComplex, NoiseModel, noisy_marginals_analytical};

let ghz = CircuitBuilder::new_with_classical(3, 3).h(0).cx(0, 1).cx(1, 2).measure_all().build();
let noise = NoiseModel::uniform_depolarizing(&ghz, 0.01);
let marginals = noisy_marginals_analytical(&ghz, &noise, 42)?;
assert!(marginals.iter().all(|p| (p - 0.5).abs() < 1e-9));
let complex = ErrorChainComplex::build(&ghz, &noise, 42)?;
let logical_classes = complex.homology_dim();
Ok::<(), prism_q::PrismError>(())
}

Sampled noisy expectation values

Past the density matrix memory ceiling, Simulate::expectation_values_sampled estimates Tr(rho P) by averaging Backend::pauli_expectations across noise trajectories on any pure state backend (Statevector, StatevectorGpu, Mps, Factored, Sparse, TensorNetwork, ProductState, and Clifford tableaux under Pauli noise). It returns sample means and standard errors for each observable, rejects require_exact() and readout error, and leaves exact mixture evaluation to BackendKind::DensityMatrix with expectation_values_reported.

Gates compiled from pulses

The unstable-pulse feature adds prism_q::pulse, which integrates a pulse schedule on a model of one to three transmons once and hands the result to the gate level. It sits outside the stability promise: its items may change in any release.

cargo add prism-q --features unstable-pulse
use prism_q::pulse::{compile, Device, Envelope, Schedule, Transmon};
use prism_q::{Circuit, Gate};

let device = Device::new([Transmon { frequency: 5e9, anharmonicity: -300e6, levels: 3 }])
    .relaxation(0, 50e-6, 30e-6);
let mut schedule = Schedule::new(1e-9);
let drag = Envelope::Drag { amp: 50e6, sigma: 5e-9, beta: 1.0 / (2.0 * std::f64::consts::PI * 300e6) };
schedule.play(0, 0.0, 20e-9, drag);
let gate = compile(&device, &schedule, 16)?;
let mut circuit = Circuit::new(1, 0);
circuit.add_unitary(gate.unitary(), &[0])?;
let residual = gate.error_after(&Gate::X);
let pauli = gate.pauli_rates(&Gate::X);

Frequencies and amplitudes are in Hz and times in seconds. Calling Device::relaxation adds T1 amplitude damping and T2 pure dephasing to a site, switching compile to a Lindblad channel integrator. The outputs:

  • unitary(): the nearest unitary to the propagator restricted to |0> and |1> on every site, packed for Gate::unitary and Circuit::add_unitary with site 0 on the first target.
  • leakage(): per site, the probability that the site leaves {|0>, |1>} from |0> and from |1> while every other site starts in |0>. It misses leakage that needs an excited neighbour, such as |11> to |02> on a coupled pair.
  • leakage_from(levels): the total probability of ending outside the computational subspace from one device basis state, levels giving each site's level. For p in the Leakage channel above, take the mean of leakage_from over the computational inputs. From an input with a site at |2> or above, one minus leakage_from is the probability of returning, a value for Seepage.
  • error_after(ideal): the residual channel to attach after ideal with a NoiseBuilder, as a Custom or Kraus2q Kraus set. Without relaxation this holds a single coherent operator; with relaxation it holds the minimal Kraus set extracted from the computational Choi matrix.
  • pauli_rates(ideal): the Pauli twirl of error_after(ideal), returning [px, py, pz] for one site or 15 rates in QecNoise::PauliChannel2 order for two sites.

evolve returns the populations after each sample period instead, for Rabi or leakage curves.

Quantum Error Correction

Two routes sample error correction experiments without a dense statevector per shot. A Clifford Circuit with reset reuse compiles into a detector sampler, and the native QEC program IR adds detectors, logical observables, postselection and noise annotations as operations. Noise on ordinary circuits is on Noise Models. The QEC memory tutorial runs a decoded experiment, and QEC from Python covers the Python surface.

Detector sampling

compile_detector_sampler(&circuit, detector_rows, observable_rows, seed) compiles a Clifford circuit with measurement and reset reuse, the shape of repeated syndrome extraction, into a packed sampler. Each detector and observable is a row of measurement record indices, in circuit measurement order, and samples as the parity of those records. Reset reuse becomes fresh qubit aliases, so no shot replays the tableau.

#![allow(unused)]
fn main() {
use prism_q::{CircuitBuilder, compile_detector_sampler};

let mut builder = CircuitBuilder::new_with_classical(3, 4);
builder.h(0).cx(0, 2);
for round in 0..2 {
    builder.cx(0, 1).cx(2, 1).measure(1, round).reset(1);
}
let circuit = builder.measure(0, 2).measure(2, 3).build();

let mut sampler =
    compile_detector_sampler(&circuit, vec![vec![0], vec![0, 1]], vec![vec![2, 3]], 42)?;
let batch = sampler.sample_packed(1000)?;
assert!((0..1000).all(|shot| !batch.detectors.get_bit(shot, 1)));
assert!((0..1000).all(|shot| !batch.observables.get_bit(shot, 0)));
Ok::<(), prism_q::PrismError>(())
}

Qubit 1 checks the ZZ parity of qubits 0 and 2 twice. The data qubits read random but equal values, so the observable over both data records never fires, and neither does the detector comparing the two rounds. sample_packed draws the measurements once and derives both parity sets from the same shots; sample_detector_counts streams a histogram.

Native QEC programs

A QecProgram holds detectors, logical observables, postselection and Pauli noise annotations as operations of their own, where a Circuit has none. Its text format follows the Stim circuit language for the instructions listed below; LEAK, SEEP, LEAK_TRANSPORT and EXP_VAL are additions, and any other instruction is a parse error.

#![allow(unused)]
fn main() {
use prism_q::{parse_qec_program, run_qec_program};

let qec_text = "
    R 0 1 2 3 4
    X_ERROR(0.01) 0 2 4
    CX 0 1 2 1 2 3 4 3
    MR 1 3
    DETECTOR rec[-2]
    DETECTOR rec[-1]
    M 0 2 4
    OBSERVABLE_INCLUDE(0) rec[-1]
";
let program = parse_qec_program(qec_text).unwrap();
let result = run_qec_program(&program).unwrap();
}

run_qec_program lowers Clifford programs into the packed compiled sampler; run_qec_program_reference is the per-shot statevector oracle for validating small programs. program.to_text() writes the same text format back, so a program built in code can be saved and parsed again.

What QEC programs support

Clifford gates (including the SQRT_*, C_XYZ / C_ZYX, CY, SWAP, ISWAP, CXSWAP, and SWAPCX spellings), basis resets and measurements, MPP and MXX / MYY / MZZ Pauli product measurements, MPAD constant records, detectors, observables, postselection, X_ERROR / Y_ERROR / Z_ERROR / DEPOLARIZE1 / DEPOLARIZE2 / PAULI_CHANNEL_1 / PAULI_CHANNEL_2 noise, E / CORRELATED_ERROR chains with ELSE_CORRELATED_ERROR, HERALDED_ERASE, LEAK / SEEP / LEAK_TRANSPORT leakage, and terminal EXP_VAL final-state expectation estimates. A noiseless EXP_VAL runs under a QecTStrategy: Auto tries exact light-cone SPD, then CAMPS, then a tensor network scalar, and run_qec_program_with_strategy picks Spd, Camps or Reference directly. The packed runner still samples detector records. A noisy EXP_VAL is computed exactly on the density matrix when it fits, and falls to the per-shot reference runner when the program carries measurement records or postselection or exceeds the density matrix cap. The packed sampling path rejects non-Clifford gates. QEC programs has the full grammar, the runner routing, the V1 reset requirement, and the EXP_VAL placement rules.

Reading Stim circuit files

parse_stim_circuit (or QecProgram::from_stim, QecProgram.from_stim in Python) reads .stim circuit text, such as the surface, repetition and color code memory circuits other QEC tooling generates, into the same program:

#![allow(unused)]
fn main() {
use prism_q::{parse_stim_circuit, run_qec_program};

let program = parse_stim_circuit("
    R 0 1 2
    X_ERROR(0.01) 0 1 2
    CX 0 1 2 1
    MR 1
    DETECTOR(1, 0) rec[-1]
    M !0 2
    OBSERVABLE_INCLUDE(0) rec[-2]
").unwrap();
let result = run_qec_program(&program).unwrap();
}

It accepts the instruction set above apart from the native additions (T, T_DAG, LEAK, SEEP, LEAK_TRANSPORT, POSTSELECT, EXP_VAL, RECORD_FLIP), and adds four Stim behaviours the native parser rejects, ignores or reads differently:

  • inverted measurement targets (M !0, MR !0, MXX !0 1, MPP !X0*Z1), lowered as a Pauli on either side of the measurement so only the record flips; the second Pauli waits for the qubit's next use and is dropped at a reset, so a qubit measured once stays on the compiled sampler;
  • record-controlled Paulis (CX rec[-1] 2, CY rec[-1] 2, CZ rec[-1] 2), lowered to feed-forward corrections;
  • SHIFT_COORDS, which offsets later DETECTOR coordinates;
  • measurement error on M(p), MR(p), MPP(p), MXX(p) / MYY(p) / MZZ(p), MPAD(p) and the X and Y variants, which flips each record the line produces independently with probability p and leaves the qubits alone, so M(0.2) 0 then M 0 gives a second record that is always 0, and MPP(0.1) Z0*Z1 Z1*Z2 flips its two records independently. Native text reads M(p) as a Pauli flip before the measurement, which differs only when the qubit is measured again without a reset, and takes no argument on MPP, the pair measurements or MPAD.

Any other instruction and sweep[k] targets are parse errors naming the line. A record flip lowers to QecOp::RecordFlip after the op that produced the record, which every runner and detector_error_model honour; to_text writes it as the native RECORD_FLIP(p) line after the measurement.

Detector reference

A detector reports 1 when its records disagree with the noiseless reference run of the program, so a noiseless program never fires and a detector event always means noise flipped it. Observables and logical error counts follow the same convention. The reference run takes 0 for every random measurement outcome, including the hidden collapse of a reset. A detector whose noiseless value is random is still XORed with that run's value: it fires in about half the shots, and detector_error_model rejects the program. Postselection and heralds read the raw records, and programs with non-Clifford gates report raw parities.

QecOptions::detector_reference selects the convention. QecDetectorReference::Raw (detector_reference="raw" in Python) reports the plain parity of each detector's records instead:

#![allow(unused)]
fn main() {
use prism_q::{QecDetectorReference, QecOptions, parse_qec_program, run_qec_program};

let mut program = parse_qec_program(
    "R 0
     X 0
     M 0
     DETECTOR rec[-1]
     OBSERVABLE_INCLUDE(0) rec[-1]",
)?;
assert_eq!(run_qec_program(&program)?.logical_error_rates(), vec![0.0]);

program.set_options(QecOptions {
    detector_reference: QecDetectorReference::Raw,
    ..QecOptions::default()
});
assert_eq!(run_qec_program(&program)?.logical_error_rates(), vec![1.0]);
Ok::<(), prism_q::PrismError>(())
}

Compiling once for repeated sampling

run_qec_program compiles the program on every call. QecProgram::compile_sampler compiles once and returns a QecCompiledSampler, so many small batches or a sweep over seeds pay for one compile:

#![allow(unused)]
fn main() {
use prism_q::parse_qec_program;

let program = parse_qec_program(
    "R 0 1 2
     X_ERROR(0.01) 0 2
     CX 0 1 2 1
     M 0 1 2
     DETECTOR rec[-2]
     OBSERVABLE_INCLUDE(0) rec[-1]",
)?;
let mut sampler = program.compile_sampler()?;
let first = sampler.sample(100, None)?;
let seeded = sampler.sample(100, Some(7))?;
Ok::<(), prism_q::PrismError>(())
}

sample(shots, Some(seed)) draws exactly the shots run_qec_program draws with that seed in the program's options. sample(shots, None) continues one stream: the first call uses the program's seed and each later call derives a fresh seed from the previous one, so two samplers compiled from the same program replay the same sequence. The sampler is Send and sample takes &mut self, so share one behind a lock or compile one per thread. Programs that need the per-shot or analytical runners (EXP_VAL, non-Clifford gates) return an error from compile_sampler.

Leakage as heralded erasure

LEAK(p) q ... leaks each target with probability p, SEEP(p) q ... returns each leaked target to a random basis state with probability p, and LEAK_TRANSPORT(p) a b ... spreads leakage across each pair at rate p. run_qec_program samples them as erasures: a leaking qubit gets a uniformly random Pauli frame, a two-qubit gate meeting a leaked qubit fully depolarizes both its qubits, other noise annotations naming a leaked qubit are skipped, and the leaked qubit's own measurement reports 1. On a Clifford program this matches the trajectory leakage model in Noise Models in distribution.

Each LEAK target adds one column to QecSampleResult::heralds, set when that qubit is leaked just after the annotation; LEAK(0) reads the flags without changing them. An MPP over a leaked qubit reports a random parity. The detector error model and the reference runner have no leak flag and reject these programs, and the memory experiment generators below emit no leakage.

#![allow(unused)]
fn main() {
use prism_q::{QecProgram, run_qec_program};

let program = QecProgram::from_text(
    "R 0 1 2
     CX 0 1
     LEAK(0.01) 0 1
     CX 1 2
     LEAK_TRANSPORT(0.1) 1 2
     M 0 1 2
     DETECTOR rec[-1] rec[-2]",
)?;
let result = run_qec_program(&program)?;
let heralds = result.heralds.as_ref().unwrap();
assert_eq!(heralds.num_measurements(), 2);
Ok::<(), prism_q::PrismError>(())
}

Memory experiments

QecProgram::repetition_memory, surface_memory and color_memory build the standard memory experiments with circuit-level noise from a QecCircuitNoise: depolarization after every Clifford gate, a flip before every measurement and after every reset, and depolarization of the data at the start of each round. Each program carries detectors with coordinates and logical observable 0:

#![allow(unused)]
fn main() {
use prism_q::{QecBasis, QecCircuitNoise, QecProgram, UnionFindDecoder, run_qec_program};

let noise = QecCircuitNoise::uniform(0.002);
let program = QecProgram::surface_memory(3, 3, QecBasis::Z, &noise)?;
let model = program.detector_error_model()?.decompose_graphlike()?;
let decoder = UnionFindDecoder::from_model(&model)?;
let result = run_qec_program(&program)?;
let predicted = decoder.decode_packed(&result.detectors)?;
let failures = (0..result.total_shots)
    .filter(|&shot| predicted.get_bit(shot, 0) != result.observables.get_bit(shot, 0))
    .count();
Ok::<(), prism_q::PrismError>(())
}

The repetition code protects a Z memory; the rotated surface and triangular 6.6.6 color codes take an X or Z memory basis. A zero rate adds no annotation, so QecCircuitNoise::default() gives the noiseless program, whose detectors and observable never fire. QEC programs has the layouts and schedules.

Detector error model export

Matching and belief propagation decoders read an error model, not raw detector samples. QecProgram::detector_error_model derives one from the program's noise annotations, detectors and observables, and to_text writes it in the detector error model text format external decoders read:

#![allow(unused)]
fn main() {
let program = prism_q::parse_qec_program(
    "R 0 1 2 3 4
     X_ERROR(0.01) 0 2 4
     CX 0 1 2 1 2 3 4 3
     MR 1 3
     DETECTOR rec[-2]
     DETECTOR rec[-1]
     M 0 2 4
     OBSERVABLE_INCLUDE(0) rec[-1]",
)?;
let model = program.detector_error_model().unwrap();
std::fs::write("memory_d3.dem", model.to_text()).unwrap();
Ok::<(), prism_q::PrismError>(())
}

Each mechanism carries a probability and the detector and observable indices it flips; detector coordinates pass through from the program. Matching decoders need at most two detectors per mechanism: decompose_graphlike splits each hypergraph mechanism across existing graphlike ones and returns an error when no split exists, and to_text writes the splits as components separated by ^. Every detector and observable must be deterministic in the noiseless program, since a random one has no error mechanism to describe it; detector_error_model names it in the error.

DetectorErrorModel::from_text reads the same format, repeat blocks and shift_detectors included, so a model written by another tool can drive the decoders in the crate:

#![allow(unused)]
fn main() {
use prism_q::{DetectorErrorModel, UnionFindDecoder};

let model = DetectorErrorModel::from_text(
    "error(0.1) D0
     repeat 2 {
         error(0.1) D0 D1
         shift_detectors 1
     }
     error(0.1) D0 L0",
)?;
assert_eq!(model.num_detectors(), 3);
let decoder = UnionFindDecoder::from_model(&model)?;
Ok::<(), prism_q::PrismError>(())
}

QEC decoding has the derivation semantics and the grammar in both directions.

Decoding

UnionFindDecoder decodes sampled detectors against a graphlike model in-process, so a memory experiment's logical error rate needs no external tool:

#![allow(unused)]
fn main() {
use prism_q::{UnionFindDecoder, run_qec_program};

let program = prism_q::parse_qec_program(
    "R 0 1 2 3 4
     X_ERROR(0.01) 0 2 4
     CX 0 1 2 1 2 3 4 3
     MR 1 3
     DETECTOR rec[-2]
     DETECTOR rec[-1]
     M 0 2 4
     OBSERVABLE_INCLUDE(0) rec[-1]",
)?;
let model = program.detector_error_model()?.decompose_graphlike()?;
let decoder = UnionFindDecoder::from_model(&model)?;
let result = run_qec_program(&program)?;
let predicted = decoder.decode_packed(&result.detectors)?;
let failures = (0..result.total_shots)
    .filter(|&shot| predicted.get_bit(shot, 0) != result.observables.get_bit(shot, 0))
    .count();
Ok::<(), prism_q::PrismError>(())
}

The decoder is weighted union-find with peeling: edges weigh ln((1-p)/p), one-detector mechanisms are boundary edges, and mechanisms that flip no detector set a floor under the achievable logical error rate. Construction rejects hypergraph models and points to decompose_graphlike. Decoding is deterministic and allocates nothing per shot, and large batches decode in parallel.

Two more decoders take the same model and expose the same decode_packed and logical_error_rate calls. MatchingDecoder is exact minimum-weight perfect matching over the same graphlike model: it finds the least-weight correction for every shot, so it fails no more often than union-find on hard noise, at a higher per-shot cost.

BpOsdDecoder runs belief propagation with ordered statistics decoding on the check matrix and accepts hypergraph models directly, which color codes and qLDPC codes need. BpOsdOptions picks the BP rule (MinSum { scaling } or ProductSum), the iteration cap, and the OSD search (Zero, CombinationSweep { order }, or Exhaustive { order }).

#![allow(unused)]
fn main() {
use prism_q::{BpOsdDecoder, BpOsdOptions, MatchingDecoder, OsdMethod, run_qec_program};

let program = prism_q::parse_qec_program(
    "R 0 1 2 3 4
     X_ERROR(0.01) 0 2 4
     CX 0 1 2 1 2 3 4 3
     MR 1 3
     DETECTOR rec[-2]
     DETECTOR rec[-1]
     M 0 2 4
     OBSERVABLE_INCLUDE(0) rec[-1]",
)?;
let result = run_qec_program(&program)?;
let model = program.detector_error_model()?;
let matching = MatchingDecoder::from_model(&model.decompose_graphlike()?)?;
let matching_rate = matching.logical_error_rate(&result.detectors, &result.observables)?;

let options = BpOsdOptions {
    osd_method: OsdMethod::CombinationSweep { order: 10 },
    ..BpOsdOptions::default()
};
let bposd = BpOsdDecoder::with_options(&model, options)?;
let bposd_rate = bposd.logical_error_rate(&result.detectors, &result.observables)?;
Ok::<(), prism_q::PrismError>(())
}

QEC decoding covers each algorithm, its complexity, and its validation against brute force and the exact ML rate.

GPU Backend

Info

The GPU backend is optional and gated behind the gpu feature. Building it needs no CUDA toolkit: the NVIDIA driver loads when the first GpuContext opens, and NVRTC when kernels need compiling. Running it needs a CUDA-capable device, a driver for CUDA 12.0 or newer, and NVRTC from a CUDA 12 or CUDA 13 toolkit on the loader path (PATH on Windows, the ld.so search path on Linux). NVRTC 12 is preferred when both load, since NVRTC 13 does not compile for cards older than Turing. A missing driver or NVRTC surfaces as a PrismError from GpuContext::new.

cargo build --release --features "parallel gpu"
cargo nextest run --features "parallel gpu" --test golden_gpu --test golden_gpu_density_matrix

Constructing a GpuContext compiles the CUDA kernels through NVRTC, one to three seconds on a GTX 1080 Ti. NVRTC emits a cubin for the device's exact architecture, which loads on any CUDA 12 driver. An NVRTC older than the device compiles PTX for the newest architecture it knows, and the driver JITs it. That path needs a driver at least as new as the NVRTC, and GpuContext::new names both versions when it is not.

The compiled image is cached in prism-q-ptx under the user cache directory, keyed by device architecture, crate version and kernel source, so later processes skip the compile. A cached cubin loads without NVRTC. Delete the directory to force a recompile.

The device runs statevector, stabilizer and density matrix execution and compiled BTS sampling. BackendKind has four device kinds, and the backends and samplers below opt in directly:

  • BackendKind::AutoGpu { context } (simulate(circuit).gpu_auto(ctx)). The decision tree runs unchanged, and a selected statevector or stabilizer workload that clears its family's qubit crossover and fits in VRAM runs on the device. Everything else, including a device allocation that fails at init, takes the identical CPU path. RunMetadata::placement reports Host or Device for the run.
  • BackendKind::StatevectorGpu { context } (simulate(circuit).gpu(ctx)). Keeps fusion and subsystem decomposition, and leaves sub-circuits below crate::gpu::min_qubits() (default 14, PRISM_GPU_MIN_QUBITS override) on the CPU. Measurements and resets in one instruction run are decided on the device and read back together, at the end of the run or before a classically conditioned gate or region. A noisy trajectory shot keeps them on the device across its noise sites until a conditional, a region, a readout flip, a Kraus branch picked on the host, or the end of the shot. Terminal shots and counts are drawn on the device, and one state index per shot comes back in place of the 2^n probability vector, while that moves fewer bytes: fewer shots than about two thirds of the amplitudes. More shots read the probabilities back and sample on the host.
  • BackendKind::StabilizerGpu { context }. Gates apply to a device tableau through one word-grouped batched Clifford kernel (stab_apply_word_grouped). Measurement and reset keep pivot search, row cascade, phase fixup and deterministic outcomes on the device, a run of measurements with a few launches and no host copy per measurement. Circuits from 1,000 qubits run on the device (STABILIZER_MIN_QUBITS_DEFAULT, PRISM_STABILIZER_GPU_MIN_QUBITS override), unless a measurement group shorter than eight, a reset or a guarded region would take a host round trip each; those stay on the CPU at any width. Direct backend benchmarks should use StabilizerBackend::with_gpu(ctx) to exclude diagnostic readbacks from probabilities(), export_tableau() and export_statevector(). Golden tests cover every kernel path, including 500q GHZ measure-all.
  • BackendKind::DensityMatrixGpu { context }. The exact mixture in device memory. Explicit only: neither Auto nor AutoGpu selects it, and it has no crossover and no host fallback. init budgets the 4^n buffer against free VRAM and errors before allocating when it does not fit, so an 11 GiB card holds 14 qubits (4 GiB at 14 plus a 2^n diagonal scratch; 15 needs 16 GiB). The unitary half reuses the dense statevector kernels on the embedded 2n-qubit buffer, and every channel, measurement and readout sweep has a kernel of its own. The noisy Simulate terminals answer from the device mixture exactly as DensityMatrix does. DensityMatrixBackend::new(seed).with_gpu(ctx) is the direct form.
  • StatevectorBackend::new(seed).with_gpu(ctx). Every instruction routes to CUDA once the context is attached, with no crossover or subsystem decomposition.
  • StabilizerBackend::new(seed).with_gpu(ctx), for kernel benchmarks and targeted correctness tests.
  • run_shots_compiled_with_gpu (or CompiledSampler::with_gpu(ctx)). BTS sampling for flat sparse parity: one kernel per chunk of 65_536 shots, random bits generated on the host, and the CPU sample_bts_meas_major layout. Sparse parity CSR arrays, packed reference bits and scratch stay cached on the device. A sampler stays on the CPU, where launch and transfer setup would cost more than the kernel saves, below 131_072 shots (PRISM_GPU_BTS_MIN_SHOTS), below rank 4 (PRISM_GPU_BTS_MIN_RANK; GHZ and other low-rank samplers expand each shot from a few bits), or with fewer than 2 parity entries per measurement (PRISM_GPU_BTS_MIN_WEIGHT_FACTOR). sample_bulk_packed_device returns a DevicePackedShots handle. Marginals reduce to one counter per measurement row on the device. Exact counts use a bounded device hash reduction for up to 8 packed measurement words when the compact result is cheaper to transfer than the full shot matrix, and a host copy otherwise.
  • NoisyCompiledSampler::with_gpu(ctx). The same BTS path with Pauli noise. Noise masks come from an RNG stream seeded on the device when the event probabilities allow it, or from the host otherwise, and counts and marginals reduce on the device. The device stream differs from the CPU one, so output matches the CPU statistically, not shot for shot. Readout error keeps materialized shots on the CPU.
  • CompiledDetectorSampler::with_gpu(ctx). Detector and observable sampling over the device measurement sampler, with parity rows derived as on the CPU.

On the hard statevector path (StatevectorGpu, with_gpu), a state that does not fit the free VRAM is rejected at init with an error naming the requested and free device memory.

GpuContext reports on its device before a run: device_name, vram_bytes and vram_available, max_qubits_for_statevector (the advisory cap from free memory), and fits_statevector(n) for the amplitudes alone. fits_statevector_with_scratch(n) and fits_tableau(n) are the checks AutoGpu runs before placing a block. synchronize waits for queued kernels, which timing device work needs. gpu::is_available() opens no context. gpu::nvrtc_available() reports whether NVRTC loads, which matters only when no cached kernel image fits the device. Under bench-internal, pass_census counts launches, passes over the state and host copies since the context opened.

Python reaches the four device kinds too. The Linux and Windows wheels carry the gpu feature, and pip install "prism-q[cuda12]" adds NVRTC from PyPI. See Python Bindings.

Module layout (src/gpu/)

FileRole
mod.rsGpuContext public entry point, the GpuState and GpuTableau device buffers (private to the crate), crossover knobs, GpuPassCensus (bench-internal)
device.rsGpuDevice: cudarc wrapper, compiles the kernel image at device construction
memory.rsGpuBuffer: device Complex64 storage
tiles.rsLowering of a fused stream to mixed tile ops and the tile planner
kernels/mod.rsKERNEL_NAMES, LauncherScratch, composed kernel_source() concatenating dense, stabilizer, BTS and density
kernels/dense.rsRust launchers for every Gate variant; CUDA C source in kernels/dense.cu
kernels/stabilizer.rsLaunchers for tableau init, the batched Clifford kernel stab_apply_word_grouped, stab_rowmul_words, and measurement as pivot search, cascade, fixup and a deterministic branch; source in kernels/stabilizer.cu
kernels/bts.rsLaunchers for compiled BTS shot sampling; source in kernels/bts.cu
kernels/density.rsLaunchers for the density-matrix path: sandwiches, Kraus channels, projection and Pauli expectation; source in kernels/density.cu

Kernel design notes live in the module docstrings under src/gpu/kernels/. The statevector crossover measurement is on MIN_QUBITS_DEFAULT in src/gpu/mod.rs.

Kernel coverage

Every Gate variant runs on the device, though not each through a kernel of its own. The one- and two-qubit gates with a fixed matrix share one dense matrix launcher. QftBlock runs as shared memory DIF passes (qft_dif_pass, up to 11 stages each) plus a bit reversal pass where the flags need one, and PauliRot lowers to a CNOT ladder around a parity-phase kernel. Batched variants (BatchPhase, BatchRzz, DiagonalBatch, MultiFused { all_diagonal: true }) use LUT kernels fed by the same host table builders as the CPU path.

Non-diagonal MultiFused uses a shared memory tiled kernel (apply_multi_fused_tiled, TILE_Q = 10, TILE_SIZE = 1024) over ten qubits per pass: the five lowest, which keep a warp's loads contiguous, plus up to five of the sub-gates' higher targets. A MultiFused over n qubits takes about (n - 5) / 5 passes, and a pass with fewer than three sub-gates falls back to per gate launches. Multi2q launches once per sub-gate. A sub-gate or Fused2q whose matrix is exactly a CX, swap, CZ or controlled phase runs on that gate's kernel, and one with a single nonzero per row (a permutation with phases, or a diagonal) on apply_monomial_2q. Only the rest pay the dense 4x4 multiply, which takes three real multiply-adds per complex product (the Gauss form). On a card with reduced FP64 rate such as the GTX 1080 Ti it costs about one sweep of the state instead of one and a half.

From 18 qubits the statevector fuses for the device (FusionProfile::Device, see Fusion Pipeline) and apply_instructions lowers the stream to tiles. One apply_mixed_tile block gathers the 2^11 amplitudes of 11 qubits (the two lowest plus up to nine the planner picks) into 32 KB of shared memory, applies every op the tile holds, and writes them back: one pass for a run of 1q matrices, diagonals, CX, swap, CZ, controlled phases and Rzz. A real 1q matrix, or one shaped like Rx, takes half the multiplies of a general one. Dense 4x4 blocks, Mcu, QftBlock and the rest keep their kernels. On a GTX 1080 Ti a five-layer hardware efficient ansatz at 24 qubits drops from 115 dense passes to 7 tile passes, and a random depth-10 circuit from 73 to 7. The tiles are FP64 bound on that card, so a dense 1q gate still costs about half a sweep.

The CUDA C source sits in .cu files beside the launchers and reaches KERNEL_SOURCE_TEMPLATE through include_str!. Placeholders in kernels/dense.cu are filled at device construction. Batch table sizes such as {{BP_TABLE_SIZE}} come from the constants in src/backend/statevector/kernels/batch_tables/mod.rs, so CPU and GPU share one value; the tile width {{TILE_Q}} comes from the GPU tile constants.

Correctness

tests/golden_gpu.rs compares GPU amplitudes against the CPU statevector within 1e-12 for every gate variant, the fusion paths, and the BackendKind::StatevectorGpu public dispatch path at the crossover boundary. tests/golden_gpu_density_matrix.rs does the same for the full density matrix buffer. Both suites fail when no device opens, unless PRISM_ALLOW_NO_GPU=1 lets them skip on a host without a card. No CI job opens a device; scripts/test-gpu.ps1 runs them on a host with one.

Shot reproducibility

The golden equality tests do not cover three limits on what a seed guarantees.

  • CPU against GPU: agreement in distribution, not bit for bit. Both paths draw the same RNG stream for a given shot seed, but the device reduction behind a measurement probability sums in tree order with FMA contraction and can differ from the host sum in the last ulp. A uniform draw landing between the two flips that outcome and every one after it. Where the probability is a dyadic rational (0.5, 1.0, and the amplitudes Clifford gates reach) both sums are exact and the shots match, as statevector_gpu_mid_measure_shots_match_cpu pins. statevector_gpu_shot_frequencies_match_cpu_off_dyadic pins the general case: equal frequencies within 5 sigma after Rx(0.3).
  • Terminal shots and counts on the GPU statevector: below about two shots for every three amplitudes, the device walks a scan of the state in blocks of 4096 amplitudes, which rounds differently from the host's running sum, so a draw within rounding of the boundary between two outcomes can land on the neighbouring one. The choice of walk counts bytes only, so neither it nor the result depends on the card or the Rayon thread count. statevector_gpu_terminal_sampling_matches_cpu_marginals pins the frequencies against the CPU probabilities.
  • GPU BTS sampling: reproducible outright. The random bits are drawn on the device from one seed per call, one xoshiro256++ stream per 64-shot batch and block of 32 parity columns, so the shots do not depend on the Rayon thread count or on how a call is split into chunks, and the host and device result paths return the same shots.

Current limits

  • Stabilizer probabilities(), export_tableau(), and export_statevector() read back to the CPU.
  • Every trajectory shot rebuilds the backend and reallocates the device buffer, measured at 0.1 ms per shot at 20 qubits.
  • A one-qubit Custom Kraus channel with more than 16 operators, or with an operator whose diagonal test depends on the branch weight, picks its branch on the host from a reduced density matrix read back from the device (rdm_qubit). Damping, thermal relaxation and the other Custom channels pick the branch on the device.
  • Two-qubit Kraus channels compute the pair reduced density matrix on the device (rdm_2q, 128-byte readback) and apply the chosen branch on the device.
  • PRISM_PTX_CACHE_DIR overrides the disk PTX and cubin cache location; setting it to an empty string disables disk caching.

Distributed Statevector and MPI

The distributed statevector backend splits one exact 2^n amplitude vector across 2^p ranks, for registers that do not fit one host. Each rank holds a 2^(n-p) slice in an ordinary statevector backend, so local gates run on the same SIMD kernels and fusion pipeline as a single-host run. The result does not depend on the rank count: one rank is bitwise the Statevector backend, and P ranks gather to the same vector.

Info

Two feature flags. distributed adds the backend and the single-rank and thread loopback transports, with no external dependency. distributed-mpi adds the MPI transport over rsmpi, which needs a system MPI installation and libclang for its bindgen step. The published Python wheels carry neither; build from source to enable them (see Python Bindings).

Running

use prism_q::{distributed::DistributedContext, simulate};

let context = DistributedContext::world()?;
let result = simulate(&circuit).distributed(context).seed(42).run()?;

DistributedContext::world() and attached_world() need the distributed-mpi feature. world() calls MPI_Init at MPI_THREAD_FUNNELED and captures the world communicator. Dropping the context on the thread that created it runs MPI_Finalize. When another component already owns MPI, such as an embedding interpreter with mpi4py, attached_world() attaches without taking over the MPI lifetime. It returns Ok(None) when MPI is not initialized, and an error when MPI runs below the thread level the backend needs. DistributedContext::serial() gives a single rank with no MPI, which is how the tests and a build with distributed alone run.

simulate(&circuit).distributed(context) is shorthand for .backend(BackendKind::StatevectorDistributed { context }). Automatic dispatch never selects this backend.

Launch the binary under the MPI launcher with a power-of-two rank count:

mpiexec -n 4 ./target/release/my_simulation

Every rank runs the same program and enters every collective inside the backend (SPMD), so branching on context.rank() before a simulation call deadlocks the other ranks.

Other transports

DistributedContext::from_comm(Arc<dyn RankComm>) wraps any transport. RankComm (prism_q::distributed::RankComm) is the whole contract the backend uses: rank, size, allgathers of Complex64, f64 and u64 blocks, a scalar allreduce_sum_f64, a paired sendrecv_c64 exchange, and barrier. Every rank must issue the same sequence of calls, as under MPI. SerialComm is the single-rank implementation and MpiComm the MPI one.

The thread loopback in prism_q::distributed::loopback, compiled under bench-internal, runs ranks as threads in one process. run_ranks(size, f) calls f once per rank with a context whose transport reaches the others and returns the results in rank order:

use prism_q::{distributed::loopback::run_ranks, simulate};

let probabilities = run_ranks(4, |context| {
    simulate(&circuit).distributed(context).seed(42).run().unwrap().probabilities
});

Memory layout

Global index rank * 2^(n-p) + local_index. Qubit q below n - p is bit q of the local index, and qubit q at or above n - p is bit q - (n - p) of the rank id. Qubit 0 is the least significant bit, as everywhere in PRISM-Q, and |0...0> is index 0 on rank 0.

PRISM_DIST_MIN_LOCAL_QUBITS (default 10) sets the fewest local qubits a rank may hold; a split that leaves fewer is rejected at init.

Qubit relabeling

At more than one rank the backend maps circuit qubits to physical positions, so a SWAP is a map update with no amplitude movement. Before a gate acts non-diagonally on a qubit in a rank bit, the backend moves that qubit to a local position by exchanging the half slice whose local bit differs from the rank bit, evicting the least recently used local qubit. Later gates on it run without communication until it is evicted. Diagonal gates and control bits are free on global qubits and never trigger a relabel.

Relabeling pays off when gate activity has locality: SWAP networks, repeated gates on the same qubits, working sets that fit the local positions. A cyclic scan over more hot qubits than local positions evicts on every layer. PRISM_DIST_RELABEL=0 switches the map off and falls back to a direct exchange per gate. PRISM_DIST_EXCHANGE_CHUNK tiles each exchange into messages of that many amplitudes and bounds the transfer buffers. The default, 2^29 amplitudes, sends a slice of up to 8 GiB as one message and keeps every message within the int count MPI calls take.

What runs distributed

  • Gates, including fused and batched payloads, measurement, reset, and classical conditionals. Measurement probabilities gather one scalar per rank and sum in rank order, and every rank draws from the same seeded stream, so ranks agree on the outcome without exchanging it.

  • Per-qubit probabilities, Pauli expectation values, and multi-shot terminal sampling answer from rank-local sums plus one reduction, at any register width, without gathering the dense state.

  • Reduced density matrices, summed from rank-local partial traces. Kept qubits on rank bits move to local positions first, one half-slice exchange each, and stay there with relabeling on. With PRISM_DIST_RELABEL=0 the layout is restored afterwards. A subsystem wider than the local slice reads the gathered state. Entanglement entropy needs a global SVD and declines.

  • probabilities() and export_statevector() gather, so they carry the dense output cap; a register past the cap is rejected before the run.

  • A caller-supplied initial_state: every rank receives the full vector and keeps its own slice.

  • Noisy shots through .noise(&model), for every channel the trajectory engine runs: Pauli and depolarizing, amplitude and phase damping, thermal relaxation, one- and two-qubit Kraus, leakage, and quasi-static drift. Ranks run the shots one at a time in shot order on one sharded state, re-initialized per shot, and seed each shot's noise stream from the run seed and shot index, so they draw the same branches without exchanging them. What each event reads from the state:

    EventRead
    Paulinothing
    Damping or thermalthe qubit's excited population, one scalar gathered per rank
    One-qubit Krausthe qubit's reduced density matrix, four scalars per rank, plus a half-slice exchange when the qubit sits on a rank bit
    Two-qubit Krausthe pair's block, after relabeling the pair local

    With relabeling off, that relabel is undone after the read, two more exchanges. With fewer than two local qubits the event gathers the whole state, under the export cap. Ranks sum the gathered parts in rank order, so each weighs a draw against the same value. The records match the host statevector's trajectory engine run serially at the same seed. For a Pauli-only model with terminal measurements the host's default route samples from shared error prefixes instead, so its records differ.

  • Before the first noisy shot the ranks compare the circuit, noise model, shot count and seed, and whether each rank accepted the run under the limits it resolved. A run any rank rejects fails on every rank instead of leaving the others waiting at a collective.

Not supported: GPU execution, which is single device; shot parallelism and the shared Pauli error prefixes the host trajectory engine uses; and selection by BackendKind::Auto.

Testing and measuring

The thread loopback transport covers the rank logic without an MPI runtime:

cargo nextest run --features "parallel distributed" -E 'test(distributed)'

scripts/test-mpi.ps1 (Windows, MS-MPI) and scripts/test-mpi.sh (Linux, Open MPI flags) build tools/dist_mpi_check.rs with the distributed-mpi feature and launch it at 1, 2 and 4 ranks under three configurations (default, tiled exchange, relabeling off). Rank 0 compares the gathered result against a one-process statevector and fails on mismatch, and a three-rank launch checks the power-of-two rule. Each script's timed arm prints per-rank timings for comparing exchange pipelines across hosts.

cargo bench --bench bench_distributed --features "parallel distributed bench-internal" runs the loopback benchmarks. Their ranks share one memory system, so the rows price packing, copying and per-gate dispatch rather than network latency (see Benchmark Methodology).

The exchange paths and relabeling algorithm are documented on the distributed_statevector module, and per-backend support is in the Capability and Support Matrix.

Compatibility and Versioning

Rust version

The minimum supported Rust version is 1.89.0, pinned in three places updated together: rust-version in Cargo.toml, msrv in clippy.toml, and the CI_MSRV variable the msrv CI job builds against. That job checks the library with parallel, gpu and distributed. distributed-mpi needs a system MPI to build and is not checked at the floor. Raising the MSRV is a minor bump while the crate is below 1.0. The development toolchain is separate: rust-toolchain.toml pins an exact stable release (see Contributing).

Feature flags

Four feature flags are part of the surface: parallel, on by default, and gpu, distributed and distributed-mpi, each off. bench-fast and bench-internal are not. They shape benchmark runs, gate items no caller should reach for, and may change or disappear in any release. unstable-pulse is not part of it either: the pulse module it enables may change or disappear in any release.

Versions

The crate and the Python wheel carry one version. A release bumps the crate, writes the same version into the bindings manifest and tags the wheel py-v<version>, so a wheel and a crate with the same number were built from one commit. Below 1.0 the minor position is the compatibility boundary. Cargo reads 0.32.0 as ^0.32.0, so 0.32 to 0.33 already signals a break to every caret requirement, and the release tooling resolves a breaking change to a minor bump rather than 1.0.0.

A version promises the surface tabulated in API surface and the Python package. Which backend Auto picks for a circuit, where the fusion thresholds sit, how fast a kernel runs and what the benchmark rows are named are implementation, and they move without a bump. Public enums are #[non_exhaustive] apart from a few that mirror a closed set, which that page names, so a new variant is additive and a match outside the crate keeps a wildcard arm. The Backend trait is sealed, so only the crate implements it and a new method is additive. Items hidden from the rendered API docs, such as prism_q::circuit::fusion, are reachable for tests and tooling but are not part of the surface.

Changed results

A breaking release can keep a public field and change what it reports. These fields changed meaning:

  • 0.39.0: run_stabilizer_rank_approx runs on the Clifford register and changes three fields of its StabRankResult. discarded_weight is the sum over cuts of the exact 2-norm each cut dropped, where it was the summed 1-norm of the dropped branch weights; a caller's 4 * discarded_weight remains a valid bound on the summed absolute difference from the exact distribution. num_terms and pruned_count count register coefficients, not branches. The new field kept_norm_sqr carries the kept norm, and fidelity_bound() uses both. A register wider than 20 qubits now returns BackendUnsupported, and seed is ignored.
  • 0.39.0: run_stabilizer_rank, and run() on BackendKind::StabilizerRank, build the Clifford register up to 24 qubits wide, where the cap was 20. A circuit whose register is 21 to 24 qubits wide and carries more than 20 T gates now returns its probabilities, where it returned BackendUnsupported for too many terms. run_stabilizer_rank_approx keeps the 20 qubit cap.
  • 0.39.0: RunMetadata::exactness on an MPS run reports the run instead of the route. A run whose cuts discarded a summed squared weight of at most 1e-24 is Exact at any bond cap, where any chain wider than bond 1 was Approximate with a bound of 1.0. Python's is_exact follows it. require_exact still declines the MPS route before the run.
  • Unreleased: run_qec_program_with_strategy under QecTStrategy::Auto lowers the program once for SPD, CAMPS and the tensor network. A program that lowering refuses returns the refusal itself, an IncompatibleBackend from QEC deferred lowering or QEC SPD / CAMPS, where it returned one from QEC auto T-strategy that repeated the refusal for each of the three strategies.
  • Unreleased: run_qec_program on a noiseless EXP_VAL program without detectors whose analytical lowering refuses it (a FEEDFORWARD, a measured qubit reused without a reset, or a gate on three or more qubits) now returns estimates from run_qec_program_reference, where it returned IncompatibleBackend. That route costs shots times 2^n, so it takes programs up to Limits::max_qec_reference_qubits (PRISM_MAX_QEC_REFERENCE_QUBITS, default 20 qubits) and within the statevector cap. A wider program returns the refusal with the limit named, and one past the statevector cap returns a ResourceLimit whose message also names why the lowering refused.

Seeded output

A seed reproduces a result within a version, under the thread-count rules each path states in Determinism. Across versions it does not: a minor release may change what a seed draws, and its release notes say so. Such a change moves which bits a seed lands on, not the distribution they come from; the distribution changes only to fix a bug.

Seeded output has changed in these releases:

  • 0.33.0 seeds shot i with a SplitMix64 hash of the run seed and i instead of seed + i. That covers per-shot replay of circuits with mid-circuit measurements, the distributed per-shot loop, noise trajectories (serial and parallel, noisy stabilizer trajectories included), the block seeds of a decomposed run, and the per-qubit and per-observable seeds of Stochastic Pauli Propagation. Fixed-seed results on those routes changed, and on a replay route shots(1) with seed x no longer reproduces run() with seed x.
  • 0.35.0 changes three sampling routes and fixes a fourth. Product-state and factored terminal shots and counts draw in blocks of 256 shots, one stream per block, so they fill in parallel; the dense sampler over factored block probabilities, which also serves decomposed terminal shots, draws the same blocks so the two still agree shot for shot. Noiseless circuits with mid-circuit measurements on the host statevector evolve once per outcome history and split shots binomially, so a shot no longer corresponds to a run on its own seed; once only measurements remain, each branch draws its readout from its own state in one pass. Dynamic programs on the host statevector branch the same way, so their shots no longer follow mix_seed(seed, i). Compiled Clifford counts at high shot counts draw from a corrected binomial sampler, which also fixes their spread.
  • 0.39.0: these routes draw differently:
    • Shots from the Clifford register draw differently on every circuit that route serves: Auto and explicit StabilizerRank terminal shots of a Clifford+T circuit, and circuits whose mid-circuit measurements move to the end. The register is split into independent parts, and shots are drawn in blocks of 256 with one ChaCha8 stream per block. More circuits reach the register: one wider than 20 qubits qualifies when each part fits 24 qubits or divides into two sides of at most 20, up to 64 register qubits in all, and those circuits move from the statevector, or past the statevector cap from the MPS. Fixed-seed shots on all of these circuits changed. Probabilities from run_stabilizer_rank are unchanged.
    • The Clifford register reads the outcome table of a part it holds whole as the Walsh transform of the expectation values of the part's measured rows, wherever that costs less than diagonalizing the part's amplitudes. The two tables agree to about 1e-15, so a fixed-seed shot changes only where its draw lands that close to the boundary between two outcomes. The cheaper readout also moves Auto terminal shots of some Clifford+T circuits from the statevector to the register, those whose register is nearly as wide as the circuit, and fixed-seed shots on those circuits changed.
    • The Clifford register holds a part of 25 or 26 qubits whole, where the widest whole part was 24, when the part has no cut into two sides of at most 20 across at most 12 row pairs. Those circuits move to the register: Auto terminal shots from the statevector, or past the statevector cap from the MPS, and explicit StabilizerRank shots return where they returned BackendUnsupported. Fixed-seed shots on those circuits changed. A part of 25 or 26 qubits with such a cut keeps it and its shots. The amplitudes summed over the parts are held to the process statevector cap, so under a cap below 25 a register past it declines where it was taken.
    • Auto terminal shots of a Clifford+T circuit are priced between the Clifford register and the dense run instead of capping the T count. Circuits with more than 20 T gates, or at least as many T gates as qubits, whose register fits 20 qubits move to the register from the statevector, or past the statevector cap from the MPS. A register nearly as wide as the circuit, or one wider than the independent blocks the circuit splits into, moves the other way. Fixed-seed shots on those circuits changed.
    • Auto shots of a Clifford+T circuit with a mid-circuit measurement, a guard or a reset sample from the Clifford register once its measurements move to the end, in place of the weighted MPS branches, and explicit StabilizerRank does the same. Within the statevector cap, a circuit the register does not take runs on the statevector walk; past the cap, one whose measurements stay in place keeps the branches up to 6 T gates and goes to the dispatch tree beyond. Fixed-seed shots on those circuits changed.
    • Auto shots of a circuit that reaches the mid-circuit walk drop parity ancillas. An ancilla that only collects CX gates from data qubits and X flips, is measured, and is then reset or left alone becomes a parity measurement on those data qubits, so the walk runs on a smaller register. Fixed-seed shots on those circuits changed; explicit Statevector keeps the ancillas and its shots.
    • The host statevector walk skips the probability pass of a reset, or of a repeated measurement, when the qubit was last measured as 1 and nothing has touched it since, taking the probability as exactly 1. The pass returned 1 to within about 1e-14, so later probabilities on that branch move in the last bits, and a fixed-seed outcome changes only where a draw lands that close to a boundary.
    • More noisy and noiseless Clifford circuits with mid-circuit measurements move from per-shot tableau replay to the compiled sampler, which draws a different stream: circuits that use a measured qubit again without a reset, active reset by a guarded X among them, guarded Paulis under a register comparison reading several measured bits (the form switch and lookup decoding take), and asymmetric readout error on a bit a guard reads. Circuits that compiled before keep their shots.
    • QEC measurement records that a noisy or feed-forward program reads are sampled from one noiseless reference run spread by random Pauli frames, in place of a compiled sampler over the deferred circuit. Kept records, and detectors or observables that are random without noise, change for a seed; detectors, observables and postselection counts that are fixed without noise do not.
    • Compiled Clifford sampling with a GPU context draws its random bits on the device, from one seed per call and one stream per 64 shots and 32 parity columns, in place of bits drawn on the host. Fixed-seed shots, counts and marginals from the device sampler changed, and they no longer depend on the Rayon thread count.
    • Terminal shots and counts from a GPU statevector are drawn on the device against a scan of the state in blocks of 4096 amplitudes, with each uniform scaled by the total weight, in place of a host walk over the probability vector, when the walk moves fewer bytes than reading the 2^n probabilities back: fewer shots than about two thirds of the amplitudes. The uniforms are unchanged, so a fixed-seed shot over the full register moves only where its draw lands within rounding of the boundary between two outcomes, and then to the neighbouring outcome. Counts drawn on the device whose map is anything but qubit i into bit i across the whole register, a partial or permuted map, walk the full state where they sampled a table keyed by the measured bits, so fixed-seed counts on those circuits changed. A run with more shots keeps the host sampler and its output, including the table for a partial map.

Architecture: Overview and Layered Design

How PRISM-Q is built. Terms are defined in the Glossary.

Goals

  • The fastest practical quantum circuit simulation in Rust. When goals conflict, performance is weighed first, then correctness, then maintainability.
  • Correct simulation of the supported gate sets on every backend.
  • A backend trait that a new simulation strategy implements without changes to the core.

Non-goals

  • Full OpenQASM 3.0 compliance; a practical subset is supported.
  • GUI or notebook integration (library-first).
  • Connections to hardware or a QPU.

Layered design

A circuit flows top to bottom: OpenQASM text or a builder produces a backend-agnostic IR, the route layer picks an engine for the terminal asked, the fusion pipeline rewrites the gate stream for that engine, and the engine runs it. Programs with runtime control flow and native QEC programs enter beside the circuit path and reuse its parts.

flowchart TD
    API["Public API: simulate, run_qasm, run_on (src/lib.rs)"]
    P["OpenQASM parser (src/circuit/openqasm/)"]
    IR["Circuit IR (src/circuit/mod.rs)"]
    DP["DynamicProgram: blocks of Circuit IR (src/circuit/dynamic/)"]
    QP["QecProgram (src/qec/)"]
    R["Route and plan: Auto dispatch, Simulate::plan (src/sim/route.rs, dispatch.rs)"]
    F["Fusion pipeline and stage planner (src/circuit/fusion.rs, fusion_stage.rs)"]
    API --> P --> IR --> R
    API --> DP --> R
    R --> F --> B["Nine CPU backends (src/backend/)"]
    R --> CT["Clifford+T engines: stabilizer rank, SPP, SPD, Pauli path (src/sim/)"]
    R --> CS["Compiled samplers and noisy engines (src/sim/compiled/, src/sim/noise/)"]
    F --> G["GPU statevector, stabilizer, density matrix (src/gpu/, feature gpu)"]
    F --> D["Distributed statevector (src/distributed/, feature distributed)"]
    API --> QP --> QS["QEC samplers, estimators, decoders (src/qec/)"]
    QS --> CS

The pages in this section follow that flow: the parser and circuit IR, dynamic programs, the fusion pipeline, the simulation engine and dispatch, the individual backends, parameters, binding and gradients, the compiled samplers, noise compilation, the QEC programs and their decoders, threading, SIMD and memory layout, and the error model and public API surface.

Parser and Circuit IR

Parser

Handwritten front end in three stages: a lexer turns source into tokens, a parser turns tokens into a statement tree, and a walker turns the tree into Circuit IR. The tree holds syntax only, so meaning is decided once, in the walker. A statement ends at its ; and a block at its }, wherever the newlines fall.

The OpenQASM guide tabulates what parses, what declines, and which error each decline returns.

Circuit IR

Circuit holds num_qubits, num_classical_bits, and Vec<Instruction>. Instructions are an enum:

VariantFieldsDescription
Gategate, targetsGate application
Measurequbit, classical_bitDestructive measurement
ResetqubitReturn one qubit to the zero state, mid-circuit
BarrierqubitsSynchronization barrier
Conditionalcondition, gate, targetsClassical-controlled gate
RegionBox<GuardedRegion>Classical-controlled span of instructions
Savespec, qubits, labelRecord the state at this point

Targets are a SmallVec<[usize; 4]>, stored inline up to 4 qubits, so a typical gate allocates nothing.

Save points

Save records the state at its position. Its qubits field lists the whole register, which makes it a fusion barrier: every pass reads an instruction's qubits to decide what may move past it, so a save blocks reordering both ways with no rule of its own.

No backend implements a save. The runner splits the stream at each save point, hands the backend the segments between, and reads the state through the export the spec names: export_statevector for StateVector, probabilities for Probabilities, reduced_density_matrix over the whole register for DensityMatrix. A backend that cannot produce that form fails the run with its own message. A route that rewrites the circuit instead of executing it (the compiled samplers, the stabilizer-rank engine, the Pauli-propagation engines) declines a circuit carrying one.

Only Simulate::run returns the records. Every other terminal declines a circuit with save points rather than discarding what they recorded.

Guarded regions

Region carries a condition and a body that runs, in order, only when the condition holds against the classical bits as they stand when control reaches it. The body admits any instruction, measurement and reset included, and nests to MAX_REGION_DEPTH. It is boxed, so Instruction stays at 96 bytes.

GuardedRegion caches the sorted union of the qubits its body touches, nested bodies included. Passes read that set instead of re-walking the body: fusion flushes exactly those qubits at the boundary and is transparent elsewhere, and no pass fuses across the boundary because a region is not an Instruction::Gate.

fuse_region_bodies runs the same pipeline over each body as an ordinary instruction list on the same register, nested bodies included. Fusion stays inside the body, and fusing it as a unit is sound because it executes as a unit.

Conditional is the single-gate lowering of the same construct. if (c) x q[0]; keeps that form, so the common guarded gate allocates nothing; anything else becomes a Region. Build either through circuit::guarded, which picks the form and returns None for an empty body.

A circuit holding a region runs once per shot: measurement-conditioned execution has no single distribution to sample, so the compiled samplers reject it and the run replays. A noiseless run on the host statevector replays once per distinct outcome history instead, splitting the shots binomially at each measurement until only measurements remain, then drawing each branch's readout from its state. Routes requiring a unitary circuit (adjoint gradients, exact expectation values, Pauli propagation, stabilizer-rank probabilities) reject a region as they reject a bare conditional. A noise model gives guarded instructions their own event slots, and only routes holding one state per shot serve such a model.

Circuit::fold_static_guards runs once per shots or counts call and resolves guards that cannot depend on a measurement. A condition reading only bits no earlier measurement writes depends only on the initial classical state, which every backend zeroes, so the guard is dropped or inlined, and a circuit whose only guard can never fire returns to terminal sampling. A circuit with no guard borrows through unchanged.

Condition language

ClassicalCondition is a pure function of a bit slice: BitIsOne, BitIsZero, RegisterEquals and RegisterNotEquals over a contiguous range read as u64, and Parity over an arbitrary bit set compared against an expected value. The bit set is boxed, so the enum stays at the size the register variants set. The language is closed under negation (ClassicalCondition::negate), so else lowers without growing the instruction.

else emits the then guard and a second guard with the negated condition. switch emits one RegisterEquals guard per case label, with the default arm nested once per label to spell the conjunction of their negations. Both lowerings re-read the classical bits after an earlier body has run, so the parser rejects a source whose body measures into a bit its own guard reads.

Gate enum

Gate is a Clone enum kept at 16 bytes. Simple variants carry parameters inline; composite variants Box their payload.

Keep the enum at 16 bytes

Adding inline data larger than 16 bytes pollutes cache lines and has caused 40-130% regressions. Check size_of::<Gate>() after adding a variant, and Box large payloads.

VariantDataSize
Id, X, Y, Z, H, S, Sdg, T, Tdg, SX, SXdgNone16B
Rx(f64), Ry(f64), Rz(f64), P(f64), Rzz(f64)Inline f6416B
Cx, Cz, SwapNone16B
QftBlock { start: u8, num: u8, inverse: bool, swaps: bool, big_endian: bool }Inline range and form flags, the one boxless composite16B
Cu(Box<[[Complex64; 2]; 2]>)Boxed 2×216B
Mcu(Box<McuData>)Boxed matrix + control count16B
Fused(Box<[[Complex64; 2]; 2]>)Boxed pre-fused 1q matrix16B
Fused2q(Box<[[Complex64; 4]; 4]>)Boxed pre-fused 2q matrix16B
MultiFused(Box<MultiFusedData>)Batched 1q gates for tiled pass16B
Multi2q(Box<Multi2qData>)Batched 2q gates for tiled pass16B
BatchPhase(Box<BatchPhaseData>)Batched cphase with shared control16B
BatchRzz(Box<BatchRzzData>)Batched ZZ rotations16B
DiagonalBatch(Box<DiagonalBatchData>)Mixed diagonal 1q/2q batch16B
PauliRot(Box<PauliRotData>)Multi-qubit Pauli rotation, boxed angle plus letters16B
MultiPauliRot(Box<MultiPauliRotData>)Batched Pauli rotations as masks and angles for tiled pass16B
Unitary(Box<UnitaryData>)Caller-supplied dense 2^k x 2^k matrix, boxed with its width16B

Unitary is the one variant built from a caller's matrix, through Gate::unitary. It checks U U^dagger = I to 1e-9, then lowers to an existing variant where one fits: a named gate or Fused at one qubit; a named two-qubit gate, Cu or Fused2q at two; Mcu at any width when the matrix is the identity outside its trailing 2x2 block. Only a dense matrix on three or four qubits reaches the variant, so Clifford recognition and the controlled-gate kernels keep firing on the forms they know. Circuit::add_unitary adds the one lowering that needs target indices: a diagonal whose phases factor into one- and two-body terms becomes a DiagonalBatch.

Fusion neither builds nor absorbs a Unitary. Blocking follows instruction targets, so the gate is a barrier over its own qubits while runs on other qubits fuse around it.

Qubit ordering

q[0] is the least significant bit. Applying x q[0] produces state index 1, not 2.

Dynamic Programs

A Circuit is a finite instruction list. Guarded regions, else, switch and bounded for loops fit in one because each lowers to a span of the list at parse time. A while loop that repeats until an outcome comes up, or a counter a measurement increments, has no finite list to lower to. DynamicProgram holds such programs as a control-flow graph and walks it per shot, or per outcome history on the host statevector.

Every block holds an ordinary Circuit, every circuit pass works on a block, and a program with no runtime control flow never reaches the graph walker.

The program

PartShape
BasicBlockA Circuit over the full register, then a list of Actions, then a Terminator
TerminatorJump(block), Branch { condition, then, otherwise }, or End. Block 0 is the entry
ActionAssign { var, value } stores into a variable; Rotation { kind, targets, angle } applies rx, ry, rz, p or rzz at an angle computed at runtime; WriteBits { bits, value } writes the low bits of an integer or bool to classical bits, through Backend::set_classical_bit
VariableA name, a ClassicalType, and the value every shot starts from
ClassicalExprConstants, variables, one classical bit, a register of up to 64 bits read as an unsigned integer, and unary and binary operators

A block runs its circuit, then its actions. Bits a measurement writes in the circuit are visible to the actions and the terminator. The circuit's own guarded regions read the bits as they stand, so measurement-conditioned code inside a block keeps the guarded-region form. Variables are never visible to a circuit, which keeps fusion's dependency model intact: fusion orders instructions by the qubits they touch, and the only classical state a circuit reads is written by a measurement on a qubit the same circuit orders.

ClassicalType is bool, int[n] and uint[n] for n from 1 to 64, float[n] for n of 16, 32, 64 or 128, and angle. A store converts to the declared type. Integers truncate toward zero and wrap to their width, a 16- or 32-bit float rounds to half or single precision, and an angle reduces into [0, 2 pi). Arithmetic on two integers stays integral, / truncating, and a float on either side makes it a float. % and the bitwise operators take integers only, and construction rejects a float operand. Comparisons and logical operators return a bool, and && and || short-circuit. Integer division by zero fails the run with InvalidParameter.

DynamicProgram::new validates every block a terminator names, every variable an expression or assignment reads, and every qubit and classical bit an instruction or expression touches. It rejects a save point, since a shot result has nowhere to return one, and a bitwise operator on a float.

Building one

DynamicProgramBuilder takes structured control flow:

  • begin_while opens an empty header block that tests the condition and branches to the body or past the loop; the body jumps back to the header.
  • begin_if opens a branch to a join block. begin_else switches the open if to its other arm, or reopens the if that end just closed.
  • break_loop and continue_loop jump to the innermost loop's exit or header and continue in a fresh block that nothing reaches until a later construct joins into it.

An instruction appended after an action starts a new block, since a block's actions run after its whole circuit. build threads every jump through empty blocks, merges each block into the one block that alone jumps to it, and drops what the entry cannot reach. Fusion then sees the longest straight-line circuits the control flow allows.

Lowering OpenQASM

openqasm::parse_dynamic walks the same statement tree as openqasm::parse, with the same evaluator, and builds the graph as it goes. The OpenQASM guide lists what it reads beyond parse, and Dynamic declines what it still rejects.

A pass before the walk decides which classical variables live at runtime. A variable does when it is assigned from a measured bit or another runtime variable, or written under a while body or a measured branch its declaration sits outside. The rule iterates to a fixed point, which settles chains of assignments. Every other variable folds at parse time as parse folds it. A variable declared and written inside one loop body stays a parse-time value, because each pass re-declares it, and so does one written only in an unrolled for.

A for still unrolls when a measurement decides a break or continue in it, but its passes become blocks in sequence: continue jumps to the next pass and break past the last. The pass over the tree marks such a loop. Every variable its body writes from outside lives at runtime, since a pass may stop before the write.

An exit every path reaches stops the unrolling at parse time, as under parse. The exception is a measured continue earlier in the pass that sent some paths on to the next one. Then the exit jumps and the unrolling goes on. A return likewise leaves the code after the loop in place when a measured break reached the loop's exit. A measured end jumps to a block that ends the shot, and a def holding an end runs as a call so the same holds inside it. An end that no branch, return or measured exit separates from the program top still stops the parse there, through every call.

The evaluator streams each statement's instructions into the current block. An if takes one of three forms:

  • Folded at parse time, when its condition reads no bit and no runtime variable.
  • A guarded region, the form parse produces, when the instruction list can carry the condition and nothing in the bodies opens a block.
  • A branch in the graph otherwise. That covers a condition over a runtime variable or a general expression, and a body that writes a runtime variable, loops, or applies a runtime angle. It also covers an else whose if body measures its own condition, which the guard pair could not lower soundly.

A switch over a runtime variable, or with an arm that opens a block, becomes a chain of branches. A program with no runtime control flow never opens a block, so it lowers to one block holding the instruction list parse returns.

Runtime subroutines expand into the same graph. Each call copies its classical arguments into local variables and gets its own exit block. A return assigns the typed result and jumps to that exit, including from a loop inside the callee. Loop exits cannot cross the call boundary. Locals are initialized each time the call executes, and every reachable path through a typed call must return. Definitions keep their lexical constants and cannot see the caller's variables.

Calls in a while condition expand into its header, so their effects repeat at each test. A call on the right of a runtime && or || expands into a branch, which keeps short-circuit evaluation. Static calls keep the instruction-list path.

Running one

simulate_program(&program).seed(s).shots(n) returns the same ShotsResult, and sample_counts the same CountsResult, as a circuit run.

A program that is a single block with no actions is its circuit and runs through the circuit path unchanged: same routing, same sampling shortcuts, same seeded shots.

Any other program is prepared once. Routing reads every block's instructions together, with each runtime rotation standing in at a generic angle. A program whose blocks hold only Clifford gates runs on the stabilizer tableau, and a runtime angle counts as non-Clifford. Each block is expanded and fused for the chosen backend once. Every shot initializes one backend, resets the variables, and walks the graph from block 0. At each block it applies the fused circuit, evaluates the actions against that shot's bits and variables, and follows the terminator.

On the host statevector the shots walk the graph together, by the outcome branching that circuits with mid-circuit measurements use. At each measurement the shots on a branch split by a binomial draw on the outcome probability, and each non-empty outcome carries its own state, variables and step count. Variables, loop tests and branch conditions are functions of the outcome history, so every shot on a branch takes the same path. A prefix all shots share, the entry block included, evolves once. The live-state budget and the per-shot fallback past it are the circuit walk's. Only a block that ends the graph with no actions is cut after its last measurement or drawn as a terminal readout, since anywhere else a later block may still read the state.

On every other backend shot i draws from mix_seed(seed, i), the seed the per-shot circuit routes give shot i, and shots split across Rayon workers by the same rule those routes use. Each backend is built per shot.

A shot that runs more blocks than its step bound stops with PrismError::StepLimit naming the loop it was in. The bound defaults to one million blocks, and SimulateProgram::max_steps sets another. Every block entered counts, the empty loop header included.

Backend coverage

Every backend that holds a per-shot state walks a graph through its ordinary apply_instructions: statevector, stabilizer, sparse, MPS, product state, factored, factored stabilizer, tensor network and density matrix. Stabilizer rank and the Pauli-propagation engines keep no per-shot state, and the distributed statevector runs its ranks in lockstep on one circuit, so all three decline with IncompatibleBackend.

Noise

SimulateProgram::noise takes a NoiseBuilder, not a NoiseModel. A model is laid out slot by slot against one circuit, and a program holds one circuit per block, as the builder's merging decides. The rules compile against each block's circuit, guarded regions included, and against each runtime rotation as a one-gate circuit.

The compiled noisy sampler and the error chain complex cannot follow control flow, and the density matrix holds no per-shot state to branch on, so a noisy program runs one trajectory per shot. Routing reads the summary circuit and every compiled event as a noisy circuit's trajectory route does. Pauli noise on Clifford blocks stays on the tableau, other channels move to the statevector family, and a channel the chosen backend cannot sample is rejected before a shot starts. Blocks run unfused so each event stays on its instruction. The host statevector stops branching by outcome history, since noise makes every history its own. Shot i draws its noise from the stream a circuit trajectory gives shot i. Readout error flips a bit as a measurement writes it, so a branch reads the noisy bit, as a guarded region does, and a classical write stores its value unflipped.

Leak flags and quasi-static draws belong to the shot, not the block. Each shot draws its quasi-static normals once before its first event, for every source any block or rotation names. A leaked qubit stays leaked into later blocks until a reset or seepage returns it. ShotsResult::leaked carries the heralds as for a circuit. A program whose arms are written as guarded regions of one circuit draws the same values in the same order, so both give the same seeded shots (tests/integration/noisy_programs.rs).

Declined with IncompatibleBackend: the density matrix, which holds the mixture rather than a trajectory, and an over-rotation rule (fixed or drifting) matching a runtime rotation, whose angle exists only once the shot evaluates it.

A program with no runtime control flow builds the rules against its one circuit and runs as that circuit does under Simulate::noise, mixture routes included.

Cost

Off the host statevector a dynamic program runs once per shot. It pays the per-shot cliff every guarded circuit pays, plus one evaluation per action and terminator. On the host statevector it pays one evolution per distinct outcome history. Fusion runs within a block and never across a boundary, so the loop body and the code around it fuse separately. dynamic/rus/{10,16} price a repeat-until-success loop at 1000 shots on 10 and 16 qubits.

Fusion Pipeline

Rewrites of the gate stream before execution, each pass gated on a qubit count. The count is the width of the buffer the backend sweeps: the density matrix holds n qubits as a 2n-qubit statevector, so it reaches each floor at half the circuit width (fuse_circuit_for_width in src/circuit/fusion.rs). Every pass returns Cow<Circuit> and stays Borrowed when it changes nothing, so an untouched circuit is never cloned.

flowchart TD
    IN[Input Circuit] --> PR["fuse_region_bodies (always): each guarded body through this same pipeline"]
    PR --> P0["cancel_self_inverse_pairs (always)"]
    P0 --> P0r["fuse_rzz (always): CX&middot;Rz&middot;CX to Rzz"]
    P0r --> D{"FusionProfile::Device?"}
    D -- yes --> PD["1q fusion and reorder (>=10q), 2q runs on one pair (>=12q)"]
    PD --> OUT
    D -- no --> P0b["fuse_batch_rzz (>=14q): N&times;Rzz to BatchRzz"]
    P0b --> G{"qubits >= MIN_QUBITS_FOR_FUSION (10)?"}
    G -- no --> OUT[Output Circuit]
    G -- yes --> P1["fuse_single_qubit_gates (>=10q)"]
    P1 --> P1r["reorder_1q_gates (>=10q)"]
    P1r --> P1c["cancel_self_inverse_pairs (>=10q)"]
    P1c --> P1f["fuse_single_qubit_gates re-fuse (>=10q)"]
    P1f --> P2q["fuse_2q_gates (>=12q): CX/CZ + adjacent 1q to Fused2q"]
    P2q --> P2qb["fuse_same_pair_2q_blocks (>=12q)"]
    P2qb --> S{"state past the last-level cache?"}
    S -- yes --> PS["plan_stages: tile and diagonal stages"]
    PS --> OUT
    S -- no --> P2["fuse_multi_1q_gates (>=14q) to MultiFused"]
    P2 --> P2qr["reorder_fused2q_into_tiles (>=12q)"]
    P2qr --> Pm2q["fuse_multi_2q_gates (>=12q) to Multi2q"]
    Pm2q --> Ppr["fuse_pauli_rot_batches (>=16q) to MultiPauliRot"]
    Ppr --> Pcp["fuse_controlled_phases (>=14q) to BatchPhase"]
    Pcp --> Pdb["fuse_diagonal_batch (>=14q) to DiagonalBatch"]
    Pdb --> Ppp["batch_post_phase_1q (>=14q; >=18 on the density matrix buffer)"]
    Ppp --> OUT

Threshold constants

ConstantValueRationale
MIN_QUBITS_FOR_FUSION10Below this, clone cost exceeds simulation savings
MIN_QUBITS_FOR_MULTI_FUSION14MultiFused tiling overhead vs benefit
MIN_QUBITS_FOR_DIAG_BATCH14Diagonal batch, cphase, and Rzz batching, and the 1q rebatch after phase fusion on a buffer as wide as the circuit (the statevector)
MIN_QUBITS_FOR_POST_PHASE_BATCH18The 1q rebatch after phase fusion on a wider buffer (the density matrix's 2n)
MIN_QUBITS_FOR_2Q_FUSION12QV and random sweeps make fewer memory passes from 12q
MIN_QUBITS_FOR_MULTI_2Q_FUSION12Same as 2q fusion
MIN_QUBITS_FOR_PAULI_ROT_BATCH16At 15q a parallel subcube pass has tiles for half of an eight-thread pool
Stage floorderived, 20 on an 8 MB L3First width whose statevector outgrows the last-level cache; 20 when the OS reports none, never below 16

Stage planner

Once the statevector outgrows the last-level cache every pass is a sweep of main memory, so plan_stages (src/circuit/fusion_stage.rs) replaces the batching passes from fuse_multi_1q_gates on. It splits the stream at measurements, resets, conditionals, regions, barriers, saves and gates no batch carries, then schedules each segment as stages over the dependency frontier. A stage is one gathered tile: the low multi_2q_low_bits qubits plus up to the Multi2q high budget of others. High qubits grow greedily from the frontier, each step adding the qubits that take the most moving gates per qubit added, ties going to the gate with the longest dependency chain behind it. Gates commute when both act diagonally on every qubit they share, so diagonal gates never block each other.

Each stage leaves as one existing batch: a Multi2q with every 1q gate folded into a 2q entry on its qubit, a MultiFused when it holds no 2q gate, or a MultiPauliRot, whose Z letters cost no tile slot. Diagonal gates ride in a tile when a later gate needs them. The rest wait for a diagonal stage (BatchRzz or DiagonalBatch), taken when no tile moves anything or when clearing them first doubles what the next tile moves. The schedule reads only the stream and the tile geometry, which comes from the hardware, not the Rayon pool, so results are bitwise equal across thread counts. The planner records provenance like the passes it replaces, so a PreparedCircuit replays its stages. The density matrix keeps the batching passes.

Device profile

Backend::fusion_profile picks the pipeline. The statevector picks FusionProfile::Device when a GPU is attached and the state reaches gpu::tiles::MIN_QUBITS (18). Every other backend, and the device below that width, keeps the host pipeline above. The device profile stops after the 1q passes and fuses 2q gates only in runs of at least two on one pair with a moving gate among them (quantum volume blocks), where the run's leading 1q gates fold in as well. A lone CX keeps its neighbours as 1q gates. Neither the batching passes nor the stage planner run.

The device lowers each run of gates between measurements, resets, conditionals, regions and saves itself (src/gpu/tiles.rs). 1q matrices, diagonals and antidiagonals, CX, swap and two-qubit diagonals become ops of apply_mixed_tile, and a planner built like the stage planner schedules them into shared-memory tiles of 11 qubits, one pass each. A dense 4x4 and every other gate launch on their own kernels. The stage planner's tiles would not serve the device: its Multi2q folds every 1q gate into a dense 4x4 entry, which the device launches one entry at a time. A dense 4x4 stays out of the mixed tile as well: on a card with a low FP64 rate it is compute bound and runs faster on its own kernel.

The lowering runs after binding and reads only the bound stream, so a PreparedCircuit captures and replays its plan under the profile of the backend it holds.

Mixed CPU tiles

The stage planner runs at fusion time and emits ordinary batch gates into the circuit. Mixed tiles run at apply time, inside the backend, over whatever stream fusion handed over: they regroup operations the batches left apart, without adding a gate variant.

Past the last-level cache floor, the CPU statevector lowers the fused instruction slice into a schedule of its own. A stage admits operations whose moving qubits fit one cache tile and whose dependencies are met. Diagonal qubits and Pauli Z letters outside the tile are constant within a subcube and take no tile slot. The planner examines at most four times the state width in skipped operations per scan, and in candidate seeds per growth step.

Homogeneous stages use the existing 1q, 2q, Pauli or diagonal batch kernels. Mixed stages gather once, execute their operations in order, and scatter once. Controlled X and swap keep their permutation operations. Measurements, resets, conditionals, regions, barriers and QFT blocks end a stage. No schedule enters the gate enum.

A statevector slice whose operations all lower to one batch kind (dense 1q, dense 2q or Pauli rotations) skips the schedule and applies its staged instructions directly, since the stage planner already batched that stream for the same kernel. The density matrix keeps its doubled schedule for every slice.

Across applications the backend keeps only stage indices and operation shapes, and reloads numerical payloads from the current slice each time. A changed state width, gate family or dependency mask rebuilds the schedule. Scheduling reads state width and cache geometry, not the Rayon pool width.

The density matrix schedules a doubled stream over its 2n-qubit buffer: ket gates on q+n, conjugated bra gates on q. Each register keeps circuit order internally, while commuting work from the other register can share a tile. An unsupported operation ends the segment and runs through the density matrix backend. The device path keeps its own fusion profile and kernels. The static density-matrix census accepts only supported gate streams. Unsupported kernels have their own ket, bra and conjugation passes and are excluded from that count.

QFT recognition

Before this pipeline runs, a backend with a native QftBlock kernel (the statevector, host or device) has recognize_qft_blocks (src/circuit/qft_recognition.rs) fold each expanded QFT back into one block, so a QFT parsed from OpenQASM runs as the FFT rather than as n^2 / 2 controlled phases. It matches every sequence qft_textbook_steps emits: forward or inverse, with or without the bit-reversal swaps, in either label order. The phases of one column may come in any order with either qubit as control, and the swaps in any order, so a decomposition that emits each column's phases from the nearest qubit outward, or puts the control on the other qubit, still folds. Each phase must equal e^{±iπ/2^d} to within 1e-12, so an approximate QFT stays as gates.

Only ranges the FFT runs natively fold: blocks starting at q[0] that span the register or cover at least 10 qubits (MIN_SUBRANGE_QFT_QUBITS). A narrower QFT stays as gates, which the tiled passes run in a sweep or two. The gates must be consecutive top-level instructions, so a QFT with another gate inside it, or on non-contiguous qubits, is left alone. The scan allocates nothing until it finds a match and returns the circuit borrowed when there is none. PRISM_NO_QFT_BLOCK turns off kernel and recognition together.

The kernel runs the DIF network over each 2^num amplitude chunk, with conjugate twiddles for the inverse, and reaches every form by adding a bit reversal of the chunk index before the network, after it, or both.

Payload capacities

The batched gates carry a lookup table sized at compile time, and the pass that emits them keeps the payload inside it. Both caps are declared on the payload (BatchRzzData::MAX_EDGES, BatchPhaseData::MAX_PHASES) and pinned to the kernel table shape by a compile-time assertion. The kernels also assert on entry in release builds, so a producer that outgrows a table fails loudly instead of dropping work.

PayloadCapProducer behavior past the cap
BatchRzz32 edgesfuse_batch_rzz splits the run into consecutive batches
BatchPhase40 entriesfuse_controlled_phases splits the chain into consecutive batches
DiagonalBatch4 tables of 10 qubitsfuse_diagonal_batch closes the run and opens a new one

Splitting the first two is sound because both hold mutually commuting diagonal terms. A repeated (control, target) pair folds into the existing entry. That keeps the BMI2 and fallback paths in agreement (the BMI2 kernel indexes one bit per distinct qubit, and a repeated target has no bit of its own) and bounds a chain by the qubit count.

A DiagonalBatch table covers the qubits its two-qubit entries join, so the cap is on those components, not the entry count: they must pack into DiagonalBatchData::MAX_GROUPS tables of MAX_QUBITS_PER_GROUP qubits. The producer runs the kernel's first-fit packing on every gate it admits and closes the run before a gate breaks it. A hand-built batch that does not fit still runs, element by element.

Diagonal batching

fuse_diagonal_batch takes every diagonal form the earlier passes leave behind: the named diagonal gates, a Cu with a diagonal matrix (crz as well as controlled phases), a diagonal Fused2q, an all-diagonal MultiFused or Multi2q, and every BatchPhase and BatchRzz. A diagonal two-qubit block enters as a phase on each qubit and one on |11>. A gate on no qubit of the open run is emitted ahead of it, so a layer of 1q gates elsewhere does not split the run, and a gate on one of its qubits closes it.

fuse_controlled_phases roots each chain on its control. A chain holding one phase whose target is also the target of another one-phase chain flushes with it as one BatchPhase rooted on that target, since a controlled phase is symmetric in its qubits. The controlled powers of phase estimation all share the eigenstate qubit and run as one batch.

Plan capture and replay

PreparedCircuit records the block structure these passes choose and rebuilds only the matrices a new binding changes, under guards that fall back to the full pipeline when a binding flips a decision read from a matrix. The recipes and guards are on Parameters, Binding and Gradients.

Fusion cost against apply cost

Fusion cost tracks instruction count and is nearly flat in qubit count, while gate application is 2^n. For hardware_efficient_ansatz(n, 5, seed) on this project's reference host, fusion is about 22% of a run at 12 qubits and about 0.3% at 20.

From 16 qubits fusion is off the hot path, and these passes are written for correctness and clarity rather than their own runtime. Below that, plan capture amortizes it.

Simulation Engine and Dispatch

Backend trait

Backend in src/backend/mod.rs is sealed: only the crate's own backends implement it, so a method can be added without a breaking release. Six methods are required and about 35 more have defaults. The sketch shows the required set, and the rustdoc page lists every method.

#![allow(unused)]
fn main() {
pub trait Backend: sealed::Sealed {
    fn name(&self) -> &'static str;
    fn init(&mut self, num_qubits: usize, num_classical_bits: usize) -> Result<()>;
    fn apply(&mut self, instruction: &Instruction) -> Result<()>;
    fn classical_results(&self) -> &[bool];
    fn probabilities(&self) -> Result<Vec<f64>>;
    fn num_qubits(&self) -> usize;

    // Defaulted: provenance (resolved, exactness, placement, bond_report), start
    // states, batch and region apply, fusion profile, native sampling, Pauli
    // expectations, reduced density matrices, entropy, overlap, reset.
}
}

Contract: init before apply. Instructions arrive in circuit order. Measurement is destructive. Results are deterministic for a given RNG seed.

Entry points

The orchestration layer is src/sim/, with the builder in src/sim/simulate.rs. simulate(&circuit) returns a Simulate builder; .backend(kind), .noise(&model), .limits(limits), .initial_state(..) and .require_exact() configure it, .seed(seed) arms it, and one terminal runs it.

Terminal or functionReturns
run()RunOutcome: probabilities, classical bits, save records, metadata
shots(n), sample_counts(n)Per-shot records, or a histogram
marginals()P(1) per qubit
expectation_values(obs)⟨P_k⟩ per Pauli string
observable_expectation(h), observable_variance(h)Weighted Pauli sum, see weighted observables
expectation_gradient(h, params)⟨H⟩ and the adjoint gradient
expectation_gradient_shift(h, params)⟨H⟩ and the parameter shift gradient
reduced_density_matrix(qubits), entanglement_entropy(qubits), overlap(other)State diagnostics, see Backends
state_vector(), probabilities_of(qubits)Dense amplitudes, or a marginal distribution
plan(query)The route a terminal would take, without running it; see query route inspection
run_on(backend, circuit), run_on_state(backend, circuit, amps)A run on a backend the caller built, from `
sim::run_batch(circuits, kind, seed)One result per circuit, holding one backend where widths match
run_qasm(qasm, seed)Parse and run
simulate_program(&program)The builder for a DynamicProgram; see Dynamic Programs

RunOutcome::probabilities is None only when the backend has no dense probability terminal for the circuit: sparse, MPS, stabilizer, factored or product above PRISM_MAX_PROB_QUBITS, or a register too wide to index. A statevector or tensor network run above that cap is an error naming it, since the register already fits the state. Other extraction failures propagate as errors too.

marginals() needs a direct Pauli marginal route or backend probabilities, and returns BackendUnsupported when it has neither rather than fabricating uniform marginals. The stochastic and deterministic Pauli backends accept only unitary circuits of Clifford gates and Pauli rotations, with no measurement, reset or conditional. T, Tdg, Rz, P, Rzz and multi-qubit PauliRot branch natively, and the deterministic engine also branches on Rx and Ry. The stochastic engine lowers those two to Clifford conjugation around one Rz. Fused matrices lower to the named gate they equal up to phase, or to an Euler triple, and a Cu with a diagonal or Pauli target lowers to Z rotations and Cliffords. Automatic dispatch sends only Clifford+T circuits to SPD (rotations at multiples of pi/4 count as Clifford or T), so arbitrary angles reach the Pauli engines only by explicit selection.

Noise across the terminals

The selected backend, not the terminal, fixes how a noise model is applied. How a model compiles into events is on Noise Compilation.

Backends holding a pure state per shot average trajectories: each shot evolves the circuit again with sampled channels, and a distribution converges as 1/sqrt(shots). Only shots and sample_counts take that route, since one trajectory is not an answer to run, marginals or expectation_values.

The density matrix holds the mixture, so shots means one exact evolution followed by a draw per shot. Every terminal reads that evolution: run and marginals return the exact noisy distribution, expectation_values the exact Tr(rho P), and shots and sample_counts carry sampling noise but no trajectory variance. Readout error applies to drawn outcomes on its own RNG stream, so run and marginals reject a model carrying it rather than return a distribution the sampled terminals would contradict.

The mixture holds every measurement branch and never chooses one, so a circuit with mid-circuit measurement or classical conditioning is rejected on this route, with or without noise: the outcome a later gate depends on was never fixed. The check sits on the evolution, so density_matrix_expectation_values refuses the same circuits as the Simulate terminals, and they stay on trajectory averaging. The density matrix is also left out of the branching families of tests/integration/conformance_matrix.rs, where it serves as the mixture oracle.

expectation_gradient rejects a noise model on every backend, because the adjoint method backpropagates through a pure state. expectation_gradient_shift accepts one on the density matrix kinds and on BackendKind::PauliPath: the channels do not depend on the shifted angle, so the shift rule holds. On the density matrix each of the 1 + 2 * links evaluations reads the exact mixture; the Pauli path applies each channel's adjoint and is approximate only where its budget truncates. Other backends reject the pair, naming the density matrix.

Result provenance

Every terminal's result carries a RunMetadata. The Capability and Support Matrix lists its fields and what Approximate means, and Backends how a backend fills them.

require_exact() resolves the route from the circuit and errors before allocating. Exactness depends on route and circuit together: an oversize circuit of diagonal and permutation gates holds one basis state, so its MPS never leaves bond 1 and is accepted. Sparse Pauli dynamics truncates on coefficient magnitudes it learns only while propagating, so that route is caught by a second check on the finished result. Both checks run in every terminal.

Auto-dispatch decision tree

BackendKind::Auto resolves in src/sim/route.rs and src/sim/dispatch.rs (plan_probability_route, then select_auto_backend_choice). Terminal routes come first; the rest of the tree is the state route every terminal falls back to.

flowchart TD
    A[BackendKind::Auto] --> Q{"Terminal route applies?<br/>(table below)"}
    Q -- yes --> QR["Compiled Clifford sampler, stabilizer rank,<br/>SPD or tensor contraction"]
    Q -- no --> D{"Independent blocks, 8+ qubits,<br/>largest block 3+ below n?"}
    D -- "Clifford, 16+ qubits, a block of 2+" --> FS[FactoredStabilizer]
    D -- yes --> DEC["Decomposed: each block re-enters the tree"]
    D -- no --> T{"Not all Clifford, fits the cap,<br/>Clifford prefix of max(2n, 16) gates?"}
    T -- yes --> TC["Stabilizer prefix, then Statevector tail"]
    T -- no --> E{Entangling gates?}
    E -- none --> PS["ProductState, O(n)"]
    E -- yes --> CL{All Clifford?}
    CL -- yes --> STB["Stabilizer, O(n^2)"]
    CL -- no --> MEM{Above the statevector cap?}
    MEM -- "yes, sparse friendly or at most 128 entries" --> SPR["Sparse, O(k)"]
    MEM -- "yes, otherwise" --> MPS["MPS, bond dim 256"]
    MEM -- no --> IND{"Some qubits independent?"}
    IND -- yes --> FAC["Factored"]
    IND -- no --> SV["Statevector"]

The statevector cap is half of physical memory, about 29 qubits on a 16 GiB host, and PRISM_MAX_SV_QUBITS overrides it. Backends holds the derivation and the other caps.

A circuit with no entangling gate at 8 qubits or more meets the block split first and runs as one product state block per qubit. Shots skip the split and sample the product state directly (Compiled Samplers).

Past the cap, dispatch runs the gates on a sparse map and takes it when the map never holds more than 128 entries, as a W state does. A sparse gate costs about 8 ns per entry and an MPS gate about 2 us even at bond 2, so the MPS wins past that on a circuit that barely entangles. A circuit whose gates only permute or phase basis states stays on one entry and skips the probe.

Choosing a Backend is the user-facing version.

Routes the tree does not show

Each of these is tested before the state route, with its own constants in src/sim/dispatch.rs, src/sim/route.rs and src/sim/mod.rs:

RouteTaken when
Compiled Clifford samplerShots on a Clifford circuit whose measurements are terminal or rewrite to terminal; see Compiled Samplers
Clifford register (stabilizer rank)Shots on a Clifford+T circuit with terminal measurements only and no reset, at least 16 qubits, when the register splits into parts the sampler takes (each part at most 26 qubits whole, or cut in two sides of at most 20, up to 64 register qubits) and the work to build their tables is below the dense run's. A register pass over 2^k amplitudes costs 25 statevector instruction-amplitudes per amplitude, against the instruction count times 2^n, summed over independent blocks. When a block passes the statevector cap, a register that splits is taken whatever the cap, as long as its parts hold no more amplitudes than a statevector at the process cap. A bound from the T count decides circuits whose register fits 20 qubits; the rest take a tableau dry run that plans the split
Deferred Clifford register (stabilizer rank)Shots on a Clifford+T circuit with a mid-circuit measurement, a guard or a reset whose measurements move to the end: every guard applies a Pauli and reads a parity of measured bits, and a measured qubit used again copies its record onto a fresh qubit. The register tests above apply to the rewritten circuit, with the dense side priced as one run per outcome history the statevector walk can reach, at most the shot count
Stabilizer rank branchesThe same shots past the statevector cap when the measurements stay in place, up to 6 T gates. Under the cap such a circuit takes the statevector walk, and past 6 T gates the tree
Clifford register parts (stabilizer rank)An expectation or marginals terminal, or probabilities_of on at most 10 qubits, on a unitary Clifford+T circuit. Each observable pulled through the Clifford is a product of one factor per part, the register qubits that excess T rotations link: a lone qubit's Bloch vector, a dense array of the part up to 20 qubits, or the observable propagated back through up to 20 excess rotations of the part, whichever costs less. From 12 qubits under the statevector cap when the tableau, priced at (instructions + t n) n letter updates, plus the parts cost less than the dense run, at the register's 25 statevector instruction-amplitudes per unit; above the cap whenever every touched part has an exact engine
Deterministic Pauli marginalsA marginals terminal on a unitary Clifford+T circuit of at least 12 qubits that the register parts decline. The propagation is exact, and at or below the statevector cap it hands over to the tree once its summed term count passes the dense run's amplitude updates divided by 64
Deterministic Pauli expectationsAn expectation terminal on a Clifford circuit
Scalar tensor contractionAn expectation or marginals terminal on a unitary circuit whose bounded greedy plan for every observable stays under a peak bound. From 18 qubits under the statevector cap the bound is 2^12 elements. Above the cap it is the tensor network peak cap (PRISM_MAX_TN_PEAK_QUBITS), and the plan must also cost less than an estimate of the MPS run Auto would take

Each answers where the tree would have said statevector or stabilizer, so the backend a result reports (what a backend reports) is the only reliable record of what ran.

marginals() on a route that goes straight to the resolved backend's observable path is not held to the dense output cap: a Clifford circuit with measurements reads its marginals off the tableau at any width, and the dense statevector reads them off its amplitudes without building the 2^n distribution. It falls back to the dense distribution on a circuit that splits into independent blocks, unless those blocks run as product states, and under a noise model, where the mixture is read densely and the density-matrix cap applies.

Parity ancillas on the walk

Auto shots that reach the mid-circuit walk, after the compiled sampler, the Clifford register and the temporal Clifford prefix have declined, first drop their parity ancillas (src/circuit/parity_ancilla.rs). A qubit a qualifies when every instruction touching it reads

( CX(d -> a) | X a )*   Measure a -> bit   ( Reset a | if (bit) x a )?

repeated, the closing group optional only on the last span, and each source d takes nothing but CX gates it controls from its pickup to the measurement. Each span becomes a measurement of the parity of its sources (the X a count inverts it): the sources fan onto the lowest one with CX gates, it is measured into the same bit, and the fan is undone. The ancilla leaves the register and the other qubits keep their order, so the walk, the independence analysis and Simulate::plan all see the smaller width. Any other gate, guard or region on the ancilla, an empty parity, a reset with no measurement, or a second measurement with no reset keeps that ancilla; a save keeps them all. Explicit backends, noisy runs, start states and dynamic programs never reach the rewrite.

Auto dispatch policy

Routing constants are static values in src/sim/dispatch.rs, except the dense memory caps, which src/backend/memory.rs derives from detected physical memory.

Capability limits are detected: a wrong one means a failed allocation or a swapping host, and physical memory is cheap to read and hard to misread. PRISM_MAX_SV_QUBITS and its siblings override the derivation.

Performance thresholds stay static, with an environment override where the value is worth sweeping. The device crossover is the worked case: a default of 14 qubits with PRISM_GPU_MIN_QUBITS beside it, not a figure read off the installed card. Detecting cache geometry or device throughput wrongly is a silent slowdown no test catches, while a wrong static default is the same slowdown on every host and shows in one measurement. Runtime detection waits for a host that can validate it.

Changing a threshold takes a measurement. The auto/crossover group under benches/circuits/ holds both arms either side of the factored-stabilizer floor, the exact stabilizer-rank budget and the Pauli marginals floor. The fusion floors and the parallel threshold have no such pair, since nothing selects between them at run time: moving one means building both values and comparing the binaries.

Start states other than |0...0>

Simulate::initial_state bypasses the tree. Every branch of it reads circuit structure and is sound only from the all-zero start: a Clifford circuit yields a stabilizer state only from a stabilizer input, the product state and subsystem split assume an unentangled input, and the Pauli engines propagate observables back to |0...0>. Any of them on an arbitrary start returns a wrong answer, not an error, so initial_state_plan in src/sim/dispatch.rs constrains the route instead:

  • Auto resolves to the statevector, with no memory check, since a caller holding 2^n amplitudes can already afford the dense state.
  • StatevectorDistributed starts the sharded statevector from it; every rank receives the full vector and keeps the slice its rank bits select.
  • DensityMatrix takes it as the pure mixture |psi><psi|.
  • Every other kind returns IncompatibleBackend.

The vector is validated first: 2^n entries for the circuit's n qubits, all finite, unit norm to 1e-9. An unnormalized vector is rejected, not rescaled, because the load resets the statevector's deferred normalization factor to 1 and a silent rescale would hide the error inside it.

Simulate::initial_density_matrix is the mixed-state counterpart. It takes the 4^n buffer DensityMatrixBackend::density_matrix exports, row-major 2^n x 2^n with qubit 0 the least significant bit of both indices, so a mixture can be stored between runs or composed from two evolutions. Only DensityMatrix and DensityMatrixGpu accept one. initial_state_plan declines every other kind by name, Auto included, since automatic dispatch never selects the density matrix. Backend::init_from_density_matrix validates before sizing the register: 4^n entries, all finite, each entry pair Hermitian to 1e-12 (scaled by the larger magnitude once that exceeds 1), and unit trace to 1e-9, with InvalidParameter naming the failed check. Positive semidefiniteness is not checked, because that needs an eigendecomposition the backend does not carry, so a mixture with a negative eigenvalue evolves without complaint. The host backend takes ownership of the buffer, and the device uploads it in one transfer instead of forming the outer product of a pure state.

Subsystem decomposition

Union-find finds independent qubit groups in O(n·α(n)), and each block runs separately. Under Auto each block picks its own backend; under an explicit kind every block runs that kind. The merged result reports Decomposed and lists each block's engine in RunMetadata::blocks. Clifford-only circuits skip the split on an explicit FactoredStabilizer, and under Auto from 16 qubits once a block holds two or more, because that backend already keeps one tableau per cluster and merges and splits them as the circuit runs. Results merge lazily through Probabilities::Factored, a Kronecker product evaluated per element in O(K). The O(2^N) dense vector is built only on request.

Blocks run in parallel under Rayon only when every block is below 15 qubits (src/sim/decomposed.rs), so block threads do not oversubscribe the kernels' own parallelism.

Temporal Clifford decomposition

Under Auto, a circuit that is not Clifford only and opens with a Clifford prefix of at least max(2n, 16) gates (min_clifford_prefix_gates in src/sim/dispatch.rs) runs that prefix on the stabilizer backend and exports the state to the statevector for the tail. The saving is the dense cost of the prefix, not memory: the route requires the register to fit the statevector cap.

Weighted observables

PauliObservable (src/sim/observable.rs) carries a weighted Pauli sum H = Σ c_k P_k in the (f64, Vec<PauliTerm>) term shape the gradient surface takes. Terms are canonical: factors sorted by qubit, identical strings merged. Qubit-wise commuting (QWC) groups come from greedy first-fit-decreasing coloring, cached in the observable and invalidated on mutation. Two strings qubit-wise commute when every shared qubit carries the same axis, so a group has one axis per qubit it touches.

observable_expectation computes Var(H_g) = ⟨H_g²⟩ - ⟨H_g⟩² per group on the statevector family. Small groups share one batched traversal (pauli_expectations_from_masks). Two strings in a QWC group multiply without a phase, so each P_i P_j is another Pauli string, and a small group's ⟨H_g²⟩ expands into pairwise product masks appended to the traversal that serves the term means.

A group past the pair budget (MAX_PAIR_MASKS_PER_GROUP, set where the quadratic expansion would cost more than a state sweep) takes one moment pass of its own: on the state as run when the group is Z only, otherwise on a copy rotated by H on qubits assigned X and by Sdg then H on qubits assigned Y, after which members are Z strings with a plus sign. Both moments come from that pass. h(j) is built 64 indices at a time: with the high index bits fixed, each member reduces to a signed coefficient on its low bit pattern, and a Walsh-Hadamard transform over those patterns gives h across the block, at one scalar step per member per block and six butterflies per index.

The pass is a fallback because it loses on molecular shapes: a 2000-string Jordan-Wigner Hamiltonian groups into about 850 groups of mean size 2.3, and a copy, rotation and sweep per group costs more than the single ungrouped traversal that already yields the mean. Grouping buys the variance.

The reported variance is Σ_g Var(H_g): the variance of a grouped estimate drawing one shot per group, and the input to shot allocation through the vector per group. It excludes covariances across groups, so it equals Var(H) only when one group covers every term. Routes without the grouped evaluator (Clifford and SPD, the native paths of other backends, a run with a noise model or start state) report the weighted mean with no variance.

Expectation-value gradients

expectation_gradient runs the adjoint method on the statevector at a cost independent of the parameter count. expectation_gradient_shift runs 1 + 2 * links forward evaluations on any backend with an observable path, the density matrix and noise models included. Both read the links a Parameters table records. The algorithms, the gate set and the binding they share are on Parameters, Binding and Gradients.

Backend dispatch variants

The BackendKind variants outside feature gates. AutoGpu, StatevectorGpu, DensityMatrixGpu and StabilizerGpu sit behind gpu (see the GPU guide), and StatevectorDistributed behind distributed.

VariantBackendSelection
AutoDecision tree (see above)Default
StatevectorFull state vectorExplicit
StabilizerAaronson-Gottesman tableauExplicit or auto (all Clifford)
FactoredStabilizerOne tableau per clusterExplicit or auto (large independent Clifford blocks)
SparseHash map stateExplicit or auto (above the cap, sparse friendly or at most 128 entries)
Mps { max_bond_dim }Matrix product stateExplicit or auto (above the cap)
ProductStateProduct of qubit statesExplicit or auto (no entangling gates)
TensorNetworkDeferred contractionExplicit, or auto for an expectation or marginals terminal (see the routes table)
TensorNetworkBounded { tolerance }Deferred contraction with truncation past the peak capExplicit
FactoredDynamic split stateExplicit or auto (partial independence)
DensityMatrixExact mixed stateExplicit
StabilizerRankWeighted stabilizer sum, or a Clifford tableau over a dense T register for terminal shotsExplicit, or auto for shots (see the routes table); never auto for probabilities
StochasticPauli { num_samples }SPPExplicit
DeterministicPauli { truncation }SPDExplicit, or auto for marginals and expectations (see the routes table)
PauliPath { epsilon, max_terms }Noisy Heisenberg Pauli sumExplicit

Query route inspection

Simulate::plan(Query) and terminal execution share the shot, noisy trajectory, marginal, expectation and diagnostic decisions in sim::route. A decision holds backend plans and bounded tensor contraction plans, which execution consumes. Backend sampling capabilities are readable before a backend is constructed.

The report separates the selected route from runtime alternatives: bounded SPD work can decline at execution, and soft GPU initialization can lose device residency. Plan::fallbacks declares those possibilities and RunMetadata::reason records one actually taken. would_fail reports predictable failures, and malformed query inputs return an error. Exactness checks per query admit exact marginal and expectation routes even where the full-state tree would choose MPS.

Gradient queries carry their Hamiltonian and parameter links. Parameter shift plans reuse the prepared family decision when execution does, and report each evaluation in baseline, plus, minus order. Deterministic differences between shifted evaluations are not reported as runtime fallbacks.

Backends

PRISM-Q ships ten CPU backends: statevector, stabilizer, factored stabilizer, sparse, MPS, product state, tensor network, factored, density matrix and MPO. The statevector, stabilizer and density matrix also run on CUDA (with opt-in cuSOLVER SVD offload for MPS), and the distributed feature adds a statevector sharded across MPI ranks. Four Clifford+T engines (stabilizer rank, SPP, SPD and the Pauli path) hold no state and sit beside the backends. The simulation engine picks a backend unless the caller names one, and never picks the density matrix, MPO or distributed backend. Choosing a Backend covers the same ground by task.

Scroll wide circuit figures horizontally, or focus them and use the arrow keys. Open the full SVG for gate tooltips; rotation angles are in radians.

A Hadamard followed by a chain of four controlled X gates across five qubits.
GHZ preparation uses Clifford gates and routes to a stabilizer backend. Open full SVG.

Reset semantics

reset is the channel rho -> |0⟩⟨0| ⊗ tr_q rho on every backend: the qubit is traced out and replaced by |0⟩, leaving the rest of the register in the mixture the trace produces. Projecting onto |0⟩ and renormalizing agrees with it only when the qubit is unentangled; otherwise projection also collapses its partners into the branch correlated with |0⟩. Resetting qubit 1 of a Bell pair leaves ⟨Z0⟩ = 0 under the channel and ⟨Z0⟩ = 1 under projection.

A pure-state backend runs one trajectory instead: sample the outcome, collapse onto it, and apply X when it is 1, consuming one draw from its RNG stream. Averaged over shots that is the channel. The density matrix applies the channel directly, with no draw. tests/integration/reset_channel.rs pins the contract across backends.

Memory budget

A backend whose state would not fit returns PrismError::ResourceLimit instead of handing work to another. The error names the backend, the requirement, the cap, the layer that set the cap, and the Limits field and environment variable that override it. BackendKind::Auto chooses from circuit structure before any backend is constructed. The check lives in Backend::init, so run_on gets the same guard as simulate.

The statevector cap comes from detected physical memory: half of it is the budget, and the cap is the widest register whose 2^n Complex64 amplitudes fit, so 29 qubits on a 16 GiB host and 30 on 32 GiB. PRISM_MAX_SV_QUBITS overrides it with a qubit count, and an unparseable value warns and leaves detection in charge rather than disabling the cap. When detection itself fails every cap is disabled, with a warning on stderr, since a guessed budget is worse than an unknown one: a register too wide for the machine then aborts on allocation rather than routing to another backend. src/backend/memory.rs holds the derivation and the other dense caps that share it.

CapLimits field and variableDefault
Statevector statemax_statevector_qubits, PRISM_MAX_SV_QUBITSLargest 2^n Complex64 state fitting half of detected physical memory
Density-matrix statemax_density_matrix_qubits, PRISM_MAX_DM_QUBITS, bounded by PRISM_MAX_SV_QUBITSfloor(cap_sv / 2), since a density matrix of n qubits is a 2n-qubit statevector
Dense probability outputmax_probability_qubits, PRISM_MAX_PROB_QUBITSSame budget over f64
Dense statevector exportmax_export_qubits, PRISM_MAX_EXPORT_QUBITSSame budget over Complex64
Dense outcome samplingenvironment only, PRISM_MAX_DENSE_OUTCOME_BITSSame budget over two f64 per outcome
Sparse entry countmax_sparse_qubits, PRISM_MAX_SPARSE_QUBITS (the map holds at most 2^q entries)Same budget at 64 bytes per entry across the double-buffered maps
Factored merged-block widthmax_factored_merge_qubits, PRISM_MAX_FACTORED_MERGE_QUBITSSame budget over Complex64
MPS gate workspacemax_mps_workspace_qubits, PRISM_MAX_MPS_WORKSPACE_QUBITS (at most 2^q amplitudes of live contraction buffers)Same budget over Complex64
Tensor-network peak intermediatemax_tn_peak_qubits, PRISM_MAX_TN_PEAK_QUBITS (at most 2^q elements in the largest planned intermediate, summed over the slices running at once)Same budget over Complex64
Factored stabilizer merged-cluster widthmax_stabilizer_cluster_qubits, PRISM_MAX_STABILIZER_CLUSTER_QUBITSWidest joint tableau fitting the same budget, counted as 2n + 1 rows of 2 * ceil(n / 64) words and halved to cover the peak while both source tableaux are still live

Each cap resolves through four layers, highest first: the request's Limits (Simulate::limits), the process default (set_default_limits), the environment, and detection. A layer that sets memory_budget_bytes re-derives every cap from that budget and discards the per-cap values below it, so a wide PRISM_MAX_SV_QUBITS cannot lift a cap past a tenant budget. Caps resolve once per request and travel with the backend. No gate kernel reads them.

The five growth caps (sparse, factored, MPS, tensor network, factored stabilizer) are independent of PRISM_MAX_SV_QUBITS. Those backends exist to run above the statevector cap, so lowering it to steer routing must not shrink what they hold. Their defaults come from the same detected budget. The factored stabilizer cap is the only one that is not a 2^n amplitude count: a cluster costs O(n^2 / 64) words, and a dense cap would hold it to a qubit ceiling Clifford circuits pass routinely.

The density-matrix cap is the tighter of its own override and half the statevector cap, computed in one place so dispatch validation and the init guard agree. Raising PRISM_MAX_DM_QUBITS past that bound needs PRISM_MAX_SV_QUBITS raised too, and the rejection says so, naming the density matrix rather than the statevector it allocates internally.

Parallel noisy trajectories are the one path holding several states: each Rayon thread runs its own backend, so peak memory is threads * state(n). The path is limited to circuits below 14 qubits; above that, trajectories run serially under the ordinary cap. Pauli-noise runs grouped by error pattern follow the same rule and add a pattern table plus 16 bytes a shot, with no 2^n outcome table. Damping runs sharing a no-jump prefix hold a walked state beside each shot state, so above the split width they run only where two states fit. The distributed statevector runs trajectories serially at every width, one slice per rank re-initialized per shot, and groups no error patterns.

Three backends grow after init, and each checks before allocating:

  • a factored merge checks the merged block width against the merge cap;
  • the sparse map checks a branching gate's worst fan-out against the entry cap, so a rejection can fire one gate early on a state that would have deduplicated below it;
  • MPS gate application checks its live contraction buffers against the workspace cap. That bounds the workspace, not max_bond_dim: a large bond cap is fine while bonds stay small.

Statevector

Full-state simulation in a flat Vec<Complex64> of 2^n amplitudes. The primary backend up to the memory cap, 29 qubits on a 16 GiB host.

Gate kernels use enum dispatch with specialized routines for CX, CZ, SWAP, Cu, MCU, Rzz, BatchRzz, BatchPhase, DiagonalBatch, MultiFused and PauliRot. PauliRot is one pass over (j, j ^ xmask) pairs for exp(-i θ P / 2), or a parity-phase sweep for a Z-only string; backends without the kernel receive the CNOT-ladder lowering from expand_pauli_rotations. Single-qubit gates go through PreparedGate1q with FMA SIMD.

MultiFused runs a tiled kernel whose tile sizes come from the cache topology the OS reports (see the performance guide), with a cheaper path for an all-diagonal batch.

Rayon parallelism starts at 15 qubits with par_chunks_mut and MIN_PAR_ELEMS = 4096 per task. BMI2 _pext_u64 speeds BatchPhase, BatchRzz and DiagonalBatch LUT indexing.

Normalization is deferred: pending_norm accumulates the factors a measurement collapse or a no-jump damping branch would rescale by, instead of sweeping the state each time.

Stabilizer

Aaronson-Gottesman bit-packed tableau for Clifford circuits, O(n²) time and space, scaling to thousands of qubits. Kernels use wordwise bit operations and popcount for phases. Supports H, S, Sdg, SX, SXdg, X, Y, Z, Id, CX, CZ, SWAP, measurement, reset and classical conditionals. Destabilizer rows materialize lazily, when probabilities are requested.

On 256 qubits and up, a run of Clifford gates with at least one cross-word two-qubit gate per tableau word moves to a column-major copy of the gate rows: one 64x64 bit-block transpose each way, and each gate updates its qubits' columns, O(n/64) words, instead of a pass over every row. The run ends at the first measurement, reset, region or non-Clifford instruction.

Probability extraction is coset enumeration with GF(2) Gaussian elimination, O(2^k) in the number k of non-diagonal generators rather than O(2^n).

export_tableau returns the rows as (words, phases) and init_from_tableau accepts the same pair, for a warm start or a checkpoint. Packing: 2n + 1 rows of 2 * ceil(n / 64) u64 words, destabilizer rows 0..n, stabilizer rows n..2n, then a scratch row the importer ignores. Each row is its X words then its Z words, with qubit q at bit q % 64 of word q / 64, and phases[r] is true when row r carries sign -1. The import checks lengths and that destabilizer i anticommutes with stabilizer i, nothing more: rows that break the rest of the commutation structure give wrong outcomes silently. The random stream restarts from the importing backend's seed. The factored stabilizer imports the pair as one cluster, held to the merged-cluster cap, and exports every cluster into the joint layout.

Factored Stabilizer

FactoredStabilizerBackend keeps one tableau per cluster, starting at one qubit per cluster. A 2q gate across clusters merges their tableaux; measurement and reset can split independent tableaux apart again, so product structure never pays for the joint tableau. Auto takes it for Clifford circuits of at least 16 qubits that split into blocks.

Sparse

FxHashMap (the crate's multiply-xor hasher) keyed by u64 up to 64 qubits and u128 up to 128 qubits for states with few non-zero amplitudes, O(k) memory. After gates that can shrink or cancel amplitudes, entries with |a|² at or below a pruning threshold (1e-28, roundoff level) are removed and the rest rescaled to keep the norm. A run with the threshold raised above the default reports Approximate with a fidelity bound from the dropped weight. Dense Gate::Unitary gates up to four qubits act directly on the sparse map.

An entry costs about 16 times a dense amplitude, so a state holding more than roughly a sixteenth of its basis runs slower than a dense vector of the same width. There is no mid-run handoff to the statevector: an explicitly selected sparse run on a densifying circuit degrades in place. Automatic dispatch picks this backend only above the statevector cap, and a run that branches past the entry cap rejects the gate. Circuits wider than 128 qubits are rejected at init, and automatic dispatch sends them to MPS.

MPS (Matrix Product State)

Chain of rank-3 tensors with adaptive bond dimension (default max 256), O(n·χ²) memory. Single-qubit gates absorb with FMA SIMD over bond-dimension slices. Two-qubit gates contract adjacent sites, apply, and SVD-truncate back; non-adjacent gates route through SWAP chains. Gauge moves use CholeskyQR2 when well conditioned and blocked Householder QR otherwise. Two-qubit splits bypass SVD via a shifted Cholesky full-rank check on unsaturated bonds, use one-sided Gram eigendecomposition where singular value separation allows, and fall back to faer SVD (m×n ≥ 256), opt-in cuSOLVER GPU offload (gpu feature) or Jacobi sweeps below.

A cut that can reach the bond cap first moves the orthogonality center to the cut, at any bond, so the discarded singular weight is the state's 2-norm error. A threshold cut does the same once any bond reaches 128. Below that, a threshold cut runs ungauged and treats drops under four machine epsilons of the largest value as rounding; one that would drop a larger value is thrown away and made again in gauge. Once a center is recorded, every later two-qubit gate keeps it.

Product State

Per-qubit [Complex64; 2] storage, O(n) memory, O(1) per single-qubit gate. Rejects entangling gates and is selected automatically for circuits with no 2q gates.

Shots and Pauli expectations read the per-qubit states instead of a 2^n probability vector, so both stay O(n) at widths no dense route reaches (Sampling Architecture).

Tensor Network

Deferred contraction planned on metadata: a greedy min-size pass, with seeded restarts when its peak intermediate grows large, picks the pair order. Gates append tensors, and contraction happens at probability extraction, where PRISM_MAX_PROB_QUBITS guards the dense readout and an explicit run past it errors naming the cap rather than reporting probabilities: None.

Every contraction checks its planned peak intermediate against PRISM_MAX_TN_PEAK_QUBITS before allocating. A plan over the cap is sliced and stays exact, holding no more memory than an unsliced run. Only a plan still over the cap at PRISM_MAX_TN_SLICES assignments is rejected, naming the cap. BackendKind::TensorNetworkBounded { tolerance } truncates before it slices, with the same first-order bound as the MPS; the Capability and Support Matrix gives both kinds' contract.

Measurement and reset draw from the single-qubit reduced density matrix and absorb the renormalizing projector into the tensor holding the measured qubit's output leg, so mid-circuit measurement has no width ceiling and the tensor count does not grow across measurements.

A one-qubit reduced density matrix and a Pauli expectation contract the network against its conjugate, so they cost what the doubled network costs. An identity factor is a closed leg: a weight-k observable adds k tensors, not n.

The trajectory engine draws general noise from the one- and two-qubit reductions, so amplitude damping, phase damping, thermal relaxation and custom Kraus channels on one or two qubits run here under explicit dispatch. The two-qubit reduction is the same doubled contraction with both qubits' ket and bra legs left open.

Factored

Starts with n independent 1-qubit states and merges by tensor product only when a 2q gate bridges groups. Sub-states of 15 qubits or more use the statevector's parallel kernels. Selected when subsystem decomposition detects partial independence.

Density Matrix

Exact mixed-state evolution. The density operator rho for n qubits is a 4^n Complex64 buffer, row-major: index (r << n) | c holds ⟨r|rho|c⟩. That is a 2n-qubit statevector whose high n qubits index the ket (row) and low n the bra (column), so U rho U^dagger is two statevector passes: U on the ket register, and the gate's conjugate form on the bra register, or a conjugation of the buffer around the pass for a variant with no conjugate form.

Rzz and the batched diagonal families (BatchPhase, BatchRzz, DiagonalBatch) take one pass per sandwich over a combined table, and a MultiFused or Multi2q block runs its ket constituents and their bra conjugates through the statevector tiled kernels together.

Memory is 16 * 4^n bytes: about 14 qubits on a 16 GiB host and 15 on 32 GiB (PRISM_MAX_DM_QUBITS moves it within the statevector budget). With a device attached (BackendKind::DensityMatrixGpu, or with_gpu on the backend) the buffer lives in VRAM, budgeted against free memory at init. An 11 GiB card holds 14 qubits, so the device is for throughput, not width. Auto and AutoGpu never select either kind, and the device kind has no host fallback.

With a noise model attached it is the exact route for every Simulate terminal that reads a mixture. Four decline because they need a pure state: the adjoint gradient, which walks one backward, and state_vector, overlap and entanglement_entropy, whose answers a mixture does not define. run and marginals reject a model carrying readout error and point at sample_counts. Noise across the terminals has the full rules.

MPO (Matrix Product Operator)

Mixed-state tensor train in the orthonormal Pauli basis {I, X, Y, Z} / sqrt(2), selected explicitly via BackendKind::Mpo { max_bond_dim }. Every Hermitian density operator has real coordinates in this basis, so each site stores a real f64 rank-3 tensor of shape (bond_left, 4, bond_right) in O(n·χ²) memory. Unitary gates, Reset, and memoryless one- and two-qubit noise channels act through real 4x4 and 16x16 Pauli transfer matrices; non-adjacent two-qubit operations route via virtual SWAP chains.

MPO targets noisy 1D and weakly entangled circuits past the dense DensityMatrix qubit ceiling (14 to 100+ qubits) where dissipation bounds the operator Schmidt rank. It answers expectation values, marginals, reduced density matrices and conditional Born sampling natively without forming a 4^n buffer, and declines dense 3+ qubit unitaries, shot memory channels (Leakage, Seepage, LeakageTransport, QuasiStatic), and pure-state diagnostics (state_vector, overlap, entanglement_entropy).

Stabilizer Rank

src/sim/stabilizer_rank.rs expands each T gate as T = αI + βZ, so a circuit with t T gates is a weighted sum of up to 2^t stabilizer branches. One shared StabilizerBackend runs every Clifford once. Each branch is a weight and a signed Pauli string, the Zs earlier T positions chose, conjugated through the Cliffords that followed. Clifford gates cost O(n²) for all branches together and each T gate doubles the count.

  • Exact probabilities (run_stabilizer_rank) come from the Clifford register below, which sums branches that differ by a stabilizer of the base state, so they stop at 25 qubits and a register of 20 qubits at any T count. A wider register falls back to the branch sum, capped at 2^20 terms.
  • run_stabilizer_rank_approx cuts the same register back to its budget after each T gate. The coefficients are orthonormal, so each cut drops an exact norm d_j; the exact state lies within sum d_j of the kept one, and fidelity_bound() turns that and the kept norm into a fidelity floor. A register past 20 qubits is refused.
  • Terminal shots run on the same tableau in the product gauge, split into parts (src/sim/clifford_split.rs): qubits an excess rotation links, joined where the measured rows fail to commute part by part. A part of up to 26 qubits is one dense table; a wider one, one past 20 that pays few row pairs, or one past 24 whose cut prices below its table, is cut in two sides of at most 20 that no rotation crosses. The sides are drawn apart, then each shot corrects the draw over the row pairs across the cut, at most 12. Up to 64 register qubits in all. Small tables are packed, each shot reads a fixed count of words from one ChaCha8 stream per 256 shots, and every drawn bit carries a precomputed classical key. Shots with mid-circuit measurement keep coherent branches as MPS, project each outcome, and contract pairwise branch overlaps with no dense state.
  • Expectation values and marginals read the same tableau in the product gauge (src/sim/clifford_parts.rs): a T gate that reaches a qubit in |0> adds it as a one-qubit state, every other T gate is an excess rotation, and qubits an excess rotation links form a part. The state is a product over parts, so a part past the width cap answers through its excess rotations and does not block the others.

BackendKind::StabilizerRank rejects a circuit with no T gate, pointing at the stabilizer. Auto takes it for shots, expectation values and marginals; the thresholds are in routes the tree does not show.

SPP and SPD

Both propagate an observable backward through a unitary circuit of Clifford gates and Pauli rotations (src/sim/unified_pauli/). Neither holds a state or is a Backend, and the dispatcher reaches them directly. A rotation at a non-Clifford angle splits each anticommuting string into two.

SPP (StochasticPauli { num_samples }, run_spp) samples one branch per rotation and averages num_samples backward walks, so its cost follows samples and gate count, not 2^n. The result carries a standard error.

SPD (DeterministicPauli { truncation }, run_spd) carries the whole weighted sum. SpdTruncation::Threshold { epsilon, max_terms } drops terms below epsilon once the sum passes max_terms, and Budget { max_terms } drops the smallest surplus to hold the sum at the budget. With nothing to drop the run is exact and errors at a fixed term ceiling rather than truncating. Either way the discarded coefficient mass bounds the error, |error| <= sum |discarded|. Auto sends marginals on Clifford+T circuits from 12 qubits here when the register parts decline, and expectation values on Clifford circuits.

Pauli Path

Heisenberg propagation of an observable through a noisy circuit as a weighted sum of Pauli strings, reached directly like SPP and SPD. It serves expectation_values and observable_expectation (and the parameter-shift gradient built on them); run, shots, marginals and probabilities are rejected naming those two terminals.

Rz and Rzz split each anticommuting term into a cos and a -i sin branch, which grows the sum, and a noise channel scales each term by its action on the letters it touches, which shrinks it. The engine is polynomial where shrinking wins: a circuit whose noise rate outpaces its density of non-Clifford rotations. Observable weight drives the term count more than width or depth: under light depolarizing noise a weight-one Z holds the sum flat as the register widens, while a full-width Z chain fills any budget.

Channels enter through their adjoint on the Pauli basis, not a twirl, so nothing is approximated at the channel. Pauli, Depolarizing, PhaseDamping and TwoQubitDepolarizing scale each letter by one eigenvalue. AmplitudeDamping and ThermalRelaxation are not unital: their adjoint sends Z to (1 - gamma) Z + gamma I, and a thermal channel with nonzero excited_population scales the identity branch by the steady-state polarization 1 - 2 p. Custom and Kraus2q channels enter through their exact one- and two-qubit Pauli transfer matrices; only readout error is rejected naming the density matrix.

With max_terms = 0 the run is exact and errors at the shared term ceiling instead of truncating. With a budget set, terms below epsilon are dropped once the sum exceeds it. Every channel and Clifford conjugation is a contraction in the Pauli 1-norm, so the discarded coefficient mass bounds the error. A run that truncated nothing reports itself exact whatever its budget.

State diagnostics

Simulate::reduced_density_matrix, Simulate::entanglement_entropy and Simulate::overlap read the output state, so all three require a unitary circuit: a measurement, reset or conditional leaves one seeded branch. Each asks a single backend for the answer in its own representation. An explicitly selected backend with no kernel reports BackendUnsupported naming itself and the diagnostic, with no dense export fallback. Under BackendKind::Auto a backend that cannot answer is replaced by the statevector while the circuit fits its cap; a partially independent circuit keeps the factored backend and a Clifford circuit its tableau.

BackendReduced density matrixEntanglement entropyState overlap
Statevector (host or device)Partial trace over the complementOne thin SVD of the reshaped amplitudes, with the Schmidt spectrumDense dot product
SparseGrouped over the traced indexEigenvalues of the smaller side's reduced density matrixLookup join over the nonzeros against another sparse map, at any width
FactoredKronecker of the per-block tracesOne thin SVD per block the cut splits, summed; the Schmidt spectrum is their sorted Kronecker productUnion connected components across the two block partitions
Product stateKronecker of the per-qubit factors0, with the single Schmidt value 1Product of the per-qubit inner products against another product state, at any width
Density matrixPartial trace of the mixtureDeclines: a mixture has no Schmidt decompositionDeclines: the fidelity of two mixtures is not an inner product
MPOPartial trace over the Pauli basis chainDeclines: a mixture has no Schmidt decompositionDeclines: the fidelity of two mixtures is not an inner product
MPSOne environment sweep over the span of the named sites, tracing the restOne SVD at the cut, or the eigenvalues of the reduced density matrix when the subsystem is not contiguous in chain orderChain contraction at any width, aligning differing site orders with virtual SWAPs on a clone of the narrower chain
Tensor networkOne doubled contraction with the named qubits' ket and bra legs openEigenvalues of the smaller side's reduced density matrixDense export
Stabilizer, factored-stabilizerProjector onto the generators supported inside the subsystemRank of the generators restricted to the cut, less the subsystem size, in units of ln 2, with a flat spectrumRank of the two tableaux merged, at any width, across host, device, and factored tableaux
Distributed statevectorRank-local partial trace after relabeling the kept qubits local, summed across ranks; a subsystem wider than the slice reads the gathered stateEigenvalues of the smaller side's reduced density matrixDense export

Entropy is von Neumann in nats (a Bell pair reads ln 2). Schmidt values come back descending, squares summing to one. A stabilizer cut of rank r has 2^r equal weights. Past the dense export cap that list no longer fits, so the entropy comes back alone with EntropyResult::schmidt_values at None, as it does on the factored backend when the product of its blocks' spectra no longer fits. The reduced density matrix is row major with side 2^k and trace one, priced as a 2k-qubit statevector against the export cap. A noise model sends the marginal and the entropy to the density matrix, which answers the marginal of the exact mixture and declines the entropy.

Simulate::overlap takes a second seeded builder, so each side has its own backend, seed and start state; both circuits must declare the same width. The result is the squared modulus of the inner product of the two normalized states, not the amplitude, since a tableau keeps no global phase and every MPS truncation moves one. Every route divides by both norms, so an unnormalized chain answers like a unit-norm state. Two states in the same representation take the native route at any width; any other pair uses a dense export of both, up to the export cap. A noise model on either side is rejected.

What a backend reports about its own result

Four Backend methods fill the result's metadata: resolved, exactness, placement and bond_report. All four have defaults, and a backend keeping the resolved default is named by Backend::name. They are reports, not predictions: exactness is read after the run, from the singular values actually discarded, and placement after any device fallback.

The MPS sums discarded weight per SVD. A total at or under 1e-24, the weight of one singular value at the default 1e-12 cutoff, reports Exact at any bond cap; a larger total reports Approximate with 1 - total as the fidelity lower bound. That is a first-order estimate, not a certificate: errors compound across SVDs, and the strict infidelity bound is the square of the summed square roots, which matches the sum only when one SVD truncates.

The decomposed route runs one backend per independent block and merges: exactness is the weakest of the parts, the fidelity bound is the product, the bond report is the peak over the MPS blocks against their shared cap, and placement is Device only when every block was. Per-shot routes evolve one state per shot and keep the weakest claim, with the bound a minimum rather than a product.

The GPU backend has its own guide, and the distributed statevector is covered in the Capability and Support Matrix.

Parameters, Binding and Gradients

A variational sweep holds one gate sequence and varies only the angles. Three pieces share that view of a circuit: Parameters names the angles, PreparedCircuit reuses the fusion work across bindings, and the gradient engines read the same links to know which gates to differentiate.

Parameter slots (src/circuit/parameter.rs)

Parameters is a side table over a circuit, not a field on the gates, so Gate stays at 16 bytes. Each ParamLink ties an instruction index to a slot in the value vector, and a slot may drive several instructions: bind writes one angle to each, and the adjoint gradient sums their contributions into one entry. CircuitBuilder::param records a link on the gate it follows, and OpenQASM input declarations name the slots.

The arity is declared at construction, so a value vector of the wrong length is rejected even when its trailing slots carry no link. The table also records the gate kind and targets at each linked index, and validate compares them, because links are instruction indices and an edited circuit would otherwise rebind the wrong gate without complaint. bind_into overwrites a caller's circuit instead of allocating one per point.

Bindable gates are Rx, Ry, Rz, Rzz, P and PauliRot, the Gate variants carrying a rotation angle.

Adding a gate that carries an angle

A new Gate variant with an angle owes three sites beyond its kernel: Gate::pauli_generator for the gradients, angle_of and angle_mut in src/circuit/parameter.rs for binding, and an angle recipe in src/circuit/plan.rs for replay. Miss the third and PreparedCircuit::bind_fused keeps the template's angle with no error, because replay patches only the sites it recorded.

Plan capture and replay

Fusion decides the same block structure at every point of a sweep. PreparedCircuit settles it once in a FusionPlan (src/circuit/plan.rs), along with the backend choice, and rebinds against it. Capture gates the fusion floors on the buffer width of the backend the prepared circuit holds, so a prepared density matrix fuses at 2n as a direct run does.

The plan is reusable. The matrices are not, since a changed angle changes every fused matrix it feeds. FusionPlan records a recipe per payload derived from an angle: a list of template instructions and how each one's matrix enters the product. Replay recomputes the products and never caches them. Nested recipes splice by rewriting a placement flag instead of materializing the inner product, which is sound because widening to a pair and SWAP conjugation are both multiplicative.

The passes record under a Tracer that is inactive on the ordinary path, so fusion outside the prepared form allocates what it always did.

Decisions that read a matrix rather than the gate sequence are guarded:

DecisionRead byRecorded as
A 1q run collapsing to the identityflush, which elides itGuard::Fuses1q
A 1q run matching a named gateGate::recognize_matrixGuard::Fuses1q
Whether a 1q block is diagonalreorder_1q_gates, commuting it past a controlGuard::Fuses1q
Whether a 2q block is diagonalPairRun::should_fuseGuard::Diag4q
Whether a pair is a controlled phasefuse_controlled_phasesGuard::Phase2q

Each guard is tested again per binding, and a binding that flips one falls back to running the pipeline, so the stream matches an independently fused circuit either way. The 1q diagonality guard lives on the run, not on a payload site: the block is often absorbed into a Fused2q with no 2x2 of its own, and the reorder it steered has already happened.

DiagonalBatch records one recipe per phase or parity entry. A diagonal pair is decomposed after rebuilding its full matrix product, since its factors need not be diagonal one by one. BatchPhase keeps source products through merging of repeated pairs, batch splitting and changes of control qubit. The stage planner carries this provenance through its nested diagonal passes, so a PreparedCircuit replays its stages, and the device lowering runs after binding, so it replays under the profile of the backend held.

A rewritten CX Rz CX records an Rzz matrix derived from the source angle, so standalone parity batches and later pair fusion replay the same operation. A gate the passes leave untouched still needs a site when it carries an angle: PauliRot holds its angle in a boxed payload, not the enum slot, and replay patches it as it patches an Rz.

PreparedCircuit carries run, expectation_values, observable_expectation, expectation_gradient and expectation_gradient_shift, each answering as the Simulate terminal of that name does on the bound circuit, plus a _many form of each that takes a list of bindings and splits it across cores where run_batch would. Gradient batches split only below the statevector kernels' parallel width, 15 qubits, and run in order above it. Where the held backend would answer differently, the call binds and hands the circuit to simulate.

Capture pays most on narrow circuits, where fusion cost is the larger share of a run.

Adjoint gradient

simulate(circuit).seed(seed).expectation_gradient(hamiltonian, params) and sim::gradient::run_expectation_gradient compute ⟨H⟩ and the exact gradient d⟨H⟩/dθ for a weighted Pauli sum H = Σ c_k P_k, given as a PauliObservable, at a cost independent of the parameter count (src/sim/gradient.rs). PreparedCircuit::expectation_gradient runs the same pass on a held template, applying its replayed fusion plan as the forward pass.

Two statevectors are propagated backwards. With U = U_L…U_1 and |φ⟩ = U|0⟩:

  1. The forward pass (fused) keeps |φ⟩. Build |λ⟩ = H|φ⟩; the value is Re⟨φ|λ⟩.
  2. Sweep i = L…1. For a trainable gate with generator G_i, accumulate Im⟨λ|G_i|φ⟩ (projector form for P), then step both states back through U_i† (Gate::inverse()).

The sweep is not gate by gate. A gate can be inverted once every gate above it that it does not commute with has been, and a trainable gate's sandwich can be read once every gate still above it commutes with its generator. A planner assigns each gate its earliest such step, so one sandwich pass serves every gate ready at the same time (an Rz layer, then an Ry layer of a hardware efficient ansatz, instead of one pass per qubit). Gates inverted between two steps go through the fusion pipeline at the state width and apply to both states as one stretch. Commutation is structural: exact between two Pauli rotations, and per qubit otherwise, with each gate acting on a qubit as Z, X, Y, or anything.

The sandwich ⟨λ|G|φ⟩ is the forward pauli_expectation_from_masks kernel generalized to two vectors (pauli_sandwich, Rayon parallel from 16 qubits).

Gate::pauli_generator identifies the differentiable gates. A multi-qubit Pauli rotation is exp(-iθP/2), so its generator is the string itself: GeneratorKind::RotPauli borrows the letters off the gate and the sandwich takes the masks they imply. Trainable links on other gates, non-unitary instructions and QftBlock are rejected.

The planner reads the unfused instruction stream so each gate keeps its link to its generator, which fusion would erase along with the stored angle. Only the forward pass and the inverted stretches are fused. Three prunings cut work without changing results: the sweep stops at the earliest trainable gate in the cone, so a prefix with nothing trainable costs no inverse applications; a gate no trainable gate below it waits on is never inverted; and a trainable gate outside the Hamiltonian's inverse light cone has a zero gradient, so its sandwich is skipped.

Memory is two statevectors, so the ceiling is about one qubit below a single run. Only the statevector backend is supported.

Parameter shift

simulate(circuit).backend(kind).seed(seed).expectation_gradient_shift(hamiltonian, params) and sim::gradient::run_expectation_gradient_shift evaluate d⟨H⟩/dθ = (f(θ+π/2) - f(θ-π/2)) / 2 per trainable gate, exactly, from forward expectation_values calls. The path inherits whatever the selected backend can represent: sparse, MPS, factored, product state, density matrix and distributed, widths past the statevector cap, and circuits containing QftBlock. A backend with no native observable path reports BackendUnsupported naming itself.

The rule is exact because each differentiable gate is exp(-iθG/2) with G of eigenvalues ±1, so ⟨H⟩ is a trigonometric polynomial of degree 1 in that angle. P(θ) has the projector |1⟩⟨1| as generator, eigenvalues {0, 1}, but P(θ) = e^{iθ/2} Rz(θ) and the scalar cancels against its conjugate in ⟨ψ|H|ψ⟩ wherever the gate sits, so the same shift applies.

The gate set is the adjoint's, so parameter shift reaches no gate the adjoint rejects. It extends the backends and circuit shapes, not the gates. A PauliRot on a backend without the native kernel is shifted in place, because the ladder expansion happens below the forward evaluation.

Gates sharing a slot are shifted one at a time and their contributions summed. Shifting them together gives a different quantity: two Rx(θ) on one qubit under ⟨Z⟩ give cos 2θ, whose joint ±π/2 shift is zero rather than -2 sin 2θ.

Cost is 1 + 2 * links evaluations against the adjoint's one, with no light cone pruning: a trainable gate with a zero gradient is still evaluated twice. Evaluations run in sequence, because each already drives a Rayon parallel backend run and several in flight would multiply peak state memory by the parameter count, the resource this path exists to stay under. With a noise model, only the density matrix kinds accept the pair (noise across the terminals).

Compiled Samplers

Shot sampling that does not evolve a full statevector per shot. Noisy sampling, noise models and leakage are on Noise Compilation.

Noiseless compiled sampler (src/sim/compiled/)

compile_measurements propagates Pauli Z observables backward through the circuit. Each measured qubit becomes a row of a GF(2) parity matrix M recording which input qubits it depends on, and a Clifford gate conjugates a Pauli string in O(1). compile_forward tracks stabilizer generator dependencies forward through the circuit and produces the same matrix.

A shot draws random bits for the independent generators, then XORs them through the parity matrix:

StrategyConditionMethod
FlipLutSmall rank256-entry XOR lookup table
SparseParitySparse rowsFlip only the nonzero columns
ParityBlocksBlocked structureEach block sampled independently

Results collect through the ShotAccumulator trait:

AccumulatorOutputUse case
HistogramAccumulatorBitstring → count mapStandard shot output
MarginalsAccumulatorP(1) per qubitMarginal probabilities
PauliExpectationAccumulator⟨P⟩ for Pauli observablesVQE/QAOA
CorrelatorAccumulator⟨Z_i Z_j⟩ correlationsEntanglement analysis
NullAccumulatorNothingTiming raw sampling

PackedShots::RAW_FORMAT_VERSION is the replay contract for raw_data() and into_data(). Version 1 stores little-endian bit order within each u64. ShotMajor stores one row per shot with m_words() = ceil(num_measurements / 64), and MeasMajor one row per measurement with s_words() = ceil(num_shots / 64). try_from_shot_major and try_from_meas_major reject shape mismatches and nonzero semantic padding. Histograms, marginals, parity rows and accumulators mask only semantic padding: the bits past the last measurement in shot major data, and past the last shot in measurement major data.

compile_detector_sampler compiles Clifford circuits that reuse qubits after measurement, with or without a reset between, into the same packed sampler, then derives detector and observable records as packed parity rows over measurement record indices. A reset becomes a fresh qubit alias and a measured qubit used again copies its record onto one, so repeated syndrome extraction replays no tableau per shot. The sampler returns packed measurements, detectors or observables, detector counts, or feeds packed detector chunks into any ShotAccumulator.

Native backend sampling (Backend::sample_basis_states)

A non-Clifford circuit sampled through Backend::probabilities() pays a dense 2^n allocation, which caps shots at the dense width even on a backend whose state is polynomial.

Two Backend hooks lift that cap. supports_native_sampling declares that a backend draws outcomes from its own representation, and sample_basis_states(num_shots, seed) returns packed per-qubit outcomes as BasisSamples (ceil(n / 64) words per shot). Seeding comes from the argument, not the backend's RNG, so a shot request replays exactly, and the call does not collapse the state. It takes &mut self because a backend may first reorganize its storage: the distributed backend restores its qubit map, a collective, so each rank owns a contiguous slice in circuit order. supports_pauli_expectation and pauli_expectations(observables) are the observable pair. They do not assume a unit norm, so a truncated MPS is divided by ⟨ψ|ψ⟩.

BackendSampling costMethod
SparseO(k log k) once, O(log k) per shotCDF over the k stored amplitudes, ordered by basis index
FactoredO(Σ 2^kᵢ) once, O(B log) per shotOne draw per block state, concatenated; B blocks
MPSO(n·χ³) once, O(n·χ²) per shotSequential conditional sampling against precomputed right environments
Product StateO(n) once, O(n) per shotOne Bernoulli draw per qubit against that qubit's own weight on 1
DistributedO(2^(n-p)) once, O(log) per shotCDF over the local slice; one scalar gathered per rank picks the owner
Everything elsedenseUnchanged: probabilities() then CDF

The sparse, factored and product-state samplers draw in blocks of 256 shots, each from its own ChaCha8 stream keyed on the seed and block index, so blocks fill in parallel and the bits do not depend on the thread count. The dense sampler over factored block probabilities walks the same blocks in the same order, so it matches the factored backend's native draws shot for shot.

run_shots_with and run_counts_with share prepare_shot_source. Terminal route selection builds the circuit without measurements and its measurement map once, then passes both to preparation. A native sampler requires a single backend whose capability is checked before initialization. The counts path aggregates its draws without materializing a ShotsResult.

Drawing every shot from one evolved state needs Circuit::has_terminal_measurements_only, which counts a reset as a measurement unless no multi-qubit gate has touched its qubit. Such a qubit is still a product factor, so the reset is deterministic, and the leading resets of an OpenQASM program keep the terminal route. A reset on an entangled qubit draws an outcome that one evolution would share across every shot, so the circuit replays per shot. The density matrix is the exception: it applies reset as the channel, and its terminal draw stays exact.

The product state is the one backend taken past subsystem decomposition. It already stores one factor per qubit, so splitting a non-entangling circuit into blocks pays a backend, a partition and a merge per block to rebuild what one native draw reads off the state, and past 64 qubits the merged block distribution has no representation. Every other backend keeps the block split. only_the_product_state_takes_the_native_sampler_past_decomposition (src/sim/tests.rs) pins both sides.

For multiple shots of terminal measurements above 64 total qubits, decomposed host statevector blocks cache their states before the first measurement. Each shot copies that state into a reusable buffer and applies the original measurement suffix with the same shot and block seeds as full replay. Gate evolution runs once per block; measurement order, collapse arithmetic and ordered shot output stay unchanged. Blocks at the statevector memory cap, resets and other backend families retain full replay.

MPS records each bit against the logical qubit hosted at a site, not the site index, so a layout permuted by SWAP routing needs no canonicalization pass. tests/integration/native_sampling.rs pins that case. mps_conditional_path_probabilities_match_the_dense_vector (src/backend/mps/mps_tests.rs) checks the conditional decomposition against the dense vector to 1e-12, and the query matrix in tests/integration/conformance_matrix.rs is the corpus-wide comparison.

The tensor network answers below its dense ceiling from one contraction of the full distribution. Past it, each bit draws from the conditioned single-qubit marginal, contracted on the doubled network, and the outcome projector is absorbed before the next qubit. A shot costs one doubled contraction per qubit, with peaks set by treewidth rather than 2^n. The measured crossover that put the dense arm below the ceiling is in the backend's module docstring.

Weighted observables and their commuting groups are on the engine page.

Noise Compilation

How a noise model becomes events, and which engine samples them. The user-facing version is the noise guide, and the native QEC path is on QEC programs.

Noise models (src/sim/noise/)

NoiseModel holds one list of noise events per instruction slot. Every noisy engine supports Pauli and depolarizing channels, and every one but noisy_marginals_analytical supports two-qubit depolarizing. Amplitude damping, phase damping, thermal relaxation, and one- and two-qubit custom Kraus operators need the trajectory engine. Readout error acts on the measurement record rather than the state, so the route is chosen on the channels alone and each engine applies readout itself.

NoiseBuilder (src/sim/noise/builder.rs) compiles declarative rules into the same slot vector. The rules cover rates by gate type and by qubit, idle decoherence against circuit layers, crosstalk through a coupling map, and coherent over-rotation proportional to a rotation gate's angle. They also cover reset error, error before measurement, readout per bit, idle relaxation and detuning timed by an as-soon-as-possible schedule of gate durations, and amplitude drift per shot. Every rule is evaluated once at build time, so nothing reaches a loop over shots or instructions. The drift rules emit fixed weights over draws the trajectory makes per shot. A timed rule places each qubit's events for a layer just before that qubit's next instruction, since instruction order can list a later layer's gate on the qubit ahead of an earlier layer's last instruction.

Custom Kraus sets must be trace preserving, sum_k Kdagger_k K_k = I to 1e-9: the exact route applies a set literally while the trajectory route normalizes its branch probabilities. ThermalRelaxation is generalized amplitude damping composed with pure dephasing on both routes. Populations decay as exp(-gate_time/t1) and coherences as exp(-gate_time/t2) toward a steady state of excited_population. A mixture of reset and Z would match the coherence decay only for t2 <= t1.

Two-qubit Kraus operators are indexed K[t][t'] with t = 2*bit(q0) + bit(q1), the packing Gate::matrix_4x4 uses. The density matrix compiles the set into a 16x16 block superoperator (apply_2q_kraus, which apply_2q_depolarizing lowers onto). The trajectory engine draws a branch from Tr(Kdagger K rho) over Backend::reduced_density_matrix_2q and applies the normalized operator as a Fused2q. The host statevector, sparse, factored, MPS, tensor network and distributed statevector backends answer that reduction, the distributed one through Backend::reduced_density_matrix. The tableau backends and the product state decline it.

Auto counts a two-qubit Kraus event as entangling when it picks the trajectory backend, so one-qubit gates carrying a crosstalk channel run on the statevector (or the sparse map or MPS past the dense cap), not the product state. Routing asks the trajectory backend for Backend::supports_two_qubit_kraus before the first shot. An explicit kind that declines the channel, a device statevector included, is named at dispatch, and Auto with a device keeps such a model on the host statevector.

Noisy compiled sampler

Backward Pauli propagation through the circuit gives each noise location an X-flip and a Z-flip sensitivity row. At sample time Bernoulli draws decide which channels fire, and their sensitivity rows XOR into the sample.

With the gpu feature and a context attached via with_gpu, the sampler can sample, apply noise, and reduce counts or marginals on the device. Device noise masks come from a stream seeded on the device, so GPU output matches CPU output statistically, not bit for bit. Device counts are limited to 512 measurements (8 packed words); larger circuits fall back to the CPU reduction.

Engine routing and the observable contract

Noisy sampling is reachable through simulate(...).noise(...).shots(n) and .sample_counts(n) on trajectory backends. The density matrix also serves run, marginals and expectation_values (noise across the terminals). run_shots_with_noise (src/sim/shot_routes.rs) routes Pauli-only noise on Clifford circuits to the compiled family when the backend is Auto or a stabilizer kind and the measurements are terminal or rewrite to terminal (below). Every other accepted combination runs the trajectory engine over the resolved backend. Within the compiled family, run_shots_noisy (src/sim/noise/mod.rs) picks one engine per call:

EngineSelected whenLimitations
Brute-force replay (run_shots_noisy_brute_with)Dynamic circuits the rewrite declinesTableau replay per shot, O(shots) simulations; non-Clifford circuits error here (the public entry point routes them to the trajectory engine instead)
Pauli frameShallow circuits: gate count / qubits < 3, or < 5 at >= 200 qubitsClifford, terminal measurements, no event in a guarded body
Compiled Pauli (NoisyCompiledSampler)Remaining Clifford circuitsClifford, terminal measurements after the rewrite

All engines sample the same distribution of measurement records for the models and circuits they accept. They consume independent RNG streams, so one seed gives different shots with matching marginals, correlators and histograms. The frame and compiled engines and the noiseless compiled sampler all resolve to ResolvedBackend::CompiledStabilizer, and RunMetadata::engine names which one ran.

defer_noisy_circuit (src/sim/compiled/mod.rs) rewrites a circuit with resets, mid-circuit measurements or guarded Pauli gates to terminal measurements. A reset moves its qubit to a fresh alias. A measurement whose qubit nothing touches before its next reset moves to the end unchanged; one whose qubit a later gate, guard or measurement uses becomes a CX onto a fresh alias measured at the end, so the qubit stays live and the copy only ever controls. A guarded Pauli P on qubit t becomes P controlled by the alias of each record its condition reads, plus an unconditional P when the condition is inverted. That holds for a single bit, a Parity, or a register comparison reading at most one written bit. A comparison reading several written bits is an AND of records, which no controlled Pauli applies, so its Pauli stays out of the circuit as a guarded entry. A guarded body holds Pauli gates only. An event on a measured alias drops. The noiseless shot route takes the same rewrite at two shots or more.

An event in a guarded body fires only on shots whose guard holds, which no fixed linear map expresses. The compiled sampler draws every shot's records under the unguarded events. Each guarded entry then lands its precomputed record flips in execution order: an event draws at its rate on every shot and lands where its guard holds, and a guarded Pauli lands on every shot its guard holds. When a guarded Pauli is among the entries, they land on measurement rows, so a guard is a few word operations per 64 shots; readout comes last. Readout error on a bit a guard reads is not left to the end: the rewrite places an X of that rate on each alias measured into the bit, which the guard's controls and the record then both see. A rate equal both ways fires that X on every shot. Unequal rates make it a guarded entry instead, drawn at the rate the record's value picks after the earlier entries land. Such a circuit always takes the compiled sampler, never the frame sampler.

Slots for guarded instructions

Slots 0..n follow the n top-level instructions and fire every shot, a guarded instruction's included. Body slots come after: each region lays out its body's slots, then its nested guards', and a conditional takes one slot for its gate. A body slot fires only on the shots its instruction runs. NoiseBuilder gate rules put a guarded gate's noise in its body slot, and rules that read a schedule decline a circuit holding a region. compile_noisy and the error chain complex reject body slots that carry an event, and the density matrix rejects any guard.

Trajectories

The trajectory engine (src/sim/trajectory.rs) covers everything the compiled family rejects (non-Pauli channels, non-Clifford gates, dynamic circuits the rewrite declines) at the cost of one state evolution per shot. On the distributed statevector the trajectories run serially in shot order on every rank, so the ranks issue their collectives in lockstep.

Pauli noise on the host statevector skips the per-shot cost when all measurements are terminal, there is no reset, and no live event follows the first measurement. Every shot's error pattern is drawn first from its own seed, and shots with the same pattern share one evolution. Each shot then draws its record from its group's final state on its own stream. The distribution is right but the shots differ, seed for seed, from the per-shot path. When distinct patterns exceed nine tenths of the shots, the run falls back to one trajectory per shot.

Amplitude and phase damping on the host statevector share a prefix of gates: everything before the first instruction that is not a gate or barrier, or whose events include a channel other than Pauli, depolarizing or damping. Until a shot draws below a damping gamma or a Pauli threshold, its state is the one every such shot holds. The run walks the shared state once, and each shot copies it where it leaves, redraws its stream that far and finishes alone. The records match the per-shot path seed for seed. A walk that reads P(1) past one by more than its headroom falls back to per-shot trajectories, as do leakage and quasi-static channels.

Two-qubit channels

A two-qubit channel is one joint draw over its 15 non-identity Pauli products, never two single-qubit draws: both letters move with probability 0.6p, where independent draws give (0.8p)^2. The compiled sampler stores the propagated X and Z components of both targets, four rows an event, in a table run as a second pass after the single-qubit rows. A pair whose targets fall in different subsystem blocks takes the monolithic compile.

A non-empty pair table keeps noise application on the host, because the device noise kernel would draw the two qubits independently. The noiseless parity sample and the bit transpose still run on the device.

Readout and validation

Readout error flips a classical bit when a measurement writes it, so a condition reads the noisy bit and each measurement into the bit draws its own flip. The state is never touched. When no condition reads a bit carrying readout error, only each bit's last write reaches the record, and flipping the finished record draws the same distribution. Every route then keeps doing that, with the seeded shots it always drew. A trajectory whose conditions read such a bit, the brute-force stabilizer replay included, flips each bit on the shot's noise stream right after the measurement instead.

The frame and compiled samplers apply readout error to the packed measurement record after the reference outcomes are folded in, so a set bit is a measured one. Records are thinned at max(p01, p10), then a candidate is accepted at the rate its live bit selects. Brute-force replay flips each shot's unpacked record on that shot's own stream, as the trajectory engine does.

Every entry point that draws shots calls NoiseModel::validate_for against the circuit before allocating state. It checks one event slot per instruction, channel parameters in range, distinct targets on a two-qubit channel, and every target inside the register. noisy_marginals_analytical is the exception, having no per-shot state to allocate.

Leakage and quasi-static drift (src/sim/trajectory.rs, src/qec/leakage.rs)

Two channel families carry state from one event to the next within a shot: leakage (Leakage, Seepage, LeakageTransport) keeps a leak flag per qubit, and QuasiStatic reads standard normal draws made once at the start of the shot. Neither is a CPTP map applied event by event, so the density matrix and the Pauli path estimator decline them and they run on the trajectory engines only. A model holding neither takes the trajectory loop unchanged, which MemorySpec::of decides once per run.

A leaked qubit in a trajectory

When a qubit leaks, the engine resets it and flips it to |1>, then leaves it alone until it returns. Gates naming it are skipped, other channels skip events naming it, and a measurement of it reports 1. The reset is one trajectory of the channel rho -> |0><0| (x) tr_q rho (see Backend::reset), so averaged over shots the rest of the register holds exactly tr_q rho. After the reset the qubit is an unentangled basis state:

  • Measuring it is a deterministic outcome that collapses nothing else, so the ordinary measurement path reports 1, and a classical condition reading the bit sees the same 1.
  • A multi-qubit gate it blocks is replaced by one uniformly random Pauli (I, X, Y, Z at a quarter each) on each unleaked target: complete depolarization.
  • Seepage returns the qubit to a uniformly random basis state with one coin and at most one X.

ShotsResult::leaked records, per shot, which qubits leaked at any point: the erasure herald.

Quasi-static draws

QuasiStatic { axis, weights } rotates its qubit by sum_k w_k z_k, where z holds one independent standard normal per source index, drawn by Box-Muller from the shot's noise stream before its first event. NoiseBuilder lowers a DriftDistribution with covariance Sigma through its Cholesky factor L. Qubit q's offset is row q of L against z, so the offsets have covariance L L^T = Sigma exactly, and detuning scales the row by each scheduled layer's duration. A singular Sigma (perfect correlation) keeps zero columns where the factor has no variance left.

Leakage on the compiled QEC path

QecLeakageSampler walks the deferred circuit forward per unit of 8192 shots, holding a packed leak row per alias next to the frame rows. A Pauli frame cannot skip a gate, and does not need to. A qubit that leaks gets a uniformly random frame Pauli, and every two-qubit gate meeting a leaked qubit scrambles the frames of both its qubits on the shots where either is leaked. Since tr_ab(U rho U^dag) = tr_ab(rho) for any U on the pair, the rest of the register sees what a trajectory that skips the gate sees. Pauli annotations replay in program order with the leakage ones, and a firing that names a leaked qubit is dropped. The leaked qubit's own record is forced to 1 after the frame flips land.

The result matches trajectory leakage in distribution on a Clifford program. LEAK targets add herald columns, QecSampleResult::heralds. Forcing a bit is not a linear flip, so these programs bypass the record noise and parity projection samplers.

Error chain complex (src/sim/homological.rs)

ErrorChainComplex is a GF(2) chain complex over the circuit's noise locations. The kernel of its boundary map gives the error cycles syndrome measurements cannot detect. noisy_marginals_analytical gives closed-form marginals from the parity matrix and noise rates, with no Monte Carlo sampling.

QEC Programs

QecProgram in src/qec/mod.rs is a measurement-record IR for QEC workloads: detectors, logical observables, postselection, expectation metadata and noise annotations, held before sampler lowering. It is separate from Circuit so these programs do not have to fit final-measurement OpenQASM semantics. Workflow examples are in the QEC guide. Public entry points: run_qec_program, run_qec_program_reference, run_qec_program_with_strategy, run_qec_program_spd_rerouted, and compile_qec_program_rows.

Program, ops, and options

QecProgram holds a qubit count, an ordered op list, and a QecOptions value. The typed builders (push_gate, measure, measure_pauli_product, reset, detector, observable_include, expectation_value, postselect, noise) validate each op as it is appended. measure and measure_pauli_product return the new record index, and detector the detector index. Validation covers gate arity, qubit bounds, finite coordinates, coefficients and probabilities, record-reference scope, duplicate qubits in a gate's targets or a Pauli product, observable indices below 2^24, branch probabilities summing to at most 1, and target pairing for DEPOLARIZE2 and PAULI_CHANNEL_2.

QecOp variantPayloadSemantics
Gategate, targetsStandard gate. The compiled runner requires Clifford gates; the reference runner accepts any gate the statevector backend supports.
Measurebasis, qubitSingle-qubit measurement in the requested basis. One record. The basis rotation is not undone, so the qubit is left in the Z frame. Reuse before a Reset is rejected (see the reset requirement below), by the reference runner too after a non-Z basis, so that frame is never observable.
MeasurePauliProducttermsOne record equal to the parity of the listed Pauli terms. Unlike Measure, the per-term basis rotations are undone before the record is taken.
Resetbasis, qubitReset to the +1 eigenstate of the requested basis.
Detectorrecords, coordsParity over the listed records. coords is passthrough metadata with no effect on sampling.
ObservableIncludeobservable, recordsIncludes for the same observable index XOR into a single row.
ExpectationValueterms, coefficientcoefficient * <P> in the final state. Terminal placement, live qubits only.
Postselectrecords, expectedThe shot is accepted only when the parity over records matches expected.
Feedforwardrecords, expected, bodyThe body runs only when the parity over records matches expected. See Feed-forward for what a body admits.
Noisechannel, targetsPauli-noise annotation. Zero probability is inactive.
CorrelatedErrorbranchesMutually exclusive Pauli products: branch i fires with its probability only when no earlier branch fired. The text chain E / ELSE_CORRELATED_ERROR is one op.
HeraldedEraseprobability, qubitOne record: 1 with the given probability, in which case a uniformly random Pauli (identity included) hits the qubit; 0 otherwise.
PadvalueOne constant record.
RecordFlipprobabilityReadout error: flips the record of the op directly before it with the given probability, leaving the state alone. Must directly follow a record-producing op or another RecordFlip, so no feed-forward reads the record before the flip. The compiled runner and the detector error model lower it to an X on the record's measured alias, which no later gate touches.
TickScheduling separator with no semantic effect.

Record references are QecRecordRef::Absolute indices or QecRecordRef::Lookback distances (1 is the most recent record, 0 is rejected), resolved against the records that exist when the referencing op is appended. Detector, observable and postselection rows therefore hold absolute measurement indices by the time a sampler compiles them.

QecOptions fieldDefaultEffect
shots1024Number of shots requested by the runner APIs.
seed42RNG seed for stochastic samplers and Pauli-noise dispatch.
chunk_sizeNonePer-batch shot bound for the compiled runner. None is equivalent to Some(shots); Some(0) is rejected. No effect on the reference runner or on seeded noise.
keep_measurementstrueWhen false, QecSampleResult::measurements is returned with zero shots (column count preserved). Detector and observable records are always populated.
detector_referenceNoiselessNoiseless XORs each detector and observable with its value in the noiseless reference run; Raw reports the plain record parity. See Result shape.

Feed-forward

QecOp::Feedforward conditions a body on the parity of a record list against an expected value, the shape a detector already has, and reuses the guarded-region contract. The QEC record space and the classical bit vector are one address space (the reference runner writes record i to classical bit i), so a resolved record index is the bit a ClassicalCondition::Parity reads. The op executes as the guarded instruction circuit::guarded picks for its body: a Region through Backend::apply_region, or a Conditional when the body is one gate.

The body admits gates and resets only. Detectors and observables index the record space absolutely, so a measurement whose execution depended on a record would make every later index depend on the shot.

The compiled QEC sampler evaluates a static affine map from random bits to outcomes, and a record-conditioned branch breaks that. A Pauli product body is the exception. A Pauli at a fixed point flips the same later records in whichever shot it fires, like a noise fault there, and reaches only records produced after it. run_qec_program therefore samples the program without its feed-forwards and applies noise. It then walks the feed-forwards in op order, XORing each one's precomputed flip set into the shots where its predicate holds, so a predicate reads records that earlier corrections already flipped. The flip sets come from the forward Pauli frame walk the record noise uses, up to 64 corrections as lanes of one walk. A Pauli on a qubit measured since its last reset flips nothing and is dropped, as noise there is.

A body holding any other gate or a reset, and a feed-forward in a program with leakage annotations, are rejected by name with a pointer to run_qec_program_reference. A feed-forward program also skips the parity route that reads no records. The deferred lowering's other consumers and the density matrix estimator reject the op outright, and detector error model derivation inherits the deferred lowering's rejection. Build the op with QecProgram::feedforward, since the native text format does not spell it.

Parsing

parse_qec_program and QecProgram::from_text parse the native QEC text subset: I, X, Y, Z, H, S, S_DAG, T, T_DAG, CX, CZ, R/RX/RY, M/MX/MY, MR variants, MPP, DETECTOR, OBSERVABLE_INCLUDE, POSTSELECT, EXP_VAL, the Pauli noise instructions (X_ERROR, Y_ERROR, Z_ERROR, DEPOLARIZE1, DEPOLARIZE2, PAULI_CHANNEL_1, PAULI_CHANNEL_2), the leakage annotations (LEAK(p), SEEP(p), and LEAK_TRANSPORT(p) on pairs), TICK, QUBIT_COORDS, SHIFT_COORDS (ignored), flattened REPEAT blocks, and the instructions below, which lower onto the same ops. rec[-k] resolves to an absolute index while parsing. A numeric argument on a basis measurement, such as M(0.001), lowers to a Pauli flip on that record just before the measurement. Inverted (!) targets, a two-qubit gate pair naming one qubit twice (CX 0 0), and a qubit or observable index of 2^24 or more are rejected, and instruction tags such as X_ERROR[tag](p) are ignored.

InstructionLowering
SQRT_X / SQRT_X_DAGGate::SX / Gate::SXdg, the +pi/2 and -pi/2 X rotations.
SQRT_Y / SQRT_Y_DAGS_DAG, SQRT_X (or SQRT_X_DAG), S on the qubit.
SQRT_Z / SQRT_Z_DAGS / S_DAG.
C_XYZS_DAG, H: the X -> Y -> Z -> X axis cycle.
C_ZYXH, S: the inverse cycle, X -> Z -> Y -> X.
CY a bS_DAG b, CX a b, S b.
SWAP a bCX a b, CX b a, CX a b.
ISWAP a b / ISWAP_DAG a bS a, S b (S_DAG for the dagger), CZ a b, then the three CX of a swap.
CXSWAP a bCX b a, CX a b (a CX a b followed by a swap).
SWAPCX a bCX a b, CX b a (a swap followed by CX a b).
MXX / MYY / MZZ a b ...A MeasurePauliProduct over each pair, one record per pair; no measurement-error argument.
MPAD v ...A Pad op per value, each one constant record.
E(p) / CORRELATED_ERROR(p) P ...A CorrelatedError with one branch: the Pauli product fires with probability p.
ELSE_CORRELATED_ERROR(p) P ...Appends a branch to the chain it directly follows, fired only when no earlier branch fired.
HERALDED_ERASE(p) q ...A HeraldedErase op per target: one record, 1 when the qubit is erased, with a uniformly random Pauli applied on erasure.
RECORD_FLIP(p)A RecordFlip of the record just produced. No targets; it must directly follow a record-producing instruction or another RECORD_FLIP.
LEAK(p) / SEEP(p) / LEAK_TRANSPORT(p)QecNoise::Leak, Seep and LeakTransport annotations; see leakage on the compiled QEC path.

QecProgram::to_text writes the same subset back, and parsing its output reproduces the op list. Consecutive gates, measurements, resets and MPP products of one kind share a line, so MR comes back as M then R, MZZ as MPP, SWAP as three CX, and SQRT_Y as S_DAG, SQRT_X, S. Record references print as rec[-k] and parse back to absolute indices. A leading QUBIT_COORDS line keeps the register width when the highest qubit is idle. QecOptions are not written, and zero-probability noise reads back as nothing. A gate outside the parser's set or a FEEDFORWARD op is an error rather than a lossy write.

Memory-experiment generators

src/qec/generators.rs builds the standard memory experiments as ordinary programs, so sampling, model derivation, decoding and text export treat them like any other. Each generator validates its op list once through QecProgram::from_ops, because the incremental builders recount records on every append and would make a distance-13, 1000-round program quadratic to build.

GeneratorQubitsRoundMemory basisObservable 0
repetition_memory(d, r, noise)d data on even indices, d - 1 ZZ ancillas between themtwo CX layers, then measure and reset the ancillasZdata qubit 0
surface_memory(d, r, basis, noise)d * d data, then one ancilla per stabilizerH on X ancillas, four CX layers, H, measure and resetX or Zleft data column (Z), top row (X)
color_memory(d, r, basis, noise)(3 d^2 + 1) / 4 data, then one ancilla per faceX stabilizers in six CX layers, measure and reset, then the Z stabilizers likewiseX or Zevery data qubit

QecCircuitNoise has four rates, each emitted only when nonzero:

RateEmits
after_clifford_depolarizationDEPOLARIZE1 after each H layer, DEPOLARIZE2 after each CX layer
before_measure_flip_probabilitythe flip the basis is sensitive to: X_ERROR before Z measurements, Z_ERROR before X ones
after_reset_flip_probabilitythe same, after resets
before_round_data_depolarizationDEPOLARIZE1 on the data at the start of every round

TICK separates the layers.

Detectors compare each stabilizer with its previous round. In the first round only stabilizers of the memory basis have detectors. After the final data readout in the memory basis, each such stabilizer gets one more detector: the product of its data readouts against its last ancilla record, at t = rounds. Coordinates:

  • repetition: (x, t), x the ancilla's qubit index;
  • surface: (x, y, t), data qubit (r, c) at (2c + 1, 2r + 1), each ancilla at its plaquette centre;
  • color: (x, y, t, c), c the face color, plus 3 for Z stabilizers.

The surface schedule visits X plaquettes NW, SW, NE, SE and Z plaquettes NW, NE, SW, SE. On every data pair an X and a Z ancilla share, the Z ancilla acts first on both or on neither, so interleaved ancillas measure the stabilizers correctly. The order also lays each hook error (the two-qubit error an ancilla fault halfway through a plaquette leaves on the data) perpendicular to the logical operator it could extend. The graphlike distance of the decomposed model (the fewest mechanisms that flip the observable with no detector) equals d for both bases at d = 3 and 5, as it does for the repetition code.

The color code is the triangular 6.6.6 code. Data qubits are the honeycomb vertices inside a triangle with one boundary of each color, giving hexagons in the bulk and weight-4 half hexagons on the boundary. A face visits its vertices in angular order, and a vertex sits at a different angular position in each of its three faces, so six layers measure every face without two ancillas meeting one data qubit. X and Z stabilizers use the same ancilla in separate halves of the round, so no interleaving argument is needed.

There are no flag qubits. An ancilla fault midway through a hexagon can leave weight-3 damage, and the circuit distance can fall below d. The code distance is d: under data noise alone, the fewest undetected observable-flipping mechanisms is exactly d at d = 3 and 5 in both bases. A bulk data error flips three faces. From distance 5 some of those hyperedges have no graphlike cover, so decompose_graphlike rejects the model and union-find does not apply. A hypergraph decoder consumes the model as derived.

With the union-find decoder at 100k shots, seed 42, d rounds and uniform noise:

CodepFailures
repetition0.01691, 152, 21 at d = 3, 5, 7
surface, Z memory0.002309, 112 at d = 3, 5
surface, X memory0.002339, 144 at d = 3, 5

The MPP-based repetition and surface memories in the benchmark and test helpers are a different program: they measure stabilizers directly under phenomenological noise, and seeded-record digests and benchmark history pin them.

Runner routing

run_qec_program picks one of six paths:

flowchart TD
    A[run_qec_program] --> B{EXP_VAL ops present?}
    B -- yes --> C[validate placement rules]
    C --> D{active noise?}
    D -- yes --> M{density-matrix eligible?}
    M -- yes --> X[density-matrix estimator]
    M -- no --> R[reference runner]
    X -- lowering or oracle rejects --> R
    D -- no --> E{detectors present?}
    E -- yes --> S[two-run split]
    E -- no --> L[analytical Auto ladder]
    S -- either half fails --> R
    L -- lowering refuses --> R
    B -- no --> F{active noise?}
    F -- yes --> N[noisy compiled sampler]
    F -- no --> P[clean compiled sampler]

Programs without EXP_VAL take the packed compiled path: QecProgram::compile_sampler, then one QecCompiledSampler::sample call at the program's shot count and seed. Validation rejects non-Clifford gates and reports whether active noise is present. A program with no measurements returns an empty record buffer without compiling a sampler. Noisy Clifford programs compile a noise-aware sampler, and clean ones lower to a circuit and compile a detector sampler. Both sample in batches of at most QecOptions::chunk_size shots, with detector, observable, postselection and logical-error accounting per chunk, so peak memory is one chunk of records when raw measurements are not kept.

The two-run split serves noiseless EXP_VAL programs with detectors, which are record metadata with no effect on the state, so the halves compose. The packed sampler runs the program without its EXP_VAL ops (real measurement, detector and observable records), and the analytical ladder runs it without its detectors (exact estimates attached to the sampled result). When either half cannot run (non-Clifford gates on the packed half), the whole program falls back to the reference runner.

A noiseless EXP_VAL program without detectors goes to the Auto ladder, which lowers it once for all three strategies. When that lowering refuses the program (a FEEDFORWARD, a measured qubit reused without a reset, or a gate on three or more qubits), the program runs on the reference runner instead, when it is no wider than Limits::max_qec_reference_qubits (default 20, since that runner costs shots times 2^n) and fits the statevector cap. A wider program returns the refusal, naming the limit. An error after lowering, such as the 12-row postselection cap or a contraction over the tensor network cap, is returned. A noisy EXP_VAL program with leakage annotations is rejected, since no runner estimates under leakage.

The density-matrix estimator serves noisy EXP_VAL programs whose ensemble the mixed state can carry in full. There Tr(rho P) is the exact value the reference runner approximates by averaging per-shot statevector expectations. Eligibility:

  • No measurement records. M and MPP collapse the state per shot and feed the measurement, detector and observable rows, and the mixed state holds no record stream.
  • No postselection, which would condition the estimate on an accepted subensemble Tr(rho P) does not express.
  • Width within the density-matrix cap (PRISM_MAX_DM_QUBITS, default half the statevector cap), since the backend stores 4^n amplitudes.

R is eligible. Both paths implement the reset channel rho -> |0><0| (x) tr_q rho from the backends reset contract. The density matrix applies it directly, and the reference runner samples one trajectory per shot, so the shot mean still converges to Tr(rho P).

A gate or channel the density-matrix path rejects surfaces as an error from the lowering or the oracle, and also falls back to the reference runner. The lowering maps gates one to one and expands a basis reset into Reset plus its Z-to-basis rotation. Each Pauli-noise annotation becomes NoiseModel events on the instruction it follows, applied through the backend's exact one-qubit Kraus and two-qubit depolarizing channels.

run_qec_program_reference is the correctness oracle: one statevector simulation per shot, O(shots * 2^n). It executes ops in order, samples Pauli noise from a dedicated RNG stream derived from the seed, lowers MPP onto one scratch qubit at index num_qubits, and evaluates postselection parities per shot.

Compiled rows

compile_qec_program_rows is the public sampler-row primitive. It lowers basis measurements and MPP ops into QecCompiledRows: one packed X/Z Pauli row per measurement record (bitmask words over the qubits), plus detector, observable and postselection rows as absolute record indices with their expected values. Parity projection delegates to PackedShots::parity_rows. It is a lowering artifact, not an execution path, and rejects programs containing gates, resets, active noise, or EXP_VAL.

The clean compiled path builds its sampler from the lowered Clifford circuit instead. It backward-propagates each measurement observable into a Pauli sensitivity row. Gaussian elimination reduces the rows to independent flip rows plus a deterministic reference outcome, and each shot XORs a random subset of flip rows into the reference bits. Detector and observable rows are then applied as parities over the sampled records (compiled samplers).

Lowering

Two lowerings turn a QEC program into a circuit the samplers accept. They share the basis-rotation helpers (append_basis_to_z_rotation and its inverse) and MPP parity accumulation in append_mpp_parity_rotations, which rotates each term into Z, accumulates parity on a scratch qubit via CX, undoes the rotations and measures the scratch. Both lowerings finish by checking that exactly num_measurements records were emitted.

The clean Clifford lowering measures in place: it rotates the qubit into Z, measures into the next record and leaves the rotation, so the qubit stays in the Z frame. MPP uses one scratch qubit at index num_qubits, reset between uses. A reset emits a reset followed by the basis rotation.

The deferred lowering backs the noisy path and the analytical estimator prelude. A reset gives the program qubit a fresh circuit alias, so every measurement can be deferred to a terminal record. Each program qubit's final alias is recorded so terminal EXP_VAL terms translate onto the lowered circuit. Noise ops are recorded as positioned events for sensitivity compilation instead of applied to the circuit.

V1 reset requirement

In a noisy program a measured qubit must be reset before any later gate reuses it, because the compiled lowering defers measurements to terminal records. The noiseless compiled sampler copies the record onto a fresh alias instead and accepts the reuse.

Noisy data flow

Noise never executes during compiled sampling. It compiles into record flips: the deferred lowering produces the noiseless circuit plus positioned noise events, and backward Pauli propagation walks the circuit in reverse, carrying each measurement's observable to each event position. For a program whose records are sampled, the walk carries one record fingerprint word per live alias and keeps an event when one of its branches moves that word. A program whose records are read starts every shot from one noiseless reference run: a stabilizer tableau run of the program with every random outcome forced to 0. A fair-coin Pauli Z at the birth of each alias (an initial qubit, a reset, a Pauli-product scratch qubit) spreads it over the noiseless outcome space, and the backward walk drops the births whose Z flips no record.

When records are neither kept nor postselected, the walk holds rows only for the aliases live at each position and projects each event onto detector and observable bits as it reaches it. Compile memory then follows the live qubit count rather than records times aliases. The same walk reads the noiseless detector and observable values from the propagated signs, and falls back to the record path if any is random. A noiseless program takes the same walk with no events, at cost live qubits times records. On the record path the walk carries the fingerprint word alone, so its compile also follows the live qubit count rather than the record count.

At sample time the reference records fill every shot, then the coins and faults land through a Pauli frame walked forward over the deferred circuit: a fault lands on its alias's frame at its anchor, the gates push the frame on, and an alias's X frame at its last use is the flip of its record. Small-probability events skip between firing shots by geometric sampling. Dense events (probability at or above 0.5, or a unit of fewer than 32 shots) iterate every shot. DEPOLARIZE2 precomputes the flip masks of all 15 non-identity two-qubit Pauli branches and picks one uniformly per firing. PAULI_CHANNEL_2 precomputes the same masks and picks a branch from a second uniform draw against its cumulative branch rates, kept in one table per op rather than in every event.

Noise draws in fixed units of 8192 shots. Unit k covers shots [8192 k, 8192 (k + 1)) and draws every event in program order from ChaCha stream k of the noise seed, so a unit's faults depend only on the seed and k. A chunk boundary inside a unit continues that unit's draws, so seeded noise is independent of QecOptions::chunk_size, and units run in parallel under the parallel feature without changing any bit. When records are neither kept nor postselected and every detector and observable is fixed in the noiseless circuit, the draws land directly on detector and observable rows, bit for bit what the record path produces. The unit size is part of the seeded output: changing it changes noisy results at a given seed. The birth coins draw per unit from a stream of their own, so faults fire on the same shots with or without them. A noiseless program without feed-forward whose records are random still draws from a compiled sampler per chunk.

Supported Pauli channels are X_ERROR, Y_ERROR, Z_ERROR, DEPOLARIZE1, PAULI_CHANNEL_1(px, py, pz), DEPOLARIZE2, and PAULI_CHANNEL_2 with its 15 probabilities in the order IX, IY, IZ, XI, XX, XY, XZ, YI, YX, YY, YZ, ZI, ZX, ZY, ZZ, the first letter on the first target of each pair. Every one-qubit channel is one draw with three branch rates, so Y_ERROR(p) is (0, p, 0). Noise on an already-measured target is dropped, since it can no longer affect a record. A two-qubit channel with one measured target degrades to its marginal on the survivor: DEPOLARIZE1 at p * 0.8 for DEPOLARIZE2, and for PAULI_CHANNEL_2 the PAULI_CHANNEL_1 that sums branch rates by the survivor's letter.

The leakage annotations LEAK(p), SEEP(p) and LEAK_TRANSPORT(p) (on pairs) carry a leak flag per qubit through the shot, which no fixed flip map holds. run_qec_program samples them with a forward frame walk next to the leak rows, and each LEAK target adds a herald column to QecSampleResult::heralds (leakage on the compiled QEC path). The reference runner, the record noise sampler and the error model derivation reject them by name, and so does a program pairing them with a feed-forward.

The reference runner applies the Pauli channels stochastically to each shot's state. The density-matrix estimator applies them exactly: the one-qubit channels as Pauli channels, DEPOLARIZE1 as a symmetric one-qubit depolarizing channel, DEPOLARIZE2 as a two-qubit depolarizing channel on each target pair, and PAULI_CHANNEL_2 as a two-qubit Kraus channel of sqrt(p) P terms. The noisy engines for circuits are on Noise Compilation.

Detector error models and decoding

QecProgram::detector_error_model derives the independent error mechanisms behind a program's detectors, and three in-crate decoders consume the result. Both are on QEC Decoding.

Expectation values

EXP_VAL(c) P1*...*Pk estimates c * <P> for the Pauli product P in the program's final state and returns one QecObservableEstimate per op, in op order, in QecSampleResult::expectation_values. Two placement rules define "final state" on every path:

  • Terminal placement: no gate, measurement, reset, or active noise may follow an EXP_VAL op. Detector, observable, postselection and tick metadata may.
  • Live qubits only: a term may not reference a qubit that a single-qubit measurement read after its last reset. The Pauli then commutes with every prior measurement projector, so the sampled post-measurement average equals the measurement-stripped pure-state expectation the analytical strategies compute. MPP does not affect liveness: the deferred lowering measures a scratch alias, and the projected cross terms cancel exactly.
PathSelectionmeanvariance
Density-matrix estimatorrun_qec_program with active noise on an eligible programexact c * Tr(rho P)0.0
Reference runnerrun_qec_program with active noise on an ineligible program, or as the detector-split fallback; run_qec_program_reference directlyper-shot exact c * <P> averaged over accepted shotsunbiased sample variance
Analytical ladder (SPD, CAMPS, tensor network)run_qec_program noiseless; run_qec_program_with_strategyexact c * <P> on the lowered unitaryc^2 * squared SPD truncation weight; 0.0 for CAMPS and tensor network

The reference runner precomputes Pauli masks per observable and evaluates c * <P> on the final statevector of every accepted shot. It reports the sample mean and unbiased sample variance with num_shots equal to the accepted count. Programs wider than 64 qubits (the MPP scratch qubit included) are rejected, since the mask reduction packs X and Z masks into 64-bit words. With noise annotations the per-shot trajectories average to Tr(rho P).

The analytical strategies evaluate <0|U^dag P U|0> on the deferred lowering with the trailing measurements stripped. Record observables become Z strings, and EXP_VAL terms translate through the final qubit aliases. The strategies reject detectors and active noise, which run_qec_program handles through the split and reference routes. QecTStrategy selects the path:

  • Auto, the production ladder. Light-cone SPD runs first (truncation tolerance 1e-10, term cap 16384) and is accepted when every estimate reports no truncation. SPD encodes truncation as variance = total_discarded^2, and variance at or below 1e-12 counts as exact. Otherwise CAMPS runs (bond dimension cap 256) and hard-errors when SVD truncation discards weight above 1e-12, so the ladder falls through to the exact tensor-network scalar fallback. When all three fail, the error reports each stage's reason.
  • Reference, the per-shot oracle.
  • Spd and Camps run their stage directly.

CAMPS evaluates arbitrary X/Y/Z strings by conjugating each letter through the signed Clifford prefix (Y = i * X * Z composes the two inverse-tableau rows). Postselection composes on both paths: the reference runner averages over accepted shots, and the analytical combiner conditions via <O * Pi> / <Pi> over the projector subsets, capped at 12 postselection predicates. The projector Z strings live on measured aliases and never overlap EXP_VAL terms.

run_qec_program_spd_rerouted takes caller-supplied Z stabilizers per observable. It evaluates each rerouted observable on the XOR-equivalent support with the smallest inverse light cone, after verifying via SPD that the substituted stabilizer product holds <S> = +1 in the lowered state. Observables without a reroute use their original support. It rejects EXP_VAL ops, postselection, and resets (resets relabel qubits, making stabilizer indices ambiguous).

tests/integration/qec_exp_val.rs pins routing and placement, and tests/integration/qec_e2e_d3.rs checks distance-3 repetition-code fixtures against closed-form expectations on the compiled, analytical and reference paths.

Result shape

Every runner returns a QecSampleResult. The type is #[non_exhaustive]: construct through new, new_with_total_shots, or empty, and match fields with a trailing ...

FieldMeaning
total_shotsShots requested. accepted_shots + discarded_shots == total_shots.
measurementsRaw measurement records, or a zero-shot buffer when keep_measurements is false (column count preserved).
detectorsOne bit per detector per shot.
observablesOne bit per observable per shot. Synthesized on the analytical path (below).
accepted_shotsShots accepted after postselection (total_shots without a predicate).
discarded_shotsShots rejected by postselection.
logical_errorsPer observable, the count of accepted shots whose parity is 1.
observable_expectationsOptional weighted-estimator expectation per observable; None when the strategy emits raw bit counts only.
expectation_valuesEstimates for the program's EXP_VAL ops, one per op in op order, coefficient-scaled; None when the program has none.

QecObservableEstimate carries mean, variance, and num_shots (shots that contributed, postselection rejections excluded). Zero accepted shots yield {mean: 0.0, variance: 0.0, num_shots: 0}.

Analytical strategies have no per-shot stream, so they synthesize the packed observables records to match the logical_errors counts, with the one-bits at positions [0, accepted_shots) and inert padding after. Derive rates with logical_error_rates (denominator accepted_shots), and do not align these rows shot for shot with detector rows.

The compiled runner delivers shot-major PackedShots record buffers: one row of packed record bits per shot, record j at bit j % 64 of word j / 64. The Clifford+T sampler emits measurement-major records instead, so consumers branch on layout() or read through get_bit. Detector, observable and postselection parities are XORs of the referenced records.

Under QecDetectorReference::Noiseless, detector and observable parities are then XORed with their values in the noiseless reference run. That run is computed once at compile time with every random outcome taken as 0, the hidden collapse of a reset included. The compiled sampler is rebased onto that run's records, so samples depend only on the seed. A reset on a qubit entangled since its last measurement falls back to a forced-outcome stabilizer run for the reference. Postselection and heralds read raw records, and non-Clifford programs report raw parities under either setting. Summary statistics: survivor_rate, logical_error_rates, and their Wilson-interval variants.

QEC Decoding

How a native QEC program becomes a detector error model, how that model is written and read as text, and the three decoders that consume it. Program execution is on QEC programs, and workflow examples in the QEC guide.

Detector error model

QecProgram::detector_error_model derives a DetectorErrorModel: the independent error mechanisms implied by the program's noise annotations, detectors and observables. Matching and belief propagation decoders consume this model rather than raw detector samples.

The derivation reuses the noisy data flow. Every annotation expands into its fault branches, three per target for one-qubit channels and fifteen per pair for two-qubit ones, and zero-probability branches do not fire. Each branch's record mask projects through the detector and observable rows to its symptom, the detectors and observables it flips.

Branches merge into mechanisms at fault-site granularity (one target of a one-qubit annotation, or one target pair of a two-qubit one):

  • Branches at one site are mutually exclusive, so same-symptom branches sum. A DEPOLARIZE1 site whose X and Y branches flip the same records yields one mechanism at exactly 2p/3.
  • Distinct sites are independent, distinct targets of one annotation included, so same-symptom mechanisms compose as p = p1(1-p2) + p2(1-p1).

Faults that flip no detector and no observable are omitted. Mechanisms keep program order (the position of the annotation that first produced each symptom). They are independent in the model even where the branches were exclusive, so model statistics agree with the sampler to second order in the branch probabilities, not exactly.

Sampler semantics carry over. A measurement error argument (M(p)) is a pre-measurement Pauli fault on that record's detectors, noise on an already-measured qubit contributes nothing, and a two-qubit channel with one measured target enters as its exact one-qubit marginal. Non-Clifford gates and reuse of a measured qubit without reset are rejected, as on the noisy compiled sampling path. So are leakage annotations, whose leak flag no independent mechanism expresses.

Hypergraph mechanisms (more than two detectors, as DEPOLARIZE2 produces) stay intact in the derived model, and check-matrix decoders consume them directly. A matching decoder needs the graphlike form, which is opt-in. decompose_graphlike returns a new model in which each hypergraph mechanism is replaced by two or more existing graphlike mechanisms. Their non-empty detector sets partition its detectors, their observable XOR matches it, and the mechanism's probability composes into every component. A DEPOLARIZE2 Y-Y branch, for example, splits into the same channel's single-qubit branches. Cross-component correlations are lost, but single-detector marginals are unchanged. A mechanism with no such cover is an error naming its symptom. Decomposition is never applied silently, and the writer serializes whichever model it is given.

Text format

DetectorErrorModel::to_text renders the model in the common detector error model text format that external matching and belief propagation decoders read. The emitted subset:

error(<p>) D<i> ... L<j> ...
error(<p>) D<i> D<k> ^ D<m> L<j> ...
detector D<i>
detector(<c0>, <c1>, ...) D<i>
logical_observable L<j>
  • One error line per mechanism in mechanism order, with its probability and its D-prefixed detector and L-prefixed observable indices, both ascending.
  • A mechanism on more than two detectors is written as ^-separated components: the suggestion it was imported with, otherwise the cover decompose_graphlike would pick, otherwise flat when no cover exists.
  • One detector line per detector in index order, with the program's detector coordinates when present, and one logical_observable line per observable slot.

Indices are zero-based and dense, and probabilities print with enough digits to round-trip exactly. There are no repeat blocks and no shift_detectors, because derivation merges mechanisms across the whole program by symptom and the per-round structure is not in the model. A distance-13 surface memory over 1000 rounds at uniform circuit noise writes 3.4 million mechanisms, about 200 MB of text.

DetectorErrorModel::from_text reads the format back: error(p) with D, L and ^ targets, detector with optional coordinates, logical_observable, shift_detectors(<coordinate shift>) <detector shift>, and nested repeat N { ... } blocks, expanded as read. Shifts accumulate in program order through the expansion. Instruction names are case-insensitive, error[tag](p) tags are ignored, and # starts a comment. Each error line becomes one mechanism in line order, not merged with others of the same symptom, and a target named twice in one component cancels. Its ^ components are kept as ErrorMechanism::suggested_decomposition. decompose_graphlike splits along them when every component flips one or two detectors, adding any component no existing mechanism matches. Detector and observable counts are one past the highest index named. A repeat whose expansion would exceed 2^25 instructions is rejected before it runs. Export then import reproduces the mechanisms, the detector coordinates, and the text itself.

Example, one syndrome round of the three-qubit repetition memory under X_ERROR(0.05) on the data qubits:

error(0.05) D0
error(0.05) D0 D1
error(0.05) D1
detector D0
detector D1

In Python, QecProgram.detector_error_model() returns the model with probabilities() (float64), detector_matrix() and observable_matrix() (bool, detectors or observables by mechanisms), detector_coords(), suggested_decompositions(), and to_text(). DetectorErrorModel.from_text reads one. The matrix triple feeds check-matrix decoder constructors directly.

Decoders

Three decoders in the crate take a run from samples to a logical error rate with no external tool:

DecoderModelCorrection
UnionFindDecodergraphlikeunion-find with peeling, almost-linear cost
MatchingDecodergraphlikeexact minimum-weight perfect matching
BpOsdDecoderany, hypergraph includedbelief propagation, then ordered statistics

All three compile from a DetectorErrorModel and share one batch driver. decode_packed takes a PackedShots of detector samples in either layout and returns shot-major predicted observable flips. logical_error_rate decodes and counts shots whose prediction differs from the sampled observables in any observable. Scratch is reused across shots, and under the parallel feature large batches split into Rayon chunks with one scratch per chunk. A shot the model cannot explain rejects the batch with an error naming the first such shot.

Mechanisms that flip no detector cannot enter any decoder's graph or check matrix. Their probability mass is a floor under the logical error rate over the model. Mechanisms sharing one detector set collapse to the most probable, in all three decoders.

Union-find

Weighted cluster growth with peeling (Delfosse and Nickerson, arXiv:1709.06218). UnionFindDecoder::from_model compiles a graphlike model: detectors become vertices, a two-detector mechanism an internal edge, a one-detector mechanism a boundary edge, each weighted ln((1-p)/p) clamped at zero. A mechanism with more than two detectors is rejected with a pointer to decompose_graphlike.

Decoding is deterministic: no randomness, ties break by ascending edge index in mechanism order, and serial and Rayon results are identical. Under the parallel feature, batches of at least 1024 shots decode in parallel over 256-shot chunks with no per-shot allocation. A model with no observables decodes serially at any batch size.

On the enumerable distance-3 models the exact union-find failure rate sits between the maximum-likelihood rate and P(two or more faults) plus the measured single-fault misses.

Minimum-weight perfect matching

MatchingDecoder::from_model builds the union-find graph (same edge dedup, same weights) and quantizes every weight to an even integer, 2 * round(w / w_max * 2^23). Matching is exact for the quantized weights. Each shot's correction is a minimum-weight edge set whose boundary is the shot's defects, with the open boundary absorbing any number of chain ends. Construction runs one multi-source Dijkstra from every boundary edge, giving each detector its exact boundary distance.

Per shot the decoder runs Edmonds' primal-dual blossom algorithm in the cut formulation, organized like sparse blossom (Higgott and Gidney, arXiv:2303.15933). Each defect grows its own Dijkstra ball instead of sparse blossom's vertex-owning regions, so a shrinking T node needs no undo on the graph. Every tight pair carries its exact distance, and the result is optimal by LP duality. Arithmetic is exact i64: with even weights every event falls on an integer time.

Per shot with k defects, Dijkstra work is O(B log B) over the B vertex entries the balls settle. The matcher performs at most k augmentations, O(k^2 P log P) worst case over P discovered pairs. At low defect density balls stop at the first collision or the boundary, so work stays close to linear in k. Decoding allocates nothing per shot after warm-up.

Brute-force checks on random graphs of up to 48 detectors confirm optimality, and on the distance-3 models rate_ML <= rate_MWPM <= rate_UF.

BP+OSD

BpOsdDecoder takes any model. Each mechanism flipping at least one detector is a column of the check matrix (detectors are rows) with prior log-likelihood ratio ln((1-p)/p). Belief propagation runs a flooding schedule on the Tanner graph with the product-sum rule or scaled min-sum (default scaling 0.625). It runs at most 30 iterations by default and stops once its hard decision reproduces the syndrome.

A converged decision can still carry a zero-syndrome cycle on top of a lighter solution. On the distance-3 color code, the first min-sum iteration satisfies the syndrome of a single center-qubit fault with that fault plus a weight-3 logical. The decoder therefore reruns the OSD search restricted to the decision's support and the checks it touches, and keeps the lighter of the two, at O(k * r) for a decision of k columns touching r checks.

When belief propagation does not converge, ordered-statistics decoding (Panteleev and Kalachev, arXiv:1904.02703; Roffe et al., arXiv:2005.07016) sorts columns by posterior log-likelihood and reduces the check matrix in that order over GF(2). A nonzero right-hand side below the rank rejects the batch. Each candidate fixes the free (non-pivot) bits and reads the pivot bits from the reduced rows, and the candidate of least prior weight wins:

OsdMethodCandidates
Zerothe all-zero free pattern
CombinationSweep { order }plus every single free bit and every pair among the first order free bits (default order 7)
Exhaustive { order }all 2^order patterns over the first order free bits in Gray-code order; exact maximum-likelihood error decoding once order covers every free column

Belief propagation costs O(iterations * nnz) per shot. Elimination costs O(rank * rows * columns / 64) word operations, and each candidate one packed XOR over the pivot rows plus a weighted walk of its set bits. Batches of 64 shots or more decode in parallel over 16-shot chunks.

On the [15, 7, 5] BCH code every error of weight at most two is recovered under every rule and OSD method. decompose_graphlike drops the correlations of the hyperedges it splits, and that is where BP+OSD gains: on the distance-3 surface memory at p = 0.02 under two-qubit depolarizing noise (20k shots, seed 42), union-find fails 603 times and exact matching 654 times over the decomposed model, BP+OSD 436 times over the full one.

Python exposes UnionFindDecoder(model), MatchingDecoder(model) and BpOsdDecoder(model, ...), each with decode(detectors) -> (shots, num_observables) over numpy bool arrays, decode_packed(detectors) over the packed uint8 rows of packed_detectors(), and logical_error_rate(detectors, observables) over either form.

Threading, SIMD, and Memory Layout

The Capability and Support Matrix lists the SIMD tiers and architectures each backend supports.

Memory layout

BackendState representationMemoryAccess pattern
StatevectorVec<Complex64> (2^n)Strided pair iteration
StabilizerBit-packed Vec<u64> tableau bytesSequential row iteration
Factored StabilizerOne bit-packed tableau per cluster bitsMerge on a bridging gate, split on measurement
SparseFxHashMap<usize, Complex64>, = nonzeroHashed random access
MPSChain of rank-3 tensorsSequential site access
ProductVec<[Complex64; 2]>Each qubit independent
Tensor NetworkNetwork of dense tensorsSet by the contraction order
FactoredVec<Option<SubState>> worst caseDispatch per block state
Density MatrixVec<Complex64> (), a -qubit statevectorStrided pairs on the ket and bra registers
Distributed statevector amplitudes on each of ranks per rankLocal pairs; a pairwise exchange on a rank qubit

Threading

A statevector kernel is a body handed to one of the traversals in statevector/kernels/mod.rs (for_each_hi_half, for_each_half_pair, sum_hi_halves, reduce_half_pairs), and the traversal owns the split. Under the parallel feature it switches to Rayon par_chunks_mut at PARALLEL_THRESHOLD_QUBITS = 15 (src/backend/mod.rs), below which thread-pool overhead exceeds the work. With four or more blocks each block is a task; with fewer, each half splits into tiles of at least MIN_PAR_ELEMS = 4096 amplitudes, 64 KiB. Passes that tile on their own terms, such as one gate over the whole state and the batch phase tables, keep a separate parallel entry point behind the same threshold.

The pool is the process-wide Rayon pool, sized on the first simulation call to every logical core, and RAYON_NUM_THREADS overrides it. Hyperthreads help from 24 qubits by hiding memory latency.

On a CPU with two core classes (Intel's performance and efficiency cores), MPS runs and host statevector runs of 15 and 16 qubits, noisy trajectories included, use a second pool sized to the performance cores. Their kernels split work evenly and wait for the slowest share: on an 8 performance plus 16 efficiency core part, 8 workers beat 24 by 6% to 48% on those runs and lost 16% on a 20 qubit statevector, which keeps the full pool. RAYON_NUM_THREADS, or a call inside a caller's pool, turns the second pool off.

An application that owns the global pool can hand PRISM-Q a bounded one instead: ThreadPool::with_threads(n) builds it and install runs a closure on it, leaving the global pool unbuilt and unresized. Calls outside install take the global path. Pool width can change results (Determinism).

SIMD

One Complex64 fills a 128-bit register. Single-qubit gate kernels use PreparedGate1q with runtime CPU detection and tiered dispatch:

  1. AVX-512 (512-bit): 4 complex pairs per iteration, with masked tails. Opt in through PRISM_AVX512=1 on CPUs with avx512f and avx512vpopcntdq; it follows the same MAX_AVX2_STATE and tile rules as AVX2. Verified under emulation, not yet timed on AVX-512 hardware.
  2. AVX2+FMA (256-bit): 2 complex pairs per iteration. Held back by MAX_AVX2_STATE on passes over the full state (Skylake frequency throttling), and used freely inside MultiFused L2 tiles, where the data sits in cache.
  3. FMA (128-bit): the default for larger states. A complex multiply in three ops (permute, mul, fmaddsub).
  4. SSE2 (128-bit): the x86_64 baseline, 2 mul plus shuffle, xor and add.
  5. NEON (128-bit): the aarch64 baseline, 1 mul plus 1 fma against a negated matrix prepared in advance.
  6. Scalar: no intrinsics, for everything that is neither x86_64 nor aarch64.

_pext_u64 is not a tier. BatchPhase, BatchRzz and DiagonalBatch use it for LUT indexing where BMI2 is present, one bit extraction in place of a shift-and-or loop, and use the loop otherwise.

Two structs broadcast the matrix into registers once, at construction, so the loop over elements does no dispatch:

  • PreparedGate1q, the 2×2 matrix: apply_full_sequential (full state), apply_tiled (a tile in cache, no AVX2 throttle guard), apply_slice_pairs (MPS bond slices), apply_pair_ptr (Cu and Mcu in parallel).
  • PreparedGate2q, the 4×4 matrix: apply_full (iteration by mask), apply_tiled (Multi2q tiles in cache, with the AVX2 kernel over paired groups when available), apply_group_ptr (4 scattered indices).

The 2q tiled AVX2 path processes groups k and k + 1 together when the lower target qubit is above 0, so each row load is contiguous. It falls back to the 128-bit FMA kernel for lo == 0 or without AVX2+FMA. For A/B timing, PRISM_NO_AVX2_2Q forces the 128-bit FMA path and PRISM_NO_REORDER disables the Fused2q reordering that fills each tile.

Determinism

Reproducibility is stated per path. Gate application never reduces across tasks, so it is exactly reproducible. Anything that sums floating-point values in parallel is stable only to about the last ulp, and the batched compiled sampler only at a fixed thread count. tests/determinism.rs pins the dense unitary, terminal sampling, per-shot replay, reduction and compiled-sampler claims below by running the same seeded circuits in scoped 1-thread and 4-thread pools. The trajectory, SPD and stabilizer bullets rest on the mechanisms they state.

Every clause depends on thread count, not on which pool supplied the threads, so a caller-supplied ThreadPool moves exactly the results a different RAYON_NUM_THREADS would: bitwise claims survive it, the reduction bound holds across it, and compiled shot payloads change whenever its width differs from the comparison run's.

  • Unitary evolution on the dense kernels: bitwise, at any thread count. Gate kernels partition the state into index-derived disjoint ranges (fixed chunk boundaries, index bijections for the SendPtr kernels) and write elementwise, so the schedule cannot reach any value. Pinned bitwise for representative fused circuits and a QFT.
  • Terminal sampling on the dense route: bitwise for a given seed, at any thread count, when the measurement map covers the register directly. Shot thresholds are drawn and sorted up front from the seeded generator, the probability vector is an elementwise transform, and the CDF walk is sequential. A measurement map that compacts into fewer outcomes builds its histogram through a parallel reduction and moves to the ulp-stable class below.
  • Noisy trajectory shots: bitwise for a given seed, at any thread count. Each shot's generator is seeded from the run seed and the shot index, not the worker, and results are collected in shot order. Pauli-noise runs that simulate each distinct error pattern once keep the rule, since a shot's pattern, outcome and readout flips all draw from its own seed. So do damping runs that walk the shared no-jump state once: a shot copies the walk where its own draws leave it, whichever worker walked that far. Pauli noise on a Clifford circuit usually takes the compiled family instead, and on the noisy compiled sampler its shots depend on the pool width (see compiled sampling below).
  • Native block sampling: bitwise for a given seed, at any thread count. The sparse, factored and product-state samplers draw shots in blocks of 256, each block from its own ChaCha8 stream keyed on the block index. The blocks depend on the shot count alone, so filling them in parallel moves no bit. The dense sampler over factored block probabilities walks the same blocks. Pinned for all three backends.
  • Per-shot replay: bitwise for a given seed, at any thread count. A circuit with a mid-circuit measurement, a condition or a region runs once per shot off the host statevector, and below the width where the resolved engine's own kernels go parallel those runs split across workers: 15 qubits for dense engines, 128 for a tableau, any width for a product state. Noisy trajectories follow the same rule, except on the host statevector, where they split below 19 qubits and each shot runs its kernels serially, so their reductions keep one order at any thread count. Shot i runs on a seed hashed from the run seed and i with SplitMix64, and results fold in shot order. Adjacent run seeds draw unrelated shots, not the same shots offset by one. Pinned for decomposed, tableau and product-state circuits, and for tableau trajectories.
  • Outcome branching: bitwise for a given seed, at any thread count. A noiseless circuit of that kind on the host statevector evolves once per distinct outcome history instead: at each measurement the shots on a branch split by a binomial draw from a generator seeded by the run seed and the branch's outcome path, and from 10 qubits up to the dense floor the two sides of a split run on separate workers. Rows are laid out in record order, then shuffled from the run seed, so the schedule reaches neither. The split compares a draw against a collapse probability, which above the dense floor is a parallel reduction and carries the caveat below. Once only measurements remain, a branch draws its readout from its own state through the terminal sampler, seeded from its outcome path. A dynamic program on the host statevector walks its graph the same way. Pinned for 8-, 12- and 16-qubit circuits and a 12-qubit program.
  • Parallel reductions: stable to about 1e-12, not bitwise. Norms, measurement collapse probabilities, reduced density matrices, and expectation values sum deterministic per-chunk partials in Rayon's combine order, which varies with pool width and work stealing. A mid-circuit measurement compares a seeded draw against such a sum, so an outcome flip is possible in principle when the draw lands inside the ulp gap.
  • Compiled QEC noise: bitwise for a given seed, at any thread count and chunk size. Noise draws per fixed 8192-shot unit from a counter-based stream indexed by the unit, and each unit writes only its own shots, so neither the schedule nor chunk_size reaches a fault. Pinned in tests/integration/qec_ir.rs with 1-thread and 4-thread pools.
  • Compiled (BTS) sampling: reproducible at a fixed thread count, on any ISA. The batched sampler derives one RNG stream per worker and splits shots by rayon::current_num_threads(), so another pool width yields a different, equally distributed shot set. Pin the width when byte-identical payloads matter across machines: RAYON_NUM_THREADS on the global path, the ThreadPool::with_threads width on the scoped one. The noisy compiled sampler, which takes Pauli noise on most Clifford circuits, depends on the width the same way: from 4,096 shots its scalar and pair noise passes split the shots into one chunk per Rayon thread and seed each chunk from the master stream, so one seed gives different shots at another pool width. Within a stream the AVX-512, AVX2, NEON and scalar kernels lay the same four xoshiro lanes over the shot words, so an x86 host and an Apple or Graviton host draw the same shots from one seed; tests/integration/qec_ir.rs pins the noiseless fingerprint on every CI platform. Noise draws go through the platform's exp and ln, so a noisy payload is bitwise on one platform and can differ across C libraries on the rare draw that lands within an ulp of a threshold. The GPU analogue is documented in the GPU guide.
  • SPD analytic estimates: stable to about 1e-12 between runs. Hash-order term accumulation moves the last ulp even at a fixed thread count, and tests carry that tolerance.
  • Stabilizer tableau: bitwise, at any thread count. Row operations are integer and exactly associative. MPS carries no bitwise claim: truncation runs through faer's threaded SVD.

Error Model and Public API

Error model

Fallible public APIs return Result<T, PrismError>. Error variants:

VariantCategoryDescription
ParseParsingOpenQASM parse error with line number
UnsupportedConstructParsingValid OpenQASM not supported by PRISM-Q
UndefinedRegisterParsingReference to undeclared register
InvalidQubitValidationQubit index exceeds register size
InvalidClassicalBitValidationClassical bit index exceeds register
GateArityValidationWrong number of qubits for gate
InvalidParameterValidationInvalid gate parameter (NaN, etc.)
ExportUnsupportedExportInstruction with no OpenQASM 3.0 spelling
BackendUnsupportedRuntimeBackend can't perform requested operation
IncompatibleBackendRuntimeBackend incompatible with circuit
StepLimitRuntimeA dynamic program shot ran more blocks than its step bound; names the loop
ResourceLimitRuntimeAn allocation over a memory cap; the boxed ResourceLimit carries the operation, the ResourceKind unit, required and limit, and the environment variable that overrides the cap

Note

Invalid input data (QASM text, incompatible backend) returns PrismError. API misuse (out-of-range indices, wrong-variant accessors) panics, and each such method documents the condition under # Panics. debug_assert! is used for internal invariants only.

Public API surface

Top-level re-exports from src/lib.rs. The full generated documentation is on docs.rs.

AreaItems
Simulationsimulate, Simulate, Unseeded, Seeded, run_on, run_on_state, run_qasm, PauliObservable, ObservableExpectation, ObservableVariance, ExpectationResult, OverlapResult, bitstring
Route inspectionQuery, Plan, PlanFallback, PlannedExactness, RejectReason, RouteRule, MemoryEstimate, MemoryEstimateKind
LimitsLimits, LimitKnob, LimitSource, default_limits, set_default_limits
Dynamic programsDynamicProgram, DynamicProgramBuilder, simulate_program, SimulateProgram
GradientsExpectationGradient, returned by Simulate::expectation_gradient, Simulate::expectation_gradient_shift and the PreparedCircuit methods of the same names, all taking the Hamiltonian as a PauliObservable
ParametersParameters, ParamLink, PreparedCircuit
Compiled samplingcompile_measurements, compile_forward, compile_detector_sampler, compile_noisy, run_shots_compiled, run_shots_noisy, noisy_marginals_analytical, density_matrix_expectation_values, CompiledSampler, CompiledDetectorSampler, DetectorSampleBatch; with gpu: run_shots_compiled_with_gpu, DevicePackedShots
AccumulatorsShotAccumulator, HistogramAccumulator, MarginalsAccumulator, PauliExpectationAccumulator, CorrelatorAccumulator, NullAccumulator, PackedShots, ShotLayout, ParityStats
NoiseNoiseModel, NoiseBuilder, NoiseChannel, NoiseEvent, GateFilter, ReadoutError, DriftDistribution, NoisyCompiledSampler, DeviceCalibration, QubitCalibration, GateCalibration, GateTimes, ErrorChainComplex
Native QECparse_qec_program, compile_qec_program_rows, run_qec_program, run_qec_program_reference, run_qec_program_with_strategy, run_qec_program_spd_rerouted, QecProgram, QecOp, QecOptions, QecSampleResult, QecBasis, QecPauli, QecRecordRef, QecNoise, QecCorrelatedBranch, QecCircuitNoise, QecDetectorReference, QecMeasurementRow, QecCompiledRows, QecCompiledSampler, QecObservableEstimate, QecObservableReroute, QecTStrategy
QEC decodingDetectorErrorModel, ErrorMechanism, UnionFindDecoder, MatchingDecoder, BpOsdDecoder, BpOsdOptions, BpMethod, OsdMethod
Clifford+Trun_stabilizer_rank, run_stabilizer_rank_approx, stabilizer_overlap_sq, stabilizer_inner_product, StabRankResult, run_spp, run_spp_observable, run_spd, run_spd_with, run_spd_observable, run_spd_observable_budgeted, run_spd_observable_light_cone, inverse_light_cone, PauliAxis, PauliTerm, SppResult, SppObservableResult, SpdResult, SpdObservableResult, SpdTruncation
Circuits and gatesCircuit, CircuitBuilder, TrotterOrder, Instruction, ClassicalCondition, SaveSpec, SaveRecord, SavedValue, SvgOptions, TextOptions, Gate, GeneratorKind, McuData, UnitaryData
Results and provenanceBackendKind, RunOutcome, CountsResult, MarginalsResult, ShotsResult, ReducedDensityMatrix, EntropyResult, Probabilities, FactoredBlock, RunMetadata, BondReport, Engine, Exactness, Placement, ResolvedBackend
ErrorsPrismError, ResourceLimit, ResourceKind, Result
BackendsStatevectorBackend, StabilizerBackend, SparseBackend, MpsBackend, ProductStateBackend, TensorNetworkBackend, FactoredBackend, FactoredStabilizerBackend, DensityMatrixBackend; with distributed: DistributedStatevectorBackend, DistributedContext, RankComm, SerialComm; with distributed-mpi: MpiComm
Threadingwith parallel: ThreadPool, a Rayon pool the caller supplies, which simulation runs inside instead of sizing the process-wide one; see Threading, SIMD, and Memory Layout

Not re-exported at the root but part of the documented surface: the Backend trait and BasisSamples at prism_q::backend, run_batch at prism_q::sim, parse_dynamic and the IR types under prism_q::circuit::openqasm and prism_q::circuit::dynamic, and the accumulator chunk size helpers (default_chunk_size, optimal_chunk_size) at prism_q::sim::compiled. Backend is sealed: only the crate implements it, so a new method is additive. Items behind the bench-internal feature (bench_variant, the sweep profile helpers, QecProfiledSampler) are benchmark tooling, not public API.

The complete item list is checked in as public-api.txt, generated by cargo public-api with --features "parallel gpu distributed". CI regenerates it and fails on a difference, so every surface change shows in review as a diff to that file.

Save points

Circuit::add_save appends an Instruction::Save recording a SaveSpec, and Simulate::run returns one SaveRecord per point in RunOutcome::saves, carrying a SavedValue. See Circuit IR for what a save does to fusion and which routes decline one.

Batches

prism_q::sim::run_batch runs a list of circuits, holding one backend across those of the same width that draw no randomness. Results match running each circuit alone with the same seed. Under parallel, batches of circuits up to 16 qubits split across cores, one circuit per core with each run single threaded. Wider batches run one circuit at a time on the kernels' own threads.

State diagnostics

  • Simulate::reduced_density_matrix returns a ReducedDensityMatrix (row major, side 2^k, qubits[0] the lowest bit of the row index) with purity for Tr(rho^2).
  • Simulate::entanglement_entropy returns an EntropyResult: the von Neumann entropy in nats and the descending Schmidt spectrum, None where the backend holds the entropy without the spectrum.
  • Simulate::overlap takes a second seeded builder over a circuit of the same width and returns an OverlapResult: the squared inner product and the provenance of both runs.

All three require a unitary circuit, and under BackendKind::Auto a route that cannot answer falls back to the statevector. Backends tabulates which backends answer each.

Prepared circuits

PreparedCircuit answers the Simulate terminals on a bound circuit, each with a _many form over a list of bindings. Parameters, Binding and Gradients lists the terminals and how the batches split.

Growth of the public enums

Public enums are #[non_exhaustive] unless named below. A new gate, backend, engine label, error variant, noise channel, truncation policy, dialect, result request or result value is an additive release, so a match from outside the crate keeps a wildcard arm. RunMetadata is #[non_exhaustive] too: a new field is additive, and outside code reads it rather than building it.

Instruction stays exhaustive. It is the circuit IR, and a new instruction kind changes what every consumer handles, so adding one is a breaking change.

Enums mirroring a closed mathematical set stay exhaustive as well, since a wildcard arm the caller can never reach buys nothing: PauliAxis and QecBasis are X, Y and Z, GeneratorKind and DiagEntry are gate-algebra shapes, and QftTextbookStep is a fixed decomposition.

Performance

Report a benchmark resultNumbers that differ on your machine, a method question, or a missing simulator: the form asks for the host, the command and the rows.

Median wall time per call for PRISM-Q and other simulators on the same gate lists. Each simulator's output at its top thread count on a row is checked against a reference: dense vectors by total variation distance, samples by per-statistic tests, expectation values by absolute difference. Records below the top thread count, rows under 100 shots (deterministic bits only) and the reference output itself are not checked; tables mark them.

These numbers come from one host and the harness in comparison/. If the method looks wrong, a number does not reproduce, or a simulator should be added, open a benchmark issue.

  • Host Intel64 Family 6 Model 198 Stepping 2, GenuineIntel, 24 cores, 24 threads, Windows 11, 31.5 GB RAM, NVIDIA GeForce RTX 5070 Ti (16 GB) for the GPU rows. Every number on this page comes from this host.
  • Run 20261121T232653-02f5f1, profile reference, started 2026-11-22, commit ba6bb2cd83 with uncommitted changes, 9.3 h of measurement, 26 supplementary runs.
  • Protocol One process per measurement: a cold call, then a set of warm calls; the median warm call is reported.
  • Ratio Peer median time / PRISM-Q median time. Warm samples within one process agree closely, but between runs of identical code on this host most rows moved by up to about 10% and some, mostly MPS and tensor network calls, by up to about 2x. Ratios within 0.9x to 1.1x are not distinguishable, and on those rows a gap under 2x is indicative only.
  • Raw data comparison/results/matrix-ultra7-270k/; how it was taken: Benchmark Methodology.

All sections · peer time over PRISM-Q time

Peer median time over PRISM-Q median time, per section and peer

Thread counts, PRISM-Q matched to the peer: Aer automatic, Aer density matrix, Aer MPS, Aer MPS cap 256, Aer stabilizer, Aer, Aer fp32, PRISM-Q Python, qip, qsim fp32, QuEST, QuEST DM GPU, QuEST GPU, quimb MPS cap 256, quimb TN and Spinoza at 24 threads; PyMatching and Stim at 1 thread

Exact numbers
SectionPeerPrecisionThreadsRowsRange
Statevector, fp64Aerdouble, PRISM-Q double24155.53x to 13.2x
Statevector, fp64QuESTdouble, PRISM-Q double24156.04x to 73.2x
Statevector, fp64Spinozadouble, PRISM-Q double24724.0x to 81.5x
Statevector, fp64qipdouble, PRISM-Q double24928.2x to 120x
Statevector against fp32 peersAer fp32fp32 peer, PRISM-Q fp6424113.15x to 7.62x
Statevector against fp32 peersqsim fp32fp32 peer, PRISM-Q fp6424151.75x to 19.4x
StabilizerStimexact (tableau), PRISM-Q double131.70x to 5.13x
High-shot stabilizerStimexact (tableau), PRISM-Q double1530.1x to 67.6x
Matrix product stateAer MPSdouble, PRISM-Q double246114x to 1127x
Deep MPSAer MPS cap 256double, PRISM-Q double24154.67x to 77.0x
Deep MPSquimb MPS cap 256double, PRISM-Q double24109.42x to 22.8x
Tensor network expectation valuesquimb TNdouble, PRISM-Q double24856.4x to 397x
Tensor network expectation valuesAer MPSdouble, PRISM-Q double2481.43x to 7.38x
Shot samplingAerdouble, PRISM-Q double2464.74x to 127x
Shot samplingAer fp32fp32 peer, PRISM-Q fp642463.92x to 132x
Shot samplingqsim fp32fp32 peer, PRISM-Q fp642461.72x to 42.9x
Disjoint componentsAer MPSdouble, PRISM-Q double244104x to 914x
Circuit zoo, statevectorAerdouble, PRISM-Q double24121.85x to 13.2x
Circuit zoo, statevectorQuESTdouble, PRISM-Q double24122.43x to 31.0x
Circuit zoo, statevectorSpinozadouble, PRISM-Q double2449.21x to 38.5x
Circuit zoo, statevectorqipdouble, PRISM-Q double24810.6x to 56.5x
Circuit zoo, statevectorAer fp32fp32 peer, PRISM-Q fp642461.70x to 3.80x
Circuit zoo, statevectorqsim fp32fp32 peer, PRISM-Q fp6424121.13x to 10.7x
Circuit zoo, stabilizerStimexact (tableau), PRISM-Q double1611.1x to 240x
Circuit zoo, stabilizerAer stabilizerexact (tableau), PRISM-Q double2427653x to 57604x
Circuit zoo, W stateAer MPSdouble, PRISM-Q double2432475x to 7972x
GPU statevector, fp64QuEST GPUdouble, PRISM-Q double24263.09x to 9.23x
Mid-circuit dynamic circuitsAerdouble, PRISM-Q double243358x to 4021x
Mid-circuit dynamic circuitsAer automaticdouble, PRISM-Q double242362x to 951x
Mid-circuit dynamic circuitsStimexact (tableau), PRISM-Q double130.28x to 0.86x
Mid-circuit dynamic circuitsAer stabilizerexact (tableau), PRISM-Q double24323.4x to 1804x
Python bindingsPRISM-Q Pythondouble, PRISM-Q double24100.48x to 1.09x
Python bindingsAerdouble, PRISM-Q double2464.67x to 51.9x
Python bindingsqsim fp32fp32 peer, PRISM-Q fp642461.79x to 20.0x
Python bindingsStimexact (tableau), PRISM-Q double121.94x to 5.30x
Python bindingsAer MPSdouble, PRISM-Q double2421.89x to 799x
Python bindingsquimb TNdouble, PRISM-Q double24165.7x
QEC detector samplingStimexact (tableau), PRISM-Q double1114.56x to 17.2x
QEC syndrome decodingPyMatchingexact (mwpm), PRISM-Q double191.02x to 2.57x
Exact density matrixAer density matrixdouble, PRISM-Q double24140.53x to 3.16x
Exact density matrixQuEST DM GPUdouble, PRISM-Q double24100.63x to 1.90x
Noisy trajectoriesAerdouble, PRISM-Q double24354.6x to 286x
Noisy trajectoriesAer MPSdouble, PRISM-Q double2460.50x to 1700x
Noisy MPO expectation valuesAer density matrixdouble, PRISM-Q double2441.75x to 82.9x
Adjoint gradientsPRISM-Q Pythondouble, PRISM-Q double24140.79x to 1.08x
Variational parameter sweepsPRISM-Q Pythondouble, PRISM-Q double2460.65x to 1.03x
Variational parameter sweepsAerdouble, PRISM-Q double2462.04x to 44.7x
Clifford+T circuitsAerdouble, PRISM-Q double248115x to 16761x
Clifford+T circuitsAer MPSdouble, PRISM-Q double244176x to 215x
Sparse statevectorAerdouble, PRISM-Q double2429.30x to 67.3x
Sparse statevectorAer MPSdouble, PRISM-Q double24649.7x to 3661x
Sparse statevectorAer automaticdouble, PRISM-Q double2448.91x to 12881x

Scaling to the ceiling

  • Each simulator climbs each ladder until a rung times out (120 s on the Stabilizer, Tensor network and Factored ladders; 300 s on the Statevector and MPS ladders), is refused for memory or takes longer than 60 s for its cold call; wider rungs are then skipped. Timeouts and memory refusals mark ceilings on the chart; failed checks remain failures.
  • Cold calls are timed inside each process: QuEST, Spinoza and qip report them from their runners, excluding process start and output serialization.
  • Dense ladders force PRISM-Q's statevector so every rung is exact; past its memory cap, automatic dispatch would switch representations.
  • PRISM-Q's statevector runs with PRISM_MAX_SV_QUBITS=30, the widest state the harness admits for any dense peer (80% of RAM), in place of its default cap of half of physical memory.
  • Stim runs single-threaded, so the stabilizer ladders also run PRISM-Q at 1 thread.
  • PRISM-Q GPU and QuEST GPU run the statevector on the NVIDIA GeForce RTX 5070 Ti (16 GB); the timed call includes copying the probability vector back to the host. Linux-only GPU peers (cuStateVec, Aer GPU, qsim GPU, lightning.gpu) were not measured on Windows.
  • Random brickworkStatevector28qubitsPRISM-Q statevector · 1.73 s · top of the ladderwidest fp64 peer: QuEST at 28fp32 peer: qsim fp32 at 28GPU: PRISM-Q GPU at 28, widest GPU peer: QuEST GPU at 28
  • QFTStatevector28qubitsPRISM-Q statevector · 1.28 s · top of the ladderwidest fp64 peer: Aer at 28fp32 peer: qsim fp32 at 26GPU: PRISM-Q GPU at 28, widest GPU peer: QuEST GPU at 28
  • QAOA, 3-regularStatevector28qubitsPRISM-Q statevector · 860 ms · top of the ladderwidest fp64 peer: QuEST at 28fp32 peer: qsim fp32 at 28GPU: PRISM-Q GPU at 28, widest GPU peer: QuEST GPU at 28
  • Hardware-efficient ansatzStatevector28qubitsPRISM-Q statevector · 1.33 s · top of the ladderwidest fp64 peer: QuEST at 28fp32 peer: qsim fp32 at 28GPU: PRISM-Q GPU at 28, widest GPU peer: QuEST GPU at 28
  • GHZCompiled stabilizer10,000qubitsPRISM-Q · 1.18 ms · top of the ladderwidest exact peer: Aer stabilizer at 1001 thread: PRISM-Q 10,000, Stim 10,000
  • Bernstein-VaziraniCompiled stabilizer10,000qubitsPRISM-Q · 16.8 ms · top of the ladderwidest exact peer: Aer stabilizer at 1001 thread: PRISM-Q 10,000, Stim 10,000
  • Clifford brickworkCompiled stabilizer10,000qubitsPRISM-Q · 96.3 ms · top of the ladderno fp64 peer ran1 thread: PRISM-Q 10,000, Stim 10,000
  • Shallow brickworkMPS3,000qubitsPRISM-Q · 145 ms · top of the ladderwidest fp64 peer: Aer MPS at 1,000
  • W stateMPS3,000qubitsPRISM-Q · 51.2 ms · top of the ladderwidest fp64 peer: Aer MPS at 1,000
  • Random brickworkTensor network1,024qubitsPRISM-Q · 10.6 ms · top of the ladderwidest fp64 peer: quimb TN at 1,024
  • Ising chainTensor network1,024qubitsPRISM-Q · 7.41 ms · top of the ladderwidest fp64 peer: quimb TN at 1,024
  • Disjoint 10-qubit blocksDecomposed10,000qubitsPRISM-Q · 2.05 s · top of the ladderwidest fp64 peer: Aer MPS at 1,000

Time against register width · every simulator until its ceiling

Widest PRISM-Q run on the CPU per method: 28 statevector, 10,000 stabilizer, 3,000 MPS, 1,024 tensor network and 10,000 factored

Whiskers span the 25th to 75th percentile of the warm calls. A marker above a cell names the rung where a simulator stopped; a hollow point failed its check. ‡ reference output with no cross-check by a second simulator.

Exact numbers
LadderSimulatorPrecisionLargest registerMedian thereStopped by
Random brickworkQuESTdouble28166.98 sone call over the rung budget at 28 qubits
Random brickworkqsim fp32single284.38 stop of the ladder
Random brickworkQuEST GPUdouble2810.89 stop of the ladder
Random brickworkPRISM-Q GPUdouble281.75 stop of the ladder
Random brickworkPRISM-Q statevectordouble281.73 stop of the ladder
Random brickworkAerdouble28‡11.48 stop of the ladder
QFTQuESTdouble241.80 stimeout at 26 qubits
QFTqsim fp32single2688.68 sone call over the rung budget at 26 qubits
QFTAerdouble28‡17.30 stop of the ladder
QFTQuEST GPUdouble283.73 stop of the ladder
QFTPRISM-Q GPUdouble28403 mstop of the ladder
QFTPRISM-Q statevectordouble281.28 stop of the ladder
QAOA, 3-regularQuESTdouble2813.34 stop of the ladder
QAOA, 3-regularqsim fp32single281.90 stop of the ladder
QAOA, 3-regularAerdouble28‡5.23 stop of the ladder
QAOA, 3-regularPRISM-Q statevectordouble28860 mstop of the ladder
QAOA, 3-regularQuEST GPUdouble281.64 stop of the ladder
QAOA, 3-regularPRISM-Q GPUdouble28322 mstop of the ladder
Hardware-efficient ansatzQuESTdouble2848.81 stop of the ladder
Hardware-efficient ansatzqsim fp32single285.36 stop of the ladder
Hardware-efficient ansatzAerdouble28‡10.33 stop of the ladder
Hardware-efficient ansatzPRISM-Q statevectordouble281.33 stop of the ladder
Hardware-efficient ansatzPRISM-Q GPUdouble28973 mstop of the ladder
Hardware-efficient ansatzQuEST GPUdouble284.54 stop of the ladder
GHZPRISM-Qdouble10,0001.18 mstop of the ladder
GHZPRISM-Q 1 threaddouble10,0001.19 mstop of the ladder
GHZStimexact (tableau)10,000285 mstop of the ladder
GHZAer stabilizerexact (tableau)100858 mstimeout at 1,000 qubits
Bernstein-VaziraniPRISM-Q 1 threaddouble10,00016.3 mstop of the ladder
Bernstein-VaziraniPRISM-Qdouble10,00016.8 mstop of the ladder
Bernstein-VaziraniStimexact (tableau)10,000206 mstop of the ladder
Bernstein-VaziraniAer stabilizerexact (tableau)100859 mstimeout at 1,000 qubits
Clifford brickworkPRISM-Q 1 threaddouble10,00092.0 mstop of the ladder
Clifford brickworkPRISM-Qdouble10,00096.3 mstop of the ladder
Clifford brickworkStimexact (tableau)10,000384 mstop of the ladder
Clifford brickworkAer stabilizerexact (tableau)nonen/atimeout at 1,000 qubits
Shallow brickworkPRISM-Qdouble3,000145 mstop of the ladder
Shallow brickworkPRISM-Q MPS cap 64double3,000138 mstop of the ladder
Shallow brickworkAer MPSdouble1,00055.23 stimeout at 3,000 qubits
Shallow brickworkquimb MPS cap 64double100121.58 sone call over the rung budget at 100 qubits
W statePRISM-Q MPS cap 64double3,00049.4 mstop of the ladder
W statePRISM-Qdouble3,00051.2 mstop of the ladder
W stateAer MPSdouble1,00057.52 stimeout at 3,000 qubits
W statequimb MPS cap 64double100120.68 sone call over the rung budget at 100 qubits
Random brickworkquimb TNdouble1,0242.70 stop of the ladder
Random brickworkAer MPSdouble1,024227 mstop of the ladder
Random brickworkPRISM-Q TNdouble1,02410.3 mstop of the ladder
Random brickworkPRISM-Qdouble1,02410.6 mstop of the ladder
Ising chainquimb TNdouble1,0241.01 stop of the ladder
Ising chainAer MPSdouble1,02463.2 mstop of the ladder
Ising chainPRISM-Q TNdouble1,0246.85 mstop of the ladder
Ising chainPRISM-Qdouble1,0247.41 mstop of the ladder
Disjoint 10-qubit blocksPRISM-Q factoreddouble10,00018.18 stop of the ladder
Disjoint 10-qubit blocksPRISM-Qdouble10,0002.05 stop of the ladder
Disjoint 10-qubit blocksAer MPSdouble1,00049.49 stimeout at 3,000 qubits

Statevector, fp64

  • QFT rows take their gate list from PRISM-Q's qft_circuit generator, and PRISM-Q recognizes that expansion and runs it as one FFT block; the control below reruns PRISM-Q with PRISM_NO_QFT_BLOCK=1, gate by gate.
  • The timed call ends at the simulator's own result: PRISM-Q, QuEST, Spinoza and qip, a probability vector; Aer, a Result holding the probability vector.
  • 15 rows take their reference vector from one simulator with no cross-check by a second.
  • Every simulator here stores 2^n complex amplitudes in double precision.
  • Output is the full probability vector, checked against Aer by total variation distance.

Statevector · fp64 · full probability vector

Aer takes 5.53x to 13.2x the PRISM-Q time, 16 to 28 qubits

‡ reference output with no cross-check by a second simulator.

Exact numbers
WorkloadPRISM-QAerQuESTSpinozaqip
rcs 20q d107.11 ms40.0 ms (5.62x)‡75.4 ms (10.6x)379 ms (53.3x)225 ms (31.6x)
rcs 24q d10104 ms642 ms (6.17x)‡5.86 s (56.4x)6.64 s (63.8x)9.81 s (94.3x)
rcs 26q d10409 ms2.79 s (6.82x)‡26.84 s (65.6x)not runnot run
rcs 28q d101.72 s11.48 s (6.65x)‡115.73 s (67.1x)not runnot run
rcs 20q d2011.4 ms79.6 ms (6.97x)‡150 ms (13.1x)752 ms (65.8x)435 ms (38.1x)
rcs 24q d20163 ms1.25 s (7.72x)‡11.69 s (71.9x)13.25 s (81.5x)19.42 s (120x)
rcs 26q d20734 ms5.46 s (7.43x)‡53.50 s (72.9x)not runnot run
rcs 28q d203.16 s22.47 s (7.12x)‡231.11 s (73.2x)not runnot run
qft 20q4.02 ms33.2 ms (8.27x)‡24.3 ms (6.04x)cannot run113 ms (28.2x)
qft 24q72.9 ms822 ms (11.3x)‡1.60 s (22.0x)cannot run4.52 s (61.9x)
qft 26q315 ms3.86 s (12.3x)‡8.03 s (25.5x)not runnot run
qft 28q1.31 s17.30 s (13.2x)‡36.47 s (27.8x)not runnot run
qv 16q2.13 ms19.0 ms (8.90x)‡38.7 ms (18.2x)51.2 ms (24.0x)77.6 ms (36.4x)
qv 20q13.3 ms82.2 ms (6.20x)‡203 ms (15.3x)643 ms (48.5x)560 ms (42.2x)
qv 24q254 ms1.40 s (5.53x)‡15.40 s (60.8x)16.61 s (65.5x)27.44 s (108x)

Cold call, fastest warm call, the time Aer reports for itself, and the smallest shift in a marginal a sampled check detects:

WorkloadPRISM-QAerQuESTSpinozaqip
rcs 20q d10cold 8.37 ms, fastest 6.58 mscold 51.5 ms, fastest 39.4 ms, internal 34.3 mscold 84.6 ms, fastest 74.9 mscold 371 ms, fastest 350 mscold 234 ms, fastest 222 ms
rcs 24q d10cold 103 ms, fastest 98.8 mscold 634 ms, fastest 640 ms, internal 635 mscold 5.86 s, fastest 5.84 scold 6.64 s, fastest 6.62 scold 9.79 s, fastest 9.80 s
rcs 26q d10cold 406 ms, fastest 404 mscold 2.78 s, fastest 2.79 s, internal 2.79 scold 26.81 s, fastest 26.84 snot runnot run
rcs 28q d10cold 1.70 s, fastest 1.72 scold 11.57 s, fastest 11.46 s, internal 11.47 scold 115.76 s, fastest 115.72 snot runnot run
rcs 20q d20cold 15.5 ms, fastest 11.2 mscold 88.5 ms, fastest 77.7 ms, internal 68.3 mscold 170 ms, fastest 149 mscold 732 ms, fastest 737 mscold 442 ms, fastest 434 ms
rcs 24q d20cold 169 ms, fastest 162 mscold 1.25 s, fastest 1.23 s, internal 1.24 scold 11.73 s, fastest 11.69 scold 13.33 s, fastest 13.22 scold 19.44 s, fastest 19.42 s
rcs 26q d20cold 745 ms, fastest 727 mscold 5.48 s, fastest 5.45 s, internal 5.44 scold 53.58 s, fastest 53.47 snot runnot run
rcs 28q d20cold 3.17 s, fastest 3.15 scold 22.43 s, fastest 22.40 s, internal 22.46 scold 231.05 s, fastest 230.87 snot runnot run
qft 20qcold 6.25 ms, fastest 3.59 mscold 40.6 ms, fastest 27.9 ms, internal 28.2 mscold 29.7 ms, fastest 22.9 mscannot runcold 117 ms, fastest 113 ms
qft 24qcold 74.8 ms, fastest 71.6 mscold 822 ms, fastest 807 ms, internal 816 mscold 1.62 s, fastest 1.60 scannot runcold 4.53 s, fastest 4.49 s
qft 26qcold 314 ms, fastest 313 mscold 3.84 s, fastest 3.83 s, internal 3.86 scold 8.01 s, fastest 8.02 snot runnot run
qft 28qcold 1.28 s, fastest 1.31 scold 17.25 s, fastest 17.28 s, internal 17.29 scold 36.42 s, fastest 36.46 snot runnot run
qv 16qcold 21.4 ms, fastest 1.93 mscold 20.4 ms, fastest 18.2 ms, internal 11.3 mscold 41.1 ms, fastest 38.3 mscold 53.0 ms, fastest 50.4 mscold 83.7 ms, fastest 76.2 ms
qv 20qcold 17.6 ms, fastest 13.0 mscold 89.4 ms, fastest 81.0 ms, internal 69.8 mscold 199 ms, fastest 184 mscold 657 ms, fastest 624 mscold 565 ms, fastest 557 ms
qv 24qcold 258 ms, fastest 251 mscold 1.38 s, fastest 1.40 s, internal 1.38 scold 15.38 s, fastest 15.39 scold 16.62 s, fastest 16.61 scold 27.41 s, fastest 27.43 s
QFT controlPRISM-QPRISM-Q, QFT recognition offAer
qft 20q4.02 ms7.58 ms33.2 ms‡
qft 24q72.9 ms64.9 ms822 ms‡
qft 26q315 ms279 ms3.86 s‡
qft 28q1.31 s1.29 s17.30 s‡

Statevector against fp32 peers

  • QFT rows take their gate list from PRISM-Q's qft_circuit generator, and PRISM-Q recognizes that expansion and runs it as one FFT block; the control below reruns PRISM-Q with PRISM_NO_QFT_BLOCK=1, gate by gate.
  • The timed call ends at the simulator's own result: PRISM-Q and qsim fp32, a probability vector; Aer fp32, a Result holding the probability vector.
  • qsim runs with max_fused_gate_size 3 at 16 and 20 qubits and 4 at 24, 26 and 28 qubits.
  • qsim and Aer fp32 store single-precision amplitudes, half the bytes PRISM-Q moves per amplitude.
  • fp32 outputs are checked at a tolerance of 1e-5 instead of 1e-8.

Statevector · PRISM-Q fp64, peers fp32

qsim fp32 takes 1.75x to 19.4x the PRISM-Q time, 16 to 28 qubits

Exact numbers
WorkloadPRISM-QAer fp32qsim fp32
rcs 20q d107.11 ms31.5 ms (4.44x)12.4 ms (1.75x)
rcs 24q d10104 ms390 ms (3.75x)201 ms (1.93x)
rcs 26q d10409 ms1.65 s (4.02x)966 ms (2.36x)
rcs 28q d101.72 s6.76 s (3.92x)4.03 s (2.34x)
rcs 20q d2011.4 ms62.8 ms (5.50x)22.9 ms (2.01x)
rcs 24q d20163 ms741 ms (4.56x)373 ms (2.30x)
rcs 26q d20734 ms3.22 s (4.38x)1.82 s (2.48x)
rcs 28q d203.16 s13.22 s (4.19x)7.74 s (2.45x)
qft 20q4.02 mscrash15.3 ms (3.80x)
qft 24q72.9 mscrash955 ms (13.1x)
qft 26q315 mscrash5.43 s (17.2x)
qft 28q1.31 scrash25.44 s (19.4x)
qv 16q2.13 ms16.3 ms (7.62x)10.4 ms (4.88x)
qv 20q13.3 ms61.5 ms (4.63x)26.0 ms (1.96x)
qv 24q254 ms799 ms (3.15x)470 ms (1.85x)

Cold call, fastest warm call, the time Aer reports for itself, and the smallest shift in a marginal a sampled check detects:

WorkloadPRISM-QAer fp32qsim fp32
rcs 20q d10cold 8.37 ms, fastest 6.58 mscold 36.1 ms, fastest 30.5 ms, internal 25.8 mscold 15.5 ms, fastest 11.8 ms
rcs 24q d10cold 103 ms, fastest 98.8 mscold 385 ms, fastest 375 ms, internal 383 mscold 200 ms, fastest 200 ms
rcs 26q d10cold 406 ms, fastest 404 mscold 1.64 s, fastest 1.63 s, internal 1.64 scold 954 ms, fastest 951 ms
rcs 28q d10cold 1.70 s, fastest 1.72 scold 6.72 s, fastest 6.74 s, internal 6.75 scold 4.01 s, fastest 4.01 s
rcs 20q d20cold 15.5 ms, fastest 11.2 mscold 66.7 ms, fastest 59.5 ms, internal 51.9 mscold 26.1 ms, fastest 22.5 ms
rcs 24q d20cold 169 ms, fastest 162 mscold 749 ms, fastest 735 ms, internal 728 mscold 373 ms, fastest 369 ms
rcs 26q d20cold 745 ms, fastest 727 mscold 3.23 s, fastest 3.20 s, internal 3.20 scold 1.78 s, fastest 1.81 s
rcs 28q d20cold 3.17 s, fastest 3.15 scold 13.24 s, fastest 13.17 s, internal 13.20 scold 7.72 s, fastest 7.73 s
qft 20qcold 6.25 ms, fastest 3.59 mscrashcold 20.7 ms, fastest 15.1 ms
qft 24qcold 74.8 ms, fastest 71.6 mscrashcold 947 ms, fastest 947 ms
qft 26qcold 314 ms, fastest 313 mscrashcold 5.39 s, fastest 5.42 s
qft 28qcold 1.28 s, fastest 1.31 scrashcold 25.47 s, fastest 25.43 s
qv 16qcold 21.4 ms, fastest 1.93 mscold 25.2 ms, fastest 15.9 ms, internal 8.77 mscold 13.7 ms, fastest 10.2 ms
qv 20qcold 17.6 ms, fastest 13.0 mscold 65.4 ms, fastest 60.1 ms, internal 48.4 mscold 28.8 ms, fastest 24.7 ms
qv 24qcold 258 ms, fastest 251 mscold 833 ms, fastest 791 ms, internal 782 mscold 471 ms, fastest 459 ms

Stabilizer

  • Stim runs single-threaded; PRISM-Q runs at 1 and 24 threads, and ratios pair Stim with the 1-thread PRISM-Q record.
  • The timed call ends at the simulator's own result: PRISM-Q, a histogram; Stim, a bit-packed per-shot array.
  • Smallest shift in a marginal the sampled check detects: PRISM-Q 0.023 and Stim 0.023; checks above 0.05 are marked weakly tested.
  • Both draw shots from a compiled sampler.

Stabilizer tableau · 10,000 shots

Stim takes 1.70x to 5.13x the 1-thread PRISM-Q time, 100 to 10,000 qubits

Exact numbers
WorkloadPRISM-Q 24 threadsPRISM-Q 1 threadStim 1 thread
clifford 100q 10k shots798 us804 us1.37 ms (1.70x)
clifford 1000q 10k shots2.92 ms3.11 ms16.0 ms (5.13x)
clifford 10000q 10k shots96.3 ms92.0 ms384 ms (4.18x)

Cold call, fastest warm call, and the smallest shift in a marginal a sampled check detects:

WorkloadPRISM-Q 24 threadsPRISM-Q 1 threadStim 1 thread
clifford 100q 10k shotscold 1.22 ms, fastest 755 us, detects 0.023cold 142 ms, fastest 501 us, detects 0.023cold 3.27 ms, fastest 1.34 ms, detects 0.023
clifford 1000q 10k shotscold 3.50 ms, fastest 2.81 ms, detects 0.023cold 3.24 ms, fastest 2.84 ms, detects 0.023cold 19.4 ms, fastest 15.9 ms, detects 0.023
clifford 10000q 10k shotscold 99.3 ms, fastest 93.9 ms, detects 0.023cold 93.9 ms, fastest 91.1 ms, detects 0.023cold 388 ms, fastest 379 ms, detects 0.023

High-shot stabilizer

  • Stim runs single-threaded; PRISM-Q runs at 1 and 24 threads, and ratios pair Stim with the 1-thread PRISM-Q record.
  • The timed call ends at the simulator's own result: PRISM-Q and Stim, bit-packed shot buffers.
  • Smallest shift in a marginal the sampled check detects: PRISM-Q 0.00072 to 0.0023 and Stim 0.00072 to 0.0023; checks above 0.05 are marked weakly tested.
  • Each simulator returns only single-bit counts, adjacent-pair parity counts and the shot total.
  • Time covers compiling the sampler and drawing every shot into a packed buffer; reducing the buffer to statistics is outside the timer on both sides.

Stabilizer tableau · statistics only

Stim takes 30.1x to 67.6x the 1-thread PRISM-Q time, 100 to 10,000 qubits

Exact numbers
WorkloadPRISM-Q 24 threadsPRISM-Q 1 threadStim 1 thread
clifford 100q 1M shots1.96 ms4.05 ms145 ms (35.9x)
clifford 100q 10M shots10.6 ms34.9 ms1.51 s (43.4x)
clifford 1000q 1M shots17.9 ms56.6 ms1.70 s (30.1x)
clifford 1000q 10M shots193 ms546 ms16.70 s (30.6x)
clifford 10000q 1M shots477 ms462 ms31.22 s (67.6x)

Cold call, fastest warm call, and the smallest shift in a marginal a sampled check detects:

WorkloadPRISM-Q 24 threadsPRISM-Q 1 threadStim 1 thread
clifford 100q 1M shotscold 2.30 ms, fastest 1.77 ms, detects 0.0023cold 5.49 ms, fastest 3.89 ms, detects 0.0023cold 145 ms, fastest 143 ms, detects 0.0023
clifford 100q 10M shotscold 11.5 ms, fastest 10.4 ms, detects 0.00072cold 35.0 ms, fastest 34.5 ms, detects 0.00072cold 1.53 s, fastest 1.49 s, detects 0.00072
clifford 1000q 1M shotscold 19.4 ms, fastest 16.5 ms, detects 0.0023cold 55.2 ms, fastest 56.3 ms, detects 0.0023cold 1.69 s, fastest 1.70 s, detects 0.0023
clifford 1000q 10M shotscold 194 ms, fastest 180 ms, detects 0.00073cold 542 ms, fastest 539 ms, detects 0.00073cold 16.78 s, fastest 16.68 s, detects 0.00073
clifford 10000q 1M shotscold 480 ms, fastest 469 ms, detects 0.0023cold 469 ms, fastest 457 ms, detects 0.0023cold 30.80 s, fastest 30.95 s, detects 0.0023

Matrix product state

  • Aer automatic refuses 6 of 6 rows before running: it picks its statevector method and reports that the state would not fit in memory.
  • Truncation besides the bond cap: PRISM-Q drops singular values at or below 1e-12 of the largest; Aer runs with matrix_product_state_truncation_threshold 1e-16.
  • The timed call ends at the simulator's own result: PRISM-Q, a histogram; Aer MPS and Aer automatic, a Result holding a histogram.
  • Smallest shift in a marginal the sampled check detects: PRISM-Q 0.022 to 0.023 and Aer MPS 0.022 to 0.023; checks above 0.05 are marked weakly tested.
  • Aer's matrix product state method runs with mps_lapack=True and mps_omp_threads equal to the thread count.

MPS · shallow wide brickwork · 10,000 shots

Aer MPS takes 114x to 1127x the PRISM-Q time, 50 to 200 qubits

Exact numbers
WorkloadPRISM-QAer MPSAer automatic
lowent 50q d4 10k shots3.27 ms2.97 s (907x)refused, statevector would not fit
lowent 100q d4 10k shots6.04 ms5.36 s (887x)refused, statevector would not fit
lowent 200q d4 10k shots10.6 ms11.97 s (1127x)refused, statevector would not fit
lowent 50q d8 10k shots22.3 ms2.55 s (114x)refused, statevector would not fit
lowent 100q d8 10k shots41.4 ms5.90 s (142x)refused, statevector would not fit
lowent 200q d8 10k shots70.7 ms11.73 s (166x)refused, statevector would not fit

Cold call, fastest warm call, the time Aer reports for itself, and the smallest shift in a marginal a sampled check detects:

WorkloadPRISM-QAer MPSAer automatic
lowent 50q d4 10k shotscold 9.65 ms, fastest 3.12 ms, detects 0.022cold 2.96 s, fastest 2.94 s, internal 2.96 s, detects 0.022refused, statevector would not fit
lowent 100q d4 10k shotscold 7.67 ms, fastest 5.59 ms, detects 0.023cold 5.31 s, fastest 5.33 s, internal 5.34 s, detects 0.023refused, statevector would not fit
lowent 200q d4 10k shotscold 13.4 ms, fastest 10.2 ms, detects 0.023cold 11.93 s, fastest 11.97 s, internal 11.94 s, detects 0.023refused, statevector would not fit
lowent 50q d8 10k shotscold 32.3 ms, fastest 21.4 ms, detects 0.022cold 2.55 s, fastest 2.49 s, internal 2.54 s, detects 0.022refused, statevector would not fit
lowent 100q d8 10k shotscold 40.5 ms, fastest 38.4 ms, detects 0.023cold 5.80 s, fastest 5.85 s, internal 5.87 s, detects 0.023refused, statevector would not fit
lowent 200q d8 10k shotscold 93.8 ms, fastest 70.1 ms, detects 0.023cold 11.58 s, fastest 11.69 s, internal 11.69 s, detects 0.023refused, statevector would not fit

MPS bond cap against accuracy · rcs 20q d10

At bond cap 32, PRISM-Q MPS reaches distance 1.4e-14 in 15.1 ms; Aer MPS reaches 7.5e-15 in 562 ms

Exact numbers
Bond capPRISM-Q MPSDistanceAer MPSDistance
22.68 ms0.8433 ms0.79
43.41 ms0.57464 ms0.6
84.41 ms0.39482 ms0.41
1615.8 ms0.17513 ms0.17
3215.1 ms1.4e-14562 ms7.5e-15

Deep MPS

  • Truncation besides the bond cap: PRISM-Q drops singular values at or below 1e-12 of the largest; Aer runs with matrix_product_state_truncation_threshold 1e-16; quimb's CircuitMPS runs with cutoff 1e-16 (the value of Aer's threshold).
  • The timed call ends at the simulator's own result: PRISM-Q MPS cap 256, a histogram; Aer MPS cap 256, a Result holding a histogram; quimb MPS cap 256, a per-shot sample list.
  • Warm median more than 20% above the cold call: Aer MPS cap 256 lowent 500q d12 1k shots (80.87 s cold, 106.18 s warm) and Aer MPS cap 256 lowent 1000q d12 100 shots (35.54 s cold, 43.18 s warm).
  • Smallest shift in a marginal the sampled check detects: Aer MPS cap 256 0.099 to 0.33, quimb MPS cap 256 0.31 to 0.33 and PRISM-Q MPS cap 256 0.07 to 0.23; checks above 0.05 are marked weakly tested.
  • Aer's matrix product state method runs with mps_lapack=True and mps_omp_threads equal to the thread count.
  • Brickwork at depth 12 needs bond 64 across a cut and depth 16 needs 256; all runs use bond cap 256.
  • Where the cone reference cannot reach a statistic, counts are checked against another simulator.

MPS · bond cap 256

Aer MPS cap 256 takes 4.67x to 77.0x the PRISM-Q MPS cap 256 time, 50 to 1,000 qubits

† weakly tested: the check detects only shifts above 0.05 in a marginal.

Exact numbers
WorkloadPRISM-Q MPS cap 256Aer MPS cap 256quimb MPS cap 256
lowent 50q d12 100 shots189 ms†1.02 s (5.39x)†2.45 s (13.0x)†
lowent 50q d12 1k shots182 ms†2.63 s (14.4x)†not run
lowent 100q d12 100 shots486 ms†2.27 s (4.67x)†5.42 s (11.2x)†
lowent 100q d12 1k shots535 ms†6.81 s (12.7x)†not run
lowent 200q d12 100 shots1.01 s†5.50 s (5.44x)†12.28 s (12.1x)†
lowent 200q d12 1k shots1.16 s†16.36 s (14.1x)†not run
lowent 500q d12 100 shots2.76 s†16.34 s (5.92x)†38.18 s (13.8x)†
lowent 500q d12 1k shots3.20 s†106.18 s (33.2x)†not run
lowent 1000q d12 100 shots5.59 s†43.18 s (7.73x)†127.33 s (22.8x)†
lowent 1000q d12 1k shots6.49 s†499.81 s (77.0x)†not run
lowent 50q d16 100 shots2.01 s†18.34 s (9.10x)†22.57 s (11.2x)†
lowent 100q d16 100 shots5.61 s†44.64 s (7.95x)†54.59 s (9.73x)†
lowent 200q d16 100 shots11.99 s†97.22 s (8.11x)†117.66 s (9.81x)†
lowent 500q d16 100 shots31.91 s†266.96 s (8.37x)†319.10 s (10.0x)†
lowent 1000q d16 100 shots65.85 s†630.76 s (9.58x)†620.04 s (9.42x)†

Cold call, fastest warm call, the time Aer reports for itself, and the smallest shift in a marginal a sampled check detects:

WorkloadPRISM-Q MPS cap 256Aer MPS cap 256quimb MPS cap 256
lowent 50q d12 100 shotscold 188 ms, fastest 176 ms, detects 0.22cold 1.04 s, fastest 1.01 s, internal 999 ms, detects 0.31cold 2.37 s, fastest 2.43 s, detects 0.31
lowent 50q d12 1k shotscold 226 ms, fastest 181 ms, detects 0.07cold 2.64 s, fastest 2.61 s, internal 2.61 s, detects 0.099not run
lowent 100q d12 100 shotscold 497 ms, fastest 465 ms, detects 0.23cold 2.46 s, fastest 2.27 s, internal 2.24 s, detects 0.32cold 5.35 s, fastest 5.39 s, detects 0.32
lowent 100q d12 1k shotscold 561 ms, fastest 517 ms, detects 0.072cold 6.95 s, fastest 6.80 s, internal 6.77 s, detects 0.1not run
lowent 200q d12 100 shotscold 984 ms, fastest 980 ms, detects 0.23cold 5.36 s, fastest 5.38 s, internal 5.44 s, detects 0.33cold 12.10 s, fastest 12.15 s, detects 0.33
lowent 200q d12 1k shotscold 1.16 s, fastest 1.16 s, detects 0.073cold 16.97 s, fastest 16.06 s, internal 16.29 s, detects 0.1not run
lowent 500q d12 100 shotscold 2.83 s, fastest 2.72 s, detects 0.23cold 15.86 s, fastest 16.14 s, internal 16.18 s, detects 0.33cold 38.11 s, fastest 38.02 s, detects 0.33
lowent 500q d12 1k shotscold 3.19 s, fastest 3.18 s, detects 0.073cold 80.87 s, fastest 88.57 s, internal 106.02 s, detects 0.1not run
lowent 1000q d12 100 shotscold 5.57 s, fastest 5.55 s, detects 0.23cold 35.54 s, fastest 42.94 s, internal 42.85 s, detects 0.33cold 119.94 s, fastest 126.82 s, detects 0.33
lowent 1000q d12 1k shotscold 6.50 s, fastest 6.45 s, detects 0.073cold 467.09 s, fastest 492.33 s, internal 499.46 s, detects 0.1not run
lowent 50q d16 100 shotscold 2.01 s, fastest 1.98 s, detects 0.22cold 18.37 s, fastest 18.33 s, internal 18.32 s, detects 0.31cold 23.39 s, fastest 22.38 s, detects 0.31
lowent 100q d16 100 shotscold 5.75 s, fastest 5.57 s, detects 0.23cold 44.76 s, fastest 44.53 s, internal 44.60 s, detects 0.32cold 52.37 s, fastest 54.34 s, detects 0.32
lowent 200q d16 100 shotscold 11.91 s, fastest 11.95 s, detects 0.23cold 97.99 s, fastest 97.13 s, internal 97.13 s, detects 0.33cold 121.89 s, fastest 114.32 s, detects 0.33
lowent 500q d16 100 shotscold 31.94 s, fastest 31.91 s, detects 0.23cold 279.54 s, fastest 266.96 s, internal 266.66 s, detects 0.33cold 311.92 s, fastest 319.10 s, detects 0.33
lowent 1000q d16 100 shotscold 66.96 s, fastest 65.85 s, detects 0.23cold 623.15 s, fastest 630.76 s, internal 630.17 s, detects 0.33cold 615.93 s, fastest 620.04 s, detects 0.33

MPS bond cap against expectation-value error · brickwork depth 8

Largest error in Z and adjacent ZZ against the exact value, 32 and 48 qubits; every simulator is within 1e-8 from bond cap 16 at 48 qubits

Error is the largest absolute difference from the cone reference over every Z and adjacent ZZ value.

Exact numbers
QubitsBond capPRISM-Q MPSLargest errorAer MPSLargest errorquimb MPSLargest error
322393 us0.488.78 ms0.5186.0 ms0.53
324937 us0.189.94 ms0.1388.9 ms0.16
3281.54 ms0.02212.5 ms0.0191.0 ms0.014
32167.79 ms4.1e-1514.7 ms3.3e-1592.7 ms4.3e-15
32327.62 ms4e-1515.3 ms3.3e-1592.9 ms4.3e-15
482692 us0.7313.3 ms0.53130 ms0.76
4841.56 ms0.1614.6 ms0.15132 ms0.16
4882.36 ms0.02218.4 ms0.017134 ms0.022
48169.68 ms5.1e-1522.5 ms3.6e-15140 ms3.4e-15
48329.43 ms6.3e-1522.8 ms3.6e-15138 ms3.4e-15

Tensor network expectation values

  • kahypar was unavailable, so cotengra searched paths with greedy and labels under sbplx, with cotengrust installed for its greedy and optimal paths.
  • quimb's circuit storage is cleared on every call and a fresh optimizer built for every observable, so the contraction path search is inside every timed call.
  • The timed call ends at the simulator's own result: PRISM-Q, PRISM-Q TN, PRISM-Q MPS cap 256 and quimb TN, expectation values; Aer MPS, a Result holding the marginal probabilities of each observable's qubits.
  • Aer's matrix product state method runs with mps_lapack=True and mps_omp_threads equal to the thread count.
  • Unmeasured rcs brickwork and 4-step Trotterized Ising chains; every value is checked against the exact cone reference.

Expectation values · 4 Z and 4 ZZ

quimb TN takes 56.4x to 397x the PRISM-Q time, 32 to 256 qubits

Exact numbers
WorkloadPRISM-QPRISM-Q TNPRISM-Q MPS cap 256quimb TNAer MPS
rcs 32q d8 4 Z + 4 ZZ7.63 ms6.63 ms5.73 ms675 ms (88.4x)10.9 ms (1.43x)
rcs 64q d8 4 Z + 4 ZZ10.9 ms7.97 ms10.7 ms748 ms (68.9x)21.1 ms (1.95x)
rcs 128q d8 4 Z + 4 ZZ8.08 ms8.42 ms16.6 ms809 ms (100x)35.6 ms (4.41x)
rcs 256q d8 4 Z + 4 ZZ8.35 ms9.06 ms29.3 ms990 ms (119x)61.6 ms (7.38x)
tfim 32q 4 steps 4 Z + 4 ZZ801 us5.53 ms778 us318 ms (397x)3.18 ms (3.97x)
tfim 64q 4 steps 4 Z + 4 ZZ3.27 ms6.35 ms3.09 ms332 ms (102x)5.57 ms (1.71x)
tfim 128q 4 steps 4 Z + 4 ZZ6.68 ms7.93 ms2.86 ms377 ms (56.4x)10.2 ms (1.53x)
tfim 256q 4 steps 4 Z + 4 ZZ6.87 ms7.14 ms5.92 ms431 ms (62.7x)18.0 ms (2.62x)

Cold call, fastest warm call, the time Aer reports for itself, and the smallest shift in a marginal a sampled check detects:

WorkloadPRISM-QPRISM-Q TNPRISM-Q MPS cap 256quimb TNAer MPS
rcs 32q d8 4 Z + 4 ZZcold 8.60 ms, fastest 7.54 mscold 8.12 ms, fastest 6.00 mscold 8.87 ms, fastest 3.12 mscold 1.92 s, fastest 660 mscold 13.8 ms, fastest 10.8 ms, internal 4.40 ms
rcs 64q d8 4 Z + 4 ZZcold 11.2 ms, fastest 10.3 mscold 8.92 ms, fastest 7.48 mscold 11.1 ms, fastest 9.63 mscold 1.70 s, fastest 735 mscold 23.9 ms, fastest 21.1 ms, internal 6.32 ms
rcs 128q d8 4 Z + 4 ZZcold 10.2 ms, fastest 7.83 mscold 11.6 ms, fastest 7.69 mscold 16.7 ms, fastest 15.7 mscold 1.80 s, fastest 804 mscold 38.8 ms, fastest 35.4 ms, internal 7.84 ms
rcs 256q d8 4 Z + 4 ZZcold 11.2 ms, fastest 7.32 mscold 9.36 ms, fastest 7.40 mscold 29.2 ms, fastest 28.7 mscold 1.94 s, fastest 973 mscold 62.3 ms, fastest 59.5 ms, internal 8.91 ms
tfim 32q 4 steps 4 Z + 4 ZZcold 1.47 ms, fastest 727 uscold 8.16 ms, fastest 5.03 mscold 1.44 ms, fastest 716 uscold 1.47 s, fastest 313 mscold 6.92 ms, fastest 3.11 ms, internal 905 us
tfim 64q 4 steps 4 Z + 4 ZZcold 3.95 ms, fastest 3.17 mscold 9.63 ms, fastest 5.83 mscold 3.85 ms, fastest 3.08 mscold 1.29 s, fastest 329 mscold 8.51 ms, fastest 5.49 ms, internal 1.36 ms
tfim 128q 4 steps 4 Z + 4 ZZcold 10.4 ms, fastest 6.57 mscold 9.33 ms, fastest 6.37 mscold 3.82 ms, fastest 2.77 mscold 1.29 s, fastest 356 mscold 12.2 ms, fastest 9.82 ms, internal 1.69 ms
tfim 256q 4 steps 4 Z + 4 ZZcold 11.0 ms, fastest 6.63 mscold 16.9 ms, fastest 6.64 mscold 6.49 ms, fastest 5.75 mscold 1.37 s, fastest 415 mscold 21.8 ms, fastest 17.6 ms, internal 1.97 ms

Shot sampling

  • The timed call ends at the simulator's own result: PRISM-Q, a histogram; Aer and Aer fp32, a Result holding a histogram; qsim fp32, a per-shot measurement array, which qsimcirq's run builds by expanding each shot into Python bools.
  • Smallest shift in a marginal the sampled check detects: PRISM-Q 0.002 to 0.067, Aer fp32 0.002 to 0.067, qsim fp32 0.002 to 0.067 and Aer 0.002 to 0.067; checks above 0.05 are marked weakly tested.
  • qsim runs with max_fused_gate_size 3 at 16 and 20 qubits and 4 at 24 qubits.
  • Time covers building the state and drawing every shot.

Statevector sampling · rcs depth 10

Aer takes 4.74x to 127x the PRISM-Q time, 16 to 24 qubits

* output not checked; † weakly tested: the check detects only shifts above 0.05 in a marginal.

Exact numbers
WorkloadPRISM-QAerAer fp32qsim fp32
sampling 16q 1 shot1.32 ms*11.6 ms*10.8 ms*6.22 ms*
sampling 16q 1M shots27.6 ms3.51 s (127x)3.63 s (132x)1.18 s (42.9x)
sampling 20q 1 shot8.23 ms*37.4 ms*28.8 ms*11.8 ms*
sampling 20q 1k shots8.85 ms†42.0 ms (4.74x)†34.7 ms (3.92x)†15.2 ms (1.72x)†
sampling 20q 100k shots19.7 ms437 ms (22.2x)417 ms (21.2x)165 ms (8.38x)
sampling 20q 1M shots73.4 ms3.85 s (52.5x)3.88 s (52.9x)1.53 s (20.8x)
sampling 20q half measured 1M shots47.9 ms3.60 s (75.1x)3.49 s (73.0x)1.43 s (29.9x)
sampling 24q 1 shot122 ms*609 ms*351 ms*197 ms*
sampling 24q 1M shots243 ms6.02 s (24.7x)4.84 s (19.9x)1.87 s (7.68x)

Cold call, fastest warm call, the time Aer reports for itself, and the smallest shift in a marginal a sampled check detects:

WorkloadPRISM-QAerAer fp32qsim fp32
sampling 16q 1 shotcold 2.05 ms, fastest 1.23 mscold 14.8 ms, fastest 11.5 ms, internal 7.28 mscold 14.8 ms, fastest 10.8 ms, internal 6.19 mscold 7.70 ms, fastest 6.17 ms
sampling 16q 1M shotscold 27.6 ms, fastest 26.1 ms, detects 0.0021cold 3.53 s, fastest 3.49 s, internal 3.50 s, detects 0.0021cold 3.62 s, fastest 3.61 s, internal 3.62 s, detects 0.0021cold 1.22 s, fastest 1.16 s, detects 0.0021
sampling 20q 1 shotcold 11.3 ms, fastest 7.75 mscold 51.3 ms, fastest 36.9 ms, internal 31.9 mscold 37.6 ms, fastest 28.7 ms, internal 23.1 mscold 17.0 ms, fastest 11.6 ms
sampling 20q 1k shotscold 10.8 ms, fastest 8.25 ms, detects 0.067cold 55.5 ms, fastest 41.3 ms, internal 36.1 ms, detects 0.067cold 42.0 ms, fastest 33.7 ms, internal 27.9 ms, detects 0.067cold 19.4 ms, fastest 14.1 ms, detects 0.067
sampling 20q 100k shotscold 20.9 ms, fastest 18.9 ms, detects 0.0067cold 443 ms, fastest 433 ms, internal 423 ms, detects 0.0067cold 414 ms, fastest 413 ms, internal 404 ms, detects 0.0067cold 169 ms, fastest 161 ms, detects 0.0067
sampling 20q 1M shotscold 73.7 ms, fastest 72.7 ms, detects 0.0021cold 3.84 s, fastest 3.84 s, internal 3.76 s, detects 0.0021cold 3.89 s, fastest 3.87 s, internal 3.79 s, detects 0.0021cold 1.54 s, fastest 1.46 s, detects 0.0021
sampling 20q half measured 1M shotscold 48.9 ms, fastest 47.7 ms, detects 0.002cold 3.60 s, fastest 3.59 s, internal 3.59 s, detects 0.002cold 3.50 s, fastest 3.48 s, internal 3.49 s, detects 0.002cold 1.51 s, fastest 1.39 s, detects 0.002
sampling 24q 1 shotcold 129 ms, fastest 121 mscold 617 ms, fastest 602 ms, internal 602 mscold 359 ms, fastest 347 ms, internal 344 mscold 193 ms, fastest 187 ms
sampling 24q 1M shotscold 243 ms, fastest 241 ms, detects 0.003cold 6.02 s, fastest 5.97 s, internal 5.79 s, detects 0.003cold 4.85 s, fastest 4.83 s, internal 4.62 s, detects 0.003cold 1.93 s, fastest 1.84 s, detects 0.003

Disjoint components

  • Aer automatic refuses 4 of 4 rows before running: it picks its statevector method and reports that the state would not fit in memory.
  • PRISM-Q resolves Decomposed, with route IndependentBlocks at 40 qubits and PerShot at 100 and 200 qubits.
  • The timed call ends at the simulator's own result: PRISM-Q, a histogram; Aer MPS and Aer automatic, a Result holding a histogram.
  • Smallest shift in a marginal the sampled check detects: PRISM-Q 0.022 to 0.023 and Aer MPS 0.022 to 0.023; checks above 0.05 are marked weakly tested.
  • Aer's matrix product state method runs with mps_lapack=True and mps_omp_threads equal to the thread count.

Independent 10-qubit blocks · 10,000 shots

Aer MPS takes 104x to 914x the PRISM-Q time, 40 to 200 qubits

Exact numbers
WorkloadPRISM-QAer MPSAer automatic
disjoint 40q contiguous 10k shots2.33 ms1.95 s (836x)refused, statevector would not fit
disjoint 40q strided 10k shots2.43 ms2.22 s (914x)refused, statevector would not fit
disjoint 100q contiguous 10k shots47.0 ms4.87 s (104x)refused, statevector would not fit
disjoint 200q contiguous 10k shots60.3 ms9.91 s (164x)refused, statevector would not fit

Cold call, fastest warm call, the time Aer reports for itself, and the smallest shift in a marginal a sampled check detects:

WorkloadPRISM-QAer MPSAer automatic
disjoint 40q contiguous 10k shotscold 4.90 ms, fastest 2.26 ms, detects 0.022cold 1.97 s, fastest 1.92 s, internal 1.94 s, detects 0.022refused, statevector would not fit
disjoint 40q strided 10k shotscold 2.76 ms, fastest 2.37 ms, detects 0.022cold 2.22 s, fastest 2.20 s, internal 2.21 s, detects 0.022refused, statevector would not fit
disjoint 100q contiguous 10k shotscold 48.1 ms, fastest 44.5 ms, detects 0.023cold 4.81 s, fastest 4.84 s, internal 4.84 s, detects 0.023refused, statevector would not fit
disjoint 200q contiguous 10k shotscold 68.9 ms, fastest 54.5 ms, detects 0.023cold 9.79 s, fastest 9.89 s, internal 9.85 s, detects 0.023refused, statevector would not fit

Circuit zoo, statevector

  • The timed call ends at the simulator's own result: PRISM-Q, QuEST, Spinoza, qip and qsim fp32, a probability vector; Aer and Aer fp32, a Result holding the probability vector.
  • 12 rows take their reference vector from one simulator with no cross-check by a second.
  • qsim runs with max_fused_gate_size 3 at 20 qubits and 4 at 24 and 26 qubits.
  • Hardware-efficient ansatz, QAOA on a random 3-regular graph, a 10-step Trotterized Ising chain, and a ripple-carry adder over a superposed register.
  • QAOA and Ising rows use RX and RZZ. QuEST applies them natively and qip as one matrix each; Spinoza decomposes RZZ into two phase gates and a controlled phase.
  • Aer fp32 exits with an access violation on CP when fusion is on and on RZZ, so it has no QFT, QAOA or Ising timings.
  • qsim and Aer fp32 store single-precision amplitudes and are checked at 1e-5.

Statevector · full probability vector

Aer takes 1.85x to 13.2x the PRISM-Q time, 20 to 26 qubits

‡ reference output with no cross-check by a second simulator.

Exact numbers
WorkloadPRISM-QAerQuESTSpinozaqipAer fp32qsim fp32
hea 20q6.81 ms23.4 ms (3.43x)‡32.2 ms (4.74x)135 ms (19.8x)108 ms (15.8x)17.8 ms (2.61x)9.63 ms (1.41x)
hea 24q75.7 ms542 ms (7.16x)‡2.33 s (30.8x)2.57 s (33.9x)4.28 s (56.5x)287 ms (3.80x)240 ms (3.17x)
hea 26q369 ms2.40 s (6.51x)‡10.60 s (28.7x)not runnot run1.35 s (3.65x)1.17 s (3.17x)
qaoa 20q4.19 ms10.5 ms (2.51x)‡10.2 ms (2.43x)cannot run44.5 ms (10.6x)crash4.72 ms (1.13x)
qaoa 24q48.3 ms268 ms (5.56x)‡818 ms (16.9x)cannot run1.33 s (27.5x)crash104 ms (2.16x)
qaoa 26q188 ms1.22 s (6.51x)‡3.18 s (16.9x)not runnot runcrash446 ms (2.38x)
tfim 20q 10 steps10.1 ms44.6 ms (4.42x)‡130 ms (12.9x)92.9 ms (9.21x)162 ms (16.0x)crash13.7 ms (1.36x)
tfim 24q 10 steps126 ms1.54 s (12.2x)‡3.86 s (30.6x)4.85 s (38.5x)5.75 s (45.6x)crash372 ms (2.95x)
tfim 26q 10 steps533 ms7.02 s (13.2x)‡16.49 s (31.0x)not runnot runcrash1.81 s (3.39x)
adder 20q8.60 ms15.9 ms (1.85x)‡35.9 ms (4.18x)cannot run116 ms (13.5x)23.5 ms (2.74x)31.9 ms (3.71x)
adder 24q105 ms222 ms (2.12x)‡2.45 s (23.4x)cannot run4.64 s (44.3x)214 ms (2.04x)1.12 s (10.7x)
adder 26q434 ms967 ms (2.23x)‡11.19 s (25.8x)not runnot run739 ms (1.70x)3.54 s (8.16x)

Cold call, fastest warm call, the time Aer reports for itself, and the smallest shift in a marginal a sampled check detects:

WorkloadPRISM-QAerQuESTSpinozaqipAer fp32qsim fp32
hea 20qcold 8.56 ms, fastest 6.33 mscold 29.4 ms, fastest 22.5 ms, internal 20.9 mscold 37.0 ms, fastest 31.5 mscold 159 ms, fastest 104 mscold 115 ms, fastest 107 mscold 26.5 ms, fastest 17.5 ms, internal 15.0 mscold 14.3 ms, fastest 9.05 ms
hea 24qcold 78.3 ms, fastest 74.6 mscold 541 ms, fastest 535 ms, internal 539 mscold 2.33 s, fastest 2.32 scold 2.55 s, fastest 2.56 scold 4.27 s, fastest 4.27 scold 285 ms, fastest 283 ms, internal 284 mscold 238 ms, fastest 231 ms
hea 26qcold 371 ms, fastest 362 mscold 2.39 s, fastest 2.38 s, internal 2.40 scold 10.61 s, fastest 10.60 snot runnot runcold 1.33 s, fastest 1.33 s, internal 1.34 scold 1.16 s, fastest 1.16 s
qaoa 20qcold 5.46 ms, fastest 3.73 mscold 14.6 ms, fastest 10.3 ms, internal 9.47 mscold 11.9 ms, fastest 9.89 mscannot runcold 46.0 ms, fastest 43.5 mscrashcold 6.38 ms, fastest 4.56 ms
qaoa 24qcold 46.8 ms, fastest 46.7 mscold 267 ms, fastest 259 ms, internal 267 mscold 847 ms, fastest 802 mscannot runcold 2.03 s, fastest 1.30 scrashcold 106 ms, fastest 102 ms
qaoa 26qcold 188 ms, fastest 184 mscold 1.25 s, fastest 1.22 s, internal 1.22 scold 3.23 s, fastest 3.16 snot runnot runcrashcold 442 ms, fastest 439 ms
tfim 20q 10 stepscold 13.8 ms, fastest 8.99 mscold 50.1 ms, fastest 44.3 ms, internal 40.8 mscold 137 ms, fastest 118 mscold 113 ms, fastest 90.1 mscold 173 ms, fastest 161 mscrashcold 17.8 ms, fastest 13.5 ms
tfim 24q 10 stepscold 129 ms, fastest 123 mscold 1.57 s, fastest 1.52 s, internal 1.53 scold 3.85 s, fastest 3.86 scold 4.85 s, fastest 4.83 scold 5.79 s, fastest 5.74 scrashcold 368 ms, fastest 368 ms
tfim 26q 10 stepscold 533 ms, fastest 525 mscold 7.01 s, fastest 6.97 s, internal 7.01 scold 16.33 s, fastest 16.40 snot runnot runcrashcold 1.80 s, fastest 1.81 s
adder 20qcold 10.4 ms, fastest 7.86 mscold 15.9 ms, fastest 15.0 ms, internal 13.2 mscold 40.0 ms, fastest 35.7 mscannot runcold 127 ms, fastest 116 mscold 25.0 ms, fastest 22.7 ms, internal 20.6 mscold 32.6 ms, fastest 30.9 ms
adder 24qcold 108 ms, fastest 103 mscold 218 ms, fastest 221 ms, internal 218 mscold 2.46 s, fastest 2.44 scannot runcold 4.63 s, fastest 4.62 scold 215 ms, fastest 205 ms, internal 211 mscold 1.12 s, fastest 1.11 s
adder 26qcold 428 ms, fastest 425 mscold 977 ms, fastest 954 ms, internal 963 mscold 11.43 s, fastest 11.15 snot runnot runcold 716 ms, fastest 684 ms, internal 734 mscold 3.66 s, fastest 3.36 s

Circuit zoo, stabilizer

  • Stim runs single-threaded; PRISM-Q runs at 1 and 24 threads, and ratios pair Stim with the 1-thread PRISM-Q record.
  • The timed call ends at the simulator's own result: PRISM-Q, a histogram; Stim, a bit-packed per-shot array; Aer stabilizer, a Result holding a histogram.
  • Smallest shift in a marginal the sampled check detects: PRISM-Q 0.023 to 0.033, Aer stabilizer 0.032 and Stim 0.032 to 0.033; checks above 0.05 are marked weakly tested.
  • GHZ preparation along a line and Bernstein-Vazirani with a seeded secret.

Stabilizer tableau · 10,000 shots

Stim takes 11.1x to 240x the 1-thread PRISM-Q time, 100 to 10,000 qubits

Exact numbers
WorkloadPRISM-Q 24 threadsPRISM-Q 1 threadStim 1 threadAer stabilizer 24 threads
ghz 100q 10k shots15 us13 us845 us (63.0x)858 ms (57604x)
ghz 1000q 10k shots103 us104 us11.5 ms (110x)timeout
ghz 10000q 10k shots1.18 ms1.19 ms285 ms (240x)not run
bv 100q 10k shots112 us108 us1.20 ms (11.1x)859 ms (7653x)
bv 1000q 10k shots1.00 ms950 us13.7 ms (14.4x)timeout
bv 10000q 10k shots16.8 ms16.3 ms206 ms (12.6x)not run

Cold call, fastest warm call, the time Aer reports for itself, and the smallest shift in a marginal a sampled check detects:

WorkloadPRISM-Q 24 threadsPRISM-Q 1 threadStim 1 threadAer stabilizer 24 threads
ghz 100q 10k shotscold 103 us, fastest 12 us, detects 0.023cold 92 us, fastest 11 us, detects 0.023cold 2.80 ms, fastest 815 us, detects 0.032cold 874 ms, fastest 853 ms, internal 857 ms, detects 0.032
ghz 1000q 10k shotscold 185 us, fastest 70 us, detects 0.023cold 204 us, fastest 70 us, detects 0.023cold 13.7 ms, fastest 11.1 ms, detects 0.033timeout
ghz 10000q 10k shotscold 1.39 ms, fastest 1.17 ms, detects 0.033cold 1.46 ms, fastest 1.13 ms, detects 0.033cold 290 ms, fastest 283 ms, detects 0.033not run
bv 100q 10k shotscold 192 us, fastest 91 uscold 224 us, fastest 102 uscold 3.64 ms, fastest 1.19 ms, detects 0.032cold 862 ms, fastest 858 ms, internal 857 ms, detects 0.032
bv 1000q 10k shotscold 1.83 ms, fastest 859 uscold 1.23 ms, fastest 942 uscold 16.7 ms, fastest 13.7 ms, detects 0.033timeout
bv 10000q 10k shotscold 17.8 ms, fastest 16.6 mscold 17.4 ms, fastest 16.1 mscold 207 ms, fastest 202 ms, detects 0.033not run

Circuit zoo, W state

  • The timed call ends at the simulator's own result: PRISM-Q, a histogram; Aer MPS and Aer automatic, a Result holding a histogram.
  • Smallest shift in a marginal the sampled check detects: PRISM-Q 0.031 to 0.033 and Aer MPS 0.031 to 0.033; checks above 0.05 are marked weakly tested.
  • Aer's matrix product state method runs with mps_lapack=True and mps_omp_threads equal to the thread count.
  • The W state holds n nonzero amplitudes and needs bond 2 across every cut.

Sampled · 10,000 shots

Aer MPS takes 2475x to 7972x the PRISM-Q time, 50 to 200 qubits

Exact numbers
WorkloadPRISM-QAer MPSAer automatic
wstate 50q 10k shots379 us3.02 s (7972x)refused, statevector would not fit
wstate 100q 10k shots2.21 ms5.48 s (2475x)refused, statevector would not fit
wstate 200q 10k shots3.60 ms11.01 s (3060x)refused, statevector would not fit

Cold call, fastest warm call, the time Aer reports for itself, and the smallest shift in a marginal a sampled check detects:

WorkloadPRISM-QAer MPSAer automatic
wstate 50q 10k shotscold 537 us, fastest 360 us, detects 0.031cold 3.03 s, fastest 3.01 s, internal 3.02 s, detects 0.031refused, statevector would not fit
wstate 100q 10k shotscold 3.33 ms, fastest 2.17 ms, detects 0.032cold 5.49 s, fastest 5.43 s, internal 5.48 s, detects 0.032refused, statevector would not fit
wstate 200q 10k shotscold 5.15 ms, fastest 3.48 ms, detects 0.033cold 11.03 s, fastest 11.00 s, internal 11.00 s, detects 0.033refused, statevector would not fit

GPU statevector, fp64

  • QFT rows take their gate list from PRISM-Q's qft_circuit generator, and PRISM-Q recognizes that expansion and runs it as one FFT block.
  • The timed call ends at the simulator's own result: PRISM-Q GPU, QuEST GPU and PRISM-Q statevector, a probability vector.
  • Every GPU simulator runs fp64 on CUDA device 0 and copies the full 2^n probability vector back to host memory inside the timed call.
  • PRISM-Q CPU statevector is shown as a host reference; ratios divide peer GPU time by PRISM-Q GPU time.
  • Linux-only GPU peers (cuStateVec, Aer GPU, qsim GPU, lightning.gpu) were not measured on Windows.

Statevector · CUDA · fp64 · probability vector on host

QuEST GPU takes 3.09x to 9.23x the PRISM-Q GPU time, 20 to 28 qubits

Exact numbers
WorkloadPRISM-Q GPUQuEST GPUPRISM-Q statevector
rcs 20q d105.95 ms23.9 ms (4.01x)6.90 ms
rcs 24q d1094.7 ms587 ms (6.20x)99.6 ms
rcs 26q d10401 ms2.54 s (6.33x)412 ms
rcs 28q d101.75 s10.89 s (6.21x)1.73 s
rcs 20q d2010.7 ms45.8 ms (4.27x)12.4 ms
rcs 24q d20179 ms1.14 s (6.39x)161 ms
rcs 26q d20768 ms4.95 s (6.44x)734 ms
rcs 28q d203.30 s21.29 s (6.45x)3.19 s
qft 20q1.73 ms7.77 ms (4.48x)3.98 ms
qft 24q24.3 ms190 ms (7.84x)73.2 ms
qft 26q95.3 ms837 ms (8.78x)317 ms
qft 28q403 ms3.73 s (9.23x)1.28 s
qv 20q11.3 ms52.3 ms (4.62x)12.8 ms
qv 24q213 ms1.49 s (6.98x)252 ms
hea 20q3.53 ms10.9 ms (3.09x)7.26 ms
hea 24q52.9 ms249 ms (4.70x)75.3 ms
hea 26q227 ms1.06 s (4.70x)377 ms
hea 28q973 ms4.54 s (4.67x)1.33 s
qaoa 20q1.48 ms5.17 ms (3.50x)3.16 ms
qaoa 24q19.1 ms93.4 ms (4.90x)48.9 ms
qaoa 26q82.8 ms391 ms (4.72x)191 ms
qaoa 28q322 ms1.64 s (5.08x)860 ms
tfim 20q 10 steps4.70 ms16.8 ms (3.56x)9.51 ms
tfim 24q 10 steps66.0 ms370 ms (5.60x)123 ms
tfim 26q 10 steps275 ms1.59 s (5.80x)541 ms
tfim 28q 10 steps1.18 s6.83 s (5.80x)2.19 s

Cold call, fastest warm call, and the smallest shift in a marginal a sampled check detects:

WorkloadPRISM-Q GPUQuEST GPUPRISM-Q statevector
rcs 20q d10cold 24.7 ms, fastest 5.77 mscold 53.1 ms, fastest 23.8 mscold 8.54 ms, fastest 6.47 ms
rcs 24q d10cold 101 ms, fastest 94.3 mscold 613 ms, fastest 584 mscold 105 ms, fastest 99.4 ms
rcs 26q d10cold 411 ms, fastest 400 mscold 2.55 s, fastest 2.54 scold 401 ms, fastest 406 ms
rcs 28q d10cold 1.80 s, fastest 1.75 scold 10.89 s, fastest 10.88 scold 2.61 s, fastest 1.72 s
rcs 20q d20cold 21.0 ms, fastest 10.6 mscold 73.3 ms, fastest 45.6 mscold 13.9 ms, fastest 12.0 ms
rcs 24q d20cold 184 ms, fastest 178 mscold 1.17 s, fastest 1.14 scold 166 ms, fastest 160 ms
rcs 26q d20cold 780 ms, fastest 762 mscold 4.97 s, fastest 4.94 scold 740 ms, fastest 731 ms
rcs 28q d20cold 3.34 s, fastest 3.29 scold 21.26 s, fastest 21.25 scold 3.14 s, fastest 3.17 s
qft 20qcold 21.6 ms, fastest 1.64 mscold 37.8 ms, fastest 7.74 mscold 6.42 ms, fastest 3.38 ms
qft 24qcold 31.0 ms, fastest 23.9 mscold 214 ms, fastest 187 mscold 75.6 ms, fastest 72.1 ms
qft 26qcold 111 ms, fastest 95.0 mscold 853 ms, fastest 834 mscold 320 ms, fastest 314 ms
qft 28qcold 449 ms, fastest 399 mscold 3.77 s, fastest 3.72 scold 1.26 s, fastest 1.27 s
qv 20qcold 20.4 ms, fastest 11.0 mscold 79.5 ms, fastest 51.8 mscold 17.5 ms, fastest 12.3 ms
qv 24qcold 224 ms, fastest 212 mscold 1.52 s, fastest 1.47 scold 258 ms, fastest 248 ms
hea 20qcold 21.2 ms, fastest 3.42 mscold 37.3 ms, fastest 10.9 mscold 9.39 ms, fastest 7.19 ms
hea 24qcold 60.0 ms, fastest 52.5 mscold 274 ms, fastest 247 mscold 80.6 ms, fastest 74.0 ms
hea 26qcold 238 ms, fastest 224 mscold 1.08 s, fastest 1.06 scold 475 ms, fastest 369 ms
hea 28qcold 1.01 s, fastest 965 mscold 4.54 s, fastest 4.52 scold 1.35 s, fastest 1.30 s
qaoa 20qcold 20.8 ms, fastest 1.44 mscold 33.0 ms, fastest 5.04 mscold 5.98 ms, fastest 3.07 ms
qaoa 24qcold 27.9 ms, fastest 18.7 mscold 124 ms, fastest 92.7 mscold 46.5 ms, fastest 47.0 ms
qaoa 26qcold 96.8 ms, fastest 82.4 mscold 418 ms, fastest 389 mscold 192 ms, fastest 188 ms
qaoa 28qcold 361 ms, fastest 319 mscold 1.68 s, fastest 1.63 scold 820 ms, fastest 851 ms
tfim 20q 10 stepscold 24.7 ms, fastest 4.64 mscold 46.0 ms, fastest 16.7 mscold 13.8 ms, fastest 8.93 ms
tfim 24q 10 stepscold 72.7 ms, fastest 65.8 mscold 394 ms, fastest 368 mscold 132 ms, fastest 122 ms
tfim 26q 10 stepscold 289 ms, fastest 271 mscold 1.61 s, fastest 1.58 scold 538 ms, fastest 538 ms
tfim 28q 10 stepscold 1.22 s, fastest 1.17 scold 6.90 s, fastest 6.81 scold 2.53 s, fastest 2.11 s

Mid-circuit dynamic circuits

  • Stim runs single-threaded; PRISM-Q runs at 1 and 24 threads, and ratios pair Stim with the 1-thread PRISM-Q record.
  • The timed call ends at the simulator's own result: PRISM-Q, a histogram; Aer, Aer automatic and Aer stabilizer, a Result holding a histogram; Stim, a bit-packed per-shot array.
  • Smallest shift in a marginal the sampled check detects: PRISM-Q 0.0067 to 0.023, Aer automatic 0.0067 to 0.021, Aer 0.0067 to 0.022, Aer stabilizer 0.022 to 0.023 and Stim 0.022 to 0.023; checks above 0.05 are marked weakly tested.
  • Aer's matrix product state method runs with mps_lapack=True and mps_omp_threads equal to the thread count.
  • Three rounds of data evolution, ancilla parity measurement, conditional X feed-forward and ancilla reset, followed by final data readout.
  • Non-Clifford rows compare against Qiskit Aer; Clifford rows compare against Stim at 1 thread and Aer stabilizer.

Mid-circuit measure, feed-forward and reset

Aer takes 358x to 4021x the PRISM-Q time, 12 to 150 qubits

Exact numbers
WorkloadPRISM-Q 24 threadsPRISM-Q 1 threadAer 24 threadsAer automatic 24 threadsStim 1 threadAer stabilizer 24 threads
midcircuit 12q 10k shots2.98 msnot run1.07 s (358x)1.08 s (362x)not runnot run
midcircuit 12q 100k shots11.3 msnot run45.36 s (4021x)10.73 s (951x)not runnot run
midcircuit 18q 10k shots38.9 msnot run124.27 s (3199x)timeoutnot runnot run
midcircuit clifford 18q 10k shots1.18 ms1.22 msnot runnot run343 us (0.28x)27.5 ms (23.4x)
midcircuit clifford 60q 10k shots2.47 ms2.36 msnot runnot run1.26 ms (0.53x)2.22 s (901x)
midcircuit clifford 150q 10k shots4.18 ms4.06 msnot runnot run3.51 ms (0.86x)7.55 s (1804x)

Cold call, fastest warm call, the time Aer reports for itself, and the smallest shift in a marginal a sampled check detects:

WorkloadPRISM-Q 24 threadsPRISM-Q 1 threadAer 24 threadsAer automatic 24 threadsStim 1 threadAer stabilizer 24 threads
midcircuit 12q 10k shotscold 3.37 ms, fastest 2.94 ms, detects 0.021not runcold 1.11 s, fastest 1.03 s, internal 1.07 s, detects 0.021cold 1.09 s, fastest 1.05 s, internal 1.08 s, detects 0.021not runnot run
midcircuit 12q 100k shotscold 11.8 ms, fastest 11.2 ms, detects 0.0067not runcold 48.02 s, fastest 45.33 s, internal 45.36 s, detects 0.0067cold 10.76 s, fastest 10.32 s, internal 10.72 s, detects 0.0067not runnot run
midcircuit 18q 10k shotscold 38.0 ms, fastest 36.4 ms, detects 0.022not runcold 240.08 s, fastest 108.90 s, internal 124.26 s, detects 0.022timeoutnot runnot run
midcircuit clifford 18q 10k shotscold 1.34 ms, fastest 1.17 ms, detects 0.022cold 1.36 ms, fastest 1.20 ms, detects 0.022not runnot runcold 2.91 ms, fastest 330 us, detects 0.022cold 36.7 ms, fastest 26.8 ms, internal 23.4 ms, detects 0.022
midcircuit clifford 60q 10k shotscold 2.73 ms, fastest 2.25 ms, detects 0.023cold 2.50 ms, fastest 2.19 ms, detects 0.023not runnot runcold 3.41 ms, fastest 1.19 ms, detects 0.023cold 2.23 s, fastest 2.22 s, internal 2.21 s, detects 0.023
midcircuit clifford 150q 10k shotscold 4.29 ms, fastest 4.05 ms, detects 0.023cold 4.17 ms, fastest 3.99 ms, detects 0.023not runnot runcold 6.03 ms, fastest 3.45 ms, detects 0.023cold 7.58 s, fastest 7.52 s, internal 7.51 s, detects 0.023

Python bindings

  • Stim runs single-threaded; PRISM-Q runs at 1 and 24 threads, and ratios pair Stim with the 1-thread PRISM-Q record.
  • Smallest shift in a marginal the sampled check detects: PRISM-Q 0.0021 to 0.067, Stim 0.023, PRISM-Q Python 0.0021 to 0.067, Aer MPS 0.023, qsim fp32 0.0021 to 0.067 and Aer 0.0021 to 0.067; checks above 0.05 are marked weakly tested.
  • 3 rows take their reference vector from one simulator with no cross-check by a second.
  • qsim runs with max_fused_gate_size 3 at 16 and 20 qubits and 4 at 24 qubits.
  • Aer's matrix product state method runs with mps_lapack=True and mps_omp_threads equal to the thread count.
  • PRISM-Q Python runs the prism-q wheel inside the same Python worker used for Aer, qsim, Stim and quimb.
  • Ratios divide each column by native PRISM-Q at the matching thread count to isolate FFI overhead.

Python API overhead · PRISM-Q wheel against native Rust and Python peers

PRISM-Q Python takes 0.48x to 1.09x the PRISM-Q time, 16 to 1,000 qubits

† weakly tested: the check detects only shifts above 0.05 in a marginal; ‡ reference output with no cross-check by a second simulator.

Exact numbers
WorkloadPRISM-Q 24 threadsPRISM-Q Python 24 threadsPRISM-Q 1 threadPRISM-Q Python 1 threadAer 24 threadsqsim fp32 24 threadsStim 1 threadAer MPS 24 threadsquimb TN 24 threads
rcs 64q d8 4 Z + 4 ZZ10.8 ms10.7 ms (0.99x)not runnot runnot runnot runnot run20.4 ms (1.89x)711 ms (65.7x)
rcs 16q d102.29 ms1.09 ms (0.48x)not runnot run10.7 ms (4.67x)‡6.13 ms (2.68x)not runnot runnot run
rcs 20q d106.84 ms7.43 ms (1.09x)not runnot run40.5 ms (5.92x)‡13.6 ms (1.99x)not runnot runnot run
rcs 24q d10101 ms104 ms (1.03x)not runnot run649 ms (6.43x)‡198 ms (1.96x)not runnot runnot run
clifford 100q 10k shots776 us648 us (0.83x)767 us525 usnot runnot run1.49 ms (1.94x)not runnot run
clifford 1000q 10k shots2.99 ms3.24 ms (1.09x)3.12 ms3.45 msnot runnot run16.5 ms (5.30x)not runnot run
lowent 100q d4 10k shots6.61 ms5.65 ms (0.85x)not runnot runnot runnot runnot run5.28 s (799x)not run
sampling 20q 1k shots8.78 ms†9.03 ms (1.03x)†not runnot run42.9 ms (4.89x)†15.7 ms (1.79x)†not runnot runnot run
sampling 20q 100k shots18.7 ms19.4 ms (1.04x)not runnot run463 ms (24.7x)162 ms (8.67x)not runnot runnot run
sampling 20q 1M shots75.0 ms74.1 ms (0.99x)not runnot run3.89 s (51.9x)1.50 s (20.0x)not runnot runnot run

Cold call, fastest warm call, the time Aer reports for itself, and the smallest shift in a marginal a sampled check detects:

WorkloadPRISM-Q 24 threadsPRISM-Q Python 24 threadsPRISM-Q 1 threadPRISM-Q Python 1 threadAer 24 threadsqsim fp32 24 threadsStim 1 threadAer MPS 24 threadsquimb TN 24 threads
rcs 64q d8 4 Z + 4 ZZcold 12.5 ms, fastest 9.74 mscold 10.8 ms, fastest 10.5 msnot runnot runnot runnot runnot runcold 23.8 ms, fastest 20.1 ms, internal 6.29 mscold 3.46 s, fastest 706 ms
rcs 16q d10cold 3.13 ms, fastest 1.62 mscold 2.34 ms, fastest 997 usnot runnot runcold 12.8 ms, fastest 10.4 ms, internal 6.16 mscold 7.54 ms, fastest 5.84 msnot runnot runnot run
rcs 20q d10cold 7.85 ms, fastest 6.07 mscold 9.50 ms, fastest 7.22 msnot runnot runcold 48.3 ms, fastest 38.7 ms, internal 34.6 mscold 15.4 ms, fastest 13.0 msnot runnot runnot run
rcs 24q d10cold 106 ms, fastest 99.4 mscold 106 ms, fastest 104 msnot runnot runcold 639 ms, fastest 632 ms, internal 642 mscold 195 ms, fastest 188 msnot runnot runnot run
clifford 100q 10k shotscold 1.29 ms, fastest 766 us, detects 0.023cold 1.36 ms, fastest 543 us, detects 0.023cold 876 us, fastest 753 us, detects 0.023cold 995 us, fastest 487 us, detects 0.023not runnot runcold 3.26 ms, fastest 1.38 ms, detects 0.023not runnot run
clifford 1000q 10k shotscold 3.74 ms, fastest 2.68 ms, detects 0.023cold 4.43 ms, fastest 3.10 ms, detects 0.023cold 3.21 ms, fastest 2.90 ms, detects 0.023cold 3.53 ms, fastest 3.03 ms, detects 0.023not runnot runcold 18.8 ms, fastest 16.4 ms, detects 0.023not runnot run
lowent 100q d4 10k shotscold 7.97 ms, fastest 5.86 ms, detects 0.023cold 8.13 ms, fastest 5.51 ms, detects 0.023not runnot runnot runnot runnot runcold 5.30 s, fastest 5.26 s, internal 5.27 s, detects 0.023not run
sampling 20q 1k shotscold 10.1 ms, fastest 8.22 ms, detects 0.067cold 11.9 ms, fastest 8.39 ms, detects 0.067not runnot runcold 51.6 ms, fastest 41.1 ms, internal 37.0 ms, detects 0.067cold 19.4 ms, fastest 15.2 ms, detects 0.067not runnot runnot run
sampling 20q 100k shotscold 20.0 ms, fastest 18.4 ms, detects 0.0067cold 20.7 ms, fastest 18.8 ms, detects 0.0067not runnot runcold 467 ms, fastest 457 ms, internal 450 ms, detects 0.0067cold 168 ms, fastest 143 ms, detects 0.0067not runnot runnot run
sampling 20q 1M shotscold 75.3 ms, fastest 72.0 ms, detects 0.0021cold 77.1 ms, fastest 72.0 ms, detects 0.0021not runnot runcold 3.88 s, fastest 3.88 s, internal 3.81 s, detects 0.0021cold 1.46 s, fastest 1.48 s, detects 0.0021not runnot runnot run

QEC detector sampling

  • Stim runs single-threaded; PRISM-Q runs at 1 and 24 threads, and ratios pair Stim with the 1-thread PRISM-Q record.
  • The timed call ends at the simulator's own result: PRISM-Q and Stim, bit-packed detector and observable buffers.
  • Smallest shift in a marginal the sampled check detects: PRISM-Q 0.0032 to 0.01 and Stim 0.0032 to 0.01; checks above 0.05 are marked weakly tested.
  • Both parse the same .stim circuit, compile a detector sampler and draw packed detector and observable shots inside the timed call.
  • Logical error rate and detector trigger rates are checked statistically against each other.

Circuit-level QEC · rotated surface and repetition codes

Stim takes 4.56x to 17.2x the 1-thread PRISM-Q time, 15 to 625 qubits

Exact numbers
WorkloadPRISM-Q 24 threadsPRISM-Q 1 threadStim 1 thread
qec surface d=5 r=5 p=0.001 100k shots763 us1.10 ms11.8 ms (10.8x)
qec surface d=5 r=5 p=0.005 100k shots1.29 ms2.77 ms12.6 ms (4.56x)
qec surface d=9 r=9 p=0.001 100k shots3.46 ms6.18 ms80.2 ms (13.0x)
qec surface d=9 r=9 p=0.005 100k shots4.99 ms19.1 ms87.7 ms (4.59x)
qec surface d=9 r=9 p=0.005 1M shots29.7 ms177 ms902 ms (5.09x)
qec surface d=13 r=13 p=0.001 100k shots7.06 ms19.1 ms329 ms (17.2x)
qec surface d=13 r=13 p=0.005 100k shots10.8 ms55.5 ms351 ms (6.33x)
qec surface d=25 r=25 p=0.005 100k shots72.4 ms400 ms4.19 s (10.5x)
qec rep d=15 r=25 p=0.005 100k shots2.09 ms7.62 ms37.0 ms (4.86x)
qec rep d=15 r=25 p=0.005 1M shots14.9 ms67.0 ms377 ms (5.63x)
qec rep d=25 r=25 p=0.005 100k shots3.40 ms11.5 ms71.1 ms (6.19x)

Cold call, fastest warm call, and the smallest shift in a marginal a sampled check detects:

WorkloadPRISM-Q 24 threadsPRISM-Q 1 threadStim 1 thread
qec surface d=5 r=5 p=0.001 100k shotscold 1.48 ms, fastest 635 us, detects 0.01cold 1.20 ms, fastest 946 us, detects 0.01cold 13.8 ms, fastest 11.7 ms, detects 0.01
qec surface d=5 r=5 p=0.005 100k shotscold 1.95 ms, fastest 1.03 ms, detects 0.01cold 3.18 ms, fastest 2.67 ms, detects 0.01cold 15.1 ms, fastest 12.4 ms, detects 0.01
qec surface d=9 r=9 p=0.001 100k shotscold 3.26 ms, fastest 2.42 ms, detects 0.01cold 6.25 ms, fastest 5.74 ms, detects 0.01cold 82.9 ms, fastest 80.0 ms, detects 0.01
qec surface d=9 r=9 p=0.005 100k shotscold 5.13 ms, fastest 4.45 ms, detects 0.01cold 18.1 ms, fastest 18.6 ms, detects 0.01cold 91.1 ms, fastest 85.9 ms, detects 0.01
qec surface d=9 r=9 p=0.005 1M shotscold 32.2 ms, fastest 29.2 ms, detects 0.0032cold 173 ms, fastest 175 ms, detects 0.0032cold 913 ms, fastest 892 ms, detects 0.0032
qec surface d=13 r=13 p=0.001 100k shotscold 7.65 ms, fastest 6.93 ms, detects 0.01cold 22.2 ms, fastest 18.5 ms, detects 0.01cold 336 ms, fastest 321 ms, detects 0.01
qec surface d=13 r=13 p=0.005 100k shotscold 12.6 ms, fastest 10.5 ms, detects 0.01cold 55.0 ms, fastest 54.9 ms, detects 0.01cold 356 ms, fastest 344 ms, detects 0.01
qec surface d=25 r=25 p=0.005 100k shotscold 72.2 ms, fastest 71.5 ms, detects 0.01cold 407 ms, fastest 397 ms, detects 0.01cold 4.23 s, fastest 4.17 s, detects 0.01
qec rep d=15 r=25 p=0.005 100k shotscold 2.84 ms, fastest 1.83 ms, detects 0.01cold 8.13 ms, fastest 6.63 ms, detects 0.01cold 39.4 ms, fastest 36.8 ms, detects 0.01
qec rep d=15 r=25 p=0.005 1M shotscold 15.8 ms, fastest 14.3 ms, detects 0.0032cold 63.0 ms, fastest 64.4 ms, detects 0.0032cold 379 ms, fastest 375 ms, detects 0.0032
qec rep d=25 r=25 p=0.005 100k shotscold 4.65 ms, fastest 3.02 ms, detects 0.01cold 10.9 ms, fastest 10.8 ms, detects 0.01cold 73.8 ms, fastest 70.2 ms, detects 0.01

QEC syndrome decoding

  • PyMatching runs single-threaded; PRISM-Q MWPM runs at 1 and 24 threads, and ratios pair PyMatching with the 1-thread PRISM-Q MWPM record.
  • The timed call ends at the simulator's own result: PRISM-Q MWPM, PRISM-Q Union-Find and PyMatching, bit-packed logical predictions.
  • Every decoder receives the same bit-packed syndrome batch; DEM parsing and graph construction run outside the timer.
  • PRISM-Q Union-Find is shown beside MWPM as a linear-time decoder.

Detector error model decoding · MWPM and Union-Find

PyMatching takes 1.02x to 2.57x the 1-thread PRISM-Q MWPM time, 15 to 169 qubits

Exact numbers
WorkloadPRISM-Q MWPM 24 threadsPRISM-Q MWPM 1 threadPRISM-Q Union-Find 24 threadsPRISM-Q Union-Find 1 threadPyMatching 1 thread
decode surface d=5 r=5 p=0.001 10k shots91 us226 us166 us234 us579 us (2.57x)
decode surface d=5 r=5 p=0.005 10k shots274 us1.07 ms301 us1.12 ms1.68 ms (1.58x)
decode surface d=9 r=9 p=0.001 10k shots244 us1.12 ms250 us1.16 ms2.63 ms (2.36x)
decode surface d=9 r=9 p=0.005 10k shots953 us8.43 ms979 us7.36 ms10.1 ms (1.20x)
decode surface d=9 r=9 p=0.005 100k shots5.49 ms80.0 ms5.09 ms73.7 ms101 ms (1.26x)
decode surface d=13 r=13 p=0.001 10k shots600 us3.82 ms872 us4.50 ms7.81 ms (2.05x)
decode surface d=13 r=13 p=0.005 10k shots2.85 ms29.5 ms2.50 ms24.0 ms30.2 ms (1.02x)
decode rep d=15 r=25 p=0.005 10k shots664 us3.90 ms647 us3.07 ms6.67 ms (1.71x)
decode rep d=25 r=25 p=0.005 10k shots960 us7.44 ms816 us5.57 ms11.2 ms (1.50x)

Cold call, fastest warm call, and the smallest shift in a marginal a sampled check detects:

WorkloadPRISM-Q MWPM 24 threadsPRISM-Q MWPM 1 threadPRISM-Q Union-Find 24 threadsPRISM-Q Union-Find 1 threadPyMatching 1 thread
decode surface d=5 r=5 p=0.001 10k shotscold 745 us, fastest 65 uscold 357 us, fastest 212 uscold 726 us, fastest 59 uscold 330 us, fastest 220 uscold 792 us, fastest 571 us
decode surface d=5 r=5 p=0.005 10k shotscold 941 us, fastest 153 uscold 1.37 ms, fastest 1.06 mscold 782 us, fastest 203 uscold 1.21 ms, fastest 1.00 mscold 1.94 ms, fastest 1.66 ms
decode surface d=9 r=9 p=0.001 10k shotscold 866 us, fastest 176 uscold 1.33 ms, fastest 1.09 mscold 1.20 ms, fastest 216 uscold 1.28 ms, fastest 1.11 mscold 3.15 ms, fastest 2.60 ms
decode surface d=9 r=9 p=0.005 10k shotscold 1.72 ms, fastest 848 uscold 8.44 ms, fastest 7.97 mscold 1.64 ms, fastest 834 uscold 7.34 ms, fastest 7.30 mscold 10.9 ms, fastest 10.0 ms
decode surface d=9 r=9 p=0.005 100k shotscold 8.58 ms, fastest 4.92 mscold 80.7 ms, fastest 79.2 mscold 6.81 ms, fastest 4.46 mscold 73.1 ms, fastest 73.1 mscold 103 ms, fastest 101 ms
decode surface d=13 r=13 p=0.001 10k shotscold 1.57 ms, fastest 588 uscold 3.99 ms, fastest 3.71 mscold 1.83 ms, fastest 757 uscold 4.52 ms, fastest 4.27 mscold 9.43 ms, fastest 7.75 ms
decode surface d=13 r=13 p=0.005 10k shotscold 3.75 ms, fastest 2.59 mscold 29.1 ms, fastest 29.3 mscold 3.65 ms, fastest 2.27 mscold 24.6 ms, fastest 23.4 mscold 31.7 ms, fastest 30.1 ms
decode rep d=15 r=25 p=0.005 10k shotscold 1.25 ms, fastest 544 uscold 4.01 ms, fastest 3.75 mscold 1.19 ms, fastest 546 uscold 3.18 ms, fastest 3.00 mscold 7.16 ms, fastest 6.49 ms
decode rep d=25 r=25 p=0.005 10k shotscold 1.70 ms, fastest 863 uscold 7.21 ms, fastest 6.91 mscold 1.71 ms, fastest 647 uscold 5.67 ms, fastest 5.48 mscold 11.7 ms, fastest 10.9 ms

Exact density matrix

  • The timed call ends at the simulator's own result: PRISM-Q DM, PRISM-Q DM GPU and QuEST DM GPU, a probability vector; Aer density matrix, a Result holding the probability vector.
  • 14 rows take their reference vector from one simulator with no cross-check by a second.
  • Identical depolarizing or amplitude-damping channels after each gate layer; returns the full 2^n diagonal probability vector in fp64.
  • PRISM-Q and QuEST share depolarizing rate p; Aer scales p by 4/3 (1q) and 16/15 (2q) to match.
  • Ratios divide each peer column by CPU PRISM-Q DM; PRISM-Q DM GPU is shown beside it.

Noisy density matrix · fp64 · full probability vector

Aer density matrix takes 0.53x to 3.16x the PRISM-Q DM time, 8 to 14 qubits

‡ reference output with no cross-check by a second simulator.

Exact numbers
WorkloadPRISM-Q DMPRISM-Q DM GPUAer density matrixQuEST DM GPU
noisy rcs 8q d4 amp damp2.05 msnot run3.82 ms (1.86x)‡not run
noisy rcs 10q d4 amp damp6.71 ms3.19 ms16.9 ms (2.51x)‡12.0 ms (1.78x)
noisy rcs 12q d4 amp damp209 ms56.3 ms229 ms (1.09x)‡328 ms (1.57x)
noisy rcs 8q d4 depol1.61 msnot run5.08 ms (3.16x)‡not run
noisy rcs 10q d4 depol6.52 ms3.12 ms16.8 ms (2.57x)‡12.4 ms (1.90x)
noisy rcs 12q d4 depol207 ms56.4 ms240 ms (1.16x)‡349 ms (1.68x)
noisy rcs 13q d4 depol917 ms238 ms1.04 s (1.13x)‡1.51 s (1.64x)
noisy rcs 14q d4 depol4.13 s1.03 s4.35 s (1.05x)‡6.49 s (1.57x)
noisy hea 8q L3 amp damp2.27 msnot run3.93 ms (1.73x)‡not run
noisy hea 10q L3 amp damp10.9 ms2.20 ms16.1 ms (1.47x)‡6.83 ms (0.63x)
noisy hea 12q L3 amp damp279 ms81.1 ms321 ms (1.15x)‡183 ms (0.66x)
noisy hea 8q L3 depol9.86 msnot run5.19 ms (0.53x)‡not run
noisy hea 10q L3 depol9.67 ms4.52 ms21.9 ms (2.26x)‡7.79 ms (0.81x)
noisy hea 12q L3 depol282 ms82.5 ms358 ms (1.27x)‡214 ms (0.76x)

Cold call, fastest warm call, the time Aer reports for itself, and the smallest shift in a marginal a sampled check detects:

WorkloadPRISM-Q DMPRISM-Q DM GPUAer density matrixQuEST DM GPU
noisy rcs 8q d4 amp dampcold 2.86 ms, fastest 1.96 msnot runcold 6.93 ms, fastest 3.65 ms, internal 2.42 msnot run
noisy rcs 10q d4 amp dampcold 8.99 ms, fastest 6.35 mscold 7.76 ms, fastest 3.12 mscold 21.1 ms, fastest 15.8 ms, internal 15.1 mscold 38.0 ms, fastest 11.6 ms
noisy rcs 12q d4 amp dampcold 208 ms, fastest 205 mscold 63.5 ms, fastest 56.2 mscold 240 ms, fastest 223 ms, internal 227 mscold 354 ms, fastest 326 ms
noisy rcs 8q d4 depolcold 2.18 ms, fastest 1.61 msnot runcold 8.48 ms, fastest 4.90 ms, internal 2.99 msnot run
noisy rcs 10q d4 depolcold 8.79 ms, fastest 5.83 mscold 7.70 ms, fastest 3.11 mscold 25.6 ms, fastest 16.7 ms, internal 14.1 mscold 40.5 ms, fastest 12.2 ms
noisy rcs 12q d4 depolcold 204 ms, fastest 203 mscold 63.2 ms, fastest 56.3 mscold 253 ms, fastest 234 ms, internal 237 mscold 377 ms, fastest 345 ms
noisy rcs 13q d4 depolcold 924 ms, fastest 914 mscold 255 ms, fastest 236 mscold 1.05 s, fastest 1.03 s, internal 1.03 scold 1.53 s, fastest 1.51 s
noisy rcs 14q d4 depolcold 4.12 s, fastest 4.11 scold 1.08 s, fastest 1.02 scold 4.35 s, fastest 4.34 s, internal 4.34 scold 6.50 s, fastest 6.49 s
noisy hea 8q L3 amp dampcold 3.38 ms, fastest 2.20 msnot runcold 7.34 ms, fastest 3.76 ms, internal 2.80 msnot run
noisy hea 10q L3 amp dampcold 12.9 ms, fastest 9.46 mscold 7.03 ms, fastest 2.19 mscold 27.1 ms, fastest 15.7 ms, internal 14.7 mscold 34.1 ms, fastest 6.80 ms
noisy hea 12q L3 amp dampcold 286 ms, fastest 271 mscold 89.1 ms, fastest 81.0 mscold 322 ms, fastest 313 ms, internal 319 mscold 207 ms, fastest 183 ms
noisy hea 8q L3 depolcold 7.79 ms, fastest 8.99 msnot runcold 8.55 ms, fastest 4.79 ms, internal 3.39 msnot run
noisy hea 10q L3 depolcold 11.9 ms, fastest 9.40 mscold 9.10 ms, fastest 4.50 mscold 31.4 ms, fastest 21.5 ms, internal 19.4 mscold 34.2 ms, fastest 7.75 ms
noisy hea 12q L3 depolcold 287 ms, fastest 275 mscold 89.1 ms, fastest 82.4 mscold 363 ms, fastest 345 ms, internal 355 mscold 238 ms, fastest 211 ms

Noisy trajectories

  • The timed call ends at the simulator's own result: PRISM-Q, a histogram; Aer and Aer MPS, a Result holding a histogram.
  • Smallest shift in a marginal the sampled check detects: PRISM-Q 0.029 to 0.03, Aer 0.029 and Aer MPS 0.029 to 0.03; checks above 0.05 are marked weakly tested.
  • Aer's matrix product state method runs with mps_lapack=True and mps_omp_threads equal to the thread count.
  • Samples trajectories through the same depolarizing or amplitude-damping noise model.

Stochastic trajectories · hardware-efficient ansatz · 10,000 shots

Aer takes 54.6x to 286x the PRISM-Q time, 12 to 20 qubits

Exact numbers
WorkloadPRISM-QAerAer MPS
noisy hea 12q L3 amp damp 10k shots19.6 ms1.45 s (74.3x)33.25 s (1700x)
noisy hea 16q L3 amp damp 10k shots9.54 srefused60.48 s (6.34x)
noisy hea 20q L3 amp damp 10k shots57.23 srefused89.70 s (1.57x)
noisy hea 12q L3 depol 10k shots15.3 ms4.38 s (286x)4.85 s (317x)
noisy hea 16q L3 depol 10k shots208 ms11.34 s (54.6x)7.49 s (36.1x)
noisy hea 20q L3 depol 10k shots19.00 stimeout9.59 s (0.50x)

Cold call, fastest warm call, the time Aer reports for itself, and the smallest shift in a marginal a sampled check detects:

WorkloadPRISM-QAerAer MPS
noisy hea 12q L3 amp damp 10k shotscold 21.4 ms, fastest 18.5 ms, detects 0.029cold 1.48 s, fastest 1.41 s, internal 1.45 s, detects 0.029cold 33.20 s, fastest 33.24 s, internal 33.25 s, detects 0.029
noisy hea 16q L3 amp damp 10k shotscold 9.55 s, fastest 9.54 s, detects 0.029refusedcold 60.54 s, fastest 60.31 s, internal 60.48 s, detects 0.029
noisy hea 20q L3 amp damp 10k shotscold 57.13 s, fastest 57.11 s, detects 0.03refusedcold 87.71 s, fastest 89.55 s, internal 89.70 s, detects 0.03
noisy hea 12q L3 depol 10k shotscold 14.6 ms, fastest 14.2 ms, detects 0.029cold 4.38 s, fastest 4.37 s, internal 4.38 s, detects 0.029cold 4.87 s, fastest 4.81 s, internal 4.85 s, detects 0.029
noisy hea 16q L3 depol 10k shotscold 184 ms, fastest 175 ms, detects 0.029cold 11.22 s, fastest 11.23 s, internal 11.33 s, detects 0.029cold 8.05 s, fastest 7.00 s, internal 7.48 s, detects 0.029
noisy hea 20q L3 depol 10k shotscold 19.05 s, fastest 18.98 s, detects 0.03timeoutcold 9.56 s, fastest 9.58 s, internal 9.59 s, detects 0.03

Noisy MPO expectation values

  • The timed call ends at the simulator's own result: PRISM-Q MPO cap 64 and PRISM-Q DM, expectation values; Aer density matrix, a Result holding the marginal probabilities of each observable's qubits.
  • MPO evolution at bond cap 64 beside exact density-matrix references at 10 to 12 qubits, and out to 40 qubits beyond exact density-matrix memory.

Noisy Ising chain · 4 Z and 4 ZZ · MPO against exact density matrix

Aer density matrix takes 1.75x to 82.9x the PRISM-Q MPO cap 64 time, 10 to 40 qubits

* output not checked.

Exact numbers
WorkloadPRISM-Q MPO cap 64PRISM-Q DMAer density matrix
noisy tfim 10q 4 steps amp damp 4 Z + 4 ZZ3.73 ms8.42 ms23.4 ms (6.28x)
noisy tfim 12q 4 steps amp damp 4 Z + 4 ZZ5.47 ms378 ms453 ms (82.9x)
noisy tfim 10q 4 steps depol 4 Z + 4 ZZ16.1 ms11.7 ms28.2 ms (1.75x)
noisy tfim 12q 4 steps depol 4 Z + 4 ZZ23.5 ms459 ms464 ms (19.7x)
noisy tfim 20q 4 steps depol 4 Z + 4 ZZ50.1 ms*not runnot run
noisy tfim 40q 4 steps depol 4 Z + 4 ZZ116 ms*not runnot run

Cold call, fastest warm call, the time Aer reports for itself, and the smallest shift in a marginal a sampled check detects:

WorkloadPRISM-Q MPO cap 64PRISM-Q DMAer density matrix
noisy tfim 10q 4 steps amp damp 4 Z + 4 ZZcold 11.1 ms, fastest 3.59 mscold 11.8 ms, fastest 6.53 mscold 33.2 ms, fastest 23.2 ms, internal 22.0 ms
noisy tfim 12q 4 steps amp damp 4 Z + 4 ZZcold 11.8 ms, fastest 4.48 mscold 378 ms, fastest 375 mscold 459 ms, fastest 446 ms, internal 452 ms
noisy tfim 10q 4 steps depol 4 Z + 4 ZZcold 22.6 ms, fastest 15.7 mscold 16.0 ms, fastest 10.8 mscold 38.0 ms, fastest 27.5 ms, internal 25.8 ms
noisy tfim 12q 4 steps depol 4 Z + 4 ZZcold 32.0 ms, fastest 22.4 mscold 468 ms, fastest 446 mscold 473 ms, fastest 461 ms, internal 461 ms
noisy tfim 20q 4 steps depol 4 Z + 4 ZZcold 52.1 ms, fastest 47.8 msnot runnot run
noisy tfim 40q 4 steps depol 4 Z + 4 ZZcold 117 ms, fastest 109 msnot runnot run

Adjoint gradients

  • The timed call ends at the simulator's own result: PRISM-Q and PRISM-Q Python, energy and adjoint gradient vector.
  • Computes Hamiltonian expectation and all 2nL rotation derivatives in fp64 by reverse-mode adjoint.
  • Checked elementwise to 1e-8 against an exact NumPy adjoint reference up to 12 qubits.
  • PennyLane Lightning is omitted on Windows because its PyPI wheel builds without OpenMP or AVX2.

Variational HEA · exact energy and adjoint gradient · TFIM and Heisenberg

PRISM-Q Python takes 0.79x to 1.08x the PRISM-Q time, 12 to 24 qubits

Exact numbers
WorkloadPRISM-QPRISM-Q Python
var hea 12q L2 heisenberg756 us643 us (0.85x)
var hea 16q L2 heisenberg3.90 ms4.22 ms (1.08x)
var hea 20q L2 heisenberg27.5 ms29.3 ms (1.06x)
var hea 24q L2 heisenberg557 ms570 ms (1.02x)
var hea 12q L5 heisenberg1.34 ms1.19 ms (0.89x)
var hea 16q L5 heisenberg7.78 ms8.16 ms (1.05x)
var hea 20q L5 heisenberg46.4 ms48.3 ms (1.04x)
var hea 12q L2 tfim558 us442 us (0.79x)
var hea 16q L2 tfim3.68 ms3.42 ms (0.93x)
var hea 20q L2 tfim22.1 ms22.6 ms (1.02x)
var hea 24q L2 tfim382 ms388 ms (1.02x)
var hea 12q L5 tfim1.08 ms1.01 ms (0.93x)
var hea 16q L5 tfim7.21 ms7.44 ms (1.03x)
var hea 20q L5 tfim45.3 ms41.0 ms (0.91x)

Cold call, fastest warm call, and the smallest shift in a marginal a sampled check detects:

WorkloadPRISM-QPRISM-Q Python
var hea 12q L2 heisenbergcold 804 us, fastest 714 uscold 797 us, fastest 632 us
var hea 16q L2 heisenbergcold 5.20 ms, fastest 3.70 mscold 5.71 ms, fastest 3.73 ms
var hea 20q L2 heisenbergcold 31.4 ms, fastest 25.6 mscold 32.1 ms, fastest 27.8 ms
var hea 24q L2 heisenbergcold 569 ms, fastest 541 mscold 586 ms, fastest 559 ms
var hea 12q L5 heisenbergcold 1.59 ms, fastest 1.29 mscold 1.36 ms, fastest 1.17 ms
var hea 16q L5 heisenbergcold 9.00 ms, fastest 7.69 mscold 10.5 ms, fastest 7.96 ms
var hea 20q L5 heisenbergcold 55.5 ms, fastest 45.4 mscold 53.2 ms, fastest 46.7 ms
var hea 12q L2 tfimcold 626 us, fastest 514 uscold 580 us, fastest 430 us
var hea 16q L2 tfimcold 5.09 ms, fastest 3.62 mscold 5.50 ms, fastest 3.41 ms
var hea 20q L2 tfimcold 28.0 ms, fastest 21.3 mscold 27.9 ms, fastest 21.8 ms
var hea 24q L2 tfimcold 395 ms, fastest 376 mscold 395 ms, fastest 382 ms
var hea 12q L5 tfimcold 1.28 ms, fastest 1.06 mscold 1.18 ms, fastest 963 us
var hea 16q L5 tfimcold 9.23 ms, fastest 6.65 mscold 9.94 ms, fastest 7.09 ms
var hea 20q L5 tfimcold 49.8 ms, fastest 44.5 mscold 51.6 ms, fastest 39.7 ms

Variational parameter sweeps

  • The timed call ends at the simulator's own result: PRISM-Q and PRISM-Q Python, energy vector across all parameter bindings; Aer, a Result holding all binding energies.
  • Evaluates Hamiltonian expectation across 20 deterministic parameter vectors on a 2-layer HEA.
  • PRISM-Q reuses a PreparedCircuit fusion plan and cached PauliObservable grouping across all 20 points; Aer binds all 20 points in one batched run with parameter_binds.

Variational HEA · 20 parameter bindings · reusable fusion plan

Aer takes 2.04x to 44.7x the PRISM-Q time, 12 to 20 qubits

Exact numbers
WorkloadPRISM-QPRISM-Q PythonAer
var hea 12q L2 heisenberg 20 pts925 us873 us (0.94x)24.6 ms (26.6x)
var hea 16q L2 heisenberg 20 pts4.80 ms4.93 ms (1.03x)215 ms (44.7x)
var hea 20q L2 heisenberg 20 pts153 ms155 ms (1.02x)658 ms (4.31x)
var hea 12q L2 tfim 20 pts920 us597 us (0.65x)14.9 ms (16.2x)
var hea 16q L2 tfim 20 pts4.02 ms3.81 ms (0.95x)82.2 ms (20.5x)
var hea 20q L2 tfim 20 pts139 ms136 ms (0.98x)283 ms (2.04x)

Cold call, fastest warm call, the time Aer reports for itself, and the smallest shift in a marginal a sampled check detects:

WorkloadPRISM-QPRISM-Q PythonAer
var hea 12q L2 heisenberg 20 ptscold 1.93 ms, fastest 869 uscold 1.79 ms, fastest 599 uscold 25.7 ms, fastest 24.4 ms, internal 22.8 ms
var hea 16q L2 heisenberg 20 ptscold 5.48 ms, fastest 4.17 mscold 6.91 ms, fastest 4.56 mscold 289 ms, fastest 207 ms, internal 211 ms
var hea 20q L2 heisenberg 20 ptscold 163 ms, fastest 149 mscold 163 ms, fastest 153 mscold 8.09 s, fastest 633 ms, internal 655 ms
var hea 12q L2 tfim 20 ptscold 1.89 ms, fastest 844 uscold 2.15 ms, fastest 447 uscold 16.6 ms, fastest 14.1 ms, internal 12.5 ms
var hea 16q L2 tfim 20 ptscold 6.33 ms, fastest 3.57 mscold 6.73 ms, fastest 3.40 mscold 85.9 ms, fastest 79.7 ms, internal 79.3 ms
var hea 20q L2 tfim 20 ptscold 145 ms, fastest 136 mscold 142 ms, fastest 134 mscold 2.34 s, fastest 277 ms, internal 280 ms

Clifford+T circuits

  • Smallest shift in a marginal the sampled check detects: PRISM-Q 0.067 to 0.07 and Aer 0.067; checks above 0.05 are marked weakly tested.
  • Aer's matrix product state method runs with mps_lapack=True and mps_omp_threads equal to the thread count.
  • Clifford brickwork with 4 to 16 interleaved T and Tdg gates: shot counts against Aer extended_stabilizer and dense statevector up to 24 qubits, and Z/ZZ expectations out to 48 qubits.

Near-Clifford brickwork · interleaved T and Tdg gates

Median time, 20 to 48 qubits

† weakly tested: the check detects only shifts above 0.05 in a marginal.

Exact numbers
WorkloadPRISM-QAer extended stabilizerAerAer MPS
clifford t 20q d4 T=4 1k shots167 us†timeout19.9 ms (119x)†not run
clifford t 20q d4 T=8 4 Z + 4 ZZ6 usnot run7.05 ms (1156x)not run
clifford t 20q d4 T=8 1k shots173 us†timeout19.9 ms (115x)†not run
clifford t 20q d4 T=12 1k shots173 us†timeout21.6 ms (125x)†not run
clifford t 24q d4 T=4 1k shots170 us†not run267 ms (1570x)†not run
clifford t 24q d4 T=8 4 Z + 4 ZZ6 usnot run109 ms (16761x)not run
clifford t 24q d4 T=8 1k shots178 us†not run265 ms (1488x)†not run
clifford t 24q d4 T=12 1k shots187 us†not run258 ms (1380x)†not run
clifford t 32q d4 T=4 1k shots208 us†not runnot runnot run
clifford t 32q d4 T=8 4 Z + 4 ZZ8 usnot runnot run1.76 ms (215x)
clifford t 32q d4 T=8 1k shots191 us†not runnot runnot run
clifford t 32q d4 T=12 1k shots185 us†not runnot runnot run
clifford t 32q d4 T=16 4 Z + 4 ZZ10 usnot runnot run1.85 ms (187x)
clifford t 32q d4 T=16 1k shots211 us†timeoutnot runnot run
clifford t 48q d4 T=4 1k shots209 us†not runnot runnot run
clifford t 48q d4 T=8 4 Z + 4 ZZ12 usnot runnot run2.36 ms (202x)
clifford t 48q d4 T=8 1k shots223 us†not runnot runnot run
clifford t 48q d4 T=12 1k shots240 us†not runnot runnot run
clifford t 48q d4 T=16 4 Z + 4 ZZ13 usnot runnot run2.25 ms (176x)
clifford t 48q d4 T=16 1k shots237 us†not runnot runnot run

Cold call, fastest warm call, the time Aer reports for itself, and the smallest shift in a marginal a sampled check detects:

WorkloadPRISM-QAer extended stabilizerAerAer MPS
clifford t 20q d4 T=4 1k shotscold 310 us, fastest 161 us, detects 0.067timeoutcold 26.5 ms, fastest 19.0 ms, internal 18.6 ms, detects 0.067not run
clifford t 20q d4 T=8 4 Z + 4 ZZcold 76 us, fastest 6 usnot runcold 11.4 ms, fastest 6.91 ms, internal 5.98 msnot run
clifford t 20q d4 T=8 1k shotscold 298 us, fastest 162 us, detects 0.067timeoutcold 27.1 ms, fastest 19.4 ms, internal 18.6 ms, detects 0.067not run
clifford t 20q d4 T=12 1k shotscold 305 us, fastest 168 us, detects 0.067timeoutcold 28.2 ms, fastest 20.8 ms, internal 20.3 ms, detects 0.067not run
clifford t 24q d4 T=4 1k shotscold 297 us, fastest 160 us, detects 0.067not runcold 276 ms, fastest 262 ms, internal 265 ms, detects 0.067not run
clifford t 24q d4 T=8 4 Z + 4 ZZcold 70 us, fastest 6 usnot runcold 108 ms, fastest 104 ms, internal 108 msnot run
clifford t 24q d4 T=8 1k shotscold 287 us, fastest 160 us, detects 0.067not runcold 266 ms, fastest 260 ms, internal 263 ms, detects 0.067not run
clifford t 24q d4 T=12 1k shotscold 322 us, fastest 180 us, detects 0.067not runcold 267 ms, fastest 256 ms, internal 256 ms, detects 0.067not run
clifford t 32q d4 T=4 1k shotscold 333 us, fastest 174 us, detects 0.068not runnot runnot run
clifford t 32q d4 T=8 4 Z + 4 ZZcold 70 us, fastest 8 usnot runnot runcold 4.26 ms, fastest 1.68 ms, internal 295 us
clifford t 32q d4 T=8 1k shotscold 312 us, fastest 182 us, detects 0.068not runnot runnot run
clifford t 32q d4 T=12 1k shotscold 313 us, fastest 180 us, detects 0.068not runnot runnot run
clifford t 32q d4 T=16 4 Z + 4 ZZcold 80 us, fastest 10 usnot runnot runcold 4.18 ms, fastest 1.67 ms, internal 308 us
clifford t 32q d4 T=16 1k shotscold 344 us, fastest 195 us, detects 0.068timeoutnot runnot run
clifford t 48q d4 T=4 1k shotscold 341 us, fastest 207 us, detects 0.07not runnot runnot run
clifford t 48q d4 T=8 4 Z + 4 ZZcold 96 us, fastest 11 usnot runnot runcold 4.84 ms, fastest 2.08 ms, internal 347 us
clifford t 48q d4 T=8 1k shotscold 344 us, fastest 222 us, detects 0.07not runnot runnot run
clifford t 48q d4 T=12 1k shotscold 366 us, fastest 236 us, detects 0.07not runnot runnot run
clifford t 48q d4 T=16 4 Z + 4 ZZcold 161 us, fastest 12 usnot runnot runcold 5.38 ms, fastest 2.23 ms, internal 342 us
clifford t 48q d4 T=16 1k shotscold 353 us, fastest 225 us, detects 0.07not runnot runnot run

Sparse statevector

  • The timed call ends at the simulator's own result: PRISM-Q and PRISM-Q sparse, a histogram; Aer, Aer MPS and Aer automatic, a Result holding a histogram.
  • Smallest shift in a marginal the sampled check detects: PRISM-Q 0.021 to 0.032, Aer 0.021, Aer MPS 0.021 to 0.032, Aer automatic 0.021 to 0.03 and PRISM-Q sparse 0.021 to 0.032; checks above 0.05 are marked weakly tested.
  • Aer's matrix product state method runs with mps_lapack=True and mps_omp_threads equal to the thread count.
  • Long-range CX/CZ/T circuits keeping support at 16 to 4,096 nonzero amplitudes while crossing every 1D MPS cut.

Non-local sparse support · bounded nonzero amplitudes · 10,000 shots

Aer MPS takes 49.7x to 3661x the PRISM-Q time, 20 to 100 qubits

* output not checked.

Exact numbers
WorkloadPRISM-QPRISM-Q sparseAerAer MPSAer automatic
sparse ghz t 20q 4 branches 10k shots717 us227 us48.2 ms (67.3x)1.08 s (1509x)46.4 ms (64.7x)
sparse ghz t 30q 4 branches 10k shots876 us255 usnot run1.76 s (2013x)11.29 s (12881x)
sparse ghz t 50q 4 branches 10k shots987 us315 usnot run2.77 s (2807x)refused, statevector would not fit
sparse ghz t 100q 4 branches 10k shots1.49 ms365 usnot run5.45 s (3661x)refused, statevector would not fit
sparse walk 20q k=10 10k shots6.08 ms604 us56.6 ms (9.30x)5.08 s (836x)54.2 ms (8.91x)
sparse walk 30q k=10 10k shots548 ms608 usnot run27.26 s (49.7x)23.11 s (42.1x)
sparse walk 50q k=10 10k shots8.78 s879 usnot runtimeoutrefused, statevector would not fit
sparse walk 50q k=12 10k shotsinvalid2.34 msnot runtimeoutrefused, statevector would not fit
sparse walk 80q k=10 10k shots31.17 s*1.58 ms*not runtimeoutrefused, statevector would not fit

Cold call, fastest warm call, the time Aer reports for itself, and the smallest shift in a marginal a sampled check detects:

WorkloadPRISM-QPRISM-Q sparseAerAer MPSAer automatic
sparse ghz t 20q 4 branches 10k shotscold 866 us, fastest 648 us, detects 0.021cold 405 us, fastest 194 us, detects 0.021cold 51.8 ms, fastest 43.9 ms, internal 47.5 ms, detects 0.021cold 1.10 s, fastest 1.08 s, internal 1.08 s, detects 0.021cold 51.1 ms, fastest 42.7 ms, internal 45.7 ms, detects 0.021
sparse ghz t 30q 4 branches 10k shotscold 1.01 ms, fastest 858 us, detects 0.022cold 450 us, fastest 252 us, detects 0.022not runcold 1.75 s, fastest 1.61 s, internal 1.76 s, detects 0.022cold 11.40 s, fastest 11.24 s, internal 11.28 s, detects 0.022
sparse ghz t 50q 4 branches 10k shotscold 1.20 ms, fastest 985 us, detects 0.031cold 526 us, fastest 310 us, detects 0.031not runcold 2.73 s, fastest 2.76 s, internal 2.77 s, detects 0.031refused, statevector would not fit
sparse ghz t 100q 4 branches 10k shotscold 1.83 ms, fastest 1.44 ms, detects 0.032cold 572 us, fastest 363 us, detects 0.032not runcold 5.46 s, fastest 5.35 s, internal 5.45 s, detects 0.032refused, statevector would not fit
sparse walk 20q k=10 10k shotscold 6.64 ms, fastest 5.32 ms, detects 0.021cold 777 us, fastest 592 us, detects 0.021cold 63.3 ms, fastest 50.9 ms, internal 55.3 ms, detects 0.021cold 5.16 s, fastest 5.08 s, internal 5.08 s, detects 0.021cold 58.7 ms, fastest 50.8 ms, internal 52.9 ms, detects 0.021
sparse walk 30q k=10 10k shotscold 589 ms, fastest 540 ms, detects 0.03cold 859 us, fastest 596 us, detects 0.03not runcold 27.81 s, fastest 27.04 s, internal 27.26 s, detects 0.03cold 22.95 s, fastest 23.04 s, internal 23.11 s, detects 0.03
sparse walk 50q k=10 10k shotscold 8.75 s, fastest 8.75 s, detects 0.022cold 1.07 ms, fastest 855 us, detects 0.022not runtimeoutrefused, statevector would not fit
sparse walk 50q k=12 10k shotscold 12.81 s, fastest 12.76 s, detects 0.022cold 2.64 ms, fastest 2.13 ms, detects 0.022not runtimeoutrefused, statevector would not fit
sparse walk 80q k=10 10k shotscold 29.08 s, fastest 29.22 scold 1.72 ms, fastest 1.51 msnot runtimeoutrefused, statevector would not fit

Every row

  • Filter the comparisons above by method, circuit family and simulator.

Explore

Peer time as a multiple of PRISM-Q time, per workload

Thread scaling

  • 24 physical cores, 24 hardware threads; rows below 24 threads are timed without an output check.

Strong scaling · 1 to 24 threads

PRISM-Q time at 1 thread is 4.51x to 9.30x its time at 24 threads

Exact numbers
24 threads over 1PRISM-QAerqsim fp32QuEST
qaoa 24q4.52x6.00x5.66x2.26x
qft 24q4.51x7.16x2.32x2.80x
qv 22q8.61x10.0x7.57x5.65x
rcs 24q d109.30x9.55x7.58x2.40x

Automatic dispatch

  • Each row also runs with every PRISM-Q backend forced by hand, on the same circuit.

Auto against every forced backend

Automatic dispatch takes 0.28x to 1.20x the time of the fastest forced backend on 9 rows

Forced backends without a valid output: factored (3 refused); mps-64 (1 invalid); sparse (3 refused); tensor-network (2 timeout).

Exact numbers
WorkloadAutomatic choiceFastest forced backendAutomatic / fastest
rcs 20q d10Statevector, 7.11 msstatevector, 6.90 ms1.03x
qft 20qStatevector, 4.02 msstatevector, 3.98 ms1.01x
qaoa 20qStatevector, 3.80 msstatevector, 3.16 ms1.20x
clifford 1000q 1k shotsCompiledStabilizer, 1.26 msstabilizer, 1.13 ms1.11x
ghz 1000q 1k shotsCompiledStabilizer, 109 usstabilizer, 101 us1.08x
lowent 100q d4 1k shotsMps, 1.91 msmps-64, 1.88 ms1.01x
disjoint 100q contiguous 1k shotsDecomposed, 5.97 msfactored, 20.1 ms0.30x
midcircuit 12q 1k shotsStatevector, 1.00 mssparse, 3.62 ms0.28x
sampling 20q 100k shotsStatevector, 19.7 msstatevector, 19.3 ms1.02x

Peak memory

  • Peak working set of the whole process, including the Python interpreter for peers run from Python.

Peak working set · rcs depth 10

At 28 qubits PRISM-Q peaks at 6.01 GB; the bare fp64 state is 4.00 GB

Exact numbers
Workloadfp64 statePRISM-QAerQuESTAer fp32qsim fp32
rcs 20q d1016 MB36 MB112 MB30 MB103 MB220 MB
rcs 24q d10256 MB397 MB473 MB390 MB344 MB580 MB
rcs 26q d101.00 GB1.51 GB1.59 GB1.51 GB1.09 GB1.69 GB
rcs 28q d104.00 GB6.01 GB6.09 GB6.00 GB4.09 GB6.19 GB

Correctness

  • Dense, total variation distance against the reference vector: 383 of 383 within tolerance.
  • Expectation values, absolute difference per value against the cone reference (⟨Z⟩ = 1 - 2p, ⟨ZZ⟩ = 1 - 2 P(odd)), against a simulator of another family where the cone is too wide: 92 of 92 within tolerance; 2 not tested.
  • Parameter sweeps, elementwise absolute difference across all parameter bindings against the exact NumPy statevector reference up to 12 qubits, or against another simulator beyond: 18 of 18 within tolerance.
  • Adjoint gradients, elementwise absolute difference on energy and every adjoint partial derivative against the exact NumPy adjoint reference up to 12 qubits, or against another simulator beyond: 28 of 28 within tolerance.
  • Sampled, exact binomial test per statistic against the cone reference, two-sample z-test against another simulator where the cone is too wide; Bonferroni family-wise alpha 1e-3: 311 of 312 passed; 85 of those passes detect only shifts above 0.05 in a marginal; 12 under 100 shots checked on deterministic bits only; 2 not tested.
  • Statistics only, exact binomial test per statistic against the cone reference, two-sample z-test against another simulator where the cone is too wide; Bonferroni family-wise alpha 1e-3, on the statistics and shot total the simulator returns: 15 of 15 passed.
  • QEC syndrome decoding, shot total and logical error rate check on one shared syndrome batch, compared against exact minimum-weight perfect matching where available: 45 of 45 passed.
  • QEC detector sampling, two-sample z-test per detector and logical observable firing rate against another QEC sampler; Bonferroni family-wise alpha 1e-3, plus exact shot total check: 33 of 33 passed.

Runs without a valid timing:

SimulatorOutcomeWorkloadsDetail
PRISM-Qinvalidsparse walk 50q k=12 10k shotsb10: p 3.08e-11 below 1.01e-05; b22: p 6.94e-13 below 1.01e-05; b34: p 3.08e-11 below 1.01e-05; b46: p 3.08e-1
Aer automaticrefused, statevector would not fit6 shallow, 4 disconnected, 3 wstate, 5 sparse rowsAer reports the statevector would not fit in memory
Aer automatictimeoutmidcircuit 18q 10k shotspast the 600 s timeout
Aer extended stabilizertimeout4 clifford rowspast the 120 s timeout
Aer MPStimeoutsparse walk 50q k=10 10k shots, sparse walk 80q k=10 10k shots, sparse walk 50q k=12 10k shotspast the 300 s timeout
Aer stabilizertimeoutghz 1000q 10k shots, bv 1000q 10k shotspast the 300 s timeout
Aer statevectorrefusednoisy hea 16q L3 amp damp 10k shots, noisy hea 20q L3 amp damp 10k shotsSomething went wrong in heevx call within eigensystem_hermitian funcion
Aer statevectortimeoutnoisy hea 20q L3 depol 10k shotspast the 600 s timeout
Aer statevector (fp32)crash4 qft, 3 qaoa, 3 tfim rowsexit 0xC0000005

PRISM-Q alone

  • bench_suite measured 2026-11-30 with PRISM-Q 0.39.0 on Intel Core Ultra 7 270K Plus, automatic dispatch, 24 threads.
  • Backend each family resolved to: GHZ on Stabilizer; QFT, HEA and QV on Statevector.
  • Rows without a probability vector time the run alone: GHZ at 256, 1,024 and 4,096 qubits. Every other row includes the dense probability vector.

bench_suite · PRISM-Q 0.39.0 · 2026-11-30

Median time per run up to 28 dense qubits

Exact numbers
FamilyQubitsMedian
GHZ2422.3 ms
GHZ28356 ms
GHZ25648 us
GHZ1,024251 us
GHZ4,0961.73 ms
QFT16510 us
QFT202.50 ms
QFT2452.0 ms
QFT26230 ms
QFT28943 ms
HEA161.11 ms
HEA206.26 ms
HEA2476.2 ms
HEA26372 ms
HEA281.34 s
QV161.72 ms
QV2012.5 ms
QV24251 ms

Setup and versions

  • 10 of 30 shown bondsweep records come from the older run 20261122T100027-8edcc6 (2026-11-22, commit 91aaace71d with uncommitted changes).
  • 63 of 136 shown headline records come from the older run 20261121T232653-02f5f1 (2026-11-21, commit 91aaace71d with uncommitted changes).
  • 5 of 15 shown highshot records come from the older run 20261122T100027-8edcc6 (2026-11-22, commit 91aaace71d with uncommitted changes).
  • 25 of 40 shown mpsdeep records come from the older runs 20261122T100027-8edcc6 (2026-11-22, commit 91aaace71d with uncommitted changes) and 20261122T155821-4e85fd (2026-11-22, commit ab9d609f96 with uncommitted changes).
  • 18 of 36 shown sampling records come from the older run 20261121T232653-02f5f1 (2026-11-21, commit 91aaace71d with uncommitted changes).
  • 46 of 224 shown scaling records come from the older runs 20261122T125954-351f34 (2026-11-22, commit 91aaace71d with uncommitted changes), 20261122T150802-b9931a (2026-11-22, commit ab9d609f96 with uncommitted changes) and 20261122T191145-100a21 (2026-11-22, commit ab9d609f96 with uncommitted changes).
  • 4 of 12 shown seeds records come from the older run 20261122T100027-8edcc6 (2026-11-22, commit 91aaace71d with uncommitted changes).
  • 32 of 64 shown threads records come from the older runs 20261121T232653-02f5f1 (2026-11-21, commit 91aaace71d with uncommitted changes) and 20261122T190226-900c36 (2026-11-22, commit ab9d609f96 with uncommitted changes).
  • 8 of 40 shown tn records come from the older run 20261122T100027-8edcc6 (2026-11-22, commit 91aaace71d with uncommitted changes).
  • 52 of 109 shown zoo records come from the older runs 20261122T100027-8edcc6 (2026-11-22, commit 91aaace71d with uncommitted changes), 20261122T173220-3be21e (2026-11-22, commit ab9d609f96 with uncommitted changes), 20261122T174253-c4c575 (2026-11-22, commit ab9d609f96 with uncommitted changes), 20261122T190343-ac768a (2026-11-22, commit ab9d609f96 with uncommitted changes) and 20261122T190438-5c6a2f (2026-11-22, commit ab9d609f96 with uncommitted changes).
ItemValue
HostIntel64 Family 6 Model 198 Stepping 2, GenuineIntel, 24 cores, 24 threads, Windows 11
PRISM-Q0.39.0, rustc 1.99.0, parallel
Python3.14.0
Commitba6bb2cd83 with uncommitted changes
Runs20261121T232653-02f5f1 and 26 supplementary runs; the rows below describe 20261130T193717-34f778
PRISM-Q Python0.39.0, double
Aer statevector0.17.2, double, OMP_WAIT_POLICY=PASSIVE
Aer density matrix0.17.2, double, OMP_WAIT_POLICY=PASSIVE
Aer statevector (fp32)0.17.2, single, OMP_WAIT_POLICY=PASSIVE
Aer automatic0.17.2, double, OMP_WAIT_POLICY=PASSIVE
Aer stabilizer0.17.2, exact (tableau), OMP_WAIT_POLICY=PASSIVE
Aer extended stabilizer0.17.2, double, OMP_WAIT_POLICY=PASSIVE
Aer MPS0.17.2, double, OMP_WAIT_POLICY=PASSIVE
Stim1.16.0, exact (tableau), package 1.16.0 loading stim._stim_sse2
PyMatching2.4.0, exact (mwpm)
quimb TN1.15.0, double, cotengra 0.8.3, cotengrust 0.2.1, OMP_WAIT_POLICY=PASSIVE
quimb MPS1.15.0, double, OMP_WAIT_POLICY=PASSIVE
qsim (fp32)0.22.1, single, OMP_WAIT_POLICY=PASSIVE
QuESTv4.3.0, double, OMP_WAIT_POLICY=PASSIVE, built with MSVC 19.44.35230.0, /DWIN32 /D_WINDOWS /EHsc /O2 /Ob2 /DNDEBUG /arch:AVX2 -openmp
QuEST GPUv4.3.0, double, built with MSVC 19.44.35230.0, /DWIN32 /D_WINDOWS /EHsc /O2 /Ob2 /DNDEBUG /arch:AVX2 -openmp, nvcc 13.5.37 for 120
QuEST DM GPUv4.3.0, double, built with MSVC 19.44.35230.0, /DWIN32 /D_WINDOWS /EHsc /O2 /Ob2 /DNDEBUG /arch:AVX2 -openmp, nvcc 13.5.37 for 120
Spinoza0.5.1 (git f900971), double, built with rustc 1.102.0-nightly, rustflags -C target-cpu=x86-64-v3
qip1.5.0, double, built with rustc 1.102.0-nightly, rustflags -C target-cpu=x86-64-v3

Rerun the matrix and regenerate this page (these results took 9.3 h of measurement; --profile smoke takes a few minutes):

comparison/.venv/Scripts/python comparison/matrix.py run --profile reference --out comparison/results/my-run
comparison/.venv/Scripts/python comparison/matrix.py report comparison/results/my-run --docs docs/performance

Rerun the PRISM-Q suite (rewrites suite.json beside this page):

cargo run --release --features parallel --example bench_suite

Circuit Builders

Prebuilt circuits for benchmarks and tests, in prism_q::circuits (src/circuits.rs). Every function in the table returns a Circuit ready for simulate(&circuit).

FunctionDescription
qft_circuit(n)Quantum Fourier Transform
random_circuit(n, depth, seed)Random gates at given depth
hardware_efficient_ansatz(n, layers, seed)HEA with Ry/Rz + CX
clifford_heavy_circuit(n, depth, seed)Random Clifford (adjacent CX)
clifford_random_pairs(n, depth, seed)Random Clifford (random pair CX)
ghz_circuit(n)GHZ state (H + CX chain)
qaoa_circuit(n, layers, seed)QAOA MaxCut
single_qubit_rotation_circuit(n, depth, seed)Single-qubit rotations only
clifford_t_circuit(n, depth, t_fraction, seed)Clifford+T with tunable T ratio
w_state_circuit(n)W state preparation
quantum_volume_circuit(n, depth, seed)Quantum volume (random SU(4))
cz_chain_circuit(n, depth, seed)CZ chains
phase_estimation_circuit(n)Quantum phase estimation
independent_bell_pairs(n_pairs)Independent Bell pairs
independent_random_blocks(blocks, size, depth, seed)Independent random blocks
partially_independent_circuit(n, depth, seed)Mostly independent halves with a few crossing gates
measure_split_circuit(n, layers, seed)A chain that mid-circuit measurements and resets halve, then rotation layers on the survivors; n >= 8
controlled_rotation_circuit(n, layers, seed)Local rotations alternating with controlled Rx and Ry on offset ring pairings
disjoint_block_layers_circuit(n, k, layers, seed)Layers of disjoint k-qubit blocks
diagonal_mixed_circuit(n, layers, seed)Diagonal families mixed with single-qubit rotations
local_clifford_blocks(num_blocks, block_size, depth, seed)Clifford blocks with no coupling between them
clifford_prefix_measured_blocks(num_blocks, block_size, depth, seed)Clifford blocks, then per block rotations, a mid-circuit measurement with feed-forward, and a final measurement
brickwork_circuit(n, depth, seed)Alternating even and odd two-qubit layers
matched_brickwork_circuit(n, depth, seed)Brickwork whose layers pair up for cancellation
sparse_walk_circuit(n, k, depth, seed)Walk that keeps roughly k amplitudes live

jordan_wigner_hamiltonian(n, max_terms, seed) returns a Hamiltonian instead, a Vec<(f64, Vec<PauliTerm>)> that PauliObservable::from_terms turns into the observable expectation_gradient takes: the Jordan-Wigner transform of a seeded random fermionic operator on n modes, cut to the max_terms largest coefficients.

Example

#![allow(unused)]
fn main() {
use prism_q::circuits::qft_circuit;
use prism_q::simulate;

let circuit = qft_circuit(10);
let result = simulate(&circuit).seed(42).run().unwrap();
}

Hand-built circuits go through CircuitBuilder. Signatures are on docs.rs.

Python API

The Rust free functions with a Python counterpart, Rust paths relative to the crate root. Methods and result fields map one to one under Python conventions; the rules and the renamed classes are on Errors, Typing and Names. bindings/python/parity.toml gives the reason for each function left out, and bindings/python/tests/test_parity.py fails when this table and the manifest disagree.

RustPython
circuit::guardedCircuitBuilder.guarded
circuit::openqasm::parseparse_qasm
circuit::openqasm::parse_braketparse_braket
circuit::openqasm::parse_dynamicparse_qasm_dynamic
circuit::openqasm::parse_dynamic_with_externsparse_qasm_dynamic
circuit::openqasm::parse_dynamic_with_inputsparse_qasm_dynamic
circuit::openqasm::parse_parametricparse_qasm_parametric
circuit::openqasm::parse_parametric_with_externsparse_qasm_parametric
circuit::openqasm::parse_parametric_with_inputsparse_qasm_parametric
circuit::openqasm::parse_with_externsparse_qasm
circuit::qasm_export::to_qasm3Circuit.to_qasm
circuits::clifford_heavy_circuitcircuits.clifford_heavy
circuits::clifford_random_pairscircuits.clifford_random_pairs
circuits::clifford_t_circuitcircuits.clifford_t
circuits::cz_chain_circuitcircuits.cz_chain
circuits::ghz_circuitcircuits.ghz
circuits::hardware_efficient_ansatzcircuits.hardware_efficient_ansatz
circuits::independent_bell_pairscircuits.independent_bell_pairs
circuits::independent_random_blockscircuits.independent_random_blocks
circuits::local_clifford_blockscircuits.local_clifford_blocks
circuits::phase_estimation_circuitcircuits.phase_estimation
circuits::qaoa_circuitcircuits.qaoa
circuits::qft_circuitcircuits.qft
circuits::quantum_volume_circuitcircuits.quantum_volume
circuits::random_circuitcircuits.random
circuits::single_qubit_rotation_circuitcircuits.single_qubit_rotation
circuits::w_state_circuitcircuits.w_state
compile_measurementsCompiledSampler
compile_noisyCompiledSampler
default_limitsdefault_limits
density_matrix_expectation_valuesSimulation.expectation
gpu::is_availableGpuContext.is_available
noisy_marginals_analyticalnoisy_marginals_analytical
parse_qec_programQecProgram.from_text
parse_stim_circuitQecProgram.from_stim
run_qasmrun_qasm
run_qec_programQecProgram.run
run_qec_program_referenceQecProgram.run_reference
run_shots_compiledSimulation.shots
run_shots_noisySimulation.shots
run_spdBackendKind.deterministic_pauli
run_spd_withBackendKind.deterministic_pauli_budget
run_sppBackendKind.stochastic_pauli
run_stabilizer_rankBackendKind.stabilizer_rank
set_default_limitsset_default_limits
sim::calibration::presets::neutral_atomDeviceCalibration.neutral_atom
sim::calibration::presets::superconducting_transmonDeviceCalibration.superconducting_transmon
sim::calibration::presets::trapped_ionDeviceCalibration.trapped_ion
sim::gradient::run_expectation_gradientSimulation.expectation_gradient
sim::gradient::run_expectation_gradient_shiftSimulation.expectation_gradient_shift
sim::run_batchrun_batch
sim::run_expectation_valuesSimulation.expectation
sim::run_observable_expectationSimulation.expectation
sim::unified_pauli::run_pauli_path_observableBackendKind.pauli_path
simulatesimulate
simulate_programsimulate_program

Glossary

Backend A simulation strategy implementing the Backend trait: statevector, stabilizer, MPS and the others. BackendKind::Auto picks one per circuit, or the caller names one.

Bond dimension The size of the index joining two neighbouring tensors in an MPS. It bounds how much entanglement the chain can carry across that cut; Mps { max_bond_dim } caps it, and a run that hits the cap truncates.

Clifford The gates generated by H, S and CNOT. Stabilizer tableaus simulate them in O(n²) time.

Compiled sampler A sampler that propagates the circuit's measurements once into a reusable form, then draws every shot from it without rebuilding the state. CompiledStabilizer in run metadata names this route for Clifford circuits.

Count A histogram of measured bitstrings across shots, returned by simulate(&circuit).seed(seed).sample_counts(shots).

Detector A parity of measurement records that reads 0 in every shot when no error occurs. A QEC program declares detectors, and a decoder reads which ones fired.

Detector error model The list of independent error mechanisms in a noisy QEC program, each with its probability and the detectors and observables it flips. Decoders take it as input.

Fusion The pass pipeline that merges, cancels and reorders gates before simulation.

Kraus channel A noise channel written as a set of matrices K_i with sum K_i† K_i = I. Depolarizing, damping and custom channels are all Kraus channels; the density-matrix backend applies them exactly, and trajectory runs pick one K_i per shot.

Leakage Noise that moves a qubit out of the two computational levels. A leaked qubit ignores gates and measures as 1 until a reset or seepage returns it, and shot results report which qubits leaked.

Marginal A (P(0), P(1)) pair for one qubit, extracted without computing the full joint distribution.

MPS (Matrix Product State) A backend that stores the state as a chain of rank-3 tensors with bounded bond dimension, trading exactness for polynomial memory.

Noise model A set of probabilistic error channels, such as depolarizing noise, applied during noisy simulation.

OpenQASM A text language for quantum circuits. PRISM-Q parses a practical subset of OpenQASM 3.0 and exports circuits back to it.

Pauli propagation Simulation that tracks an observable as a weighted sum of Pauli strings, pushed backwards through the circuit, instead of tracking the state. PRISM-Q has a stochastic, a deterministic and a noisy (Pauli path) form.

Shot One execution of a circuit from initialization to measurement, producing one bitstring.

Stabilizer A Clifford state stored as a bit-packed tableau of Pauli generators, which scales to thousands of qubits.

Stabilizer rank The number of stabilizer states summed to write a non-Clifford state. The stabilizer-rank engine tracks such a sum, whose size grows with the T count, not the qubit count.

State vector The 2^n complex amplitudes of the full quantum state, as held by the statevector backend.

T count The number of T gates a circuit lowers to, counting T† and gates that decompose into T. Circuit::t_count reports it, and it sets the cost of the Clifford+T engines.

Tensor network A backend that holds gates as tensors and defers contraction until a query reads the result. BackendKind::Auto routes only expectation and marginal queries to it.

Trajectory One sampled path through a noisy circuit: each channel picks one outcome per shot, and the state evolves as a pure state. Averaging many trajectories approximates the mixed state the density matrix holds exactly.

Roadmap

Open work on PRISM-Q, grouped by theme in rough priority order, with what each item waits on. These are intentions, not commitments, and carry no dates. A shipped item leaves the page for the changelog.

1.0 has no date. Until then, Compatibility and Versioning says what each release promises.

StatusMeaning
PlannedOpen, with nothing outside the project in the way
Needs hardwareWaits on a machine the project has no access to; see Hardware that would help
Needs a use caseWaits on a circuit or caller that needs it. A discussion describing one moves it up
ResearchThe approach is not settled

QEC and noise

ItemStatus
Error mitigation primitives on the expectation-value APINeeds a use case

Large structured circuits

ItemStatus
A dense or MPS engine for each slice of a sliced tensor network contraction, for circuits whose peak passes the tensor network cap. A Clifford engine per slice is ruled out, since a sliced bond keeps every non-Clifford gateResearch
Automatic dispatch and Schmidt probes into the MPO mixed-state backend for noisy circuits past the density matrix capResearch

Input and interop

ItemStatus
Conversion from Python circuit frameworks, behind an optional dependencyPlanned
Checkpoint and resume across processes, which needs a state format firstResearch
OpenPulse input and Python bindings for pulse-level gate compilation. Closed-system unitary compilation, leakage rates, T1/T2 Lindblad channels and Pauli twirl rates ship behind the unstable-pulse feature (see Noise Models)Needs a use case

GPU on one device

ItemStatus
CUDA graph capture for repeated fused streams below 18 qubitsResearch

CPU reach

ItemStatus
AVX-512 on by default. The kernels ship behind PRISM_AVX512=1, verified under emulation and not yet timed on AVX-512 hardwareNeeds hardware
Tile sizes and the NEON two-qubit kernel measured on ARM64 and Apple silicon; both were tuned on x86-64Needs hardware
Cache-tile and thread floors measured on many-core AMD Zen hosts, and NUMA placement for 28 qubits and up on multi-socket machinesNeeds hardware

Beyond one device

ItemStatus
ROCm ports of the CUDA statevector and stabilizer kernelsNeeds hardware
Multi-GPU statevector sharded across peer-connected devices on one host. The design is written; the build waits on a host with peer accessNeeds hardware
Multi-node GPU execution, after multi-GPU on one hostResearch
Distributed runs validated across hosts; every test so far runs its ranks on one machineNeeds hardware
An out-of-core statevector that streams tiles past host memoryNeeds a use case

Hardware that would help

The thresholds and tile sizes in the source were tuned on an Intel i7-6700K with a GTX 1080 Ti and have not been derived again on the current development host, an Intel Core Ultra 7 270K Plus with a 16 GiB RTX 5070 Ti, which Performance describes. The Needs hardware items wait on one of these:

  • an x86-64 CPU with AVX-512
  • an Apple silicon Mac or another ARM64 machine
  • a many-core AMD Zen host, or a multi-socket server
  • an AMD GPU
  • two or more NVIDIA GPUs with peer access
  • two or more hosts joined by an MPI fabric

If you have one, say so in Discussions. scripts/tile_sweep.sh runs the cache-tile sweep the CPU items need from one bench binary.

Not planned

  • A command-line tool. PRISM-Q is a Rust library and a Python package.
  • Single-precision amplitudes. Every backend computes in f64 complex.- A C ABI, WASM bindings or QIR, until someone needs one. A discussion with the use case reopens it.