Controller Backends API#

See The Program a Backend Reads for the exported program, Write and Validate a Backend for how backends are found, Describe Your Control System for the lines and limits of a controller, and Errors for ControllerLimitError and the BackendError exceptions.

Export and limits#

ScheduledKernel.export_to_controller(
sample_rate_ghz=None,
*,
controller=None,
version=1,
)[source]

The program for an out-of-tree controller backend: its lines and every timed operation with its waveform, tone, frame and branches (see cudaq_pulse.controller); with sample_rate_ghz, each envelope’s samples too. On a control system of several controllers, the program of the one controller indexes, in its own cycles (a program that plays the lines of more than one needs it). Exporting each controller in turn walks and checks the whole program once: the program keeps that until every controller’s part is exported. version=2 gives the structured format, which keeps loops rolled.

Parameters:
  • sample_rate_ghz (float | None)

  • controller (int | None)

  • version (int)

Return type:

dict[str, Any]

cudaq_pulse.controller.FORMAT = 'cudaq-pulse.controller/1'#

The format of the program that export_to_controller() returns by default: the schema’s name and, after the slash, its major version.

class cudaq_pulse.controller.DriveLine(
qudits,
delay_ns=0.0,
*,
max_concurrent_tones=1,
broadcast=False,
frequency_hz=None,
)[source]#

Bases: _Line

A drive line of a controller (Controller.drive_lines); see ReadoutLine. A bare carrier index in drive_lines is an undelayed DriveLine. A line whose one tone reaches several qudits at once is a broadcast line: DriveLine([0, 1, 2], broadcast=True). A kernel gets it with get_drive_line(q) of any of its qudits or with get_drive_line(a, b, c) of all of them, and a drive on it drives every one. Its tone starts at frequency_hz (DriveLine([0, 1, 2], broadcast=True, frequency_hz=5.1e9)), which may be left out when its qudits share one frequency; each qudit is driven off resonance by the difference from its own. Where the qudits give an Offset from one reference, the tone is the Offset they share and frequency_hz is not taken; where they give no frequency, the tone is at the carrier of each qudit the line reaches, a change of its frequency in a kernel is that offset from each, and frequency_hz is not taken. Both keywords are for a list of qudits: with one qudit given as an int they are ignored, and DriveLine([0], broadcast=True) is an error.

Parameters:
  • qudits (int | Iterable[int])

  • delay_ns (float | Time)

  • max_concurrent_tones (int)

  • broadcast (bool)

  • frequency_hz (float | None)

Return type:

Self

class cudaq_pulse.controller.ReadoutLine(
qudits,
delay_ns=0.0,
*,
max_concurrent_tones=1,
broadcast=False,
frequency_hz=None,
)[source]#

Bases: _Line

A readout line of a controller (Controller.readout_lines): ReadoutLine(5, delay_ns=12.0) reads out qudit 5, its pulses played 12 ns early. A bare carrier index in readout_lines is an undelayed ReadoutLine. A feedline reading out several qudits is shared: ReadoutLine([0, 1, 2, 3], max_concurrent_tones=4) plays up to four readout tones at once (1 by default, at most the qudits it reaches).

Parameters:
  • qudits (int | Iterable[int])

  • delay_ns (float | Time)

  • max_concurrent_tones (int)

  • broadcast (bool)

  • frequency_hz (float | None)

Return type:

Self

class cudaq_pulse.controller.UpdateBus(drive_lines=(), readout_lines=(), cycles_per_update=1)[source]#

Bases: object

A bus that carries the updates of a group of a controller’s lines (Controller.update_buses) one at a time, each holding it for the cycles_per_update of the controller’s cycles before the update takes effect: UpdateBus(drive_lines=[0, 1], cycles_per_update=8). drive_lines and readout_lines name its lines by carrier index, as the controller’s own do. An update is a frame update, or a drive or readout whose tone’s frequency, or whose phase other than as the tone runs on, differs from the drive or readout before it on its line; see “Update buses” in the controller backends guide.

Parameters:
  • drive_lines (Sequence[int])

  • readout_lines (Sequence[int])

  • cycles_per_update (int)

drive_lines: Sequence[int] = ()#
readout_lines: Sequence[int] = ()#
cycles_per_update: int = 1#
as_dict()[source]#

The bus as JSON-serializable data, as a system file holds it.

Return type:

dict[str, Any]

class cudaq_pulse.controller.WaveformMemoryScope(*values)[source]#

Bases: StrEnum

Which lines one waveform memory of a controller serves (Controller.waveform_memory); the strings "per_line" and "shared" mean the same.

PER_LINE = 'per_line'#

Each line has a memory of its own.

SHARED = 'shared'#

One memory serves every line, and holds a waveform they share once.

class cudaq_pulse.Event(*values)[source]#

Bases: StrEnum

The kind of an event of a format /2 program: what the controller does, named alike for every modality.

PLAY plays a waveform on a line and READOUT plays one and acquires a measurement result; WAIT idles a line, SYNC aligns lines and LOOP repeats its body. CALL sends a request to a classical function over a link and ANSWER takes its answer. An event in a branch keeps its kind and lists its conditions; a frame’s phase and frequency are carried by the events that play on it, and FRAME_UPDATE is a phase or frequency change that no later event plays with on some path, at its place on the timeline. The export holds the plain strings, so Event.PLAY == "play".

PLAY = 'play'#
READOUT = 'readout'#
WAIT = 'wait'#
SYNC = 'sync'#
LOOP = 'loop'#
CALL = 'call'#
ANSWER = 'answer'#
FRAME_UPDATE = 'frame_update'#
cudaq_pulse.controller.check(lowered, limits=None)[source]#

The limits lowered exceeds, of limits or else its controller’s: a list, or past 10,000 violations in rolled loops a sequence that builds each one when read (ControllerLimitError.violations).

Of a module with float parameters (lowered.generic), the limits it exceeds whatever their values; a call’s values are checked when it is made, so a limit never fails first at export. A shared line of limits is checked as compiling for it checks it (the tones it plays at once).

Parameters:
Return type:

Sequence[str]

cudaq_pulse.controller.export(lowered, sample_rate_ghz=None, controller=None, version=1)[source]#

A scheduled kernel for a controller backend, as JSON-serializable data.

With sample_rate_ghz, each drive and readout also carries its envelope’s samples at that rate (samples: real and imaginary parts), which must be a whole multiple of the clock. version 2 gives format cudaq-pulse.controller/2: a loop whose iterations repeat is one loop event holding its body, each distinct waveform is listed once, and what follows from the rest is left out (unroll gives format /1 back). Raises ControllerLimitError when the limits of its controller are exceeded. On a control system of several controllers, the program of the one controller indexes (see _export_part); without it, a program on more than one is a ValueError. Without runtime qudits, each line has the frequency of its own tone (_native_frequencies).

Parameters:
  • lowered (ScheduledKernel)

  • sample_rate_ghz (float | None)

  • controller (int | None)

  • version (int)

Return type:

dict[str, Any]

cudaq_pulse.controller.unroll(program)[source]#

A format /2 export in format /1: every event once per loop iteration.

A program already in format /1 is returned as it is. Times, iterations and references are those of the /1 export of the same kernel; a phase is its first iteration’s plus its steps, equal up to rounding; branches are numbered in the order they first appear.

Parameters:

program (Mapping[str, Any])

Return type:

dict[str, Any]

cudaq_pulse.controller.sample_waveform(node, duration_cycles, samples_per_cycle=1)[source]#

The complex envelope of a waveform, samples_per_cycle per cycle.

Sample k is the envelope at k / samples_per_cycle cycles from the start, with the definitions of the waveform ops (times in cycles), the same the simulator plays. samples_per_cycle may be fractional, but the waveform must then last a whole number of samples. Raises ValueError when it does not, or for a waveform the export cannot evaluate: a pulse.custom op of hand-written IR, whose samples the runtime computes, or one whose parameters are not numbers.

Parameters:
  • node (Mapping[str, Any])

  • duration_cycles (int)

  • samples_per_cycle (float)

Return type:

npt.NDArray[np.complex128]

cudaq_pulse.controller.evaluate_expression(expression, readouts=None, answers=None)[source]#

The value an exported run-time expression takes, as a controller must compute it (see the controller backends guide for each term).

readouts gives the level each readout event the expression reads observed, and answers the results of each answer event, both by the event index the expression names. A frame change’s value may be a number, which is its value. A term that several terms use is in the expression’s terms and {"term": n} where it is used; it is computed once. An expression may be any number of terms deep. Raises ExecutionError where the controller must fail the run (a division by zero, say), and InvalidValueError for an input not given or a term not of ExpressionTerm.

Parameters:
  • expression (Any)

  • readouts (Mapping[int, int] | None)

  • answers (Mapping[int, Sequence[float | int | bool]] | None)

Return type:

float | int | bool

class cudaq_pulse.controller.ExpressionTerm(*values)[source]#

Bases: StrEnum

An op an exported expression of a run-time value may have; see evaluate_expression and the controller backends guide.

ADD = 'add'#
SUB = 'sub'#
MUL = 'mul'#
DIV = 'div'#
NEG = 'neg'#
MAX = 'max'#
MIN = 'min'#
EQ = 'eq'#
NE = 'ne'#
LT = 'lt'#
LE = 'le'#
GT = 'gt'#
GE = 'ge'#
FLOOR_DIV = 'floor_div'#
REM = 'rem'#
TO_FLOAT = 'to_float'#
TO_INT = 'to_int'#
CONTROLLER_CYCLES = 'controller_cycles'#
SELECT = 'select'#
cudaq_pulse.controller.shape_key(node)[source]#

A key equal for waveforms that differ only in overall amplitude.

Scale and negation drop out, and so does the amplitude of a built-in shape, known or not; custom samples are normalized to their largest magnitude. None when a parameter other than the amplitude is not known while the program compiles.

Parameters:

node (Mapping[str, Any] | None)

Return type:

tuple[Any, …] | None

cudaq_pulse.controller.shape_known(node)[source]#

Whether shape_key(node) is not None, without building the key.

A backend that refuses a waveform known only at run time asks this of each drive and readout of a format /1 program before it emits anything:

refused = [
    f"event {event['index']} has a waveform known only at run time"
    for event in program["events"]
    if event["kind"] in ("drive", "readout") and not shape_known(event["waveform"])
]

The answer, and the error for a waveform that is not well formed, are those of shape_key; a list of samples that are all floats is not read one by one.

Parameters:

node (Mapping[str, Any] | None)

Return type:

bool

What classical functions cost#

processor.usage(fn) (cudaq_pulse.Processor.usage()) is what one classical function costs on a processor on its own: a FunctionUsage with its cycles, and its time when the processor has a clock.

class cudaq_pulse.controller.FunctionCost(
name,
ops,
size,
local_count,
loop_count,
helpers,
violations,
iteration_count=0,
unrolled_size=0,
)[source]#

Bases: object

The static cost of one classical function’s body.

ops counts the operations of the longest path through the body by class (OpCounts: what one call executes at most); size counts every operation of the body, both arms of each branch (what the controller stores). local_count is how many scalars the body and its helpers hold at once at most, beyond the arguments and results. violations lists what keeps the body off a processor; empty when it runs_on_processor. helpers names the functions it calls whose bodies were counted too.

For a Processor: iteration_count counts the loop iterations on the longest path (each also counted in ops as an add and a branch, the loop’s counter and jump); unrolled_size is size with every loop unrolled; uses gives, by OpClass (LOOP too), where the body or a helper first uses it.

Parameters:
  • name (str)

  • ops (OpCounts)

  • size (int)

  • local_count (int)

  • loop_count (int)

  • helpers (tuple[str, ...])

  • violations (tuple[str, ...])

  • iteration_count (int)

  • unrolled_size (int)

name: str#
ops: OpCounts#
size: int#
local_count: int#
loop_count: int#
helpers: tuple[str, ...]#
violations: tuple[str, ...]#
iteration_count: int = 0#
unrolled_size: int = 0#
property uses: dict[OpClass, str]#

Where the body or a helper first uses each class of operation.

property total: int#

Operations on the longest path.

property runs_on_processor: bool#
processor_cycles(cycles_per_op, loops)[source]#

Clock cycles of the longest path on a processor: cycles_per_op by class, and a loop’s counter and jump as one loop per iteration if the processor loops, else nothing (unrolled).

Parameters:
Return type:

int

class cudaq_pulse.controller.OpClass(*values)[source]#

Bases: StrEnum

A class of operation: those a classical function’s body is counted in (OpCounts), and LOOP, a rolled loop’s counter and jump, which a processor costs per iteration (OpCycles) and may not run (Processor.unsupported). BRANCH is an if or else.

ADD = 'add'#
MUL = 'mul'#
DIV = 'div'#
COMPARE = 'compare'#
BRANCH = 'branch'#
LOAD = 'load'#
CONVERT = 'convert'#
POPCOUNT = 'popcount'#
SQRT = 'sqrt'#
EXP = 'exp'#
LOG = 'log'#
TRIG = 'trig'#
LOOP = 'loop'#
class cudaq_pulse.controller.OpCounts(
*,
add=0,
mul=0,
div=0,
compare=0,
branch=0,
load=0,
convert=0,
popcount=0,
sqrt=0,
exp=0,
log=0,
trig=0,
)[source]#

Bases: _OpTable

How many operations of each class something runs: a function’s longest path (FunctionCost.ops), or what a controller_cost hook says a call of a built-in takes. Every class not given is 0; an unknown one is a TypeError, as for any keyword.

Parameters:
  • add (int)

  • mul (int)

  • div (int)

  • compare (int)

  • branch (int)

  • load (int)

  • convert (int)

  • popcount (int)

  • sqrt (int)

  • exp (int)

  • log (int)

  • trig (int)

property total: int#

The operations of every class.

class cudaq_pulse.controller.OpCycles(
*,
add=1,
mul=1,
div=1,
compare=1,
branch=1,
load=1,
convert=1,
popcount=1,
sqrt=1,
exp=1,
log=1,
trig=1,
loop=1,
)[source]#

Bases: _OpTable

The clock cycles one operation of each class takes on a processor (Processor.cycles_per_op), and loop, a rolled loop’s counter and jump per iteration. Every class not given takes 1 cycle; an unknown one is a TypeError, as for any keyword.

Parameters:
  • add (int)

  • mul (int)

  • div (int)

  • compare (int)

  • branch (int)

  • load (int)

  • convert (int)

  • popcount (int)

  • sqrt (int)

  • exp (int)

  • log (int)

  • trig (int)

  • loop (int)

loop: int#

Backends#

cudaq_pulse.backends.GROUP = 'cudaq_pulse.backends'#

The entry-point group in which a backend’s distribution registers it, under the backend’s name.

class cudaq_pulse.backends.Backend(*args, **kwargs)[source]#

Bases: Protocol

A controller backend.

name: str#
control_system()[source]#

The control system to compile for this controller: a ControlSystem, or its one Controller.

Return type:

ControlSystem | Controller

emit(program)[source]#

The controller’s program for ScheduledKernel.export_to_controller().

Parameters:

program (Mapping[str, Any])

Return type:

Any

run(artifact, *, shots_count=1)[source]#

Run an emitted program on the controller.

Parameters:
  • artifact (Any)

  • shots_count (int)

Return type:

Any

cudaq_pulse.backends.available()[source]#

The names of the backends installed or registered, sorted; none is imported.

Return type:

list[str]

cudaq_pulse.backends.get(name)[source]#

The backend name, loaded on first use and kept.

A registered backend takes precedence over an installed one of the same name. Raises InvalidTypeError when name is not a str, BackendNotFoundError when no backend of that name is installed or registered, and IncompatibleBackendError when an installed backend fails to load, or when the backend is not a Backend or reads none of the formats this cudaq-pulse exports. An error a registered factory raises is passed on as it is.

Example:

backends.register("text", TextBackend)
backend = backends.get("text")
backends.get("text") is backend    # True
Parameters:

name (str)

Return type:

Backend

cudaq_pulse.backends.register(name, factory)[source]#

Make factory the backend name in this process; it takes precedence over an installed backend of the same name.

factory is called with no arguments when the backend is first used, and must return a Backend (a class is called to make one). Registering again replaces the earlier factory. Raises InvalidTypeError when name is not a str or factory is not callable, and InvalidValueError when name is not an identifier.

Example:

backends.register("text", TextBackend)
backend = backends.get("text")
Parameters:
  • name (str)

  • factory (Callable[[], Backend])

Return type:

None

cudaq_pulse.backends.unregister(name)[source]#

Remove a backend register added.

Does nothing when name was never registered. An installed backend of the same name is unaffected, and get finds it again.

Parameters:

name (str)

Return type:

None

cudaq_pulse.backends.validate(
backend,
controller=None,
*,
shots_count=1000,
tolerance=0.05,
)[source]#

Run the export test corpus through backend (a Backend or the name of one) and report what it does wrong.

The corpus has 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, timeout_function, the same for a function declared with latency_mode="timeout", and two with values known only at run time (one a frequency change made ahead of the pulse that takes it), compiled for controller (by default the backend’s control system’s), in each format the backend reads. Four more are wired from that controller: shared_line, both qudits read out at once on one readout line, shared_drive_line_two_tones and shared_drive_line_one_tone, both driven at once on one drive line (the second on a system whose qudits share a frequency), and several_controllers, on two controllers made from it, one of them reading out both qudits on such a line, each controller’s part in format /1 (not compared with emulate). Each must be emitted or refused with IncompatibleBackendError; a program with an event kind no format has, and one in a newer format, must be refused. A program that exceeds the controller’s limits is skipped. Every pulse and wait of the corpus lasts the fewest whole times as long that the controllers play: on their lines’ timestep and no shorter than their min_pulse_cycles; as written wherever they play it so.

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.

A backend may offer two more methods, which make the checks stronger. events(artifact) gives back the emitted programs, one list per controller, each event a mapping with its kind, line (the link of a call or answer), start_cycles and optionally duration_cycles, every execution in program order; the count of programs and the timing and order of plays, acquisitions, calls and answers on each line must then match the controller program, and the pulses must respect the controller’s limits. emulate(artifact, shots_count=...) gives each shot’s measurement outcomes, in the order they end; the fraction of 1s of each must match cudaq_pulse.simulate within tolerance plus three standard errors.

The report’s ok is whether nothing failed; str() gives one line per program, such as FAIL unsupported_event: emit() accepted 'forward_outcome'; it should raise IncompatibleBackendError.

Parameters:
  • backend (Backend | str)

  • controller (Controller | None)

  • shots_count (int)

  • tolerance (float)

Return type:

_Report