Tutorial 7: a practice run before the virtual QPU#
Before you queue a training loop on the virtual QPU, you can find out what it would send.
cosmiq.runtime runs a whole training function as one unit: shipped as source, with
checkpoints that a stop or a crash can resume from, and a practice run (a rehearsal) that books
the loop’s virtual QPU jobs here, on this machine. We’ll
write a training function in a file of its own, and make it a runtime;
run it with
train.local, which saves checkpoints as it goes;stop a run partway, as Ctrl+C would, and resume it from its checkpoint;
check that the resumed run ends exactly where an uninterrupted one does;
rehearse the loop against the virtual QPU: its jobs, its shots and the seconds the site would book, with no job sent and nothing priced.
The virtual QPU isn’t open yet; a practice run sends nothing, so it runs now, on this machine.
Run it with python docs/tutorials/07_practice_run.py. COSMIQ_TUTORIAL_QUICK=1 gives a
quick version, which runs in a few seconds. docs/runtime.md has the details.
import contextlib
import importlib
import io
import json
import math
import os
import shutil
import sys
import tempfile
from pathlib import Path
from typing import Any
import cosmiq as cq
from cosmiq.runtime import LocalRun
QUICK = os.environ.get("COSMIQ_TUTORIAL_QUICK") == "1"
STEPS = 4 if QUICK else 30
SAVE_EVERY = 2 if QUICK else 10
STOP_AT = 2 if QUICK else 14
PRACTICE_STEPS = 2 if QUICK else 8
CFG: dict[str, Any] = {
"steps": STEPS,
"save_every": SAVE_EVERY,
"lr": 0.2,
"shots": 50 if QUICK else 200,
"samples": 2 if QUICK else 4,
"vqpu": False,
}
1. The training function, in a file#
A runtime ships your function’s source, never a pickle, so the function must be at module
level in a .py file (NOT_A_MODULE otherwise). In a project of yours, you write that file.
This tutorial writes it from a string, so the page stays in one piece.
The loop trains tutorial 4’s sweep to read r g r, from shots only, as hardware would have to: each step estimates the gradient by SPSA, two runs per random direction. The function
seeds Python’s, NumPy’s and torch’s global generators first, so that a resumed run can continue exactly as an uninterrupted one;
draws each step’s SPSA seed from torch’s global generator, which every checkpoint saves;
loops over
steps(...), which savesstate(the program and the optimiser) everysave_everysteps, after the last step, and at a stop;logs each step’s parameters with
log, as events;takes its shots from a local emulator, or from the virtual QPU when
cfg["vqpu"]is set;at step
cfg["stop_at"], sends itself the signal Ctrl+C sends, so that this tutorial can stop a run at a step of its choosing.
SOURCE = """\
# sweep_run.py: tutorial 7's training loop, made a runtime.
import contextlib
import random
import signal
from typing import Any
import numpy as np
import torch
import cosmiq as cq
from cosmiq.runtime import log, runtime, steps
from cosmiq.units import MHz, um, us
class Sweep(cq.AnalogProgram):
# Tutorial 4's sweep: Ω fixed, the detuning's two ends trained through a tanh.
def __init__(self) -> None:
super().__init__(cq.Register.chain(3, spacing=6.1 * um))
self.start = torch.nn.Parameter(torch.tensor(-0.5, dtype=torch.float64))
self.stop = torch.nn.Parameter(torch.tensor(0.5, dtype=torch.float64))
def drive(self) -> cq.GlobalDrive:
t = [0.0, 0.2 * us, 0.8 * us, 1.0 * us]
omega = 1.0 * MHz
start, stop = 2.0 * MHz * torch.tanh(self.start), 2.0 * MHz * torch.tanh(self.stop)
return cq.GlobalDrive(
amplitude=cq.pwl(t, [0.0, omega, omega, 0.0]),
detuning=cq.pwl(t, [start, start, stop, stop]),
)
def missed(result: Any) -> float:
# The loss: the fraction of shots that didn't read r g r.
labels = result.shots[0].labels
return 1.0 - float((labels == [1, 0, 1]).all(axis=1).mean())
def shot_source(cfg: dict[str, Any]) -> Any:
# The virtual QPU (a session), or a local emulator that returns shots only.
if cfg["vqpu"]:
return cq.remote.session("vqpu:cosmiq-ref-1")
return contextlib.nullcontext(cq.Emulator(samples_only=True))
@runtime(target="emu:gpu", max_minutes=10)
def train(cfg: dict[str, Any]) -> dict[str, float]:
torch.set_num_threads(1)
random.seed(7)
np.random.seed(7)
torch.manual_seed(7)
program = Sweep().to_target("cosmiq-ref-1")
opt = torch.optim.Adam(program.parameters(), lr=cfg["lr"])
state = {"program": program, "opt": opt}
with shot_source(cfg) as source:
for step in steps(cfg["steps"], state=state, save_every=cfg["save_every"]):
seed = int(torch.randint(0, 2**62, (1,))) # torch's generator: in every checkpoint
grad = cq.gradients.estimate(
program,
missed,
emulator=source,
shots=cfg["shots"],
samples=cfg["samples"],
seed=seed,
)
opt.zero_grad()
for name, parameter in program.named_parameters():
parameter.grad = grad.value[name]
opt.step()
log(step=step, start=program.start.item(), stop=program.stop.item())
if step == cfg.get("stop_at"):
signal.raise_signal(signal.SIGINT) # what Ctrl+C sends
return {"start": program.start.item(), "stop": program.stop.item()}
"""
WORK = Path(tempfile.mkdtemp(prefix="cosmiq-tutorial-7-"))
CODE = WORK / "code"
CODE.mkdir()
(CODE / "sweep_run.py").write_text(SOURCE, encoding="utf-8")
sys.path.insert(0, str(CODE))
sys.modules.pop("sweep_run", None) # a fresh import, should this cell run again
train = importlib.import_module("sweep_run").train # train(cfg) is still the plain function
def local(cfg: dict[str, Any], name: str, **options: Any) -> tuple[LocalRun, str]:
"""`train.local(cfg, ...)` in WORK/runs/<name>, and what it printed to stderr (the package's
file list, and a rehearsal's notice), kept so that this page can show it."""
printed = io.StringIO()
with contextlib.redirect_stderr(printed):
run = train.local(cfg, run_dir=WORK / "runs" / name, **options)
return run, printed.getvalue().replace(str(CODE), "<code>")
2. A run, with its checkpoints#
train.local(cfg) packs the source exactly as a remote run ships it, prints the file list
(the check of what ships), and runs the function in a fresh Python process on this machine.
max_minutes is for remote runs: train.local doesn’t enforce it. The run’s directory keeps
its code, its events, its log and its checkpoints; the LocalRun gives its status, its result
and its events.
plain, listing = local(CFG, "plain")
print(listing, end="")
print(f"{plain.status} (exit code {plain.exit_code}): {plain.result}")
print("its directory:", sorted(path.name for path in plain.run_dir.iterdir()))
logs = [event["fields"] for event in plain.events if event["type"] == "log"]
saved = [event["step"] for event in plain.events if event["type"] == "checkpoint_saved"]
print(f"{len(logs)} log events, the last {logs[-1]}")
print("checkpoints saved after steps", saved)
assert (plain.status, plain.exit_code) == ("completed", 0)
assert [fields["step"] for fields in logs] == list(range(STEPS))
assert saved == [s for s in range(STEPS) if (s + 1) % SAVE_EVERY == 0 or s == STEPS - 1]
cosmiq.runtime: sweep_run:train from <code> (1 files, 2711 bytes, gitignore not applied):
sweep_run.py (2711 bytes)
completed (exit code 0): {'start': -0.5675567169072474, 'stop': 2.2192257277875997}
its directory: ['.ckpt', 'cfg.json', 'code', 'events.jsonl', 'log.txt', 'result.json', 'status.json']
30 log events, the last {'step': 29, 'start': -0.5675567169072474, 'stop': 2.2192257277875997}
checkpoints saved after steps [9, 19, 29]
3. Stop a run, and resume it#
Ctrl+C (SIGINT) inside the loop asks for a stop: the step in progress finishes, the boundary
saves a checkpoint and waits for its commit, and the run ends stopped, with exit code 130
and no result. Our function sends itself that signal at step stop_at.
def status_of(run: LocalRun) -> dict[str, Any]:
"""The run's `status` event, its last."""
return next(event for event in reversed(run.events) if event["type"] == "status")
stopped, _ = local({**CFG, "stop_at": STOP_AT}, "stopped")
status = status_of(stopped)
checkpoint = stopped.checkpoint()
assert checkpoint is not None
print(f"{stopped.status} (exit code {stopped.exit_code}), result {stopped.result}")
print(f"last save after step {status['last_save']}, committed: {status['final_commit']}")
print(f"its latest checkpoint: step {checkpoint.header['step']}")
print(f"it holds {sorted(checkpoint.state)} and the generators {sorted(checkpoint.rng)}")
assert (stopped.status, stopped.exit_code, stopped.result) == ("stopped", 130, None)
assert checkpoint.header["step"] == status["last_save"] == STOP_AT
assert status["final_commit"] is True
stopped (exit code 130), result None
last save after step 14, committed: True
its latest checkpoint: step 14
it holds ['opt', 'program'] and the generators ['numpy_legacy', 'python', 'torch_cpu', 'torch_cuda']
train.local(cfg, resume_from=...) picks the newest committed checkpoint of that run that
verifies, restores the state and every generator before the first step, and goes on from the
saved step + 1.
resumed, _ = local({**CFG, "stop_at": STOP_AT}, "resumed", resume_from=stopped.run_dir)
start = next(event for event in resumed.events if event["type"] == "start")
first = next(event for event in resumed.events if event["type"] == "log")
print(f"{resumed.status}: resumed from step {start['resume_step']}")
print(f"its first step: {first['fields']['step']}; its result: {resumed.result}")
assert resumed.status == "completed"
assert (start["resume_step"], first["fields"]["step"]) == (STOP_AT, STOP_AT + 1)
completed: resumed from step 14
its first step: 15; its result: {'start': -0.5675567169072474, 'stop': 2.2192257277875997}
4. As if it had never stopped#
On the CPU, a resumed run continues bitwise identical to an uninterrupted run started with the
same seeds, on the same machine, thread count and versions: a tested claim (on the Claims and
limits page). Each checkpoint_saved event carries the sha256 of the
state and of the generators it saved, so we compare the last save of each run, and their
results.
def last_save(run: LocalRun) -> dict[str, Any]:
"""The run's last `checkpoint_saved` event."""
return [event for event in run.events if event["type"] == "checkpoint_saved"][-1]
for name, run in (("uninterrupted", plain), ("stopped and resumed", resumed)):
save = last_save(run)
state, rng = save["state_sha256"][:16], save["rng_sha256"][:16]
print(f"{name:19s}: step {save['step']}, state {state}..., generators {rng}...")
keys = ("step", "state_sha256", "rng_sha256")
assert [last_save(plain)[key] for key in keys] == [last_save(resumed)[key] for key in keys]
assert plain.result == resumed.result
uninterrupted : step 29, state 439b5de1cf8652de..., generators cdce6ce8fc3de7ad...
stopped and resumed: step 29, state 439b5de1cf8652de..., generators cdce6ce8fc3de7ad...
5. A practice run 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
against the site’s request caps and the target’s atom cap, booked with the seconds the site
would project for it, and run at once on this machine, along the virtual QPU’s own path. The
site projects a job’s seconds as
A rehearsal runs under a snapshot of the target’s numbers. By default it fetches the site’s
(one GET /v1/targets, with your key). Here we supply our own, so that this page runs without
an account: they are numbers we chose for the example, not the site’s. The loop is the same
function, with vqpu set, for a few steps. Each step’s SPSA estimate sends all its points, two
per direction, in one job. A rehearsal models no queue wait, no maintenance window and no price
(docs/runtime.md lists what it doesn’t model).
snapshot = cq.remote.TargetStatus(
id="vqpu:cosmiq-ref-1",
status="online",
queue_depth=0,
next_window=None,
calibration_id=None,
shot_rate_hz=2.0, # our numbers for the example, not the site's
job_overhead_s=2.0,
max_atoms=20,
keys=(),
)
practice_cfg = {**CFG, "steps": PRACTICE_STEPS, "vqpu": True}
practice, printed = local(
practice_cfg,
"practice",
rehearse="vqpu:cosmiq-ref-1",
rehearse_seed=11,
rehearse_snapshot=snapshot,
)
report = practice.rehearsal
assert report is not None
print(printed.splitlines()[-1])
job_log = (practice.run_dir / report.log).read_bytes()
bookings = [line for line in map(json.loads, job_log.splitlines()) if "rows" in line]
for job in bookings:
rows, shots, seconds = job["rows"], job["shots"], job["projected_seconds"]
print(f" job {job['k']}: {rows} rows x {shots} shots, {seconds} s projected")
done = f"{report.jobs} jobs ({report.jobs_completed} completed), {report.shots} shots"
print(f"{report.status}: {done}, {report.projected_seconds} s projected; priced: {report.priced}")
print("calibrations the jobs ran under:", report.executed_calibration_ids)
per_job = CFG["shots"] * 2 * CFG["samples"] # SPSA: two points a direction, one row each
assert (practice.status, report.status, report.priced) == ("completed", "complete", False)
assert (report.jobs, report.jobs_completed) == (PRACTICE_STEPS, PRACTICE_STEPS)
assert report.shots == PRACTICE_STEPS * per_job
for job in bookings:
assert job["shots_total"] == job["shots"] * job["rows"] == per_job
expected = snapshot.job_overhead_s + job["shots_total"] / snapshot.shot_rate_hz
assert job["projected_seconds"] == expected
assert report.projected_seconds == math.fsum(job["projected_seconds"] for job in bookings)
rehearsing vqpu:cosmiq-ref-1 under sha256:49add87ffd08478eae4682c369aa6b2a5c0c93895b056006fbfafdff291daa9a (seed 11): no job leaves this machine, and nothing is priced
job 0: 8 rows x 200 shots, 802.0 s projected
job 1: 8 rows x 200 shots, 802.0 s projected
job 2: 8 rows x 200 shots, 802.0 s projected
job 3: 8 rows x 200 shots, 802.0 s projected
job 4: 8 rows x 200 shots, 802.0 s projected
job 5: 8 rows x 200 shots, 802.0 s projected
job 6: 8 rows x 200 shots, 802.0 s projected
job 7: 8 rows x 200 shots, 802.0 s projected
complete: 8 jobs (8 completed), 12800 shots, 6416.0 s projected; priced: False
calibrations the jobs ran under: ('cosmiq-ref-1/2026-10-31T00:00Z',)
The rehearsal recorded its seed, and wrote the snapshot it ran under to its run directory. Given both back, the same loop on the same machine, with one thread and the same versions, books a byte-identical job log: a tested claim. So a practice run can be repeated, offline.
again, _ = local(
practice_cfg,
"again",
rehearse="vqpu:cosmiq-ref-1",
rehearse_seed=int(report.seed),
rehearse_snapshot=practice.run_dir / "rehearsal-snapshot.json",
)
assert again.rehearsal is not None
same_log = (again.run_dir / again.rehearsal.log).read_bytes() == job_log
print(f"snapshot from a {again.rehearsal.snapshot['source']}, seed {again.rehearsal.seed}")
print("the same job log, byte for byte:", same_log)
assert again.rehearsal.snapshot["snapshot_id"] == report.snapshot["snapshot_id"]
assert same_log
snapshot from a file, seed 11
the same job log, byte for byte: True
The run directories are plain files. We remove ours.
sys.path.remove(str(CODE))
shutil.rmtree(WORK)