# Verifying and benchmarking cuqml How a change is verified, and how a speed is measured: when to run the checks, who runs them, how the result is judged and what is recorded. The verification commands are in A4; the benchmark commands are in `benchmarks/README.md`. What a change owes before it gets here is in [development.md](development.md). Part A is written to be handed, alone, to whoever verifies a change. ## Part A. Verification ### A1. When to run - After any change to code: `cuqml/`, `verify/`, the Dockerfile or the pinned versions. - Before a handoff that calls the change verified. - Always the whole set, not only the script written for the change (`CLAUDE.md`/`AGENTS.md` §7). The set is the 14 scripts of A4. `verify/qkan/cuqml_solver.py` needs an image of its own, so it is reported separately, as run or not run. A change to markdown alone needs no run. Check instead that its links resolve and that it retypes no number. ### A2. Who runs it Someone who did not write the change: a freshly started agent, or another person. **If you are the agent that wrote the change, do not run Part A yourself: spawn another agent to run it.** Give that agent this file and the commit to verify, and nothing else: not the conversation that produced the change, and not the author's reasoning. The code is then written in one context and verified in another, so the verifier cannot inherit the author's assumptions. If you are the agent that was spawned, you are the verifier: carry on from A3. The verifier changes nothing. It runs, judges and reports. ### A3. Setup - A CUDA GPU, and the versions `README.md` › *Install* lists. Results on other versions are reported as such. - A clean checkout of the commit under test: `git status` shows nothing modified. - `pip install -e .`, then `python -c "import cuqml"`. The first import builds the four plugins and installs them, with the two target files, into the CUDA-Q installation. Where that tree is not writable, as in the stock image, it uses password-free sudo, `sudo -n`. Where CUDA-Q came from a wheel that ships no NVQIR headers, as from 0.16 on, it fetches them once into `~/.cache/cuqml`, which needs network access. - In anything you write yourself, `import cuqml` before `import cudaq`. ### A4. The scripts Every script that checks a result checks it against CUDA-Q's own simulator — `parity.py` against an independent reference — never against a hand-written expectation, so a convention that changes underneath fails a script instead of quietly producing wrong numbers. `build_check.py` builds, and `measure.py` times. The Reference and Note columns of the table below say where a script departs from that. ```bash python verify/build_check.py # the kernels build and run here; the targets rebuild when stale python verify/gate_support.py # every gate, amplitude-for-amplitude vs qpp-cpu python verify/verify_api.py # sample / observe / get_state / run python verify/sampling.py # sample_batch vs cudaq.sample, exactly and statistically python verify/verify_backend_selection.py # the fp32 state-vector kernels ran, with zero fallback python verify/equivalence.py # observe and get_state vs CUDA-Q, row by row python verify/gradients.py # both diff_methods vs cudaq.gradients python verify/parity.py # each kernel vs an independent reference python verify/measure.py # forward-pass timings, medians and spread python verify/large_batch.py # a batch past the launch limit, as a small one python verify/arguments.py # arguments and captures, as cudaq.observe takes them python verify/angles.py # computed angles vs the ones CUDA-Q computes python verify/fp64.py # the fp64 target, every surface vs qpp-cpu and nvidia python verify/tensornet.py # cuqml-tensornet's expectations, gradients, shots vs CUDA-Q ``` Run `build_check.py` first: it fails fast on a broken toolchain. The rest run in any order. | Script | What it checks | Reference | Bar | Note | |---|---|---|---|---| | `build_check.py` | The kernels build, and one runs. The targets, each import in a process of its own: current, `import cuqml` builds nothing, and what its check costs is timed; stale, it rebuilds them, replacing all six installed files, its line saying it is done ending "with sudo" exactly where this user cannot write the tree, and a new process selects all four builds; a target file replaced by a copy of itself, the stamp untouched, it rebuilds them, giving that file as the reason; with the check holding the tree's lock, it says it is waiting, and once the lock is released builds once, or nothing where the targets were made current while it waited; with `cudaq` imported first, it rebuilds them and refuses the import, naming the order, and refuses every later import of `cuqml` or `cuqml._bridge` in that process, and where that build fails, the next import in that process after a new process has rebuilt them; in a tree this user cannot write, with a `sudo` that refuses, it refuses naming the tree | A fixed value: `` is 1 on the all-zero state; for the targets, the stamp the build writes and the simulators `cudaq.set_target` loads | 1e-6, in the script | A build check, not a check of results. The verdict says how many of the eight target checks were judged. The last is not judged where this user can write the tree, as root can; any other not judged fails the run. Each target check leaves the targets current | | `gate_support.py` | Gate constructs on `cuqml`, amplitude for amplitude; controls in any order; a custom operation under a built-in gate's name; a non-unitary operation and a repeated control refused | `qpp-cpu` | `TOL`, 1e-4 | A construct the target refuses is printed as unsupported and does not fail the run, except on the control-order rows and the eleven custom-operation name kernels, which are not rows of the table; five of those run in a process of their own. Two measurement rows are only run, not compared | | `verify_api.py` | `cudaq.get_state`, `observe` and the state accessors; `cudaq.sample` and `run`; a kernel let go leaves nothing behind | `qpp-cpu` for the first three; fixed expectations for `sample` and `run` | `TOL`, 2e-4; 0.05 for `sample`, in the script | Runs on `cuqml` at fp32 only, except the last check, which goes over all four builds | | `sampling.py` | `sample_batch` against `cudaq.sample`: exactly where the outcome is certain, statistically elsewhere | `qpp-cpu` | `TOL`, 2e-4; statistical bars are CUDA-Q's own spread times `MARGIN`, 2.0; two checks use 0.05 | | | `verify_backend_selection.py` | That the cuqml kernels ran, and that no dispatcher reached no kernel | A count of calls, no reference | none | Covers the fp32 state-vector build only, one of the four | | `equivalence.py` | `observe_batch`, `get_state_batch` and `TorchLayer` against `cudaq.observe` and `cudaq.get_state`, row by row; refusals; a measurement whose outcome is certain, and one whose outcome is rare, at fp32 over 2**25 and 2**23 rows, seeded; the random states of kernels that measure, at fp32 and fp64, each row one of the states `cudaq.get_state` returns and as often; a measurement in a called kernel that never runs, answered by every call as CUDA-Q answers it | `qpp-cpu`; 300,000 seeded calls of `cudaq.get_state` for the rare outcome, and 10,000 a kernel for the random states | `TOL`, 2e-4; `TOL_FP64`, 1e-10, for a random state at fp64; a collapse's frequencies by a chi-squared test of homogeneity, failing below `P_FAIL`, 1e-4 | | | `gradients.py` | Both `diff_method`s: value, independence of rows, convergence; refusals | `cudaq.gradients` on `qpp-cpu`: `CentralDifference`, and `ParameterShift` where it is valid; `cuqml-tensornet`'s reverse mode beside them for rotations under controls | `TOL`, 2e-3 | The loosest bar of the set | | `parity.py` | The dense, controlled, diagonal, rotation, rotation-gradient and Pauli primitives | A plain torch contraction that shares no code with the kernel | `TOL`, 2e-5; 1e-5 relative for the gradient cases | The one script that takes no reference from CUDA-Q. The fused-layer, sweep and contraction kernels are not in it | | `measure.py` | Times the forward pass | none | none | A timing, not a check: it judges nothing | | `large_batch.py` | A batch past the launch limit, at the seams between slices | `qpp-cpu` | `TOL`, 1e-4 | | | `arguments.py` | Kernel arguments passed as `cudaq.observe` takes them; the Python variables a kernel captured, and its fixed arguments, each changed between calls of one kernel object; a measurement a fixed or a captured value switches off; a list read outside the length the call hands it, refused by name | `qpp-cpu`; `nvidia` as well for a measurement switched off; for a register started from a fixed list, `cudaq.observe`'s refusal on the target itself; for a list read outside its length, which has no answer in CUDA-Q, `cudaq.observe` on `qpp-cpu` taking the call | `TOL`, 1e-4 | Two of the captured-variable checks read the engine's program store by count and identity, and one of those replaces the engine's `_bound` for five rows. Three of the fixed-argument checks read the store by count, identity or the type of its keys, and one of those calls the engine's `_program` with no value for a fixed argument; one counts the engine's readings of what a kernel writes | | `angles.py` | Angles a kernel computes, through loops of 50 to 1,500 turns; angles it rounds to single precision; kernels whose circuit follows an argument's value; a called kernel undone by `cudaq.adjoint`; kernels CUDA-Q hands a simulator in other gates than they write, answered or refused by name at every build | `qpp-cpu`; CUDA-Q's `tensornet` for one 60-qubit check | `TOL`, 1e-4; 1e-10 at fp64 in twenty-two checks of rotations that arrive as one, as written or not at all, and in four of angles rounded to single precision; in five of the twenty-six the angles built equal to the ones CUDA-Q hands over | Seven checks script capture's probe generator, each with a row that says the scripted draw took place; one scripts the IR's reading, and three count the engine's reads of the IR on first calls | | `fp64.py` | The fp64 state-vector target, every surface | `qpp-cpu`, and `nvidia` at fp64 for the wide state | `TOL`, 1e-10 | | | `tensornet.py` | `cuqml-tensornet` at both precisions: values, gradients, shots, amplitudes, refusals; a custom operation by its matrix (registered again, beside its adjoint, in a called kernel, under a built-in gate's name on both targets); the networks a session builds, by count | `qpp-cpu`; CUDA-Q's `tensornet` at width; cuqml's own state-vector adjoint for gradients where both fit; `torch.einsum` for the contraction kernels alone | `BAR`, 1e-5 at fp32 and 1e-10 at fp64 | | Each named bar is a constant at the top of its script; the script is where it is defined, and this table only names it. Some checks carry a literal of their own inside the check. Two things sit beside the set and do not replace it. `verify/qkan/cuqml_solver.py` checks QKAN's layers on cuqml against CUDA-Q; QKAN is not a dependency of this repo, so it runs in the image `verify/qkan/Dockerfile` builds. `docs/src/sample.py` is the one run behind the generated page. ### A5. What counts as a pass - Every script ends with exit status 0. - None was skipped, and none was stopped early. - No bar was edited, and no check was removed or switched off. - `git status` is still clean afterwards. A pass establishes what the scripts examine and no more. The Note column says where a script examines less than its name suggests. ### A6. The report One row in the *Verification runs* table of [status.md](status.md): - the commit, by its full hash; - the date; - the machine: GPU, CUDA-Q version, torch version; - which scripts ran; - the result: pass, or the script that failed with its last lines; - what was not run, and why. "Not verified" is a valid report. A pass that was not observed is not. ### A7. When something fails Say which of four things it is, because each is handled differently: | The failure is in | Signs | What happens | |---|---|---| | The environment | The build fails; memory is taken by another process; versions differ from the pinned ones | Fix the environment and run again. Say so in the report | | The check | The check asserts something CUDA-Q does not do, or cannot tell right from wrong | Report it. The check is fixed in place with the reason beside it ([development.md](development.md) §3), as a change of its own | | The implementation | cuqml disagrees with CUDA-Q on the same input | Report it to the author. The verifier does not fix it | | The specification | It is unclear what the right answer is, or CUDA-Q itself looks wrong | Stop and ask the human (`CLAUDE.md`/`AGENTS.md` §10). Where CUDA-Q itself is wrong, §5, *When CUDA-Q cannot be the reference*, says what replaces it | A bar is never loosened and a check never removed to turn a failure into a pass. ### A8. Cleanup A run leaves nothing that git tracks: `git status` stays clean. In the tree it leaves files git ignores: `cuqml.egg-info/` and `__pycache__/`. Outside the tree it leaves: - the four plugins, two target files and the build's stamp in the CUDA-Q installation, which the next build replaces; there is no uninstall step; - the editable install of `cuqml`; - the kernels' compiled extension in torch's extension cache, and under `~/.cache/cuqml` up to two symlinks and, where CUDA-Q came from a wheel, the NVQIR headers fetched for it. Release the GPU when you are done. ### A9. Writing a new check - **Compare with CUDA-Q's own answer for the same input:** the call that means the same thing (`CLAUDE.md`/`AGENTS.md` §5), at the same precision or, as the fp32 scripts do, against a more precise reference with the bar at fp32's floor. Never a value written by hand. - **Take the reference in the same run,** and see first that it can tell right from wrong: a basis state that reads the same backwards cannot catch a reversed bit order. - **Use the script's bar.** A new bar needs its reason beside it. - **Check the refusal as well as the answer:** what cannot be honoured is refused by name. - **Cover the edges:** each target and precision the feature exists on, a batch of one, and the seam wherever work is done in slices. - **Exit non-zero on failure,** and print what was compared and by how much. - **Say in the commit message which checks fail without the change.** - **List the script,** with its command and its row, in A4. ## Part B. Benchmarks ### B1. When a benchmark is needed - A claim about speed is being made. - The engine changed in a way that could move published numbers. Until they are measured again, the published tables describe the earlier code: say so in [status.md](status.md). ### B2. The method `benchmarks/_bench.py` implements the timing, the bar, the `MISMATCH` cell and the output; `benchmarks/README.md` › *Reading the numbers* states the rest. Every sweep follows it unless B3 says otherwise. - **Results before timings.** A sweep computes both sides' values and prints `MISMATCH` in place of a speedup when they disagree by more than its bar. - **The baseline is CUDA-Q's own:** `nvidia` or `tensornet`, or cuTensorNet, the library CUDA-Q ships. Both sides run at the same precision, selected the same way. - **Five trials, each after three warm-up calls.** The median is reported, with the ratio of slowest to fastest of cuqml's trials beside it as `spread`. The GPU is synchronised around the timed region. - **CUDA-Q has no batch axis,** so above one row its time is one row's, multiplied by the batch. - **In the two tensor-network sweeps, a call slower than two seconds is timed once,** after a first call. - **A cell that does not fit is refused before it runs** and printed as `>VRAM`. - **A quiet GPU.** Whoever runs a sweep starts it once the GPU has held no other process for five minutes, and keeps the run only if none appeared. No script checks this. - **One run makes the table, the CSV file and the figure.** - **Losing cells stay in the table** (`CLAUDE.md`/`AGENTS.md` §5). ### B3. The sweeps | Sweep | Measures | Baseline | Bar | Precisions | Departs from B2 | |---|---|---|---|---|---| | `qsvm_sweep.py` | `get_state_batch` over a batch of data | `nvidia` | Its own: 2e-4 at fp32, 1e-10 at fp64 | fp32, fp64 | A looser fp32 bar than the shared one | | `vqa_sweep.py` | The gradient at one parameter vector | `nvidia`, parameter shift | Shared: 1e-4 at fp32, 1e-10 at fp64 | fp32, fp64 | | | `qml_sweep.py` | The gradient over a batch | `nvidia`, parameter shift per row | Shared | fp32, fp64 | | | `hybrid_sweep.py` | `TorchLayer` inside `nn.Sequential` | The same layer written by hand on `nvidia`; PennyLane where it is installed | Shared | fp32, fp64 | PennyLane is optional and not a dependency | | `kernel_form_sweep.py` | Kernels as CUDA-Q writes them, beside a rewrite | `nvidia`, central difference | Its own: 1e-4, relative to the largest magnitude compared | fp32 only | No `--precision` option and no figure; its reference gradient is taken at fp64 | | `tensornet_sweep.py` | `cuqml-tensornet`: values, gradients, and shots with `--shots` | CUDA-Q's `tensornet` | Its own: 1e-5 at fp32, 1e-10 at fp64, scaled by the observable's coefficients; shots judged by `P_BAR`, 1e-3 | fp32, fp64 | First and second calls, and `tensornet`'s gradient, are timed once | | `cutensornet_sweep.py` | The same networks on cuTensorNet itself | cuTensorNet, checked against `tensornet` | `tensornet_sweep.py`'s | fp32, fp64 | cuqml's first call is timed once | One departure is common to all seven: no sweep writes the commit, the library versions or the date into its output. `_bench.header()` prints the GPU, the trial count, the precision and the two targets. ### B4. How numbers reach the READMEs - A published table is the CSV file of one run, and a figure is the one that run drew (`--csv`, `--png`). No number is retyped (`CLAUDE.md`/`AGENTS.md` §5). - Record the machine and the date with them, in `benchmarks/README.md` › *Reading the numbers*. Record the commit that was measured in [status.md](status.md), not in a README: the sweeps do not print it, so take it yourself with `git rev-parse HEAD` before the run. - Update the tables and the *Summary* section of `benchmarks/README.md` in the same change. - Quote a number with its cell: its width, its batch and its sweep. ### B5. Adding a sweep - Build it from `_bench.py`: its options, its timing, its `MISMATCH` cell, its table and figure output. - Compare results as well as timings, with the shared bar unless a reason is written beside another. - Measure generic scenarios, not the one configuration a change was tuned on (`CLAUDE.md`/`AGENTS.md` §5). - Keep the scenario's name in `benchmarks/`: no workload name enters `cuqml/` (`CLAUDE.md`/`AGENTS.md` §4). - Add its commands and tables to `benchmarks/README.md`, and its row to B3.