Tutorial 4: remote jobs, offline, with cq.remote.local()#
A remote session (cq.remote.session("emu:gpu", max_minutes=30)) runs your jobs on your own
box: a job is data (the schedule, the observables, the options), never your code. local()
has the same API and runs each job in this process, through the very function a box answers
with (cq.remote.execute). So this tutorial runs anywhere, without an account, and the same
code runs on a box by swapping local() for session(...). We’ll
train a sweep, the expectations coming back as remote results attached to our graph;
estimate the same gradient with SPSA from shots, all evaluation points in one job;
submit a job and collect it later.
Remote jobs aren’t open yet, and local() lets you write and test this code now.
Run it with python docs/tutorials/04_remote_offline.py. COSMIQ_TUTORIAL_QUICK=1 gives a
quick version, which runs in a few seconds. docs/remote.md has the details.
import os
import torch
import cosmiq as cq
from cosmiq.emulator import density, projector
from cosmiq.units import MHz, um, us
QUICK = os.environ.get("COSMIQ_TUTORIAL_QUICK") == "1"
ATOMS = 3
DURATION = 1.0 * us
STEPS = 2 if QUICK else 25
SAMPLES = 2 if QUICK else 10
The program#
\(\Omega\) ramps up, holds and ramps down, and the detuning sweeps between two trainable values, through a tanh (any torch code works; gradients flow back through it on your machine).
class Sweep(cq.AnalogProgram):
def __init__(self) -> None:
super().__init__(cq.Register.chain(ATOMS, 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:
ramp = 0.2 * us
t = [0.0, ramp, DURATION - ramp, DURATION]
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]),
)
program = Sweep().to_target("cosmiq-ref-1")
target = projector("rgr", name="rgr")
The session#
The three parts run in one session, so they share one cell; a comment opens each.
# 1. Train. `box.run` sends one job per step. The box returns P(rgr) and its Jacobian with
# respect to the schedule's slots in the same answer, and `loss.backward()` carries it to θ.
with cq.remote.local() as box: # on a box: cq.remote.session("emu:cpu", max_minutes=10)
optimizer = torch.optim.Adam(program.parameters(), lr=0.2)
for _ in range(STEPS):
optimizer.zero_grad()
result = box.run(program(), observables=[target])
loss = 1 - result.expectations["rgr"][0]
loss.backward()
optimizer.step()
print(f"P(rgr) after {STEPS} steps: {1 - float(loss.detach()):.3f}")
# The same numbers as a local run, bitwise.
with torch.no_grad():
here = cq.Emulator().run(program(), observables=[target]).expectations["rgr"]
there = box.run(program(), observables=[target]).expectations["rgr"]
print("the same numbers as a local run, bitwise:", torch.equal(here, there))
# 2. SPSA from shots, as hardware would have to estimate it. Every evaluation point's
# schedule is computed here, and all of them go to the box in one job, each seeded as the
# local estimator seeds it: the estimate equals the local one, bitwise.
def from_shots(result: cq.emulator.EmulationResult) -> float:
"""The fraction of shots that read r g r."""
(shots,) = result.shots or ()
return float((shots.labels == [1, 0, 1]).all(axis=1).mean())
box.emulator = cq.Emulator(observable=density())
remote = cq.gradients.estimate(
program, from_shots, method="spsa", emulator=box, shots=200, samples=SAMPLES, seed=1
)
local = cq.gradients.estimate(
program,
from_shots,
method="spsa",
emulator=box.emulator,
shots=200,
samples=SAMPLES,
seed=1,
)
same = all(torch.equal(remote.value[k], local.value[k]) for k in local.value)
print(f"SPSA from {remote.shots} shots in one job: {dict(remote.value)}; as local: {same}")
# 3. Submit now, collect later: a job's result comes back detached from any graph.
with torch.no_grad():
job = box.submit(program(), observables=[density()], shots=100, seed=7)
print(f"job {job.id}: {job.status()}")
print("densities:", job.result().expectations["density"][0].tolist())
P(rgr) after 25 steps: 0.867
the same numbers as a local run, bitwise: True
SPSA from 4000 shots in one job: {'start': tensor(-0.0500, dtype=torch.float64), 'stop': tensor(-0.0300, dtype=torch.float64)}; as local: True
job ec2d3a41-58e3-40d8-b719-8334b30cc41e: completed
densities: [0.8767772943435332, 0.09467924027946088, 0.8767772943435331]