The runtime: a whole training loop, with checkpoints#

cosmiq.runtime turns your training function into a run you can stop and resume. It saves checkpoints as it goes, so Ctrl+C, a crash or a lost machine costs only the steps since the last save. A run goes on your machine with train.local, on a GPU box with train.submit, as a sweep over several settings, or as a practice run of a virtual QPU loop that sends nothing.

import torch
import cosmiq as cq
from cosmiq.emulator import density
from cosmiq.runtime import log, runtime, steps
from mymodels import build, loss_fn, x  # your code, shipped with the run by include=


@runtime(target="emu:gpu", max_minutes=60, include=["mymodels"])
def train(cfg):
    program, head = build(cfg)  # ordinary torch modules
    opt = torch.optim.Adam([*program.parameters(), *head.parameters()], lr=cfg["lr"])
    emulator = cq.Emulator(precision="double", gradient="adjoint")
    for step in steps(
        cfg["steps"], state={"program": program, "head": head, "opt": opt}, save_every=100
    ):
        opt.zero_grad()
        loss = loss_fn(
            head(emulator.run(program(x), observables=[density()]).expectations["density"])
        )
        loss.backward()
        opt.step()
        log(step=step, loss=loss.item())
    return {"loss": loss.item()}


if __name__ == "__main__":
    run = train.local({"lr": 0.02, "steps": 2000})
    print(run.status, run.result)
    if run.status in ("stopped", "lost"):
        run = train.local({"lr": 0.02, "steps": 2000}, resume_from=run.run_dir)
  • train(cfg) is still your plain function: called directly, steps() is range(total) and saves nothing.

  • @cq.runtime(...) works too. Type checkers see cq.runtime as a module, so typed code uses from cosmiq.runtime import runtime.

  • Guard the call with if __name__ == "__main__":. The run imports your module again in a fresh process, and a train.local there is refused (ALREADY_ON_A_BOX).

  • Seed all three global generators at the start of the function if you want a resumed run to continue exactly as an uninterrupted one would:

    import random
    
    import numpy as np
    import torch
    
    random.seed(7)
    np.random.seed(7)
    torch.manual_seed(7)
    

Tutorial 7 runs a whole example: a run, a stop, a resume and a practice run.

Running on your machine#

train.local(cfg, *, run_dir=None, resume_from=None, rehearse=None, ...) packs your function’s source exactly as a remote run ships it, prints the list of files it packed, and runs the function in a fresh Python process on this machine. cfg must be JSON. It returns a LocalRun once the run ends:

How the function ended

run.status

it returned

completed

a stop was asked for (Ctrl+C)

stopped

it raised

failed

the process was killed, or died

lost

run.result is what the function returned, run.events its events (each log call, each checkpoint, the end), run.run_dir the directory with its code, its log (log.txt) and its checkpoints, and run.checkpoint() its latest checkpoint. max_minutes is for remote runs; train.local doesn’t enforce it.

The run’s environment is yours, less anything that looks like a secret (variables whose names hold KEY, TOKEN, SECRET, PASSWORD and the like, or whose values hold a URL with a password) and less PYTHONPATH. So behind a proxy whose address carries credentials, the run has no network through it.

What ships: source, never pickle#

A run ships your function’s file, plus the files under each directory named in include (.py files) and the files include names, relative to the directory your package is in. Secrets, caches and git-ignored files are left out; the file list printed before each run shows what ships. Matching is by name, so a hard link isn’t caught: a file named notes.txt that is a hard link to ~/.ssh/id_rsa ships. Check the list.

Every import in the package is read (nothing runs), so a missing module is refused before the run starts, not halfway through. The refusals you’re most likely to meet:

Code

When

NOT_A_MODULE

the function isn’t at module level in a .py file (a notebook, the REPL, a nested function)

NOT_IN_PACKAGE

an import of a file that isn’t in the package, or was left out as a secret

NOT_IN_IMAGE

an import found neither in the package nor installed where the run goes

PACK_TOO_MANY_FILES, PACK_TOO_LARGE

the package is too big (Named limits)

The full rules, the list of excluded names and the package format are in the runtime reference.

Steps, saves and stops#

steps(total, *, state, save_every) yields 0 to total - 1, and saves state every save_every steps, after the last step, and at a stop. A save changes nothing in your run: no value and no random generator.

What state holds: names mapped to modules, optimizers and learning-rate schedulers, random generators, and dicts, lists, tensors and numpy arrays. Python’s, NumPy’s and torch’s global generators are always saved too. Anything else is refused before the first step (CHECKPOINT_TYPE), and so is a state too large to save (CHECKPOINT_TOO_LARGE). Tensors inside a dict or list come back on the CPU; a tensor given directly keeps its device.

A stop. The first Ctrl+C inside the loop asks for a stop: the step in progress finishes, the checkpoint is saved, and the run ends stopped. A second Ctrl+C stops at once. So a stop costs at most the rest of the current step plus the save.

  • A step longer than a minute gets a slow_step event: a remote run’s deadline waits for the step in progress, so with steps that long it may fall back to the last periodic save.

  • A supervisor that stops a run should signal the whole process group, not just the parent’s PID: the parent alone never passes the signal on.

  • steps() runs once per run (STEPS_ONCE).

log(**fields) records JSON values for the step, as an event. Outside a run it writes a line on the cosmiq.runtime logger.

Resuming#

train.local(cfg, resume_from=<a stopped or lost run's directory>) picks that run’s newest checkpoint that verifies, restores the state and every generator, and goes on from the step after it. A damaged checkpoint is skipped for the one before it, and the new run’s events say so. A completed run isn’t resumed (RESUME_COMPLETED); a run with no checkpoint that verifies is CHECKPOINT_NONE; and a state whose names or kinds differ from the checkpoint’s is RESUME_MISMATCH.

Reading a checkpoint#

A checkpoint is a plain file, never a pickle, so you can read it outside a run:

ckpt = run.checkpoint()  # the run's latest checkpoint, decoded on the CPU; None if it has none
ckpt.header["step"]  # the step it was saved after, with the versions that saved it
program.load_state_dict(ckpt.state["program"])  # each state= name holds what was saved

path = sorted((run.run_dir / ".ckpt").glob("*.ckpt"))[-1]  # or any checkpoint file
ckpt = cq.runtime.load_checkpoint(path)

A damaged file is refused by name, never decoded halfway. The format is in the runtime reference.

What is claimed#

On the CPU, a resumed run continues bitwise identical to an uninterrupted run started with the same seeds (Python, NumPy, torch), on the same machine, thread count and versions. On CUDA, nothing like that is claimed yet. The tests behind this are in the evidence.

Inside a run#

  • cq.remote.session("emu:…") is refused (RUNTIME_LOCAL_ONLY): the emulator runs in the run’s own process (cq.Emulator(device=...)).

  • train.local, submit and run.resume() are refused inside any run (ALREADY_ON_A_BOX).

  • When an emulator call in the run bypasses a refusal (unverified=), its checkpoints, its events and LocalRun.unverified say so.

Practice runs before the virtual QPU#

train.local(cfg, rehearse="vqpu:cosmiq-ref-1") runs the function as above, and every cq.remote.session("vqpu:cosmiq-ref-1") in it becomes a rehearsed session: each job is checked as the site would check it, booked with the time the site would project for it, and run at once on this machine, along the virtual QPU’s own path. No job leaves this machine, and nothing is priced. It tells you, before you queue a loop on the virtual QPU, how many jobs and shots it sends and how long the site would project them to take.

By default a practice run reads the virtual QPU’s numbers (its shot rate and its overhead per job) from identityoperator.com, which needs an API key. Remote access isn’t open yet, so pass numbers of your own, as here:

numbers = cq.remote.TargetStatus(
    id="vqpu:cosmiq-ref-1",
    status="online",
    queue_depth=0,
    next_window=None,
    calibration_id=None,
    shot_rate_hz=2.0,  # example numbers, not the site's
    job_overhead_s=2.0,
    max_atoms=20,
    keys=(),
)
run = train.local(
    {"lr": 0.02, "steps": 20}, rehearse="vqpu:cosmiq-ref-1", rehearse_snapshot=numbers
)
print(run.rehearsal.jobs, run.rehearsal.shots, run.rehearsal.projected_seconds)
again = train.local(  # the same practice run, repeated offline
    {"lr": 0.02, "steps": 20},
    rehearse="vqpu:cosmiq-ref-1",
    rehearse_seed=int(run.rehearsal.seed),
    rehearse_snapshot=run.run_dir / "rehearsal-snapshot.json",
)
  • rehearse: vqpu:cosmiq-ref-1, vqpu:cosmiq-ref-1-ideal or vqpu:cosmiq-ref-1-future.

  • rehearse_snapshot: the target’s numbers the practice run uses (its shot rate, its overhead per job, its atom limit). By default it fetches them from the site, the one request a practice run makes; you can pass a cq.remote.TargetStatus, or an earlier run’s snapshot file to repeat a run offline.

  • rehearse_seed: the seed of the jobs’ shots. By default it’s drawn, printed and recorded, so passing it back repeats the run.

  • run.rehearsal reports the target, the seed, the jobs booked and completed, the shots, the projected seconds and a status: complete, partial (the run stopped or failed) or refused.

A practice run’s jobs are refused as a real session’s would be, with the same errors. An emulator call that bypasses a refusal anywhere in the run refuses the practice run (REHEARSAL_UNVERIFIED). Queue waits, maintenance windows, plan limits and any price aren’t modelled (the full list), and its shots are never the virtual QPU’s own.

Remote runs, on your own GPU box#

train.submit(cfg) runs the same packed function on a GPU box in the cloud. Remote runs aren’t open yet; train.local(cfg) runs the same function on your machine.

run = train.submit({"lr": 0.02, "steps": 2000})  # returns at once; prints the run's id
for event in run.events():  # Ctrl+C detaches: the run goes on
    if event["type"] == "log":
        print(event["fields"])
print(run.result())  # waits; the function's return value

run = cq.runtime.attach("<run id>")  # from any process, later
run.stop()  # stop at the next step boundary, with a checkpoint
again = run.resume()  # the same code and cfg, from its checkpoint
ckpt = run.checkpoint().load()  # its latest checkpoint, downloaded, checked and decoded
  • GPU only in this release (target="emu:gpu"). The emulator runs in the run’s own process, on the device you name (cq.Emulator(device="cuda:0")).

  • One torch thread to start with: call torch.set_num_threads(n) in your function for more.

  • submit checks the package against the box’s installed packages, so an import train.local took can be refused here (NOT_IN_IMAGE).

  • Sessions. With no session=, the run gets a box of its own, which stops when the run ends. With session= (a cq.remote.session("emu:gpu", max_minutes=..., keep=True) of yours) the run uses that box and leaves it running; a resume lands on the same box only that way.

  • idempotency_key=: the same call with the same key, after a crash say, gives the same run rather than a second one, for up to a day.

  • The run’s deadline is its own: shortly before max_minutes (or your plan’s limit) the run stops itself, as stop() does, and ends stopped with the code DEADLINE.

run.events() gives the run’s events as the box writes them; run.result() waits for the end and gives what the function returned (only a completed run has a result: RUN_ENDED_WITHOUT_RESULT otherwise); run.logs() gives its log.txt; and cq.runtime.list(active=True) lists your runs that haven’t ended. The site keeps each run’s latest checkpoints for a week.

Limits. A box that dies is declared lost within a few minutes, and its billing ends; a site outage at the very end of a run can leave it failed with RESULT_MISSING. Either way, resume it from its last checkpoint. What was tested is in the evidence; the box’s own budgets and the full list of refusals are in the runtime reference.

Sweeps#

cq.runtime.sweep(train, cfgs, boxes=k, key=None) runs train once per cfg, each point as its own remote run, at most k at once. Like remote runs, sweeps aren’t open yet.

sw = cq.runtime.sweep(train, [{"lr": 1e-3}, {"lr": 3e-3}, {"lr": 1e-2}], boxes=2, key="lr-scan-1")
for i, event in sw.events():  # each started point's events; Ctrl+C detaches
    ...
out = sw.results()  # in point order: each run's result, or its error
sw.pending  # the points not started yet
sw.stop()  # start nothing more, and stop the started runs
  • Starts go in point order, while fewer than boxes of the sweep’s runs are active.

  • The key: the same sweep run again with the same key picks up the runs it already started and starts the rest. A changed function or cfg under a used key is refused (SWEEP_CHANGED).

  • Waiting: a start over your plan’s jobs at once waits for a run to end. The site limits how often GPU boxes can start, so a large sweep may wait.

  • Your process runs the sweep: Ctrl+C in events() or results(), or an exit, detaches; the started runs go on, and running the sweep again with the same key goes on from there.

  • A sweep takes 1 to 16 points and 1 to 3 boxes, on emu:gpu only, each point on its own box, and returns forward results only.

Sweeps were tested against simulated sites, not on real boxes (the evidence).