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(...)(alsocq.runtime(...)): the decorator;train(cfg)stays the plain function.steps(total, state=, save_every=): the loop’s steps, savingstateat 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): acosmiq.checkpoint/1file, decoded on the CPU.Runtime,LocalRun,Checkpoint: what the decorator,.local()andload_checkpointreturn;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(),attachandrun.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 theSweepit returns.
cq.runtime is itself callable
cq.runtime(target=..., *, max_minutes, include=..., **more)
A decoded checkpoint: |
|
How a |
|
A request the runtime refuses, by name: |
|
A rehearsal's report ( |
|
A committed checkpoint at the site: |
|
A remote run, as the site last showed it ( |
|
A training function made a runtime: call it as the function, or |
|
A runtime stopped at a boundary after a SIGINT: |
|
A sweep ( |
|
The run with this id, from any process: one GET. |
|
Your runs that haven't ended ( |
|
Decode a checkpoint, from a file or from its bytes, onto the CPU. |
|
Log JSON values for this step: |
|
Make a module-level training function a runtime, shipped as source: |
|
The steps of a training loop, 0 to |
|
Run |
Classes
- class cosmiq.runtime.Checkpoint(header: dict[str, Any], state: dict[str, Any], rng: dict[str, Any])#
Bases:
objectA decoded checkpoint:
header(format, step, versions, the determinism record, unverified and its count, blob_bytes),state(eachstate=key’s value: a module’s, optimizer’s or scheduler’sstate_dict(), a generator, or the tree it was) andrng(python, numpy_legacy, torch_cpu, torch_cuda). Tensors are CPU copies.
- 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:
objectHow a
train.localrun 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.
- 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:
CosmiqErrorA request the runtime refuses, by name:
code(one ofCODES) anddetail.
- 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:
objectA 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 asrehearse_seed=to repeat the run), andseed_source, “given” or “drawn”;status: “complete” (the run completed), “partial” (stopped, failed or lost), or “refused” (an emulator call bypassed a refusal: REHEARSAL_UNVERIFIED, itscode);jobs,jobs_completed,jobs_failed(every other outcome, a job cut short while it ran included),shots(shots * rows, summed) andprojected_seconds(the site’s formula, summed withmath.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.
- class cosmiq.runtime.RemoteCheckpoint(run: RemoteRun, step: int, sha256: str, nbytes: int, unverified: bool)#
Bases:
objectA committed checkpoint at the site:
step,sha256,nbytes, andunverified(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:
objectA 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 ofcompleted,failed,stoppedorlost(no clean end).- property code: str | None#
The end’s code (
status_detail.code): STOPPED, DEADLINE, RESULT_MISSING, …
- 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 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 resume_step: int | None#
The step of the checkpoint the resume started from (chosen at its create).
- events(after: int = 0) Iterator[dict[str, Any]]#
The run’s events after
after, inseqorder, 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. Alostrun’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
timeoutseconds. 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.
- 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: avqpu:*target, to rehearse the run against the virtual QPU (see “Practice runs before the virtual QPU” in the runtime guide): itscq.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.rehearsalholds 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 (oneGET /v1/targets), or acq.remote.TargetStatus, or a snapshot file (a run’srehearsal-snapshot.json).
ALREADY_ON_A_BOX inside a runtime; REHEARSAL_TARGET, REHEARSAL_SNAPSHOT, and NOT_IN_V1 for
rehearse=withresume_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 runqueued; it prints the run’s id.session: acq.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 withsession=);idempotency_key: 8-128 characters of [A-Za-z0-9_-], so the same call after a crash gives the same run;api_key,url: ascq.remote.session’s.
ALREADY_ON_A_BOX on a box; NOT_IN_V1 for
rehearse=andresume_from=(userun.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:
KeyboardInterruptA runtime stopped at a boundary after a SIGINT:
stepis the last step done and saved,committedsays whether its checkpoint was committed within 100 s,sha256is 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:
objectA sweep (
cq.runtime.sweep): one remote run per point, started in point order while fewer thanboxesof 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 (afterstop()or a detach) holds RemoteError(“not_started”);runs: each point’sRemoteRun, 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()andresults()raise it. Ctrl+C in either detaches: the started runs go on, nothing more starts.- events() Iterator[tuple[int, dict[str, Any]]]#
Each started point’s events as
(i, event)(each asRemoteRun.events()gives it), as they come, until every point has ended. Ctrl+C detaches.
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 duringsubmitis 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 alogevent, 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.pyfiles) 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 (theirstate_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
trainonce per cfg, each point as its own remote run (train.submit(cfg)), with at mostboxesof them at once; returns aSweepat 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.