Write and Validate a Backend#

A controller backend runs compiled kernels on a quantum controller: it lowers a scheduled program to the controller’s own instructions and waveform memory, and runs it there. Backends live outside cudaq-pulse, in their own distributions, and cudaq-pulse finds the installed ones by a standard Python entry point. This page shows a complete minimal backend, how to use and validate it, and its errors and cost; examples/controller_backend/ is the same backend as an installable distribution.

It is for people who write a backend for their own control electronics. The program a backend receives is in The Program a Backend Reads, and how a backend states what its controller can run is in Describe Your Control System.

A minimal backend#

A backend is an object with a name and three methods, the cudaq_pulse.backends.Backend protocol: control_system() returns the control system to compile for (a ControlSystem, or its one Controller), emit(program) takes an exported program and returns the controller’s, and run(artifact, shots_count=...) runs it. formats, if present, lists the export formats it reads. A program it cannot emit it refuses with IncompatibleBackendError.

Two more methods are optional, and only backends.validate uses them (see Validating a backend). events(artifact) gives an emitted artifact back as one list of events per controller program, each a mapping with its kind (cudaq_pulse.Event, or the /1 name), line (the link of a call or answer), start_cycles and optionally duration_cycles, every execution in program order. emulate(artifact, shots_count=...) runs it on the backend’s emulator and gives each shot’s measurement outcomes, in the order the measurements end.

This one emits one line of text per drive and readout:

from collections.abc import Mapping
from typing import Any

from cudaq_pulse import Controller
from cudaq_pulse.backends import IncompatibleBackendError
from cudaq_pulse.controller import FORMAT


class TextBackend:
    name = "text"
    formats = (FORMAT,)

    def control_system(self) -> Controller:
        return Controller(clock_ghz=1.0, instruction_cycles=2, min_idle_cycles=2)

    def emit(self, program: Mapping[str, Any]) -> list[str]:
        if program["format"] != FORMAT:
            raise IncompatibleBackendError(f"cannot read {program['format']}")
        played = []
        for event in program["events"]:
            if event["kind"] in ("wait", "sync"):
                continue
            if event["kind"] not in ("drive", "readout") or event["conditions"]:
                raise IncompatibleBackendError(f"cannot play event {event['index']}")
            played.append(
                f"{event['start_cycles']} {event['kind']} line {event['line']} "
                f"{event['waveform']['shape']} at {event['frequency_hz']:.6g} Hz"
            )
        return played

    def run(self, artifact: Any, *, shots_count: int = 1) -> list[list[str]]:
        return [list(artifact) for _ in range(shots_count)]

A backend that sets a carrier or a local oscillator for a line takes the line’s frequency from the export’s native_frequency_hz (the same number as dressed_frequency_hz of the line’s qudit), not from the qudit’s bare frequency_hz. On a system with couplings the two differ. Two qudits at 5.0 GHz and 5.15 GHz coupled with 3 MHz have native_frequency_hz 4999940023.980819 and 5150059976.019181: the first qudit’s tone is 59976.02 Hz below its frequency_hz. A carrier set to 5.0 GHz leaves every pulse on that line with this offset, about 0.377 rad of phase per microsecond, and rounds that should repeat stop being equal in phase. See The Program a Backend Reads for the field.

Its distribution registers it under its name in the cudaq_pulse.backends entry-point group, naming the backend class or any callable without arguments that returns one:

[project.entry-points."cudaq_pulse.backends"]
text = "text_controller:TextBackend"

Using a backend#

backends.available() lists the installed backends without importing any, and backends.get(name) loads one on first use and keeps it. backends.register(name, factory) adds a backend in the running process without a distribution, and takes precedence over an installed one of the same name:

import cudaq_pulse as pulse
from cudaq_pulse import backends
from cudaq_pulse.quantum_systems import PhysicalQudit

backends.register("text", TextBackend)
backend = backends.get("text")
qs = pulse.quantum_system(
    name="one-qubit", qudits={0: PhysicalQudit(0, 5.0e9, 50.0, 30.0, anharmonicity_hz=-2.0e8)}, clock_ghz=1.0
)


@pulse.kernel
def drive_and_measure(q, x_duration, x_sigma, readout_duration):
    drive_line = get_drive_line(q)
    readout_line = get_readout_line(q)
    drive(drive_line, gaussian(x_duration, 0.5, x_sigma))
    sync(drive_line, readout_line)
    readout(readout_line, square(readout_duration, 0.05))


compiled = pulse.compile(drive_and_measure, quantum_system=qs, control_system=backend.control_system())
scheduled = compiled.lower(
    qs.qudits[0],
    x_duration=40 * pulse.ns,
    x_sigma=10 * pulse.ns,
    readout_duration=200 * pulse.ns,
)
program = scheduled.export_to_controller()
print(backend.run(backend.emit(program), shots_count=1))
# [['0 drive line 0 gaussian at 5e+09 Hz', '40 readout line 1 square at 5e+09 Hz']]

Validating a backend#

backends.validate(backend, controller=...) runs the export test corpus, which ships with cudaq-pulse, through a backend: a program for each kind of event (cudaq_pulse.Event), one with a branch, answer_timeout, which branches on whether a call’s answer came in time and on the answer itself (its conditions differ only in result), timeout_function, the same for a function declared with latency_mode="timeout", and one with values known only at run time, compiled for the controller (by default the backend’s control system’s) and exported in each format the backend reads. Four more are wired from that controller: shared_line reads out both qudits at once on one readout line reaching both (ReadoutLine([0, 1], max_concurrent_tones=2) in place of its readout lines), shared_drive_line_two_tones drives both qudits at once with the same envelope on one drive line reaching both (DriveLine([0, 1], max_concurrent_tones=2) in place of its drive lines, its readout lines as they are) and reads both out; its two tones are at the qudits’ two frequencies. shared_drive_line_one_tone is the same program on a system of the corpus’s own whose two qudits share a frequency, so that a backend whose line plays one tone for all its qudits can emit it. And several_controllers runs on two controllers made from it, one driving qudit 0 and reading out both qudits on such a line, the other driving qudit 1, with a shared reference clock; each controller’s part is emitted on its own in format /1 (several_controllers[0], several_controllers[1]), and is not compared with emulate. Each must be emitted or refused with IncompatibleBackendError, and a program with an event kind no format has, or in a newer format, must be refused. A program that exceeds the controller’s limits is skipped. The corpus’s pulses and waits last 16 to 200 cycles, all multiples of 4; on a controller with a longer min_pulse_cycles, or a timestep or sample rate those lengths are off, every one of them lasts the fewest whole times as long that the controller plays (16 cycles become 64 for a min_pulse_cycles of 64), so its programs are checked rather than skipped. On every other controller the corpus is as written.

from cudaq_pulse import Controller, backends

report = backends.validate("text", controller=Controller(clock_ghz=1.0))
print(report)
# PASS play
# ...
# REFUSED call: cannot play event 1
# ...
# PASS unsupported_event
# PASS newer_format
# backend 'text': 12 passed, 8 refused
print(report.ok)  # True

A backend that accepted the unknown event would instead report FAIL unsupported_event: emit() accepted 'forward_outcome'; it should raise IncompatibleBackendError.

branch plays its pulse on the readout’s outcome once the controller’s feedback_latency_cycles have passed after the readout ends: every schedule waits for it, so a controller with long feedback latency runs branch too.

slow = Controller(clock_ghz=1.0, feedback_latency_cycles=2000)  # 2 us
backends.validate(backend, controller=slow)
# PASS branch

Two optional methods make the checks stronger. With events(artifact), which gives the emitted programs back, one list of events per controller (each with its kind, line, start_cycles and optionally duration_cycles, every execution in program order), the number of programs and the timing and order of plays, acquisitions, calls and answers on each line must match the controller program, and the pulses must respect the controller’s limits. With emulate(artifact, shots_count=...), which gives each shot’s measurement outcomes in the order they end, the fraction of 1s of each must match cudaq_pulse.simulate within tolerance (0.05 by default) plus three standard errors of the shots_count. Validating imports nothing until it is called.

Errors#

backends.get raises BackendNotFoundError (a LookupError) for a name no backend has, listing the installed ones, and IncompatibleBackendError (a TypeError) for a backend that fails to import, is not a Backend, or reads none of the formats this version writes; both are BackendError. Compiling a program that exceeds the backend’s limits raises ControllerLimitError, a CompilationError.

Cost#

Importing cudaq-pulse neither imports the backend modules nor looks for installed backends; that happens on the first call to backends. A control system without controllers adds nothing to compilation. The export and the limit checks are native. Exporting in /1 takes time and memory linear in a program’s executions; in /2, and for the checks, a loop whose iterations repeat costs as much as its first two iterations and its last, whatever its trip count. A violation inside it is still listed once per iteration, each message built when it is read.

Where to go next#