# How cuqml works
What happens between a CUDA-Q kernel and a gradient in a torch tensor.
Each section opens **in plain words**, for a reader who has never written GPU code, with a
schematic where one helps. The parts headed **Under the hood** are for readers who have, and
can be skipped. What each call takes and returns is in [api.md](api.md); which file holds what
is in [development.md](development.md#2-code-map).
## The path of one call
```mermaid
flowchart TD
U["Your code
a CUDA-Q kernel, torch tensors of shape
(batch, n) for its float arguments,
and one value for any other"]
C["1 · Capture, kept between calls
record the kernel's gates and
where each angle comes from"]
F["2 · Compile, kept between calls
fuse the gates into a short list
of GPU operations"]
R["3 · Run
one state per row: (batch, 2ⁿ) amplitudes;
each operation covers every row"]
M["4 · Measure
⟨H⟩ for every row: a (batch,) tensor"]
B["5 · Differentiate, on .backward()
one sweep back through the gates
fills params.grad: (batch, n_params)"]
U --> C --> F --> R --> M --> B
```
Steps 1 and 2 run the first time a kernel is seen, and their result is kept: a later call
starts at step 3, unless a fixed argument or a Python variable the kernel captured has
changed, and then they run again for the new values. `get_state_batch` hands back the state
after step 3 and still takes step 5; for a kernel that measures, it collapses each measured
qubit where the kernel measures it, between the operations of step 3, and takes no step 5.
`sample_batch` draws shots from that state and takes no gradient; `TorchLayer` is the same
path as an `nn.Module`. On `cuqml-tensornet`, steps 2 to 5 are done without ever holding a
state: see [The tensor network](#the-tensor-network).
CUDA-Q's own calls on these targets, such as `cudaq.observe` and `cudaq.sample`, come in
another way. CUDA-Q loads a plugin that buffers the kernel's gates and hands the whole queue to
the same engine, for one row and with no torch gradient: on `cuqml` the same compiler and GPU
kernels, on `cuqml-tensornet` the same network. On `cuqml` nothing is kept between such calls.
On `cuqml-tensornet` the session keeps the network of each gate list it has seen, up to 256,
found again by each gate's name, qubits and number of angles, and by a custom operation's
matrix.
Four words carry a precise meaning below:
| Word | Meaning here |
|---|---|
| **CUDA-Q kernel** | the Python function under `@cudaq.kernel`: your circuit |
| **GPU kernel** | a function compiled for the GPU. One *launch* runs it on thousands of threads at once, each on its own part of the data |
| **state** | the `2**n` complex numbers, the *amplitudes*, that describe `n` qubits |
| **row** | one entry of the batch: one set of argument values, with the state and the results computed for it |
## From a CUDA-Q kernel to a differentiable program
**In plain words.** CUDA-Q runs a kernel with numbers in its arguments, so a simulator is
handed gates with concrete angles: `ry(0.31)`, never `ry(theta[0])`. To take a gradient, cuqml
has to know which argument each angle came from. It finds out once per kernel, and again when a
fixed argument or a Python variable the kernel captured changes, in three moves:
1. **Read.** It reads the kernel's compiled form, CUDA-Q's IR, for what follows the
arguments' values: angles computed by arithmetic, and anything that would make the circuit
differ from row to row.
2. **Record.** It runs the kernel on two made-up vectors for the arguments a batch varies, the
*probes*, beside the fixed ones' values, and records the gates instead of simulating them.
This is **capture**. Some kernels are recorded at a third probe, or a fourth, as below. A
kernel handed to `get_state_batch` that measures is built a second time, at probes of its
own, and recorded at each of them under `cudaq.get_state` as well, which hands over each
measurement where it stands: that marks where the kernel collapses, and one that the
values of its fixed arguments or of what it captured switch off is not handed over. CUDA-Q's
check of whether a kernel measures reads that kernel alone, so the kernels it calls are read
for a measurement from their own IR, and where one holds one the kernel is recorded under
`cudaq.get_state` at both probes too, by the first call that reads whether it measures;
`sample_batch`, which defers every measurement, never does. It measures where a measurement
is recorded, and one that a captured value, a fixed argument, or an argument the calling
kernel passes the same for every row, switches off is none; one that follows a row is
refused, as any branch on an argument is.
3. **Match.** An angle equal to `probe[i]` in both recordings is argument `i`. One that is the
same in both is a constant. The rest is read from the IR: arithmetic, or written angles
lined up with the ones CUDA-Q handed over. In a kernel that calls another it is an argument
that `cudaq.adjoint` or a gate written `.adj` negated.
The result is a *program*: the gate list and, for each angle, where it comes from. It is kept,
so later calls skip all three moves while the kernel's fixed arguments and the Python
variables it captured hold the same values.
```
probe A = [0.31, 0.77] probe B = [0.88, 0.18]
kernel ry(theta[0], q[0]) rz(2.0 * theta[1], q[1]) rx(0.5, q[0])
recorded A ry(0.31) rz(1.54) rx(0.5)
recorded B ry(0.88) rz(0.36) rx(0.5)
| | |
probe[0] in both neither probe's value: the same in both
arithmetic, read from the IR
v v v
program angle = theta[0] angle = 2.0 * theta[1] angle = 0.5
```
**In detail.**
- **Capture is cheap.** The kernel is run as CUDA-Q would run it, with the bridge recording
the gate queue instead of simulating it: no state, no launch, no GPU work. A program is kept
for each kernel at each argument width, device, precision and target, and at each value of
its fixed arguments and captured variables; and, for `get_state_batch` of a kernel that
measures, a second one cut where `cudaq.get_state` collapses it.
- **Captured variables are read at every call, and fixed arguments checked.** CUDA-Q binds
the Python variables a kernel captured afresh each time it runs the kernel, so a batched call
of such a kernel asks CUDA-Q's resolver what it would bind now, through the kernels this one
calls as well. A fixed argument goes through CUDA-Q's own conversion, as `cudaq.observe`
would take it, before anything is captured; a tensor for one is refused. The same values
find the program again; other values mean another capture, and the last 32 programs set
aside that way are kept for a call that binds their values again.
- **Several arguments** are laid side by side into one block, a slice per `list[float]` and a
number per `float`. Past that boundary the engine sees one block. A fixed argument takes no
column: capture is handed its value where the kernel takes it, and the IR has it written in
where it is a `bool` or an `int`, and its length where it is a list. A list's elements, a
`cudaq.pauli_word` and a `complex` are not written in.
- **Why the IR is read as well.** Two probes are two points: they cannot tell an argument from
arithmetic that equals it at both, or a constant from arithmetic that holds still between
them. So the IR is read before capture, with the arguments' lengths, the numbers the kernel
captured from Python and the `bool`s and `int`s it is handed as fixed arguments written in,
and CUDA-Q's own passes folding and unrolling what they decide. Where an angle is to be
lifted, every loop CUDA-Q can count is unrolled, however long, and an angle carried round a
loop is followed however deep its arithmetic runs.
- **Where CUDA-Q hands over other gates than the kernel writes.** Two `rx`, `ry`, `rz` or `r1`
under the same controls that meet on a qubit arrive as one, in the later one's place, unless
the later angle is read from a list argument at its gate; they meet across gates they commute
with, and across two `h` or two `x` in a row, which do not arrive. A rotation at a constant
written in the kernel that is the identity does not arrive, nor do a rotation and its adjoint
at one angle standing last. An `exp_pauli` arrives as the gates it is made of. So where an
angle is read from the IR the two are lined up qubit by qubit. On each qubit a rotation acts
on, or a gate that takes an angle, what is handed over has to be what is written there, in
order, each operation with its name and its qubits, save that rotations of one gate that
stand together — nothing else written between them acts on the qubit or a control, a
measurement apart, which marks no place in what is handed over — arrive as one or more of
that gate's rotations in their place; anything else is refused. A qubit that holds neither is
not read: its gates are built as they are handed over. Each delivered angle is a run of them,
every one summed in, in float64 from the last written to the first, as CUDA-Q sums them, the
terms computed as the C library CUDA-Q's kernel calls computes them. At fp64 the sum has to
be the delivered angle to the last bit at both probes, and a run of two or more is refused
where a term goes through a function other than `+`, `-`, `*`, `/`, `sqrt`, a sign, a
magnitude, the larger or the smaller of two and a rounding to single precision: the program
computes it in torch, which differs from that library in the last bit at some rows, and the
sum would carry that bit into its rounding. At fp32, where the delivered angles are rounded to single precision, the sum has to
be the angle to one part in a million. Before any of this, a kernel is refused where the
rotations of one gate on one qubit hold a constant, or any number standing together, that
come to whole turns or to nothing — every row of a run of constants summed at once, each a
float64 vector sum, from the last to the first — or a rotation and its adjoint at one angle
with nothing but rotations of their gate between them: CUDA-Q drops those, or sums them in,
and the probes need not tell which. One way to cut the rotations into runs is the pairing.
Stretches of one gate's rotations with nothing but what commutes with them between them on
the qubit are cut together, since CUDA-Q may hand a rotation over across that: a term the
probes leave on either side of it is two ways, and one way that crosses it is a merge across
a gate. Two are refused, since two probes cannot say which it is; none is refused too:
CUDA-Q did something that is not followed, or an angle has no value at the probes. Under
`explicit_measurements` capture ends where CUDA-Q draws, so a kernel whose angles are read
from the IR, or as negated, is recorded twice more without the flag, to its end.
- **Where every angle reads as an argument or a constant.** Nothing is lined up, and the angles
are run as read. CUDA-Q can still have summed into an argument's rotation constants that come
to nothing, or a rotation and its adjoint: the angle it hands over is then the argument's
value to the last bit at both probes, and another number at other rows. It sums only
rotations of one gate on one qubit under the same controls — a line — so a line it hands over
one for one had nothing summed into it, and nothing is taken of what it merges across.
`_ir.dependence`, the IR walk every first call makes, says whether one rotation gate is
written both at an argument's angle and at a number — written in the kernel or captured, in a
kernel called with no argument's value (looked up in the IR CUDA-Q keeps, not reduced), at a
called kernel's argument that some call hands a number, or out of storage the kernel puts a
number in beside an argument's value — or plain and `.adj` at an argument's angle, a call
that undoes a kernel counting as `.adj`. Only then is what the kernel writes read
(`_ir.written`), on from what `_ir.dependence` reduced: each kernel it calls in place of the
call, on the qubits it is handed, undone or controlled as the call is; its scopes; a branch a
number decides; a loop CUDA-Q can count — its count compared with a bound and stepped by a
number, in its step or at the end of its body, whatever else it carries round from pass to pass —
as many times as it runs, its body read once for all its passes where nothing in it moves with
the count but the column of an argument it picks, that column a function of the count; an
`exp_pauli` as the rotations it is made of; and nothing lifted into torch. Qubits are numbered as
CUDA-Q numbers them, measured: the registers the kernel allocates at its top level first, in
order, where each has a size written in its IR, and any other qubit — one a kernel it calls
allocates, or one allocated in a loop or a branch — when CUDA-Q reaches it, after them. Only the
first are numbered here; where a top-level register is sized at run time, CUDA-Q numbers every
qubit as it reaches it, and only those before the first other one are. A `cudaq.control` call's
controls go on the rotations of the kernel it calls, and on an `exp_pauli`'s `rz` alone, as NVQIR
applies it. On each line that holds a rotation at an argument's angle, bare or negated, or one at
an angle not read beside one CUDA-Q handed over that reads as an argument, the rotations written
are counted against those CUDA-Q handed over. Fewer handed over is the sign that it summed or
dropped some, and the kernel is refused by name where the line holds constants that come to whole
turns or nothing — any row of them in order, whatever stands between, summed as CUDA-Q sums them
— a rotation and its adjoint, or a rotation at a number not read to the bit. Where the two are as
many, the count says nothing was summed only if the line read is CUDA-Q's; so each rotation
CUDA-Q handed over there must be the one written there, in order, at both probes — a constant to
the bit, or within `_SAME` (1e-12) where the C library computes it from numbers, an argument's
rotation at its value, one negated at minus it — or the kernel is refused for that, as read
otherwise than CUDA-Q runs it. That holds where the two differ: where the reading leaves out just
the constants CUDA-Q sums to nothing into an argument's rotation — as it can where it decides a
called kernel's branch, loop count or qubit by a parameter CUDA-Q folds at the call otherwise,
two booleans put in order or integer arithmetic past 64 bits — the two agree, and the kernel is
answered wrong (known-limits.md). A qubit with no number has its rotations counted, gate by gate,
against those CUDA-Q handed over on qubits numbered none here: fewer there is refused, since on
which qubit is not told, and as many is held in order the same way. A line that cannot be counted
— a loop CUDA-Q cannot count, a branch on what is not known before the kernel runs or on what is
not evaluated here, a call of what is no kernel — or where more are handed over than are read, is
refused for that. A value the kernel captured from Python is read as CUDA-Q binds it at the call:
a number, a Pauli word, a list's length and elements, a tuple's or a dataclass's numbers; a
branch on one is decided as CUDA-Q decides it, through the operations it emits — `%` as an
unsigned remainder, `//` as a floor division, `and` and `or` and a variable assigned on either
side as values a branch yields, a float's truth as IEEE's unordered `!=`, `int()` of a float and
`**` of integers where they land inside their type — and a number the kernel stores in a branch
not decided is not known after it. A loop that changes a value carried beside its count or steps
the count in its body, a float's truth, `int()`, `**` and a word from a list are read only where
the reading computes no number otherwise than CUDA-Q — two booleans put in order, which CUDA-Q
takes as signed one-bit integers, an integer past its type, which CUDA-Q wraps; where it computes
one, the kernel is read again without them, so that none of them is decided by it.
- **An angle undone by `cudaq.adjoint`.** The IR of a kernel that calls another does not hold
the called kernel's gates, so it has no arithmetic to read for them. Where neither kernel
computes an angle from an argument, an angle that is minus `probe[i]` in both recordings is
argument `i` negated. The kernel is then recorded at a third probe, where every angle has to
be what the first two made of it: an argument, one negated, or the constant. Anything else is
refused by name; and where `_ir.dependence` found a rotation that can meet an argument's to
nothing, the kernel is held as above, line by line, to what CUDA-Q handed over.
- **An angle that holds still.** Where a kernel computes no angle from its arguments and takes
more than one argument value, an angle that is the same in both recordings may be a constant,
or a sum CUDA-Q made of two arguments that happens to be one number at both probes. A kernel
with such an angle is recorded at a third probe, which tells the two apart.
- **One circuit for every row.** A `list[float]` or `float` value that reaches a branch
condition, a loop bound, a qubit index or a register's size would mean a circuit per row,
where a batch runs one. The kernel is refused, naming which it reached;
[api.md](api.md#kernel-arguments) says what to write instead. A fixed argument's value may
reach any of them: it is one value for the whole batch, and the circuit is captured at it.
- **A list is read inside its length.** CUDA-Q does not check an index: a kernel that reads
outside a list it is handed reads whatever lies in memory there, and so does capture, where
that is mostly a number that holds still between the probes and reads as a constant. So the
walk of the IR that refuses those also holds each element the kernel's own function reads
of a `list[float]` argument, a fixed list or a list it captured — of a list of lists, the
outer one — to its length at this call, where the read runs whenever the kernel does: at a
number, or, in a loop CUDA-Q leaves whole whose start, bound and step are numbers, at the
first and last values of the loop's count, where the index is that count times a number
plus a number. No loop is unrolled for it. A read outside the list is refused by name;
[known-limits.md](known-limits.md) lists the reads it does not judge.
- **Arithmetic becomes one torch function** of the argument block, run on the whole batch in
float64, as CUDA-Q runs a kernel's arithmetic, a level at a time: `rz(2.0 * gammas[l], q)`
at every gate of every layer is one multiply, not one per gate or per sample. Where the
kernel rounds to single precision — `np.float32` of a value compiles to a cast from f64 to
f32, and CUDA-Q then runs arithmetic on such values in single precision — the function
rounds too, at the same places: IEEE's single-precision `+`, `-`, `*`, `/` and `sqrt` are
the float64 result rounded once more, so these come out to the bit. A single-precision
`sinf` or `cosf` of the C library does not, nor does torch's float64 `sin` rounded always
meet the library's, so at fp64 a rounding of such a function is refused by name. Before
the function is trusted it must reproduce, at both probes, the angles the kernel actually
emitted, and what has no translation into torch (`np.ceil`, `%`) is refused by name.
The module docstrings of `cuqml/_torch.py` and `cuqml/_ir.py` give the full account.
## The batch: a tensor dimension, not a loop
**In plain words.** `n` qubits are described by `2**n` amplitudes, and a gate works across
all of them. A model evaluates the same circuit at many argument vectors, one per data sample.
Simulating them one after another pays every fixed cost once per sample. cuqml keeps all the
states in one block of shape `(batch, 2**n)` and applies each gate to the whole block at once:
the batch is one more dimension of the data, not a loop around the simulator.
```
amplitude index 0 1 2 ... 2**n - 1
row 0 (sample 0) [ a a a ... a ]
row 1 (sample 1) [ a a a ... a ] one launch applies
: a gate to every row,
row B - 1 (sample B - 1) [ a a a ... a ] each at its own angle
```
Launch overhead, parameter upload and allocator traffic are paid once for the batch rather
than once per sample. The backward pass carries the same dimension, so one sweep returns a
`(batch, n_params)` gradient with independent rows.
**Under the hood.**
- **Layout.** The block is two arrays, the real parts and the imaginary parts, each
`(batch, 2**n)`, rather than one array of interleaved complex numbers, so that a kernel
reads each with coalesced accesses.
- **Grid.** Every gate kernel carries the batch on the launch grid's `y` dimension and the
amplitudes on `x`, and each row reads its own angle. CUDA caps `gridDim.y` at 65,535, so a
larger batch is launched in slices of that many rows; `verify/large_batch.py` checks the
seams.
- **Memory bounds how many rows run at once; the kernels do not.** Nothing spills to host
memory. A batch whose states do not fit together runs in slices where the engine can slice
it, as for a gradient or for shots, and is refused by name where it cannot:
`get_state_batch` returns every row's state, and no call can run a row that does not fit
alone.
## The kernels
**In plain words.** A gate on one qubit touches the whole state: it pairs up the amplitudes
whose indices differ only in that qubit's bit, and mixes each pair with a 2×2 matrix. The
pairs do not depend on each other, which is what a GPU is built for: they are shared out
among thousands of threads that all run at the same time.
```
3 qubits, a gate on qubit 1 index bits are q2 q1 q0
index 000 001 010 011 100 101 110 111
pair 1 o-----------o 000 <-> 010
pair 2 o-----------o 001 <-> 011
pair 3 o-----------o 100 <-> 110
pair 4 o-----------o 101 <-> 111
target space the amplitudes one gate mixes together 2**K for a gate on K qubits
outer space the independent groups it repeats over 2**(n-K), shared out among threads
```
The time goes into moving amplitudes through memory, not into arithmetic. That leaves two
ways to be faster: make fewer passes over the state, and make each pass read less of it.
**Fewer passes: fusion.** Before anything runs, the compiler merges gates by their structure.
Nothing recognises a named ansatz.
| In the circuit | Becomes |
|---|---|
| Fixed single-qubit gates in a row | one layer; gates on the same qubit are multiplied into one 2×2 |
| Rotations on different qubits | one layer |
| A run of rotations on one wire | one operation; standing alone it is one pass, each pair staying in registers for up to 32 gates |
| CNOT, RZ, CNOT on a pair of qubits | one RZZ |
| A run of RZZ, or a run of CPHASE | one phase pass for up to 64 gates: diagonal gates commute, so their phases add |
| Consecutive CNOTs | layers of CNOTs that share no qubit; each CNOT is still a pass, over only the half of the state its control admits |
| H on every qubit at the start | skipped in the forward run: the state starts as the uniform superposition |
At fp32 a layer of single-qubit gates is applied in a few passes rather than one per gate: one
gate on each of 24 qubits takes 4 passes where gate by gate takes 24. At fp64 a layer is one
pass per gate.
**Less per pass: three primitives.** Each exists because folding it into another would cost
memory, not lines. The fused kernels above sit beside them: the same-wire run and the fp32
layers.
| Primitive | Applies | What it saves |
|---|---|---|
| A given matrix | a fixed gate or a custom unitary, on up to 4 qubits, or on 1 or 2 under up to 4 controls: H, CZ, SWAP, CNOT, CCX | under controls, only the groups the controls admit are read; the rest of the state is never touched |
| A rotation from its angle | RX, RY, RZ and a phase, each under up to 4 controls, at a different angle in every row; a controlled `u3` is three of them | the 2×2 is built in registers from each row's angle, so no matrix per row is stored or uploaded |
| A phase | a layer of RZZ or CPHASE | no mixing at all, so one pass adds up every gate's phase for each amplitude |
**Under the hood.**
- **Index spaces.** The matrix primitive takes the target and outer spaces drawn above from
CuTe layouts (`cuqml/cute/csrc/layout.cuh`), and the rotation primitive its outer space, a
control pinning its bit as a constant offset. One templated kernel then serves any qubit
positions and any register width.
A thread owns one outer group: it loads the group's amplitudes, applies the gate in
registers and writes them back.
- **Layers at fp32.** A low pass stages a block's 4,096 contiguous amplitudes in shared
memory and applies every gate on the low qubits there, with one write back. A high pass has
each thread hold in registers the `2**K` amplitudes that up to four high qubits connect, and
apply all of their gates before writing back. Neither has an fp64 build.
- **Sums.** No sum is added across blocks into one address, where an atomic add would change
the last digits from run to run: each block writes its own partial sum and the partials are
added in a fixed order, the gradient kernels' in double.
**The observable** is read the same way. Any Pauli string reduces to three integers — the bits
carrying X or Y, the bits carrying Y or Z, and the number of Ys mod 4 — from which `P|j>` is one
XOR and a phase factor. So `
` is a single pass over the state whatever the string's weight,
the adjoint it seeds is another, and terms sharing the first integer share a pass, eight at a
time in the forward, because they read the same amplitude pairs and differ only in register
arithmetic. An all-Z string is
that same kernel's `flip = 0` case, and the one exception is a lone X or Y in the forward
pass, kept only because a fused kernel measured 1.25-2x faster there.
**Tensor cores are deliberately unused.** Applying a K-qubit gate has an arithmetic intensity
of `0.5 * 2^K` FLOP per byte, far below this hardware's balance point, so state-vector
simulation is memory-bound however the arithmetic is done — MMA would raise a ceiling that is
not the limit. This is also why the benchmark speedups narrow as `n` grows: what cuqml
amortises is fixed per-execution overhead, and once the state is large enough that amplitude
traffic dominates, both backends converge on the same bandwidth limit.
## The gradient: one adjoint sweep, not `2 * n_params` circuits
**In plain words.** Training needs the derivative of the loss in every angle. If you have
reached for parameter shift, this is what replaces it. Parameter shift is exact, but it runs
the whole circuit twice per parameter, so a 160-parameter ansatz costs 320 simulations for one
gradient. **Adjoint differentiation** runs the circuit forward, then walks back through the
gates once, and picks up every parameter's derivative on the way: the cost follows the number
of gates, not the number of parameters. It is the same exact gradient.
```
forward |0...0> --G1(θ1)--> ψ1 --G2(θ2)--> ψ2 --G3(θ3)--> ψ3 -->