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_batch and cuqml.TorchLayer — take torch tensors on the GPU for a kernel’s list[float] and float arguments, 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. On cuqml-tensornet, get_state_batch returns 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_state and cudaq.run, with cudaq.gradients and cudaq.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

cuqml.observe_batch(kernel, h, *args)

torch.Tensor, (batch,) real, differentiable

cudaq.observe(kernel, h, *args)

cudaq.ObserveResult; its .expectation() is a float

Gradient

.backward(), then .grad on the argument

torch.Tensor, the argument’s shape

cudaq.gradients.ParameterShift().compute(...)

list[float]

State

cuqml.get_state_batch(kernel, *args)

on cuqml, BatchState: a torch.Tensor, (batch, 2**n) complex, differentiable. On cuqml-tensornet, BatchNetworkState

cudaq.get_state(kernel, *args)

cudaq.State

One amplitude

psi.amplitude(basis)

torch.Tensor, (batch,) complex, differentiable

state.amplitude(basis)

complex

Shots

cuqml.sample_batch(kernel, *args)

BatchSampleResult: a torch.Tensor, (batch, shots_count) int64, with no gradient

cudaq.sample(kernel, *args)

cudaq.SampleResult

A layer of a model

cuqml.TorchLayer(kernel, ...)

an nn.Module; its output is a torch.Tensor, (*, n_out), differentiable

none

Optimiser

torch.optim

torch’s own

cudaq.optimizers

CUDA-Q’s own

A return value per shot

none

cudaq.run(kernel, *args)

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

cudaq.set_target(...)

Engine

Precision

Tensors you pass

Amplitudes

"cuqml"

state vector

fp32

torch.float32

complex64

"cuqml", option="fp64"

state vector

fp64

torch.float64

complex128

"cuqml-tensornet"

tensor network

fp32

torch.float32

complex64

"cuqml-tensornet", option="fp64"

tensor network

fp64

torch.float64

complex128

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**n amplitudes, which is what this target exists to avoid. get_state_batch returns one whose amplitudes are contracted when asked for, as cudaq.get_state does on tensornet, and refuses what needs them all; cudaq.get_state itself, and TorchLayer without observables or amplitudes, are refused, pointing at cuqml.

  • No collapse. cudaq.sample draws a kernel’s measurements as shots, which needs no state. A measurement that must collapse the state where it stands, as cudaq.run makes, is refused, and so is a reset.

  • 63 measured qubits in sample_batch, which packs an outcome into one int64 as it does on cuqml. cudaq.sample returns 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 tensornet would 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

observe_batch, get_state_batch, each argument shaped (batch, n) or shared as (n,); an argument of another type one value for every row

unchanged — its arguments are passed as cudaq.observe takes them, in its own order. The batch is a tensor dimension, so one launch per gate covers every sample

gradients as a torch tensor

.backward(), then params.grad; diff_method= picks the method

unchanged — one adjoint sweep for the whole batch replaces 2 * n_params * batch circuit evaluations, and torch.optim steps on the result

measurement outcomes over a batch

sample_batch → (batch, shots_count) int64

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 batch of them

a differentiable state vector, on the GPU

get_state_batch → (batch, 2**n) complex

unchanged — the autograd edge survives, so a classical layer consumes the amplitudes with no host round-trip

CUDA-Q’s accessors, answering per row

most_probable, count, expectation, get_marginal_counts on a sample_batch result; amplitude, amplitudes, to_numpy on a get_state_batch one

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 nn.Module

TorchLayer, with n_qubits reporting the captured width

unchanged — the layer owns the weights and appends them to whatever it is handed, so a circuit drops into nn.Sequential between two nn.Linears

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

cudaq.set_target("cuqml-tensornet")

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

cudaq.sample, observe, get_state, run, cudaq.gradients, cudaq.optimizers, cudaq.register_operation, cudaq.set_random_seed

unchanged — on the cuqml target they behave as on any other, with one exception: cudaq.State.from_data raises, since state initialisation is not supported. A custom unitary is a dispatch case, not a new kernel: it takes the same dense primitive every given matrix takes, controlled or not

fp32 or fp64, said out loud

cudaq.set_target("cuqml") for fp32, option="fp64" for fp64, as the nvidia target takes it

unchanged — but arguments or TorchLayer weights at the other precision, a gate with no kernel, a size that cannot fit, a non-unitary custom operation, or a noise_model= raises naming what it needed, rather than degrading quietly

Kernel arguments

What a batched call takes for each argument of the kernel:

The kernel declares

You pass

Shapes

list[float]

a torch.Tensor

(n,), shared by every row, or (batch, n), one row each

float

a number or a torch.Tensor

a number or (), shared by every row, or (batch,), one per row

int, bool, list[int], list[bool], cudaq.pauli_word, list[cudaq.pauli_word], complex, list[complex]

one plain value, as cudaq.observe takes it

a fixed argument: one value for every row, the circuit captured at it, with no gradient

any other type: a NumPy scalar such as np.int32, a dataclass or a tuple, list[list[...]], cudaq.State, a kernel

nothing

refused, naming the argument: capture the value from Python instead

  • The arguments go in the kernel’s own order, as cudaq.observe takes them, and there are as many as the kernel declares.

  • At least one list[float] or float argument is a tensor. Every tensor is on one CUDA device and at one dtype, the target’s: float32 at fp32, float64 at fp64. No tensor is moved or cast for the caller, and no array or list is converted for a list[float]; a plain number given for a float takes the tensors’ dtype and device. A fixed argument takes what cudaq.observe takes for its type, converted as CUDA-Q converts it — a str for a cudaq.pauli_word, a NumPy array or a tuple for a list[int], an np.int64 for an int — 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 list[float] or float argument

ValueError

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 list[float] argument, a fixed list such as a list[int] or a list[bool], a list captured from Python, the outer list of a captured list of lists — past its end, or before its start: at theta[-3], since CUDA-Q counts from the end at a literal -1 alone, at an int of -1, or at a bool index that is True, which CUDA-Q takes as -1. Judged in the kernel’s own body, where the read runs whenever the kernel does: at an index that is a number once CUDA-Q’s passes have run, as it is in a loop of fewer than 50 passes, which they unroll; and in a loop of 50 or more passes whose start, bound and step are numbers, at the loop’s count times a number plus a number. CUDA-Q does not check the index, and hands the simulator whatever lies there; known-limits.md lists the reads that are not judged

IndexError, naming the element and the list’s length

a list as long as the kernel reads; an index of 0 or more

Angle arithmetic with no translation into torch or no derivative (np.ceil, %), an angle computed inside a called kernel or in a kernel that calls another, or one computed from a captured Python variable that is not a bool, an int or a float — a list, a NumPy array, np.float32 — or from a fixed argument that is not a bool or an int: an element of a list argument, a complex; at fp64, an angle rounded to single precision from a value computed through a function other than +, -, *, /, sqrt, a sign, a magnitude, the larger or the smaller of two, as np.cos(np.float32(b))

ValueError

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 break leaves, a while that tests something other than an integer counter, a bound that is a float, the length of a captured list or an element of a list argument

ValueError

a for over a range, bounded by an integer

Beside a computed angle: a branch that a fixed argument or a captured value takes, or any if/else on one; a branch on a fixed or captured value that is not written into the IR, as an element of a list or a complex is not, taken or not; a branch on a loop’s counter or an argument’s length that is taken

ValueError

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 exp_pauli at an argument’s angle

ValueError

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 h or two x in a row are, or rotations of one gate handed over as one across another gate written between them on the qubit or a control: the qubit the target of a controlled x or of an rx under controls, a control on an rz’s qubit, a rotation under other controls; among the rotations of one gate on one qubit under the same controls, a constant one, or any number written together, that come to a whole number of the gate’s turns — 4π for rx, ry and rz, 2π for r1, to within 1e-12 — or to nothing, as ry(4.0 * np.pi, q) or rx(0.1, q), rx(0.2, q), rx(-0.3, q) do, a number the kernel captured among them; a rotation and its adjoint at one angle, rx(a, q) and rx.adj(a, q) or rx(-a, q), with nothing but rotations of that gate between them; rotations that meet, with another of that gate after them on the qubit, where capture’s probes leave two ways to line them up — a term that is nothing at both written last before a gate they commute with among them; a rotation handed over as a run of written ones on both sides of such a gate; at fp64, a rotation handed over as the sum of two or more written ones, one of them computed through a function other than +, -, *, /, sqrt, a sign, a magnitude, the larger or the smaller of two and a rounding to single precision, as rx(k * np.arctan(c), q) beside rx(b, q); or an angle that has no value at one of the probes, such as np.arccos(a)

ValueError

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 exp_pauli by a word that is neither written in the kernel nor one captured cudaq.pauli_word nor one handed as an argument, such as a word of a list[cudaq.pauli_word]

ValueError

write the index, the size or the word in the kernel; or pass the word as a cudaq.pauli_word argument

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 rx(c, q), h(p), rx(-c, q), rx(b, q) do, or a rotation and its adjoint at one angle, or a rotation at a number that is not read to the bit, such as one a called kernel returns — read through calls, scopes, branches CUDA-Q decides before the kernel runs and counted loops; or CUDA-Q hands over as many, and one of them is not the rotation written there, in order, at capture’s probes; or fewer on qubits cuqml gives no number, such as an ancilla a called kernel allocates; or the line’s 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, beside a call of what is no kernel — or CUDA-Q hands over more of them than are read

ValueError

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 for over a range, bounded by an integer; allocate every qubit at the kernel’s top level, in registers of sizes written there, and hand it to the kernels that use it

On cuqml: rx, ry, rz, r1 or u3 under five or more controls, whose angle comes from an argument

NotImplementedError (UnsupportedGate)

cuqml-tensornet

A gate the target has no kernel for

NotImplementedError (UnsupportedGate)

a gate it has; verify/gate_support.py prints which

A custom operation whose matrix is not unitary

ValueError

a unitary matrix

A register started from amplitudes

RuntimeError, in the target’s own words

gates, their angles computed in torch

A branch on a measurement result

NotImplementedError; from observe_batch, and from TorchLayer with observables, cudaq.observe’s own refusal as a RuntimeError where it has one

cudaq.run on cuqml for shots; for values and gradients, control the later gate on the qubit

An argument of a type no batched call takes yet: a NumPy scalar such as np.int32 or np.float32, a dataclass or a tuple, list[list[...]], cudaq.State, a kernel

TypeError

capture the value from Python, which is read again at every call

A torch.Tensor for a fixed argument, of any shape

TypeError

its value, t.item() or t.tolist(); for a value per row, a call per value with the rows that share it

A value CUDA-Q refuses for a fixed argument: one its own conversion refuses, such as True for an int, 1 for a bool or a list for an int, which cudaq.observe broadcasts where it comes first; or one it lets through and cudaq.observe then fails on, such as an int, or a list[int]’s element, past a signed 64-bit integer (std::bad_cast)

RuntimeError, with CUDA-Q’s words, or as CUDA-Q raises it where its conversion lets the value through; an int past 64 bits is named with the range its int holds

a value of the type the kernel declares, an int from -263 to 263 - 1

A kernel whose arguments are all fixed

TypeError

cudaq.observe, cudaq.get_state or cudaq.sample

Fixed values that leave the kernel no gate, such as a loop bound of 0

ValueError

cudaq.observe, cudaq.get_state or cudaq.sample at those values

A kernel from which no gate is captured, usually because its source cannot be recovered

ValueError

define the kernel in a .py file

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

(batch, ...)

observe_batch(kernel, hamiltonian, *args, shots_count=0, diff_method="adjoint")

scalar

(batch,)

get_state_batch(kernel, *args)

(2**n,) complex

(batch, 2**n) complex

sample_batch(kernel, *args, shots_count=1000, explicit_measurements=False)

(shots_count,) int64

(batch, shots_count) int64

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

kernel

a @cudaq.kernel

hamiltonian

one CUDA-Q spin operator; its terms are summed into one value per row. A list or tuple of operators is refused

*args

the kernel’s arguments, as under Kernel arguments

shots_count

keyword-only int. Zero or negative, the exact expectation; 0 is the default. Positive, an estimate from that many measurements of each term, which carries no gradient

diff_method

keyword-only: "adjoint", the default, or "parameter-shift"

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:

"adjoint" (default)

one reverse sweep for the whole batch

"parameter-shift"

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

TypeError

TorchLayer(..., observables=[...]), or one call per operator

An operator with a complex coefficient

ValueError

a Hermitian operator

A shots_count that is not an integer

ValueError

an int

A diff_method other than the two

ValueError

"adjoint" or "parameter-shift"

A gradient of a shot estimate: shots_count > 0 with an argument that requires grad

RuntimeError

shots_count=0, or .detach() the argument

A kernel that measures

RuntimeError, in cudaq.observe’s own words

a kernel without the measurement

A kernel that calls one that measures, where the measurement runs, which cudaq.observe’s check does not see

NotImplementedError

a kernel without the measurement

A kernel that resets a qubit part-way through

NotImplementedError

cudaq.observe on the cuqml target

A second derivative, on cuqml or by parameter shift

RuntimeError

reverse mode on cuqml-tensornet

Forward-mode AD

NotImplementedError

reverse mode: .backward() or torch.autograd.grad. On cuqml, diff_method="parameter-shift" where the tangent of a gradient is wanted

On cuqml, a row that does not fit in GPU memory; on cuqml-tensornet, a batch whose contraction does not fit

torch.cuda.OutOfMemoryError

what the message names

get_state_batch

cuqml.get_state_batch(kernel, *args)

Argument

Takes

kernel

a @cudaq.kernel

*args

the kernel’s arguments, as under Kernel arguments

Returns, by target:

  • On cuqml, a BatchState: a torch.Tensor subclass on the GPU, (batch, 2**n) complex, or (2**n,) when no argument has a batch axis; complex64 at fp32 and complex128 at fp64. It is differentiable, and carries amplitude, amplitudes and to_numpy.

  • On cuqml-tensornet, a BatchNetworkState, which is not a tensor and holds no amplitude. Its amplitude and amplitudes contract what they are asked for and return differentiable tensors; its to_numpy is 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

NotImplementedError

cudaq.get_state on the cuqml target

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

RuntimeError

.detach() the argument

On cuqml-tensornet: a kernel that measures, in it, as CUDA-Q’s check reads it as written, or in a kernel it calls, where the measurement runs

NotImplementedError

cudaq.set_target("cuqml")

On cuqml-tensornet: to_numpy(), a NumPy conversion, or a torch function applied to the state itself

RuntimeError

amplitude or amplitudes; or cuqml for the whole state

A basis state that is not bits, or not one bit per qubit

TypeError or ValueError

a string of 0 and 1, or a sequence of 0 and 1, one per qubit

amplitudes handed one string, or an empty sequence

TypeError or ValueError

a list of basis states

A second derivative of the state, on cuqml

RuntimeError

the amplitudes a loss names, on cuqml-tensornet

Forward-mode AD

NotImplementedError

reverse mode

States that do not fit in GPU memory at once

torch.cuda.OutOfMemoryError

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

kernel

a @cudaq.kernel; its mz calls name the qubits reported

*args

the kernel’s arguments, as under Kernel arguments

shots_count

keyword-only positive int; 1000 is the default

explicit_measurements

keyword-only bool, with cudaq.sample’s meaning

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

RuntimeError

.detach() the argument

A shots_count that is not a positive integer

ValueError

a positive int

explicit_measurements=True on a kernel that collapses part-way through, measures a qubit again, measures on after a gate on a measured qubit, or is drawn before any gate has run

NotImplementedError

cudaq.sample(..., explicit_measurements=True) on the cuqml target

explicit_measurements=True on a kernel that computes an angle from its arguments and that CUDA-Q hands the simulator in other gates than it writes, for what is written after the last measurement on a gate and qubit that CUDA-Q hands a rotation of before it — one written there, or the rz it makes of an exp_pauli whose word ends on the qubit: any of the refusals above of lined-up angles, such as rx(c, q) and rx.adj(c, q), or a rotation whose angle has no value for arguments between 0.1 and 3.0, such as rx(np.sqrt(a - 5.0), q); and wherever it is written, an exp_pauli whose word is taken from a captured list or a list argument, or a rotation on a qubit that an element of a captured list or of a list argument picks

ValueError

cudaq.sample(..., explicit_measurements=True) on the cuqml target; or leave out what is written after the last measurement, which CUDA-Q draws nothing from

On cuqml-tensornet: a reset or a collapse part-way through

NotImplementedError

cudaq.set_target("cuqml")

On cuqml-tensornet: more than 63 measured qubits

ValueError

cudaq.sample on cuqml-tensornet, which returns strings

explicit_measurements=True on a kernel with no mz

RuntimeError, in cudaq.sample’s own words

an mz in the kernel

Forward-mode AD

NotImplementedError

the tensor’s primal

On cuqml, not even one row fits in GPU memory: its states, or its shots beside the whole result. On cuqml-tensornet, the draw’s contraction does not fit

torch.cuda.OutOfMemoryError

what the message names

In an accessor: a register_name other than '__global__', a bitstring of the wrong width, or an index outside the measured qubits

ValueError

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

most_probable(register_name)

sample_batch

list[str]

str

str

count(bitstring, register_name)

sample_batch

(batch,) int64

int

int

expectation(register_name)

sample_batch

(batch,) float

float

float

get_marginal_counts(indices, *, register_name)

sample_batch

the same type

the same type

SampleResult

amplitude(basis)

get_state_batch

(batch,) complex

0-dim tensor

complex

amplitudes([basis, ...])

get_state_batch

(batch, k) complex

(k,) complex

list[complex]

to_numpy()

get_state_batch

(batch, 2**n) ndarray

(2**n,) ndarray

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

kernel

a @cudaq.kernel of exactly one list[float], read as inputs then weights, and any fixed arguments, given as args

weight_shape

a positive int, or a tuple of them: the shape of the layer’s weights

observables

a list or tuple of CUDA-Q spin operators, or one operator; one output column each. Or None

amplitudes

keyword-only: a list of basis states whose amplitudes are the output; or None. A layer takes observables or amplitudes, not both

init

keyword-only: a callable applied to the weights in place at construction

diff_method

keyword-only: "adjoint", the default, or "parameter-shift", which needs observables

args

keyword-only: a tuple of the kernel’s other arguments, in its order around its list[float], each one plain value for every row, as cudaq.observe takes it — args=(2,) for block(theta: list[float], layers: int). Empty, the default, for a kernel of one list[float]

x

a torch.Tensor on the GPU at the target’s precision, (*, n_inputs)

Returns a real torch.Tensor, differentiable in the weights and in x:

Constructed with

Output

observables=[...]

(*, n_obs)

amplitudes=[...]

(*, 2k): real and imaginary parts, interleaved

neither

(*, 2**(n+1)): the state, interleaved the same way. On cuqml only

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 list[float] and no float, or args that are not as many as its other arguments

TypeError

observe_batch(kernel, h, x, w) for separate data and weights; args with a value for each of the kernel’s other arguments, in its order

args that is not a tuple, at construction or given later

TypeError

args=(2,) for 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 args changes what the kernel reads

ValueError

a weight_shape and an input width the kernel reads in full

A weight_shape that is not a positive int or a tuple of them

ValueError

a positive size

observables that is empty

ValueError

at least one operator, or None

Both observables and amplitudes

ValueError

one of them

amplitudes as one string, or empty

TypeError or ValueError

a list of basis states

diff_method="parameter-shift" without observables, or a diff_method other than the two

ValueError

the default, "adjoint"

A basis state in amplitudes that is not bits, or not one bit per qubit; found at the first forward, and again where a captured variable or args changes the circuit’s width

TypeError or ValueError

a string of 0 and 1, one per qubit

On cuqml-tensornet: neither observables nor amplitudes

RuntimeError

observables, amplitudes, or cuqml

An input that is not a tensor, has no feature axis, or is on the CPU

TypeError or ValueError

a CUDA tensor (*, n_inputs); move the model with .cuda()

Weights at another precision than the target’s

TypeError

.float() or .double() to match the target

What the call beneath it refuses — observe_batch with observables, get_state_batch without: a kernel that resets; one that measures, with observables, and without them while the inputs or weights require grad; an operator with a complex coefficient, a second derivative, forward-mode AD, what does not fit in memory

as that call raises it

as for that call; without observables, a kernel that measures is evaluated under torch.no_grad()

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 cuqml

On cuqml-tensornet

cudaq.observe(kernel, h, *args), with or without shots_count

cudaq.ObserveResult

supported

supported; a kernel with a reset is refused

cudaq.sample(kernel, *args), with or without explicit_measurements

cudaq.SampleResult

supported

supported where the measurements are drawn as shots; a collapse or a reset is refused

cudaq.get_state(kernel, *args)

cudaq.State, with its amplitude, amplitudes, overlap, num_qubits and to_numpy

supported

refused: use cuqml, or cuqml.get_state_batch(...).amplitudes(...)

cudaq.run(kernel, *args)

a list, one return value per shot

supported

refused: it collapses the state

cudaq.gradients, cudaq.optimizers

CUDA-Q’s own

supported

supported

cudaq.register_operation(name, matrix)

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

cudaq.set_random_seed(seed)

nothing

supported: see Seeding

supported

cudaq.State.from_data(...), or a register started from amplitudes

refused

refused

noise_model=, cudaq.set_noise(...)

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 cuqml nor cuqml-tensornet

RuntimeError

cudaq.set_target("cuqml")

A batched call while CUDA-Q holds a noise model

RuntimeError

cudaq.unset_noise(), or a CUDA-Q target built for noise

A tensor at the other precision

TypeError

cast it, or select the precision with option=

A tensor on the CPU

ValueError

.cuda()

A NumPy array or a list where a tensor is due

TypeError

torch.as_tensor(..., device="cuda") at the target’s dtype

The wrong number of arguments, none of the list[float] and float ones a tensor, or a kernel with none of those

TypeError

the kernel’s own arguments, at least one a tensor; cudaq.observe and its siblings for a kernel whose arguments are all fixed

A tensor for a fixed argument

TypeError

its value, t.item() or t.tolist(); for a value per row, a call per value

Tensors on two devices, batch axes of two sizes, or a tensor with too many axes for its argument

ValueError

one device, one batch size; (n,) or (batch, n) for a list[float], () or (batch,) for a float

Tensors at two dtypes

TypeError

one dtype, the target’s

import torch._dynamo after cudaq was imported before cuqml

ImportError

import cuqml before cudaq