Lowering to Your Controller’s Instruction Set#
Note
Experimental. The export this page lowers from is a versioned format, but how a backend spans several controllers may change.
This tutorial is for people who build control systems or QPUs. You write a small pass that turns a compiled pulse program into the instructions of a toy controller.
What you’ll learn:
how to describe a controller, and a QPU built from two of them, as data
what the compiler hands a backend: the scheduled program, as data
how to lower that program to an instruction set, one kind of event at a time
how to test the result with
backends.validate
The full code is in examples/isa_lowering/toy_isa.py. Save it beside your own code: this page shows it piece by piece and imports it.
All the code on this page is also one Python script,
isa_lowering.py.
A toy instruction set#
Each toy controller has one sequencer. It issues these instructions in order:
Instruction |
What it does |
|---|---|
|
Sets channel 0’s oscillator to 5.002 GHz. |
|
Adds 0.502655 rad to its phase. |
|
Starts waveform |
|
Starts |
|
Lets 35 timesteps pass. |
|
Jumps to |
|
Jumps to |
|
Jumps to |
|
Sends bits |
|
Waits for the decoder’s answer, into bit |
|
Takes the answer if it is there. Bit |
A few rules complete the picture:
Only
waitmoves time. Aplayoracquirestarts a pulse and returns.A channel that several qudits share has an oscillator per tone, such as
ch1.0andch1.1.Oscillators start each shot at phase 0.
Outcome bits reach every sequencer over a shared bus.
There are no loops and no registers to compute with.
Describe the controllers as data#
Before any lowering, the compiler needs to know what each controller can do. You give it that as data.
The controller description#
A controller description is a file its maker ships, one per model. These are the toy model’s limits:
# Pulses start and end every 4 cycles.
cycles_per_timestep = 4
# From an acquisition's end until a branch can use it.
feedback_latency_cycles = 80
# Instruction memory.
max_pulses = 256
# Waveform memory, and oscillator frequencies, per channel.
waveform_memory_samples = 1024
max_frequencies_per_line = 2
# A poll can give up on an answer that is late.
supports_timeouts = true
The file also names the model and lists what it supports: plays, readouts, waits, syncs, branches, forwarding outcomes, and decoder calls. Save it next to your code:
import math
from pathlib import Path
import cudaq_pulse as pulse
from toy_isa import DESCRIPTION
description = Path("toy_sequencer.toml")
description.write_text(DESCRIPTION)
Two controllers, wired#
Which qudits a controller drives is the installation’s part, not the maker’s. Both toy controllers are the same model, wired differently:
from cudaq_pulse.controller import ReadoutLine
# One feedline reads qudits 0 and 1 at once.
feedline = ReadoutLine([0, 1], max_concurrent_tones=2)
first = pulse.controller(
"toy_sequencer.toml",
drive_lines=[0, 1],
readout_lines=[feedline],
peer_latency_cycles=40,
)
second = pulse.controller(
"toy_sequencer.toml",
drive_lines=[2],
readout_lines=[2],
peer_latency_cycles=40,
)
print("model: ", first.model)
print("max pulses:", first.max_pulses)
Output
model: toy.sequencer
max pulses: 256
What to notice:
The first controller drives qudits 0 and 1, and reads both on one feedline.
The second controller drives and reads qudit 2.
An outcome takes 40 more cycles to reach the other controller.
One QPU#
The QPU has three qudits, each with its frequency and coherence times:
from cudaq_pulse.quantum_systems import PhysicalQudit
qudits = {}
for number in range(3):
qudits[number] = PhysicalQudit(
index=number,
frequency_hz=5.0e9 + 3.0e8 * number,
t1_us=50.0,
t2_star_us=30.0,
)
The control system holds both controllers, the clock and the link to the
decoder. The QPU puts it together with the qudits. It is one value, which
as_dict saves as a file:
decoder_link = pulse.Link(fixed_ns=4, feedback_ns=8)
control_system = pulse.ControlSystem(
controllers=[first, second],
reference_clock_ghz=0.25,
links={"decoder": decoder_link},
)
qpu = pulse.quantum_system(
name="toy-qpu",
qudits=qudits,
clock_ghz=1.0,
control_system=control_system,
)
saved = qpu.as_dict()
controllers = saved["control_system"]["controllers"]
print("controllers:", len(controllers))
print("second line drives:", controllers[1]["drive_lines"])
Output
controllers: 2
second line drives: [2]
Both controllers count from the 250 MHz reference clock. A call to the decoder takes 4 ns to go out and 8 ns to come back, on top of its own latency. Every compile now checks a program against these two controllers.
The QPU as as_dict saves it. Each controller’s drive lines are
solid and its readout lines dashed; the first controller reads its two
qudits on one feedline. The decoder’s link belongs to the control
system.#
Diagram of the toy QPU. 3 qudits at 5, 5.3, 5.6 GHz and 2 toy.sequencer controllers: controller 0 drives qudits 0 and 1, and one feedline reads qudits 0 and 1; controller 1 drives qudit 2, and a readout line reads qudit 2. An outcome takes 40 cycles from one controller to the other. The decoder link of the control system, drawn to both controllers, takes 4 ns out and 8 ns back. The reference clock is 250 MHz and the program clock 1 GHz.
The program before lowering#
This section shows what a backend receives: the scheduled program.
A Ramsey sequence with a reset#
The kernel is a detuned Ramsey sequence, then an active reset:
@pulse.kernel
def ramsey_then_reset(qudit):
drive_line = get_drive_line(qudit)
readout_line = get_readout_line(qudit)
x90 = gaussian(duration=40, amplitude=0.25, sigma=10.0)
x180 = gaussian(duration=40, amplitude=0.5, sigma=10.0)
probe = square(duration=200, amplitude=0.05)
# Ramsey, detuned by 2 MHz while it waits.
drive(drive_line, x90)
shift_frequency(drive_line.tone, 2.0e6)
wait(drive_line, 100)
shift_phase(drive_line.tone, math.pi / 2)
drive(drive_line, x90)
shift_frequency(drive_line.tone, -2.0e6)
# Read out, and play a π pulse when it reads 1.
sync(drive_line, readout_line)
outcome = readout(readout_line, probe)
sync(drive_line, readout_line)
if outcome:
drive(drive_line, x180)
What to notice: the reset flips the qudit back when it reads 1.
The scheduled IR#
Compile with the resource-constrained schedule, rcp. The scheduled
pulse dialect gives each operation a place in time, as the attributes
start_cycles and duration_cycles. The regular expression below
picks each operation’s name and those two attributes out of the MLIR
text, to print its start and length in clock cycles:
import re
compiled = pulse.compile(
ramsey_then_reset,
quantum_system=qpu,
schedule="rcp",
)
scheduled = compiled.lower(qpu.qudits[0])
op_timing = re.compile(
r"= (pulse\.\w+) .*"
r"duration_cycles = (\d+) : i64, start_cycles = (\d+)"
)
for op, duration, start in op_timing.findall(scheduled.mlir()):
print(f"{op:<23} start {start:>3} length {duration:>3}")
Output
pulse.drive start 0 length 40
pulse.shift_frequency start 40 length 0
pulse.wait start 40 length 100
pulse.drive start 140 length 40
pulse.shift_frequency start 180 length 0
pulse.readout start 180 length 200
pulse.drive start 460 length 40
What to notice:
The last drive sits inside an
scf.ifon the readout.No phase shift is left. The compiler folded the virtual Z into the second drive.
The same schedule, drawn from the program’s export. This QPU’s clock is 1 GHz, so a cycle is 1 ns. The dashed x180 pulse plays only when the readout reads 1, and starts once the outcome is back, after the controller’s feedback latency.#
Timeline of the scheduled program on qudit 0's drive and readout lines, with a lane for the outcome. An x90 pulse from 0 to 40 ns, a 100 ns wait, a second x90 pulse detuned by +2 MHz from 140 to 180 ns, then the readout from 180 to 380 ns. The outcome is ready 80 ns after the readout ends, and the x180 pulse, which plays only if the readout read 1, runs from 460 to 500 ns.
The export#
The export is the same program as versioned data. It is the one to read:
program = scheduled.export_to_controller()
for event in program["events"]:
if event["kind"] not in ("drive", "readout"):
continue
start = event["start_cycles"]
gigahertz = event["frequency_hz"] / 1e9
phase = event["phase_rad"]
print(f"{event['kind']:<7} at {start:>3}: "
f"{gigahertz:.3f} GHz, {phase:.6f} rad")
Output
drive at 0: 5.000 GHz, 0.000000 rad
drive at 140: 5.002 GHz, 2.827433 rad
readout at 180: 5.000 GHz, 0.000000 rad
drive at 460: 5.000 GHz, 3.330088 rad
Each pulse carries its absolute frame. So the sequencer never has to add up phase itself.
The reset’s π pulse is conditional. Its event says on what:
reset_pulse = program["events"][6]
condition = reset_pulse["conditions"][0]
print("test:", condition["test"])
print("on readouts:", condition["readouts"])
Output
test: is_set
on readouts: [4]
It plays when the outcome of event 4, the readout, is set.
The lowering pass#
The pass builds one ToyProgram per controller. This section goes
through it in the order a program meets it.
State#
A ToyProgram starts from the program’s clock grid, with empty state:
def __init__(self, program: Mapping[str, Any]) -> None:
if program.get("format") != FORMAT:
message = f"the toy sequencer reads {FORMAT} only"
raise IncompatibleBackendError(message)
self.controller: int = program.get("controller", 0)
self.limits: Mapping[str, Any] = program["limits"] or {}
self.timestep: int = self.limits.get("cycles_per_timestep") or 1
# The listing so far, and the cycle the sequencer has reached.
self.code: list[str] = []
self.now = 0
self.frames: Frames = {}
self.table: dict[Any, int] = {}
self.waveforms: list[Any] = []
self.channels: dict[str, int] = {}
self.polls: set[int] = set()
self.wiring = self.wire(program["lines"])
It tracks the code so far, the cycle the sequencer has reached, each oscillator’s frame, and a table of waveforms.
Channels#
Each line of the export becomes a channel. The lines of a shared line’s qudits become tones of one channel:
@staticmethod
def wire(lines: Sequence[Mapping[str, Any]]) -> dict[int, Wire]:
"""Each export line's physical channel. The lines of a shared
line's qudits are tones of one channel."""
channel_of: dict[tuple[str, tuple[int, ...]], int] = {}
wiring = {}
for line in lines:
qudits = tuple(line.get("qudits", [line["qudit"]]))
key = (line["role"], qudits)
channel = channel_of.setdefault(key, len(channel_of))
label = f"{line['role']} q{line['qudit']}"
wiring[line["line"]] = Wire(channel, len(qudits) > 1, label)
return wiring
An event on a shared line gives its tone in tone_slot:
def channel(self, event: Event) -> str:
"""The channel *event* plays on: ``ch0``, or ``ch1.0`` for tone
0 of a shared channel."""
wire = self.wiring[event["line"]]
if wire.shared:
name = f"ch{wire.channel}.{event['tone_slot']}"
else:
name = f"ch{wire.channel}"
self.channels[name] = event["line"]
return name
Time#
Time moves only by wait, in timesteps of 4 cycles:
def wait_until(self, cycle: int) -> None:
gap = cycle - self.now
if gap < 0 or gap % self.timestep:
why = f"no wait goes from cycle {self.now} to {cycle}"
raise refuse(why)
if gap:
timesteps = gap // self.timestep
self.code.append(f"wait {timesteps}")
self.now = cycle
Every start in the export is already on that grid. A kernel whose lengths can’t be is refused when it compiles, so this only divides.
What the toy sequencer can’t play, it refuses. It never plays it some other way:
def refuse(why: str) -> IncompatibleBackendError:
message = f"the toy sequencer cannot play this: {why}"
return IncompatibleBackendError(message)
Frequency and phase#
The toy oscillator can only be set to a frequency and shifted in phase. So the pass shifts by the difference from the frame it had:
def set_frame(
toy: ToyProgram,
channel: str,
frequency: float | None,
phase: float,
) -> None:
"""Set *channel*'s oscillator to *frequency*, and shift its phase by
the difference to *phase*."""
old_frequency, old_phase = toy.frames.get(channel, (None, 0.0))
if frequency != old_frequency:
toy.code.append(f"set_freq {channel} {frequency:.0f}")
shift = math.remainder(phase - old_phase, 2 * math.pi)
if abs(shift) > 1e-9:
toy.code.append(f"shift_phase {channel} {shift:.6f}")
toy.frames[channel] = (frequency, phase)
Waveforms#
Waveforms that differ only in gain share a table entry, which
shape_key names:
def table_entry(toy: ToyProgram, event: Event) -> str:
"""The waveform table's name for *event*'s envelope. The first time
an envelope is seen, its samples are stored at gain 1."""
key = shape_key(event["waveform"])
if key not in toy.table:
samples = sample_waveform(
event["waveform"],
event["duration_cycles"],
)
toy.table[key] = len(toy.waveforms)
toy.waveforms.append(samples / gain(event))
return f"w{toy.table[key]}"
Play and acquire#
A drive becomes a play. A readout becomes an acquire into the
bit named for its event index:
def play(toy: ToyProgram, event: Event) -> None:
"""A drive as a ``play``. A readout as an ``acquire`` into a bit."""
refuse_run_time_values(event)
toy.wait_until(event["start_cycles"])
channel = toy.channel(event)
set_frame(
toy,
channel,
frequency=event["frequency_hz"],
phase=event["phase_rad"],
)
waveform = table_entry(toy, event)
operands = f"{channel} {waveform} {written(gain(event))}"
if event["kind"] == "readout":
toy.code.append(f"acquire {operands} m{event['index']}")
else:
toy.code.append(f"play {operands}")
The event index is the same in every controller’s part of a program. So a bit has one name everywhere.
Decoder calls#
A call to the decoder becomes a submit of the bits it reads:
def submit(toy: ToyProgram, event: Event) -> None:
"""A call to the decoder, sending the outcome bits it reads."""
bits = []
for operand in event["operands"]:
if set(operand) != {"readout"}:
index = event["index"]
why = f"event {index} sends a value computed at run time"
raise refuse(why)
bits.append(f"m{operand['readout']}")
toy.wait_until(event["start_cycles"])
toy.code.append(f"submit L{event['link']} {' '.join(bits)}")
Its answer becomes an answer, or a poll when the call has a
deadline:
def answer(toy: ToyProgram, event: Event) -> None:
"""The decoder's answer: an ``answer`` that waits for it, or, for a
call with a timeout, a ``poll`` at the deadline."""
toy.wait_until(event["start_cycles"])
if event.get("wait") == "timeout":
instruction = "poll"
toy.polls.add(event["index"])
else:
instruction = "answer"
toy.code.append(f"{instruction} L{event['link']} a{event['index']}")
Those are all the events the sequencer issues by itself:
EMIT: dict[str, Callable[[ToyProgram, Event], None]] = {
"drive": play,
"readout": play,
"submit": submit,
"answer": answer,
}
Branches#
A branch spans events. First, the pass names the bit it tests:
def tested_bit(toy: ToyProgram, condition: Mapping[str, Any]) -> str:
"""The bit a branch tests: ``m4`` for readout 4's outcome, ``a3``
or ``a3.1`` for answer 3's first or second value, and ``a3.ok``
for whether a poll found answer 3 in time."""
if condition["test"] == "is_set":
return f"m{condition['readouts'][0]}"
number = condition["answers"][0]
result = condition["result"]
if number in toy.polls:
if result == 0:
return f"a{number}.ok"
result -= 1
if result == 0:
return f"a{number}"
return f"a{number}.{result}"
Each arm becomes code that ends at the same cycle:
def arm(
toy: ToyProgram,
events: Sequence[Event],
*,
taken: bool,
before: Frames,
) -> list[str]:
"""One arm's code: its pulses, then a wait to the branch's end."""
first, last = span(events)
toy.now = first
toy.frames = dict(before)
start = len(toy.code)
for event in sorted(events, key=start_cycle):
if event["conditions"][0]["arm"] is taken:
play(toy, event)
toy.wait_until(last)
restore_phases(toy, before)
code = toy.code[start:]
del toy.code[start:]
return code
Each arm also ends with the phases it started with. So what follows the branch doesn’t depend on the outcome:
def restore_phases(toy: ToyProgram, before: Frames) -> None:
"""Shift each oscillator's phase back to what it was before an arm,
so what follows the branch doesn't depend on the outcome."""
for channel, (frequency, _) in toy.frames.items():
_, phase = before.get(channel, (None, 0.0))
set_frame(toy, channel, frequency=frequency, phase=phase)
The two arms then go behind one branch:
def branch_code(
number: int,
bit: str,
taken: list[str],
other: list[str],
) -> list[str]:
"""Both arms behind one branch, with a jump when both play."""
end = f"end{number}"
if not taken:
return [f"branch {bit} {end}", *other, f"{end}:"]
if not other:
return [f"branch !{bit} {end}", *taken, f"{end}:"]
otherwise = f"else{number}"
return [
f"branch !{bit} {otherwise}",
*taken,
f"jump {end}",
f"{otherwise}:",
*other,
f"{end}:",
]
Putting it together#
The pass groups events into units. A unit is an event that always plays, or a branch with the events of both its arms:
def units(program: Mapping[str, Any]) -> list[Unit]:
"""The program's events in units, in time order."""
grouped: dict[tuple[str, int], list[Event]] = {}
for event in program["events"]:
if event["kind"] in FOLDED:
continue
check(event)
grouped.setdefault(unit_of(event), []).append(event)
def first_start(unit: Unit) -> int:
_, members = unit
return span(members)[0]
return sorted(grouped.items(), key=first_start)
It refuses what the toy can’t express, such as a branch inside a branch:
def check(event: Event) -> None:
"""Refuse an event the toy sequencer has no instruction for."""
index = event["index"]
if event["kind"] not in EMIT:
raise refuse(f"event {index} is a {event['kind']}")
conditions = event["conditions"]
if not conditions:
return
nested = len(conditions) > 1
computed = conditions[0]["test"] not in ("is_set", "answer")
is_call = event["kind"] in ("submit", "answer")
if nested or computed or is_call:
raise refuse(f"event {index} is in a nested or computed branch")
Last, lower issues the units in time order:
def lower(program: Mapping[str, Any]) -> ToyProgram:
"""The toy listing of one controller's ``export_to_controller()``
program. Raises ``IncompatibleBackendError`` for what the toy
sequencer cannot play."""
toy = ToyProgram(program)
for (kind, number), members in units(program):
if kind == "branch":
branch(toy, number, members)
else:
event = members[0]
emit = EMIT[event["kind"]]
emit(toy, event)
return toy
The program after lowering#
Now lower the Ramsey sequence and read the listing.
The head and the Ramsey part#
The head names the channels and the waveform table:
from toy_isa import lower
toy = lower(program)
listing = str(toy).splitlines()
for line in listing[:10]:
print(line)
Output
.chan ch0 drive q0
.chan ch1.0 readout q0
.wave w0 40
.wave w1 200
set_freq ch0 5000000000
play ch0 w0 0.25
wait 35
set_freq ch0 5002000000
shift_phase ch0 2.827433
play ch0 w0 0.25
What to notice:
The three Gaussians are one table entry,
w0.The second π/2 pulse plays at the detuned frequency.
The readout and the reset#
The rest of the listing reads the qudit out and resets it:
for line in listing[10:]:
print(line)
Output
wait 10
set_freq ch1.0 5000000000
acquire ch1.0 w1 0.05 m4
wait 70
branch !m4 end0
set_freq ch0 5000000000
shift_phase ch0 0.502655
play ch0 w0 0.5
shift_phase ch0 -0.502655
end0:
What to notice:
The readout plays on tone 0 of the feedline,
ch1.0.The branch waits 70 timesteps: the 200-cycle readout, then 80 cycles of feedback latency.
The π pulse shifts its phase by 2π × 2 MHz × 40 ns = 0.502655 rad, then shifts it back before the arm ends.
Test your backend#
CUDA-Q Pulse ships programs for testing a backend. This section runs the toy pass through them.
Read a listing back#
To compare a backend with the schedule, give it events. It reads a
listing back into what it plays:
def events(toy: ToyProgram) -> list[dict[str, Any]]:
"""What *toy* plays, both arms of each branch, read back from its
listing alone."""
found = []
now = 0
branched_at = 0
for instruction in toy.code:
op, *args = instruction.split()
if op == "wait":
now += int(args[0]) * toy.timestep
elif op == "branch":
branched_at = now
elif op.startswith("else"):
now = branched_at
elif op in PULSES:
found.append(pulse_event(toy, op, args, now))
elif op in CALLS:
found.append(call_event(op, args, now))
return found
The backend#
The backend wraps the pass and the read-back:
class ToyBackend:
"""The toy controllers as a ``cudaq_pulse.backends.Backend``."""
name = "toy"
formats = (FORMAT,)
def control_system(self) -> ControlSystem:
return toy_control_system()
def emit(self, program: Mapping[str, Any]) -> ToyProgram:
return lower(program)
def events(self, artifact: ToyProgram) -> list[list[Any]]:
return [events(artifact)]
Its run plays listings on an emulator of the toy controllers.
Validate it#
The test programs compile with the default schedule, which waits out the toy controller’s feedback latency. So validate against the toy controller itself:
from cudaq_pulse import backends
from toy_isa import ToyBackend
report = backends.validate(ToyBackend())
lines = str(report).splitlines()
print(lines[-1])
Output
backend 'toy': 29 passed, 2 skipped
The test programs cover:
one program per kind of event
a branch, and branches on whether a decoder answered in time, with the call’s timeout and with the function’s own
values known only at run time
a shared line, and two controllers
Two are skipped. Print them:
for result in lines[:-1]:
if not result.startswith("PASS"):
name = result.split(":")[0]
print(name)
Output
SKIP runtime
SKIP runtime_frequency
Both set a frame from a decoder’s answer at run time. The toy description doesn’t support that, so the compiler turns them away.
Check your own programs#
Check your own programs against their schedule the same way:
from toy_isa import events
played = []
for event in events(toy):
played.append((event["kind"], event["line"], event["start_cycles"]))
expected = []
for event in scheduled.schedule:
if event.kind != "wait":
expected.append((event.kind, event.line, event.start_cycles))
print("plays as scheduled:", sorted(played) == sorted(expected))
Output
plays as scheduled: True
Then pin each listing with a golden copy in your tests.
Where to go next#
Getting More out of Your Controller’s Instruction Set goes through six common controller limits with this pass, from feedback latency to waveform memory.
From Kernel to Controller packages a backend as a distribution that CUDA-Q Pulse finds by its entry point.
The Program a Backend Reads documents every key of the export.