The emulator#

cq.Emulator simulates what a device would do with your program and returns what you ask to measure: the atoms’ Rydberg populations, their correlations, bitstring probabilities or shots. Everything it returns is differentiable, so you can train a program, or a network in front of it, with PyTorch. It runs on a laptop or an NVIDIA GPU, with or without the device’s noise.

A first run#

import cosmiq as cq
from cosmiq.emulator import density

program = cq.program(
    cq.Register.chain(4, spacing=7.0),
    lambda p: cq.GlobalDrive(
        amplitude=cq.pwl([0.0, 0.1, 0.9, 1.0], [0.0, p["omega"], p["omega"], 0.0]),
        detuning=cq.pwl([0.0, 1.0], [-10.0, 10.0]),
    ),
    {"omega": 9.0},
).to_target("cosmiq-ref-1")

emulator = cq.Emulator()  # the CPU, double precision
result = emulator.run(program(), observables=[density()])
rho = result.expectations["density"]  # [batch, atoms]: each atom's Rydberg population
rho.sum().backward()  # exact gradients, back to the program's parameters
print(program.params["omega"].grad)
print(result.report)  # how the run was done

The examples below run in order, like the cells of a notebook: each reuses the names defined above it (program, emulator, density and the imports).

A run needs the device: its interaction strength, its clock and its calibrated noise. A program targeted with to_target(...) carries all three; for a schedule you built yourself, pass the device with spec= (from cosmiq.devices.get).

Arguments#

Emulator(...) argument

What it does

device

"cpu", "cuda", or None to run where the schedule lives

precision

"auto" (double on the CPU, single on a GPU), "single" or "double"

method

"auto", "split", "krylov" (no gradients), "dense" (a small exact reference) or "density_matrix"

gradient

"auto", "adjoint", "checkpoint", "none" (values only) or "trajectory"

observable

what calling the emulator returns, so it works as a PyTorch layer

samples_only

return shots only, read the way the hardware reads them

space

"full" (the default), "blockade" or "tensor": see Choosing a simulator

max_memory

the memory budget in bytes; a batch is split to fit it

unverified

a reason to run past refusals for lack of evidence: see below

backend, tol, blockade, bond_dim

fine-tuning for the engine and the special spaces (see the API reference)

run(...) argument

What it does

schedule

a targeted program’s output, any schedule with spec=, or a document from cq.formats.loads (its gradients go through vjp)

observables

what to measure: see What you can measure

shots

how many bitstrings to sample per batch row

noise

None (ideal), "device", "hardware" or a NoiseModel: see Noise

trajectories

how many noisy runs to average over (100 by default)

seed

the seed of every random draw

spec, dt

the device, and the time step in µs (the device’s clock by default)

keep_state, initial

keep the final state, or start from your own (noiseless runs)

The emulator doesn’t check a schedule against the device’s limits again, since to_target already did. Check a loaded document with cosmiq.devices.check first.

What you can measure#

Everything is read in the basis the device measures in: each atom in its ground state (g) or its Rydberg state (r).

Observable

Value per batch row

What it is

density()

[N]

each atom’s probability of being in r

correlation()

[N, N]

the probability that atoms i and j are both in r

probabilities()

\([2^N]\)

the probability of each bitstring

projector(["0101", "1010"])

[]

the probability of any of these bitstrings

diagonal(weights, name="cost")

[]

a cost: each bitstring’s probability times its weight

A bitstring lists atom 0 first: "0110", "grrg" or [0, 1, 1, 0]. The weights of diagonal are a vector over the bitstrings, or a function of the bits:

from cosmiq.emulator import correlation, diagonal

count = diagonal(lambda bits: bits.sum(1).double(), name="count")  # atoms in r
result = emulator.run(program(), observables=[density(), correlation(), count])
result.expectations["count"]  # [batch], differentiable

Shots#

shots= samples bitstrings as the device would record them. Each batch row gives a cosmiq.results.Shots, whose labels read 0 (ground), 1 (Rydberg) or 2 (lost):

shots = emulator.run(program(), shots=1000).shots[0]
shots.labels  # [1000, 4]

Real hardware can’t tell a lost atom from a Rydberg atom. cq.Emulator(samples_only=True) reads shots that way (a lost atom reads 1) and returns nothing else: no state, no expectation values, no gradients. The virtual QPU is built on it.

Starting from another state#

run(..., initial=psi) starts from your own state instead of every atom in g, and gradients flow back to it, so gates and runs chain into one PyTorch graph. It’s for noiseless runs; the order of the states is in Conventions.

import torch

psi = torch.zeros(16, dtype=torch.complex128)
psi[-1] = 1.0  # all four atoms in r
result = emulator.run(program(), initial=psi, keep_state=True)
result.state  # the final state, [batch, 16]

Results and the report#

run returns an EmulationResult: expectations (each observable by name), shots when you ask for them, state with keep_state=True, and report, which says how the result was made:

  • how the run was done: the simulator, where it ran, its precision and its time steps;

  • how accurate it is: the simulator’s own error estimate, and after backward() a check on the gradient;

  • which noise: what acted, what was left out and why, the standard error over the noisy runs, the calibration and the seed;

  • how long it took and the memory it used, and every automatic choice in plain words (report.all_notes).

emulator.last_report holds the report of the emulator’s last call, for when you call it as a layer rather than through run.

Gradients#

Gradients are exact: they flow from any value the emulator returns back through the device’s rounding to the program’s parameters, and to any network that produced them. The default method rebuilds the states on the way back instead of storing them, so a long pulse needs no more memory than a short one; when its own check finds a gradient too imprecise, it recomputes it another way, and the report says so. gradient="none" skips gradients when you only need values.

To train with the emulator as a layer, give it an observable; calling it returns that value:

layer = cq.Emulator(observable=density())
optimizer = torch.optim.Adam(program.parameters(), lr=0.1)
for _ in range(5):
    optimizer.zero_grad()
    loss = -layer(program()).sum()  # maximise the Rydberg population
    loss.backward()
    optimizer.step()

Server-side gradients: vjp#

When a program travels as a document, to a remote job say, its gradient comes in two halves: the side that runs it calls vjp for the gradient with respect to the document’s numbers, and the side that wrote it multiplies that by the document’s Jacobian.

text = cq.formats.dumps(program(), jacobian_wrt=dict(program.named_parameters()))
cotangent = torch.ones(1, 4, dtype=torch.float64)  # dL/d(density), one row of 4 atoms
slots = emulator.vjp(cq.formats.loads(text), [density()], {"density": cotangent})

Noise#

noise=None, the default, is the ideal device. The two other settings add the errors in the device’s calibration:

  • noise="device": empty sites, atoms prepared wrong, atoms lost before readout, shot-to-shot jitter in the lasers’ strength and frequency, the beam’s finite width, the atoms’ thermal motion, crosstalk between local detunings, and readout errors. Gradients pass through it to the pulse, so you can train programs that hold up on a realistic device.

  • noise="hardware": all of that, plus what happens during the sequence: the Rydberg state’s decay and dephasing, the lasers’ finite rise time, and atoms lost mid-sequence. It is the closest to a real run, and the virtual QPU always uses it. The default simulator runs it without gradients; for gradients, see Choosing a simulator.

Without shots, a noisy result is the average of many noisy runs (100 by default, set by trajectories=), with its standard error in the report. With shots, each shot is its own noisy run, up to a thousand.

noisy = emulator.run(program(), observables=[density()], noise="device", seed=7)
noisy.expectations["density"]  # the average of 100 noisy runs, differentiable
noisy.report.standard_error["density"]

Your own noise model#

NoiseModel picks, scales or sets the errors by hand. Its keys are a fixed vocabulary with units (NoiseModel.KEYS), checked when the model is built, so a typo is an error, not silently no noise. Give a value as a tensor that requires gradients, and you can fit the model to data:

from cosmiq.devices import get
from cosmiq.emulator import NoiseModel

gentler = NoiseModel.from_spec(get("cosmiq-ref-1")).without("thermal").scaled(0.5)
sigma = torch.tensor(0.02, dtype=torch.float64, requires_grad=True)
fitted = NoiseModel({"laser.amplitude_sigma": sigma})
result = emulator.run(program(), observables=[density()], noise=fitted, seed=7)
result.expectations["density"].sum().backward()
sigma.grad  # how the result changes with the laser's jitter

Errors that pick a discrete outcome, such as an empty site or a lost atom, can’t be trained this way. If a site is empty in every noisy run of a batch row, its density is NaN and the report names it; every other value and gradient stays finite.

Seeds#

With seed=, a run repeats exactly, whatever the batch size or memory split. Without one, a seed is drawn from PyTorch’s generator (so torch.manual_seed makes runs repeat too), and the report records it. Results repeat on the same device and precision; across them, they agree statistically.

Choosing a simulator#

The default fits most work. The others trade generality for reach: each runs only where it was tested and refuses the rest with a named code. Exactly where each one runs is in Claims and limits.

The default#

The full quantum state of the register, on the CPU or a GPU, with every kind of noise and exact gradients. Each extra atom doubles the memory it needs, so your machine sets the largest register.

method="density_matrix": exact hardware noise, small registers#

It computes the effect of noise exactly instead of averaging noisy runs, and takes exact gradients under noise="hardware". Use it on small registers (up to 12 atoms, 10 with gradients), on the CPU.

It’s the slowest simulator: each extra atom multiplies its cost by four, so start small.

from cosmiq.devices import get
from cosmiq.emulator import NoiseModel
from cosmiq.units import MHz, us

t = [0.0, 0.2 * us, 0.8 * us, 1.0 * us]
small = cq.program(  # three atoms: a quick example
    cq.Register.chain(3, spacing=6.1),
    lambda p: cq.GlobalDrive(
        amplitude=cq.pwl(t, [0.0, p["omega"], p["omega"], 0.0]),
        detuning=cq.pwl(t, [p["start"], p["start"], p["stop"], p["stop"]]),
    ),
    {"omega": 1.5 * MHz, "start": -2.0 * MHz, "stop": 2.0 * MHz},
).to_target("cosmiq-ref-1")

t2 = NoiseModel.from_spec(get("cosmiq-ref-1"), include=["coherence"], hardware=True)  # T2 only
exact = cq.Emulator(method="density_matrix")
result = exact.run(small(), observables=[density()], noise=t2)  # one exact run
result.expectations["density"].sum().backward()

With T2 alone (decay and dephasing) it’s one exact run, which takes seconds. The rest of noise="hardware" (the laser, thermal and loss noise) is still drawn at random, 100 runs by default, each one a density-matrix run: with all of it, this example takes minutes.

gradient="trajectory": gradients through hardware noise (experimental)#

It estimates gradients through noise="hardware"’s decay and losses from many noisy runs of the default simulator. The estimate is unbiased but noisy, and the report doesn’t give its spread yet. Up to 6 atoms, on the CPU.

sampled = cq.Emulator(gradient="trajectory")
result = sampled.run(program(), observables=[density()], noise="hardware", seed=1)
result.expectations["density"].sum().backward()

space="blockade": large registers in the blockade regime#

When the drive is weak next to the interaction between neighbours, two neighbours are never both in r. This mode leaves those configurations out, so it reaches registers the full state can’t: chains of up to 28 atoms and triangular patches of up to 35. It runs only on the registers, programs and observables it was tested on, and shows no error estimate.

from cosmiq.devices import get
from cosmiq.units import MHz

drive = cq.GlobalDrive(cq.constant(4.0, 2.4 * MHz), cq.constant(4.0, 0.0))  # 4 µs
chain = cq.Schedule.from_drive(cq.Register.chain(12, 4.8), cq.Drive(drive))
blockade = cq.Emulator(space="blockade")
result = blockade.run(chain, spec=get("cosmiq-ref-1"), observables=[density(), correlation()])

space="tensor": chains as tensor networks#

It holds a chain’s state as a matrix product state, whose cost grows with how entangled the state becomes rather than with the number of atoms. It runs noiseless, on the CPU, on the chains and programs it was tested on: 8, 12 and 16 atoms, 4.8 µm apart.

drive = cq.GlobalDrive(
    amplitude=cq.pwl([0.0, 0.5, 2.0, 3.5, 4.0], [0.0, 12.0, 15.0, 12.0, 0.0]),  # rad/µs
    detuning=cq.pwl([0.0, 2.0, 4.0], [-40.0, 20.0, 100.0]),
)
chain = cq.Schedule.from_drive(cq.Register.chain(8, 4.8), cq.Drive(drive))
tensor = cq.Emulator(space="tensor")
result = tensor.run(chain, spec=get("cosmiq-ref-1"), observables=[density(), correlation()])
tensor.last_report.tensor  # the bond dimension used, and what truncation dropped

GPU, precision and memory#

cq.Emulator(device="cuda") runs on an NVIDIA GPU. precision="auto" uses double precision on the CPU and single precision on a GPU, keeping phases and sums in double; "double" forces double precision everywhere. Apple’s "mps" device is refused, as it has no complex doubles.

A batch that doesn’t fit in memory is split into pieces that do, and a gradient run recomputes each piece on the way back rather than holding them all. max_memory= sets the budget in bytes. probabilities() refuses a very large result unless you ask for it with probabilities(allow_large=True).

Running outside the tested range#

A refusal for lack of evidence means “not shown to be accurate”, not “wrong”. If you need to run such a case anyway, for a study of your own, say so on the emulator:

drive = cq.GlobalDrive(cq.constant(4.0, 2.4 * MHz), cq.constant(4.0, 0.0))
chain = cq.Schedule.from_drive(cq.Register.chain(10, 4.8), cq.Drive(drive))
study = cq.Emulator(space="blockade", unverified="chain 10 study, compared elsewhere")
result = study.run(chain, spec=get("cosmiq-ref-1"), observables=[density()])  # warns
print(result.report.verified)  # False
print(result.report.bypassed)  # ('BLK_SIZE',)

No accuracy claim of any kind applies to a result that bypassed a refusal. A tested call through the same emulator keeps its claim, and reports verified=True.

  • What it opens: only the refusals for lack of evidence, marked “yes” in the refusal table: the blockade mode’s untested cases, and the density matrix and the trajectory gradient beyond their tested sizes or off the CPU. Refusals for what would be wrong, isn’t built or doesn’t fit stay hard.

  • How: on the emulator object only, with a reason of 1 to 500 characters, read-only and shown in its repr. There’s no global switch, context manager or environment variable.

  • What you get: a cq.UnverifiedWarning on every call that bypassed something, naming the reason and each code; a warning in the cosmiq.emulator log when the emulator is built or unpickled; report.verified, report.bypassed and report.reason; and cq.emulator.unverified_bypass_count(), the number of such calls in the process.

  • Where it’s refused: results that leave your process can’t carry that record, so remote sessions, cq.remote.local(), the PennyLane devices and cq.gradients.estimate refuse an unverified emulator.

  • Memory: past the tested sizes, the emulator’s own memory estimate is the only guard; it refuses a run whose estimate is above the budget.

What a bypassed call runs, and why the other refusals stay hard, is in Claims and limits.

What it doesn’t do yet#

  • Gradients with method="krylov", and exact gradients through hardware noise above 10 atoms.

  • Observables that aren’t diagonal in the measurement basis, trainable atom positions, and several GPUs at once.

  • space="tensor" beyond its tested chains: longer chains, 2D registers, local detuning or phase, noise, shots, GPUs, single precision, remote use, and unverified=.