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