cosmiq.remote#

Remote jobs on your own box (see the Remote jobs guide).

with cq.remote.session("emu:gpu", max_minutes=30) as box:
    result = box.run(program(), observables=[cq.emulator.density()])
    loss = -result.expectations["density"][0].mean()
    loss.backward()                     # exact: ∂y/∂slots from the box, θ → slots here
  • session(...): a session on your own box, through the site: a job is data (the schedule, observables, options), never code, and one warm training step is one request.

  • local(): the same API in this process, through execute, for tests and offline work.

  • execute(job): the pure function a box answers a cosmiq.job/1 with.

  • cq.gradients.estimate(..., emulator=box): SPSA and finite differences in one job.

  • session("vqpu:cosmiq-ref-1"): the virtual QPU: shots only, the device’s full noise, the site’s seed; status() is its TargetStatus, and verify checks a job’s signed receipt (the cosmiq[verify] extra).

  • session("vqpu:...", max_vqpu_seconds=, max_shots=, max_jobs=): caps checked before each job is sent; budget() is its Budget.

Budget

A capped vQPU session's caps and what it has counted (session.budget()).

LocalSession

session()'s API in this process: each job goes through execute, as on a box, with no HTTP (cq.remote.local()).

RemoteError

A remote request or job that failed.

RemoteJob

A submitted job (submit): result() waits for it and returns the EmulationResult, detached from any graph.

RemoteSession

A session on the user's own box (cq.remote.session(...)): a context manager that stops the box on exit unless keep=True.

SessionStatus

A session as the site sees it.

TargetStatus

A vQPU target as GET /v1/targets lists it.

execute

Run one cosmiq.job/1 (a dict, or its JSON text) and return its cosmiq.result/1, or the error object {"error": {"code", "message", "details"}}.

local

The remote API in this process: each job is checked and run by execute, as a box would, without HTTP.

session

Open (or reuse) a session on your own box and wait until it's ready, logging its boot marks on the "cosmiq.remote" logger (no job runs without a session).

verify

The receipt of a vQPU job's view (GET /v1/jobs/{id}), checked, in order: its domain; that it names this job (its job_id is the view's id, and job_id when given) and, given the job sent, that job's target; that its key_id is one of keys (a target's TargetStatus.keys, or the list itself) and valid at its released_at; the ed25519 signature over its canonical JSON (needs cosmiq[verify]: an ImportError naming it otherwise); that its result_digest is the view's result's; for a digital job (the job sent is digital, or the result's vqpu block names a profile_version), that it names the result's profile_version; and, given the job (its document or canonical text), that its job_digest is that job's.

Classes

class cosmiq.remote.Budget(max_vqpu_seconds: float | None, spent_vqpu_seconds: float, max_shots: int | None, spent_shots: int, max_jobs: int | None, jobs: int)#

Bases: object

A capped vQPU session’s caps and what it has counted (session.budget()). A cap is None when it isn’t set.

  • spent_vqpu_seconds: the job views’ projected_seconds (what the site booked), summed with math.fsum;

  • spent_shots: shots x rows, summed;

  • jobs: the jobs counted.

A job is counted once the site accepts it, and stays counted unless it was cancelled while queued. A job still being sent isn’t in it yet.

max_vqpu_seconds: float | None#
spent_vqpu_seconds: float#
max_shots: int | None#
spent_shots: int#
max_jobs: int | None#
jobs: int#
class cosmiq.remote.LocalSession(emulator: Emulator | None)#

Bases: _Session

session()‘s API in this process: each job goes through execute, as on a box, with no HTTP (cq.remote.local()).

__enter__() → LocalSession#
__exit__(kind: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None) → None#
property emulator: Emulator#

The emulator whose options a run takes when it’s given none (its torch device means nothing remotely: the target decides). `cq.gradients.estimate(…, emulator=session)reads itsobservableandsamples_only`.

run(schedule: Schedule | ScheduleData, *, observables: Sequence[Observable] | Observable | None = None, shots: int | None = None, seed: int | None = None, emulator: Emulator | None = None, noise: Literal['device', 'hardware'] | NoiseModel | None = None, trajectories: int | None = None, dt: float | None = None, spec: DeviceSpec | None = None, gradient: Literal['auto', 'jacobian', 'vjp', 'none'] = 'auto', initial: Tensor | None = None, keep_state: bool = False, clock: Literal['fast', 'realistic'] | None = None) → EmulationResult#

Emulator.run(schedule, ...), on the session’s box. The arguments are Emulator.run‘s, with emulator for its options (default: the session’s).

When the schedule’s slots carry a gradient (a program’s output, grad on), the expectations come back attached to its graph, so loss.backward() gives exactly local autograd’s gradient. gradient: “auto” takes the Jacobian in the same job while \(O \le 64\) scalar outputs a row and \(B \cdot O \cdot S \le 524{,}288\), else (warning once) the vjp path, a second job in the backward pass; “jacobian” or “vjp” choose; “none” asks for no gradient. Shot mode, samples-only mode and gradient="none" emulators bring no gradient back.

Not carried yet (NotImplementedError, with the local alternative): initial, keep_state, NoiseModel objects (noise="device" and "hardware" are), diagonal(fn).

On a vQPU session (session("vqpu:...")), a run takes shots (1 to 1,000 per row) and clock (“fast”, the default, or “realistic”) only: the box owns the physics, so every other argument raises FormatError before anything is sent. It returns shots (their seed None: the site’s seed stays on the box), no expectations, and the reports’ whitelist.

submit(schedule: Schedule | ScheduleData, *, observables: Sequence[Observable] | Observable | None = None, shots: int | None = None, seed: int | None = None, emulator: Emulator | None = None, noise: Literal['device', 'hardware'] | NoiseModel | None = None, trajectories: int | None = None, dt: float | None = None, spec: DeviceSpec | None = None, gradient: Literal['auto', 'jacobian', 'vjp', 'none'] = 'auto', initial: Tensor | None = None, keep_state: bool = False, clock: Literal['fast', 'realistic'] | None = None) → RemoteJob#

run‘s job, sent without waiting: a RemoteJob, whose result() is detached from any graph (so no gradient is asked for). A vQPU job’s has a receipt().

class cosmiq.remote.RemoteError(message: str, *, code: str, job_id: str | None = None, status: int | str | None = None)#

Bases: CosmiqError

A remote request or job that failed.

  • code: the server’s code: a job’s (invalid_job, run_error, timeout, …; the remote protocol reference lists them all) or an HTTP error’s (NO_SESSION, RATE_LIMITED, …), or the client’s own (network, tls, bad_response, session_failed, cancelled, expired, …);

  • job_id: the job’s id, when a job failed;

  • status: the job’s status (“failed”, “cancelled”, “expired”) when a job failed, the HTTP status for a refused request, else None.

class cosmiq.remote.RemoteJob(ticket: _Ticket, request: Request, keys: Callable[[bool], Sequence[Mapping[str, Any]]] | None = None)#

Bases: object

A submitted job (submit): result() waits for it and returns the EmulationResult, detached from any graph. A vQPU job also has the site’s signed receipt().

property id: str#

The job’s id (a UUID).

status() → str#

queued, running, completed, failed, cancelled or expired.

result(timeout: float | None = None) → EmulationResult#

Wait (long-polls, at most timeout seconds, else as long as it takes) and return the result. Raises ConstraintError when the box’s device check refused the program, RemoteError for any other failure, TimeoutError when timeout passed first.

cancel() → str#

Cancel the job: a queued one at once, a running one at its next heartbeat. Returns its status.

receipt(*, verify: bool = True) → dict[str, Any]#

A vQPU job’s receipt, once it’s done (waiting as result() does): the site’s signed statement that it accepted this result for this job (cq.remote.verify, which verify=True runs with this job’s id, the job sent and the target’s keys: fetched once per session, and once more when a receipt names a key not yet seen, after a rotation). Raises RemoteError(“bad_receipt”) when it doesn’t verify, FormatError for a job that isn’t a vQPU job’s.

class cosmiq.remote.RemoteSession(client: Client, view: dict[str, Any] | None, *, target: Literal['emu:cpu', 'emu:gpu', 'vqpu:cosmiq-ref-1', 'vqpu:cosmiq-ref-1-ideal', 'vqpu:cosmiq-ref-1-future'], keep: bool, max_minutes: int | None)#

Bases: _Session

A session on the user’s own box (cq.remote.session(...)): a context manager that stops the box on exit unless keep=True. On a vqpu:* target it’s the virtual QPU’s handle instead: it starts and stops nothing, and its runs take shots and the clock only.

property emulator: Emulator#

The emulator whose options a run takes when it’s given none (its torch device means nothing remotely: the target decides). `cq.gradients.estimate(…, emulator=session)reads itsobservableandsamples_only`.

property id: str#

The session’s id (a UUID); “” on a vQPU target, which has none.

property target: Literal['emu:cpu', 'emu:gpu', 'vqpu:cosmiq-ref-1', 'vqpu:cosmiq-ref-1-ideal', 'vqpu:cosmiq-ref-1-future']#

“emu:cpu”, “emu:gpu” or a “vqpu:…” target.

budget() → Budget#

A capped vQPU session’s caps, and what it has counted (a Budget: vQPU seconds as the site booked them, shots x rows, and jobs). FormatError for a session opened without caps.

run(schedule: Schedule | ScheduleData, *, observables: Sequence[Observable] | Observable | None = None, shots: int | None = None, seed: int | None = None, emulator: Emulator | None = None, noise: Literal['device', 'hardware'] | NoiseModel | None = None, trajectories: int | None = None, dt: float | None = None, spec: DeviceSpec | None = None, gradient: Literal['auto', 'jacobian', 'vjp', 'none'] = 'auto', initial: Tensor | None = None, keep_state: bool = False, clock: Literal['fast', 'realistic'] | None = None) → EmulationResult#

Emulator.run(schedule, ...), on the session’s box. The arguments are Emulator.run‘s, with emulator for its options (default: the session’s).

When the schedule’s slots carry a gradient (a program’s output, grad on), the expectations come back attached to its graph, so loss.backward() gives exactly local autograd’s gradient. gradient: “auto” takes the Jacobian in the same job while \(O \le 64\) scalar outputs a row and \(B \cdot O \cdot S \le 524{,}288\), else (warning once) the vjp path, a second job in the backward pass; “jacobian” or “vjp” choose; “none” asks for no gradient. Shot mode, samples-only mode and gradient="none" emulators bring no gradient back.

Not carried yet (NotImplementedError, with the local alternative): initial, keep_state, NoiseModel objects (noise="device" and "hardware" are), diagonal(fn).

On a vQPU session (session("vqpu:...")), a run takes shots (1 to 1,000 per row) and clock (“fast”, the default, or “realistic”) only: the box owns the physics, so every other argument raises FormatError before anything is sent. It returns shots (their seed None: the site’s seed stays on the box), no expectations, and the reports’ whitelist.

submit(schedule: Schedule | ScheduleData, *, observables: Sequence[Observable] | Observable | None = None, shots: int | None = None, seed: int | None = None, emulator: Emulator | None = None, noise: Literal['device', 'hardware'] | NoiseModel | None = None, trajectories: int | None = None, dt: float | None = None, spec: DeviceSpec | None = None, gradient: Literal['auto', 'jacobian', 'vjp', 'none'] = 'auto', initial: Tensor | None = None, keep_state: bool = False, clock: Literal['fast', 'realistic'] | None = None) → RemoteJob#

run‘s job, sent without waiting: a RemoteJob, whose result() is detached from any graph (so no gradient is asked for). A vQPU job’s has a receipt().

status() → SessionStatus | TargetStatus#

The session as the site sees it now; on a vQPU target, the target’s entry in GET /v1/targets (a TargetStatus: its status, queue, next window, calibration, shot clock, atom cap and receipt keys).

close() → None#

Stop the session’s box (DELETE /v1/sessions/{id}). Jobs can’t be sent after. A vQPU session stops nothing: it only stops sending.

__enter__() → RemoteSession#
__exit__(kind: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None) → None#
class cosmiq.remote.SessionStatus(id: str, target: str, tier: str | None, state: str, marks: tuple[tuple[str, str], ...], max_until: str | None, idle_minutes: int | None, created_at: str | None, ready_at: str | None, ended_at: str | None, end_reason: str | None)#

Bases: object

A session as the site sees it. state is provisioning, booting, ready, stopping, stopped or failed; marks are the boot marks, (mark, ISO time); times are ISO 8601 UTC strings.

id: str#
target: str#
tier: str | None#
state: str#
marks: tuple[tuple[str, str], ...]#
max_until: str | None#
idle_minutes: int | None#
created_at: str | None#
ready_at: str | None#
ended_at: str | None#
end_reason: str | None#
class cosmiq.remote.TargetStatus(id: str, status: str, queue_depth: int, next_window: tuple[str, str] | None, calibration_id: str | None, shot_rate_hz: float, job_overhead_s: float, max_atoms: int, keys: tuple[Mapping[str, Any], ...])#

Bases: object

A vQPU target as GET /v1/targets lists it. status is online, calibrating, maintenance or offline; next_window is a maintenance window’s (start, end), ISO 8601 UTC; keys are the site’s receipt-signing keys, each {"key_id", "public_key" (base64 of 32 raw ed25519 bytes), "valid_from", "valid_until"}, for verify.

id: str#
status: str#
queue_depth: int#
next_window: tuple[str, str] | None#
calibration_id: str | None#
shot_rate_hz: float#
job_overhead_s: float#
max_atoms: int#
keys: tuple[Mapping[str, Any], ...]#

Functions

cosmiq.remote.execute(job: Mapping[str, Any] | str, *, lease: Mapping[str, Any] | None = None) → dict[str, Any]#

Run one cosmiq.job/1 (a dict, or its JSON text) and return its cosmiq.result/1, or the error object {"error": {"code", "message", "details"}}. Never raises for a bad job or a failed run (see the Remote jobs guide). lease is the site’s `{“seed”: “<decimal 63-bit>”, “max_atoms”: n}`, which a vQPU job needs (and any other job ignores).

cosmiq.remote.local(*, emulator: Emulator | None = None) → LocalSession#

The remote API in this process: each job is checked and run by execute, as a box would, without HTTP. For tests and offline work; emulator is the default for runs.

cosmiq.remote.session(target: Literal['emu:cpu', 'emu:gpu', 'vqpu:cosmiq-ref-1', 'vqpu:cosmiq-ref-1-ideal', 'vqpu:cosmiq-ref-1-future'], *, max_minutes: int | None = None, idle_minutes: int | None = None, tier: str | None = None, keep: bool = False, api_key: str | None = None, url: str | None = None, max_vqpu_seconds: float | None = None, max_shots: int | None = None, max_jobs: int | None = None) → RemoteSession#

Open (or reuse) a session on your own box and wait until it’s ready, logging its boot marks on the “cosmiq.remote” logger (no job runs without a session).

  • target: “emu:cpu” or “emu:gpu”; or the virtual QPU, “vqpu:cosmiq-ref-1” (or its “-ideal” and “-future” siblings);

  • max_minutes (required for “emu:*”): the longest it may run (your plan’s limit caps it); idle_minutes: stop it after that long without a job (your plan’s idle stop caps it); tier: a GPU tier (default: your plan’s lowest);

  • keep: leave the box running when the with block ends (default: stop it);

  • api_key: else COSMIQ_API_KEY, else ~/.config/cosmiq/credentials (mode 600);

  • url: the site, else COSMIQ_URL, else https://identityoperator.com.

The box is billed in minutes, as Code Studio’s are; a job that runs again after its worker was lost costs the minutes it takes again (see the Remote jobs guide).

A “vqpu:*” session is the virtual QPU’s shared queue: it takes no max_minutes, idle_minutes or tier (TypeError), starts nothing and sends nothing until a run.

Its caps (an emu:* session takes none: TypeError): max_vqpu_seconds (the site’s projected seconds, job_overhead_s + shots_total / shot_rate_hz, on the shot clock read when the session opens), max_shots (shots x rows) and max_jobs. A job that would pass one is refused before it’s sent (RemoteError “vqpu_budget”); budget() shows them. They hold within this process, across its threads, not across processes or at the site; and they aren’t rehearsed (NOT_IN_V1 in a rehearsal).

cosmiq.remote.verify(view: Mapping[str, Any], keys: Sequence[Mapping[str, Any]] | TargetStatus, *, job: Mapping[str, Any] | str | None = None, job_id: str | None = None) → dict[str, Any]#

The receipt of a vQPU job’s view (GET /v1/jobs/{id}), checked, in order: its domain; that it names this job (its job_id is the view’s id, and job_id when given) and, given the job sent, that job’s target; that its key_id is one of keys (a target’s TargetStatus.keys, or the list itself) and valid at its released_at; the ed25519 signature over its canonical JSON (needs cosmiq[verify]: an ImportError naming it otherwise); that its result_digest is the view’s result’s; for a digital job (the job sent is digital, or the result’s vqpu block names a profile_version), that it names the result’s profile_version; and, given the job (its document or canonical text), that its job_digest is that job’s. Returns the receipt; any failure, on any input, raises RemoteError(“bad_receipt”).