API
Everything that can be called on the cuqml and cuqml-tensornet targets: what each call
takes, what it returns and what it refuses. How the engine does it is in
how-it-works.md; what it does not do at all is in
known-limits.md.
Two ways to call, and what each returns
Two families of calls run on these targets, and they return different kinds of things.
cuqml’s batched calls —
cuqml.observe_batch,cuqml.get_state_batch,cuqml.sample_batchandcuqml.TorchLayer— take torch tensors on the GPU for a kernel’slist[float]andfloatarguments, with a batch axis where you give one, and one plain value for an argument of another type, and return torch tensors on the GPU. Expectation values, states and amplitudes are differentiable:.backward()fills the gradient of the tensors that went in. Oncuqml-tensornet,get_state_batchreturns a state object in place of a tensor; the amplitudes it gives are tensors.CUDA-Q’s own calls —
cudaq.observe,cudaq.sample,cudaq.get_stateandcudaq.run, withcudaq.gradientsandcudaq.optimizers— take one set of arguments and return CUDA-Q’s own objects, as on any other CUDA-Q target. Selecting a cuqml target changes which simulator runs the kernel, not what a CUDA-Q call takes or returns. What these targets cannot run is refused, and listed below.
Quantity |
cuqml call |
It returns |
CUDA-Q call |
It returns |
|---|---|---|---|---|
Expectation value |
|
|
|
|
Gradient |
|
|
|
|
State |
|
on |
|
|
One amplitude |
|
|
|
|
Shots |
|
|
|
|
A layer of a model |
|
an |
none |
|
Optimiser |
|
torch’s own |
|
CUDA-Q’s own |
A return value per shot |
none |
|
a list, one value per shot |
The shapes are for arguments that carry a batch axis. Without one, the batch axis is absent from the result as well.
Targets and precision
|
Engine |
Precision |
Tensors you pass |
Amplitudes |
|---|---|---|---|---|
|
state vector |
fp32 |
|
|
|
state vector |
fp64 |
|
|
|
tensor network |
fp32 |
|
|
|
tensor network |
fp64 |
|
|
The target and its precision are read at every call, not when a kernel is first seen or a
layer is made. A batched call under any other target is refused with a RuntimeError.
Import order
Import cuqml before cudaq: CUDA-Q embeds LLVM and so does triton, which torch loads
lazily, with torch._dynamo — constructing an optimiser is enough, and so is
torch.compile or torch.use_deterministic_algorithms. Importing cuqml first loads it
while that is still safe; in the other order that import raises an ImportError saying
so, where it would abort the process. Importing cuqml first also builds the two targets,
where they are missing or stale, before CUDA-Q reads its targets, which it does once, at
import cudaq; with cudaq first, such a build still runs and the import raises an
ImportError, as does every later import of cuqml in that process, since that process
cannot use the targets. Nothing else about the order matters.
Precision
cuqml runs at the precision its target is set to, as the nvidia target does: fp32 by
default, fp64 with option="fp64". Each is that precision end to end — the state, the
kernels, and the amplitudes it publishes.
cudaq.set_target("cuqml") # fp32: complex64 amplitudes, float32 arguments
cudaq.set_target("cuqml", option="fp64") # fp64: complex128 amplitudes, float64 arguments
Measured against qpp-cpu on the same circuits, fp32 agrees to 1.1e-07 and fp64 to
1.2e-15 — values, amplitudes and gradients alike, in verify/fp64.py — and at 18 qubits
fp64 agrees with nvidia’s own fp64 to 1.1e-15.
At fp32, single precision is the storage type, not the arithmetic everywhere: gate matrices and captured constants are built exactly in double and rounded once, at the point of use, and every reduction sums its per-block partials in double. A circuit whose constants were themselves fp32 would cap the result below what the state can carry.
The torch surface takes arguments at the target’s precision — float32 at fp32, float64 at
fp64 — and refuses the other by name rather than widening or narrowing it, because numbers
computed at one precision under another’s label is the one outcome worse than refusing. A
TorchLayer’s weights start float32, as an nn.Linear’s do, and .double() moves the
layer to fp64 with the rest of the model.
Two fp32 kernels have no fp64 build: the large-n layer kernels, which apply a whole layer in a few passes over the state, and the fused backward sweep. At fp64 those circuits take the per-gate paths instead — the same results, in more passes over a state twice the size.
The tensor-network target
cudaq.set_target("cuqml-tensornet") runs the same calls — observe_batch, sample_batch,
TorchLayer, get_state_batch’s amplitudes, and cudaq.observe and cudaq.sample — by
exact tensor-network contraction, for circuits a state vector cannot hold: wide, and shallow
or of low treewidth, so that their contractions stay small. It sits beside cuqml as
CUDA-Q’s tensornet sits beside nvidia, and is chosen only by name, never inferred from a
qubit count. option="fp64" selects fp64; without it the precision is fp32, as on cuqml —
where CUDA-Q’s tensornet defaults to fp64, so a comparison names both sides’ precision.
What it adds to CUDA-Q’s tensornet is what cuqml adds to nvidia: a batch axis, and a
gradient in a torch tensor, by either diff_method — reverse mode as one backward pass
through the contractions, parameter shift as one contraction of the shifted rows.
tensornet contracts one ⟨H⟩ at one point well, but there a batch is a call per row, and a
gradient 2 * n_params more calls by parameter shift. For one ⟨H⟩ at one point it stays the
right tool, as it does for circuits whose contractions grow large;
benchmarks/README.md measures where each wins.
Exact contraction only — no MPS or other approximation — on one GPU, without noise. What it cannot do is refused by name:
No whole state. The state is
2**namplitudes, which is what this target exists to avoid.get_state_batchreturns one whose amplitudes are contracted when asked for, ascudaq.get_statedoes ontensornet, and refuses what needs them all;cudaq.get_stateitself, andTorchLayerwithout observables or amplitudes, are refused, pointing atcuqml.No collapse.
cudaq.sampledraws a kernel’s measurements as shots, which needs no state. A measurement that must collapse the state where it stands, ascudaq.runmakes, is refused, and so is areset.63 measured qubits in
sample_batch, which packs an outcome into one int64 as it does oncuqml.cudaq.samplereturns strings and reaches any width.What does not fit. Before a contraction runs, what it will hold at the call’s batch is checked against free GPU memory, and what cannot fit is refused, saying what it needed. It is not sliced to fit, as CUDA-Q’s
tensornetwould slice it.
Not built. Slicing; terms whose light cones overlap sharing work; a plan better than the greedy one; and shots drawn a block of qubits at a time. Each is a measurement for when a workload needs it.
What cuqml adds
what it adds |
API |
your CUDA-Q kernel |
|---|---|---|
a batch axis over data samples |
|
unchanged — its arguments are passed as |
gradients as a torch tensor |
|
unchanged — one adjoint sweep for the whole batch replaces |
measurement outcomes over a batch |
|
unchanged — one state per parameter row, every shot drawn from it, so a batch costs one execution — or as few as hold it — rather than |
a differentiable state vector, on the GPU |
|
unchanged — the autograd edge survives, so a classical layer consumes the amplitudes with no host round-trip |
CUDA-Q’s accessors, answering per row |
|
unchanged — a row is one experiment, so each answers once per row. Shapes and the three places they diverge from CUDA-Q are in Result accessors |
the kernel as an |
|
unchanged — the layer owns the weights and appends them to whatever it is handed, so a circuit drops into |
gate fusion by structure |
none — automatic |
unchanged — single-qubit gates on different qubits become one layer, a run of rotations on one wire one operation, a run of RZZ or of CPHASE one phase pass. Nothing recognises a named ansatz |
circuits too wide for a state vector |
|
unchanged — the same calls, by exact tensor-network contraction, for wide circuits whose contractions stay small. What differs is in The tensor-network target |
everything else, from CUDA-Q |
|
unchanged — on the |
fp32 or fp64, said out loud |
|
unchanged — but arguments or |
Kernel arguments
What a batched call takes for each argument of the kernel:
The kernel declares |
You pass |
Shapes |
|---|---|---|
|
a |
|
|
a number or a |
a number or |
|
one plain value, as |
a fixed argument: one value for every row, the circuit captured at it, with no gradient |
any other type: a NumPy scalar such as |
nothing |
refused, naming the argument: capture the value from Python instead |
The arguments go in the kernel’s own order, as
cudaq.observetakes them, and there are as many as the kernel declares.At least one
list[float]orfloatargument is a tensor. Every tensor is on one CUDA device and at one dtype, the target’s:float32at fp32,float64at fp64. No tensor is moved or cast for the caller, and no array or list is converted for alist[float]; a plain number given for afloattakes the tensors’ dtype and device. A fixed argument takes whatcudaq.observetakes for its type, converted as CUDA-Q converts it — astrfor acudaq.pauli_word, a NumPy array or a tuple for alist[int], annp.int64for anint— and no tensor.Arguments that carry a batch axis agree on its size.
A kernel called through observe_batch, get_state_batch or sample_batch takes any
number of list[float] and float arguments, and of fixed arguments, passed in its own order
the way cudaq.observe passes them — observe_batch(kernel, h, x, w) for
kernel(x: list[float], w: list[float]), observe_batch(kernel, h, 2, theta) for
kernel(layers: int, theta: list[float]); TorchLayer’s takes exactly one list[float],
beside fixed arguments given as args=, as below. An argument without a batch
axis is shared by every row, so weights sit beside per-sample data without being copied. An
angle may be computed from them — rz(2.0 * gamma, q), ry(np.sin(w[i]) * x[i], q) — and is
then run in torch over the whole batch, differentiable. An angle the kernel rounds to single
precision — np.float32 of a value, and arithmetic CUDA-Q then runs in single precision — is
rounded where CUDA-Q rounds it, at either precision, and its gradient passes the rounding as the
identity. At fp64, a rounding of a value computed through a function other than +, -, *,
/, sqrt, a sign, a magnitude, the larger or the smaller of two —
np.cos(np.float32(b)), np.float32(np.sin(b)) — raises: the C library CUDA-Q’s kernel
calls computes that function otherwise than torch, and the rounding would carry the
difference into a whole single-precision step. What has no translation, or no derivative to
take (np.ceil, %), raises naming the gate. So does a kernel whose circuit itself follows
the value of a list[float] or float argument — a branch on one, a loop one bounds, a qubit
one picks — naming which: a batch is one circuit for every row. A fixed argument may do each
of these, since its one value holds for the whole batch. See
From a CUDA-Q kernel to a differentiable program.
A loop beside a computed angle runs any number of turns, as long as CUDA-Q can count them when
it compiles the kernel: a for over a range or over an argument, or a while on an integer
counter, bounded by a number written in the kernel, an integer captured from Python, an int
argument or an argument’s length, a list argument’s included. An angle may be carried from one
turn to the next.
A kernel may call other kernels, and undo one with cudaq.adjoint, as long as no angle in it
or in them is computed from an argument. With a and b each a list[float], encode(q, a)
followed by cudaq.adjoint(encode, q, b) is the overlap circuit a fidelity or a quantum kernel
is written as, and its undone angles are read as the arguments negated, differentiable like any
other. With float arguments the rotations of the two meet, and the kernel is refused, as is
an exp_pauli at an argument’s angle beside a call. A kernel that computes an angle calls no
other kernel.
CUDA-Q does not always hand a simulator the gates a kernel writes. Rotations of one gate that
meet on a qubit arrive as one, at the sum of their angles, unless the later angle is an element
of a list[float] read at its gate; they meet across gates they commute with, and across two
h or two x in a row, which do not arrive; an exp_pauli arrives as the gates it is made of;
a rotation at a constant written in the kernel that is the identity does not arrive. Where an
angle of such a kernel has to be read from its IR, cuqml lines what the kernel writes up with
what it is handed, qubit by qubit, and the kernel is batched like any other. 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 one of its
controls — arrive as one or more of that gate’s rotations in their place. Each angle handed
over is then a run of them, every one summed in, in float64 from the last written to the
first: the sum CUDA-Q makes, which at fp64 has to be the angle it handed over, to the last bit,
at both probes. The kernel is refused by name where what is handed over on such a qubit is not
what is written there; where the rotations of one gate on one qubit hold what CUDA-Q may hand
over otherwise and the probes need not tell — constants that cancel or come to whole turns,
however many stand together, which CUDA-Q drops or sums in, or a rotation and its adjoint at
one angle with nothing but rotations of their gate between them; where the probes leave two
ways to cut the rotations into runs, a term on either side of a gate the rotations commute with
among them; where the one way crosses such a gate; and at fp64 where a run of two rotations or
more has a term computed through a function other than +, -, *, /, sqrt, a sign, a
magnitude, the larger or the smaller of two and a rounding to single precision, which torch
computes otherwise than the C library CUDA-Q’s kernel calls. A rotation and its adjoint with a gate between them that CUDA-Q hands
over as written, as in a change of basis, are answered one for one.
Where every angle of a kernel reads as an argument, an argument negated or a constant at
capture’s probes, nothing is lined up: 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, and
then the angle it hands over is the argument’s value to the last bit at the probes and another
number at other rows. It sums only rotations of one gate on one qubit under the same controls —
a line — so on each line that holds a rotation at an argument’s angle, bare or negated, cuqml
counts the rotations written there against those CUDA-Q hands over, and assumes nothing of what
it merges across. Where CUDA-Q hands over fewer, the kernel is refused by name if the line holds
constants that come to whole turns or to nothing — a row of any length, in order on the line
whatever stands between them, summed as CUDA-Q sums them — or a rotation and its adjoint at one
angle, or a rotation at a number it does not read to the bit, such as one a called kernel
returns or the sine of a number, which the C library computes; else it is answered, since what CUDA-Q summed there leaves no argument’s value standing
for another number. Where the two are as many, nothing was summed into one — so long as the line
read is CUDA-Q’s. That rests on three things: qubits 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 it, and any other qubit, one a kernel it calls allocates or one allocated in a loop or
a branch, when CUDA-Q reaches it; a called kernel’s rotations under the controls cudaq.control
puts on the call; and an exp_pauli as NVQIR makes it, the call’s controls on its rz alone.
So on a line where the two are as many, each rotation CUDA-Q handed over has to be the one
written there, in order, at both probes — a constant to the bit, or within 1e-12 where the C
library computes it from numbers, a rotation at an argument’s angle at that argument’s value, one
negated at minus it — and a line read otherwise than CUDA-Q runs it is refused by name wherever
what CUDA-Q handed over there is not what the kernel writes there. Where the reading leaves out
just the constants CUDA-Q sums to nothing into an argument’s rotation, the two agree: a called
kernel’s branch, loop count or qubit decided by an int or bool parameter that CUDA-Q folds at
the call otherwise than cuqml reads it — two booleans put in order, integer arithmetic past 64 bits
— is answered wrong so, as known-limits.md says. A qubit cuqml gives no number —
one a called kernel, a loop or a branch allocates, or one the kernel allocates at its top level
after such a qubit beside a register sized at run time, where CUDA-Q numbers each as it reaches it
— has its rotations counted with the others of its gate on such qubits, against those CUDA-Q hands
over on qubits cuqml numbers none of: where CUDA-Q hands over fewer there, on which qubit it summed
is not told, and the kernel is refused by name; where as many, each is held to the one written, in
order, the same way. A line is held where it has a rotation at an argument’s angle, or one at an
angle not read beside one CUDA-Q handed over there that reads as an argument at the probes. What is
written is read through the kernels it calls, on the qubits each is handed, undone by
cudaq.adjoint or controlled by cudaq.control; its scopes; a branch CUDA-Q decides before the
kernel runs — on a value it captured, through % (an unsigned remainder to CUDA-Q), //, and,
or, a variable assigned on either side, a float’s truth, int() of a float and ** of integers
where they land inside their type — and the values such a branch yields; a loop CUDA-Q counts — a
for, or a while that steps its count at the end of its body, whatever else it carries round —
as many times as it runs; a number stored and read back; and the rotations an exp_pauli is made
of, by a word written, captured or taken from a captured list — values captured from Python, and
fixed arguments, as CUDA-Q binds them. 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 in
a kernel where cuqml computes no number otherwise than CUDA-Q. A line whose rotations cannot be
counted — in a loop CUDA-Q cannot count, in a branch on what is not known before the kernel runs or
on what cuqml does not evaluate, behind a number stored in such a branch, beside a call of what is
no kernel — is refused for that, by name, as is one where CUDA-Q hands over more rotations than are
read, and every rotation of a gate is counted together where one is on a qubit picked by what is
not read. A kernel is read for this only where one rotation gate is written both at an argument’s
angle and at a number — written in it, captured or a fixed argument’s, in a kernel it calls with no
argument’s value, or at a called kernel’s argument that some call hands a number — or plain and
.adj at an argument’s angle; a kernel that calls others with nothing but its arguments’ values is
not read. A kernel that calls another and has an angle read as an argument negated is held the same
way. Under explicit_measurements=True, where capture stops at CUDA-Q’s draw, such a kernel is
captured to its end once more, at the first probe; at the second it is held as far as CUDA-Q drew.
See known-limits.md, which lists the kernels CUDA-Q answers that this refuses.
A Python variable the kernel captured — a number, a list, a kernel it calls — is not an
argument, and is read again at every call, as cudaq.observe reads it. Rebind it, or change a
captured list in place, and the next call runs the kernel as it now stands, captured again for
the new values; an angle computed from a captured bool, int or float uses the number as
it stands at that call. Kernels defined in a loop all read the loop variable as it stands when
they are called, as in CUDA-Q; a factory function gives each its own value. Reading the
captures costs every call of such a kernel: tens of microseconds for a few numbers, and time
that grows with its length for a captured list, nearly all of it CUDA-Q’s own binding. A
kernel that captures nothing pays none of it, and a long list is cheaper passed as a
list[float] argument.
A fixed argument — an int, bool, list[int], list[bool], cudaq.pauli_word,
list[cudaq.pauli_word], complex or list[complex] the kernel declares — is one value for every
row, which may shape the circuit: bound a loop, size a register, pick a qubit, switch a branch,
name an exp_pauli’s word. It is converted and checked as cudaq.observe converts it, and the
circuit is captured at that value and kept for it, found again as a captured variable’s is: a value
seen again among the last 32 set aside is no new capture. It takes no gradient: it is no column of
the block an angle is read from. Where an angle is read from the kernel’s IR, a bool or an int
among them is written in, and so is a list’s length, and a cudaq.pauli_word’s word is read from
its value; a list’s elements and a complex are not, and arithmetic on them is refused by name, as
on a captured value of the same kind. A value per row is no fixed argument: a tensor for one is
refused, and the remedy is a call per value with the rows that share it. Converting the values and
finding the program by them costs every call of such a kernel, as reading captures does: tens of
microseconds for a few numbers, and time that grows with its length for a list. A value not among
those kept costs a capture.
Refused in a kernel
In the kernel |
Raised |
Write instead |
|---|---|---|
A branch, a loop bound, a qubit index or a register size that follows the value of a |
|
a kernel per case, the batch split between them — or, where the whole batch takes one case, a fixed argument that decides it; or one circuit whose gate takes an angle, computed in torch, that turns it off |
An element read outside a list — a |
|
a list as long as the kernel reads; an index of 0 or more |
Angle arithmetic with no translation into torch or no derivative ( |
|
compute the angle in torch and pass it in; the rounding of a function is answered at fp32 |
Beside a computed angle, or angles that are lined up as above: a loop CUDA-Q cannot count when it compiles the kernel — one a |
|
a |
Beside a computed angle: a branch that a fixed argument or a captured value takes, or any |
|
a kernel per case; or compute the angle in torch and pass it in |
In a kernel that calls another: an angle that reaches the simulator as neither an argument, an argument negated nor a constant — rotations of one gate that meet on a qubit, an |
|
write the called kernel’s gates into the kernel itself |
Where written angles are lined up with other gates than the kernel writes: on a qubit a rotation, or a gate that takes an angle, acts on, what CUDA-Q hands over other than what is written there, in order — a gate left out, as two |
|
leave out gates that cancel, constants that cancel or come to whole turns, and the rotation and its adjoint; write the rotations CUDA-Q merges as one, at the sum of their angles, on one side of what stands between them; compute the angle in torch and pass it in |
There too: a gate on a qubit picked by an element of a captured list or of a list argument, or of a register sized by a captured list’s length; an |
|
write the index, the size or the word in the kernel; or pass the word as a |
Where every angle reads as an argument, one negated or a constant: on a line — one gate’s rotations on one qubit under the same controls — that holds a rotation at an argument’s angle, CUDA-Q hands over fewer rotations than are written, and the line holds constants that come to a whole number of turns or to nothing, a row of any length in order on the line, as |
|
leave out constants that cancel or come to whole turns, and the rotation and its adjoint; write the number in the kernel, or pass it in; a |
On |
|
|
A gate the target has no kernel for |
|
a gate it has; |
A custom operation whose matrix is not unitary |
|
a unitary matrix |
A register started from amplitudes |
|
gates, their angles computed in torch |
A branch on a measurement result |
|
|
An argument of a type no batched call takes yet: a NumPy scalar such as |
|
capture the value from Python, which is read again at every call |
A |
|
its value, |
A value CUDA-Q refuses for a fixed argument: one its own conversion refuses, such as |
|
a value of the type the kernel declares, an |
A kernel whose arguments are all fixed |
|
|
Fixed values that leave the kernel no gate, such as a loop bound of 0 |
|
|
A kernel from which no gate is captured, usually because its source cannot be recovered |
|
define the kernel in a |
A few more refusals guard the capture itself, such as a kernel whose lifted arithmetic does not reproduce what it emitted, or a CUDA-Q older than 0.16. Each names itself when it is met.
The whole public surface
observe_batch, get_state_batch, sample_batch and TorchLayer. That is all
import cuqml brings. The three functions take a CUDA-Q kernel and its arguments as
torch tensors — a list[float] as (n,) or (batch, n), a float as (), (batch,) or
a number — and any other argument as one plain value, and what comes back follows whether
any argument has a batch axis:
no batch axis |
|
|
|---|---|---|
|
scalar |
|
|
|
|
|
|
|
shots_count and the flags are keyword-only, as in cudaq.observe and cudaq.sample.
TorchLayer(kernel, weight_shape, observables=None, *, amplitudes=None, init=None, diff_method="adjoint", args=()) is an nn.Module rather than a function, so it sits outside
that table: like nn.Linear it takes (*, n_inputs) and returns (*, n_out).
The _batch suffix is what tells the three apart from cudaq.observe, cudaq.get_state
and cudaq.sample, which take one parameter vector and return a plain number, a state, or
a count dictionary — none of them with a batch axis.
observe_batch
cuqml.observe_batch(kernel, hamiltonian, *args, shots_count=0, diff_method="adjoint")
Argument |
Takes |
|---|---|
|
a |
|
one CUDA-Q spin operator; its terms are summed into one value per row. A list or tuple of operators is refused |
|
the kernel’s arguments, as under Kernel arguments |
|
keyword-only |
|
keyword-only: |
Returns a real torch.Tensor on the GPU at the target’s precision: (batch,), or
0-dimensional when no argument has a batch axis. It is differentiable in every tensor argument
that requires grad.
Expectation values of a spin operator, differentiable in params. The gradient arrives as
an ordinary tensor, so the optimiser is torch’s own and the whole batch trains from one
sweep:
params = torch.randn(32, 4, device="cuda", requires_grad=True)
opt = torch.optim.Adam([params], lr=0.1)
for _ in range(30):
loss = cuqml.observe_batch(ansatz, hamiltonian, params).mean()
opt.zero_grad(); loss.backward(); opt.step()
That is the part with no CUDA-Q equivalent to be faster than: cudaq.observe returns a
plain float and cudaq.gradients a list of them, so no optimiser in torch can consume
either.
diff_method selects how the gradient is taken, here per call and on TorchLayer once at
construction — which gradient a model uses is a property of the model, so it has no
business appearing in a training loop. Both values are exact and return the same number:
|
one reverse sweep for the whole batch |
|
the algorithm a device runs — 2 evaluations per parameter, 4 for a controlled rotation |
The shift dimension folds into the batch axis, so parameter shift is one execution of
the circuit at batch B·E — on cuqml-tensornet, one contraction — rather than the B·E
separate executions cudaq.gradients.ParameterShift costs.
It also differs from that class on a rotation under controls, deliberately: crx/cry/crz,
rx/ry/rz under more controls, and the first angle of a controlled u3. The two-term
shift rule needs a generator with exactly two distinct eigenvalues; a controlled rotation’s
are {0, ±½}, three of them, so the rule is wrong for it — measured 4.9e-02 off under one
control. CuQML uses the four-term rule there instead, agreeing with
cudaq.gradients.CentralDifference and with its own adjoint sweep to ~3e-07. cphase is
not affected, nor r1 under more controls, nor a controlled u3’s two phases: each
generator has two distinct eigenvalues, 0 and 1, and the leftover is a global phase that
cancels in ⟨ψ|H|ψ⟩.
A second derivative — torch.autograd.functional.hessian, a gradient penalty, anything
that differentiates a gradient again — is taken by reverse mode on cuqml-tensornet, the
default there, whose backward pass is itself differentiable: of an expectation, and of
the amplitudes a loss names. verify/tensornet.py checks its Hessians against second
central differences of cudaq.observe and cudaq.get_state. The state vector’s adjoint
sweep, and parameter shift on either target, compute a gradient once, outside autograd’s
graph. Asked to differentiate it again they refuse by name, with the remedy that fits the
call, where torch’s Hessian helper would otherwise have returned zeros. From those two a
first derivative taken with create_graph=True is the same bits as one taken without;
kept, it holds the graph behind it — the state its forward saved too, where the loss is not
linear in the call’s output — until it is dropped or detached, as any torch gradient does.
shots_count carries cudaq.observe’s meaning, and its default is exact as cudaq.observe’s
is, 0 here and -1 there: any non-positive value
is the exact expectation, a positive value an estimate from that many measurements of each
term. Non-positive rather than zero because that is what CUDA-Q does — 0, -1 and -5
all return the exact value. That is the opposite sense to sample_batch’s
shots_count=1000, which is a real shot count with no exact mode — each matches the CUDA-Q
call it sits beside. Every row draws independently, so R identical rows give R independent
estimates from one execution of the circuit, where cudaq.observe needs R calls. An
estimate has no gradient, so asking for one on parameters that require grad is refused by
name rather than answered with a tensor that fails to differentiate later.
Refused
Asked for |
Raised |
Write instead |
|---|---|---|
A list or tuple of operators |
|
|
An operator with a complex coefficient |
|
a Hermitian operator |
A |
|
an |
A |
|
|
A gradient of a shot estimate: |
|
|
A kernel that measures |
|
a kernel without the measurement |
A kernel that calls one that measures, where the measurement runs, which |
|
a kernel without the measurement |
A kernel that resets a qubit part-way through |
|
|
A second derivative, on |
|
reverse mode on |
Forward-mode AD |
|
reverse mode: |
On |
|
what the message names |
get_state_batch
cuqml.get_state_batch(kernel, *args)
Argument |
Takes |
|---|---|
|
a |
|
the kernel’s arguments, as under Kernel arguments |
Returns, by target:
On
cuqml, aBatchState: atorch.Tensorsubclass on the GPU,(batch, 2**n)complex, or(2**n,)when no argument has a batch axis;complex64at fp32 andcomplex128at fp64. It is differentiable, and carriesamplitude,amplitudesandto_numpy.On
cuqml-tensornet, aBatchNetworkState, which is not a tensor and holds no amplitude. Itsamplitudeandamplitudescontract what they are asked for and return differentiable tensors; itsto_numpyis refused.
The circuit’s state vector, differentiable in params. It stays a GPU tensor with its
autograd edge intact, so a classical layer consumes it without a host round-trip.
Amplitudes match cudaq.get_state exactly — not merely up to a global phase.
params = torch.randn(64, 4, device="cuda", requires_grad=True)
psi = cuqml.get_state_batch(ansatz, params) # (64, 16) complex64, one state per row
probs = psi.abs() ** 2 # (64, 16) Born-rule probabilities
probs.sum(dim=1) # all 1.0 — every row a normalised state
probs[:, 0].mean().backward() # gradients reach params, no host round-trip
Every amplitude of every row is built in one execution — or as few as hold it — and none of it crosses to the host: the objective above is computed where the state already is.
A kernel that measures, in it or in a kernel it calls, is run as cudaq.get_state runs it:
each measured qubit is collapsed where the kernel measures it, a Born-rule draw per row, and
the gates after it run on what is left. Every row is a state cudaq.get_state returns for
that row, at the frequency it returns it, and R identical rows are R independent calls. A
measurement that the values of the kernel’s fixed arguments, or of what it captured, switch
off is not run, as cudaq.get_state does not run it. Such a state carries no gradient.
On cuqml-tensornet no amplitude is held — 2**n of them are what that target exists to
avoid — so get_state_batch returns a state whose amplitudes are contracted when they are
asked for, as cudaq.get_state does on CUDA-Q’s tensornet:
cudaq.set_target("cuqml-tensornet")
psi = cuqml.get_state_batch(wide, params) # a 40-qubit kernel: nothing contracted yet
amps = psi.amplitudes(["0" * 40, "1" + "0" * 39]) # (batch, 2) complex, one contraction
amps.abs().pow(2).sum().backward() # gradients reach params
amplitude and amplitudes answer there as they do on the state vector — per row,
least-significant-first, differentiable — and each call closes the circuit on the basis
states it names, every row and every one of them in a single contraction. What needs the
whole state is refused by name: to_numpy(), as tensornet’s State.to_numpy refuses it,
and a torch function or a NumPy conversion applied to the state itself. So is a kernel that
measures, in it or in a kernel it calls, there being no state there to collapse.
Refused
Asked for |
Raised |
Write instead |
|---|---|---|
A kernel that resets a qubit part-way through |
|
|
A kernel that measures, with an argument that requires grad: in it, as CUDA-Q’s check reads it as written, or in a kernel it calls, where the measurement runs |
|
|
On |
|
|
On |
|
|
A basis state that is not bits, or not one bit per qubit |
|
a string of |
|
|
a list of basis states |
A second derivative of the state, on |
|
the amplitudes a loss names, on |
Forward-mode AD |
|
reverse mode |
States that do not fit in GPU memory at once |
|
a smaller batch; fewer qubits where one row does not fit |
sample_batch
cuqml.sample_batch(kernel, *args, shots_count=1000, explicit_measurements=False)
Argument |
Takes |
|---|---|
|
a |
|
the kernel’s arguments, as under Kernel arguments |
|
keyword-only positive |
|
keyword-only |
Returns a BatchSampleResult: a torch.Tensor subclass on the GPU, (batch, shots_count)
int64, or (shots_count,) when no argument has a batch axis. Each entry is one shot’s
bitstring packed into an integer. It carries most_probable, count, expectation and
get_marginal_counts, and no gradient.
Measurement outcomes, one state built per parameter row and every shot drawn from it. Unlike the two above it carries no autograd edge — an outcome is discrete — and parameters that require grad are refused by name rather than answered with one that cannot be differentiated. A batch whose states the GPU cannot hold at once runs in slices of as many rows as it can, and is refused by name only where not even one row fits: its states, or its shots beside them and the whole result.
shots_count defaults to 1000, as cudaq.sample’s does. Each outcome is the measured
bitstring packed into an integer with the kernel’s lowest-indexed measured qubit in the
most significant bit, which is the order CUDA-Q prints its keys in, whatever order the
mz calls ran in:
out = cuqml.sample_batch(kernel, params.detach()) # (batch, shots_count), no gradient
values, counts = out[0].unique(return_counts=True) # row 0's histogram
[format(int(v), f"0{k}b") for v in values] # cudaq.sample's exact keys, k = qubits measured
The kernel’s own mz decides how wide that is: mz(q[0]) gives 1-bit outcomes, mz(q)
gives n-bit ones, and a kernel with no mz measures every qubit, exactly as
cudaq.sample does. A kernel that resets a qubit part-way through gets one trajectory
per row, all its shots drawn from the state that collapse produced — which is what
cudaq.sample does, so R identical rows give R independent trajectories. observe_batch
and get_state_batch refuse a reset kernel by name rather than return the uncollapsed
answer.
explicit_measurements= is carried across from cudaq.sample with its meaning: under it an
outcome is packed in the order the kernel’s mz calls ran, the first of them most
significant, which is the key cudaq.sample(..., explicit_measurements=True) gives — after
mz(q[4]); mz(q[1]) qubit 4 leads, where by default qubit 1 does — and the accessors read
that key. It is drawn where CUDA-Q draws it, before any later gate on a measured qubit. A
kernel that ends by measuring in ascending order, mz(q), is unchanged by it, and the
tensor is the ordered per-shot sequence either way. What a batch cannot give is refused by
name instead: a kernel that collapses part-way through, which needs a trajectory per shot;
a kernel that measures a qubit again, or measures on after a gate on one it has measured,
whose key CUDA-Q draws in parts; and a kernel whose measurements are drawn before any gate
has run, which leaves no circuit to batch. A kernel with no mz is refused under the flag
by cudaq.sample itself, and so here, in its words.
A kernel that measures is read the way CUDA-Q reads it — which is not one way.
cudaq.sample treats mz as naming the qubits to report, and sample_batch follows.
cudaq.get_state executes the kernel, so it hands back a post-measurement state, each
qubit collapsed where the kernel measures it; so does get_state_batch, a Born-rule draw
per row at each measurement — and parameters that require grad are refused by name, because
a collapse has no gradient to carry. cudaq.observe refuses a measured kernel outright, so
observe_batch refuses it in the same words. Three readings of one mz, and matching each
is what keeps a result comparable to the target beside it. cudaq.observe’s check reads the
kernel it is handed alone, though: a kernel whose called kernel measures passes it, and
cudaq.observe answers it, collapsing the state call by call. observe_batch refuses such a
kernel by name instead, where the measurement runs, whatever it changes: a called kernel’s
mz of a qubit certain to read one outcome, of a fresh qubit it takes, or of a qubit in a
product state with the ones observed is refused too, though cudaq.observe answers each with
one value. Where cudaq.get_state returns one state for such a kernel, its gradient and its
state on cuqml-tensornet are refused all the same. A called kernel’s measurement that a
captured value, a fixed argument, or an argument the calling kernel passes the same for every
row, switches off, both answer; one that follows a row is refused, as any branch on an argument
is.
A measurement under a branch is read as it is written by cudaq.observe, which refuses the
kernel whatever the branch’s value, and so by observe_batch. cudaq.get_state runs only the
measurements the values leave, and so does get_state_batch on cuqml: where the values of a
kernel’s fixed arguments, or of what it captured, switch every one of them off, a row is the
state the kernel leaves, nothing collapsed. Such a kernel is still read as one that measures,
as CUDA-Q’s check reads it, so its gradient, and its state on cuqml-tensornet, are refused by
name, in words that say which of the two can switch it off.
Refused
Asked for |
Raised |
Write instead |
|---|---|---|
An argument that requires grad |
|
|
A |
|
a positive |
|
|
|
|
|
|
On |
|
|
On |
|
|
|
|
an |
Forward-mode AD |
|
the tensor’s primal |
On |
|
what the message names |
In an accessor: a |
|
the one register; a bitstring as wide as the qubits measured |
Result accessors
The last two results carry their CUDA-Q counterpart’s accessors, answering per row, since a row is one experiment:
out = cuqml.sample_batch(kernel, params.detach())
out.most_probable(); out.count("0101"); out.expectation(); out.get_marginal_counts([0, 2])
psi = cuqml.get_state_batch(kernel, params)
psi.amplitude([0, 1, 0, 1]); psi.amplitudes(["0101", "1010"]); psi.to_numpy()
accessor |
on |
batched result |
1-D result |
the CUDA-Q call returns |
|---|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
the same type |
the same type |
|
|
|
|
0-dim tensor |
|
|
|
|
|
|
|
|
|
|
ndarray |
They are ordinary tensors otherwise: indexing, unique, @ and the rest behave and cost
exactly what they did. amplitude is least-significant-first, as cudaq.State.amplitude
is, and reads qubit 0 first, as a key cudaq.sample prints by default does — so the key of
a kernel that measures every qubit is already the basis state to ask for. Under
explicit_measurements=True a key reads the qubits in the order the mz calls ran, there
and from sample_batch alike, so it is that basis state only where they ran in ascending
order. It is the two integers that run opposite ways: an outcome packs the qubit its key
reads first — qubit 0, by default — into its most significant bit and the state’s index
holds qubit 0 in its least, so an outcome is not an index into the state. That is
CUDA-Q’s convention in each place rather than one imposed here. cudaq has one measurement
register on this target, so a register_name other than '__global__' is refused by name;
note get_marginal_counts takes it keyword-only where the other three take it positionally.
Three of them differ from the CUDA-Q call they mirror, each deliberately. amplitude and
amplitudes return tensors where cudaq.State’s return a Python complex and a list of
them — that is what keeps them differentiable, and it is why a single parameter vector
gives a 0-dim tensor rather than collapsing to a complex the way most_probable and
count collapse to str and int. to_numpy is the opposite case and the only accessor
that ends the autograd edge, since NumPy has nowhere to keep one; reach for it when
leaving torch. And expectation has no expectation_z beside it, because CUDA-Q
deprecates that spelling in favour of this one.
The accessors live on what the function returned, not on slices of it — so
out.count("01")[0] rather than out[0].count("01"), since indexing yields a plain
tensor. That is what keeps indexing, unique and @ costing exactly what they cost on
any other tensor.
On cuqml-tensornet a get_state_batch result is no tensor: amplitude and amplitudes
contract the basis states they name, with the shapes above, and to_numpy is refused, as
CUDA-Q’s tensornet refuses it — see get_state_batch.
TorchLayer
layer = cuqml.TorchLayer(kernel, weight_shape, observables=None, *, amplitudes=None,
init=None, diff_method="adjoint", args=())
out = layer(x)
Argument |
Takes |
|---|---|
|
a |
|
a positive |
|
a list or tuple of CUDA-Q spin operators, or one operator; one output column each. Or |
|
keyword-only: a list of basis states whose amplitudes are the output; or |
|
keyword-only: a callable applied to the weights in place at construction |
|
keyword-only: |
|
keyword-only: a tuple of the kernel’s other arguments, in its order around its |
|
a |
Returns a real torch.Tensor, differentiable in the weights and in x:
Constructed with |
Output |
|---|---|
|
|
|
|
neither |
|
Attributes: weights, an nn.Parameter; n_qubits, the captured circuit’s width, None
until the first forward; kernel, observables, amplitudes and diff_method as given; and
args as given, which may be given another tuple for the next forward. args is no weight:
it takes no gradient and is not in state_dict, as kernel is not, so a checkpoint loaded
into a layer built with other values runs another circuit.
The same engine as an nn.Module, for building a hybrid model:
# block is an ordinary CUDA-Q kernel whose theta is 4 data angles then 2x4 weights
model = torch.nn.Sequential(
torch.nn.Linear(8, 4),
cuqml.TorchLayer(block, (2, 4), [cudaq.spin.z(i) for i in range(4)]),
torch.nn.Linear(4, 2),
).cuda()
model(x).sum().backward() # reaches both Linears and the layer's own weights
It owns the weights and concatenates them behind whatever it is handed, so the kernel takes
exactly one list[float], its theta, which is [inputs..., weights...], beside its fixed
arguments in args; a kernel with separate data and weight arguments is for
observe_batch(kernel, h, x, w) instead. A kernel whose depth is an int argument,
deep(theta: list[float], layers: int), makes a layer at a depth: TorchLayer(deep, (2, 4), observables, args=(2,)); a layer of another weight shape is another depth. The
output is (*, n_obs), every observable out of one sweep rather than one sweep each. Like
nn.Linear it takes (*, n_inputs) and returns (*, n_out), so a (batch, seq, features)
activation passes straight through and the layer drops between two Linears that carry a
sequence axis. Rows are independent, so the leading axes are flattened into the engine’s
batch — a (32, 128, 4) input is 4096 rows, and a memory refusal will say 4096. The
gradient reaches the layer in front of the circuit, which is what makes a hybrid model
train: to the engine, the inputs are just more circuit parameters.
observables=None without amplitudes= returns the state as (batch, 2**(n+1)) real
instead — get_state_batch in the form a classical layer takes. That width is 2 * 2**n,
one pair per complex amplitude, interleaved as torch.view_as_real lays them out:
[re_0, im_0, re_1, im_1, ...]. It is not the split real/imag storage the kernels use
— that layout is internal and never surfaces. With the same block as above, whose four
qubits make that width 2**(4+1):
layer = cuqml.TorchLayer(block, (2, 4)) # no observables -> the state itself
model = torch.nn.Sequential(layer, torch.nn.Linear(2 ** (4 + 1), 2)).cuda()
model(x).sum().backward() # reaches the Linear and the layer's weights
amplitudes= takes basis states, as get_state_batch(...).amplitudes does, and returns
only theirs, as (*, 2k) real interleaved the same way. It is that call viewed as real, on
either target — and on cuqml-tensornet, which has no state to return, it is how a layer
reads amplitudes at all:
layer = cuqml.TorchLayer(block, (2, 4), amplitudes=["0000", "1111"]) # (batch, 4) real
A layer returns observables or amplitudes, so it takes one or the other. Neither the state
nor an amplitude is an expectation value, which is what parameter shift differentiates, so
without observables diff_method="parameter-shift" is refused by name; the default takes
the gradient, by the adjoint sweep or, on cuqml-tensornet, reverse mode.
weights is an ordinary nn.Parameter initialised uniformly on [0, 2*pi), so
torch.nn.init.zeros_(layer.weights) after construction works exactly as it does on any
torch layer; init= takes the same in-place callable at construction instead. The two are
equivalent — init= is PennyLane’s convention rather than torch’s, where no stock layer
carries such an argument — so reach for whichever your model code already uses.
n_qubits reports the width of the captured circuit. The layer is never told it: the width
belongs to the CUDA-Q kernel and is recovered by capture, so it reads None until the first
forward has run. It follows the kernel: where a captured Python variable or args changes the
circuit’s width, n_qubits is the new width from the next forward on, and the layer checks its
parameter vector and its amplitudes again. With neither observables nor amplitudes it is what
sizes the next layer’s input, 2**(n_qubits + 1).
Refused
Asked for |
Raised |
Write instead |
|---|---|---|
A kernel that does not take exactly one |
|
|
|
|
|
A kernel that never reads some of the inputs or weights it is handed; found at the first forward, and again where a captured variable or |
|
a |
A |
|
a positive size |
|
|
at least one operator, or |
Both |
|
one of them |
|
|
a list of basis states |
|
|
the default, |
A basis state in |
|
a string of |
On |
|
observables, amplitudes, or |
An input that is not a tensor, has no feature axis, or is on the CPU |
|
a CUDA tensor |
Weights at another precision than the target’s |
|
|
What the call beneath it refuses — |
as that call raises it |
as for that call; without observables, a kernel that measures is evaluated under |
CUDA-Q’s own calls on the cuqml targets
CUDA-Q’s functions stay CUDA-Q’s. On a cuqml target each takes what it takes on any other
target and returns CUDA-Q’s own type; none of them has a batch axis, and none returns a torch
tensor. The rows are backed by the run behind cuqml-beside-cudaq.md,
by verify/verify_api.py on cuqml, and by verify/tensornet.py, verify/equivalence.py and
verify/angles.py for the refusals. Two refusals on cuqml-tensornet, of
cudaq.State.from_data and of a non-unitary matrix, rest on the plugin’s source alone.
CUDA-Q call |
It returns |
On |
On |
|---|---|---|---|
|
|
supported |
supported; a kernel with a |
|
|
supported |
supported where the measurements are drawn as shots; a collapse or a |
|
|
supported |
refused: use |
|
a list, one return value per shot |
supported |
refused: it collapses the state |
|
CUDA-Q’s own |
supported |
supported |
|
nothing |
supported in the shapes under Custom operations. A non-unitary matrix is refused when a kernel that applies it runs |
supported; a non-unitary matrix is refused the same way |
|
nothing |
supported: see Seeding |
supported |
|
refused |
refused |
|
|
refused: see Noise |
refused |
A refusal that comes back through a CUDA-Q call is a RuntimeError whose text contains
cuqml target:. CUDA-Q may put words of its own in front, as it does for cudaq.run on
cuqml-tensornet.
What comes from CUDA-Q unchanged
sample, run, gate definitions and CUDA-Q’s own optimisers come from CUDA-Q itself,
unchanged, on the cuqml target. CuQML defines no circuit API.
One exception: state initialisation is not supported. cudaq.State.from_data raises
here where qpp-cpu and nvidia return a state, so a state cannot be built from your own
amplitudes and cannot be handed to a kernel as a starting point — including a state this
target itself produced. Circuits start from |0...0> and get there by applying gates. The
refusal is by name rather than a state that quietly ignores the data.
Seeding
cudaq.set_random_seed(seed) reaches every draw cuqml makes — a shot, a mid-circuit
collapse, a reset, and the torch.binomial behind a sampled expectation. Seed, run,
re-seed, run again and the results are byte-identical; verify/sampling.py checks that
and holds qpp-cpu to the same test in the same run, so the bar is what CUDA-Q delivers.
One case is narrower: a sample_batch too large to hold at once draws slice by slice, so
it repeats byte for byte only where the memory free slices it the same way — and what the
first call leaves allocated, its own result while it is still held, can be enough to change
that.
Until you call it, draws come from torch’s default generator, so torch.manual_seed()
works as it always did. Once CUDA-Q has been given a seed, that seed is the one in
effect — which is what asking a CUDA-Q API for reproducibility ought to mean.
A seed is reproducible, not portable. cuqml’s draws come from a torch generator, so the
same seed gives a different sequence than qpp-cpu or nvidia, which share CUDA-Q’s own
RNG and therefore match each other. The API and the distribution are unchanged; only the
stream differs — which is why verify/sampling.py holds the draw to the spread CUDA-Q
shows against its own runs rather than to its exact sequence.
Custom operations
cudaq.register_operation names a matrix rather than a gate, so there is nothing to look
up: the shape is the whole dispatch. A k-qubit unitary on 1 or 2 targets runs under up
to 4 controls, and 3 or 4 targets run uncontrolled; anything outside that raises naming
the gate and its shape.
The operation is its matrix, whatever it is called. Register a name again with another matrix
and every kernel first called after that runs the new one, on both targets and in every call.
A kernel that has already been called keeps the matrix it was compiled with where the
operation is in its own body, as on every CUDA-Q target, and follows a kernel it calls once
that kernel is written again. op.adj is the adjoint matrix under the same name. A name that
is also a built-in gate’s is the registered matrix wherever CUDA-Q hands the operation over:
always in another case (S, X, Rx), and under the gate’s own spelling where CUDA-Q 0.16
makes it the operation, which is sdg.adj, sdg.ctrl, tdg.adj, tdg.ctrl and swap.adj.
sdg(q), tdg(q), swap(a, b), swap.ctrl and every spelling of s and h stay the
gates, on every target.
A non-unitary matrix is refused, which is a deliberate divergence. CUDA-Q accepts one
— measured, qpp-cpu takes diag(1, 2) and returns a state of norm² 2.5 — and every
probability and expectation drawn from that state is then wrong with nothing to signal
it. The tolerance follows the target’s precision, 1e-5 at fp32 and 1e-10 at fp64, because
the matrix arrives already rounded to it.
Noise
Noisy simulation is not supported. There are no density-matrix or trajectory
kernels, so a noise model raises rather than silently returning a noiseless result: a
noise_model= handed to a CUDA-Q call, and one set with cudaq.set_noise, under which
CUDA-Q’s calls and the four batched ones alike refuse by name — on a kernel already
captured as on a new one — until cudaq.unset_noise(). A refused cudaq.observe or
cudaq.run leaves the noise_model= it was handed set as well — CUDA-Q 0.16 unsets it
only when the call returns — so cudaq.unset_noise() is needed after one of those too.
Refusals at a glance
These are not tied to one call. Refusals that belong to one call are in its section, and refusals of a kernel are under Kernel arguments.
Asked for |
Raised |
Write instead |
|---|---|---|
A batched call under a target that is neither |
|
|
A batched call while CUDA-Q holds a noise model |
|
|
A tensor at the other precision |
|
cast it, or select the precision with |
A tensor on the CPU |
|
|
A NumPy array or a list where a tensor is due |
|
|
The wrong number of arguments, none of the |
|
the kernel’s own arguments, at least one a tensor; |
A tensor for a fixed argument |
|
its value, |
Tensors on two devices, batch axes of two sizes, or a tensor with too many axes for its argument |
|
one device, one batch size; |
Tensors at two dtypes |
|
one dtype, the target’s |
|
|
|