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

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.