{ "cells": [ { "cell_type": "markdown", "id": "7375bd21", "metadata": {}, "source": [ "Generated from cosmiq's `docs/tutorials/04_remote_offline.py` for Colab: the first cell installs cosmiq." ] }, { "cell_type": "code", "execution_count": null, "id": "41f37e2b", "metadata": {}, "outputs": [], "source": [ "%pip install --quiet cosmiq" ] }, { "cell_type": "markdown", "id": "6c663b7b", "metadata": {}, "source": [ "# Tutorial 4: remote jobs, offline, with `cq.remote.local()`\n", "\n", "A remote session (`cq.remote.session(\"emu:gpu\", max_minutes=30)`) runs your jobs on your own\n", "box: a job is data (the schedule, the observables, the options), never your code. `local()`\n", "has the same API and runs each job in this process, through the very function a box answers\n", "with (`cq.remote.execute`). So this tutorial runs anywhere, without an account, and the same\n", "code runs on a box by swapping `local()` for `session(...)`. We'll\n", "\n", "1. train a sweep, the expectations coming back as remote results attached to our graph;\n", "2. estimate the same gradient with SPSA from shots, all evaluation points in one job;\n", "3. submit a job and collect it later.\n", "\n", "Remote jobs aren't open yet, and `local()` lets you write and test this code now.\n", "\n", "Run it with `python docs/tutorials/04_remote_offline.py`. `COSMIQ_TUTORIAL_QUICK=1` gives a\n", "quick version, which runs in a few seconds. docs/remote.md has the details." ] }, { "cell_type": "code", "execution_count": null, "id": "2fb21a02", "metadata": {}, "outputs": [], "source": [ "import os\n", "\n", "import torch\n", "\n", "import cosmiq as cq\n", "from cosmiq.emulator import density, projector\n", "from cosmiq.units import MHz, um, us\n", "\n", "QUICK = os.environ.get(\"COSMIQ_TUTORIAL_QUICK\") == \"1\"\n", "ATOMS = 3\n", "DURATION = 1.0 * us\n", "STEPS = 2 if QUICK else 25\n", "SAMPLES = 2 if QUICK else 10" ] }, { "cell_type": "markdown", "id": "4ca36d9c", "metadata": { "lines_to_next_cell": 2 }, "source": [ "## The program\n", "\n", "$\\Omega$ ramps up, holds and ramps down, and the detuning sweeps between two trainable values,\n", "through a tanh (any torch code works; gradients flow back through it on your machine)." ] }, { "cell_type": "code", "execution_count": null, "id": "0263a382", "metadata": {}, "outputs": [], "source": [ "class Sweep(cq.AnalogProgram):\n", " def __init__(self) -> None:\n", " super().__init__(cq.Register.chain(ATOMS, spacing=6.1 * um))\n", " self.start = torch.nn.Parameter(torch.tensor(-0.5, dtype=torch.float64))\n", " self.stop = torch.nn.Parameter(torch.tensor(0.5, dtype=torch.float64))\n", "\n", " def drive(self) -> cq.GlobalDrive:\n", " ramp = 0.2 * us\n", " t = [0.0, ramp, DURATION - ramp, DURATION]\n", " omega = 1.0 * MHz\n", " start, stop = 2.0 * MHz * torch.tanh(self.start), 2.0 * MHz * torch.tanh(self.stop)\n", " return cq.GlobalDrive(\n", " amplitude=cq.pwl(t, [0.0, omega, omega, 0.0]),\n", " detuning=cq.pwl(t, [start, start, stop, stop]),\n", " )\n", "\n", "\n", "program = Sweep().to_target(\"cosmiq-ref-1\")\n", "target = projector(\"rgr\", name=\"rgr\")" ] }, { "cell_type": "markdown", "id": "b2f99bca", "metadata": {}, "source": [ "## The session\n", "\n", "The three parts run in one session, so they share one cell; a comment opens each." ] }, { "cell_type": "code", "execution_count": null, "id": "3cd80099", "metadata": {}, "outputs": [], "source": [ "# 1. Train. `box.run` sends one job per step. The box returns P(rgr) and its Jacobian with\n", "# respect to the schedule's slots in the same answer, and `loss.backward()` carries it to θ.\n", "\n", "with cq.remote.local() as box: # on a box: cq.remote.session(\"emu:cpu\", max_minutes=10)\n", " optimizer = torch.optim.Adam(program.parameters(), lr=0.2)\n", " for _ in range(STEPS):\n", " optimizer.zero_grad()\n", " result = box.run(program(), observables=[target])\n", " loss = 1 - result.expectations[\"rgr\"][0]\n", " loss.backward()\n", " optimizer.step()\n", " print(f\"P(rgr) after {STEPS} steps: {1 - float(loss.detach()):.3f}\")\n", "\n", " # The same numbers as a local run, bitwise.\n", " with torch.no_grad():\n", " here = cq.Emulator().run(program(), observables=[target]).expectations[\"rgr\"]\n", " there = box.run(program(), observables=[target]).expectations[\"rgr\"]\n", " print(\"the same numbers as a local run, bitwise:\", torch.equal(here, there))\n", "\n", " # 2. SPSA from shots, as hardware would have to estimate it. Every evaluation point's\n", " # schedule is computed here, and all of them go to the box in one job, each seeded as the\n", " # local estimator seeds it: the estimate equals the local one, bitwise.\n", "\n", " def from_shots(result: cq.emulator.EmulationResult) -> float:\n", " \"\"\"The fraction of shots that read r g r.\"\"\"\n", " (shots,) = result.shots or ()\n", " return float((shots.labels == [1, 0, 1]).all(axis=1).mean())\n", "\n", " box.emulator = cq.Emulator(observable=density())\n", " remote = cq.gradients.estimate(\n", " program, from_shots, method=\"spsa\", emulator=box, shots=200, samples=SAMPLES, seed=1\n", " )\n", " local = cq.gradients.estimate(\n", " program,\n", " from_shots,\n", " method=\"spsa\",\n", " emulator=box.emulator,\n", " shots=200,\n", " samples=SAMPLES,\n", " seed=1,\n", " )\n", " same = all(torch.equal(remote.value[k], local.value[k]) for k in local.value)\n", " print(f\"SPSA from {remote.shots} shots in one job: {dict(remote.value)}; as local: {same}\")\n", "\n", " # 3. Submit now, collect later: a job's result comes back detached from any graph.\n", "\n", " with torch.no_grad():\n", " job = box.submit(program(), observables=[density()], shots=100, seed=7)\n", " print(f\"job {job.id}: {job.status()}\")\n", " print(\"densities:\", job.result().expectations[\"density\"][0].tolist())" ] } ], "metadata": { "jupytext": { "cell_metadata_filter": "-all", "main_language": "python", "notebook_metadata_filter": "-all", "text_representation": { "extension": ".py", "format_name": "percent" } }, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 5 }