Quickstart#
A cosmiq program describes what happens on a neutral-atom device: where the atoms sit, what the lasers do over time, and which settings are learned. cosmiq checks the program against a device, and saves or exports it. A program is a PyTorch module, so its settings train like any other model’s.
pip install cosmiq
Times are in µs and distances in µm. Write frequencies with MHz from cosmiq.units, as in
1.5 * MHz. Conventions has the Hamiltonian, the signs and the units in full.
A first program#
import torch
import cosmiq as cq
from cosmiq.units import us, um, MHz
class Sweep(cq.AnalogProgram): # an nn.Module
def __init__(self) -> None:
super().__init__(register=cq.Register.chain(6, spacing=6.1 * um))
self.omega = torch.nn.Parameter(torch.tensor(1.5 * MHz, dtype=torch.float64))
self.delta = torch.nn.Parameter(torch.tensor([-3.0, 3.0], dtype=torch.float64) * MHz)
def drive(self) -> cq.GlobalDrive:
t = [0.0, 0.248 * us, 2.752 * us, 3.0 * us] # on the 4 ns grid
return cq.GlobalDrive(
amplitude=cq.pwl(t, [0.0, self.omega, self.omega, 0.0]),
detuning=cq.pwl(t, [self.delta[0], self.delta[0], self.delta[1], self.delta[1]]),
)
program = Sweep().to_target("cosmiq-ref-1") # checked now; ConstraintError if not
schedule = program() # forward(): concrete float64 tensors
print(schedule) # a readable table of breakpoints
cq.formats.dumps(schedule) # cosmiq.schedule/1 JSON
cq.export.to_pulser(schedule) # Pulser abstract repr (JSON str)
cq.export.to_braket_ahs(schedule) # Braket AHS program (dict, SI units)
What each step does:
cq.Register.chain(6, spacing=6.1 * um): six atoms in a line, centred on the beam.drive()builds the laser pulse from the parameters. It’s plain Python and runs on every call, so you can step through it in a debugger.cq.pwl(times, values)is a piecewise-linear shape through its breakpoints. Times are fixed numbers starting at 0; values may be numbers or tensors.to_target("cosmiq-ref-1")picks the device and checks the atom positions now: how many atoms there are, whether they fit in the device’s window, and how far apart they are. Thisdrive()takes no inputs, so the pulse is checked now too.program()builds the schedule: the pulse, as concrete values. It rounds the pulse to what the device can play and checks it. Gradients flow through the rounding, and the values are PyTorch tensors.cq.formats.dumps(schedule)saves the schedule as JSON, andcq.export.to_pulserandcq.export.to_braket_ahsexport it for Pulser and Amazon Braket.
For small programs, cq.program(register, drive_fn, params) is the short form: give it the
register, a function from a dict of parameters to the drive, and the starting values, and it
makes the same kind of module, with no class to write. Emulating a program
below uses it.
print(schedule) shows the register and each channel’s breakpoints. A * marks values that
depend on parameters or inputs:
Schedule for cosmiq-ref-1: 6 atoms, 3 µs, batch size 1
register (µm):
q0 (-15.250, 0.000)
q1 (-9.150, 0.000)
q2 (-3.050, 0.000)
q3 (3.050, 0.000)
q4 (9.150, 0.000)
q5 (15.250, 0.000)
amplitude (pwl, rad/µs):
t = 0.0000 0.000 rad/µs (2π·0.000 MHz)
* t = 0.2480 9.425 rad/µs (2π·1.500 MHz)
* t = 2.7520 9.425 rad/µs (2π·1.500 MHz)
t = 3.0000 0.000 rad/µs (2π·0.000 MHz)
detuning (pwl, rad/µs):
* t = 0.0000 -18.850 rad/µs (-2π·3.000 MHz)
* t = 0.2480 -18.850 rad/µs (-2π·3.000 MHz)
* t = 2.7520 18.850 rad/µs (2π·3.000 MHz)
* t = 3.0000 18.850 rad/µs (2π·3.000 MHz)
phase (pwc, rad):
[0.0000, 3.0000) 0 rad
* depends on parameters or inputs
When a program breaks a rule#
Nothing is clipped or fixed silently. A program that breaks one of the device’s limits raises
cq.ConstraintError, which lists every problem: which limit, where in the program, the value
and the limit, and how to fix it. It also names the parameters behind the bad value:
too_strong = Sweep()
with torch.no_grad():
too_strong.omega.fill_(3.0 * MHz) # above cosmiq-ref-1's 2π·2.4 MHz
try:
too_strong.to_target("cosmiq-ref-1")
except cq.ConstraintError as error:
print(error)
print(error.violations[0].parameters) # ('omega',)
The names come from autograd, so under torch.no_grad(), or with frozen parameters, they read
“unknown (evaluated without autograd)”.
Gradients#
Schedule values are PyTorch tensors, and gradients flow from them back to the parameters, so any differentiable function of the schedule trains the program:
samples = schedule.sample() # the midpoint of every 4 ns cell of the device's clock
loss = samples.amplitude.mean()
loss.backward()
print(program.omega.grad)
Data inputs and batches#
drive() may take inputs, such as a batch of features. The batch then comes from the data,
and program(x) works inside nn.Sequential and with torch.func.functional_call:
class Encode(cq.AnalogProgram):
def __init__(self) -> None:
super().__init__(register=cq.Register.chain(2, spacing=6.1 * um))
self.gain = torch.nn.Parameter(torch.tensor(1.0 * MHz, dtype=torch.float64))
def drive(self, x: torch.Tensor) -> cq.GlobalDrive: # x: [B] features
t = [0.0, 0.248 * us, 0.752 * us, 1.0 * us]
omega = self.gain * x
return cq.GlobalDrive(
amplitude=cq.pwl(t, [0.0, omega, omega, 0.0]),
detuning=cq.constant(1.0 * us, 0.0),
)
encode = Encode().to_target("cosmiq-ref-1") # no trial run: drive() needs x
batch = encode(torch.tensor([0.5, 1.0, 2.0], dtype=torch.float64))
print(batch.batch_size) # 3
Keeping a parameter inside the device’s limits#
cq.bounded keeps a parameter inside a range, so no training step can push it out. With
high="device", the limit is read from the device when the program is targeted, and set to the
largest value the device can play under it:
class Safe(cq.AnalogProgram):
def __init__(self) -> None:
super().__init__(register=cq.Register.chain(6, spacing=6.1 * um))
self.omega = cq.bounded(
1.5 * MHz, low=0.0, high="device", field="analog.rydberg_global.amplitude.max"
)
def drive(self) -> cq.GlobalDrive:
t = [0.0, 0.248 * us, 2.752 * us, 3.0 * us]
omega = self.omega() # always inside (0, max)
return cq.GlobalDrive(
amplitude=cq.pwl(t, [0.0, omega, omega, 0.0]),
detuning=cq.constant(3.0 * us, 0.0),
)
safe = Safe().to_target("cosmiq-ref-1")
print(safe.omega.high) # 15.079: the largest 1e-3 step inside 2π·2.4 MHz
Without bounded, a value right at a limit can cross it once rounded to what the device can
play. That’s reported, never clamped, and the error names the largest value that fits. On
cosmiq-ref-1, 2.4 * MHz is exactly the amplitude limit, yet it fails once rounded; 15.079
rad/µs is the largest amplitude that fits.
Without a device#
A program with no device gets only the basic checks: shapes, finite values, times that start
at 0 and increase, and channels that end together. cq.pad_to extends a shorter channel:
short = cq.constant(2.0 * us, 0.0)
padded = cq.pad_to(short, 3.0 * us) # holds the last value until 3 µs
Emulating a program#
cq.Emulator simulates a targeted program and measures it. Its results are tensors you can
differentiate back to the program’s parameters:
from cosmiq.emulator import correlation, density
triple = cq.program(
cq.Register.chain(3, spacing=8.0 * um),
lambda p: cq.GlobalDrive(
amplitude=cq.pwl([0.0, 0.1 * us, 0.9 * us, 1.0 * us], [0.0, p["omega"], p["omega"], 0.0]),
detuning=cq.pwl([0.0, 1.0 * us], [-2.0 * MHz, 2.0 * MHz]),
),
{"omega": 1.5 * MHz},
).to_target("cosmiq-ref-1")
emulator = cq.Emulator() # the CPU, complex128
result = emulator.run(triple(), observables=[density(), correlation()])
rho = result.expectations["density"] # [1, 3]: ⟨nᵢ⟩ per atom
rho.sum().backward() # the reversible adjoint, back to omega
print(triple.params["omega"].grad)
noisy = emulator.run(triple(), observables=[density()], noise="device", trajectories=20, seed=1)
print(noisy.report.standard_error["density"]) # over the 20 noise trajectories
shots = emulator.run(triple(), shots=100, seed=7).shots # one cq.results.Shots per batch row
print(shots[0].labels.shape) # (100, 3)
noise="device"adds the device’s own noise: empty sites, preparation and readout errors, and laser and thermal fluctuations. The default,noise=None, is noise-free.result.reportsays how the run was done: the method, its error estimate, the noise used and the seed.The emulator has the rest: shots, noise, gradients, larger systems and memory.
What was tested, and the sizes each part is claimed for, are on Claims and limits.