{ "cells": [ { "cell_type": "markdown", "id": "30207655", "metadata": {}, "source": [ "Generated from cosmiq's `docs/tutorials/01_detuning_sweep.py` for Colab: the first cell installs cosmiq." ] }, { "cell_type": "code", "execution_count": null, "id": "7626cb5f", "metadata": {}, "outputs": [], "source": [ "%pip install --quiet cosmiq" ] }, { "cell_type": "markdown", "id": "8a1ff819", "metadata": {}, "source": [ "# Tutorial 1: prepare an ordered state with a detuning sweep, and train the sweep\n", "\n", "Atoms in a chain, close enough that two neighbours can't both be in the Rydberg state (the\n", "blockade), are driven while the detuning sweeps from negative to positive. Done slowly, this\n", "carries the chain from all-ground to its antiferromagnetic state, r g r g r: every other atom\n", "excited. We'll\n", "\n", "1. build the sweep as a cosmiq program, checked against the cosmiq-ref-1 device;\n", "2. emulate it, and read the probability of the target state;\n", "3. train the sweep with exact gradients, keeping $\\Omega$ at most the device's maximum;\n", "4. estimate the same gradient the way hardware would have to, from shots;\n", "5. sample the trained program, as the device would be read.\n", "\n", "Run it with `python docs/tutorials/01_detuning_sweep.py`. `COSMIQ_TUTORIAL_QUICK=1` gives a\n", "quick version, which runs in a few seconds." ] }, { "cell_type": "code", "execution_count": null, "id": "7c070598", "metadata": {}, "outputs": [], "source": [ "import os\n", "from collections import Counter\n", "\n", "import torch\n", "\n", "import cosmiq as cq\n", "from cosmiq.emulator import projector\n", "from cosmiq.units import MHz, um, us\n", "\n", "QUICK = os.environ.get(\"COSMIQ_TUTORIAL_QUICK\") == \"1\"\n", "ATOMS = 3 if QUICK else 5\n", "DURATION = 1.0 * us if QUICK else 1.5 * us\n", "STEPS = 2 if QUICK else 30\n", "TARGET = \"rg\" * (ATOMS // 2) + \"r\" # \"rgr\", or \"rgrgr\"" ] }, { "cell_type": "markdown", "id": "a671199f", "metadata": { "lines_to_next_cell": 2 }, "source": [ "## 1. The program\n", "\n", "$\\Omega$ ramps up, holds and ramps down; the detuning sweeps linearly between two trainable\n", "values. We start from a sweep that's too shallow to reach the ordered state reliably. $\\Omega$\n", "is kept within the device's limit, and training may push it right up to that limit." ] }, { "cell_type": "code", "execution_count": null, "id": "5b1f24fe", "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.omega = cq.bounded(\n", " 1.0 * MHz,\n", " low=0.0,\n", " high=\"device\",\n", " field=\"analog.rydberg_global.amplitude.max\",\n", " mode=\"clamp\",\n", " )\n", " self.start = torch.nn.Parameter(torch.tensor(-1.0 * MHz, dtype=torch.float64))\n", " self.stop = torch.nn.Parameter(torch.tensor(1.0 * MHz, dtype=torch.float64))\n", "\n", " def drive(self) -> cq.GlobalDrive:\n", " ramp = 0.4 * us\n", " t = [0.0, ramp, DURATION - ramp, DURATION]\n", " omega = self.omega()\n", " return cq.GlobalDrive(\n", " amplitude=cq.pwl(t, [0.0, omega, omega, 0.0]),\n", " detuning=cq.pwl(t, [self.start, self.start, self.stop, self.stop]),\n", " )\n", "\n", "\n", "program = Sweep().to_target(\"cosmiq-ref-1\") # the register and a trial drive, checked now\n", "print(f\"{ATOMS} atoms, Ω ≤ {program.omega.high} rad/µs on cosmiq-ref-1, target {TARGET}\")" ] }, { "cell_type": "markdown", "id": "dedd9c6b", "metadata": {}, "source": [ "## 2. Emulate it\n", "\n", "The emulator returns expectation values as tensors that keep their gradient." ] }, { "cell_type": "code", "execution_count": null, "id": "78cde611", "metadata": {}, "outputs": [], "source": [ "emulator = cq.Emulator(observable=projector(TARGET))\n", "with torch.no_grad(): # just a look: no gradient needed\n", " before = float(emulator(program())[0])\n", "print(f\"P({TARGET}) before training: {before:.3f}\")" ] }, { "cell_type": "markdown", "id": "352ebcca", "metadata": {}, "source": [ "## 3. Train\n", "\n", "`cq.project_(program, after=optimizer)` puts $\\Omega$ back inside its limits after every step,\n", "so it can sit exactly on the maximum." ] }, { "cell_type": "code", "execution_count": null, "id": "c16853e7", "metadata": {}, "outputs": [], "source": [ "optimizer = torch.optim.Adam(program.parameters(), lr=1.0) # rad/µs per step, about\n", "cq.project_(program, after=optimizer)\n", "for _ in range(STEPS):\n", " optimizer.zero_grad()\n", " loss = 1 - emulator(program())[0]\n", " loss.backward() # the engine's reversible adjoint: exact, in memory that doesn't grow\n", " optimizer.step()\n", "with torch.no_grad():\n", " after = float(emulator(program())[0])\n", " omega, start, stop = float(program.omega()), float(program.start), float(program.stop)\n", "print(f\"P({TARGET}) after {STEPS} steps: {after:.3f}\")\n", "print(f\"Ω = {omega:.3f} rad/µs, sweep {start:.2f} → {stop:.2f} rad/µs\")" ] }, { "cell_type": "markdown", "id": "2a258c51", "metadata": { "lines_to_next_cell": 2 }, "source": [ "## 4. One gradient, three ways\n", "\n", "The adjoint is exact. Hardware gives only shots, so there the gradient must be estimated. SPSA\n", "nudges every parameter at once in a random direction, runs the program on both sides, and turns\n", "the difference into an estimate of the gradient, with its standard error. Its seed fixes every\n", "direction and every shot." ] }, { "cell_type": "code", "execution_count": null, "id": "1f98adf5", "metadata": {}, "outputs": [], "source": [ "def probability(result: cq.emulator.EmulationResult) -> torch.Tensor:\n", " return result.expectations[\"projector\"][0]\n", "\n", "\n", "def counted(result: cq.emulator.EmulationResult) -> float:\n", " labels = result.shots[0].labels # [shots, N] NumPy array: 0 ground, 1 Rydberg\n", " wanted = [1 if c == \"r\" else 0 for c in TARGET]\n", " return float((labels == wanted).all(1).mean())\n", "\n", "\n", "exact = cq.gradients.estimate(program, probability, emulator=emulator)\n", "sampled = cq.gradients.estimate(\n", " program,\n", " counted,\n", " emulator=cq.Emulator(samples_only=True),\n", " shots=300 if QUICK else 2000,\n", " samples=3 if QUICK else 20,\n", " step=0.3,\n", " seed=1,\n", ")\n", "print(f\"gradient by {exact.method}, then {sampled.method} from {sampled.shots} shots:\")\n", "for name, value in exact.value.items():\n", " estimate, error = sampled.value[name], sampled.stderr[name]\n", " print(f\" {name:10s} {float(value):+.4f} {float(estimate):+.4f} ± {float(error):.4f}\")" ] }, { "cell_type": "markdown", "id": "b8282979", "metadata": {}, "source": [ "## 5. Read it as the device would\n", "\n", "Shots, with the device's calibrated noise." ] }, { "cell_type": "code", "execution_count": null, "id": "222b41da", "metadata": {}, "outputs": [], "source": [ "shots = emulator.run(program(), shots=50 if QUICK else 500, noise=\"device\", seed=7).shots[0]\n", "words = Counter(\"\".join(\"gr.\"[b] for b in row) for row in shots.labels.tolist()) # . lost\n", "print(\"most frequent readouts:\", \", \".join(f\"{w} x{n}\" for w, n in words.most_common(3)))" ] } ], "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 }