From a Kernel to Your Control Electronics#
You have a rack of control electronics: FPGA sequencers, converters, a clock, cables to a chip. This tutorial takes one pulse kernel all the way to what those sequencers execute: an instruction list per channel, a waveform table, a measurement register and a branch on it.
This tutorial is for people who own a control stack and want pulse programs to run on it. Everything on the page runs on a laptop CPU; where your hardware plugs in is marked.
What you’ll learn:
how to describe your electronics as data: clock, timestep, sample rate, limits and latencies;
what the compiler checks against that description, and what its errors say;
how to read the scheduled program and lower it to per-channel instructions;
how measurement feedback and a wait of run-time length reach a sequencer;
where a run on hardware, or a test without it, plugs in.
The backend on this page is examples/controller_backend/sequencer_backend.py, shown a piece at a time. It is no vendor’s instruction set; it has the parts most sequencers share.
All the code on this page is also one Python script,
control_electronics.py.
Describe your control system#
A pulse.Controller states what one box can do, in cycles of its own
clock. Fill it in from the data sheet and from what you have measured:
Field |
What to put there |
|---|---|
|
the clock the sequencer counts |
|
how many cycles apart two instructions can start; every pulse starts and lasts whole timesteps |
|
the rate of the converters |
|
the shortest pulse it plays |
|
what the waveform memory of one line holds |
|
how many frequencies one line plays over a program |
|
the largest sample magnitude it plays |
|
the time from the end of a readout to the first pulse that can depend on its outcome |
This box has a 1 GHz clock, starts an instruction every 4 ns, and needs 200 ns to act on a measurement:
import cudaq_pulse as pulse
from cudaq_pulse.quantum_systems import PhysicalQudit
box = pulse.Controller(
clock_ghz=1.0,
cycles_per_timestep=4,
sample_rate_ghz=1.0,
min_pulse_cycles=16,
waveform_memory_samples=16384,
max_frequencies_per_line=4,
max_amplitude=1.0,
feedback_latency_cycles=200,
)
A pulse.ControlSystem holds the controllers and the links between them
and to classical services. One controller that lists no lines plays every
line. The control system belongs to the quantum system, here one qubit at
5 GHz:
control_system = pulse.ControlSystem(controllers=[box])
qudit = PhysicalQudit(
index=0,
frequency_hz=5.0e9,
t1_us=50.0,
t2_star_us=30.0,
anharmonicity_hz=-2.0e8,
)
system = pulse.quantum_system(
name="one-qubit",
qudits={0: qudit},
clock_ghz=1.0,
control_system=control_system,
)
print(len(control_system.controllers), "controller")
print("clock:", system.clock_ghz, "GHz")
Output
1 controller
clock: 1.0 GHz
With a 1 GHz clock, one cycle is one nanosecond. The other fields of a controller (lines with their delays, shared lines, detectors, processors, several controllers and their clocks) are in Describe Your Control System, and One QPU, Several Control Systems compares five control systems under one chip.
Compile a kernel for it#
The kernel is an active reset: a pulse that flips the qubit, a readout, and the same pulse again only if the qubit read 1. The pulse values are arguments of the kernel; on a device its amplitude comes from a calibration, and the 0.5 used below stands in for one:
@pulse.kernel
def active_reset(
qudit,
flip_duration,
flip_sigma,
flip_amplitude: float,
readout_duration,
):
drive_line = get_drive_line(qudit)
readout_line = get_readout_line(qudit)
flip = gaussian(flip_duration, flip_amplitude, flip_sigma)
drive(drive_line, flip)
sync(drive_line, readout_line)
outcome = readout(readout_line, square(readout_duration, 0.05))
sync(drive_line, readout_line)
if outcome:
drive(drive_line, flip)
lower compiles the call for the quantum system of its qudit, control
system included, and schedules it. Nothing runs:
scheduled = active_reset.lower(
system.qudits[0],
flip_duration=40 * pulse.ns,
flip_sigma=10 * pulse.ns,
flip_amplitude=0.5,
readout_duration=200 * pulse.ns,
)
print("length:", scheduled.duration)
print(f"{'kind':8} {'line':>4} {'start':>6} {'end':>6}")
for event in scheduled.schedule:
print(f"{event.kind:8} {event.line:>4} {event.start:>6} {event.end:>6}")
Output
length: 480 ns
kind line start end
drive 0 0 40
readout 1 40 240
drive 0 440 480
What to notice:
every time is a whole number of clock cycles, and here of 4-cycle timesteps;
the readout ends at cycle 240 and the conditional pulse starts at 440: the scheduler waited the controller’s 200 cycles of feedback latency. Without a control system the pulse would start at 240, sooner than the electronics can decide.
What the compiler refuses#
A program the controller cannot run fails when it compiles, with the line, the limit and the fix. A 42 ns pulse is off the 4 ns timestep:
try:
active_reset.lower(
system.qudits[0],
flip_duration=42 * pulse.ns,
flip_sigma=10 * pulse.ns,
flip_amplitude=0.5,
readout_duration=200 * pulse.ns,
)
except pulse.CompilationError as error:
print(type(error).__name__)
print(error)
Output
ControllerLimitError
the program exceeds the controller's limits:
line d0 moves in timesteps of 4 cycles; 42 cycles isn't a whole number of timesteps (the drive at cycle 0; pulse.round_duration(line, 42) gives 44, or 40 rounding down)
line d0 moves in timesteps of 4 cycles; 42 cycles isn't a whole number of timesteps (the drive at cycle 444; pulse.round_duration(line, 42) gives 44, or 40 rounding down)
cudaq_pulse.controller.check checks a scheduled program against
another controller without raising, which answers “would this program run
on the slower box?”:
from cudaq_pulse import controller
slower = pulse.Controller(
clock_ghz=1.0,
cycles_per_timestep=4,
min_pulse_cycles=64,
feedback_latency_cycles=400,
)
for violation in controller.check(scheduled, slower):
print("-", violation)
Output
- line 0 (drive of qudit 0): the drive at 0 lasts 40 cycles; the controller plays none shorter than 64 (Controller.min_pulse_cycles)
- line 0 (drive of qudit 0): the drive at 440 lasts 40 cycles; the controller plays none shorter than 64 (Controller.min_pulse_cycles)
- line 0: the drive at 440 depends on the readout ending at 240; the controller needs 400 cycles of feedback latency (start at 640 or later; schedule with rcp and readout_latency_cycles >= feedback_latency_cycles)
What to notice: two limits fail, the pulse length twice and the feedback latency once, and each message names the line, the cycle, the limit and what would fit.
Read the scheduled program#
scheduled.schedule gave each operation’s line and time. A sequencer
also needs each pulse’s waveform, frequency and phase, and the measurement
a branch tests. The backend reads all of that once, into records of its
own, and works on the records from there on.
It needs these names:
import re
from collections.abc import Mapping, Sequence
from dataclasses import dataclass, field
from typing import Any
import cudaq_pulse as pulse
from cudaq_pulse import backends
from cudaq_pulse.backends import IncompatibleBackendError
from cudaq_pulse.controller import FORMAT, evaluate_expression, sample_waveform, shape_key
The records are one Step per timed operation and a Program of
them:
@dataclass(frozen=True)
class Step:
"""One timed operation, as the sequencer needs it."""
index: int
kind: str # "drive", "readout", "wait", "submit" or "answer"
channel: int # its line; for a submit or an answer, its link
start: int # in clock cycles
length: int
segment: int = 0
condition: tuple[int, bool] | None = None # (the readout it tests, the arm)
waveform: Mapping[str, Any] = field(default_factory=dict) # of a drive or a readout
amplitude: complex = 0j
frequency_hz: float = 0.0
phase_rad: float = 0.0
max_length: int = 0 # of a wait whose length a register sets
answer: int = -1 # the answer that sets it; -1 for any other step
length_expression: Any = None # of that length, in clock cycles
function: str = ""
measurements: tuple[int, ...] = ()
@dataclass(frozen=True)
class Program:
"""A scheduled program: its channels, links and steps in time order."""
clock_ghz: float
channels: Mapping[int, str]
links: Mapping[int, str]
steps: Sequence[Step]
samples_per_cycle: float = 1.0 # of the converters, per clock cycle
read_program fills them from scheduled.export_to_controller(), the
program as plain data. It is the single place that touches that data, so it
is the one function to replace when the program is read another way; the
rest of the backend depends only on the records:
def read_program(exported: Mapping[str, Any]) -> Program:
"""The records of an exported program. Nothing else reads the export."""
if exported["format"] != FORMAT:
raise IncompatibleBackendError(f"cannot read {exported['format']}")
channels = {line["line"]: f"{line['role']}{line['qudit']}" for line in exported["lines"]}
links = {int(key): link["name"] for key, link in exported["links"].items()}
steps = []
for event in exported["events"]:
kind = event["kind"]
if kind == "sync":
continue # the scheduler has placed what it ties together
if kind not in ("drive", "readout", "wait", "submit", "answer"):
raise IncompatibleBackendError(f"no instruction for a {kind}")
step: dict[str, Any] = {}
conditions = event["conditions"]
if conditions:
if len(conditions) > 1 or conditions[0]["test"] != "is_set":
raise IncompatibleBackendError(
f"event {event['index']} tests more than one measurement register"
)
step["condition"] = (conditions[0]["readouts"][0], conditions[0]["arm"])
if kind in ("drive", "readout"):
if event["frequency_hz"] is None or "tone" in event:
raise IncompatibleBackendError(f"event {event['index']} changes a tone at run time")
amplitude = event["amplitude"]
step.update(
waveform=event["waveform"],
amplitude=complex(amplitude["re"], amplitude["im"]),
frequency_hz=event["frequency_hz"],
phase_rad=event["phase_rad"],
)
elif kind == "wait" and "length" in event:
answers = _answers(event["length"])
if len(answers) != 1 or event["max_cycles"] is None:
raise IncompatibleBackendError(
f"the wait {event['index']} needs one answer and an upper bound"
)
step.update(
max_length=event["max_cycles"],
answer=answers.pop(),
length_expression=event["length"],
)
elif kind in ("submit", "answer"):
step.update(
function=event["function"],
measurements=tuple(event.get("measurements", ())),
)
steps.append(
Step(
index=event["index"],
kind=kind,
channel=event["link"] if kind in ("submit", "answer") else event["line"],
start=event["start_cycles"],
length=event["duration_cycles"],
segment=event["segment"],
**step,
)
)
steps.sort(key=lambda step: (step.start, step.index))
# The converters' rate is the controller's, else one sample per cycle.
rate = (exported.get("limits") or {}).get("sample_rate_ghz")
samples_per_cycle = rate / exported["clock_ghz"] if rate else 1.0
return Program(exported["clock_ghz"], channels, links, steps, samples_per_cycle)
def _answers(expression: Any) -> set[int]:
"""The answers a run-time expression reads."""
if not isinstance(expression, Mapping):
return set()
found = {expression["answer"]} if "answer" in expression else set()
for part in expression.get("of", ()):
found |= _answers(part)
return found
Read the reset:
program = read_program(scheduled.export_to_controller())
print(dict(program.channels))
for step in program.steps:
shape = step.waveform["shape"]
print(step.kind, step.channel, step.start, step.length, shape, step.condition)
Output
{0: 'drive0', 1: 'readout0'}
drive 0 0 40 gaussian None
readout 1 40 200 square None
drive 0 440 40 gaussian (2, True)
What to notice:
the syncs are gone: the scheduler has already placed what they tie together, and a backend places every step at its start without scheduling again;
the last drive carries
(2, True): it plays when readout 2 is set. The 2 is the readout’s place among the program’s operations, syncs included (drive 0, sync 1, readout 2), and the register names below use the same numbers, so that a register always names the operation that wrote it;a program the backend has no instruction for is refused with
IncompatibleBackendErrorrather than run as something else.
Lower it to instructions#
What the sequencers execute is a waveform table and one instruction list per channel:
@dataclass
class Listing:
"""What the sequencers execute: a waveform table and, per channel, its
instructions.
On a line's channel every time is in timesteps of the controller; on a
link's channel, in clock cycles. An instruction behind ``if m<k>:``
lasts its length whether or not it plays: when the test fails the
channel idles for that long. ``idle`` fills the time between two steps;
``wait`` is a wait the program asked for. A register ``m<k>`` holds the outcome
of the acquisition that wrote it; a register ``r<k>`` holds an answer as
the function returned it.
"""
timestep: int
waveforms: list[Any] = field(default_factory=list)
channels: dict[str, list[str]] = field(default_factory=dict)
lines: dict[str, int] = field(default_factory=dict) # each channel's line or link
def text(self) -> str:
lines = [f"timestep: {self.timestep} cycles"]
for number, samples in enumerate(self.waveforms):
lines.append(f"w{number}: {len(samples)} samples")
for name, instructions in self.channels.items():
unit = "clock cycles" if name.startswith("link:") else "timesteps"
lines.append(f"{name} (times in {unit}):")
lines.extend(f" {instruction}" for instruction in instructions)
return "\n".join(lines)
lower walks the steps in time order. On each channel it fills gaps
with wait, sets the oscillator when the frequency changes, and stores
each waveform shape once:
def lower(program: Program, timestep: int = 1) -> Listing:
"""The instruction list of each channel of *program*."""
listing = Listing(timestep)
table: dict[Any, int] = {}
names = {**program.channels}
names.update({-1 - link: f"link:{name}" for link, name in program.links.items()})
cursor = dict.fromkeys(names, 0)
last: dict[int, Step] = {}
frequency: dict[int, float] = {}
for channel, name in names.items():
listing.channels[name] = []
listing.lines[name] = channel if channel >= 0 else -1 - channel
for step in program.steps:
channel = -1 - step.channel if step.kind in ("submit", "answer") else step.channel
out = listing.channels[names[channel]]
unit = 1 if channel < 0 else timestep
if step.start % unit or step.length % unit:
raise IncompatibleBackendError(f"step {step.index} is off the timestep")
ticks = step.length // unit
guard = ""
if step.condition is not None:
readout, arm = step.condition
guard = f"if m{readout}: " if arm else f"if not m{readout}: "
if step.kind in ("drive", "readout"):
# One entry per shape: pulses that differ in amplitude share it.
key = shape_key(step.waveform)
if key not in table:
table[key] = len(listing.waveforms)
listing.waveforms.append(
sample_waveform(step.waveform, step.length, program.samples_per_cycle)
/ step.amplitude
)
wave = f"w{table[key]} gain={abs(step.amplitude):g} phase={step.phase_rad:g}"
if step.kind == "drive":
instruction = f"drive {wave} for {ticks}"
else:
instruction = f"acquire {wave} for {ticks} into m{step.index}"
elif step.kind == "wait" and step.answer >= 0:
# The sequencer waits the register's value, so the length the
# program computes must be that value in clock cycles and no more.
low, high = step.length, step.max_length
for value in (low, high):
given = evaluate_expression(
step.length_expression, {}, {step.answer: [float(value)]}
)
if given != value:
raise IncompatibleBackendError(
f"the wait {step.index} is not its answer in clock cycles"
)
instruction = f"wait_reg r{step.answer}/{unit} min={low // unit} max={high // unit}"
elif step.kind == "wait":
instruction = f"wait {ticks}"
elif step.kind == "submit":
sent = ", ".join(f"m{readout}" for readout in step.measurements)
instruction = f"send {step.function}({sent}) for {ticks}"
else:
instruction = f"recv r{step.index}"
before = last.get(channel)
if step.start < cursor[channel]:
# Two steps at once on one channel: the two arms of one branch
# become one instruction; anything else this sequencer cannot do.
if before is None or not _two_arms(before, step):
raise IncompatibleBackendError(
f"step {step.index} starts at cycle {step.start} while its channel is busy "
f"until cycle {cursor[channel]}; a channel runs one instruction at a time"
)
# The second arm may start later than the first: it idles first.
lead = (step.start - before.start) // unit
out[-1] = f"{out[-1]} else: " + (f"idle {lead}; " if lead else "") + instruction
cursor[channel] = max(cursor[channel], step.start + step.length)
continue
if step.start > cursor[channel]:
out.append(f"idle {(step.start - cursor[channel]) // unit}")
if step.kind in ("drive", "readout") and frequency.get(channel) != step.frequency_hz:
frequency[channel] = step.frequency_hz
out.append(f"set_freq {step.frequency_hz:.0f}")
out.append(guard + instruction)
cursor[channel] = step.start + step.length
last[channel] = step
return listing
def _two_arms(first: Step, second: Step) -> bool:
"""Whether the two steps are the two arms of one branch on a readout."""
return (
first.condition is not None
and second.condition is not None
and first.condition == (second.condition[0], not second.condition[1])
and first.frequency_hz == second.frequency_hz
)
Lower the reset on the box’s 4-cycle timestep:
listing = lower(program, timestep=box.cycles_per_timestep)
print(listing.text())
Output
timestep: 4 cycles
w0: 40 samples
w1: 200 samples
drive0 (times in timesteps):
set_freq 5000000000
drive w0 gain=0.5 phase=0 for 10
idle 100
if m2: drive w0 gain=0.5 phase=0 for 10
readout0 (times in timesteps):
idle 10
set_freq 5000000000
acquire w1 gain=0.05 phase=0 for 50 into m2
What to notice:
the two pulses share one table entry,
w0: 40 samples at the converters’ rate, fromcudaq_pulse.controller.sample_waveform;on a line’s channel times are in timesteps: the 40-cycle pulse lasts 10, the readout 50;
gainis the pulse’s amplitude, the peak of its samples, on the scale on which the box’smax_amplitudeof 1.0 is the largest sample it plays;idle 100fills the time until the next step: the readout plus the feedback latency;if m2: drive ... for 10plays only when registerm2, which the acquisition wrote, is set. It lasts its 10 timesteps either way: whenm2is not set the channel idles for them, so what follows starts at the same time on both paths;the readout’s tone is at the qubit’s 5 GHz because this small system states no readout frequency of its own; a system that does plays its readout there.
Measurement feedback#
That if m2 is all a branch on a readout needs from a sequencer: a
register per acquisition and an instruction that tests it. The compiler
has done the rest:
the pulse starts no sooner than the feedback latency after the readout ends, in every schedule;
pulses in the two arms of one
ifmay overlap in time, and only one arm plays.lowerwrites the two arms of one branch on a channel as one instruction,if m2: ... else: ...(an arm that starts later idles first), and refuses any other two steps at once on a channel, since a channel runs one instruction at a time;on several controllers, an outcome read by one and used by another also waits the reader’s
peer_latency_cycles; One QPU, Several Control Systems and Getting More out of Your Controller’s Instruction Set show it.
A wait of run-time length#
Some lengths are known only during the shot. Here a classical function on the controller picks how long to wait from the readout’s outcome:
@pulse.classical(link="controller", max_latency_ns=100)
def pick_wait(outcome: pulse.Bits) -> float:
return 400.0 if outcome[0] else 80.0
@pulse.kernel
def measure_then_wait(qudit, flip_duration, flip_sigma, readout_duration):
drive_line = get_drive_line(qudit)
readout_line = get_readout_line(qudit)
outcome = readout(readout_line, square(readout_duration, 0.05))
request = pick_wait.submit([outcome])
wait_ns = request.result()
sync(drive_line, readout_line)
wait(
drive_line,
wait_ns * pulse.ns,
bounds=(80 * pulse.ns, 400 * pulse.ns),
)
drive(drive_line, gaussian(flip_duration, 0.5, flip_sigma))
The link the function is reached over belongs to the control system. This one takes 4 ns to send a request, and a pulse can use an answer 8 ns after it arrives:
links = {"controller": pulse.Link(fixed_ns=4, feedback_ns=8)}
with_link = pulse.quantum_system(
name="one-qubit",
qudits={0: qudit},
clock_ghz=1.0,
control_system=pulse.ControlSystem(controllers=[box], links=links),
)
waiting = measure_then_wait.lower(
with_link.qudits[0],
flip_duration=40 * pulse.ns,
flip_sigma=10 * pulse.ns,
readout_duration=200 * pulse.ns,
)
for segment in waiting.segments():
print(
segment.index,
segment.opened_by,
"starts at",
segment.start_cycles,
"and up to",
segment.max_shift_cycles,
"later",
)
Output
0 start starts at 0 and up to 0 later
1 wait starts at 592 and up to 320 later
The schedule places the wait at its lowest length, 80 cycles. What follows it is a new segment, which starts at cycle 592 in that schedule and up to 320 cycles later in a run. Lower it:
wait_listing = lower(
read_program(waiting.export_to_controller()),
timestep=box.cycles_per_timestep,
)
print(wait_listing.text())
Output
timestep: 4 cycles
w0: 200 samples
w1: 40 samples
drive0 (times in timesteps):
idle 128
wait_reg r2/4 min=20 max=100
set_freq 5000000000
drive w1 gain=0.5 phase=0 for 10
readout0 (times in timesteps):
set_freq 5000000000
acquire w0 gain=0.05 phase=0 for 50 into m0
link:controller (times in clock cycles):
idle 400
send pick_wait__1(m0) for 4
idle 108
recv r2
What to notice:
the link is a channel of its own, and its times are in clock cycles, as its heading says: the request goes out at cycle 400, once the outcome has passed the feedback latency, and the answer is taken into register
r2at cycle 512, when it is due;r2holds whatpick_waitreturned: 80.0 or 400.0. The kernel used it as a time in nanoseconds, which on this 1 GHz clock is a number of clock cycles;wait_reg r2/4 min=20 max=100is the wait: the channel waitsr2divided by 4 timesteps, so 20 or 100 of them, 80 or 400 ns, and no fewer than 20 or more than 100, the bounds the kernel gave.lowerchecks, with the reference evaluation of the program’s own length expression, that the length is the answer in clock cycles before it writes this, and refuses the program otherwise;the drive after it has no start time of its own. It follows the wait, which is what a segment means for a sequencer;
here the readout is the program’s first operation, so its register is
m0; the answer is its third,r2.
Check the lowering against the schedule#
A lowering can be wrong. read_back reads a listing’s instructions and
nothing else, and gives each timed operation with its channel, start and
length:
_TIMED = re.compile(
r"(?:if (?:not )?m\d+: )?(?P<kind>drive|acquire|wait|send)\b.*? (?:for )?(?P<ticks>\d+)(?: into m\d+)?$"
)
_KINDS = {"drive": "drive", "acquire": "readout", "wait": "wait", "send": "submit"}
def read_back(listing: Listing) -> list[dict[str, Any]]:
"""The timed events of an emitted listing, read from its instructions
alone: what ``backends.validate`` compares with the schedule."""
events = []
for name, instructions in listing.channels.items():
unit = 1 if name.startswith("link:") else listing.timestep
line, cursor = listing.lines[name], 0
for instruction in instructions:
if instruction.startswith("set_freq"):
continue
if instruction.startswith("idle"):
cursor += int(instruction.split()[1]) * unit
continue
if instruction.startswith("recv"):
events.append((cursor, "answer", line, 0))
continue
if instruction.startswith("wait_reg"):
# Placed at its lowest length, as the schedule places it.
ticks = int(instruction.split("min=")[1].split()[0])
events.append((cursor, "wait", line, ticks * unit))
cursor += ticks * unit
continue
longest = 0
for arm in instruction.split(" else: "):
lead = 0
if arm.startswith("idle "):
idle, arm = arm.split("; ", 1)
lead = int(idle.split()[1]) * unit
found = _TIMED.match(arm)
if found is None:
raise ValueError(f"cannot read back {arm!r}")
length = int(found["ticks"]) * unit
events.append((cursor + lead, _KINDS[found["kind"]], line, length))
longest = max(longest, lead + length)
cursor += longest
events.sort(key=lambda event: event[0])
return [
{"kind": kind, "line": line, "start_cycles": start, "duration_cycles": length}
for start, kind, line, length in events
]
The reset’s listing, read back, has the times of the schedule:
for event in read_back(listing):
print(event["kind"], event["line"], event["start_cycles"], event["duration_cycles"])
Output
drive 0 0 40
readout 1 40 200
drive 0 440 40
backends.validate, below, makes this comparison for a corpus of
programs.
Run it: where your hardware plugs in#
A backend is an object with a name and three methods: what its
controller can do (control_system), the program in the controller’s own
form (emit), and a run (run). run is where your electronics
come in: connect, upload the waveform table and the instruction lists, arm,
trigger, and fetch the acquisitions. This stand-in takes a listing and
answers its acquisitions from a list of outcomes you give it:
class DryRun:
"""Stands where the connection to the electronics goes. It takes a
listing and gives every acquisition register the next outcome of
*outcomes*, a list that is used again from its start when it runs out
(0 without one)."""
def __init__(self, outcomes: Sequence[int] = (0,)) -> None:
self.outcomes = list(outcomes)
def upload(self, listing: Listing) -> None:
self.registers = re.findall(r"into (m\d+)", listing.text())
def run(self, shots_count: int) -> list[dict[str, int]]:
shots, drawn = [], 0
for _ in range(shots_count):
shot = {}
for register in self.registers:
shot[register] = self.outcomes[drawn % len(self.outcomes)]
drawn += 1
shots.append(shot)
return shots
The backend ties the pieces together. Its control_system returns the
box described at the top of this page:
class SequencerBackend:
name = "sequencer"
formats = (FORMAT,)
def __init__(self, hardware: Any = None) -> None:
self.hardware = hardware if hardware is not None else DryRun()
def control_system(self) -> pulse.Controller:
return pulse.Controller(
clock_ghz=1.0,
cycles_per_timestep=4,
sample_rate_ghz=1.0,
min_pulse_cycles=16,
waveform_memory_samples=16384,
max_frequencies_per_line=4,
max_amplitude=1.0,
feedback_latency_cycles=200,
)
def emit(self, program: Mapping[str, Any]) -> Listing:
timestep = self.control_system().cycles_per_timestep
return lower(read_program(program), timestep)
def run(self, artifact: Listing, *, shots_count: int = 1) -> list[dict[str, int]]:
self.hardware.upload(artifact)
return self.hardware.run(shots_count)
def events(self, artifact: Listing) -> list[list[dict[str, Any]]]:
"""The emitted program read back, for ``backends.validate``."""
return [read_back(artifact)]
Register it in the running process. Then make one whose dry run answers 1 and then 0, emit the reset with it and run two shots:
backends.register("sequencer", SequencerBackend)
backend = SequencerBackend(hardware=DryRun(outcomes=[1, 0]))
artifact = backend.emit(scheduled.export_to_controller())
print(backend.run(artifact, shots_count=2))
Output
[{'m2': 1}, {'m2': 0}]
What changes on a real rack, and what does not:
the controller description becomes your controller’s numbers;
lowerwrites your sequencer’s instructions instead of these;hardwarebecomes an object with the same two methods that talks to your electronics:SequencerBackend(hardware=my_rack);the kernel, the compile, the check and
read_programstay as they are.
Before any hardware, backends.validate runs a corpus of test programs
through the backend, one for each kind of event. Each must be emitted or
refused cleanly. Because this backend gives back the events of what it
emitted (events, which calls read_back), validation also compares
their timing and order on each line with the schedule:
report = backends.validate("sequencer")
print(report)
Output
PASS play
PASS readout
PASS wait
PASS sync
PASS loop
PASS call
REFUSED answer: event 3 tests more than one measurement register
REFUSED frame_update: no instruction for a frame_update
PASS branch
REFUSED answer_timeout: event 3 tests more than one measurement register
REFUSED timeout_function: event 3 tests more than one measurement register
REFUSED runtime: event 3 changes a tone at run time
SKIP runtime_frequency: exceeds the controller's limits: line 0 (drive of qudit -1): the drive at 0 peaks at amplitude 2; the controller plays at most 1 (Controller.max_amplitude)
PASS shared_line
PASS shared_drive_line_two_tones
PASS shared_drive_line_one_tone
PASS several_controllers[0]
PASS several_controllers[1]
PASS unsupported_event
PASS newer_format
backend 'sequencer': 14 passed, 5 refused, 1 skipped
What to notice:
nothing fails. The backend emits drives, readouts, waits, loops, a branch, shared lines (each tone of a shared line is a channel of its own, as each tone is its own sequencer) and the two parts of a program on two controllers;
it refuses what it has no instruction for, and says why.
answerbranches on an answer together with a readout, which needs more than one register in a test; this page’s program used its answer as a wait’s length, which the backend does emit.runtimechanges a tone’s phase from a value known only during the shot, andframe_updateis a phase or frequency change of a tone that no later pulse takes (the export’sframe_update). Each refusal is a list of what to build next;SKIPmarks a corpus program that this controller’s limits do not allow: its pulse peaks above the box’smax_amplitude. A backend whose controller states no such limit has no skipped program.
A lowering with a mistake does fail. This backend shortens every idle
by one timestep, so each step after an idle starts 4 cycles early. The
line printed below is the corpus’s branch program: its conditional
pulse was emitted at cycle 308 where the schedule has it at 312:
class EarlyBackend(SequencerBackend):
name = "early"
def emit(self, program):
listing = super().emit(program)
for instructions in listing.channels.values():
for place, instruction in enumerate(instructions):
if instruction.startswith("idle"):
ticks = int(instruction.split()[1]) - 1
instructions[place] = f"idle {ticks}"
return listing
broken = backends.validate(EarlyBackend())
print("ok:", broken.ok)
for line in str(broken).splitlines():
if line.startswith("FAIL branch"):
print(line)
backends.unregister("sequencer")
Output
ok: False
FAIL branch: line 0: event 1 is a play at 308 cycles; the controller program has a play at 312
What your electronics must provide#
The two listings used these, and no more:
a clock, and instructions that start on its timesteps;
a waveform memory, played at a gain and a phase;
an oscillator per channel, set to a frequency;
an acquisition that writes a register, and an instruction that tests one;
for a wait of run-time length: a link that sends a request and takes its answer into a register, and a wait whose length is a register.
A controller that lacks one says so in its description
(Controller(supports=[...]), supports_timeouts), and a program that
needs it then fails to compile.
What is not on this page#
CUDA-Q Pulse ships no backend for a particular product: backends live in their own distributions and are found by an entry point (Write and Validate a Backend). The backend here is a starting point for one.
The run above returns the outcomes it was given. A run without hardware that follows a program’s classical calls in virtual time is
cudaq_pulse.classical.emulation.emulate, and a simulation of the qubits ispulse.simulate; see Simulation.What Runs Today says what runs today and what is not available yet.
Where to go next#
One QPU, Several Control Systems puts five control systems under one chip and shows what feedback latency, a hop between boxes and a limit on drives at once cost.
From Kernel to Controller covers the backend interface: registering by entry point, validation, and one program on two controllers.
Lowering to Your Controller’s Instruction Set and Getting More out of Your Controller’s Instruction Set lower to a fuller instruction set: loops kept rolled, oscillators, a decoder call with a deadline, waveform memory.
Describe Your Control System is the reference for every field of a controller description, and The Program a Backend Reads for the program a backend receives.