cosmiq.emulator#

The emulator: run a cosmiq program and get its final state, probabilities, expectation values and shots, with exact gradients (see the Emulator guide).

unverified_bypass_count() is the number of calls in this process that ran past a refusal through an Emulator(..., unverified=...); UnverifiedWarning is what each such call warns.

EmulationReport

How a run was done.

EmulationResult

What Emulator.run returns.

Emulator

A state-vector emulator of the device a schedule targets (see the Emulator guide).

NoiseModel

The noise of a run: calibration values by key, in the units of NoiseModel.KEYS.

Observable

A diagonal observable.

UnverifiedWarning

A call through Emulator(..., unverified="reason") bypassed at least one refusal: no accuracy claim applies to its result.

correlation

\(\langle n_i n_j \rangle\), [B, N, N], with \(\langle n_i \rangle\) on the diagonal; empty sites left out pair by pair.

density

\(\langle n_i \rangle\) per atom, [B, N], empty sites left out (\(E[n_i \cdot \mathrm{pre}_i]/E[\mathrm{pre}_i]\)).

diagonal

\(\sum_b w_b P(b)\), [B]: weights_or_fn is a \([2^N]\) weight vector (array or tensor, which may require grad), or a function of the bits, fn(bits) -> [2^N], where bits is a \([2^N, N]\) int64 tensor (row \(b\) is basis state \(b\), atom 0 first).

probabilities

The read bitstring distribution, \([B, 2^N]\) float64 in CONVENTIONS.state_order (atom 0 the most significant bit).

projector

The probability of reading any of bitstrings, [B].

unverified_bypass_count

How many calls in this process bypassed at least one refusal through an Emulator(..., unverified=...) and passed their pre-run checks.

Classes

class cosmiq.emulator.EmulationReport(device: str, torch_device: str, dt: float, n_cells: int, batch_size: int, trajectories: int, shots: int | None, shots_per_trajectory: int | None, effective_sample_size: int | None, noise_used: tuple[str, ...], noise_unused: Mapping[str, str], standard_error: Mapping[str, Tensor], calibration_id: str | None, seed: int | None, chunks: int, checkpointed: bool, wall_seconds: float, notes: tuple[str, ...], infos: Sequence[EngineInfo | None] = (), verified: bool = True, bypassed: tuple[str, ...] = (), reason: str | None = None, tensor: TensorReport | None = None)#

Bases: object

How a run was done. Compares by identity.

device: str#

The device ref the physics came from, “cosmiq-ref-1@1.0.0”.

torch_device: str#

Where the state lived: “cpu”, “cuda:0”.

dt: float#

µs: the cell length (the device clock, or dt=).

n_cells: int#
batch_size: int#
trajectories: int#

K, per batch row: 1 when nothing is drawn per trajectory.

shots: int | None#

Per batch row, in shot mode.

shots_per_trajectory: int | None#

The most shots any trajectory gave (shots spread evenly when shots > K).

effective_sample_size: int | None#

Independent noise draws behind the shots: K when the noise is drawn per trajectory (shots of one trajectory share it), else the number of shots.

noise_used: tuple[str, ...]#

The calibration keys that acted on this run.

noise_unused: Mapping[str, str]#

Calibration keys left out, and why (coherence.* and ramp.* unless the noise is "hardware": “opt-in: noise=’hardware’”).

standard_error: Mapping[str, Tensor]#

Per observable, the standard error of its average over the K trajectories (empty when K = 1). Detached.

calibration_id: str | None#

The calibration snapshot of the noise, or None for a noiseless run.

seed: int | None#

The root seed of the noise and shot draws (None when the run drew nothing).

chunks: int#

How many pieces the batch was evolved in (memory).

checkpointed: bool#

True when each chunk was wrapped in torch.utils.checkpoint (a gradient run in more than one chunk).

wall_seconds: float#

The whole run, front end included (the backward pass not).

notes: tuple[str, ...]#

Every automatic choice and every model assumption, in plain words.

infos: Sequence[EngineInfo | None] = ()#

The engine’s account, per chunk (kept live: a backward pass can replace an entry).

verified: bool = True#

False when this call bypassed a refusal through Emulator(..., unverified=...): then no accuracy claim of any kind applies to its result. A tested call through an unverified emulator is verified.

bypassed: tuple[str, ...] = ()#

The refusal codes the call bypassed, in the order it met them.

reason: str | None = None#

The emulator’s unverified= reason, when the call bypassed a refusal.

tensor: TensorReport | None = None#

space="tensor"‘s account (bond dimension, discarded weight, cells), None in the other spaces.

property engines: tuple[EngineInfo, ...]#

The engine’s EngineInfo of each chunk.

property method: str#
property backend: str | None#
property dtype: str#
property n_sub: int | None#

Substeps per cell (split), the largest over the chunks.

property error_estimate: float | None#

The engine’s error estimate, the largest over the chunks.

property estimate_seconds: float#

Time spent on the error control: its probe runs other than the kept one (about half a forward pass).

property peak_memory: int | None#

Bytes, when the device reports them: the largest over the chunks.

property certificate: float | None#

\(\lVert \psi_0^\mathrm{rebuilt} - \psi_0 \rVert_2\) of the adjoint, the largest over the chunks, after a backward pass; None before one, or when no chunk ran the adjoint.

property gradient_mode: str | None#

“adjoint” or “checkpoint” (or both, joined), once a backward pass has run.

property all_notes: tuple[str, ...]#

The front end’s notes, then each engine note once.

class cosmiq.emulator.EmulationResult(state: Tensor | None, expectations: Mapping[str, Tensor], shots: tuple[Shots, ...] | None, report: EmulationReport, *, probabilities: Tensor | None = None, samples_only: bool = False)#

Bases: object

What Emulator.run returns.

  • state: \(\psi(T)\), [B, D] complex, when the run kept it (keep_state=True), else None;

  • probabilities(): \(|\psi|^2\), or the averaged read distribution, [B, D] float64;

  • expectations: each observable’s value by name, float64, differentiable;

  • shots: one Shots per batch row in shot mode, else None;

  • report: how the run was done (EmulationReport).

probabilities(*, allow_large: bool = False) → Tensor#

[B, D] float64 in CONVENTIONS.state_order: the probabilities() observable when the run asked for it (averaged, read through the noise), else \(|\psi|^2\) of the kept state, computed now. Refused above 2 GiB unless allow_large=True (MemoryError).

class cosmiq.emulator.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: Module

A 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: what forward returns, so nn.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 says verified=False. In space="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 and cq.gradients.estimate refuse 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_report is the report of this emulator’s last successful call (run, forward or vjp), None before one or after a refused call. Shared across threads, the last writer wins.

property unverified: str | None

The reason given to unverified=, or None: read-only.

property last_report: EmulationReport | None

The report of this emulator’s last successful run, forward or vjp; 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, …]: for nn.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 schedule and measure it.

  • schedule: a targeted Schedule (a program’s output), any schedule with spec=, or a loaded ScheduleData (no gradients: use vjp). The device’s C6, clock and calibration come from its target, or from spec.

  • 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, on split), or a NoiseModel.

  • 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 under method="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]\), in CONVENTIONS.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 reports verified=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.

data is a loaded document’s ScheduleData; its slots (the free values, in wire order) become leaf tensors. cotangents has 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 reports verified=False in last_report.

class cosmiq.emulator.NoiseModel(values: Mapping[str, float | Tensor] | None = None, *, calibration_id: str | None = None, unused: Mapping[str, str] | None = None, hardware: bool = False)#

Bases: object

The noise of a run: calibration values by key, in the units of NoiseModel.KEYS.

Build it from a device (from_spec), or by hand: NoiseModel({"laser.amplitude_sigma": 0.02}). Values are checked when it’s built (known key, finite, in range); a value of a key in DIFFERENTIABLE may be a 0-d tensor that requires grad. A laser.detuning_offset_sigma needs a calibration_id: the offset is drawn once per snapshot, from its id.

hardware=True (what noise="hardware" builds) also reads coherence.* (T2, by quantum jumps) and ramp.* (the ramp filter), and makes loss.sequence_probability act during the sequence; such a model takes gradients only under method="density_matrix" or gradient="trajectory". Without it, those keys are refused in a model by hand and kept in unused, with the reason, by from_spec.

KEYS: ClassVar[Mapping[str, CalibrationKey]] = mappingproxy({'filling.vacancy_probability': CalibrationKey(unit='probability', low=0.0, high=1.0, meaning='an empty trap before the sequence', low_open=False), 'spam.preparation_error': CalibrationKey(unit='probability', low=0.0, high=1.0, meaning='an atom not prepared in the ground state', low_open=False), 'spam.false_positive': CalibrationKey(unit='probability', low=0.0, high=1.0, meaning='a ground atom read as Rydberg', low_open=False), 'spam.false_negative': CalibrationKey(unit='probability', low=0.0, high=1.0, meaning='a Rydberg atom read as ground', low_open=False), 'loss.sequence_probability': CalibrationKey(unit='probability', low=0.0, high=1.0, meaning='an atom lost during the sequence, per shot', low_open=False), 'coherence.t1_rydberg': CalibrationKey(unit='us', low=0.0, high=None, meaning='T1 of the Rydberg state', low_open=True), 'coherence.dephasing_rate': CalibrationKey(unit='1/us', low=0.0, high=None, meaning='the residual dephasing rate, 1/T2', low_open=False), 'thermal.doppler_sigma': CalibrationKey(unit='rad/us', low=0.0, high=None, meaning='the rms Doppler detuning, per atom', low_open=False), 'thermal.position_sigma': CalibrationKey(unit='um', low=0.0, high=None, meaning='the rms error of each position coordinate', low_open=False), 'laser.amplitude_sigma': CalibrationKey(unit='relative', low=0.0, high=None, meaning='the rms error of the Rabi frequency, shot to shot', low_open=False), 'laser.waist': CalibrationKey(unit='um', low=0.0, high=None, meaning="the global beam's waist, for the amplitude profile", low_open=True), 'laser.detuning_sigma': CalibrationKey(unit='rad/us', low=0.0, high=None, meaning='the rms error of the global detuning, shot to shot', low_open=False), 'laser.detuning_offset_sigma': CalibrationKey(unit='rad/us', low=0.0, high=None, meaning='the rms calibration offset of the global detuning', low_open=False), 'local.crosstalk': CalibrationKey(unit='relative', low=0.0, high=1.0, meaning='the fraction of the local detuning that spills onto a neighbour', low_open=False), 'local.weight_sigma': CalibrationKey(unit='relative', low=0.0, high=None, meaning='the rms error of the local weights', low_open=False), 'ramp.rabi_correction_52ns': CalibrationKey(unit='factor', low=0.0, high=1.0, meaning='the Rabi frequency reached in a 52 ns ramp', low_open=True), 'ramp.rabi_correction_100ns': CalibrationKey(unit='factor', low=0.0, high=1.0, meaning='the Rabi frequency reached in a 100 ns ramp', low_open=True), 'ramp.rabi_correction_200ns': CalibrationKey(unit='factor', low=0.0, high=1.0, meaning='the Rabi frequency reached in a 200 ns ramp', low_open=True)})#

Every calibration key, its unit and its range (cosmiq.devices’ vocabulary).

property values: Mapping[str, float | Tensor]#

The values this model uses, by key.

property unused: Mapping[str, str]#

Keys of the calibration this model leaves out, and why.

property calibration_id: str | None#

The snapshot it came from. It seeds the detuning’s calibration offset.

property hardware: bool#

True for noise="hardware"‘s model: T2, the ramp filter and loss during the sequence act.

classmethod from_spec(spec: DeviceSpec, include: Iterable[str] = GROUPS, *, hardware: bool = False) → NoiseModel#

Every mechanism the spec’s calibration has values for, in the groups (or keys) of include. cosmiq-ref-1-ideal has none, so its model is empty and its runs are exactly the noiseless ones. hardware=True reads the groups “coherence” and “ramp” too (asking for them without it raises FormatError); it refuses ramp corrections that don’t agree on one filter (ramp_fit).

classmethod none() → NoiseModel#

No noise at all: the same as noise=None.

without(*names: str) → NoiseModel#

The same model without these groups (“spam”) or keys (“spam.false_positive”).

scaled(factor: float) → NoiseModel#

Every noise strength times factor (0 turns it off, 0.5 halves it): the sigmas and probabilities, the rates 1/T1 and the dephasing rate (so T1 becomes T1/factor), and the ramp filter’s time constant. The beam waist isn’t an error, so it stays; a probability scaled above 1 raises FormatError. scaled(0) never raises: T1 is then infinite (the key moves to unused) and the ramp corrections are all 1.

value(key: str) → float | Tensor#

The value of key, or 0.0 when the model doesn’t have it.

active(key: str) → bool#

True when key is in the model and acts: a non-zero value, or for the ramp corrections a filter with a time constant above 0.

stochastic(has_local: bool) → bool#

True when a trajectory draws something: then a run needs K trajectories. T2 and loss during the sequence (hardware) draw per trajectory too.

property is_empty: bool#

True when nothing is active: a run is then exactly the noiseless one.

class cosmiq.emulator.Observable(name: str)#

Bases: object

A diagonal observable. Build one with density(), correlation(), probabilities(), projector(...) or diagonal(...); name keys the result’s expectations.

shape(n_atoms: int) → tuple[int, ...]#

The shape of one batch row’s value.

bind(n_atoms: int, batch: int, device: device) → Callable[[Readout], tuple[Tensor, Tensor | None]]#

Checks the observable against a register of n_atoms (FormatError) and returns its per-trajectory evaluation.

class cosmiq.emulator.UnverifiedWarning(message: str = '', *, hits: Sequence[Hit] = (), reason: str = '', site: str = '')

Bases: UserWarning

A 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’s unverified;

  • site: “file:line” where the emulator was built.

Functions

cosmiq.emulator.correlation() → Observable#

\(\langle n_i n_j \rangle\), [B, N, N], with \(\langle n_i \rangle\) on the diagonal; empty sites left out pair by pair.

cosmiq.emulator.density() → Observable#

\(\langle n_i \rangle\) per atom, [B, N], empty sites left out (\(E[n_i \cdot \mathrm{pre}_i]/E[\mathrm{pre}_i]\)).

cosmiq.emulator.diagonal(weights_or_fn: Any, *, name: str = 'diagonal') → Observable#

\(\sum_b w_b P(b)\), [B]: weights_or_fn is a \([2^N]\) weight vector (array or tensor, which may require grad), or a function of the bits, fn(bits) -> [2^N], where bits is a \([2^N, N]\) int64 tensor (row \(b\) is basis state \(b\), atom 0 first).

cosmiq.emulator.probabilities(*, allow_large: bool = False) → Observable#

The read bitstring distribution, \([B, 2^N]\) float64 in CONVENTIONS.state_order (atom 0 the most significant bit). Refused above 2 GiB unless allow_large=True.

cosmiq.emulator.projector(bitstrings: Sequence[str | Sequence[int]] | str, *, name: str = 'projector') → Observable#

The probability of reading any of bitstrings, [B]. A bitstring is atom 0 first: “0110”, “grrg”, or [0, 1, 1, 0].

cosmiq.emulator.unverified_bypass_count() → int#

How many calls in this process bypassed at least one refusal through an Emulator(..., unverified=...) and passed their pre-run checks. Monotonic; it can’t be set or reset. A forked child starts from its parent’s count at the fork, a spawned one from 0.