cosmiq#
cosmiq: hybrid quantum-classical algorithms on neutral atoms, CPUs and GPUs.
Subclass it and implement |
|
A value kept inside [low, high]. |
|
The target can't represent what was asked (trap layouts, atom loss, ...). |
|
One channel. |
|
One channel of a schedule. |
|
A program breaks one or more rules of its target device. |
|
A public cosmiq name that will be removed in a later release. |
|
Base class of every error cosmiq raises on purpose. |
|
Everything a program drives. |
|
A state-vector emulator of the device a schedule targets (see the Emulator guide). |
|
A document or value that isn't valid cosmiq input (bad JSON, wrong shape, NaN). |
|
The global Rydberg drive. |
|
The local detuning map: a fixed weight \(c_i \in [0, 1]\) per atom, and one PWL waveform \(\delta(t) \le 0\) shared by all, entering as \(-c_i \delta(t)\, n_i\). |
|
N atoms in 2D, in a fixed order (atom 0 first), with labels "q0", "q1", ... |
|
A schedule on a uniform grid of step |
|
A program evaluated to numbers. |
|
A schedule as numbers: µm, µs, rad/µs, rad. |
|
A call through |
|
One broken device rule, with everything needed to understand and fix it. |
|
|
|
A Bounded value: `self.omega = cq.bounded(1.5 * MHz, low=0.0, high="device", field="analog.rydberg_global.amplitude.max") |
|
pwl([0, duration], [value, value]). |
|
Extend to end at |
|
The functional form: |
|
Put every clamp-mode |
|
Piecewise-constant: values[k] on [edges[k], edges[k + 1]). |
|
Piecewise-linear through (times[k], values[k]). |
|
Raises FormatError unless the duration and every breakpoint (and PWC edge) are whole numbers of |
|
Piecewise-linear through samples at t_k = k * dt (so it counts as PWL for R16). |
|
Classes
- class cosmiq.AnalogProgram(register: Register)#
Bases:
ModuleSubclass it and implement
drive. Parameters are ordinary nn.Parameters.- property target: DeviceSpec | None#
The device the program is targeted at, or None. (Not a torch.device: the parameters’ torch device is where
program.to(...)put them.)
- property report: DiscretizationReport | None#
Every rounding behind the last schedule a targeted evaluation returned (a forward, or to_target’s trial run); None before the first one.
- drive(*inputs: Any) Drive | GlobalDrive#
Plain Python, run on every forward, so breakpoints work inside it.
- forward(*inputs: Any) Schedule#
drive(*inputs), evaluated into a Schedule; when targeted, discretised and checked (ConstraintError, naming the parameters behind each bad value).
- to_target(device: str | DeviceSpec, *, strict: bool = False) Self#
Bind a device and check what’s fixed now: the register (R1-R3, R5) and, when drive() takes no inputs, a trial forward. Resolves
bounded(..., "device")limits. Raises ConstraintError or CapabilityError, and FormatError for a device id that isn’t bundled (naming the ones that are). Returns self.The register is checked as the device will see it: rounded onto its position grid first, so an off-grid position is fine when its rounded place is (R3 is checked after rounding; atoms that rounding brings together raise R3). On any error the program is left as it was (its target, and its Bounded values).
- class cosmiq.Bounded(init: float, *, low: float | Literal['device'] | None = None, high: float | Literal['device'] | None = None, field: str | None = None, mode: Literal['sigmoid', 'clamp'] = 'sigmoid')#
Bases:
ModuleA value kept inside [low, high]. Call it to get the value:
self.omega().The trainable parameter is
raw, andmodesays how it maps to the value:“sigmoid” (the default): \(\mathrm{value}=\mathrm{low}+(\mathrm{high}-\mathrm{low})\cdot\mathrm{sigmoid}(\mathrm{raw})\). With only one limit, a softplus keeps the value on its side: \(\mathrm{low} + \mathrm{softplus}(\mathrm{raw})\), or \(\mathrm{high} - \mathrm{softplus}(\mathrm{raw})\). Every raw is inside, so any optimiser works unchanged, but the limits are only approached: the gradient vanishes there.
initmust lie strictly inside the limits.“clamp”: raw is the value, and the limits are closed:
initmay sit on one. After each optimiser step, project it back inside withcq.project_(program), or letcq.project_(program, after=optimizer)do it after everyoptimizer.step(). A value left outside raises FormatError when it’s called. Use it when the optimum may lie on a limit, full \(\Omega\) for example. With an optimum at cosmiq-ref-1’s \(\Omega\) maximum (15.079 rad/µs on its grid), Adam (lr 0.25) reached it exactly in clamp mode, at step 29 of 60, while the sigmoid was still 0.045 rad/µs short at step 60 (tests/test_program.py).
A “device” limit is read from the target’s spec at
fieldwhen the program is targeted, and moved onto the device’s grid (seeresolve); until then calling the value raises FormatError. Retargeting keeps the current value, if the new limits allow it. The limits and the mode are saved instate_dictwithraw.- resolve(spec: DeviceSpec) None#
Replace “device” limits with the spec’s value at
field(e.g. “analog.rydberg_global.amplitude.max”). Called by to_target.The limit is moved onto the device’s grid, the multiples of its section’s
resolution: a maximum to the largest grid value inside it, a minimum to the smallest. So rounding a value inside the limits can’t push it outside them (15.079644… with resolution 1e-3 becomes 15.079).fieldmay also name a section withminandmax(for example “analog.rydberg_global.detuning”), which is how both limits come from the device.
- class cosmiq.CapabilityError#
Bases:
CosmiqErrorThe target can’t represent what was asked (trap layouts, atom loss, …).
- class cosmiq.Channel(name: Literal['amplitude', 'detuning', 'phase', 'local_detuning'], kind: Literal['pwl', 'pwc'], times: tuple[float, ...], values: Tensor, free: tuple[bool, ...])#
Bases:
objectOne channel. pwl: K
times; pwc: K + 1 edges.valuesis float64 [B, K].
- class cosmiq.ChannelData(name: Literal['amplitude', 'detuning', 'phase', 'local_detuning'], kind: Literal['pwl', 'pwc'], times: tuple[float, ...], values: NDArray[float64], free: tuple[bool, ...])#
Bases:
objectOne channel of a schedule.
kind="pwl":timeshas K breakpoints,valuesis [B, K], linear in between.kind="pwc":timeshas K + 1 segment edges,valuesis [B, K], constant per segment.free[k]is True where value k depends on parameters or inputs (a slot on the wire), False where it’s a fixed number.
- values: NDArray[float64]#
- class cosmiq.ConstraintError(violations: list[Violation] = <factory>)#
Bases:
CosmiqErrorA program breaks one or more rules of its target device. Carries all of them.
- class cosmiq.CosmiqDeprecationWarning#
Bases:
FutureWarningA public cosmiq name that will be removed in a later release.
A FutureWarning rather than a DeprecationWarning, so users see it by default and not only their test runners.
- class cosmiq.Drive(global_drive: GlobalDrive, local_detuning: LocalDetuning | None = None)#
Bases:
objectEverything a program drives.
AnalogProgram.drivemay return this or a GlobalDrive.- global_drive: GlobalDrive#
- local_detuning: LocalDetuning | None = None#
- class cosmiq.Emulator(device: device | str | None = None, precision: Literal['auto', 'single', 'double'] = 'auto', method: Literal['auto', 'split', 'krylov', 'dense', 'density_matrix'] = 'auto', backend: Literal['auto', 'torch-ref', 'torch-kron', 'triton'] = 'auto', gradient: Literal['auto', 'adjoint', 'checkpoint', 'none', 'trajectory'] = 'auto', tol: float | None = None, samples_only: bool = False, observable: Observable | None = None, max_memory: int | None = None, space: Literal['full', 'blockade', 'tensor'] = 'full', blockade: Literal['kings'] | None = None, unverified: str | None = None, bond_dim: int | None = None)#
Bases:
ModuleA state-vector emulator of the device a schedule targets (see the Emulator guide).
emu = cq.Emulator() # CPU, complex128 result = emu.run(program(), observables=[density()]) result.expectations["density"] # [B, N], differentiable
device: the torch device, or None for the schedule’s own (“mps” is refused);precision,method,backend,gradient,tol,max_memory: the engine’s options (EngineOptions); “auto” picks, and the report says what;samples_only: shots only, read as the analog hardware would (a lost atom reads 1);observable: whatforwardreturns, sonn.Sequential(program, emulator)works;space: “full” (the \(2^N\) state space) or “blockade”, the blockade fast mode: allowed only on the registers, programs and observables that were tested (see Claims and limits), everything else refused;blockade="kings"blockades the diagonals of a square lattice; or “tensor”, an MPS run by two-site TDVP, allowed only on the chains, programs and sizes that were tested, everything else refused.bond_dim: space=”tensor“‘s bond dimension: None (the cell’s tested \(\chi\)), or that \(\chi\), 32 at \(N \le 12\) and 64 at \(N = 16\) (the tested values).unverified: None, or the reason you run past refusals for lack of evidence (see “Running outside the tested range” in the Emulator guide): an untested or failed cell then warns (cq.UnverifiedWarning) and runs, and its report saysverified=False. Inspace="blockade", the cells outside its table; in the full space, the density matrix above 12 atoms (its gradient above 10), the trajectory gradient above 6 atoms or in complex64, and either off the CPU. Hard refusals stay hard, and remote sessions,cq.remote.local(), PennyLane andcq.gradients.estimaterefuse such an emulator. Read-only; logged at WARNING when built and when unpickled. No accuracy claim of any kind applies to a result that bypassed a refusal.
last_reportis the report of this emulator’s last successful call (run,forwardorvjp), None before one or after a refused call. Shared across threads, the last writer wins.- property last_report: EmulationReport | None#
The report of this emulator’s last successful
run,forwardorvjp; None before one, and after a refused or failed call. Shared across threads, the last writer wins.
- forward(schedule: Schedule) Tensor#
The value of
observable(set in the constructor), [B, …]: fornn.Sequential(program, emulator).
- run(schedule: Schedule | ScheduleData, *, observables: Sequence[Observable] = (), shots: int | None = None, noise: Literal['device', 'hardware'] | NoiseModel | None = None, trajectories: int | None = None, seed: int | None = None, spec: DeviceSpec | None = None, dt: float | None = None, keep_state: bool = False, initial: Tensor | None = None) EmulationResult#
Evolve every batch row of
scheduleand measure it.schedule: a targetedSchedule(a program’s output), any schedule withspec=, or a loadedScheduleData(no gradients: usevjp). The device’s C6, clock and calibration come from its target, or fromspec.dt: the cell length in µs; the device clock by default. Every breakpoint must be on its grid.observables: what to measure, in expectation (exact over K trajectories).shots: sample this many per row (shot mode).noise: None (ideal), “device” (every noise source in the calibration, except the three “hardware” adds), “hardware” (“device” plus T2 by quantum jumps, the ramp filter and loss during the sequence: forward only, onsplit), or aNoiseModel.trajectories: K. Expectation mode: 100 by default. Shot mode: one per shot up to 1,000, then shots spread over them. One whenever the noise draws nothing per trajectory.seed: the root of every draw; None draws one from torch’s generator, and the report records it.keep_state: keep \(\psi(T)\) in the result (noiseless runs only; not undermethod="density_matrix").initial: start from this state instead of \(|g\ldots g\rangle\) (noiseless runs only): complex, \([2^N]\) for every row or \([B, 2^N]\), inCONVENTIONS.state_order, each row of norm 1. Gradients flow back to it, so runs and gates chain into one torch graph.
Through an
Emulator(..., unverified=...), a call that bypasses a refusal warns (cq.UnverifiedWarning) and reportsverified=False.
- vjp(data: ScheduleData, observables: Sequence[Observable], cotangents: Mapping[str, Any], *, noise: Literal['device', 'hardware'] | NoiseModel | None = None, trajectories: int | None = None, seed: int | None = None, spec: DeviceSpec | None = None, dt: float | None = None) Tensor#
\(\partial L/\partial\,\mathrm{slots}\), [B, n_slots] float64 on the CPU, for \(L = \sum_\mathrm{name} \sum \mathrm{cotangent} \cdot \mathrm{value}\) over
observables: the server side of a gradient. The client multiplies it by its document’s Jacobian (\(\partial\,\mathrm{slots}/\partial\,\mathrm{parameters}\)) to get its parameters’ gradient.datais a loaded document’s ScheduleData; its slots (thefreevalues, in wire order) become leaf tensors.cotangentshas one [B, …] array per observable, by name, shaped like its value.Through an
Emulator(..., unverified=...), a call that bypasses a refusal warns (cq.UnverifiedWarning) and reportsverified=Falseinlast_report.
- class cosmiq.FormatError#
Bases:
CosmiqError,ValueErrorA document or value that isn’t valid cosmiq input (bad JSON, wrong shape, NaN).
- class cosmiq.GlobalDrive(amplitude: Waveform, detuning: Waveform, phase: Waveform | float | Tensor = 0.0)#
Bases:
objectThe global Rydberg drive. \(\Omega\) (amplitude) and \(\Delta\) (detuning) are PWL, \(\varphi\) (phase) is PWC or a constant. \(\Omega \ge 0\) and the other device limits are checked when the program is targeted.
A phase built with
cq.constant(two breakpoints, one value) is a constant, so it is stored as the equivalent one-segment PWC waveform.
- class cosmiq.LocalDetuning(weights: Sequence[float], detuning: Waveform)#
Bases:
objectThe local detuning map: a fixed weight \(c_i \in [0, 1]\) per atom, and one PWL waveform \(\delta(t) \le 0\) shared by all, entering as \(-c_i \delta(t)\, n_i\).
The weights’ range \([0, 1]\) and \(\delta \le 0\) are device rules (R18), checked when the program is targeted; here they need only be fixed, finite numbers, one per atom.
- class cosmiq.Register(positions: Sequence[Sequence[float]] | NDArray[floating[Any]] | Tensor, labels: Sequence[str] | None = None)#
Bases:
objectN atoms in 2D, in a fixed order (atom 0 first), with labels “q0”, “q1”, …
- classmethod chain(n: int, spacing: float, *, center: bool = True) Register#
n atoms on the x axis,
spacingµm apart.
- classmethod square(side: int, spacing: float, *, center: bool = True) Register#
side by side atoms on a square grid, row by row.
- classmethod rectangular(rows: int, cols: int, spacing: float, *, center: bool = True) Register#
rows by cols atoms on a square grid, row by row (\(\text{atom index} = \text{row} \cdot \text{cols} + \text{col}\)).
- classmethod triangular(rows: int, cols: int, spacing: float, *, center: bool = True) Register#
rows of
colsatoms, nearest neighboursspacingapart; odd rows are shifted by half a spacing. Row by row, likerectangular.
- classmethod from_coordinates(coordinates: Sequence[Sequence[float]] | NDArray[floating[Any]] | Tensor, labels: Sequence[str] | None = None) Register#
Atoms at these absolute (x, y) positions, in µm. Nothing is moved.
- property positions: NDArray[float64]#
A read-only [N, 2] float64 copy, µm.
- distances() NDArray[float64]#
[N, N] pairwise distances, µm.
- class cosmiq.Samples(dt: float, t: Tensor, amplitude: Tensor, detuning: Tensor, phase: Tensor, local_detuning: Tensor | None, local_weights: Tensor | None)#
Bases:
objectA schedule on a uniform grid of step
dt(µs).tholds the n_t segment midpoints; each channel is [B, n_t]; PWL channels are sampled at the midpoints, PWC exactly.
- class cosmiq.Schedule(register: Register, channels: Mapping[Literal['amplitude', 'detuning', 'phase', 'local_detuning'], Channel], local_weights: tuple[float, ...] | None, device: str | None, batch_size: int, capabilities_version: str | None = None)#
Bases:
objectA program evaluated to numbers. The “amplitude”, “detuning” and “phase” channels are always present; “local_detuning” is there exactly when
local_weightsis not None.channelsis a read-only mapping. The exporters and formats check a schedule’s structure, but not its device limits again: they trust that a targeted forward() checked them. So don’t change its tensors in place. For new values, evaluate the program again, or build a schedule withfrom_dataand check it withcosmiq.devices.check.Schedules compare by identity: their values are tensors, which have no single truth value. Compare
to_data()arrays, or channel values withtorch.equal.- capabilities_version: str | None = None#
The capabilities version of
devicethe schedule was checked against: kept from a document byfrom_data(andto_datawrites it back), set to the target’s by discretisation, which checks against it; None for a schedule nothing checked yet (from_drive), for whichformats.dumpswrites the bundled device’s own version.
- classmethod from_drive(register: Register, drive: Drive | GlobalDrive, *, device: str | None = None) Schedule#
Evaluate a Drive: float64, a common batch size, structural checks (R15 channels end together, R16, RF). Raises FormatError; device limits are not checked here.
A GlobalDrive is accepted too. A phase given as one value becomes one PWC segment over the whole schedule. Channels with batch size 1 broadcast to the others’. Ends that differ only by float noise (at most 1e-9 µs) are made exactly equal.
- to_data() ScheduleData#
Detached numpy copies, for the check, formats and exporters.
- classmethod from_data(data: ScheduleData) Schedule#
Back to tensors (no gradients), e.g. after formats.loads.
Runs the same structural checks as
from_drive(RD, RF, RT, R15, R16, shapes; cosmiq._structure) and raises FormatError, so every Schedule keeps the same invariants. The device label and its capabilities version are kept as they are.
- class cosmiq.ScheduleData(positions: NDArray[float64], labels: tuple[str, ...], channels: dict[Literal['amplitude', 'detuning', 'phase', 'local_detuning'], ChannelData], local_weights: NDArray[float64] | None, device: str | None, batch_size: int, capabilities_version: str | None = None)#
Bases:
objectA schedule as numbers: µm, µs, rad/µs, rad. Compares by identity (its fields are arrays).
channelsalways has “amplitude”, “detuning” and “phase”; “local_detuning” is present exactly whenlocal_weightsis not None.- positions: NDArray[float64]#
- channels: dict[Literal['amplitude', 'detuning', 'phase', 'local_detuning'], ChannelData]#
- class cosmiq.UnverifiedWarning(message: str = '', *, hits: Sequence[Hit] = (), reason: str = '', site: str = '')#
Bases:
UserWarningA call through
Emulator(..., unverified="reason")bypassed at least one refusal: no accuracy claim applies to its result.codes,refusals,hits: what it bypassed;reason: the emulator’sunverified;site: “file:line” where the emulator was built.
- class cosmiq.Violation(rule: str, message: str, device: str | None = None, field: str | None = None, channel: str | None = None, t_start: float | None = None, t_end: float | None = None, atoms: tuple[int, ...] = (), index: int | None = None, batch_index: int | None = None, value: float | None = None, limit: float | None = None, unit: str | None = None, caused_by_rounding: bool = False, envelope: Literal['target', 'strict'] = 'target', parameters: tuple[str, ...] = (), fix: str | None = None)#
Bases:
objectOne broken device rule, with everything needed to understand and fix it.
Values and limits are in cosmiq’s units (µs, µm, rad/µs, rad, \(\mathrm{rad/\mu s^2}\)), named by
unit.- device: str | None = None#
The device and its capabilities version, “cosmiq-ref-1@1.0.0”.
- field: str | None = None#
The device-spec field that sets the limit, “analog.rydberg_global.amplitude.max”.
- channel: str | None = None#
“amplitude”, “detuning”, “phase”, “local_detuning”, or None for register rules.
- index: int | None = None#
The breakpoint (pwl) or segment (pwc) index within
channel, for value rules.
- envelope: Literal['target', 'strict'] = 'target'#
Which limits rejected it: the target device’s, or the strict envelope’s.
- class cosmiq.Waveform(kind: Literal['pwl', 'pwc'], times: tuple[float, ...], values: tuple[float | Tensor, ...])#
Bases:
objectkind="pwl": values at the Ktimes, linear in between.kind="pwc":timesare K + 1 segment edges, one value per segment.
Functions
- cosmiq.bounded(init: float, *, low: float | Literal['device'] | None = None, high: float | Literal['device'] | None = None, field: str | None = None, mode: Literal['sigmoid', 'clamp'] = 'sigmoid') Bounded#
A Bounded value: `self.omega = cq.bounded(1.5 * MHz, low=0.0, high=”device”, field=”analog.rydberg_global.amplitude.max”)
, thenself.omega()` in drive().mode="clamp"stores the value itself, for an optimum on a limit (seeBounded).
- cosmiq.constant(duration: float, value: float | Tensor) Waveform#
pwl([0, duration], [value, value]).
- cosmiq.pad_to(waveform: Waveform, t: float, value: float | Tensor | None = None) Waveform#
Extend to end at
t: pwl appends (t, value or the last value); pwc extends the last segment, or adds one whenvalueis given. The explicit fix for R15.tequal to the current end returns the waveform unchanged when novalueis given.
- cosmiq.program(register: Register, drive_fn: Callable[[...], Drive | GlobalDrive], parameters: Mapping[str, float | Tensor] | None = None) AnalogProgram#
The functional form:
drive_fn(params, *inputs), whereparamsis the program’s nn.ParameterDict built fromparameters(floats become float64 nn.Parameters).The dict is registered as
params, so parameters are named “params.<key>” innamed_parameters(), in violations and for functional_call. An nn.Parameter passed in is used as is; another tensor becomes a new nn.Parameter with its values.
- cosmiq.project_(module: Module, *, after: None = None) None#
- cosmiq.project_(module: Module, *, after: Optimizer) RemovableHandle
Put every clamp-mode
boundedvalue inmoduleback inside its limits, in place and under no_grad: the projection of projected gradient descent. Call it after each step of an optimiser that isn’t torch’s (autograd’s, PennyLane’s).With
after=optimizer, it also projects after everyoptimizer.step()from now on, by a step post-hook (Optimizer.register_step_post_hook), and returns the hook’s handle:handle.remove()stops it.optimizer = torch.optim.Adam(program.parameters(), lr=0.05) cq.project_(program, after=optimizer)
Sigmoid-mode values are left alone: they can’t leave their limits.
- cosmiq.pwc(edges: Sequence[float], values: Sequence[float | Tensor] | Tensor) Waveform#
Piecewise-constant: values[k] on [edges[k], edges[k + 1]).
valuesmay also be one tensor, as forpwl.
- cosmiq.pwl(times: Sequence[float], values: Sequence[float | Tensor] | Tensor) Waveform#
Piecewise-linear through (times[k], values[k]). Raises FormatError on RT/RF/shape.
valuesmay also be one tensor: [K] (K scalars) or [B, K] (K batched values).
- cosmiq.sample(schedule: Schedule, dt: float | None = None, rule: Literal['midpoint'] = 'midpoint') Samples#
Raises FormatError unless the duration and every breakpoint (and PWC edge) are whole numbers of
dt(within 1e-9 µs): a cell can’t hold a breakpoint inside it, so a ramp that starts or ends there would be sampled wrong. The error names the first breakpoint off the grid.dt=Nonemeans the clock period of the schedule’s device, a bundled device looked up by id; an untargeted schedule needs an explicitdt.Cell \(j\) covers \([j \cdot dt, (j + 1) \cdot dt)\) and is represented by its midpoint \(t_j = (j + \tfrac{1}{2}) \cdot dt\). A PWL channel is evaluated there by linear interpolation, which is its exact average over the cell when the breakpoints are on the grid. A PWC channel takes the value of the segment that contains \(t_j\): exactly the segment’s value, never a blend. Differentiable in the channel values.
- cosmiq.sampled(dt: float, samples: Sequence[float | Tensor] | Tensor) Waveform#
Piecewise-linear through samples at t_k = k * dt (so it counts as PWL for R16).
samplesmay be a [K] tensor, or [B, K] for a batch.
Values
- cosmiq.__version__ = '0.1.0'#