Tutorial 2: a variational circuit in PennyLane#

Single-qubit gates around an analog block, trained with torch.

Four atoms in a chain are close enough that neighbours block each other’s excitation. A layer of single-qubit rotations prepares them, a cosmiq drive (a RydbergEvolution block) evolves them, and we train both, the rotation angles and the drive’s parameters, to put the chain in r g g r: its two ends excited. We’ll

  1. run the circuit on the PennyLane device “cosmiq.emulator”;

  2. train it with torch, its gradients exact and computed by the device (cosmiq’s adjoint, through the gates and the block alike: diff_method="device", device_vjp=True);

  3. estimate the same gradient the way hardware would have to, from shots (SPSA).

It needs the extra: pip install "cosmiq[pennylane]". Run it with python docs/tutorials/02_pennylane_variational.py; COSMIQ_TUTORIAL_QUICK=1 gives a quick version, which runs in a few seconds.

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 40
ATOMS = 4
TARGET = [1, 0, 0, 1]  # r g g r, atom 0 first
OMEGA_MAX = 15.0  # rad/µs: inside cosmiq-ref-1's 15.079, on its 0.001 rad/µs grid

1. The block#

Its drive_fn, the function that builds the laser drive from the block’s parameters, takes cosmiq’s named parameters, as a cq.program’s function does. PennyLane owns the values: one tensor, in names order. \(\Omega\) goes through a sigmoid, so no training step can take it past the device’s maximum; the detuning sweeps between two values.

register = cq.Register.chain(ATOMS, spacing=6.1 * um)
times = [0.0, 0.2 * us, 1.3 * us, 1.5 * us]


def sweep(p: dict[str, torch.Tensor]) -> cq.GlobalDrive:
    omega = OMEGA_MAX * torch.sigmoid(p["omega"])
    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=ATOMS, seed=1)  # blocks target cosmiq-ref-1

2. The circuit#

Rotations, the block, and the probability of the target bitstring, read as the expectation of its projector. gradient_kwargs set SPSA for the shot runs of part 3; the exact runs ignore them.

@qml.qnode(
    device,
    interface="torch",
    diff_method="device",
    device_vjp=True,
    gradient_kwargs={"samples": 4 if QUICK else 30, "step": 0.1},
)
def circuit(angles: torch.Tensor, theta: torch.Tensor) -> torch.Tensor:
    for wire in range(ATOMS):
        qml.RY(angles[wire], wires=wire)
    RydbergEvolution(theta, register=register, drive_fn=sweep, names=names, wires=range(ATOMS))
    return qml.expval(qml.Projector(TARGET, wires=range(ATOMS)))


torch.manual_seed(0)
angles = (0.1 * torch.randn(ATOMS, dtype=torch.float64)).requires_grad_(True)
theta = torch.tensor([0.0, -1.0 * MHz, 1.0 * MHz], dtype=torch.float64, requires_grad=True)
with torch.no_grad():
    before = float(circuit(angles, theta))
print(f"P(rggr) before training: {before:.3f}")
P(rggr) before training: 0.665

Train#

Each backward() asks the device for the vector-Jacobian product: one more run of the circuit, then the reverse pass through the block’s emulation and the gates.

optimizer = torch.optim.Adam([{"params": [angles], "lr": 0.1}, {"params": [theta], "lr": 0.5}])
for step in range(STEPS):
    optimizer.zero_grad()
    loss = 1 - circuit(angles, theta)
    loss.backward()
    optimizer.step()
    if step % 10 == 0:
        print(f"  step {step:2d}: P(rggr) = {1 - float(loss.detach()):.3f}")
with torch.no_grad():
    after = float(circuit(angles, theta))
trained = theta.detach()
omega = OMEGA_MAX * float(torch.sigmoid(trained[0]))
print(f"P(rggr) after {STEPS} steps: {after:.3f}")
print(f"Ω = {omega:.3f} rad/µs, sweep {float(trained[1]):.2f} → {float(trained[2]):.2f} rad/µs")
  step  0: P(rggr) = 0.665
  step 10: P(rggr) = 0.787
  step 20: P(rggr) = 0.798
  step 30: P(rggr) = 0.898
P(rggr) after 40 steps: 0.948
Ω = 5.622 rad/µs, sweep -12.99 → 10.98 rad/µs

3. With shots#

With shots, the device can’t take an exact gradient: it estimates it by SPSA (its seed= fixes every direction and every shot). The same QNode with shots, and the exact gradient to compare it with.

exact_angles = angles.detach().clone().requires_grad_(True)
exact_theta = theta.detach().clone().requires_grad_(True)
circuit(exact_angles, exact_theta).backward()

shots = qml.set_shots(circuit, shots=2000 if QUICK else 20000)
sampled_angles = angles.detach().clone().requires_grad_(True)
sampled_theta = theta.detach().clone().requires_grad_(True)
shots(sampled_angles, sampled_theta).backward()

print("∂P/∂θ, exact then SPSA from shots:")
for name, a, b in zip(names, exact_theta.grad.tolist(), sampled_theta.grad.tolist(), strict=True):
    print(f"  {name:6s} {a:+.4f}   {b:+.4f}")
∂P/∂θ, exact then SPSA from shots:
  omega  -0.0340   -0.0696
  start  -0.0098   +0.0150
  stop   +0.0062   +0.0034