PennyLane#

cosmiq’s PennyLane plugin lets you put a cosmiq laser pulse inside a PennyLane circuit, next to ordinary single-qubit gates, and train it with PyTorch. The pulse is the operation cosmiq.pennylane.RydbergEvolution, and it runs on the device cosmiq.emulator. Gradients are exact when there are no shots, and estimated from the shots, as hardware would need, when there are. A second device, cosmiq.remote, runs the same circuits remotely (below).

Install#

pip install "cosmiq[pennylane]"   # PennyLane 0.45 or 0.46

The extra isn’t available on Intel Macs (see Installation). PennyLane finds the devices by name once it’s installed; import cosmiq never imports PennyLane.

A first circuit#

import pennylane as qml
import torch

import cosmiq as cq
from cosmiq.pennylane import RydbergEvolution
from cosmiq.units import MHz

register = cq.Register.chain(4, spacing=6.1)
t = [0.0, 0.248, 2.752, 3.0]


def drive(p):  # cosmiq's named parameters, as cq.program's functions take them
    return cq.GlobalDrive(
        cq.pwl(t, [0.0, p["omega"], p["omega"], 0.0]),
        cq.pwl(t, [p["d0"], p["d0"], p["d1"], p["d1"]]),
    )


dev = qml.device("cosmiq.emulator", wires=4)  # target="cosmiq-ref-1" by default


@qml.qnode(dev, interface="torch", diff_method="device", device_vjp=True)
def circuit(theta):
    qml.Hadamard(wires=0)
    RydbergEvolution(
        theta, register=register, drive_fn=drive, names=("omega", "d0", "d1"), wires=range(4)
    )
    return [qml.expval(qml.Projector([1], wires=w)) for w in range(4)]  # nᵢ, the densities


theta = torch.tensor([1.5 * MHz, -3 * MHz, 3 * MHz], dtype=torch.float64, requires_grad=True)
sum(circuit(theta)).backward()  # exact: cosmiq's adjoint, through the gate and the block
print(theta.grad)
  • qml.device("cosmiq.emulator", wires=4) simulates the four atoms.

  • RydbergEvolution(theta, ...) plays the pulse that drive builds from theta’s values, named in order by names. PennyLane owns theta, so it trains like any gate angle.

  • diff_method="device", device_vjp=True lets the device compute the gradient itself, exactly, through the gates and the pulse alike.

The device#

qml.device("cosmiq.emulator", wires=4, target="cosmiq-ref-1", seed=None, emulator=None)
  • wires: the atoms, in register order. A block’s wires must be these, in this order (wire i is atom i). Without wires, the first block’s wires set the order.

  • target: a bundled device’s id or a DeviceSpec. Every block is checked against it, as program.to_target would: its atom positions, and its pulse once rounded to what the device can play. A broken limit raises a ConstraintError that names the parameter behind it.

  • seed: makes shots and gradient estimates repeatable; None draws a fresh one.

  • emulator: a cq.Emulator, to choose the torch device and precision, e.g. cq.Emulator(device="cuda"). The default runs on the CPU in complex128.

  • Give the QNode its shots with qml.set_shots, as on every PennyLane device.

How a circuit runs: on one state vector, with every atom starting in g. The gates RX, RY, RZ, Hadamard, PhaseShift, Rot, Identity and GlobalPhase are applied exactly; other single-qubit gates (PauliX, S, T, SX, a one-qubit QubitUnitary, a BasisState, …) are decomposed into them. A block evolves the current state under its pulse. The whole circuit is one torch graph.

The gates are emulator-only: cosmiq-ref-1 can’t drive single atoms, so hardware couldn’t play them between blocks. Wire order is cosmiq’s atom order, atom 0 first, and 1 is the Rydberg state, so qml.Projector([1], wires=i) is \(n_i\).

In PennyLane’s terms, with cosmiq’s phase convention: with no detuning and atoms far apart, a resonant pulse of area \(\theta = \int \Omega\, dt\) at phase \(\varphi = 0\) is \(\mathrm{RX}(\theta)\) on every atom, and at \(\varphi = \pi/2\) it’s \(\mathrm{RY}(\theta)\).

RydbergEvolution#

RydbergEvolution(params, *, register, drive_fn, names, wires, dt=None)
  • params: one 1-D tensor of values, in names order. These are the trainable parameters. A [B, P] tensor runs B rows at once.

  • drive_fn(params): builds the drive from a mapping of name to value. Any torch arithmetic works inside, e.g. a sigmoid that keeps \(\Omega\) below the device’s maximum.

  • register, wires: one wire per atom.

  • dt: the length of one time step, in µs; the device’s clock by default.

RydbergEvolution(theta, wires=op.wires, **op.hyperparameters) makes a copy of op with new values.

From a program: RydbergEvolution.from_program(program, wires) turns a cq.program or any AnalogProgram into a block, with the program’s register, its parameters’ current values and its drive. Continuing the first example:

program = cq.program(register, drive, {"omega": 1.5 * MHz, "d0": -3 * MHz, "d1": 3 * MHz})
op = RydbergEvolution.from_program(program, wires=range(4))  # outside the QNode: a template
theta = op.data[0].clone().requires_grad_(True)  # the program's values, in op's order


@qml.qnode(dev, interface="torch", diff_method="device", device_vjp=True)
def from_program(theta):
    RydbergEvolution(theta, wires=op.wires, **op.hyperparameters)
    return qml.expval(qml.Projector([1], wires=0))


from_program(theta).backward()

The names are the program’s parameter names (op.hyperparameters["names"], here "params.omega", …); a parameter with several values gets one name each ("w[0]", "w[1]", …).

Limits: op.limits() gives each value’s (low, high) limits (\(\pm\infty\) for none). A from_program block keeps the limits of its program’s clamp-mode bounded values, and the device refuses a value outside them. PennyLane trains its own tensor, so clamp it after each optimiser step:

optimizer.step()
with torch.no_grad():
    theta.clamp_(*op.limits())

A block has no matrix and no decomposition: only cosmiq’s devices run it, and every other device refuses it.

Measurements#

Measurement

Without shots

With shots

qml.expval, qml.var

exact, from the state

from samples

qml.probs

exact

from samples

qml.sample, qml.counts

not supported

yes

  • Observables: PauliX, PauliY, PauliZ, Identity and Projector, and products, sums and scalar multiples of those. \(n_i\) is qml.Projector([1], wires=i), and \(n_i n_j\) is the product qml.Projector([1], wires=i) @ qml.Projector([1], wires=j).

  • Sums: an expval of a sum is measured whole. With shots, each term is sampled in its own basis. A var, probs, sample or counts of a sum is refused: measure its terms.

  • Shots: measurements that read their shared wires in the same basis share their shots, as one run would; the others get shots of their own. Shot vectors work.

Gradients#

Use diff_method="device", device_vjp=True (or "best"): the device then computes the gradient itself.

  • Without shots: exact, from cosmiq’s adjoint method: one more run of the circuit, then one pass backwards through the gates and every block.

  • With shots: estimated by SPSA, as hardware would need: each direction nudges every trainable value at once, and two runs compare the results. gradient_kwargs sets how many directions (samples) and how big a nudge (step), and the device’s seed makes the estimate repeatable. Continuing the first example:

seeded = qml.device("cosmiq.emulator", wires=4, seed=1)


@qml.qnode(
    seeded,
    interface="torch",
    diff_method="device",
    device_vjp=True,
    gradient_kwargs={"samples": 30, "step": 0.1},  # 30 SPSA directions, two runs each
)
def sampled(theta):
    qml.Hadamard(wires=0)
    RydbergEvolution(
        theta, register=register, drive_fn=drive, names=("omega", "d0", "d1"), wires=range(4)
    )
    return qml.expval(qml.Projector([1], wires=0))


theta = torch.tensor([1.5 * MHz, -3 * MHz, 3 * MHz], dtype=torch.float64, requires_grad=True)
qml.set_shots(sampled, shots=2000)(theta).backward()  # 2,000 shots per run
print(theta.grad)

Choosing the step: the device rounds values to what it can play, so keep step a whole multiple of that rounding (0.1 is, on cosmiq-ref-1), with the values themselves on it too. Otherwise the rounding adds a small error to each estimate. A clamp-mode value’s nudges stay inside its limits.

Why device_vjp=True: a block’s parameters form one vector, and PennyLane’s own gradient methods treat each parameter as a single number. So while a block is being trained, the device refuses diff_method="device" without device_vjp=True, and PennyLane’s own gradient transforms ("parameter-shift", "finite-diff", "spsa", "hadamard"), with a message saying how to fix it. Gate angles alone, with fixed blocks, can use any of them, and a forward pass that takes no gradient is never refused.

Interfaces: torch, and autograd (PennyLane’s numpy). JAX and TensorFlow are refused. With PennyLane’s numpy, give a fixed block requires_grad=False, since PennyLane differentiates every array that allows it.

The emulator’s own gradient: exact gradients need an emulator that keeps them, so Emulator(gradient="none") is refused when a block is being differentiated. It’s fine for forward passes, and with shots.

What it doesn’t do#

Each of these raises DeviceError with “not supported”:

  • multi-qubit gates (CNOT, CZ, IsingZZ, …): atoms interact only through a block’s pulse;

  • noise: the v0.1 device is noise-free;

  • mid-circuit measurements: an analog device reads every atom once, at the end;

  • other measurements (qml.state(), qml.density_matrix, entropies, …) and other observables (Hermitian, Hadamard, SparseHamiltonian, …);

  • higher-order derivatives, and gradients of sample or counts.

PennyLane’s own device test suite runs against the device, with and without shots (the details).

Remote: cosmiq.remote#

Remote jobs aren’t open yet; cq.remote.local() runs the same code on your machine. The device cosmiq.remote runs the same circuits through a cq.remote session (Remote jobs), with the same values and gradients as running locally:

import cosmiq as cq

names = ("omega", "d0", "d1")
optimizer = torch.optim.Adam([theta], lr=0.1)

with cq.remote.session("emu:gpu", max_minutes=30) as session:  # once remote jobs open
    dev = qml.device("cosmiq.remote", wires=4, session=session)

    @qml.qnode(dev, interface="torch", diff_method="device", device_vjp=True)
    def circuit(theta):  # as for cosmiq.emulator
        qml.Hadamard(wires=0)
        RydbergEvolution(theta, register=register, drive_fn=drive, names=names, wires=range(4))
        return qml.expval(qml.Projector([1], wires=0))

    for step in range(100):
        optimizer.zero_grad()
        circuit(theta).backward()  # one request per step
        optimizer.step()
qml.device("cosmiq.remote", wires=4, session=session, target="cosmiq-ref-1", emulator=None)
  • session: a cq.remote.session(...), or cq.remote.local() (this machine, for tests and offline work, with no account).

  • target, wires: as on cosmiq.emulator.

  • emulator: the emulator options remote runs use (precision, method, tolerance, …); by default the session’s. Where it runs is decided by the session (emu:gpu runs on a GPU).

  • No shots yet. Shots and gradient_kwargs are refused; for shots, use cosmiq.emulator.

What is sent. Each circuit goes as data, never as code: its gates with their angles, each block’s pulse as your machine builds it from drive_fn, and the measurements. Each block is checked on your machine before anything is sent, so a ConstraintError names the parameter behind a broken limit as it does locally.

One request per training step. A forward pass with gradients on also brings back what the backward pass needs, so a training step is one request. That costs extra when no backward pass follows: evaluate under torch.no_grad() when you don’t need gradients (validation, logging, plotting). Measuring one expval of a sum is cheaper than measuring each term.

Limits: very large circuits are refused before anything is sent, with a message saying what to cut (the details). Everything cosmiq.emulator refuses, cosmiq.remote refuses too.

Tutorials#

  • Tutorial 2: rotations around a block, trained with torch, and the same gradient by SPSA from shots.

  • Tutorial 3: a maximum independent set on a unit-disk graph, with \(n_i\) and \(n_i n_j\).

Tested limits are on Claims and limits.