CuQML beside CUDA-Q

This page is one run of docs/src/sample.py at one commit, stamped here.

this run

commit

010193914df48047eddbfe246b5f8c8453d1eedd

dirty

nothing

script_sha256

338764b9f4e54196de9895984021a5ca241fca49d8b16c04be01d3834ac7813c

cuqml

0.1.0

cudaq

CUDA-Q Version amd64-cu13-0.16.0 (https://github.com/NVIDIA/cuda-quantum 62fce8b862302158e0119c65e3ce57538f3af048)

torch

2.12.0+cu130

gpu

NVIDIA GeForce RTX 5090, 32.5 of its 33.7 GB free as the run began

@cudaq.kernel
def block(theta: list[float]):
    q = cudaq.qvector(4)
    for i in range(4):
        ry(theta[i], q[i])                        # four inputs
    for depth in range(2):
        for i in range(3):
            x.ctrl(q[i], q[i + 1])
        for i in range(4):
            rx(theta[4 + 4 * depth + i], q[i])    # then two layers of four weights

@cudaq.kernel
def encode(xs: list[float], w: list[float], scale: float):
    q = cudaq.qvector(4)
    for i in range(4):
        ry(scale * xs[i], q[i])                   # angles computed from the arguments
    for i in range(3):
        x.ctrl(q[i], q[i + 1])
    for i in range(4):
        rz(2.0 * w[i], q[i])
        ry(np.sin(w[i]) * xs[i], q[i])

@cudaq.kernel
def flag() -> bool:                               # a kernel that returns, as cudaq.run takes
    q = cudaq.qubit()
    x(q)
    return mz(q)

def energy(theta):                                # <H> at one row, as cudaq.gradients takes
    return cudaq.observe(block, H, theta).expectation()

H = (cudaq.spin.z(0) * cudaq.spin.z(1) + 0.5 * cudaq.spin.x(2)
     - 0.25 * cudaq.spin.y(1) * cudaq.spin.y(3))
OBS = [cudaq.spin.z(k) for k in range(4)]
torch.manual_seed(SEED)
X = 2 * torch.rand(8, 12, device="cuda") - 1      # eight rows of twelve angles
ROWS = X.double().tolist()                        # the same rows, as cudaq.observe takes them
BITS = [[np.pi * (k >> i & 1) for i in range(4)] + [0.0] * 8 for k in (1, 2, 5, 11)]
XB = torch.tensor(BITS, device="cuda")            # four rows of `block` with one outcome each
print("X:", describe(X), "| XB:", describe(XB))
X: Tensor (8, 12) float32 on cuda | XB: Tensor (4, 12) float32 on cuda

Legend. A block of code is a cell of that script as it ran, then what it printed; a table of results was printed by the same run, and only the table of what is not done is written by hand. An id names one thing the run did or one place on the page: chk- a check against CUDA-Q, or against what its line names, or a plain fact of the run; ref- a refusal provoked on purpose; prb- a probe, printed whatever its outcome; not- a row of what is not done; call- an entry. In a cell’s output ok opens a record that held and no mark a probe; a check ends in the largest difference, the bar, and where in verify/ the bar was read, or in equal or holds; an exception is its type, names cuqml where its text holds the word, then its text. An entry says what is the same as the CUDA-Q call beside it and what differs, runs the calls that work, then each wrong call with what it raised and the right call. Helpers, bars, seed, shot count and configurations are in the last section, the script’s imports with the import orders (ref-import-order). A repository file name — alone, or followed by › and a heading or by :: and a name — is a citation at the stamped commit: the page points there and does not restate it.

Find, by what you want or by name:

To reproduce this run, build the engine as README.md › Install describes; how it works is docs/how-it-works.md; every speed, its losing cells and how to quote one are benchmarks/README.md; the state vector’s gate list is the output of verify/gate_support.py. The checks on this page are illustrations at small sizes on one machine; the standing evidence is docs/procedure.md › A4. The scripts.

1 · What was added

Each CUDA-Q call you already have, beside what to write instead and what each returned in this run. Every name in a row is the example’s; the last column is what to watch for, by id.

you have, run here on qpp-cpu

write instead

what each returned, the second on cuqml

largest difference on cuqml

on cuqml-tensornet

watch for

[cudaq.observe(block, H, row).expectation() for row in ROWS]

cuqml.observe_batch(block, H, X)

list of 8 float → Tensor (8,) float32 on cuda

4.9e-07 <= 2e-04

1.4e-07 <= 1e-05

—

cudaq.observe(block, OBS[0], ROWS[0], shots_count=SHOTS).expectation()

cuqml.observe_batch(block, OBS[0], X, shots_count=SHOTS)

float 0.711 → Tensor (8,) float32 on cuda

—

—

ref-shots-grad

cudaq.gradients.ParameterShift().compute(ROWS[0], energy, energy(ROWS[0]))

torch.autograd.functional.jacobian(lambda x: cuqml.observe_batch(block, H, x), X[0])

list of 12 float → Tensor (12,) float32 on cuda

3.3e-07 <= 2e-03

3.0e-08 <= 2e-03

chk-two-term-off

cudaq.optimizers.Adam()

torch.optim.Adam([torch.nn.Parameter(X[0])])

Adam → Adam

—

—

—

[cudaq.get_state(block, row) for row in ROWS]

cuqml.get_state_batch(block, X)

list of 8 State → BatchState (8, 16) complex64 on cuda

2.2e-07 <= 2e-04

returns a BatchNetworkState

ref-tn-whole-state

[cudaq.get_state(block, row).amplitude('0111') for row in ROWS]

cuqml.get_state_batch(block, X).amplitude('0111')

list of 8 complex → Tensor (8,) complex64 on cuda

2.9e-08 <= 2e-04

6.5e-08 <= 1e-05

—

[list(cudaq.sample(block, row, shots_count=8)) for row in BITS]

cuqml.sample_batch(block, XB, shots_count=8)

list of 4 list → BatchSampleResult (4, 8) int64 on cuda

equal

equal

ref-sample-grad

[cudaq.sample(block, row, shots_count=8).most_probable() for row in BITS]

cuqml.sample_batch(block, XB, shots_count=8).most_probable()

list of 4 str → list of 4 str

equal

equal

—

cudaq.set_random_seed(SEED)

cudaq.set_random_seed(SEED)

None → None

—

—

prb-seed-before-target

cudaq.set_target("nvidia", option="fp64")

cudaq.set_target("cuqml", option="fp64")

nvidia at fp64 → cuqml at fp64

—

—

ref-layer-dtype

cudaq.set_target("tensornet")

cudaq.set_target("cuqml-tensornet", option="fp64")

tensornet at fp64 → cuqml-tensornet at fp64

—

—

ref-layer-dtype

cudaq.register_operation("hadamard", np.array([1, 1, 1, -1]) / 2 ** 0.5)

cudaq.register_operation("hadamard", np.array([1, 1, 1, -1]) / 2 ** 0.5)

None → None

—

—

ref-nonunitary

cudaq.run(flag, shots_count=4)

cudaq.run(flag, shots_count=4)

list of 4 bool → list of 4 bool

equal

refused: ref-tn-run

ref-tn-run

[[cudaq.observe(block, o, row[:4] + ROWS[0][4:]).expectation() for o in OBS] for row in ROWS[:2]]

cuqml.TorchLayer(block, (2, 4), OBS, init=lambda w: w.copy_(X[0, 4:].view(2, 4))).cuda()(X[:2, :4])

list of 2 list → Tensor (2, 4) float32 on cuda, requires grad

4.4e-07 <= 2e-04

9.8e-08 <= 1e-05

ref-layer-dtype

Held identical to CUDA-Q on cuqml, each by the check named: qubit order verify/gate_support.py, global phase verify/equivalence.py::check_get_state_phase, basis-state order verify/equivalence.py::check_amplitude, sample-key order verify/sampling.py::check_convention, the meaning of shots_count verify/equivalence.py::check_shots_non_positive_is_exact, parity sign verify/equivalence.py::check_sample_expectation, a measuring kernel’s refusal verify/equivalence.py::check_observe_measured. On cuqml-tensornet, values, amplitudes with their phase and shots are held to CUDA-Q by verify/tensornet.py::check_gates, verify/tensornet.py::check_amplitudes and verify/tensornet.py::check_sampling. The same additions by capability, not by call: README.md › What cuqml adds.

2 · What is not done

Not all of it: docs/known-limits.md lists more. Each row ends where the repository records it, in the repository’s own word where it gives one. refused: it raises, with the message under the id where this run provoked it; absent: cuqml has neither a name nor a refusal of its own for it; elsewhere: CUDA-Q does it and cuqml adds nothing.

id

not done

status

reach for instead

shown by the run

recorded in

not-circuit-api

a circuit API

absent

@cudaq.kernel

chk-surface-names

README.md › What comes from CUDA-Q unchanged

not-run-batch

a batched cudaq.run

absent

cudaq.run on cuqml

ref-absent-name

docs/known-limits.md

not-optimisers

optimisers of its own

absent

torch.optim

chk-surface-names, chk-app-loss-fell

README.md › observe_batch

not-argument-types

a value per row for a fixed argument, such as an int; the types the cited section refuses

refused

a call per value; a capture from Python

ref-kernel-argument-type

docs/api.md › Kernel arguments

not-angle-forms

angle arithmetic with no derivative

refused

compute it in torch

ref-angle-arithmetic

verify/angles.py::check_refusals

not-gradient-of-a-draw

a gradient of samples, of a shot estimate, of a collapse

refused

a shots_count that is exact; .detach()

ref-shots-grad, ref-sample-grad; the collapse cited only

README.md › sample_batch; verify/equivalence.py::check_measured_refuses_grad

not-second-derivative

second derivatives, state vector

refused

cuqml-tensornet

ref-second-derivative

verify/gradients.py::check_second_derivative_refused; verify/tensornet.py::check_second_derivatives

not-matrix-angle

state vector: a rotation or u3 under five or more controls, with its angle from an argument

refused

cuqml-tensornet

ref-matrix-angle

verify/angles.py::check_angle_held_by_a_matrix

not-nonunitary

a non-unitary custom operation

refused

—

ref-nonunitary

docs/api.md › Custom operations

not-custom-shapes

state vector: a custom operation on more targets or under more controls than the cited section lists

refused

—

cited only

docs/api.md › Custom operations

not-state-init

a state from the caller’s amplitudes

refused

qpp-cpu, nvidia

ref-state-init

README.md › What comes from CUDA-Q unchanged

not-noise

noise

refused

CUDA-Q’s own targets

ref-noise

docs/api.md › Noise

not-conversion

casting a tensor for the caller

refused

cast at the boundary; option=

ref-layer-dtype

verify/fp64.py::check_refusals

not-device

moving a tensor to the GPU for the caller

refused

.cuda()

prb-cpu-tensor, prb-layer-on-cpu

verify/arguments.py::check_boundary_refusals

not-spill-or-slice

what does not fit — one row, a batch of whole states, a contraction: no host spill, no sliced contraction; a batch of expectation values or of shots on the state vector runs in slices (verify/gradients.py::check_oversized_observe, verify/sampling.py::check_slices)

refused

what the message names

ref-memory-width, ref-memory-batch, ref-memory-depth

verify/gradients.py::check_oversized_remedy; verify/tensornet.py::check_refusal_remedies

not-auto-target

choosing the engine by qubit count

absent

name the target

ref-memory-width

README.md › The tensor-network target

not-cpu

CPU execution

absent

qpp-cpu

the targets table at call-targets

cuqml/cute/cuqml.yml

not-many-gpus

several GPUs

absent

—

cited only

docs/known-limits.md

not-tn-whole-state

tensor network: the whole state

refused

cuqml

ref-tn-whole-state, ref-tn-layer-state, ref-tn-get-state

README.md › The tensor-network target

not-tn-collapse

tensor network: a collapse in a kernel

refused

cuqml

ref-tn-run

verify/tensornet.py::check_torch_refusals

not-tn-wide-outcomes

tensor network: outcomes wider than one int64

refused

cudaq.sample there

cited only

verify/tensornet.py::check_torch_refusals

not-tn-not-built

tensor network: approximation, and the cited “Not built” list

absent

—

cited only, not rewritten

docs/api.md › The tensor-network target

not-more-accessors

the rest of State and SampleResult

absent

torch on the tensor

chk-surface-accessors

README.md › Result accessors

not-faster-elsewhere

being faster where there is nothing to add

elsewhere

nvidia, tensornet

nothing refused

README.md › Benchmarks, no number restated

3 · Package, targets, the surface at a glance

call-targets · Everything reached before a kernel is called: the surface as Python reports it, the four configurations, each call on each of them, CUDA-Q’s nvidia and tensornet describing themselves, the import orders (ref-import-order, ref-import-unseen), and what does not fit.

print("dir(cuqml):", dir(cuqml))
tripwire("chk-surface-names", "the public names are the four this page has an entry for",
         dir(cuqml) == ["TorchLayer", "get_state_batch", "observe_batch", "sample_batch"])
for name in dir(cuqml):
    print(f"cuqml.{name}{inspect.signature(getattr(cuqml, name))}")
print(f"cuqml.TorchLayer.forward{inspect.signature(cuqml.TorchLayer.forward)}")
for call in (cuqml.observe_batch, cudaq.observe):
    default = inspect.signature(call).parameters["shots_count"].default
    print(f"shots_count={default} is the default of {call.__module__.split('.')[0]}."
          f"{call.__name__}")
refuse("ref-absent-name", lambda: cuqml.run_batch, ("cuqml",))
print("importlib.metadata.version('cuqml'):", importlib.metadata.version("cuqml"))
accessors = {}
for target in ("cuqml", "cuqml-tensornet"):
    use(target)
    for result in (cuqml.get_state_batch(block, X), cuqml.sample_batch(block, X)):
        accessors[type(result).__name__] = sorted(
            name for name, member in vars(type(result)).items()
            if callable(member) and name[0] != "_")
        print(f"on {target}: {type(result).__name__} adds",
              accessors[type(result).__name__])
state, outcomes = ["amplitude", "amplitudes", "to_numpy"], [
    "count", "expectation", "get_marginal_counts", "most_probable"]
tripwire("chk-surface-accessors", "the accessors found are the ones the entries cover",
         accessors == {"BatchState": state, "BatchSampleResult": outcomes,
                       "BatchNetworkState": state})
layer = cuqml.TorchLayer(block, (2, 4), OBS)
print("a layer holds:", [name for name in vars(layer) if name[0] != "_"],
      "and the parameters", [name for name, _ in layer.named_parameters()])
dir(cuqml): ['TorchLayer', 'get_state_batch', 'observe_batch', 'sample_batch']
ok   chk-surface-names: the public names are the four this page has an entry for
cuqml.TorchLayer(kernel, weight_shape: 'int | tuple[int, ...]', observables=None, *, amplitudes=None, init=None, diff_method: 'str' = 'adjoint', args: 'tuple' = ()) -> 'None'
cuqml.get_state_batch(kernel, *args) -> 'torch.Tensor | BatchNetworkState'
cuqml.observe_batch(kernel, hamiltonian, *args, shots_count: 'int' = 0, diff_method: 'str' = 'adjoint') -> 'torch.Tensor'
cuqml.sample_batch(kernel, *args, shots_count: 'int' = 1000, explicit_measurements: 'bool' = False) -> 'torch.Tensor'
cuqml.TorchLayer.forward(self, x: 'torch.Tensor') -> 'torch.Tensor'
shots_count=0 is the default of cuqml.observe_batch
shots_count=-1 is the default of cudaq.observe
ok   ref-absent-name: AttributeError, names cuqml: module 'cuqml' has no attribute 'run_batch'
importlib.metadata.version('cuqml'): 0.1.0
on cuqml: BatchState adds ['amplitude', 'amplitudes', 'to_numpy']
on cuqml: BatchSampleResult adds ['count', 'expectation', 'get_marginal_counts', 'most_probable']
on cuqml-tensornet: BatchNetworkState adds ['amplitude', 'amplitudes', 'to_numpy']
on cuqml-tensornet: BatchSampleResult adds ['count', 'expectation', 'get_marginal_counts', 'most_probable']
ok   chk-surface-accessors: the accessors found are the ones the entries cover
a layer holds: ['training', 'kernel', 'observables', 'amplitudes', 'diff_method', 'n_qubits'] and the parameters ['weights']

cudaq.set_target(...)

name

simulator

precision

observe_batch

get_state_batch

sample_batch

TorchLayer

"cuqml"

cuqml

cuqml_sv_fp32

fp32

Tensor (8,) float32 on cuda

BatchState (8, 16) complex64 on cuda

BatchSampleResult (8, 1000) int64 on cuda

Tensor (8, 4) float32 on cuda, requires grad

"cuqml", option="fp64"

cuqml

cuqml_sv_fp64

fp64

Tensor (8,) float64 on cuda

BatchState (8, 16) complex128 on cuda

BatchSampleResult (8, 1000) int64 on cuda

Tensor (8, 4) float64 on cuda, requires grad

"cuqml-tensornet"

cuqml-tensornet

cuqml_tn_fp32

fp32

Tensor (8,) float32 on cuda

BatchNetworkState

BatchSampleResult (8, 1000) int64 on cuda

Tensor (8, 4) float32 on cuda, requires grad

"cuqml-tensornet", option="fp64"

cuqml-tensornet

cuqml_tn_fp64

fp64

Tensor (8,) float64 on cuda

BatchNetworkState

BatchSampleResult (8, 1000) int64 on cuda

Tensor (8, 4) float64 on cuda, requires grad

A cell of the next table is the largest difference from CUDA-Q on qpp-cpu and its bar, or the id of the refusal met there.

call

cuqml fp32

cuqml fp64

cuqml-tensornet fp32

cuqml-tensornet fp64

cuqml.observe_batch(encode, H, xs, w, scale)

3.0e-07 <= 2e-04

4.4e-16 <= 1e-10

1.8e-07 <= 1e-05

4.4e-16 <= 1e-10

its gradient in xs, w and scale, by .sum().backward()

9.4e-08 <= 2e-03

2.1e-09 <= 2e-03

9.5e-08 <= 2e-03

2.1e-09 <= 2e-03

the same with diff_method='parameter-shift'

1.9e-07 <= 2e-03

2.1e-09 <= 2e-03

1.1e-07 <= 2e-03

2.1e-09 <= 2e-03

cuqml.observe_batch(encode, OBS[0], xs, w, scale, shots_count=SHOTS), on identical rows

2.1e-03 <= 2e-02

2.1e-03 <= 2e-02

2.1e-03 <= 2e-02

2.1e-03 <= 2e-02

cuqml.get_state_batch(encode, xs, w, scale).to_numpy()

1.4e-07 <= 2e-04

1.1e-16 <= 1e-10

refused: ref-tn-whole-state

refused: ref-tn-whole-state

its .amplitudes(['0111', '0000'])

1.4e-07 <= 2e-04

1.1e-16 <= 1e-10

1.1e-07 <= 1e-05

2.5e-16 <= 1e-10

a gradient in xs through those amplitudes

2.1e-08 <= 2e-03

2.2e-10 <= 2e-03

5.6e-09 <= 2e-03

2.2e-10 <= 2e-03

cuqml.sample_batch(encode, xs, w, scale, shots_count=SHOTS).expectation()

3.3e-02 <= 6e-02

1.1e-02 <= 6e-02

1.2e-02 <= 5e-02

2.6e-02 <= 6e-02

cuqml.TorchLayer(block, (2, 4), OBS)(xs)

4.4e-07 <= 2e-04

3.9e-16 <= 1e-10

1.5e-07 <= 1e-05

4.4e-16 <= 1e-10

its gradient in xs and in the layer’s weights

7.4e-07 <= 2e-03

2.2e-15 <= 2e-03

2.2e-07 <= 2e-03

1.3e-15 <= 2e-03

cuqml.TorchLayer(block, (2, 4), amplitudes=['0111', '0000'])(xs)

2.2e-07 <= 2e-04

4.2e-17 <= 1e-10

1.1e-07 <= 1e-05

1.1e-16 <= 1e-10

cuqml.TorchLayer(block, (2, 4))(xs)

2.2e-07 <= 2e-04

1.1e-16 <= 1e-10

refused: ref-tn-layer-state

refused: ref-tn-layer-state

a second derivative of cuqml.observe_batch(block, H, theta) at fp64, by torch.autograd.gradgradcheck

—

refused: ref-second-derivative

—

holds

cudaq.set_target(...), no option

simulator

precision

"nvidia"

custatevec_fp32

fp32

"tensornet"

tensornet

fp64

OPTIMISER = "torch.optim.Adam([torch.nn.Parameter(torch.zeros(1))])"
child("ref-import-order", f"import cudaq, torch; import cuqml; {OPTIMISER}", ("cuqml",))
child("ref-import-unseen", f"import cudaq; import cuqml; import torch; {OPTIMISER}",
      ("cuqml",))
print("cuqml first, the order that works, builds", child(
    None, f"import cuqml; import cudaq, torch; print(type({OPTIMISER}).__name__)").strip())
print("this script's own:", "; ".join(
    line.split("  #")[0] for line in LINES if line.startswith("import ")
    and line.split()[1].split(".")[0] not in sys.stdlib_module_names))
PLAIN = """
    import cudaq                                         # cuqml is never imported

    @cudaq.kernel
    def pair(theta: float):
        q = cudaq.qvector(2)
        ry(theta, q[0])
        x.ctrl(q[0], q[1])

    for target in ("cuqml", "qpp-cpu"):
        cudaq.set_target(target)
        print(cudaq.observe(pair, cudaq.spin.z(0) + cudaq.spin.x(1), 0.4).expectation())"""
on_cuqml, on_qpp = map(float, child(None, PLAIN).split())
check("chk-plain-no-import", "cudaq.observe on cuqml, in a script that never imports "
      "cuqml, against the same script's on qpp-cpu", on_cuqml, on_qpp, VALUE["cuqml-fp32"],
      against="qpp-cpu, in the same child")
ok   ref-import-order: exit status 1; stderr ends: ImportError: cuqml: torch._dynamo cannot be imported after cudaq. It loads triton, and triton's LLVM on top of CUDA-Q's aborts the process. torch asks for it lazily -- constructing an optimiser is enough -- so import cuqml before cudaq, in a new process: that loads it while it is still safe.
ok   ref-import-unseen: exit status 1; stderr ends: ImportError: cuqml: torch._dynamo cannot be imported after cudaq. It loads triton, and triton's LLVM on top of CUDA-Q's aborts the process. torch asks for it lazily -- constructing an optimiser is enough -- so import cuqml before cudaq, in a new process: that loads it while it is still safe.
cuqml first, the order that works, builds Adam
this script's own: import cuqml; import cudaq; import numpy as np; import torch
ok   chk-plain-no-import: cudaq.observe on cuqml, in a script that never imports cuqml, against the same script's on qpp-cpu: 4.5e-08 <= 2e-04 (verify/equivalence.py TOL)

@cudaq.kernel
def wide(theta: list[float]):                     # 40 qubits: 40 inputs, then 40 weights
    q = cudaq.qvector(40)
    for i in range(40):
        ry(theta[i], q[i])
        rz(theta[40 + i], q[i])
    for i in range(39):
        x.ctrl(q[i], q[i + 1])

@cudaq.kernel
def mid(theta: list[float]):                      # 20 qubits
    q = cudaq.qvector(20)
    for i in range(20):
        ry(theta[i], q[i])
    for i in range(19):
        x.ctrl(q[i], q[i + 1])

@cudaq.kernel
def brick(theta: list[float]):                    # 60 qubits, 60 layers deep
    q = cudaq.qvector(60)
    for depth in range(60):
        for i in range(60):
            ry(theta[i], q[i])
        for i in range(depth % 2, 59, 2):
            x.ctrl(q[i], q[i + 1])

use("cuqml")
XW = 2 * torch.rand(2, 80, device="cuda") - 1
refuse("ref-memory-width", lambda: cuqml.get_state_batch(wide, XW),
       ("cuqml", "qubit count"))
print("fewer qubits:", describe(cuqml.get_state_batch(mid, XW[:, :20])))
use("cuqml-tensornet")                            # or the same width on the other target
print("the other target:", describe(
    cuqml.get_state_batch(wide, XW).amplitudes(["0" * 40, "1" * 40])))
use("cuqml")
free, total = torch.cuda.mem_get_info()           # bytes, at this moment
print(f"free at this moment: {free / 1e9:.1f} of {total / 1e9:.1f} GB; selecting CUDA-Q's "
      f"`tensornet` in the cell `map` took {TOOK['target-wide'] / 1e9:.1f} GB of the card")
state = torch.complex64.itemsize * 2 ** 20        # the bytes of one 20-qubit state
XM = torch.zeros(1 + total // state, 20, device="cuda")    # more than the whole card holds
refuse("ref-memory-batch", lambda: cuqml.get_state_batch(mid, XM),
       ("cuqml", "reduce the batch"))
parts = XM.split(max(1, free // 32 // state))     # a thirty-second of what is free, a part
print(f"the {len(XM)} rows, in {len(parts)} smaller batches:", describe(torch.cat(
    [cuqml.get_state_batch(mid, part).amplitude("0" * 20).abs() ** 2 for part in parts])))
use("cuqml-tensornet")
refuse("ref-memory-depth", lambda: cuqml.observe_batch(brick, cudaq.spin.z(30), XW[:, :60]),
       ("cuqml", "depth"))
print("a shallow circuit:", describe(cuqml.observe_batch(wide, cudaq.spin.z(30), XW)))
ok   ref-memory-width: torch.OutOfMemoryError (RuntimeError), names cuqml: cuqml.get_state_batch: 40 qubits x batch 2 needs about 52776.56 GB, and only 11.25 GB may be claimed, 70% of the 16.07 GB free or cached of 33.67 GB. cuqml does not spill to host memory (neither does the nvidia target by default), so reduce the qubit count: a smaller batch cannot help, one row alone needing about 26388.28 GB.
fewer qubits: BatchState (2, 1048576) complex64 on cuda
the other target: Tensor (2, 2) complex64 on cuda
free at this moment: 16.0 of 33.7 GB; selecting CUDA-Q's `tensornet` in the cell `map` took 16.2 GB of the card
ok   ref-memory-batch: torch.OutOfMemoryError (RuntimeError), names cuqml: cuqml.get_state_batch: 20 qubits x batch 4014 needs about 101.02 GB, and only 11.25 GB may be claimed, 70% of the 16.07 GB free or cached of 33.67 GB. cuqml does not spill to host memory (neither does the nvidia target by default), so reduce the batch or the qubit count.
the 4014 rows, in 69 smaller batches: Tensor (4014,) float32 on cuda
ok   ref-memory-depth: torch.OutOfMemoryError (RuntimeError), names cuqml: cuqml.observe_batch: contracting this observable's 1 term(s) at batch 2 needs about 3.19e+15 GB for its largest term, and only 11.2 GB may be claimed, 70% of the 16.1 GB free or cached of 33.7 GB. cuqml-tensornet does not slice a contraction to fit, so reduce the circuit's depth around the terms: a smaller batch cannot help, its largest term needing about 1.6e+15 GB for one row.
a shallow circuit: Tensor (2,) float32 on cuda

Why there are two precisions, what the second target is for, and where CUDA-Q’s own stays the right tool: docs/api.md › Precision, README.md › The tensor-network target. Selection is pinned by verify/fp64.py::check_selection and verify/tensornet.py::check_selection; measured in benchmarks/README.md › tensornet_sweep.py and benchmarks/README.md › fp64.

4 · Kernel arguments beside cudaq.observe’s

call-arguments · How a kernel’s arguments are passed. Beside CUDA-Q:

@cudaq.kernel
def sized(n: int, theta: list[float]):
    q = cudaq.qvector(n)
    for i in range(n):
        ry(theta[i], q[i])
    for i in range(n - 1):
        x.ctrl(q[i], q[i + 1])

@cudaq.kernel
def ceil_angle(theta: list[float]):               # a step: an angle with no derivative
    q = cudaq.qubit()
    ry(np.ceil(theta[0] / 4.0), q)

use("cuqml")
xs, w = X[:, :4], X[0, 4:8]                       # eight rows of data, one row of weights
for scale in (0.5, torch.tensor(0.5, device="cuda"), torch.full((8,), 0.5, device="cuda")):
    print(f"xs (8, 4), w (4,), scale {describe(scale)}:",
          describe(cuqml.observe_batch(encode, H, xs, w, scale)))
print("xs (4,), no batch axis:", describe(cuqml.observe_batch(encode, H, xs[0], w, 0.5)))
shared = w.clone().requires_grad_()
cuqml.observe_batch(encode, H, xs[:2], shared, 0.5).sum().backward()
with reference("qpp-cpu"):
    central, weights = cudaq.gradients.CentralDifference(), ROWS[0][4:8]
    exact = [cudaq.observe(encode, H, row[:4], weights, 0.5).expectation() for row in ROWS]
    costs = [lambda v, row=row: cudaq.observe(encode, H, row[:4], v, 0.5).expectation()
             for row in ROWS[:2]]
    summed = sum(np.array(central.compute(weights, cost, cost(weights))) for cost in costs)
    sizes = [cudaq.observe(sized, H, 4, row[:4]).expectation() for row in ROWS]
check("chk-arguments-values", "eight rows against cudaq.observe, row by row",
      cuqml.observe_batch(encode, H, xs, w, 0.5), exact, VALUE["cuqml-fp32"])
check("chk-arguments-shared", "the gradient of w, shared by two rows, against "
      "CentralDifference summed over them", shared.grad, summed, GRADIENT)
check("chk-arguments-fixed", "the int n=4, one value for every row, beside eight rows "
      "against cudaq.observe, row by row", cuqml.observe_batch(sized, H, 4, xs), sizes,
      VALUE["cuqml-fp32"])
probe("prb-one-vector", lambda: "X[:, 0], of shape (8,), is one row of eight angles and "
      "not eight rows: " + describe(cuqml.observe_batch(encode, H, X[:, 0], w, 0.5)))

def unread():                                     # twice the columns `encode` reads
    doubled = torch.cat([xs, xs], dim=1).requires_grad_()
    cuqml.observe_batch(encode, H, doubled, w, 0.5).sum().backward()
    return ("xs with twice the columns encode reads: the largest gradient of the unread "
            f"ones is {doubled.grad[:, 4:].abs().max().item()}")

probe("prb-unread-columns", unread)
probe("prb-integer-in-float-slot", lambda: "a last positional 100 is scale, the kernel's "
      "float argument, and no shot count: equal to scale=100.0, " + str(torch.equal(
          cuqml.observe_batch(encode, H, xs, w, 100),
          cuqml.observe_batch(encode, H, xs, w, 100.0))))
cudaq.set_target("qpp-cpu")
refuse("ref-wrong-target", lambda: cuqml.observe_batch(encode, H, xs, w, 0.5), ("cuqml",))
cudaq.set_target("cuqml")
refuse("ref-kernel-argument-type",                # n a value per row, as a tensor
       lambda: cuqml.observe_batch(sized, H, torch.full((8,), 4, device="cuda"), xs),
       ("cuqml", "fixed"))
refuse("ref-angle-arithmetic", lambda: cuqml.observe_batch(ceil_angle, OBS[0], xs),
       ("cuqml",))
print("the arithmetic in torch:", describe(cuqml.observe_batch(block, H, torch.ceil(X))))
child("prb-cpu-tensor", """
    import cuqml
    import cudaq, torch

    @cudaq.kernel
    def one(theta: list[float]):
        q = cudaq.qubit()
        ry(theta[0], q)

    cudaq.set_target("cuqml")
    print(cuqml.observe_batch(one, cudaq.spin.z(0), torch.zeros(2, 1)))""")
xs (8, 4), w (4,), scale float 0.5: Tensor (8,) float32 on cuda
xs (8, 4), w (4,), scale Tensor () float32 on cuda, 0.5: Tensor (8,) float32 on cuda
xs (8, 4), w (4,), scale Tensor (8,) float32 on cuda: Tensor (8,) float32 on cuda
xs (4,), no batch axis: Tensor () float32 on cuda, 0.821973
ok   chk-arguments-values: eight rows against cudaq.observe, row by row: 3.0e-07 <= 2e-04 (verify/equivalence.py TOL)
ok   chk-arguments-shared: the gradient of w, shared by two rows, against CentralDifference summed over them: 9.4e-08 <= 2e-03 (verify/gradients.py TOL)
ok   chk-arguments-fixed: the int n=4, one value for every row, beside eight rows against cudaq.observe, row by row: 2.4e-07 <= 2e-04 (verify/equivalence.py TOL)
     prb-one-vector: no error; X[:, 0], of shape (8,), is one row of eight angles and not eight rows: Tensor () float32 on cuda, 0.767516
     prb-unread-columns: no error; xs with twice the columns encode reads: the largest gradient of the unread ones is 0.0
     prb-integer-in-float-slot: no error; a last positional 100 is scale, the kernel's float argument, and no shot count: equal to scale=100.0, True
ok   ref-wrong-target: RuntimeError, names cuqml: cuqml's torch surface runs on the cuqml and cuqml-tensornet targets, but the active target is 'qpp-cpu' ('qpp'). Call cudaq.set_target("cuqml").
ok   ref-kernel-argument-type: TypeError, names cuqml: cuqml.observe_batch: argument 0 of kernel 'sized' is int, a fixed argument: one value for every row, the circuit captured at it, and no gradient. It takes one plain value, as cudaq.observe takes it; got a torch.Tensor, which is not converted. Pass its value, t.item() or t.tolist(); for a value per row, call once per value with the rows that share it.
ok   ref-angle-arithmetic: ValueError, names cuqml: cuqml: kernel 'ceil_angle' computes the angle of at least one gate from its arguments, and that arithmetic could not be lifted into torch: the angle of parametric gate 0 is computed through 'math.ceil', which has no translation into torch here. Compute it in torch instead and pass the result in, where it stays differentiable.
the arithmetic in torch: Tensor (8,) float32 on cuda
     prb-cpu-tensor: exit status 1; stderr ends: ValueError: cuqml.observe_batch: the engine runs on the GPU, so it takes CUDA tensors, torch.float32 at this target's precision; got a cpu tensor. Move it with .cuda(), or create it with device="cuda".

Read more. How a kernel’s arithmetic becomes torch: docs/how-it-works.md › From a CUDA-Q kernel to a differentiable program. The other argument refusals are pinned by verify/arguments.py::check_refusals; a batch past the launch limit by verify/large_batch.py; measured in benchmarks/README.md › kernel_form_sweep.py.

5 · cuqml.observe_batch beside cudaq.observe

call-observe-batch · Beside cudaq.observe and cudaq.gradients. Beside CUDA-Q:

  • same — the argument order and CUDA-Q’s own operator (chk-arguments-values); what shots_count means (verify/equivalence.py::check_shots_non_positive_is_exact); a measuring kernel refused in cudaq.observe’s own words: ref-measured-observe, chk-measured-words

  • differs — the result is a tensor with a batch axis and an autograd edge (chk-app-batch, chk-app-gradient); diff_method chooses between two gradients that agree (chk-grad-controlled); a gradient of a shot estimate is refused: ref-shots-grad

  • differs deliberately — through a controlled rotation both gradients agree with CentralDifference, where CUDA-Q’s ParameterShift does not: chk-grad-crx, chk-two-term-off; a called kernel’s measurement, which cudaq.observe collapses call by call, is refused: verify/equivalence.py::check_called_measurement_refused

@cudaq.kernel
def gates(theta: list[float]):
    q = cudaq.qvector(4)
    for i in range(4):
        ry(theta[i], q[i])
    rz(theta[4], q[1])
    r1(theta[5], q[2])
    u3(theta[6], theta[7], theta[8], q[3])
    y.ctrl(q[0], q[1])
    h.ctrl(q[1], q[2])
    s.ctrl(q[2], q[3])
    t.ctrl(q[3], q[0])
    x.ctrl(q[3], q[2], q[1], q[0])                # three controls, listed downwards
    swap.ctrl(q[3], q[0], q[1])
    rx(theta[9], q[0])
    ry(theta[10], q[1])
    rz(theta[11], q[2])

@cudaq.kernel
def crot(theta: list[float]):
    q = cudaq.qvector(4)
    for i in range(4):
        ry(theta[i], q[i])
    rx.ctrl(theta[4], q[0], q[1])
    ry.ctrl(theta[5], q[1], q[2])
    rz.ctrl(theta[6], q[2], q[3])

def slopes(kernel, operator, rows, method="adjoint"):
    """Each row's gradient of the expectation, by cuqml on the active target."""
    leaf = rows.clone().requires_grad_()
    cuqml.observe_batch(kernel, operator, leaf, diff_method=method).sum().backward()
    return leaf.grad

def cudaq_slopes(rule, kernel, operator, rows):
    """The same from one of CUDA-Q's own rules, on the active target."""
    def cost(theta):
        return cudaq.observe(kernel, operator, theta).expectation()
    return np.array([rule.compute(row, cost, cost(row)) for row in rows])

BASIS = [format(k, "04b") for k in range(16)]
states, through_gates, through_crot = [], [], []
for target in ("cuqml", "cuqml-tensornet"):
    use(target)
    states.append(cuqml.get_state_batch(gates, X[:2]).amplitudes(BASIS))
    for method in ("adjoint", "parameter-shift"):
        through_gates.append(slopes(gates, H, X[:2], method))
        through_crot.append(slopes(crot, H, X[:2, :7], method))
with reference("qpp-cpu"):
    shift, central = cudaq.gradients.ParameterShift(), cudaq.gradients.CentralDifference()
    exact = [cudaq.get_state(gates, row).amplitudes(BASIS) for row in ROWS[:2]]
    gates_shift = cudaq_slopes(shift, gates, H, ROWS[:2])
    crot_central = cudaq_slopes(central, crot, H, [row[:7] for row in ROWS[:2]])
    crot_shift = cudaq_slopes(shift, crot, H, [row[:7] for row in ROWS[:2]])
FIXED = "y, h, s and t under one control, x under three listed downwards and a controlled swap"
check("chk-state-controlled", f"the state after {FIXED}, on both targets, against "
      "cudaq.get_state", states, [exact] * 2, [VALUE["cuqml-fp32"], VALUE["tn-fp32"]])
check("chk-grad-controlled", f"the gradient through {FIXED}, on both targets by both "
      "methods, against cudaq.gradients.ParameterShift", through_gates, [gates_shift] * 4,
      GRADIENT)
check("chk-grad-crx", "the gradient through rx, ry and rz under a control, on both targets "
      "by both methods, against cudaq.gradients.CentralDifference", through_crot,
      [crot_central] * 4, GRADIENT)
off = float(np.abs(crot_shift - crot_central).max())
check("chk-two-term-off", "through rx, ry and rz under a control, cudaq.gradients."
      f"ParameterShift is {off:.1e} from CentralDifference, past the bar of {GRADIENT[0]:.0e}",
      off > GRADIENT[0], True, against="cudaq.gradients.CentralDifference on qpp-cpu")
ok   chk-state-controlled: the state after y, h, s and t under one control, x under three listed downwards and a controlled swap, on both targets, against cudaq.get_state: 7.4e-08 <= 1e-05 (verify/equivalence.py TOL; verify/tensornet.py BAR['fp32'])
ok   chk-grad-controlled: the gradient through y, h, s and t under one control, x under three listed downwards and a controlled swap, on both targets by both methods, against cudaq.gradients.ParameterShift: 1.5e-07 <= 2e-03 (verify/gradients.py TOL)
ok   chk-grad-crx: the gradient through rx, ry and rz under a control, on both targets by both methods, against cudaq.gradients.CentralDifference: 1.2e-07 <= 2e-03 (verify/gradients.py TOL)
ok   chk-two-term-off: through rx, ry and rz under a control, cudaq.gradients.ParameterShift is 1.7e-02 from CentralDifference, past the bar of 2e-03: holds

@cudaq.kernel
def measured(theta: list[float]):
    q = cudaq.qvector(3)
    ry(theta[0], q[0])
    x.ctrl(q[0], q[1])
    mz(q)

@cudaq.kernel
def ccry(theta: list[float]):                     # ry under two controls
    q = cudaq.qvector(3)
    h(q[0])
    h(q[1])
    ry.ctrl(theta[0], q[0], q[1], q[2])

@cudaq.kernel
def c5ry(theta: list[float]):                     # and under five, three of them set
    q = cudaq.qvector(6)
    h(q[0])
    h(q[1])
    for i in range(2, 5):
        x(q[i])
    ry.ctrl(theta[0], q[0], q[1], q[2], q[3], q[4], q[5])

use("cuqml")
X1, ROWS1 = X[:, :1], [row[:1] for row in ROWS]
ZX = OBS[2] + cudaq.spin.x(2)                     # on ccry's target; X is odd in the angle
ZX5 = cudaq.spin.z(5) + cudaq.spin.x(5)           # the same on c5ry's
refuse("ref-measured-observe", lambda: cuqml.observe_batch(measured, OBS[0], X1))
with reference("qpp-cpu"):
    words = said(lambda: cudaq.observe(measured, OBS[0], ROWS1[0]))
    exact = [cudaq.observe(ccry, ZX, row).expectation() for row in ROWS1]
    exact5 = [cudaq.observe(c5ry, ZX5, row).expectation() for row in ROWS1]
check("chk-measured-words", "the refusal is cudaq.observe's on qpp-cpu, word for word",
      said(lambda: cuqml.observe_batch(measured, OBS[0], X1)), words)
print("sampled instead:", describe(cuqml.sample_batch(measured, X1)), "| collapsed:",
      describe(cuqml.get_state_batch(measured, X1)))
XG = X.clone().requires_grad_()
refuse("ref-shots-grad", lambda: cuqml.observe_batch(block, H, XG, shots_count=SHOTS),
       ("cuqml",))
cuqml.observe_batch(block, H, XG, shots_count=0).sum().backward()
print("with shots_count=0:", describe(XG.grad))
check("chk-two-controls", "cuqml runs ccry batched, against cudaq.observe",
      cuqml.observe_batch(ccry, ZX, X1), exact, VALUE["cuqml-fp32"])
refuse("ref-matrix-angle", lambda: cuqml.observe_batch(c5ry, ZX5, X1),
       ("cuqml", "cuqml-tensornet"))
use("cuqml-tensornet")
check("chk-matrix-angle-tn", "cuqml-tensornet runs c5ry batched",
      cuqml.observe_batch(c5ry, ZX5, X1), exact5, VALUE["tn-fp32"])

def twice():
    theta = X[0].double().requires_grad_()
    (first,) = torch.autograd.grad(cuqml.observe_batch(block, H, theta), theta,
                                   create_graph=True)
    return torch.autograd.grad(first.sum(), theta)[0]

use("cuqml", "fp64")
refuse("ref-second-derivative", twice, ("cuqml",))
use("cuqml-tensornet", "fp64")
print("on cuqml-tensornet:", describe(twice()))
check("chk-second-tn", "torch.autograd.gradgradcheck passes there",
      torch.autograd.gradgradcheck(lambda theta: cuqml.observe_batch(block, H, theta),
                                   X[0].double().requires_grad_(), raise_exception=False),
      True, against="torch.autograd.gradgradcheck")
ok   ref-measured-observe: RuntimeError: observe specification violated for 'measured': kernels passed to observe cannot have measurements specified.
ok   chk-measured-words: the refusal is cudaq.observe's on qpp-cpu, word for word: equal
sampled instead: BatchSampleResult (8, 1000) int64 on cuda | collapsed: BatchState (8, 8) complex64 on cuda
ok   ref-shots-grad: RuntimeError, names cuqml: cuqml.observe_batch: shots_count=4000 gives a sampled estimate, so the result carries no gradient, but params requires grad. Use shots_count=0, the default, to differentiate. Pass params.detach() if the value is all you need.
with shots_count=0: Tensor (8, 12) float32 on cuda
ok   chk-two-controls: cuqml runs ccry batched, against cudaq.observe: 1.0e-07 <= 2e-04 (verify/equivalence.py TOL)
ok   ref-matrix-angle: cuqml._bridge.UnsupportedGate (NotImplementedError), names cuqml: cuqml: gate 'ry' under 5 control(s) takes its angle from the kernel's arguments, and the state vector builds only r1, rx, ry, rz, u3 from an angle per row, under at most 4 controls. Anything else it builds from the matrix CUDA-Q attaches, which holds one call's angles: batched, every row would get capture's probe angle, and no gradient. cuqml-tensornet builds each of those gates per row under any number of controls.
ok   chk-matrix-angle-tn: cuqml-tensornet runs c5ry batched: 1.6e-07 <= 1e-05 (verify/tensornet.py BAR['fp32'])
ok   ref-second-derivative: RuntimeError, names cuqml: cuqml.observe_batch: a derivative of this call's gradient was asked for -- a second derivative, or a product torch takes through one, as torch.autograd.functional's hessian, hvp and jvp do -- and the state vector's adjoint sweep computes that gradient outside autograd's graph, so there is nothing of it to differentiate. Reverse mode on the tensor network differentiates twice: cudaq.set_target("cuqml-tensornet"), where it is the default, diff_method='adjoint'. For a jvp alone, parameter shift on the state vector will do: diff_method='parameter-shift'.
on cuqml-tensornet: Tensor (12,) float64 on cuda
ok   chk-second-tn: torch.autograd.gradgradcheck passes there: holds

Read more. Why a controlled rotation takes four terms, and what shots_count means: README.md › observe_batch. Pinned by verify/gradients.py::check_shift_four_term, verify/equivalence.py::check_shots_distribution and verify/tensornet.py::check_replay; measured in benchmarks/README.md › qml_sweep.py and in benchmarks/README.md › vqa_sweep.py, which holds the cells it loses. The fixed gates under controls the adjoint gradient is checked through, in any order of their controls: verify/gradients.py::check_through_controlled, verify/gradients.py::check_unordered_controls.

6 · cuqml.get_state_batch beside cudaq.get_state

call-get-state-batch · Beside cudaq.get_state and cudaq.State; the one place the two targets return different things. Beside CUDA-Q:

  • same — the amplitudes with their phase (chk-app-state; verify/equivalence.py::check_get_state_phase), and a basis state spelled as cudaq.State.amplitude spells it: chk-basis-order; on cuqml, a qubit measured in the kernel or one it calls collapses there, a draw per row: verify/equivalence.py::check_random_states

  • differs — the state is a tensor on the GPU, and so is what amplitude and amplitudes return, each with its autograd edge: chk-amplitude-edge

  • differs — on cuqml-tensornet the result is no tensor, and to_numpy is refused: ref-tn-whole-state

spelled, edges = [], []
for target in ("cuqml", "cuqml-tensornet"):
    use(target)
    psi, one = cuqml.get_state_batch(block, X), cuqml.get_state_batch(block, X[0])
    print(f"on {target}: {describe(psi)}; from one row, {describe(one)}")
    if target == "cuqml":
        print(f"  to_numpy -> {describe(psi.to_numpy())}, {describe(one.to_numpy())}; "
              f"psi[0] is a plain {type(psi[0]).__name__}")
    else:
        refuse("ref-tn-whole-state", psi.to_numpy, ("cuqml",))
    for state in (psi, one):
        print(f"  amplitude -> {describe(state.amplitude('0111'))}; amplitudes -> "
              f"{describe(state.amplitudes(['0111', [1, 0, 0, 0]]))}")
    spelled.append([psi.amplitude("0111"), psi.amplitude([0, 1, 1, 1])])
    edges.append(cuqml.get_state_batch(block, XG).amplitude("0111").requires_grad)
tripwire("chk-amplitude-edge", "where the arguments require grad an amplitude requires "
         "grad, on both targets", all(edges))
with reference("qpp-cpu"):
    theirs = [cudaq.get_state(block, row) for row in ROWS]
    exact = [[state.amplitude(basis) for state in theirs] for basis in ("0111", [0, 1, 1, 1])]
check("chk-basis-order", "amplitude('0111') and amplitude([0, 1, 1, 1]), on both targets, "
      "against cudaq.State.amplitude", spelled, [exact] * 2,
      [VALUE["cuqml-fp32"], VALUE["tn-fp32"]])
use("cuqml")

def bit_order():                                  # XB[0] is a row with one outcome
    key = format(int(cuqml.sample_batch(block, XB[:1], shots_count=1)[0, 0]), "04b")
    state = cuqml.get_state_batch(block, XB[:1])
    return (f"one row's outcome is the integer {int(key, 2)}, which reads as the key {key}; "
            f"|amplitude('{key}')| is {abs(complex(state.amplitude(key)[0])):.3f}, and the "
            f"state tensor's largest entry is at index {int(state[0].abs().argmax())}")

probe("prb-bit-order", bit_order)
on cuqml: BatchState (8, 16) complex64 on cuda; from one row, BatchState (16,) complex64 on cuda
  to_numpy -> ndarray (8, 16) complex64, ndarray (16,) complex64; psi[0] is a plain Tensor
  amplitude -> Tensor (8,) complex64 on cuda; amplitudes -> Tensor (8, 2) complex64 on cuda
  amplitude -> Tensor () complex64 on cuda, 0.078952-0.0994929j; amplitudes -> Tensor (2,) complex64 on cuda
on cuqml-tensornet: BatchNetworkState; from one row, BatchNetworkState
ok   ref-tn-whole-state: RuntimeError, names cuqml: cuqml.get_state_batch: to_numpy() needs every one of the state's 2**n amplitudes, and on cuqml-tensornet the state holds none -- they are what a tensor network avoids. amplitude(...) and amplitudes([...]) contract the basis states asked for; for the whole state, select the state vector with cudaq.set_target("cuqml").
  amplitude -> Tensor (8,) complex64 on cuda; amplitudes -> Tensor (8, 2) complex64 on cuda
  amplitude -> Tensor () complex64 on cuda, 0.078952-0.0994929j; amplitudes -> Tensor (2,) complex64 on cuda
ok   chk-amplitude-edge: where the arguments require grad an amplitude requires grad, on both targets
ok   chk-basis-order: amplitude('0111') and amplitude([0, 1, 1, 1]), on both targets, against cudaq.State.amplitude: 6.5e-08 <= 1e-05 (verify/equivalence.py TOL; verify/tensornet.py BAR['fp32'])
     prb-bit-order: no error; one row's outcome is the integer 10, which reads as the key 1010; |amplitude('1010')| is 1.000, and the state tensor's largest entry is at index 5

Read more. The reasons are README.md › get_state_batch and README.md › Result accessors. Basis-state spellings are pinned by verify/equivalence.py::check_basis_states_strict, the state that holds no amplitude by verify/tensornet.py::check_amplitudes; measured in benchmarks/README.md › qsvm_sweep.py.

7 · cuqml.sample_batch beside cudaq.sample

call-sample-batch · Beside cudaq.sample and cudaq.SampleResult. An outcome is an integer that reads as cudaq.sample’s key, and that key is the string amplitude takes; the state tensor’s index reads the other way (prb-bit-order). Beside CUDA-Q:

  • same — the key order (chk-sample-key), what the kernel’s own mz decides (README.md › sample_batch), and a seed given by cudaq.set_random_seed once the target is selected: chk-seed-repeats, prb-seed-before-target

  • differs — per-shot outcomes with a batch axis (chk-sample-key), a refusal where a gradient is asked for (ref-sample-grad), and accessors on the returned object only: README.md › Result accessors

use("cuqml")
for rows in (X, X[0]):
    out = cuqml.sample_batch(block, rows, shots_count=SHOTS)
    print(f"{describe(out)}: most_probable -> {describe(out.most_probable())}; count -> "
          f"{describe(out.count('0101'))}; expectation -> {describe(out.expectation())}; "
          f"get_marginal_counts -> {describe(out.get_marginal_counts([0, 2]))}")

def seeded():
    cudaq.set_random_seed(SEED)
    return cuqml.sample_batch(block, X, shots_count=8)

def seeded_early():                               # the seed, then the switch
    cudaq.set_target("qpp-cpu")
    cudaq.set_random_seed(SEED)
    cudaq.set_target("cuqml")
    return cuqml.sample_batch(block, X, shots_count=8)

tripwire("chk-seed-repeats", "one seed, the same draws twice (cuqml against itself)",
         torch.equal(seeded(), seeded()))
probe("prb-seed-before-target", lambda: "seeded on qpp-cpu, then switched to cuqml, twice: "
      f"the same draws, {torch.equal(seeded_early(), seeded_early())}")
use("cuqml")
refuse("ref-sample-grad", lambda: cuqml.sample_batch(block, XG), ("cuqml",))
print("detached:", describe(cuqml.sample_batch(block, XG.detach())))
with reference("qpp-cpu"):
    keys = [cudaq.sample(block, row, shots_count=8).most_probable() for row in BITS]
check("chk-sample-key", f"format(int(v), '04b') of each row's outcome is cudaq.sample's "
      f"key for it, {keys}",
      [format(int(v), "04b") for v in cuqml.sample_batch(block, XB, shots_count=8)[:, 0]],
      keys)
BatchSampleResult (8, 4000) int64 on cuda: most_probable -> list of 8 str; count -> Tensor (8,) int64 on cuda; expectation -> Tensor (8,) float32 on cuda; get_marginal_counts -> BatchSampleResult (8, 4000) int64 on cuda
BatchSampleResult (4000,) int64 on cuda: most_probable -> '0000'; count -> 25; expectation -> float 0.33; get_marginal_counts -> BatchSampleResult (4000,) int64 on cuda
ok   chk-seed-repeats: one seed, the same draws twice (cuqml against itself)
     prb-seed-before-target: no error; seeded on qpp-cpu, then switched to cuqml, twice: the same draws, False
ok   ref-sample-grad: RuntimeError, names cuqml: cuqml.sample_batch: a measurement outcome is discrete, so the result carries no gradient, but params requires grad. Pass params.detach() if the value is all you need.
detached: BatchSampleResult (8, 1000) int64 on cuda
ok   chk-sample-key: format(int(v), '04b') of each row's outcome is cudaq.sample's key for it, ['1010', '0101', '1000', '1110']: equal

Read more. The three readings of one mz are README.md › sample_batch; seeding is docs/api.md › Seeding. Mid-circuit measurement and reset are pinned by verify/sampling.py::check_midcircuit and verify/sampling.py::check_reset_mixed; the only published sampling times are benchmarks/README.md › Shots.

8 · cuqml.TorchLayer beside a layer written by hand

call-torchlayer · Beside the layer a CUDA-Q user writes by hand; the one name with no CUDA-Q call beside it. Beside that layer:

  • the kernel takes one list[float], inputs then weights, which it has to read in full, and fixed arguments as args=: ref-layer-kernel, ref-layer-unread

  • the input’s leading axes are carried through to the output: chk-layer-outputs

  • three outputs — observables, chosen amplitudes, or the state where the target holds one: ref-tn-layer-state

  • the weights start float32 on the CPU, and a forward needs them on the input’s device and at the target’s precision: prb-layer-on-cpu, ref-layer-dtype

READOUT = OBS[0] + OBS[1] + OBS[2] + OBS[3]

def by_hand(kernel, observables, rows):
    """The layer a CUDA-Q user writes without cuqml: a call a row and a term."""
    return [[cudaq.observe(kernel, term, row).expectation() for term in observables]
            for row in rows]

use("cuqml")
layer = cuqml.TorchLayer(block, (2, 4), OBS)
print("new: n_qubits", layer.n_qubits, "| weights", describe(layer.weights))
probe("prb-layer-on-cpu", lambda: layer(X[:, :4]))     # its input on the GPU, it is not
layer.cuda()
for inputs in (X[:5, :4], torch.rand(3, 5, 4, device="cuda"), X[0, :4]):
    print(f"{tuple(inputs.shape)} in, {tuple(layer(inputs).shape)} out")
print("after .cuda() and a forward: n_qubits", layer.n_qubits, "| weights",
      describe(layer.weights))
inputs = X[:2, :4].clone().requires_grad_()
layer(inputs).sum().backward()
rows = [row[:4] + layer.weights.flatten().tolist() for row in ROWS]
with reference("qpp-cpu"):
    exact = by_hand(block, OBS, rows)
    shift = cudaq_slopes(cudaq.gradients.ParameterShift(), block, READOUT, rows[:2])
check("chk-layer-outputs", "eight rows through the layer against cudaq.observe, a call a "
      "row and a term", layer(X[:, :4]), exact, VALUE["cuqml-fp32"])
check("chk-layer-gradient", "its gradient in two rows of inputs and in the weights against "
      "cudaq.gradients.ParameterShift",
      torch.cat([inputs.grad.flatten(), layer.weights.grad.flatten()]),
      np.concatenate([shift[:, :4].ravel(), shift[:, 4:].sum(0)]), GRADIENT)

def filled(init):
    """Whether a layer made with that `init=` has weights that are all 3.0."""
    return bool((cuqml.TorchLayer(block, (2, 4), OBS, init=init).weights == 3.0).all())

probe("prb-init-in-place", lambda: "init=lambda w: torch.full_like(w, 3.0) returns a "
      "tensor and writes none: the weights are 3.0, "
      + str(filled(lambda w: torch.full_like(w, 3.0))))
tripwire("chk-init-in-place", "init=lambda w: w.fill_(3.0) writes the weights in place: "
         "they are 3.0", filled(lambda w: w.fill_(3.0)))
refuse("ref-layer-kernel", lambda: cuqml.TorchLayer(encode, (2, 4), OBS).cuda()(X[:, :4]),
       ("cuqml",))
print("its arguments apart:", describe(cuqml.observe_batch(encode, H, X[:, :4], X[0, 4:8],
                                                           0.5)))
refuse("ref-layer-unread", lambda: cuqml.TorchLayer(block, (3, 4), OBS).cuda()(X[:, :4]),
       ("cuqml",))
print("with weight_shape=(2, 4):", describe(layer(X[:, :4])))
use("cuqml-tensornet")
refuse("ref-tn-layer-state", lambda: cuqml.TorchLayer(block, (2, 4)).cuda()(X[:, :4]),
       ("cuqml",))
print("with amplitudes=:", describe(cuqml.TorchLayer(
    block, (2, 4), amplitudes=["0111", "1000"]).cuda()(X[:, :4])))
new: n_qubits None | weights Parameter (2, 4) float32 on cpu, requires grad
     prb-layer-on-cpu: raised RuntimeError: Expected all tensors to be on the same device, but got tensors is on cpu, different from other tensors on cuda:0 (when checking argument in method wrapper_CUDA_cat)
(5, 4) in, (5, 4) out
(3, 5, 4) in, (3, 5, 4) out
(4,) in, (4,) out
after .cuda() and a forward: n_qubits 4 | weights Parameter (2, 4) float32 on cuda, requires grad
ok   chk-layer-outputs: eight rows through the layer against cudaq.observe, a call a row and a term: 2.6e-07 <= 2e-04 (verify/equivalence.py TOL)
ok   chk-layer-gradient: its gradient in two rows of inputs and in the weights against cudaq.gradients.ParameterShift: 1.5e-07 <= 2e-03 (verify/gradients.py TOL)
     prb-init-in-place: no error; init=lambda w: torch.full_like(w, 3.0) returns a tensor and writes none: the weights are 3.0, False
ok   chk-init-in-place: init=lambda w: w.fill_(3.0) writes the weights in place: they are 3.0
ok   ref-layer-kernel: TypeError, names cuqml: cuqml.TorchLayer: the layer hands its kernel one vector -- the inputs, then the weights -- so the kernel must take exactly one list[float], and no float, beside any fixed arguments, given as args=(...) in its order; 'encode' takes 2 list[float] and 1 float argument(s). For a kernel with separate data and weight arguments, call cuqml.observe_batch(kernel, h, x, w) directly.
its arguments apart: Tensor (8,) float32 on cuda
ok   ref-layer-unread: ValueError, names cuqml: cuqml.TorchLayer: the kernel never reads theta[12], theta[13], theta[14], theta[15], but it was handed 16 parameters — 4 input(s) as theta[0:4], then 12 weight(s) as theta[4:16]. Those columns would take a zero gradient and train quietly; check the input width and weight_shape against the kernel.
with weight_shape=(2, 4): Tensor (8, 4) float32 on cuda, requires grad
ok   ref-tn-layer-state: RuntimeError, names cuqml: cuqml.TorchLayer: without observables or amplitudes the layer returns the state, and cuqml-tensornet holds none -- its 2**n amplitudes are what a tensor network avoids. Pass observables, or amplitudes for the basis states you need, or select the state vector with cudaq.set_target("cuqml").
with amplitudes=: Tensor (8, 4) float32 on cuda, requires grad

Read more. The reasons are README.md › TorchLayer. The layer a CUDA-Q user writes without it is the baseline of benchmarks/README.md › hybrid_sweep.py, to be read before quoting it. The whole-model gradient is pinned by verify/gradients.py::check_hybrid.

9 · CUDA-Q’s own calls on the two targets

call-plain-cudaq · Everything else, from CUDA-Q: call by call and target by target, including where it does not.

# Neither real nor symmetric: its transpose, its conjugate and its adjoint are each
# another operation.
cudaq.register_operation("su2", np.array([0.48 + 0.36j, 0.48 + 0.64j,
                                          -0.48 + 0.64j, 0.48 - 0.36j]))

@cudaq.kernel
def uses_su2(theta: list[float]):
    q = cudaq.qvector(2)
    ry(theta[0], q[0])
    su2(q[1])
    su2.ctrl(q[0], q[1])

THETA, OTHER = [0.7, 1.1], [0.2, 0.5]
H2, PARITY2 = OBS[0] * OBS[1] + 0.5 * cudaq.spin.x(0), OBS[0] * OBS[1]

def cost(theta):
    return cudaq.observe(sized, H2, 2, theta).expectation()

def minimise():
    optimizer = cudaq.optimizers.LBFGS()
    optimizer.initial_parameters = THETA
    return optimizer.optimize(2, lambda theta: (
        cost(theta), cudaq.gradients.ParameterShift().compute(theta, cost, cost(theta))))

PROGRAM = {  # plain CUDA-Q: no line of it names a target
    "observe": lambda: cost(THETA),
    "observe-shots": lambda: cudaq.observe(sized, PARITY2, 2, THETA,
                                           shots_count=SHOTS).expectation(),
    "gradient": lambda: cudaq.gradients.ParameterShift().compute(THETA, cost, cost(THETA)),
    "optimizer": minimise,
    "sample": lambda: cudaq.sample(sized, 2, THETA, shots_count=SHOTS).expectation(),
    "sample-explicit": lambda: cudaq.sample(
        measured, [np.pi], shots_count=4, explicit_measurements=True).get_sequential_data(),
    "amplitude": lambda: cudaq.get_state(uses_su2, THETA[:1]).amplitude("01"),
    "overlap": lambda: cudaq.get_state(uses_su2, THETA[:1]).overlap(
        cudaq.get_state(uses_su2, OTHER[:1])),
    "num-qubits": lambda: cudaq.get_state(sized, 2, THETA).num_qubits(),
    "run": lambda: cudaq.run(flag, shots_count=4),
    "custom": lambda: cudaq.observe(uses_su2, OBS[0] * cudaq.spin.y(1),
                                    THETA[:1]).expectation(),
}
HELD = {"observe": VALUE, "observe-shots": "drawn", "gradient": GRADIENT,
        "optimizer": VALUE, "sample": "drawn", "amplitude": VALUE, "overlap": VALUE,
        "custom": VALUE}                          # the other rows are held to equality
NO_STATE = {"amplitude": "ref-tn-get-state", "overlap": "ref-tn-get-state",
            "num-qubits": "ref-tn-get-state", "run": "ref-tn-run"}
use("qpp-cpu")
theirs = {call: run() for call, run in PROGRAM.items()}
exact = cudaq.observe(sized, PARITY2, 2, THETA).expectation()    # what the two draws estimate
table = {call: [describe(result)] for call, result in theirs.items()}
for config, (target, option) in CONFIGS.items():
    use(target, option)                           # the one line that changes
    mine = {}
    for call, run in PROGRAM.items():             # one seed: each draw is its own
        try:
            mine[call] = run()
        except RuntimeError as error:
            table[call].append(refused(error, NO_STATE.get(call) if "tn" in config
                                       else None))
    with reference("qpp-cpu"):                    # the energy the optimiser returned, against
        energy_there = cost(mine["optimizer"][1])    # qpp-cpu's at the parameters it returned
    for call, got in mine.items():
        ref, limit = theirs[call], HELD.get(call)
        if call == "optimizer":
            got, ref = got[0], energy_there
        if limit == "drawn":
            ref, limit = exact, drawn(exact, SHOTS)
        table[call].append(check(
            f"chk-program-{call}@{config}", f"{call} on {target} {option}", got, ref,
            limit[config] if limit is VALUE else limit))
print("| call | on `qpp-cpu` it returned | "
      + " | ".join(f"`{target}` {option}" for target, option in CONFIGS.values()) + " |\n"
      + "|---" * 6 + "|")
for call, cells in table.items():
    print(f"| {call} | " + " | ".join(cells) + " |")

call

on qpp-cpu it returned

cuqml fp32

cuqml fp64

cuqml-tensornet fp32

cuqml-tensornet fp64

observe

float 0.740662

3.4e-08 <= 2e-04

0.0e+00 <= 1e-10

4.3e-09 <= 1e-05

0.0e+00 <= 1e-10

observe-shots

float 0.444

3.9e-03 <= 7e-02

6.6e-03 <= 7e-02

7.4e-03 <= 7e-02

6.4e-03 <= 7e-02

gradient

list of 2 float

5.8e-08 <= 2e-03

1.1e-16 <= 2e-03

2.4e-08 <= 2e-03

1.1e-16 <= 2e-03

optimizer

tuple of 2 float

2.0e-07 <= 2e-04

0.0e+00 <= 1e-10

7.6e-08 <= 1e-05

2.2e-16 <= 1e-10

sample

float 0.4585

1.1e-03 <= 7e-02

9.6e-05 <= 7e-02

3.9e-03 <= 7e-02

2.0e-02 <= 7e-02

sample-explicit

list of 4 str

equal

equal

equal

equal

amplitude

complex -0.450899+0.601199j

2.4e-08 <= 2e-04

0.0e+00 <= 1e-10

refused: ref-tn-get-state

refused: ref-tn-get-state

overlap

complex 0.968912+0j

1.2e-08 <= 2e-04

0.0e+00 <= 1e-10

refused: ref-tn-get-state

refused: ref-tn-get-state

num-qubits

2

equal

equal

refused: ref-tn-get-state

refused: ref-tn-get-state

run

list of 4 bool

equal

equal

refused: ref-tn-run

refused: ref-tn-run

custom

float 0.887579

4.5e-08 <= 2e-04

1.1e-16 <= 1e-10

1.4e-08 <= 1e-05

0.0e+00 <= 1e-10

cudaq.register_operation("lossy", np.array([1.0, 0.0, 0.0, 2.0]))    # diag(1, 2)

@cudaq.kernel
def uses_lossy():
    q = cudaq.qubit()
    h(q)
    lossy(q)

use("cuqml")
refuse("ref-state-init", lambda: cudaq.State.from_data(np.array([1, 0], dtype=np.complex64)),
       ("cuqml",))
noise = cudaq.NoiseModel()
noise.add_all_qubit_channel("ry", cudaq.BitFlipChannel(0.1))
refuse("ref-noise", lambda: cudaq.sample(sized, 2, THETA, noise_model=noise), ("cuqml",))
with reference("qpp-cpu"):
    norm = float(np.linalg.norm(np.array(cudaq.get_state(uses_lossy))) ** 2)
    amplitude = cudaq.get_state(sized, 2, THETA).amplitude("01")
    flags = cudaq.run(flag, shots_count=4)
refuse("ref-nonunitary", lambda: cudaq.get_state(uses_lossy), ("cuqml",))
print(f"qpp-cpu takes it, and returns a state of norm squared {norm:.2f}")
use("cuqml-tensornet")
refuse("ref-tn-get-state", lambda: cudaq.get_state(sized, 2, THETA), ("cuqml",))
refuse("ref-tn-run", lambda: cudaq.run(flag, shots_count=4), ("cuqml",))
use("cuqml")
check("chk-get-state-on-cuqml", "cudaq.get_state on cuqml against qpp-cpu's",
      cudaq.get_state(sized, 2, THETA).amplitude("01"), amplitude, VALUE["cuqml-fp32"])
check("chk-run-on-cuqml", "cudaq.run on cuqml against qpp-cpu's",
      cudaq.run(flag, shots_count=4), flags)
ok   ref-state-init: RuntimeError, names cuqml: cuqml target: initialising a simulation from user-provided state data is not supported yet.
ok   ref-noise: RuntimeError, names cuqml: cuqml target: noisy simulation is not supported. cuqml ships no noise-channel kernels for either of its targets, so there are no density-matrix or trajectory kernels to run. Use a CUDA-Q target built for it, such as 'density-matrix-cpu', or the 'nvidia' target's trajectory noise.
ok   ref-nonunitary: RuntimeError, names cuqml: cuqml target: bridge call 'flush' raised: cuqml target: custom operation 'lossy' is not unitary -- U-dagger U differs from the identity by 3.000e+00, past the 1e-05 an fp32-rounded matrix explains. Simulating it would leave the state unnormalised and every probability and expectation taken from it wrong, with nothing to signal it. (CUDA-Q does not check this; cuqml does.)
qpp-cpu takes it, and returns a state of norm squared 2.50
ok   ref-tn-get-state: RuntimeError, names cuqml: cuqml target: bridge call 'amplitudes' raised: cuqml-tensornet holds no state vector -- its 2**n amplitudes are what a tensor network avoids -- so cudaq.get_state has none to return. For the state, use cudaq.set_target("cuqml").
ok   ref-tn-run: RuntimeError, names cuqml: Exception in measureQubit: cuqml target: bridge call 'measure' raised: cuqml-tensornet does not measure within a kernel yet: measuring qubit 0 collapses a state, which it does not hold. cudaq.sample draws shots without one; the state vector measures: cudaq.set_target("cuqml").
ok   chk-get-state-on-cuqml: cudaq.get_state on cuqml against qpp-cpu's: 2.9e-08 <= 2e-04 (verify/equivalence.py TOL)
ok   chk-run-on-cuqml: cudaq.run on cuqml against qpp-cpu's: equal

Which calls these are: README.md › What comes from CUDA-Q unchanged. Standing checks: verify/verify_api.py::check_state_accessors, verify/verify_api.py::check_run, verify/tensornet.py::check_cudaq_refusals.

10 · An application, end to end

A hybrid classifier, built in the order a developer builds it.

Start from the call you have, cudaq.observe on one row, then hand cuqml.observe_batch the whole batch and take its gradient. Reads call-arguments, call-observe-batch.

torch.manual_seed(SEED)
LABELS = torch.arange(64, device="cuda") % 2      # two classes of points in the plane,
POINTS = torch.randn(64, 2, device="cuda") / 2 + (2 * LABELS[:, None] - 1)   # around -1, +1
(TRAIN, TEST), (TRAIN_LABELS, TEST_LABELS) = POINTS.split(56), LABELS.split(56)
T = torch.cat([TEST, TEST, X[:, 4:]], dim=1)      # a row: a point twice, then eight weights
rows = T.double().tolist()
use("cuqml")
print("cudaq.observe on cuqml, one row:", cudaq.observe(block, OBS[0], rows[0]).expectation())
values = cuqml.observe_batch(block, OBS[0], T)
print("cuqml.observe_batch, the eight rows:", describe(values))
both = [slopes(block, OBS[0], T[:2], method) for method in ("adjoint", "parameter-shift")]
print("the gradient of two rows, by either diff_method:", describe(both[0]))
with reference("qpp-cpu"):
    exact = [cudaq.observe(block, OBS[0], row).expectation() for row in rows]
    shift = cudaq_slopes(cudaq.gradients.ParameterShift(), block, OBS[0], rows[:2])
check("chk-app-batch", "the eight rows against cudaq.observe on qpp-cpu", values, exact,
      VALUE["cuqml-fp32"])
check("chk-app-gradient", "two rows' gradients, by both methods, against "
      "cudaq.gradients.ParameterShift", both, [shift] * 2, GRADIENT)
cudaq.observe on cuqml, one row: 0.3283621072769165
cuqml.observe_batch, the eight rows: Tensor (8,) float32 on cuda
the gradient of two rows, by either diff_method: Tensor (2, 12) float32 on cuda
ok   chk-app-batch: the eight rows against cudaq.observe on qpp-cpu: 2.7e-07 <= 2e-04 (verify/equivalence.py TOL)
ok   chk-app-gradient: two rows' gradients, by both methods, against cudaq.gradients.ParameterShift: 2.3e-07 <= 2e-03 (verify/gradients.py TOL)

Put the same kernel between two torch.nn.Linear layers as a cuqml.TorchLayer, and train the model with torch.optim.Adam. Reads call-torchlayer.

def train(model, steps):
    """Adam on the training points' cross-entropy: each step's loss, and its seconds."""
    optimiser, losses, seconds = torch.optim.Adam(model.parameters(), lr=0.1), [], []
    for step in range(steps):
        began = time.perf_counter()
        loss = torch.nn.functional.cross_entropy(model(TRAIN), TRAIN_LABELS)
        optimiser.zero_grad()
        loss.backward()
        optimiser.step()
        losses.append(loss.item())
        seconds.append(time.perf_counter() - began)
    return losses, seconds

def accuracy(points, labels):
    return (model(points).argmax(dim=1) == labels).float().mean().item()

use("cuqml")
model = torch.nn.Sequential(torch.nn.Linear(2, 4), cuqml.TorchLayer(block, (2, 4), OBS),
                            torch.nn.Linear(4, 2)).cuda()
print("n_qubits before the first forward:", model[1].n_qubits)
losses, seconds = train(model, 30)
print("n_qubits after:", model[1].n_qubits, "| the loss, every seventh step:",
      " ".join(f"{loss:.3f}" for loss in losses[::7]))
print(f"accuracy: {accuracy(TRAIN, TRAIN_LABELS):.2f} on the {len(TRAIN)} training points, "
      f"{accuracy(TEST, TEST_LABELS):.2f} on the {len(TEST)} held out")
print(f"one call each, not a benchmark: the first step took {seconds[0]:.3f} s, the "
      f"last {seconds[-1]:.4f} s")
tripwire("chk-app-loss-fell", f"the loss fell, from {losses[0]:.3f} to {losses[-1]:.3f}",
         losses[-1] < losses[0])
n_qubits before the first forward: None
n_qubits after: 4 | the loss, every seventh step: 0.759 0.154 0.030 0.012 0.007
accuracy: 1.00 on the 56 training points, 1.00 on the 8 held out
one call each, not a benchmark: the first step took 0.063 s, the last 0.0013 s
ok   chk-app-loss-fell: the loss fell, from 0.759 to 0.007

Check the trained layer against CUDA-Q: its outputs, and the gradient of a fixed readout. Reads call-torchlayer.

def through(points):
    """The trained layer's inputs and outputs, and the rows the circuit ran:
    [inputs..., weights...]."""
    inputs = model[0](points).detach().requires_grad_()
    weights = model[1].weights.flatten().expand(len(inputs), -1)
    return inputs, model[1](inputs), torch.cat([inputs, weights], dim=1)

use("cuqml")
inputs, out, T = through(TEST)
model.zero_grad()
out[:2].sum().backward()                          # a fixed readout of the first two rows
rows = T.tolist()
with reference("qpp-cpu"):
    exact = by_hand(block, OBS, rows)
    shift = cudaq_slopes(cudaq.gradients.ParameterShift(), block, READOUT, rows[:2])
check("chk-app-outputs", "the trained layer's outputs for the held-out rows against "
      "cudaq.observe at [inputs..., weights...]", out, exact, VALUE["cuqml-fp32"])
check("chk-app-model-gradient", "the readout's gradient in the inputs and in the weights "
      "against cudaq.gradients.ParameterShift",
      torch.cat([inputs.grad[:2].flatten(), model[1].weights.grad.flatten()]),
      np.concatenate([shift[:, :4].ravel(), shift[:, 4:].sum(0)]), GRADIENT)
ok   chk-app-outputs: the trained layer's outputs for the held-out rows against cudaq.observe at [inputs..., weights...]: 2.8e-07 <= 2e-04 (verify/equivalence.py TOL)
ok   chk-app-model-gradient: the readout's gradient in the inputs and in the weights against cudaq.gradients.ParameterShift: 1.9e-07 <= 2e-03 (verify/gradients.py TOL)

Read the trained circuit three ways: its state, its shots, and an expectation value estimated from shots. Reads call-get-state-batch, call-sample-batch.

use("cuqml")
psi = cuqml.get_state_batch(block, T)             # T, rows: the trained circuit's, as above
print("the state:", describe(psi), "| each row's probabilities sum to",
      [round(p, 6) for p in psi.abs().pow(2).sum(dim=1).tolist()])
out = cuqml.sample_batch(block, T.detach(), shots_count=SHOTS)
likeliest = out.most_probable()
print("most_probable:", likeliest, f"| count('{likeliest[0]}'), a row:",
      out.count(likeliest[0]).tolist())
print("expectation:", [round(p, 3) for p in out.expectation().tolist()])
sampled = out.get_marginal_counts([0]).expectation()
estimated = cuqml.observe_batch(block, OBS[0], T.detach(), shots_count=SHOTS)
with reference("qpp-cpu"):
    states = [cudaq.get_state(block, row) for row in rows]
    exact = [cudaq.observe(block, OBS[0], row).expectation() for row in rows]
for label, values in (("get_marginal_counts([0]).expectation()", sampled.tolist()),
                      ("observe_batch(shots_count=SHOTS)", estimated.tolist()),
                      ("cudaq.observe on qpp-cpu, exactly", exact)):
    print(f"<Z0> from {label}:", [round(p, 3) for p in values])
check("chk-app-state", "the state against cudaq.get_state", psi, states,
      VALUE["cuqml-fp32"])
check("chk-app-shots", f"both estimates of <Z0> at {SHOTS} shots against cudaq.observe's "
      "exact value", [sampled, estimated], [exact] * 2, drawn([exact] * 2, SHOTS))
the state: BatchState (8, 16) complex64 on cuda, requires grad | each row's probabilities sum to [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
most_probable: ['0010', '1001', '0010', '1001', '0010', '1001', '0010', '1101'] | count('0010'), a row: [911, 37, 849, 42, 679, 0, 811, 1]
expectation: [0.108, -0.128, 0.137, -0.127, 0.084, -0.126, 0.04, -0.11]
<Z0> from get_marginal_counts([0]).expectation(): [0.941, -0.829, 0.938, -0.834, 0.524, -0.947, 0.893, -0.927]
<Z0> from observe_batch(shots_count=SHOTS): [0.929, -0.816, 0.938, -0.844, 0.518, -0.938, 0.89, -0.928]
<Z0> from cudaq.observe on qpp-cpu, exactly: [0.934, -0.82, 0.939, -0.838, 0.516, -0.944, 0.889, -0.931]
ok   chk-app-state: the state against cudaq.get_state: 9.9e-08 <= 2e-04 (verify/equivalence.py TOL)
ok   chk-app-shots: both estimates of <Z0> at 4000 shots against cudaq.observe's exact value: 6.6e-03 <= 3e-02 (verify/tensornet.py _within)

Change the precision, then the target, under the same model. Reads call-targets, call-torchlayer.

def twice(inputs):
    """A second derivative through the trained layer, on the active target."""
    (first,) = torch.autograd.grad(model[1](inputs).sum(), inputs, create_graph=True)
    return torch.autograd.grad(first.sum(), inputs)[0]

cudaq.set_target("cuqml", option="fp64")
refuse("ref-layer-dtype", lambda: model(TEST), ("cuqml",))
model.double()
inputs, out, T = through(TEST.double())
with reference("qpp-cpu"):
    exact = by_hand(block, OBS, T.tolist())
check("chk-app-fp64", "after model.double(), the layer's outputs at fp64 against "
      "cudaq.observe", out, exact, VALUE["cuqml-fp64"])
words = said(lambda: twice(inputs))               # the state vector refuses it by name
cudaq.set_target("cuqml-tensornet")
model.float()                                     # nothing else changes
inputs, out, T = through(TEST)
with reference("qpp-cpu"):
    exact = by_hand(block, OBS, T.tolist())
check("chk-app-tensornet", "on cuqml-tensornet, the same model's outputs against "
      "cudaq.observe", out, exact, VALUE["tn-fp32"])
tripwire("chk-app-engine", "the same layer object refused a second derivative on cuqml, "
         f"and after the switch it gives one, {describe(twice(inputs))}",
         words is not None and "cuqml" in words)
ok   ref-layer-dtype: TypeError, names cuqml: cuqml.TorchLayer: the active target runs at fp64, so it takes torch.float64 arguments; got torch.float32. Cast at the boundary, or select the precision you want with cudaq.set_target("cuqml", option="fp32" or "fp64").
ok   chk-app-fp64: after model.double(), the layer's outputs at fp64 against cudaq.observe: 4.4e-16 <= 1e-10 (verify/fp64.py TOL)
ok   chk-app-tensornet: on cuqml-tensornet, the same model's outputs against cudaq.observe: 1.9e-07 <= 1e-05 (verify/tensornet.py BAR['fp32'])
ok   chk-app-engine: the same layer object refused a second derivative on cuqml, and after the switch it gives one, Tensor (8, 4) float32 on cuda

Widen the kernel past what a state vector holds (ref-memory-width), train the same model code on cuqml-tensornet, and read amplitudes and shots from it. Reads call-targets, call-get-state-batch, call-sample-batch.

use("cuqml-tensornet")
OBSW = [OBS[0] * OBS[1], cudaq.spin.x(20), cudaq.spin.y(38) * cudaq.spin.x(39)]
model = torch.nn.Sequential(torch.nn.Linear(2, 40), cuqml.TorchLayer(wide, 40, OBSW),
                            torch.nn.Linear(3, 2)).cuda()
losses, seconds = train(model, 8)                 # the same loop, on the wide model
print("n_qubits:", model[1].n_qubits, "| the loss, a step at a time:",
      " ".join(f"{value:.3f}" for value in losses))
print("one call each, not a benchmark: seconds for the first, second and last step:",
      f"{seconds[0]:.3f}, {seconds[1]:.3f}, {seconds[-1]:.4f}")
front, layer, _ = model
inputs = front(TEST[:4]).detach()
WIDE_OUT = layer(inputs)
model.zero_grad()
WIDE_OUT[0, 1].backward()                         # <X20> of the first row, in the weights
WIDE_ROWS = torch.cat([inputs, layer.weights.expand(4, -1)], dim=1).detach()
WIDE_SHOTS = cuqml.sample_batch(wide, WIDE_ROWS, shots_count=SHOTS)
WIDE_STATES = WIDE_SHOTS.most_probable()          # each row's likeliest outcome, 40 bits
WIDE_AMPLITUDES = cuqml.get_state_batch(wide, WIDE_ROWS).amplitudes(WIDE_STATES)
print(f"each row's likeliest outcome of {SHOTS} shots, and that row's amplitude of it:")
for outcome, amplitude in zip(WIDE_STATES, WIDE_AMPLITUDES.diagonal().tolist()):
    print(f"  {outcome}  {amplitude:.4g}")
use("cuqml-tensornet", "fp64")
model.double()
WIDE_ROWS64 = torch.cat([front(TEST[:4].double()), layer.weights.expand(4, -1)], dim=1)
WIDE_OUT64 = layer(WIDE_ROWS64[:, :40])
print("one forward at fp64:", describe(WIDE_OUT64))
n_qubits: 40 | the loss, a step at a time: 0.696 0.676 0.637 0.574 0.494 0.408 0.321 0.237
one call each, not a benchmark: seconds for the first, second and last step: 0.017, 0.060, 0.0010
each row's likeliest outcome of 4000 shots, and that row's amplitude of it:
  1000011110110000111001101010011101100111  -0.001562+0.0002252j
  0111111000011101100001000000000000001111  -0.001019+0.01237j
  0000011110110000111000010100011101100111  0.001038+0.0002003j
  0110000111100010000000000000000000001111  -0.01014-0.003794j
one forward at fp64: Tensor (4, 3) float64 on cuda, requires grad

Close the wide step against CUDA-Q’s own tensornet at the same precision. Reads call-plain-cudaq.

gigabytes = [torch.cuda.mem_get_info()[0] / 1e9]
rows = WIDE_ROWS.double().tolist()
with reference("tensornet", "fp32"):
    exact = by_hand(wide, OBSW, rows)
    shift = cudaq_slopes(cudaq.gradients.ParameterShift(), wide, OBSW[1], rows[:1])[0, 40:]
    amplitudes = np.array([cudaq.get_state(wide, row).amplitudes(WIDE_STATES)
                           for row in rows])
check("chk-wide-outputs", "the 40-qubit layer's outputs, four rows, against cudaq.observe "
      "on tensornet", WIDE_OUT, exact, VALUE["tn-fp32"])
check("chk-wide-gradient", "the gradient of row 0's <X20> in the 40 weights against "
      "cudaq.gradients.ParameterShift on tensornet", layer.weights.grad, shift, GRADIENT)
largest = float(np.abs(amplitudes).max())         # as check_amplitudes_wide measures them
check("chk-wide-amplitudes", "each row's amplitudes of the four outcomes, as fractions of "
      "the largest, against cudaq.get_state(...).amplitudes on tensornet",
      WIDE_AMPLITUDES / largest, amplitudes / largest, VALUE["tn-fp32"])
pairs = [row[0] for row in exact]
check("chk-wide-shots", f"<Z0 Z1> from {SHOTS} shots a row, by get_marginal_counts([0, 1])"
      ".expectation(), against tensornet's exact value",
      WIDE_SHOTS.get_marginal_counts([0, 1]).expectation(), pairs, drawn(pairs, SHOTS))
with reference("tensornet", "fp64"):
    exact64 = by_hand(wide, OBSW, WIDE_ROWS64.tolist())
check("chk-wide-fp64", "the same forward at fp64 against tensornet at fp64", WIDE_OUT64,
      exact64, VALUE["tn-fp64"])
gigabytes.append(torch.cuda.mem_get_info()[0] / 1e9)
print("CUDA-Q's tensornet took these references after every cuqml call of the run; free GPU "
      "memory before it was selected at fp32 for them, and after them: "
      f"{gigabytes[0]:.1f} GB, {gigabytes[1]:.1f} GB")
ok   chk-wide-outputs: the 40-qubit layer's outputs, four rows, against cudaq.observe on tensornet: 4.2e-07 <= 1e-05 (verify/tensornet.py BAR['fp32'])
ok   chk-wide-gradient: the gradient of row 0's <X20> in the 40 weights against cudaq.gradients.ParameterShift on tensornet: 8.9e-08 <= 2e-03 (verify/gradients.py TOL)
ok   chk-wide-amplitudes: each row's amplitudes of the four outcomes, as fractions of the largest, against cudaq.get_state(...).amplitudes on tensornet: 8.6e-07 <= 1e-05 (verify/tensornet.py BAR['fp32'])
ok   chk-wide-shots: <Z0 Z1> from 4000 shots a row, by get_marginal_counts([0, 1]).expectation(), against tensornet's exact value: 1.6e-02 <= 7e-02 (verify/tensornet.py _within)
ok   chk-wide-fp64: the same forward at fp64 against tensornet at fp64: 6.7e-16 <= 1e-10 (verify/tensornet.py BAR['fp64'])
CUDA-Q's tensornet took these references after every cuqml call of the run; free GPU memory before it was selected at fp32 for them, and after them: 16.2 GB, 8.1 GB

Training on observe_batch directly is README.md › observe_batch. At the wide steps’ width, values and their gradient are pinned by verify/tensornet.py::check_wide, amplitudes by verify/tensornet.py::check_amplitudes_wide and shots by verify/tensornet.py::check_sampling; the layer, the optimiser and the accessors at that width are checked by this run alone. The call times are not benchmarks: benchmarks/README.md › Reading the numbers.

11 · Lookups and the run record

call-lookups · From an error text to its entry. The index is every error this run met, by type, first words and last; a message’s numbers are this run’s, and the engine makes refusals this run did not meet.

  • RuntimeError · Exception in measureQubit: cuqml target: bridge call 'measure' raised: cuqml-tensornet does not measure within … cudaq.sample draws shots without one; the state vector measures: cudaq.set_target("cuqml"). · ref-tn-run

  • RuntimeError · Expected all tensors to be on the same device, but got tensors is on … other tensors on cuda:0 (when checking argument in method wrapper_CUDA_cat) · prb-layer-on-cpu

  • RuntimeError · cuqml target: bridge call 'amplitudes' raised: cuqml-tensornet holds no state vector -- its 2**n … cudaq.get_state has none to return. For the state, use cudaq.set_target("cuqml"). · ref-tn-get-state

  • RuntimeError · cuqml target: bridge call 'flush' raised: cuqml target: custom operation 'lossy' is not unitary … to signal it. (CUDA-Q does not check this; cuqml does.) · ref-nonunitary

  • RuntimeError · cuqml target: initialising a simulation from user-provided state data is not supported yet. · ref-state-init

  • RuntimeError · cuqml target: noisy simulation is not supported. cuqml ships no noise-channel kernels for either … it, such as 'density-matrix-cpu', or the 'nvidia' target's trajectory noise. · ref-noise

  • RuntimeError · cuqml's torch surface runs on the cuqml and cuqml-tensornet targets, but the active target is 'qpp-cpu' ('qpp'). Call cudaq.set_target("cuqml"). · ref-wrong-target

  • TypeError · cuqml.TorchLayer: the active target runs at fp64, so it takes torch.float64 arguments; got torch.float32. … select the precision you want with cudaq.set_target("cuqml", option="fp32" or "fp64"). · ref-layer-dtype

  • ValueError · cuqml.TorchLayer: the kernel never reads theta[12], theta[13], theta[14], theta[15], but it was handed 16 … quietly; check the input width and weight_shape against the kernel. · ref-layer-unread

  • TypeError · cuqml.TorchLayer: the layer hands its kernel one vector -- the inputs, then the weights … data and weight arguments, call cuqml.observe_batch(kernel, h, x, w) directly. · ref-layer-kernel

  • RuntimeError · cuqml.TorchLayer: without observables or amplitudes the layer returns the state, and cuqml-tensornet holds none … states you need, or select the state vector with cudaq.set_target("cuqml"). · ref-tn-layer-state

  • torch.OutOfMemoryError (RuntimeError) · cuqml.get_state_batch: 20 qubits x batch 4014 needs about 101.02 GB, and only 11.25 GB … by default), so reduce the batch or the qubit count. · ref-memory-batch

  • torch.OutOfMemoryError (RuntimeError) · cuqml.get_state_batch: 40 qubits x batch 2 needs about 52776.56 GB, and only 11.25 GB … batch cannot help, one row alone needing about 26388.28 GB. · ref-memory-width

  • RuntimeError · cuqml.get_state_batch: to_numpy() needs every one of the state's 2**n amplitudes, and on cuqml-tensornet the … for the whole state, select the state vector with cudaq.set_target("cuqml"). · ref-tn-whole-state

  • RuntimeError · cuqml.observe_batch: a derivative of this call's gradient was asked for -- a second derivative, … alone, parameter shift on the state vector will do: diff_method='parameter-shift'. · ref-second-derivative

  • TypeError · cuqml.observe_batch: argument 0 of kernel 'sized' is int, a fixed argument: one value for … call once per value with the rows that share it. · ref-kernel-argument-type

  • torch.OutOfMemoryError (RuntimeError) · cuqml.observe_batch: contracting this observable's 1 term(s) at batch 2 needs about 3.19e+15 GB for … its largest term needing about 1.6e+15 GB for one row. · ref-memory-depth

  • RuntimeError · cuqml.observe_batch: shots_count=4000 gives a sampled estimate, so the result carries no gradient, but params … differentiate. Pass params.detach() if the value is all you need. · ref-shots-grad

  • ValueError · cuqml.observe_batch: the engine runs on the GPU, so it takes CUDA tensors, torch.float32 at … tensor. Move it with .cuda(), or create it with device="cuda". · prb-cpu-tensor

  • RuntimeError · cuqml.sample_batch: a measurement outcome is discrete, so the result carries no gradient, but params … grad. Pass params.detach() if the value is all you need. · ref-sample-grad

  • cuqml._bridge.UnsupportedGate (NotImplementedError) · cuqml: gate 'ry' under 5 control(s) takes its angle from the kernel's arguments, and … of those gates per row under any number of controls. · ref-matrix-angle

  • ValueError · cuqml: kernel 'ceil_angle' computes the angle of at least one gate from its arguments, … instead and pass the result in, where it stays differentiable. · ref-angle-arithmetic

  • ImportError · cuqml: torch._dynamo cannot be imported after cudaq. It loads triton, and triton's LLVM on … new process: that loads it while it is still safe. · ref-import-order

  • ImportError · cuqml: torch._dynamo cannot be imported after cudaq. It loads triton, and triton's LLVM on … new process: that loads it while it is still safe. · ref-import-unseen

  • AttributeError · module 'cuqml' has no attribute 'run_batch' · ref-absent-name

  • RuntimeError · observe specification violated for 'measured': kernels passed to observe cannot have measurements specified. · ref-measured-observe

Not exercised by this run, each line about the run, none about the engine:

  • an unbuilt target: README.md › Install

  • kernel forms — a kernel that branches on a parameter value, a kernel not defined in a file, an argument-fed exp_pauli (verify/tensornet.py::g_exp_pauli), a custom operation beyond two targets (docs/api.md › Custom operations)

  • a layer’s args=: verify/arguments.py::check_fixed_sampled_and_layered

  • sizes — a state-vector adjoint pass that does not fit (verify/gradients.py::check_oversized_observe), a batch past the launch limit (verify/large_batch.py) or of zero rows (verify/tensornet.py::check_zero_rows)

  • CUDA-Q’s own ways to fit more — nvidia spilling to the host; tensornet slicing a contraction (README.md › The tensor-network target)

  • another GPU, and any comparison of speed: benchmarks/README.md › Reading the numbers

helper

what it does

cell(name, table=False)

Open a cell: its lines of this file, what they print and the records they make. An exception nothing expected ends the cell as a failed record, and the run goes on.

use(target, option=None)

Select a target, then seed it, in that order: prb-seed-before-target is the other.

reference(target, option=None)

A with block on a CUDA-Q target of its own, seeded, where reference values are taken; afterwards the cuqml target it found is selected again.

bar(script, name, key=None)

A bar of agreement, read with ast from a constant of that script of verify/ in the checkout and returned with where it was read. This file types no tolerance.

drawn(exact, shots)

The bar for a mean of shots draws of +1 or -1 around CUDA-Q’s exact value, computed by verify/tensornet.py’s own _within.

check(id, what, got, ref, bar=None, against=None)

Compare got with ref, the answer in the same run of the CUDA-Q target the cell last took reference values on, or of what against names: equal where bar is None, otherwise within bar – one bar, or a list of them, one for each of got’s parts. A ref that is itself inside the bar fails: there a wrong answer would pass on its size.

tripwire(id, what, holds)

State a fact of this run that CUDA-Q has no say in – the page’s own entries, torch’s behaviour, cuqml against itself – and fail the run if it does not hold.

refused(error, id)

A table’s cell for a call that raised where the refusal id is expected: that id. What was raised is kept, and the last cell fails unless it is what the record of that id holds. An error raised where none is expected, or one whose text does not name cuqml, is raised again.

said(call)

The text of the exception call raises, on one line; None if it raises nothing.

refuse(id, call, says=())

Make a call that must be refused, and show the exception’s type, whether its text names cuqml, and the text. Fails if nothing is raised or a phrase of says is missing.

probe(id, call)

Make a call whose outcome is not known ahead, and show it: what was raised, as refuse shows it, or what came back – in the call’s own words where it returns a sentence. Never fails.

child(id, source, must=None)

Run source from a file of its own in a fresh interpreter and return its stdout. Under an id, show how it ended, with the last line of stderr if it failed; must is phrases that line must hold, as the last line of a Python exception: a child ended by a signal fails it. With no id the child is no record of its own, and has to end with status 0.

describe(value)

What a call returned, in a few words: its type, and a tensor’s shape, dtype, device and whether it requires grad.

the run

SEED, SHOTS, as the cells use them

20261113, 4000

CONFIGS, the four configurations a table’s columns are

{'cuqml-fp32': ('cuqml', 'fp32'), 'cuqml-fp64': ('cuqml', 'fp64'), 'tn-fp32': ('cuqml-tensornet', 'fp32'), 'tn-fp64': ('cuqml-tensornet', 'fp64')}

records of kind check

126

records of kind refusal

22

records of kind probe

7

records of kind child

3

records of kind tripwire

7

the checks, by what each is against

qpp-cpu: 117; tensornet fp32: 4; torch.autograd.gradgradcheck: 2; qpp-cpu, in the same child: 1; cudaq.gradients.CentralDifference on qpp-cpu: 1; tensornet fp64: 1

refusals a table named by an id, each the one its record holds

14

the bar VALUE["cuqml-fp32"], read from verify/equivalence.py TOL

2e-04

the bar VALUE["cuqml-fp64"], read from verify/fp64.py TOL

1e-10

the bar VALUE["tn-fp32"], read from verify/tensornet.py BAR['fp32']

1e-05

the bar VALUE["tn-fp64"], read from verify/tensornet.py BAR['fp64']

1e-10

the bar GRADIENT, read from verify/gradients.py TOL

2e-03

the bar for a draw, by verify/tensornet.py _within, in its own words

How far a mean of +-1 samples sits from its exact value, and five standard errors.

seconds a cell, CUDA-Q’s reference calls included; not a benchmark

helpers 0.0, stamp 0.08, example 0.04, surface 0.36, targets 0.04, imports 6.2, map 0.43, tour 0.87, memory 0.99, arguments 2.31, gradient-gates 0.21, observe-refused 0.45, state 0.03, sample 0.03, layer 0.14, program 0.43, program-refused 0.02, app-start 0.01, app-model 0.11, app-check 0.12, app-read 0.04, app-precision-target 0.15, app-wide 0.5, app-wide-reference 3.0, neighbours 0.0

seconds in all

16.6

records not ok

none