{ "cells": [ { "cell_type": "markdown", "id": "bf2ddc77", "metadata": {}, "source": [ "Generated from cosmiq's `docs/tutorials/02_pennylane_variational.py` for Colab: the first cell installs cosmiq." ] }, { "cell_type": "code", "execution_count": null, "id": "c9eb4465", "metadata": {}, "outputs": [], "source": [ "%pip install --quiet \"cosmiq[pennylane]\"" ] }, { "cell_type": "markdown", "id": "c11c41b8", "metadata": {}, "source": [ "# Tutorial 2: a variational circuit in PennyLane\n", "\n", "Single-qubit gates around an analog block, trained with torch.\n", "\n", "Four atoms in a chain are close enough that neighbours block each other's excitation. A layer\n", "of single-qubit rotations prepares them, a cosmiq drive (a `RydbergEvolution` block) evolves\n", "them, and we train both, the rotation angles and the drive's parameters, to put the chain in\n", "r g g r: its two ends excited. We'll\n", "\n", "1. run the circuit on the PennyLane device \"cosmiq.emulator\";\n", "2. train it with torch, its gradients exact and computed by the device (cosmiq's adjoint,\n", " through the gates and the block alike: `diff_method=\"device\", device_vjp=True`);\n", "3. estimate the same gradient the way hardware would have to, from shots (SPSA).\n", "\n", "It needs the extra: `pip install \"cosmiq[pennylane]\"`. Run it with\n", "`python docs/tutorials/02_pennylane_variational.py`; `COSMIQ_TUTORIAL_QUICK=1` gives a quick\n", "version, which runs in a few seconds." ] }, { "cell_type": "code", "execution_count": null, "id": "86ab2b9d", "metadata": {}, "outputs": [], "source": [ "import os\n", "\n", "import pennylane as qml\n", "import torch\n", "\n", "import cosmiq as cq\n", "from cosmiq.pennylane import RydbergEvolution\n", "from cosmiq.units import MHz, um, us\n", "\n", "QUICK = os.environ.get(\"COSMIQ_TUTORIAL_QUICK\") == \"1\"\n", "STEPS = 2 if QUICK else 40\n", "ATOMS = 4\n", "TARGET = [1, 0, 0, 1] # r g g r, atom 0 first\n", "OMEGA_MAX = 15.0 # rad/µs: inside cosmiq-ref-1's 15.079, on its 0.001 rad/µs grid" ] }, { "cell_type": "markdown", "id": "9936164e", "metadata": {}, "source": [ "## 1. The block\n", "\n", "Its drive_fn, the function that builds the laser drive from the block's parameters, takes\n", "cosmiq's named parameters, as a cq.program's function does. PennyLane owns the values: one\n", "tensor, in `names` order. $\\Omega$ goes through a sigmoid, so no training step can take it past\n", "the device's maximum; the detuning sweeps between two values." ] }, { "cell_type": "code", "execution_count": null, "id": "425633d6", "metadata": {}, "outputs": [], "source": [ "register = cq.Register.chain(ATOMS, spacing=6.1 * um)\n", "times = [0.0, 0.2 * us, 1.3 * us, 1.5 * us]\n", "\n", "\n", "def sweep(p: dict[str, torch.Tensor]) -> cq.GlobalDrive:\n", " omega = OMEGA_MAX * torch.sigmoid(p[\"omega\"])\n", " return cq.GlobalDrive(\n", " amplitude=cq.pwl(times, [0.0, omega, omega, 0.0]),\n", " detuning=cq.pwl(times, [p[\"start\"], p[\"start\"], p[\"stop\"], p[\"stop\"]]),\n", " )\n", "\n", "\n", "names = (\"omega\", \"start\", \"stop\")\n", "device = qml.device(\"cosmiq.emulator\", wires=ATOMS, seed=1) # blocks target cosmiq-ref-1" ] }, { "cell_type": "markdown", "id": "1b2f7edf", "metadata": { "lines_to_next_cell": 2 }, "source": [ "## 2. The circuit\n", "\n", "Rotations, the block, and the probability of the target bitstring, read as the expectation of\n", "its projector. gradient_kwargs set SPSA for the shot runs of part 3; the exact runs ignore\n", "them." ] }, { "cell_type": "code", "execution_count": null, "id": "9bb8c2ff", "metadata": {}, "outputs": [], "source": [ "@qml.qnode(\n", " device,\n", " interface=\"torch\",\n", " diff_method=\"device\",\n", " device_vjp=True,\n", " gradient_kwargs={\"samples\": 4 if QUICK else 30, \"step\": 0.1},\n", ")\n", "def circuit(angles: torch.Tensor, theta: torch.Tensor) -> torch.Tensor:\n", " for wire in range(ATOMS):\n", " qml.RY(angles[wire], wires=wire)\n", " RydbergEvolution(theta, register=register, drive_fn=sweep, names=names, wires=range(ATOMS))\n", " return qml.expval(qml.Projector(TARGET, wires=range(ATOMS)))\n", "\n", "\n", "torch.manual_seed(0)\n", "angles = (0.1 * torch.randn(ATOMS, dtype=torch.float64)).requires_grad_(True)\n", "theta = torch.tensor([0.0, -1.0 * MHz, 1.0 * MHz], dtype=torch.float64, requires_grad=True)\n", "with torch.no_grad():\n", " before = float(circuit(angles, theta))\n", "print(f\"P(rggr) before training: {before:.3f}\")" ] }, { "cell_type": "markdown", "id": "f92a6ba3", "metadata": {}, "source": [ "### Train\n", "\n", "Each backward() asks the device for the vector-Jacobian product: one more run of the circuit,\n", "then the reverse pass through the block's emulation and the gates." ] }, { "cell_type": "code", "execution_count": null, "id": "57a9f1e2", "metadata": {}, "outputs": [], "source": [ "optimizer = torch.optim.Adam([{\"params\": [angles], \"lr\": 0.1}, {\"params\": [theta], \"lr\": 0.5}])\n", "for step in range(STEPS):\n", " optimizer.zero_grad()\n", " loss = 1 - circuit(angles, theta)\n", " loss.backward()\n", " optimizer.step()\n", " if step % 10 == 0:\n", " print(f\" step {step:2d}: P(rggr) = {1 - float(loss.detach()):.3f}\")\n", "with torch.no_grad():\n", " after = float(circuit(angles, theta))\n", "trained = theta.detach()\n", "omega = OMEGA_MAX * float(torch.sigmoid(trained[0]))\n", "print(f\"P(rggr) after {STEPS} steps: {after:.3f}\")\n", "print(f\"Ω = {omega:.3f} rad/µs, sweep {float(trained[1]):.2f} → {float(trained[2]):.2f} rad/µs\")" ] }, { "cell_type": "markdown", "id": "dd1559d8", "metadata": {}, "source": [ "## 3. With shots\n", "\n", "With shots, the device can't take an exact gradient: it estimates it by SPSA (its seed= fixes\n", "every direction and every shot). The same QNode with shots, and the exact gradient to compare\n", "it with." ] }, { "cell_type": "code", "execution_count": null, "id": "2b53438b", "metadata": {}, "outputs": [], "source": [ "exact_angles = angles.detach().clone().requires_grad_(True)\n", "exact_theta = theta.detach().clone().requires_grad_(True)\n", "circuit(exact_angles, exact_theta).backward()\n", "\n", "shots = qml.set_shots(circuit, shots=2000 if QUICK else 20000)\n", "sampled_angles = angles.detach().clone().requires_grad_(True)\n", "sampled_theta = theta.detach().clone().requires_grad_(True)\n", "shots(sampled_angles, sampled_theta).backward()\n", "\n", "print(\"∂P/∂θ, exact then SPSA from shots:\")\n", "for name, a, b in zip(names, exact_theta.grad.tolist(), sampled_theta.grad.tolist(), strict=True):\n", " print(f\" {name:6s} {a:+.4f} {b:+.4f}\")" ] } ], "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 }