Simulation Acceleration Architecture¶
This document defines the target compute architecture for accelerating CASCAQit local simulation across Windows, macOS, and Linux. It is a design, not a statement of current GPU support. The current LocalBackend executes scalable workloads on CPU; SimulationOptions(device="gpu") still fails capability preflight.
Goals And Boundaries¶
The architecture must:
- keep
LocalBackend.run()andSimulationOptionsas the common user path; - preserve program semantics, logical ordering, penalty terms, result provenance, and numerical accuracy while changing compute providers;
- use vectorization, CPU cores, and GPUs where the workload has independent work;
- select a provider before execution from measured capabilities, memory, precision, and transfer cost;
- keep fixed-seed behavior reproducible within an execution profile and numerically comparable across providers;
- report the selected device, kernel, parallelism owner, precision, timing, and fallback decision.
The first delivery does not include distributed simulation, cluster scheduling, or a silent precision downgrade. Matrix Product State (MPS) and other approximate representations remain separate simulation methods with explicit truncation evidence; they are not GPU fallbacks for exact state-vector execution.
Current Baseline¶
SimulationPlanner currently considers program semantics, state representation, CPU count, host memory, worker count, and solver settings. It can plan CPU state-vector, blockade-subspace, density-matrix, and trajectory execution. Parameter sweeps and trajectories already have bounded worker ownership.
The missing pieces are device capability discovery, GPU kernels, physical-core and heterogeneous-core planning, native thread budgeting, and a lightweight objective-evaluation path. In particular, a complete Problem result currently materializes and validates rich candidate objects for the full probability distribution. A 16-variable exact distribution contains 65,536 states; repeating that work at every COBYLA evaluation can dominate the Hybrid state evolution itself.
Immediate Priority: Windows Finance Workbench¶
The first implementation target is the Windows offline finance application, before general GPU work or broad kernel refactoring. Its transaction-settlement workload has exposed a user-visible delay that prevents reliable rehearsal and customer use.
The acceptance workload is frozen as follows:
| Item | Value |
|---|---|
| Host | Windows 10/11 x64, Intel Core Ultra 5 225H, 32 GiB RAM, local SSD |
| Delivery | relocatable CPython 3.11 offline bundle, no network access |
| Scenario | transaction settlement, recommended Hybrid D-A-D route |
| Problem | 16 canonical binary variables and the unchanged settlement constraints |
| Optimization | COBYLA, evaluation budget 12, one start, one run |
| Simulation | complex128, fixed-step Krylov, 8 Analog time slices |
| Sampling | 32 shots with the released deterministic seed |
The current field observation is approximately 37 seconds on Apple M4 and several minutes on the Windows host, with about 6.5% aggregate CPU and 170 MiB process memory. These numbers identify a serial CPU path and low memory pressure; the implementation phase must replace them with repeated, versioned measurements before making a release claim.
P0 does not permit any apparent speedup obtained by changing the workload. The implementation must not reduce the COBYLA budget, replace continuous search with preset points, reduce time slices or state space, switch to complex64, omit penalty terms, truncate the probability distribution, use a classical candidate, or reuse a result from another input. The same request must produce the same public result semantics and evidence.
Until this P0 gate passes, GPU providers, MPS, distributed execution, and unrelated simulator refactors do not take implementation priority. Contract design may continue only where it is required by the P0 path and does not delay the Windows fix.
Target Flow¶
Program / Compiled Problem
|
v
semantic validation
|
v
WorkloadAnalyzer ------------------------------+
state size, operations, batch shape, |
accuracy, output and evidence requirements |
| |
v v
ComputeResourceSnapshotIR KernelCapability registry
OS, CPU topology, SIMD, memory, CPU / CUDA / ROCm / Metal / SYCL
GPU devices, runtime and drivers |
| |
+------------------+------------------+
v
ComputeExecutionPlanner
device + kernel + memory + transfer
+ parallelism ownership
|
v
PreparedExecutionContext
immutable caches + resident state + RNG plan
|
v
Digital / Analog / Hybrid / Noise kernels
|
v
lightweight objective aggregation
|
v
final decode + ResultIR + execution evidence
The semantic layer never imports a vendor runtime. Compute providers implement internal kernel protocols and consume the same validated program, state ordering, controls, noise model, and result contract.
Planning Contracts¶
The implementation should add four internal, serializable records:
| Record | Required facts |
|---|---|
ComputeResourceSnapshotIR |
OS and architecture, logical and physical CPU topology, SIMD features, available host memory, GPU provider/device/memory, driver and runtime versions |
KernelCapabilityIR |
supported methods, integrators, dtypes, operations, maximum rank, deterministic modes, batching, and device-memory requirements |
ComputeExecutionPlanIR |
selected provider, device, kernel variants, state representation, dtype, cache keys, transfer plan, memory budget, and selection reasons |
ParallelismPlanIR |
concurrency owner, process count, native threads per process, trajectory or batch chunk size, GPU streams, and peak-memory estimate |
SimulationExecutionConfigIR must evolve from CPU-only evidence to the executed provider and device. Schema migration must preserve old CPU records. An explicit device="gpu" request fails before Job creation when no provider satisfies the requested method, integrator, dtype, or memory. device="auto" may choose CPU, but records why.
Kernel And Cache Boundaries¶
The kernel registry separates numerical operations from orchestration. Initial kernel families are:
- local one-, two-, and three-qubit gate actions;
- diagonal phase and Problem energy actions;
- Analog Hamiltonian matrix-vector and matrix-matrix actions;
- fixed-step exponential action and adaptive right-hand-side evaluation;
- density-matrix local unitary and channel actions;
- batched trajectory evolution;
- probability, observable, and sampling reductions.
Prepared immutable data is cached by semantic hashes rather than Python object identity:
- Problem energy vectors, constraint contribution vectors, and feasibility masks;
- Digital axis permutations, fused gate groups, and diagonal phase data;
- Analog occupation masks, flip indexes, interaction diagonals, control boundaries, and blockade bases;
- device copies scoped to one Job or bounded by a byte-aware cache.
Cache keys include the semantic input digest, logical order, representation, dtype, provider, and kernel version. A bound control or coefficient that changes numerical behavior must change the key. Global caches have a memory limit and expose hits, misses, evictions, and preparation time.
Problem Objective Fast Path¶
Variational optimization needs a scalar objective and compact evidence for every parameter point, not a complete public result object. The execution path should therefore separate:
Objective evaluation
simulate exact state
-> probability vector
-> vectorized expectation and constraint reductions
-> lightweight ObjectiveEvaluationIR
Final selected execution
sample final state
-> decode observed and required ranked candidates
-> build complete ProblemExecutionResult
For QUBO and Ising inputs, the compiler prepares a float64 energy vector in canonical logical order. Expected objective becomes a vector reduction over the complete probability distribution. Business-objective and penalty vectors use the same ordering, so the coefficient ledger and the invariant
remain auditable without constructing one Python object per basis state.
The complete distribution is still consumed. Candidate materialization becomes lazy, not approximate: selection runs over vector indexes with stable bitstring tie-breaking, and rich candidate objects are created only for the final result fields that require them. A small scalar reference implementation remains available for numerical tests.
Windows P0 Implementation Slice¶
The Windows fix is a bounded change inside the existing CPU provider:
- Add stage timers around analysis, compile, state evolution, probability construction, objective reduction, penalty reduction, candidate decoding, final sampling, report generation, and API serialization.
- Compile one immutable
ProblemObjectivePlanper canonical Problem. It owns canonical basis indexing plusfloat64total, business-objective, per-constraint penalty, and feasibility vectors. - Add an internal lightweight evaluation result for optimizer callbacks. It retains objective, required metrics, parameter binding, Backend evidence, and stable identifiers, but does not build the full ranked candidate tuple.
- Reuse the objective plan for all 12 COBYLA evaluations. Each evaluation performs array reductions over the complete probability vector and returns only the optimizer facts.
- Materialize the complete public
ProblemExecutionResultonce for the selected/final execution. Candidate order, best-candidate selection, energy breakdown, counts, hashes, and report inputs remain compatible with the current contract. - Build the finance wheel and Windows offline bundle from the optimized SDK, then run the frozen workload from a clean installation rather than a source checkout.
The energy plan is bounded by the execution or a byte-limited cache. For 16 variables, one float64 vector contains 65,536 entries and occupies 512 KiB; business, penalty, feasibility, and workspace allocations must still be included in resource planning. Cache reuse is valid only when the canonical Problem digest, logical order, coefficient/penalty facts, dtype, and evaluator version match.
This slice is intentionally vectorization-first. One COBYLA start is sequential, so process-level parallelism cannot accelerate its dependent evaluation chain. Native array kernels may use SIMD or a numerical-library thread budget, but high aggregate CPU utilization is not a correctness or release requirement. The release decision is based on end-to-end latency and unchanged results.
Parallelism Model¶
Only one layer owns a CPU core or GPU stream at a time. The planner allocates a hierarchical budget:
- independent Jobs;
- parameter-scan points, optimizer starts, layer experiments, or repeated runs;
- trajectory batches;
- native CPU threads or GPU streams inside one kernel.
Nested pools are disabled. For example, four process workers each receive one native thread unless a measured kernel benefits more from one process with four native threads. The plan sets or scopes BLAS/OpenMP thread counts so OpenBLAS, MKL, Accelerate, and provider runtimes do not oversubscribe the host.
COBYLA and other adaptive optimizers keep one start serial because point depends on earlier evaluations. Multiple starts and repeats can run concurrently. Grid searches, explicit parameter sets, finite-difference groups, and independent trajectories can be chunked and scheduled in parallel.
CPU process execution uses spawn-safe immutable plans. Windows must not depend on fork; macOS also uses spawn-safe behavior, and Linux must not fork after a GPU runtime is initialized. Large read-only CPU arrays may use shared memory when its lifecycle and cleanup are explicit.
Workload Strategy¶
| Workload | Primary acceleration |
|---|---|
| Problem expectation and penalties | cached energy/contribution vectors, chunked bit operations, NumPy reductions |
| Digital state vector | SIMD-friendly contiguous tensors, fused local gates, specialized diagonal QAOA phases, batched independent points |
| Ideal Analog | cached matrix-free structures, blockade subspace where valid, batched Hamiltonian actions, CPU or GPU exponential action |
| Hybrid D-A-D | one resident state across all blocks, provider-compatible Digital and Analog kernels, no block-boundary host transfer |
| Exact density matrix | local tensor actions, strict memory gate, GPU only when complex precision and workspace fit |
| Quantum trajectories | process- or device-batched trajectories, counter-based seeds, bounded chunks, deterministic reduction order |
| Sampling and observables | vectorized reductions; transfer only summaries or required final arrays |
The planner uses estimated wall time as well as memory. State dimension alone is insufficient: gate count, Analog time slices, control boundaries, batch size, trajectories, expected objective reductions, and host-device transfer bytes all affect the crossover point.
GPU Providers¶
The base installation keeps the CPU reference provider. GPU support is optional and provider-specific:
| Platform | Candidate provider | Delivery rule |
|---|---|---|
| NVIDIA on Windows/Linux | CUDA | first exact GPU target after conformance and packaging gates |
| AMD on Linux | ROCm | enabled only for kernels and dtypes that pass the same conformance suite |
| Apple Silicon | Metal | selected only when required complex operations and requested precision are supported |
| Intel/other GPUs | SYCL or another explicit provider | separate optional adapter; no assumption that generic graphics APIs support the numerical contract |
A GPU Job prepares data once, keeps the quantum state resident through Digital and Analog blocks, performs objective reductions on-device, and copies back only required results. A provider that cannot execute every quantum block in a Hybrid state lifecycle is ineligible; the planner must not alternate CPU and GPU at block boundaries merely to claim acceleration.
Automatic selection includes allocation and transfer cost. Small workloads remain on CPU. Before numerical execution starts, auto may reject a GPU candidate after an allocation probe and select CPU with a recorded diagnostic. After state evolution starts, an out-of-memory or provider failure terminates the Job; it does not silently restart on CPU.
Cross-Platform Runtime Policy¶
| Host | CPU policy | Process policy | GPU boundary |
|---|---|---|---|
| Windows x64 | detect P/E topology where available; account for OpenBLAS or optional native libraries; avoid relying on base clock | spawn, explicit worker entrypoint, bounded shared memory, packaged DLL audit | CUDA first; other providers require their own wheel and driver checks |
| macOS arm64 | use Accelerate-compatible CPU kernels and SIMD; let the OS schedule heterogeneous cores unless affinity is proven beneficial | spawn-safe plans; no fork assumptions | Metal remains capability-gated, especially for complex128 |
| Linux x86_64/arm64 | support OpenBLAS/MKL-compatible CPU kernels and container CPU/memory limits | spawn or forkserver selected before provider initialization | CUDA first, ROCm separately gated |
Core count is not treated as usable concurrency by itself. The resource snapshot distinguishes logical and physical capacity where available, records container or processor-group limits, and permits caller overrides for controlled benchmarks.
Precision And Reproducibility¶
Acceleration does not change requested precision. complex128 state evolution and float64 Problem energy remain the reference path. A provider that supports only complex64 cannot satisfy an explicit complex128 request. Any future mixed-precision path requires an explicit option and separate error evidence.
Reproducibility has three levels:
- semantic: compile hashes, logical ordering, parameters, penalties, and execution plans are stable across platforms;
- execution-profile: the same provider, kernel version, dtype, worker plan, and seed reproduce stochastic streams and stable reductions;
- cross-provider: CPU and GPU results satisfy workload-specific numerical tolerances, but their floating-point encodings need not be exactly equal.
Trajectory and sampling random numbers derive from the root seed and stable item indexes, not task completion order. Parallel reductions use a deterministic merge tree when reproducible mode is requested. Tie-breaking remains based on objective, then canonical bitstring order.
Evidence And Diagnostics¶
Every result records:
- OS, architecture, CPU topology, array library, BLAS/runtime, and available memory snapshot;
- GPU model, memory, provider, driver, runtime, and kernel versions when selected;
- selected representation, integrator, dtype, process/native-thread split, chunk size, and concurrency owner;
- planning, preparation, compile, transfer, kernel, objective reduction, final decode, sampling, and total wall time;
- estimated and observed peak host/device memory where measurable;
- cache usage, transferred bytes, solver work, fallback decisions, and numerical warnings.
Provider absence, unsupported dtype, insufficient memory, unavailable kernel, and estimated slowdown use distinct diagnostic codes. Performance evidence is part of execution provenance, not a user-interface estimate.
Delivery Order¶
- Windows finance P0. Deliver the objective fast path, stage timings, numerical regressions, finance integration, clean offline bundle, and Windows host acceptance. No later item can displace this work before the release gate passes.
- Portable CPU execution. Generalize the validated fast path, detect physical/logical topology, control native thread budgets, parallelize independent scans/starts/repeats/trajectories with spawn-safe processes, and validate Windows, macOS, and Linux packages.
- Kernel provider boundary. Freeze compute capability, plan, and evidence schemas; move current NumPy/SciPy kernels behind the registry without changing numerical behavior.
- CUDA exact execution. Implement state-vector, diagonal expectation, Digital gate, Analog action, sampling, and persistent Hybrid state on one device. Add GPU memory planning and packaging.
- Additional providers and methods. Admit ROCm, Metal, or SYCL only through the conformance suite. Plan MPS and other approximate engines as separate methods with explicit error contracts.
Acceptance Gates¶
Correctness gates:
- scalar reference and vectorized
float64QUBO/Ising expectations agree within1e-10on deterministic fixtures and randomized bounded problems; - business objective, each penalty contribution, total objective, selected candidate, feasibility, and stable tie-breaking remain unchanged;
- CPU kernel changes pass state fidelity, observable, norm, trace, Hermiticity, positivity, distribution, and fixed-seed tests appropriate to each method;
- GPU
complex128paths satisfy the same numerical tolerances as the CPU reference;complex64uses separately declared tolerances; - provider selection and failure behavior are covered on supported operating systems without network or hardware-service access.
Performance gates use frozen workloads and report median and tail time, not one informal run:
- the Windows offline package runs the frozen transaction-settlement workload ten times after one unreported warm-up; median button-to-result time is at most 45 seconds, every measured run is at most 60 seconds, and the median improves by at least 3x against the frozen pre-change package;
- the same Windows runs report 12 real COBYLA objective evaluations, one start, 32 shots,
complex128, 8 Analog time slices, the same selected candidate and counts for the fixed seed, and objective/penalty differences no greater than1e-10; - the objective-reduction microbenchmark improves by at least 5x on both the Apple M4 reference host and the Windows Core Ultra host; Apple M4 end-to-end time must not regress by more than 10%;
- independent CPU work up to four workers achieves at least 60% parallel efficiency without exceeding the planned memory budget;
device="auto"selects GPU only when the measured end-to-end estimate, including transfer and preparation, beats CPU by the configured margin;- no accepted acceleration increases estimated or measured numerical error beyond the declared policy.
Benchmark records freeze program hash, Problem hash, mode, method, integrator, dtype, parameter budget, starts, repeats, shots, seed, package versions, OS, processor, device, thread environment, timing boundaries, and warm-up policy. Results from different profiles are not compared as if they were the same workload.
The Windows release gate also requires a clean VERIFY.bat / INSTALL.bat / RUN.bat installation, offline dependency verification, one API smoke run, and browser confirmation that the returned business, Problem-mapping, quantum-experiment, and audit views use the optimized execution result. A source-tree benchmark or macOS-only result cannot approve the Windows package.