Skip to content
OpenAQCPublic

About

High-Performance Simulation for Quantum Machine Learning

Resources

Contributing

Stars

5 stars

Watchers

1 watching

Forks

Repository files navigation

CuQML

CuQML is a GPU-accelerated quantum simulation engine for CUDA-Q, supporting batched execution and PyTorch autograd for quantum machine learning. Circuits stay ordinary CUDA-Q kernels; cuqml adds the two things CUDA-Q does not give a torch model — a batch axis over data samples, and gradients that flow into a torch tensor.

Documentation: https://openaqc.github.io/CuQML/

Install

You need an NVIDIA GPU with an R580 or newer driver, which CUDA 13.0 requires.

With pip

You can install CuQML using pip:

pip install cuqml

If you want to install the latest development version, you can use:

pip install git+https://github.com/OpenAQC/CuQML.git

Either way, on a machine with CUDA-Q 0.16 (cu13), install torch and the toolchain the GPU kernels compile with first, then CuQML, then import it once:

# 1. torch for CUDA 13.0, and the compiler and headers the kernels build with
pip install --index-url https://download.pytorch.org/whl/cu130 torch==2.12.0+cu130
pip install cuda-cccl==1.1.1 nvidia-cutlass==4.2.0.0 nvidia-cuda-nvcc==13.0.88 \
            nvidia-nvvm==13.0.88 nvidia-cuda-crt==13.0.88
apt-get install g++ ninja-build python3-dev
# 2. CuQML, from PyPI or from GitHub as above
pip install cuqml
# 3. builds cuqml and cuqml-tensornet, and registers them with CUDA-Q
python -c "import cuqml"

The order matters: cuqml asks for torch, so with none installed yet, pip install cuqml takes the newest torch from PyPI rather than the cu130 build these pins were verified with. Those are the versions everything here was verified on, alongside CUDA-Q 0.16.0 (cu13), g++ 13.3 and ninja 1.11. To work on cuqml itself, clone this repository and run pip install -e . in it instead.

With this repository's Docker image

This route and the next need the NVIDIA Container Toolkit, for --gpus all:

git clone https://github.com/OpenAQC/CuQML.git
cd CuQML
docker build -t cuqml .
docker run --rm -it --gpus all -v "$PWD":/work -w /work cuqml   # the entrypoint is bash -l
pip install -e .
python -c "import cuqml"   # builds cuqml and cuqml-tensornet, and registers them with CUDA-Q

The last two lines run inside the container. --rm removes the container when you leave it, and the install with it, so run them again in each new one.

In a CUDA container of your own

On nvcr.io/nvidia/cuda:13.0.3-devel-ubuntu24.04, CUDA-Q comes from pip as well:

git clone https://github.com/OpenAQC/CuQML.git
cd CuQML
docker run --rm -it --gpus all -v "$PWD":/work -w /work \
    nvcr.io/nvidia/cuda:13.0.3-devel-ubuntu24.04 bash   # the lines below run inside it
apt-get update && apt-get install -y python3 python3-dev python3-pip g++ ninja-build
pip install --break-system-packages \
    --index-url https://download.pytorch.org/whl/cu130 torch==2.12.0+cu130
pip install --break-system-packages cudaq==0.16.0 nvidia-cutlass==4.2.0.0
pip install --break-system-packages -e .
python3 -c "import cuqml"

What the first import does

import cuqml builds cuqml's two CUDA-Q targets, cuqml and cuqml-tensornet, and registers them with CUDA-Q: until it has, neither target can be selected. It builds their four plugins the first time and again whenever CUDA-Q or cuqml changes, in a few seconds, or about half a minute the first time where CUDA-Q came from pip and its headers are fetched, and says so whenever it builds. Where CUDA-Q's folder is root-owned, as in CUDA-Q's image, it installs them with password-free sudo, and it never asks for a password. Where CUDA-Q came from pip, it needs network access once, to fetch CUDA-Q's NVQIR headers from GitHub. The GPU kernels still compile at the first call, from a toolchain the build finds itself (nvcc, the CCCL and CuTe headers, libcudart), so the first kernel call, such as the Quick start's below, is slow. None of these routes needs an environment variable. Why each route is set up as it is, and what to do when a step fails: docs/install.md.

Quick start

import cuqml
import cudaq, torch

cudaq.set_target("cuqml")

@cudaq.kernel
def ansatz(theta: list[float]):
    q = cudaq.qvector(4)
    for i in range(4):
        h(q[i])
        ry(theta[i], q[i])
    for i in range(3):
        x.ctrl(q[i], q[i + 1])

hamiltonian = cudaq.spin.z(0) * cudaq.spin.z(1) + cudaq.spin.x(2)   # any CUDA-Q spin operator
params = torch.randn(64, 4, device="cuda", requires_grad=True)

# expectation values -> a scalar loss
cuqml.observe_batch(ansatz, hamiltonian, params).sum().backward()

# or the state itself -> a classical layer
model = torch.nn.Linear(32, 1).cuda()                # 16 amplitudes, as real and imaginary parts
psi = cuqml.get_state_batch(ansatz, params)          # (64, 16) complex, differentiable
model(torch.view_as_real(psi).flatten(1)).sum().backward()

# or measurement outcomes, one state per row
out = cuqml.sample_batch(ansatz, params.detach())    # (64, 1000) int64 bitstrings, no gradient

params.grad is filled by one adjoint sweep for the whole batch, not by 2 * n_params * batch circuit evaluations. Import cuqml before cudaq, as here: docs/api.md › Import order says why.

What cuqml adds

A batch axis over data samples, gradients that arrive as torch tensors, measurement outcomes and a differentiable state for a whole batch, and the kernel as an nn.Module — around a CUDA-Q kernel that stays unchanged. They are listed row by row in docs/api.md › What cuqml adds.

The whole public surface

observe_batch, get_state_batch, sample_batch and TorchLayer: that is all import cuqml brings. Their arguments, what they return and what they refuse are in docs/api.md, beside CUDA-Q's own calls on the cuqml and cuqml-tensornet targets.

observe_batch

Expectation values of a spin operator, one per row, as a tensor that is differentiable in the kernel's arguments. 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()

Its arguments, shots_count, diff_method and what it refuses: docs/api.md › observe_batch.

get_state_batch

The circuit's state on the GPU, one per row and differentiable, so a loss or a classical layer reads it with no host round-trip:

psi = cuqml.get_state_batch(ansatz, params)          # (32, 16) complex, one state per row
amps = psi.amplitudes(["0000", "1111"])              # (32, 2) complex, still differentiable
amps.abs().pow(2).sum().backward()                   # gradients reach params

psi is a tensor itself, so a loss on the whole state, such as psi.abs() ** 2, takes its gradient the same way. On cuqml-tensornet it is a state whose amplitudes are contracted when they are asked for: docs/api.md › get_state_batch.

sample_batch

Measurement outcomes, shots_count of them per row, as an int64 tensor with no gradient: docs/api.md › sample_batch.

Result accessors

most_probable, count, expectation and get_marginal_counts on a sample_batch result, and amplitude, amplitudes and to_numpy on a get_state_batch one (to_numpy on cuqml only), each answering per row: docs/api.md › Result accessors.

TorchLayer

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

Its arguments, its three kinds of output and what it refuses: docs/api.md › TorchLayer.

What comes from CUDA-Q unchanged

On cuqml, cudaq.observe, sample, get_state and run keep working and return CUDA-Q's own types; on cuqml-tensornet, observe and sample do. State initialisation and noise are refused on both: docs/api.md.

The tensor-network target

cudaq.set_target("cuqml-tensornet"), for circuits too wide for a state vector: docs/api.md › The tensor-network target.

Benchmarks

Seven sweeps measure where cuqml is faster than CUDA-Q's own simulators, and in one sweep than cuTensorNet itself, and where it is not. The summary, every table and how to read them are in benchmarks/README.md.

Where to read more

You want to Read
know why each install step is there, or fix one that fails docs/install.md
use cuqml in your own code, yourself or with a coding agent skills/cuqml-guide/SKILL.md, a guide written as a coding-agent skill, to set up and start
look up a call: what it takes, what it returns, what it refuses docs/api.md
know what cuqml does not do docs/known-limits.md
understand how the engine works docs/how-it-works.md
see the benchmarks benchmarks/README.md
see each call run beside CUDA-Q's docs/cuqml-beside-cudaq.md, generated from one run
contribute: report a bug, share your work, send a fix or a feature CONTRIBUTING.md
change cuqml CLAUDE.md/AGENTS.md, the rules (one text under two names), then docs/development.md
verify a change or run a benchmark docs/procedure.md
know where development stands, before contributing docs/status.md

License: Apache License 2.0, in LICENSE.

Disclaimer: This project is driven by the research community, including NCHC and NTU, and is not an official NVIDIA product.

About

High-Performance Simulation for Quantum Machine Learning

Resources

Contributing

Stars

5 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages