{ "cells": [ { "cell_type": "markdown", "id": "9470578b", "metadata": {}, "source": [ "Generated from cosmiq's `docs/tutorials/03_pennylane_mis.py` for Colab: the first cell installs cosmiq." ] }, { "cell_type": "code", "execution_count": null, "id": "2fc5b708", "metadata": {}, "outputs": [], "source": [ "%pip install --quiet \"cosmiq[pennylane]\"" ] }, { "cell_type": "markdown", "id": "2e662062", "metadata": {}, "source": [ "# Tutorial 3: a maximum-independent-set problem on a unit-disk graph, in PennyLane\n", "\n", "Six atoms sit on a 2 x 3 grid. Two atoms closer than the unit-disk radius share an edge, and\n", "the Rydberg blockade keeps such neighbours from both being excited, so a Rydberg pattern tends\n", "to be an independent set of the graph. Its cost\n", "\n", "$$\n", "C = -\\sum_i n_i + U \\sum_{(i,j)} n_i n_j \\qquad (\\text{the second sum over the edges, } U > 1)\n", "$$\n", "\n", "is lowest for a maximum independent set (MIS). We'll\n", "\n", "1. write $C$ with PennyLane observables: $n_i$ = qml.Projector([1], wires=i), and $n_i n_j$ their\n", " product (the device splits the sum into its terms);\n", "2. train an adiabatic sweep, a `RydbergEvolution` block, to minimise $\\langle C \\rangle$ (exact\n", " gradients from the device);\n", "3. read the trained state as hardware would, with shots, and check what it found.\n", "\n", "It needs the extra: `pip install \"cosmiq[pennylane]\"`. Run it with\n", "`python docs/tutorials/03_pennylane_mis.py`; `COSMIQ_TUTORIAL_QUICK=1` gives a quick version,\n", "which runs in a few seconds." ] }, { "cell_type": "code", "execution_count": null, "id": "cffc76bb", "metadata": {}, "outputs": [], "source": [ "import itertools\n", "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 30\n", "SHOTS = 200 if QUICK else 2000\n", "RADIUS = 7.5 * um # the unit-disk radius: the grid's sides are edges, its diagonals aren't\n", "PENALTY = 2.0 # U: an edge inside a set costs more than an atom gains" ] }, { "cell_type": "markdown", "id": "1b83383a", "metadata": {}, "source": [ "## 1. The graph and the cost\n", "\n", "The register's positions define the graph." ] }, { "cell_type": "code", "execution_count": null, "id": "d06cfcc0", "metadata": {}, "outputs": [], "source": [ "register = cq.Register.rectangular(2, 3, spacing=7.0 * um)\n", "atoms = range(len(register))\n", "distances = register.distances()\n", "edges = [(i, j) for i, j in itertools.combinations(atoms, 2) if distances[i, j] < RADIUS]\n", "print(f\"{len(register)} atoms, edges {edges}\")\n", "\n", "\n", "def n(i: int) -> qml.Projector:\n", " return qml.Projector([1], wires=i) # nᵢ: atom i in the Rydberg state\n", "\n", "\n", "cost = qml.sum(*(-1.0 * n(i) for i in atoms), *(PENALTY * (n(i) @ n(j)) for i, j in edges))" ] }, { "cell_type": "markdown", "id": "f23e52a4", "metadata": {}, "source": [ "## 2. The sweep\n", "\n", "$\\Omega$ ramps up and down, kept below the device's maximum by a sigmoid, while the detuning goes\n", "from negative (every atom in g is the ground state) to positive (excited atoms are favoured,\n", "as many as the blockade allows)." ] }, { "cell_type": "code", "execution_count": null, "id": "05a2d82d", "metadata": {}, "outputs": [], "source": [ "times = [0.0, 0.3 * us, 1.7 * us, 2.0 * us]\n", "\n", "\n", "def sweep(p: dict[str, torch.Tensor]) -> cq.GlobalDrive:\n", " omega = 15.0 * torch.sigmoid(p[\"omega\"]) # rad/µs: inside cosmiq-ref-1's 15.079\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=len(register), seed=1)\n", "\n", "\n", "def evolve(theta: torch.Tensor) -> None:\n", " RydbergEvolution(theta, register=register, drive_fn=sweep, names=names, wires=atoms)\n", "\n", "\n", "@qml.qnode(device, interface=\"torch\", diff_method=\"device\", device_vjp=True)\n", "def expected_cost(theta: torch.Tensor) -> torch.Tensor:\n", " evolve(theta)\n", " return qml.expval(cost)\n", "\n", "\n", "theta = torch.tensor([0.0, -1.5 * MHz, 1.5 * MHz], dtype=torch.float64, requires_grad=True)\n", "with torch.no_grad():\n", " print(f\"⟨C⟩ before training: {float(expected_cost(theta)):+.3f}\")\n", "\n", "optimizer = torch.optim.Adam([theta], lr=0.5)\n", "for step in range(STEPS):\n", " optimizer.zero_grad()\n", " loss = expected_cost(theta)\n", " loss.backward() # the device's vector-Jacobian product: cosmiq's adjoint\n", " optimizer.step()\n", " if step % 10 == 0:\n", " print(f\" step {step:2d}: ⟨C⟩ = {float(loss.detach()):+.3f}\")\n", "with torch.no_grad():\n", " print(f\"⟨C⟩ after {STEPS} steps: {float(expected_cost(theta)):+.3f}\")" ] }, { "cell_type": "markdown", "id": "e37a3024", "metadata": { "lines_to_next_cell": 2 }, "source": [ "Where the excitations are: $\\langle n_i \\rangle$ for every atom, and $\\langle n_i n_j \\rangle$ on\n", "the edges (near 0: blocked)." ] }, { "cell_type": "code", "execution_count": null, "id": "53c7cd33", "metadata": {}, "outputs": [], "source": [ "@qml.qnode(device, interface=\"torch\")\n", "def densities(theta: torch.Tensor) -> list[torch.Tensor]:\n", " evolve(theta)\n", " return [qml.expval(n(i)) for i in atoms] + [qml.expval(n(i) @ n(j)) for i, j in edges]\n", "\n", "\n", "with torch.no_grad():\n", " values = [float(v) for v in densities(theta)]\n", "print(\"⟨nᵢ⟩:\", \" \".join(f\"{v:.2f}\" for v in values[: len(register)]))\n", "print(\"⟨nᵢnⱼ⟩ on the edges:\", \" \".join(f\"{v:.3f}\" for v in values[len(register) :]))" ] }, { "cell_type": "markdown", "id": "7b09ddcd", "metadata": { "lines_to_next_cell": 2 }, "source": [ "## 3. Read it out\n", "\n", "SHOTS bitstrings, atom 0 first (1 = Rydberg). The set they excite should be independent (no\n", "edge inside), and as large as possible: this grid's MIS has 3 atoms, in two ways (the two\n", "checkerboards)." ] }, { "cell_type": "code", "execution_count": null, "id": "169dd4f2", "metadata": {}, "outputs": [], "source": [ "@qml.qnode(device)\n", "def readout(theta: torch.Tensor) -> dict[str, int]:\n", " evolve(theta)\n", " return qml.counts(wires=atoms)\n", "\n", "\n", "counts = qml.set_shots(readout, shots=SHOTS)(theta.detach())\n", "print(\"most frequent readouts:\")\n", "for bits, count in sorted(counts.items(), key=lambda item: -item[1])[:3]:\n", " chosen = {i for i, b in enumerate(bits) if b == \"1\"}\n", " independent = not any(i in chosen and j in chosen for i, j in edges)\n", " verdict = \"independent\" if independent else \"not independent\"\n", " print(f\" {bits} x{count}: {len(chosen)} atoms, {verdict}\")" ] } ], "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 }