# %% [markdown] # # Tutorial 1: prepare an ordered state with a detuning sweep, and train the sweep # # Atoms in a chain, close enough that two neighbours can't both be in the Rydberg state (the # blockade), are driven while the detuning sweeps from negative to positive. Done slowly, this # carries the chain from all-ground to its antiferromagnetic state, r g r g r: every other atom # excited. We'll # # 1. build the sweep as a cosmiq program, checked against the cosmiq-ref-1 device; # 2. emulate it, and read the probability of the target state; # 3. train the sweep with exact gradients, keeping $\Omega$ at most the device's maximum; # 4. estimate the same gradient the way hardware would have to, from shots; # 5. sample the trained program, as the device would be read. # # Run it with `python docs/tutorials/01_detuning_sweep.py`. `COSMIQ_TUTORIAL_QUICK=1` gives a # quick version, which runs in a few seconds. # %% import os from collections import Counter import torch import cosmiq as cq from cosmiq.emulator import projector from cosmiq.units import MHz, um, us QUICK = os.environ.get("COSMIQ_TUTORIAL_QUICK") == "1" ATOMS = 3 if QUICK else 5 DURATION = 1.0 * us if QUICK else 1.5 * us STEPS = 2 if QUICK else 30 TARGET = "rg" * (ATOMS // 2) + "r" # "rgr", or "rgrgr" # %% [markdown] # ## 1. The program # # $\Omega$ ramps up, holds and ramps down; the detuning sweeps linearly between two trainable # values. We start from a sweep that's too shallow to reach the ordered state reliably. $\Omega$ # is kept within the device's limit, and training may push it right up to that limit. # %% class Sweep(cq.AnalogProgram): def __init__(self) -> None: super().__init__(cq.Register.chain(ATOMS, spacing=6.1 * um)) self.omega = cq.bounded( 1.0 * MHz, low=0.0, high="device", field="analog.rydberg_global.amplitude.max", mode="clamp", ) self.start = torch.nn.Parameter(torch.tensor(-1.0 * MHz, dtype=torch.float64)) self.stop = torch.nn.Parameter(torch.tensor(1.0 * MHz, dtype=torch.float64)) def drive(self) -> cq.GlobalDrive: ramp = 0.4 * us t = [0.0, ramp, DURATION - ramp, DURATION] omega = self.omega() return cq.GlobalDrive( amplitude=cq.pwl(t, [0.0, omega, omega, 0.0]), detuning=cq.pwl(t, [self.start, self.start, self.stop, self.stop]), ) program = Sweep().to_target("cosmiq-ref-1") # the register and a trial drive, checked now print(f"{ATOMS} atoms, Ω ≤ {program.omega.high} rad/µs on cosmiq-ref-1, target {TARGET}") # %% [markdown] # ## 2. Emulate it # # The emulator returns expectation values as tensors that keep their gradient. # %% emulator = cq.Emulator(observable=projector(TARGET)) with torch.no_grad(): # just a look: no gradient needed before = float(emulator(program())[0]) print(f"P({TARGET}) before training: {before:.3f}") # %% [markdown] # ## 3. Train # # `cq.project_(program, after=optimizer)` puts $\Omega$ back inside its limits after every step, # so it can sit exactly on the maximum. # %% optimizer = torch.optim.Adam(program.parameters(), lr=1.0) # rad/µs per step, about cq.project_(program, after=optimizer) for _ in range(STEPS): optimizer.zero_grad() loss = 1 - emulator(program())[0] loss.backward() # the engine's reversible adjoint: exact, in memory that doesn't grow optimizer.step() with torch.no_grad(): after = float(emulator(program())[0]) omega, start, stop = float(program.omega()), float(program.start), float(program.stop) print(f"P({TARGET}) after {STEPS} steps: {after:.3f}") print(f"Ω = {omega:.3f} rad/µs, sweep {start:.2f} → {stop:.2f} rad/µs") # %% [markdown] # ## 4. One gradient, three ways # # The adjoint is exact. Hardware gives only shots, so there the gradient must be estimated. SPSA # nudges every parameter at once in a random direction, runs the program on both sides, and turns # the difference into an estimate of the gradient, with its standard error. Its seed fixes every # direction and every shot. # %% def probability(result: cq.emulator.EmulationResult) -> torch.Tensor: return result.expectations["projector"][0] def counted(result: cq.emulator.EmulationResult) -> float: labels = result.shots[0].labels # [shots, N] NumPy array: 0 ground, 1 Rydberg wanted = [1 if c == "r" else 0 for c in TARGET] return float((labels == wanted).all(1).mean()) exact = cq.gradients.estimate(program, probability, emulator=emulator) sampled = cq.gradients.estimate( program, counted, emulator=cq.Emulator(samples_only=True), shots=300 if QUICK else 2000, samples=3 if QUICK else 20, step=0.3, seed=1, ) print(f"gradient by {exact.method}, then {sampled.method} from {sampled.shots} shots:") for name, value in exact.value.items(): estimate, error = sampled.value[name], sampled.stderr[name] print(f" {name:10s} {float(value):+.4f} {float(estimate):+.4f} ± {float(error):.4f}") # %% [markdown] # ## 5. Read it as the device would # # Shots, with the device's calibrated noise. # %% shots = emulator.run(program(), shots=50 if QUICK else 500, noise="device", seed=7).shots[0] words = Counter("".join("gr."[b] for b in row) for row in shots.labels.tolist()) # . lost print("most frequent readouts:", ", ".join(f"{w} x{n}" for w, n in words.most_common(3)))