cosmiq.runtime#

The hybrid runtime (see the runtime guide): a whole training function, shipped as source, with checkpoints a stop, a crash or a lost process can resume from.

@cq.runtime(target="emu:gpu", max_minutes=60, include=["mymodels"])
def train(cfg):
    ...
    for step in cq.runtime.steps(cfg["steps"], state={"model": model, "opt": opt},
                                 save_every=100):
        ...
        cq.runtime.log(step=step, loss=loss.item())
    return {"loss": loss.item()}

run = train.local({"steps": 20})        # the packed source, in a fresh local process
run = train.local({"steps": 20}, resume_from=run.run_dir)
run = train.local({"steps": 20}, rehearse="vqpu:cosmiq-ref-1")  # its vQPU jobs, here
  • runtime(...) (also cq.runtime(...)): the decorator; train(cfg) stays the plain function.

  • steps(total, state=, save_every=): the loop’s steps, saving state at boundaries.

  • log(**fields): JSON values for this step, as events.

  • Stopped: what a stop raises at its boundary (a KeyboardInterrupt).

  • RefusedError: every refusal, by code.

  • load_checkpoint(path | bytes): a cosmiq.checkpoint/1 file, decoded on the CPU.

  • Runtime, LocalRun, Checkpoint: what the decorator, .local() and load_checkpoint return;

  • Rehearsal: a rehearsal’s report (LocalRun.rehearsal): jobs, shots and projected seconds.

Remote runs, on your own GPU box:

run = train.submit({"steps": 2000})     # queued; it prints the run's id
for event in run.events(): ...          # Ctrl+C detaches: the run goes on
print(run.result())
  • RemoteRun, RemoteCheckpoint: what .submit(), attach and run.checkpoint() return;

  • attach(run_id): a run, from any process; list(active=True): your runs not yet ended.

Sweeps: one remote run per point, at most boxes (1-3) at once:

sw = cq.runtime.sweep(train, [{"lr": 1e-3}, {"lr": 3e-3}], boxes=2, key="lr-scan-1")
for i, event in sw.events(): ...        # Ctrl+C detaches: the started runs go on
out = sw.results()                      # point order
  • sweep(train, cfgs, boxes=, key=), and the Sweep it returns.

cq.runtime is itself callable

cq.runtime(target=..., *, max_minutes, include=..., **more)

Checkpoint

A decoded checkpoint: header (format, step, versions, the determinism record, unverified and its count, blob_bytes), state (each state= key's value: a module's, optimizer's or scheduler's state_dict(), a generator, or the tree it was) and rng (python, numpy_legacy, torch_cpu, torch_cuda).

LocalRun

How a train.local run ended.

RefusedError

A request the runtime refuses, by name: code (one of CODES) and detail.

Rehearsal

A rehearsal's report (LocalRun.rehearsal; also <run_dir>/rehearsal.json, cosmiq.rehearsal/1).

RemoteCheckpoint

A committed checkpoint at the site: step, sha256, nbytes, and unverified (the site's label, from the run's report; the decoded header's is the authoritative one).

RemoteRun

A remote run, as the site last showed it (refresh() asks again).

Runtime

A training function made a runtime: call it as the function, or .local(cfg).

Stopped

A runtime stopped at a boundary after a SIGINT: step is the last step done and saved, committed says whether its checkpoint was committed within 100 s, sha256 is its checkpoint's.

Sweep

A sweep (cq.runtime.sweep): one remote run per point, started in point order while fewer than boxes of them are active.

attach

The run with this id, from any process: one GET.

list

Your runs that haven't ended (active=True, the only listing in v1), at most 50: a run left by a Ctrl+C during submit is found here.

load_checkpoint

Decode a checkpoint, from a file or from its bytes, onto the CPU.

log

Log JSON values for this step: cq.runtime.log(step=step, loss=loss.item()).

runtime

Make a module-level training function a runtime, shipped as source:

steps

The steps of a training loop, 0 to total - 1, with checkpoints inside a runtime.

sweep

Run train once per cfg, each point as its own remote run (train.submit(cfg)), with at most boxes of them at once; returns a Sweep at once, its points starting.

Classes

class cosmiq.runtime.Checkpoint(header: dict[str, Any], state: dict[str, Any], rng: dict[str, Any])#

Bases: object

A decoded checkpoint: header (format, step, versions, the determinism record, unverified and its count, blob_bytes), state (each state= key’s value: a module’s, optimizer’s or scheduler’s state_dict(), a generator, or the tree it was) and rng (python, numpy_legacy, torch_cpu, torch_cuda). Tensors are CPU copies.

header: dict[str, Any]#
state: dict[str, Any]#
rng: dict[str, Any]#
class cosmiq.runtime.LocalRun(status: str, exit_code: int, result: Any, run_dir: Path, events: tuple[dict[str, Any], ...], unverified: bool, rehearsal: Rehearsal | None = None)#

Bases: object

How a train.local run ended.

  • status: “completed”, “stopped” (Ctrl+C or a stop), “failed” (the function raised) or “lost” (the process ended without a status: killed, crashed);

  • exit_code: the child’s (0, 130 stopped, 2 a refusal, 1 another error; < 0 a signal);

  • result: what the function returned (JSON), or None;

  • run_dir: its files (code/, cfg.json, events.jsonl, log.txt, status.json, .ckpt/);

  • events: the events, in order;

  • unverified: True when an emulator call bypassed a refusal in the run;

  • rehearsal: a rehearsal’s report (rehearse=), else None.

status: str#
exit_code: int#
result: Any#
run_dir: Path#
events: tuple[dict[str, Any], ...]#
unverified: bool#
rehearsal: Rehearsal | None = None#
checkpoint() → Checkpoint | None#

The run’s latest committed checkpoint, decoded on the CPU; None when it has none. CHECKPOINT_SHA256 when the file doesn’t match its marker.

class cosmiq.runtime.RefusedError(code: str, detail: str)#

Bases: CosmiqError

A request the runtime refuses, by name: code (one of CODES) and detail.

class cosmiq.runtime.Rehearsal(target: str, snapshot: dict[str, Any], cosmiq: str, seed: str, seed_source: str, status: str, code: str | None, jobs: int, jobs_completed: int, jobs_failed: int, shots: int, projected_seconds: float, executed_calibration_ids: tuple[str, ...], priced: bool, path_dependent: bool, log: str)#

Bases: object

A rehearsal’s report (LocalRun.rehearsal; also <run_dir>/rehearsal.json, cosmiq.rehearsal/1).

  • target, snapshot (its values, snapshot_id, source, fetched_at, url), cosmiq;

  • seed (a decimal string: pass it back as rehearse_seed= to repeat the run), and seed_source, “given” or “drawn”;

  • status: “complete” (the run completed), “partial” (stopped, failed or lost), or “refused” (an emulator call bypassed a refusal: REHEARSAL_UNVERIFIED, its code);

  • jobs, jobs_completed, jobs_failed (every other outcome, a job cut short while it ran included), shots (shots * rows, summed) and projected_seconds (the site’s formula, summed with math.fsum): over the jobs booked, up to the end or the refusal, always numbers;

  • executed_calibration_ids: the calibrations the jobs ran under (shown, not checked against the snapshot’s);

  • priced: always False, nothing is; path_dependent: always True, since a loop whose jobs depend on its results gives totals for this run’s path only;

  • log: the job log, one line per booked job.

target: str#
snapshot: dict[str, Any]#
cosmiq: str#
seed: str#
seed_source: str#
status: str#
code: str | None#
jobs: int#
jobs_completed: int#
jobs_failed: int#
shots: int#
projected_seconds: float#
executed_calibration_ids: tuple[str, ...]#
priced: bool#
path_dependent: bool#
log: str#
class cosmiq.runtime.RemoteCheckpoint(run: RemoteRun, step: int, sha256: str, nbytes: int, unverified: bool)#

Bases: object

A committed checkpoint at the site: step, sha256, nbytes, and unverified (the site’s label, from the run’s report; the decoded header’s is the authoritative one).

load() → Checkpoint#

Download it (a fresh signed URL), check its length and sha256 against the record (CHECKPOINT_SHA256), and decode it on the CPU.

class cosmiq.runtime.RemoteRun(client: Client, view: dict[str, Any])#

Bases: object

A remote run, as the site last showed it (refresh() asks again). Only the site sets its status: queued (no box yet), starting (leased, unpacking), running, then one of completed, failed, stopped or lost (no clean end).

property id: str#
property status: str#
property lineage_id: str | None#
property code: str | None#

The end’s code (status_detail.code): STOPPED, DEADLINE, RESULT_MISSING, …

property message: str | None#
property final_commit: bool | None#

For a stopped run: whether its last save was committed.

property events_refused: int | None#

Events the site refused and the box dropped, never retried, as the run’s status detail reports them; None when it doesn’t say.

property session_id: str | None#
property session_opened: bool#

True when the run opened its session (it ends with the run).

property image_id: str | None#
property entry: str | None#
property max_minutes: int | None#
property box_seconds: float | None#

The box time the run took, in seconds, unrounded: for a session it opened, the session’s billed span; for a reused one, the run’s lease to its end. None until it’s known.

property box_minutes: float | None#

box_seconds / 60, unrounded (billing itself counts started minutes).

property unverified: bool#

True when the run reported bypassing an emulator refusal (self-reported).

property unverified_bypass_count: int#

The largest bypass count the run reported (self-reported).

property resume_from: str | None#

The run this one resumed.

property resume_step: int | None#

The step of the checkpoint the resume started from (chosen at its create).

property created_at: str | None#
property started_at: str | None#
property deadline_at: str | None#
property ended_at: str | None#
refresh() → RemoteRun#

Ask the site for the run’s view again (one GET); the run itself.

events(after: int = 0) → Iterator[dict[str, Any]]#

The run’s events after after, in seq order, each once, as the box wrote them ({"seq", "t", "type", ...}; unknown types too), by long-polls, until the run ended and every stored event was given. A lost run’s end adds one `{“seq”: None, “type”: “status”, “status”: “lost”, “source”: “site”}`. Ctrl+C detaches: the run goes on.

stop() → str#

Ask the run to stop at its next step boundary (its box gets a SIGINT within a heartbeat, about 10 s); the status. A run that ended stays as it is.

resume(*, max_minutes: int | None = None, session: RemoteSession | None = None, idempotency_key: str | None = None) → RemoteRun#

A new run that goes on from this one’s newest committed checkpoint (its lineage’s), with the same code and cfg. RESUME_COMPLETED for a completed run; the site refuses LINEAGE_BUSY while a run of the lineage is live, and NOTHING_TO_RESUME when the lineage committed nothing. session= resumes on that session’s box (the only way back to the same box, which the CPU claim needs).

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

Wait (long-polls) for the run’s end; what the function returned, when it completed. RUN_ENDED_WITHOUT_RESULT for any other end; TimeoutError past timeout seconds. Ctrl+C detaches: the run goes on.

checkpoint(step: int | None = None) → RemoteCheckpoint | None#

A committed checkpoint the site still keeps (the latest 3 of the lineage): the newest, or the one of step; None when there’s none.

logs() → str | None#

The run’s final log.txt (its last 32 MiB), or None when it wasn’t uploaded.

class cosmiq.runtime.Runtime(function: Callable[[P], R], target: str, max_minutes: int, include: tuple[str, ...])#

Bases: Generic[P, R]

A training function made a runtime: call it as the function, or .local(cfg).

__call__(*args: ~P, **kwargs: ~P) → R#
local(cfg: object, *, run_dir: str | PathLike[str] | None = None, resume_from: str | PathLike[str] | None = None, rehearse: str | None = None, rehearse_seed: int | None = None, rehearse_snapshot: TargetStatus | str | os.PathLike[str] | None = None) → LocalRun#

Run the function as a runtime in a fresh local process, from its packed source, with cfg (JSON, at most 64 KiB) as its argument. Blocks until it ends; Ctrl+C asks it to stop at its next step boundary (a second one stops it at once).

  • run_dir: where the run’s files go (default: a new temporary directory);

  • resume_from: a stopped or lost run’s directory, to go on from its last committed checkpoint;

  • rehearse: a vqpu:* target, to rehearse the run against the virtual QPU (see “Practice runs before the virtual QPU” in the runtime guide): its cq.remote.session(rehearse) jobs run here, each checked as the site checks it and booked with the site’s projected seconds; no job leaves this machine, and nothing is priced. LocalRun.rehearsal holds the report;

  • rehearse_seed: the root seed of the jobs’ shots, an int in [0, 2**63) (default: drawn, and recorded in the report);

  • rehearse_snapshot: the target’s numbers: None fetches them (one GET /v1/targets), or a cq.remote.TargetStatus, or a snapshot file (a run’s rehearsal-snapshot.json).

ALREADY_ON_A_BOX inside a runtime; REHEARSAL_TARGET, REHEARSAL_SNAPSHOT, and NOT_IN_V1 for rehearse= with resume_from=.

submit(cfg: object, *, session: RemoteSession | None = None, tier: str | None = None, idempotency_key: str | None = None, api_key: str | None = None, url: str | None = None, rehearse: object = None, resume_from: object = None) → RemoteRun#

Run the function on your own GPU box (see the runtime guide): pack its source against the site’s pinned image, upload it, and queue the run, with cfg (a JSON object, at most 64 KiB). Returns at once, with the run queued; it prints the run’s id.

  • session: a cq.remote.session("emu:gpu", ..., keep=True) of yours to run in (it stays yours: the run never ends it); default: the site opens one for the run and ends it with the run;

  • tier: the GPU tier of the session the site opens (not with session=);

  • idempotency_key: 8-128 characters of [A-Za-z0-9_-], so the same call after a crash gives the same run;

  • api_key, url: as cq.remote.session’s.

ALREADY_ON_A_BOX on a box; NOT_IN_V1 for rehearse= and resume_from= (use run.resume()); NOT_JSON for a cfg that isn’t an object; IMAGE_UNPINNED when the site has no pinned image; the packer’s codes; the site’s (PLAN_LIMIT, SESSION_TOO_SHORT, QUOTA, IMAGE_CHANGED, …).

class cosmiq.runtime.Stopped(step: int, committed: bool, sha256: str)#

Bases: KeyboardInterrupt

A runtime stopped at a boundary after a SIGINT: step is the last step done and saved, committed says whether its checkpoint was committed within 100 s, sha256 is its checkpoint’s. A KeyboardInterrupt, so code that doesn’t catch it stops as on Ctrl+C.

class cosmiq.runtime.Sweep(train: Runtime[..., Any], cfgs: list[dict[str, Any]], boxes: int, key: str)#

Bases: object

A sweep (cq.runtime.sweep): one remote run per point, started in point order while fewer than boxes of them are active.

  • events(): each started point’s events as (i, event), until every point has ended;

  • results(): waits for that, then each point’s outcome in point order: what its function returned, or the error its run ended with (RUN_ENDED_WITHOUT_RESULT); a point that never started (after stop() or a detach) holds RemoteError(“not_started”);

  • runs: each point’s RemoteRun, or None before it started; pending: the points not started;

  • stop(): start nothing more, and stop the started runs that haven’t ended.

A start error that isn’t waited out stops the starts, and events() and results() raise it. Ctrl+C in either detaches: the started runs go on, nothing more starts.

property runs: list[RemoteRun | None]#

Each point’s run, or None while it hasn’t started.

property pending: list[int]#

The points not started, in order.

events() → Iterator[tuple[int, dict[str, Any]]]#

Each started point’s events as (i, event) (each as RemoteRun.events() gives it), as they come, until every point has ended. Ctrl+C detaches.

results() → list[Any]#

Wait until every point has ended; each point’s outcome, in point order: what the function returned, or its run’s error. Ctrl+C detaches.

stop() → None#

Start nothing more, and stop each started run that hasn’t ended (its RemoteRun.stop(): at its next step boundary).

Functions

cosmiq.runtime.attach(run_id: str, *, api_key: str | None = None, url: str | None = None) → RemoteRun#

The run with this id, from any process: one GET. RUN_NOT_FOUND when no run of yours has it.

cosmiq.runtime.list(*, active: bool = True, api_key: str | None = None, url: str | None = None) → list[RemoteRun]#

Your runs that haven’t ended (active=True, the only listing in v1), at most 50: a run left by a Ctrl+C during submit is found here.

cosmiq.runtime.load_checkpoint(source: str | PathLike[str] | bytes) → Checkpoint#

Decode a checkpoint, from a file or from its bytes, onto the CPU. Its checks run in order: size, magic, version, sha256, header, total size, leaves; the first that fails names the refusal (CHECKPOINT_TOO_LARGE, _TRUNCATED, _MAGIC, _VERSION, _SHA256, _HEADER, _LEAF).

cosmiq.runtime.log(**fields: object) → None#

Log JSON values for this step: cq.runtime.log(step=step, loss=loss.item()). Inside a runtime they become a log event, flushed at most once a second; outside, a line on the “cosmiq.runtime” logger at INFO. NOT_JSON for a value JSON can’t hold (a tensor, NaN); TOO_LARGE past 4 KiB an event.

cosmiq.runtime.runtime(target: str = 'emu:gpu', *, max_minutes: int, include: Sequence[str] = (), deps: object = _NO_DEPS) → Callable[[Callable[[P], R]], Runtime[P, R]]#

Make a module-level training function a runtime, shipped as source:

@cq.runtime(target="emu:gpu", max_minutes=60, include=["mymodels"])
def train(cfg): ...
  • target: “emu:gpu”, the only one in v1 (NOT_IN_V1 otherwise);

  • max_minutes: the longest the run may take;

  • include: directories (their .py files) and files to ship with the function’s own file, relative to its root (the directory its top-level package is in).

  • deps= is refused (NO_DEPS_IN_V1): a runtime’s image is fixed.

train(cfg) calls the function as it is; train.local(cfg) runs it as a runtime, here.

cosmiq.runtime.steps(total: int, *, state: Mapping[str, object], save_every: int) → Iterator[int]#

The steps of a training loop, 0 to total - 1, with checkpoints inside a runtime.

  • state: what a checkpoint holds, by name: modules, optimizers and LR schedulers (their state_dict()), torch (CPU) and numpy generators, dicts, lists, tensors and numpy arrays (restored in place). Python’s, NumPy’s and torch’s global generators are always saved.

  • save_every: save after every this many steps; also after the last, and at a stop.

FormatError for a bad argument; CHECKPOINT_TYPE or CHECKPOINT_TOO_LARGE (checked now, by a trial encode; a state that grows, an optimizer’s, can still pass 32 MiB at a later save) for a state a checkpoint can’t hold; STEPS_ONCE for a second call in one run.

cosmiq.runtime.sweep(train: Runtime[..., Any], cfgs: Sequence[dict[str, Any]], *, boxes: int, key: str | None = None, session: object = None) → Sweep#

Run train once per cfg, each point as its own remote run (train.submit(cfg)), with at most boxes of them at once; returns a Sweep at once, its points starting.

  • cfgs: 1 to 16 cfgs, each a JSON object (SWEEP_SIZE; the cfg’s own refusals, naming the point);

  • boxes: 1 to 3 runs at once (SWEEP_BOXES); your plan’s jobs-at-once limit holds too: a start it refuses waits for one of the sweep’s runs to end;

  • key: 8-128 characters of [A-Za-z0-9_-]: the same sweep run again with the same key replays the points it started (none: a fresh key);

  • session= isn’t taken (SWEEP_SESSION): every point boots its own box.

SWEEP_TARGET for a runtime whose target isn’t emu:gpu; ALREADY_ON_A_BOX inside a run.