Classical Calls API#
See Call Classical Code During a Shot for how calls are scheduled, simulated and emulated.
Functions and links#
-
cudaq_pulse.classical.function(
) ClassicalFunction[Q, T][source]#implementation: Callable[Q, T],/,**options: Unpack[_Options],
-
cudaq_pulse.classical.function(
) Callable[[Callable[Q, T]], ClassicalFunction[Q, T]]implementation: None = None,/,**options: Unpack[_Options],
Declare a classical function;
pulse.classicalis this decorator.The parameters’ and result’s type hints say what it takes and returns:
float,intandcomplex(one IQ point) take one value;pulse.Bits(measurements read as bits),list[int](measured levels, or numbers),list[complex](IQ points) andlist[float]take a list whose length comes from the call. Results arefloat,int,bool,pulse.Bits,list[float],list[int], a tuple of them orNone; a list result’s length is inferred from the body.pulse.Lengthstates a fixed length where one wire schema is wanted:pulse.Length[pulse.Bits, 8]takes eight measurements read as bits andpulse.Length[list[int], 8]eight numbers; a result-> pulse.Length[pulse.Bits, 2]answers two bits.Keyword options:
max_latency_ns(required),min_latency_ns,nominal_latency_ns,latency_mode("bounded","timeout"withtimeout_ns, or"blocking"),submit("eager"or"lazy"),deadline_ns,reaction_deadline_ns,link(the link its requests travel on: a name fromControlSystem.links, such as"controller", or a link id; default 0;deviceis not used for it, because a cudaq-pulse quantum system is the QPU) andname. A latency, timeout or deadline is a time (400 * pulse.ns) or a number of ns.With
reaction_deadline_ns, compiling fails unless every call’s answer is due within that long of the end of the latest readout whose outcome the request carries (of the start of the submission when it carries none): the time from measuring to being able to act on the answer, queueing, link andmax_latency_nsincluded.The hints are read when the function is first used (a program that calls it is compiled), and a mistake in them is raised there.
- Parameters:
implementation (Callable[[...], Any] | None)
options (Any)
- Return type:
Any
- cudaq_pulse.classical.external(**options)[source]#
Declare a classical function served elsewhere: a declaration whose hints give its schema and whose body is a placeholder for its result, which never runs:
@pulse.classical.external(max_latency_ns=50, link="feedback") def table(index: pulse.Length[pulse.Bits, 3]) -> float: return float() @pulse.classical.external(max_latency_ns=900, link="gpu") def decode(syndrome: pulse.Bits) -> tuple[float, pulse.Bits]: return (float(), syndrome[:2])
A placeholder is a value of the result’s type:
float(),pulse.Bits()(its length stated), an input (return outcomes) or a slice of one, whose length the result takes; aNoneresult needs no return. A list parameter of no stated length takes its length from the call, one version per length as forpulse.classical; state the length the quantum system takes,pulse.Length[pulse.Bits, 3], and a call of another length is a compile error.It takes the keyword options of
pulse.classical. Simulating a program that calls it needs a handler for it.- Parameters:
options (Unpack[_Options])
- Return type:
Callable[[Callable[Q, T]], ClassicalFunction[Q, T]]
- cudaq_pulse.classical.dispatch_key(name)[source]#
The dispatch key of a function compiled as name, unless its controller fixes one: 32-bit FNV-1a, the hash CUDA-Q Realtime registers handlers by.
- Parameters:
name (str)
- Return type:
int
- class cudaq_pulse.classical.ClassicalDecorator(*args, **kwargs)[source]#
Bases:
_Declare,ProtocolWhat type checkers take
pulse.classicalto be: the decorator, with this module’s names as attributes.A module can’t be declared callable, so
cudaq_pulsedeclares itsclassicalattribute with this type for checkers only; at run time it is this module.- ClassicalFunction: type[_AnyFunction]#
- function: _Declare#
- external: _External#
- dispatch_key: Callable[[str], int]#
- random_index: Callable[..., _IndexFunction]#
- calibration: types.ModuleType#
- emulation: types.ModuleType#
- loop: types.ModuleType#
- wire: types.ModuleType#
-
class cudaq_pulse.classical.ClassicalFunction(
)[source]#implementation,*,name=None,max_latency_ns,min_latency_ns=0.0,nominal_latency_ns=None,latency_mode='bounded',timeout_ns=None,submit='eager',deadline_ns=None,reaction_deadline_ns=None,link=0,_signature=None,_dispatch_key=None,_key_route=None,
Bases:
Generic[P,R]A classical function a pulse kernel can call while the QPU runs.
Made by
@pulse.classical(...)or@pulse.classical.external(...). In a kernel,.submit(*args)sends a request and returns a future whose.result()takes the answer. Outside a kernel, calling it runs its reference implementation.A function with a list parameter of no stated length is a template: each set of list lengths it is called with in a kernel is a version, named
name__<lengths>(decode__4,levels__i3for three i32 numbers), dispatched by the hash of that name.specialize(...)gives one version.- Parameters:
implementation (Callable[P, R] | None)
name (str | None)
max_latency_ns (float | Time)
min_latency_ns (float | Time)
nominal_latency_ns (float | Time | None)
latency_mode (str)
timeout_ns (float | Time | None)
submit (str)
deadline_ns (float | Time | None)
reaction_deadline_ns (float | Time | None)
link (int | str)
_signature (Callable[..., Any] | None)
_dispatch_key (int | None)
_key_route (int | None)
- args: tuple[ValueType, ...]#
- results: tuple[ValueType, ...]#
- reaction_deadline_ns: float | None = None#
- uniform: int | None#
- submit(*args, **kwargs)[source]#
Call the function; outside a kernel this runs it at once.
- Parameters:
args (P.args)
kwargs (P.kwargs)
- Return type:
Pending[R]
- specialize(**lengths)[source]#
The version of this function for list parameters of lengths (by parameter name), as a kernel call with lists of those lengths makes it. A function of one schema is its own version.
- Parameters:
lengths (int)
- Return type:
ClassicalFunction[P, R]
- class cudaq_pulse.classical.Pending(*args, **kwargs)[source]#
Bases:
Protocol,GenericWhat
fn.submit(...)returns: a future while a kernel is traced, an answer already taken when called outside a kernel..result()gives the declared results; withtimeout(a time, or a number of nanoseconds, of whole program cycles) it gives(in_time, *results).
-
class cudaq_pulse.classical.Link(
)#fixed_ns=0.0,bytes_per_ns=0.0,feedback_ns=0.0,slots=64,slot_bytes=1024,controllers=None,per_controller=False,
Bases:
objectWhat one link to a classical service costs, for scheduling.
fixed_nsis the fixed cost of sending a request andbytes_per_nsits bandwidth (0 for unlimited): a request holds the link forfixed_ns + bytes / bytes_per_ns, at least one clock cycle.feedback_nsis added to every latency: the time from an answer arriving to a pulse being able to use it.fixed_nsandfeedback_nsare times (100 * pulse.ns) or numbers of ns.slotsis how many requests the link holds at once (its slots), andslot_bytesthe largest request or answer, its 24-byte header included.controllersare the controllers of aControlSystemthe link reaches (None: all of them): a call over it can send only their measurements, and only they can use its answers.A link is one service the controllers share. With
per_controller, each controller it reaches has an instance of its own, with its own slots, its own processor (Processor.links) and its own dispatch keys: a call over it runs on the instance of the controller that sends its measurements and uses its answer, which must be one controller, so no answer crosses between controllers.- Parameters:
fixed_ns (float | Time)
bytes_per_ns (float)
feedback_ns (float | Time)
slots (int)
slot_bytes (int)
controllers (Sequence[Controller] | None)
per_controller (bool)
- attribute(uncertainty_ns=0.0, name=None)[source]#
The link as an entry of the module attribute
classical.links; uncertainty_ns is how far apart the starts of the controllers it joins may be, which an answer taken on another controller than the one that sent the request adds to its budget. A per-controller link is marked so, with its name.- Parameters:
uncertainty_ns (float)
name (str | None)
- Return type:
str
- bytes_per_ns: float = 0.0#
- controllers: Sequence[Controller] | None = None#
- cost()[source]#
What the link costs, as JSON-serializable data (with
per_controllerwhen it has an instance per controller).- Return type:
dict[str, float | int]
- per_controller: bool = False#
- slot_bytes: int = 1024#
- slots: int = 64#
Measurements and randomness#
- class cudaq_pulse.classical.Bits(iterable=(), /)[source]#
Bases:
listMeasurements read as bits (
outcome != 0), bit-packed on the wire.A kernel passes a list of measurements,
fn.submit([m0, m1]); the body readsbits[0],len(bits)or iterates. As a result, the bits are answered as booleans a kernel can branch on. The length comes from the call, or is stated,pulse.Length[pulse.Bits, 8].pulse.Bits()is an empty list, an external’s placeholder result.
- cudaq_pulse.Length#
typing.Annotated, re-exported to state a fixed list length:pulse.Length[pulse.Bits, 8]takes or answers eight bits andpulse.Length[list[int], 8]eight numbers. The length is a positive whole number.
-
cudaq_pulse.classical.random_index(
)[source]#n,/,*,name='random_index',max_latency_ns=0.0,link=0,**options,
An on-device random source: a classical function of no arguments whose answer is an integer drawn uniformly from
0 .. n - 1.On hardware the controller’s random number generator answers it (the manifest marks it
"random"). Simulation without shots follows every value, each with probability 1/n; with shots each shot draws one. Emulation draws from its own seeded generator. Use it to pick a randomized-benchmarking gate per shot, branching on the index.- Parameters:
n (int)
name (str)
max_latency_ns (float | Time)
link (int | str)
options (Any)
- Return type:
ClassicalFunction[(), int]
Reports#
-
class cudaq_pulse.compiler.ClassicalCall(
)#function,compiled_name,dispatch_key,link,iteration,submit_cycles,submit_duration_cycles,due_cycles,taken_cycles,first_use_cycles,deadline_cycles,segment,link_name=None,exposed_cycles=None,controller=None,
Bases:
objectOne execution of a call to a classical function, from
classical_report().Times are in clock cycles. The request is sent from
submit_cyclesforsubmit_duration_cycles; its answer is due atdue_cycles(the budgeted latency after that) and taken attaken_cycles(Noneif the kernel never takes it).first_use_cyclesis the earliest start of a pulse whose amplitude, tone or branch comes from the answer, anddeadline_cyclesthe latest due time the function’sdeadline_nsallows.segmentis the segment it is submitted in.link_nameis the link’s name in the control system, if it has one.controlleris the controller whose instance of a per-controller link runs the call (Link(per_controller=True)), elseNone.functionis the name the function is declared with andcompiled_namethe name it is compiled and served under: a version’s, such as"adaptive_t1__1", for a function whose list lengths come from its calls, else the same name.dispatch_keyis the key its requests carry: the hash ofcompiled_name(classical.dispatch_key), or the key its controller’s firmware fixes (thedispatch_keysof the processor that runs it).exposed_cyclesis how long the first use waits for the answer beyond when it could start without the call: after its line is free and after the readout resonator of the last readout before the call has depleted (PhysicalQudit.depletion_ns), when pulses must wait anyway. The rest of the budget,hidden_cycles, overlaps that work. A latency within the depletion time is hidden entirely.- Parameters:
function (str)
compiled_name (str)
dispatch_key (int)
link (int)
iteration (tuple[int, ...])
submit_cycles (int)
submit_duration_cycles (int)
due_cycles (int)
taken_cycles (int | None)
first_use_cycles (int | None)
deadline_cycles (int | None)
segment (int)
link_name (str | None)
exposed_cycles (int | None)
controller (int | None)
- controller: int | None = None#
- property deadline_slack_cycles: int | None#
How far the due time is inside the deadline (negative: missed).
- exposed_cycles: int | None = None#
The part of the budget that overlaps other work.
- link_name: str | None = None#
- property slack_cycles: int | None#
How long the answer could arrive later without delaying a pulse.
- function: str#
- compiled_name: str#
- dispatch_key: int#
- link: int#
- iteration: tuple[int, ...]#
- submit_cycles: int#
- submit_duration_cycles: int#
- due_cycles: int#
- taken_cycles: int | None#
- first_use_cycles: int | None#
- deadline_cycles: int | None#
- segment: int#
-
class cudaq_pulse.compiler.Segment(
)[source]#index,opened_by,line,start_cycles,min_shift_cycles,max_shift_cycles,
Bases:
objectOne segment of a compiled kernel, from
ScheduledKernel.segments().A variable wait (its length computed from a classical answer) or a blocking classical wait is a barrier for the lines that depend on it: those it waits on or whose pulses use its answer, and every line tied to them by a
sync, a shared tone, a branch or a kernel with its ownschedule=. They sync before it, and what follows on them shifts with its run-time length; other lines keep their time. Segment 0 starts the program; segment k starts when the k-th barrier, in program order, ends.start_cyclesis the segment’s start in the static schedule, which places every barrier at its lowest length. At run time the segment startsshift_cycleslater, withmin_shift_cycles <= shift_cycles <= max_shift_cycles(None: unbounded); the bound adds up the barriers before it on the same lines.opened_byis"start","wait"(a variable wait on lineline) or"answer"(a blocking wait on linkline).- Parameters:
index (int)
opened_by (str)
line (int)
start_cycles (int)
min_shift_cycles (int)
max_shift_cycles (int | None)
- index: int#
- opened_by: str#
- line: int#
- start_cycles: int#
- min_shift_cycles: int#
- max_shift_cycles: int | None#
Wire format#
The wire format of a call: what a request and an answer look like.
A request is a 24-byte header (magic 'CUQR', dispatch key, argument
length, request id, timestamp) followed by the arguments, tightly packed and
little-endian in the order of the function’s argument types; an answer is a
24-byte header (magic 'CUQS', status, result length, request id,
timestamp) followed by the results. This is the layout of the CUDA-Q Realtime
messaging protocol, declared here so cudaq-pulse needs nothing from CUDA-Q;
core/mlir/include/cudaq-pulse/Runtime/WireFormat.h declares the same for
C++.
native(library, symbol, function) wraps a host handler written in C with
the signature void handler(const void *request, void *answer, size_t
slot_bytes), the shape of a CUDA-Q Realtime host-call handler, as a Python
handler for simulation.
- cudaq_pulse.classical.wire.HEADER_BYTES = 24#
The size of a request or response header.
- cudaq_pulse.classical.wire.REQUEST_MAGIC = 1129664850#
The first word of a request header,
'CUQR'.
- cudaq_pulse.classical.wire.RESPONSE_MAGIC = 1129664851#
The first word of a response header,
'CUQS'.
- cudaq_pulse.classical.wire.decode_answer(function, data)[source]#
(status, request id, answer)of an answer from function.- Parameters:
function (ClassicalFunction[..., Any])
data (bytes)
- Return type:
tuple[int, int, Any]
- cudaq_pulse.classical.wire.decode_request(function, data, dispatch_key=None)[source]#
(request id, timestamp, arguments)of a request to function at dispatch_key (as forencode_request).- Parameters:
function (ClassicalFunction[..., Any])
data (bytes)
dispatch_key (int | None)
- Return type:
tuple[int, int, list[Any]]
- cudaq_pulse.classical.wire.encode_answer(function, answer, request_id=0, timestamp=0, status=0)[source]#
The answer of function (as a handler returns it) to one request.
- Parameters:
function (ClassicalFunction[..., Any])
answer (Any)
request_id (int)
timestamp (int)
status (int)
- Return type:
bytes
-
cudaq_pulse.classical.wire.encode_request(
)[source]#function,args,request_id=0,timestamp=0,dispatch_key=None,
A request to function with args (as a handler receives them), sent to dispatch_key: the program’s (
call.dispatch_key), by default the hash of the function’s compiled name.- Parameters:
function (ClassicalFunction[..., Any])
args (Sequence[Any])
request_id (int)
timestamp (int)
dispatch_key (int | None)
- Return type:
bytes
- cudaq_pulse.classical.wire.native(library, symbol, function, slot_bytes=1024)[source]#
A handler for function that calls the C function symbol in the shared library library with a request and an answer slot.
- Parameters:
library (str)
symbol (str)
function (ClassicalFunction[..., Any])
slot_bytes (int)
- Return type:
Any
- cudaq_pulse.classical.wire.schema(function)[source]#
The function’s handler schema: per argument and result its payload type id, size in bytes and element count, as a dispatcher function table entry declares them. A function whose list lengths come from its calls has a schema per version: pass
fn.specialize(...).- Parameters:
function (ClassicalFunction[..., Any])
- Return type:
dict[str, Any]
CUDA-Q QEC decoders#
pulse.classical also takes CUDA-Q QEC’s real-time decoding functions,
cudaq_qec.qec.enqueue_syndromes, get_corrections and
reset_decoder, with the options above (max_latency_ns is 0 unless
given for the calls that answer nothing); see the user guide.
Emulation#
Emulating a controller that calls classical services, in virtual time.
export(lowered) writes what a controller needs to run a compiled kernel:
its static schedule with each event’s segment, the segment boundaries, its calls,
and the manifest of the classical functions it calls (manifest): per
function its dispatch key, link, handler schema and latency budget, which is
what a CUDA-Q Realtime dispatcher’s function table holds.
emulate(lowered, ...) runs the program shot by shot in virtual time,
without physics: measurement outcomes come from a source, each call is sent
as a real request (wire) over a channel to a service, and the answer
comes back after the modelled transport delay plus the service’s measured
time. Its budget is what the compiled program allows: it is in time if it
arrives the link’s feedback time before it is due. A late answer, or a
decoder’s NOT_READY, takes the timeout arm of a wait with a timeout; a late
answer is recorded as late otherwise. Answers are bound to the shot as in
simulation, so variable waits get their real lengths and later segments shift
accordingly.
-
class cudaq_pulse.classical.emulation.CallTrace(
)[source]#function,submit_ns,latency_ns,budget_ns,in_time,inputs,answer,
Bases:
objectOne call in an emulated shot. Times in ns of the shot’s timeline.
budget_nsis how long aftersubmit_nsthe answer may arrive: until it is due, less the link’s feedback time.in_timeis whetherlatency_nsis within it (false for a decoder’s NOT_READY).- Parameters:
function (str)
submit_ns (float)
latency_ns (float)
budget_ns (float)
in_time (bool)
inputs (tuple[Any, ...])
answer (Any)
- function: str#
- submit_ns: float#
- latency_ns: float#
- budget_ns: float#
- in_time: bool#
- inputs: tuple[Any, ...]#
- answer: Any#
- class cudaq_pulse.classical.emulation.RealtimeChannel(library, *args, **kwargs)[source]#
Bases:
objectA channel through the CUDA-Q Realtime host library, which dispatches requests to registered GPU or host services. Not available yet: use
InProcess(withwire.nativehandlers for compiled code) orUdpChannel. The requests and answers are already in its wire format, so a channel built on it drops in here.- Parameters:
library (str)
args (Any)
kwargs (Any)
- cudaq_pulse.classical.emulation.device_call_text(lowered)[source]#
CUDA-Q kernel text that makes a compiled program’s calls as
cc.device_calloperations. Not available yet: export the program withexport(orScheduledKernel.export_to_emulator()), whose manifest holds each function’s dispatch key, payload types and link.- Parameters:
lowered (Any)
- Return type:
str
- class cudaq_pulse.classical.emulation.EmulationResult(outcomes=..., calls=..., ends_ns=..., wall_s=0.0)[source]#
Bases:
objectPer shot, the measurement outcomes (in time order) and the calls.
- Parameters:
outcomes (list[list[int]])
calls (list[list[CallTrace]])
ends_ns (list[float])
wall_s (float)
- outcomes: list[list[int]]#
- ends_ns: list[float]#
- wall_s: float = 0.0#
- property late_fraction: float#
The fraction of the answers the program waits on that came late (a decoder’s NOT_READY included). A call it sends without taking an answer, such as an enqueue of syndromes, counts in neither part, though its trace says whether it came back in time.
- property calls_per_second: float#
The calls of every shot per second of the run’s wall-clock time; infinite when no wall time was measured.
- class cudaq_pulse.classical.emulation.InProcess(functions, handlers, dispatch_keys=None)[source]#
Bases:
objectA channel to services in this process: handlers by function name, called on the decoded request. A handler named for a function whose list lengths come from its calls serves each of its versions. dispatch_keys gives the program’s key per compiled name (
emulatepasses them); a function not in it is at the hash of its name.- Parameters:
functions (Sequence[ClassicalFunction[..., Any]])
handlers (Mapping[str, Callable[..., Any]])
dispatch_keys (Mapping[str, int] | None)
- call(function, request)[source]#
Deliver request; returns the answer bytes and the service’s time in ns.
- Parameters:
function (ClassicalFunction[..., Any])
request (bytes)
- Return type:
tuple[bytes, float]
- class cudaq_pulse.classical.emulation.Transport(fixed_ns=0.0, bytes_per_ns=0.0, jitter_ns=0.0)[source]#
Bases:
objectThe delay of one direction of a link:
fixed_ns + bytes / bytes_per_nsplus a jitter drawn from an exponential with meanjitter_ns(0 for none).- Parameters:
fixed_ns (float)
bytes_per_ns (float)
jitter_ns (float)
- fixed_ns: float = 0.0#
- bytes_per_ns: float = 0.0#
- jitter_ns: float = 0.0#
- class cudaq_pulse.classical.emulation.UdpChannel(address, slot_bytes=65536, timeout_s=2.0)[source]#
Bases:
objectA channel to a service reached over UDP:
serve_udp, or any server that answers in the wire format, such as a CUDA-QX decoding server.An answer ends where its header’s result length says; whatever follows, such as the padding of a server that sends whole slots, is not part of it. The service’s time is the one
serve_udpsends after the answer, or, from a server that sends none, the round trip measured here.- Parameters:
address (tuple[str, int])
slot_bytes (int)
timeout_s (float)
- call(function, request)[source]#
Send request and wait for the answer; returns the answer bytes and the service’s time in ns (the measured round trip if the server sends none). No answer within the channel’s timeout raises an error that names the function and the address.
- Parameters:
function (ClassicalFunction[..., Any])
request (bytes)
- Return type:
tuple[bytes, float]
-
cudaq_pulse.classical.emulation.emulate(
)[source]#lowered,*,shots_count=1,channel=None,handlers=None,transport=None,outcomes=None,service_time='measured',seed=None,
Run lowered for shots_count in virtual time against classical services.
channel reaches the services (
InProcessof handlers by default, the functions’ bodies unless given). transport models each link’s delay in each direction, per link (name or id) or for all. outcomes gives the level a readout reports, from its qudit and the shot’s generator (uniform 0/1 by default); a call that takes IQ points gets them drawn at those levels from the quantum system’s dispersive readout model (IQModel). The answer’s latency is the request’s transport delay, plus the service’s time ("measured"wall-clock, or"none"), plus the answer’s transport delay. shots_count is a positive int.- Parameters:
- Return type:
- cudaq_pulse.classical.emulation.export(lowered, controller=None)#
A compiled kernel for a controller emulator: schedule, segments, calls, links and manifest, as JSON-serializable data. Times are in clock cycles of the controller, at
clock_ghz(withprogram_clock_ghzwhen that is not the program clock, as incudaq_pulse.controller); each event’ssegment_start_cyclesis the static start of its segment, which moves at run time by the lengths of the run-time waits before it on its lines. An segment’s shift adds to that of the segment it follows, the one before it unless it names another inafter. On a control system of several controllers, the part of the one controller indexes, with only its events, calls, links and functions, andcontrollerits index.- Parameters:
lowered (Any)
controller (int | None)
- Return type:
dict[str, Any]
- cudaq_pulse.classical.emulation.manifest(lowered)#
The classical functions a compiled kernel calls, for a dispatcher.
- Parameters:
lowered (Any)
- Return type:
dict[str, Any]
-
cudaq_pulse.classical.emulation.serve_udp(
)[source]#functions,handlers,host='127.0.0.1',port=0,slot_bytes=65536,dispatch_keys=None,
Serve handlers over UDP: one datagram per request and per answer, in the wire format. Returns the server thread, its address and a stop function. Each answer is followed by the service’s own time: the 4-byte tag
'CUQT'and the time in ns as 8 bytes, whichUdpChannelreads. A request goes to the function at its dispatch key (dispatch_keys by compiled name, else the hash of the name). Built-in functions that share a key, such as QEC decoders, are told apart by their payload: its length, then its first argument (the decoder id).- Parameters:
functions (Sequence[ClassicalFunction[..., Any]])
handlers (Mapping[str, Callable[[...], Any]])
host (str)
port (int)
slot_bytes (int)
dispatch_keys (Mapping[str, int] | None)
- Return type:
tuple[Thread, tuple[str, int], Callable[[], None]]
Calibration#
Estimators for calibrating while the QPU runs.
Each estimator is a plain function whose state goes in and comes back out, so the same code is the body of a classical function a kernel calls between measurements, runs between shots, and is tested on its own. Nothing is kept between calls.
t1_updateandt1_wait: a gamma posterior over the decay rate 1/T1, updated from one shot of “excite, wait, measure”, and the next wait.frequency_updateandramsey_setting: a Gaussian posterior over a qubit’s detuning, updated from one Ramsey shot, and the wait and phase of the next shot (a binary search: each shot says which side of the estimate the detuning is on).survival_probability,ramsey_probabilityandrabi_probability: the outcome probabilities of those experiments with ideal pulses, for drawing shots without simulating them (rng.random() < p).three_point_decay: the decay time ofA exp(-t / T) + Bfrom three equally spaced points.three_point_phase: the phase erroreofa - b cos(theta + e)from three equally spaced settings.golden_section_step: one step of a golden-section search for a minimum;GoldenSectionholds its state.nelder_mead_step: one step of a Nelder-Mead simplex search;NelderMeadholds its state.
The two searches are ask-and-tell: a step takes the cost measured at the point the last step asked for and returns the next point, and a flag that is true once the search has converged, for the converged pattern (see the user guide).
- class cudaq_pulse.classical.calibration.GoldenSection(lo, hi, c, d, fc, fd, tolerance)[source]#
Bases:
objectThe state of a golden-section search on [lo, hi].
canddare the interior points,fcandfdtheir costs (NaN until measured).as_floats/from_floatspack it into the 7 values of alist[float]argument.- Parameters:
lo (float)
hi (float)
c (float)
d (float)
fc (float)
fd (float)
tolerance (float)
- lo: float#
- hi: float#
- c: float#
- d: float#
- fc: float#
- fd: float#
- tolerance: float#
- classmethod start(lo, hi, tolerance)[source]#
A search for the minimum of a cost on [lo, hi], with no cost measured yet.
The interior points split the interval in the golden ratio. The search has converged once the interval is no wider than tolerance, which is in the units of lo and hi.
- Parameters:
lo (float)
hi (float)
tolerance (float)
- Return type:
- converged()[source]#
Whether the interval is no wider than
tolerance(hi - lo <= tolerance).- Return type:
bool
- as_floats()[source]#
The state as 7 floats, in the order
lo,hi,c,d,fc,fd,tolerance. A cost not measured yet is NaN.- Return type:
list[float]
- class cudaq_pulse.classical.calibration.NelderMead(simplex, costs, stage, index, trial, trial_cost, tolerance)[source]#
Bases:
objectThe state of a Nelder-Mead search in
dimdimensions.simplexholds dim + 1 vertices andcoststheir costs (NaN until measured).stagesays what the point asked for last is: a vertex of the start (index), the reflection, the expansion, the contraction, or a vertex of a shrink.trialandtrial_costkeep the reflection while its expansion or contraction is measured.as_floats/from_floatspack it into alist[float]argument ofNelderMead.size(dim)values.- Parameters:
simplex (tuple[tuple[float, ...], ...])
costs (tuple[float, ...])
stage (int)
index (int)
trial (tuple[float, ...])
trial_cost (float)
tolerance (float)
- simplex: tuple[tuple[float, ...], ...]#
- costs: tuple[float, ...]#
- stage: int#
- index: int#
- trial: tuple[float, ...]#
- trial_cost: float#
- tolerance: float#
- classmethod start(x0, step, tolerance)[source]#
A search that starts from the point x0, with no cost measured yet.
The first simplex is x0 and one vertex per coordinate, each x0 moved by step along that coordinate, so step sets the size of the first simplex. The search has converged once every vertex is within tolerance of the best in every coordinate. The first point asked for is x0.
- Parameters:
x0 (Sequence[float])
step (float)
tolerance (float)
- Return type:
- property dim: int#
The number of coordinates of a point,
len(x0)at the start.
- static size(dim)[source]#
How many floats
as_floatsgives for dim dimensions.- Parameters:
dim (int)
- Return type:
int
- next_point()[source]#
The point whose cost the search needs next. That is a vertex while the start or a shrink is measured, and otherwise the reflection, expansion or contraction being tried.
- Return type:
tuple[float, …]
- converged()[source]#
Every vertex is within
toleranceof the best, in every coordinate.- Return type:
bool
- best()[source]#
The vertex with the lowest cost so far. A vertex whose cost is not measured yet is never preferred to one that has a cost.
- Return type:
tuple[float, …]
- as_floats()[source]#
The state as
NelderMead.size(dim)floats, in this order: the dim + 1 vertices of the simplex,dimcoordinates each, one vertex after the other; their dim + 1 costs;stage,indexandtolerance; thedimcoordinates oftrial; andtrial_cost. A cost not measured yet is NaN.- Return type:
list[float]
- cudaq_pulse.classical.calibration.adaptive_t1_update(shape, rate, excited, wait, error_1to0, error_0to1)[source]#
The gamma posterior over Gamma = 1/T1 after one “excite, wait wait, measure” shot that read 1 (excited) or 0, through a readout that reads
|1>as 0 with probability error_1to0 and|0>as 1 with error_0to1.The prior is Gamma(shape k, rate theta), in the time unit of wait (ns when it is a time); the likelihood of reading 1 is
error_0to1 + (1 - error_1to0 - error_0to1) exp(-Gamma wait). The posterior’s exact mean and variance give the new gamma distribution (moment matching), as in Berritta et al.; with r = theta / (theta + wait), E[Gamma^n exp(-Gamma wait)] is k (k + 1) … (k + n - 1) r^k / (theta + wait)^n.Two outcomes have a posterior that is a gamma distribution, returned as it is. A 1 through a readout whose error_0to1 is 0 has the likelihood exp(-Gamma wait): (shape, rate + wait), for every wait. A 0 through a readout whose error_1to0 is 0 has 1 - exp(-Gamma wait), which a wait much shorter than the rate makes Gamma wait: the result tends to (shape + 1, rate) as the wait tends to 0, and is that when wait / rate rounds to 0.
The prior is returned unchanged, with no sign of it, where the shot says nothing or has no meaning: a wait of 0 (also of a 0 that such a readout cannot give then), an infinite, negative or NaN wait, a wait too long to compare with the rate, a rate or shape that is not positive, and an outcome the readout never reports. A caller cannot tell these from an update that changes nothing. The variance is kept at 1e-12 of the mean squared or more, so the shape returned is at most 1e12; the difference it is computed from keeps about 16 digits less those of the shape.
Limits: the result is not reliable where wait / rate, or a product of it with the shape or with an error probability, is in the denormal range (below about 1e-307), as for a wait of 1e-310 of the rate or a 1 read with error_1to0 = 1 and an error_0to1 of 1e-310 after a very short wait; it can then be far from the posterior, up to the shape of 1e12. An infinite or NaN shape or rate is outside the function’s domain: an infinite shape gives (nan, nan) for most shots.
- Parameters:
shape (float)
rate (float)
excited (int)
wait (float | Time)
error_1to0 (float)
error_0to1 (float)
- Return type:
tuple[float, float]
- cudaq_pulse.classical.calibration.adaptive_t1_wait(shape, rate, scale=0.51)[source]#
The next wait: scale times the estimated T1 (rate / shape). The adaptive T1 tracker uses a fixed scale of 0.51.
- Parameters:
shape (float)
rate (float)
scale (float)
- Return type:
float
- cudaq_pulse.classical.calibration.binary_search_phase(mean_hz, wait_ns)[source]#
The phase of a Ramsey shot (as for
frequency_update: it reports 1 with probability (1 - cos(2 pi D t + phase)) / 2) that puts the estimate mean_hz on the fringe’s steepest point, so that a detuning above it makes 1 more likely: the Ramsey of detuning 1 / (4 t) + mean. The wait is a time, or a number of ns.- Parameters:
mean_hz (float)
wait_ns (float | Time)
- Return type:
float
-
cudaq_pulse.classical.calibration.binary_search_update(
)[source]#mean_hz,sigma_hz,outcome,wait_ns,offset=-0.02,contrast=0.6,coherence_ns=10000.0,
The Gaussian posterior over a detuning after one shot of the frequency binary search: a Ramsey shot of wait wait_ns set (by its phase,
binary_search_phase) to the fringe’s steepest point at the estimate, reading outcome +1 or -1.The likelihood of +1 is
1/2 + (offset + contrast exp(-t / T) sin(2 pi (D - mean) t)) / 2with T = coherence_ns, and the posterior is the Gaussian of its exact moments (Berritta et al. 2025); a +1 moves the estimate up. The wait and T are times, or numbers of ns.
- cudaq_pulse.classical.calibration.binary_search_wait(sigma_hz, coherence_ns=10000.0)[source]#
The wait (ns) of the next binary-search shot, from the posterior width:
(sqrt(16 pi^2 s^2 + 1/T^2) - 1/T) / (8 pi^2 s^2), for T a time or a number of ns.- Parameters:
sigma_hz (float)
coherence_ns (float | Time)
- Return type:
float
- cudaq_pulse.classical.calibration.count_ones(bits)[source]#
How many of bits are 1. Measurement results arrive bit-packed, so a controller counts them a 32-bit word at a time.
- Parameters:
bits (Sequence[int])
- Return type:
int
- cudaq_pulse.classical.calibration.decay_time(p0, p1, p3, spacing, shots_count)[source]#
The analytical decay estimator: the decay time T of
A exp(-t / T) + Cfrom its values at t0, t0 + spacing and t0 + 3 spacing, whatever A and C are (Marciniak et al., Eq. 1).With c = (p3 - p0) / (p1 - p0) = x^2 + x + 1 and x = exp(-spacing / T), x = sqrt(c - 3/4) - 1/2. Returns T, its standard deviation from the binomial noise of shots_count shots per point (error propagation), and whether an estimate was formed (1 < c < 3, and not within rounding of 3). T is in the unit of spacing: ns when it is a time.
- Parameters:
p0 (float)
p1 (float)
p3 (float)
spacing (float | Time)
shots_count (int)
- Return type:
tuple[float, float, bool]
- cudaq_pulse.classical.calibration.frequency_update(mean_hz, sigma_hz, outcome, wait_ns, phase)[source]#
The Gaussian posterior over a detuning after one Ramsey shot.
The shot waits wait_ns (a time, or a number of ns) between two pi/2 pulses, the second advanced by phase, and reports 1 with probability (1 - cos(2 pi D t + phase)) / 2 for detuning D. The posterior is the Gaussian with the exact mean and variance of prior times likelihood.
- Parameters:
mean_hz (float)
sigma_hz (float)
outcome (int)
wait_ns (float | Time)
phase (float)
- Return type:
tuple[float, float]
- cudaq_pulse.classical.calibration.golden_section_step(state, cost)[source]#
Tell the search cost at
state.next_point(); returns the new state, the point to measure next and whether the search has converged.- Parameters:
state (GoldenSection)
cost (float)
- Return type:
tuple[GoldenSection, float, bool]
- cudaq_pulse.classical.calibration.nelder_mead_step(state, cost)[source]#
Tell the search cost at
state.next_point(); returns the new state, the point to measure next and whether the search has converged.Standard coefficients: reflection 1, expansion 2, contraction 1/2, shrink 1/2.
- Parameters:
state (NelderMead)
cost (float)
- Return type:
tuple[NelderMead, tuple[float, …], bool]
- cudaq_pulse.classical.calibration.pi_train_amplitude(amplitude, theta, turns)[source]#
The corrected amplitude of a pulse from the sparse phase estimate theta of a train of its pulses that rotates by turns (odd) times pi when the amplitude is right, sampled at amplitude scales 1 - 1/(2 turns), 1 and 1 + 1/(2 turns) and read out as P(1).
P(1) = (1 - cos R) / 2 for the train’s rotation R, so theta = R + pi (mod 2 pi) and is 0 when R = turns pi. A pi pulse makes a train of turns pulses; a pi/2 pulse a train of 2 turns (Marciniak et al., Eq. 4, applying the pi/2 pulse twice).
- Parameters:
amplitude (float)
theta (float)
turns (int)
- Return type:
float
- cudaq_pulse.classical.calibration.rabi_probability(angle, amplitude_scale)[source]#
P(1) after a resonant rotation meant to be angle (rad), on a qudit whose drive is amplitude_scale times the calibrated one: sin(scale x angle / 2) ** 2.
- Parameters:
angle (float)
amplitude_scale (float)
- Return type:
float
- cudaq_pulse.classical.calibration.ramsey_detuning(mean_hz, theta, wait_ns)[source]#
The detuning from the sparse phase estimate theta of Ramsey shots of wait wait_ns at phases phi0 - pi/2, phi0 and phi0 + pi/2, with phi0 = -2 pi mean t (the convention of
frequency_update: P(1) = (1 - cos(2 pi D t + phase)) / 2): D = mean + (theta - pi) / (2 pi t), the phase taken in (-pi, pi]. The wait is a time, or a number of ns.- Parameters:
mean_hz (float)
theta (float)
wait_ns (float | Time)
- Return type:
float
- cudaq_pulse.classical.calibration.ramsey_probability(wait_ns, phase, detuning_hz)[source]#
P(1) of a Ramsey shot that waits wait_ns (a time, or a number of ns) between two pi/2 pulses, the second advanced by phase, on a qudit detuning_hz off the drive: (1 - cos(2 pi D t + phase)) / 2, the likelihood
frequency_updateuses. Ideal pulses, no decay.- Parameters:
wait_ns (float | Time)
phase (float)
detuning_hz (float)
- Return type:
float
- cudaq_pulse.classical.calibration.ramsey_setting(mean_hz, sigma_hz, scale=0.1, max_wait_ns=None)[source]#
The wait (ns) and phase of the next Ramsey shot.
The phase puts the estimated detuning on the fringe’s steepest point, so the outcome says which side of the estimate the detuning is on. The wait is scale / sigma. Longer waits resolve the detuning more finely but wash out the fringe over the prior: 0.155 narrows the posterior most per shot (about 20%), but then one unlucky early shot can leave it confidently wrong; the default 0.1 narrows it by about 14% per shot and stays on the detuning in all but a few runs in a thousand. max_wait_ns caps the wait (a fraction of T2*, past which the fringe is gone; a time, or a number of ns); once it binds, every shot still narrows the posterior, more slowly.
- Parameters:
mean_hz (float)
sigma_hz (float)
scale (float)
max_wait_ns (float | Time | None)
- Return type:
tuple[float, float]
- cudaq_pulse.classical.calibration.sparse_phase(p_minus, p_zero, p_plus, shots_count)[source]#
The sparse phase estimator: the phase theta0 of
A cos(theta) + Cfrom its values at theta0 - pi/2, theta0 and theta0 + pi/2, whatever A and C are: atan2(p- - p+, 2 (p0 - (p- + p+) / 2)) (Marciniak et al., Eq. 3; theta0 + pi for A < 0). Returns it and its standard deviation from the binomial noise of shots_count shots per point.- Parameters:
p_minus (float)
p_zero (float)
p_plus (float)
shots_count (int)
- Return type:
tuple[float, float]
- cudaq_pulse.classical.calibration.survival_probability(wait_ns, t1_us)[source]#
P(still excited) after exciting a qudit of t1_us and waiting wait_ns (a time, or a number of ns): exp(-wait / T1), the likelihood
t1_updateuses. A T1 of 0 is no decay.- Parameters:
wait_ns (float | Time)
t1_us (float)
- Return type:
float
- cudaq_pulse.classical.calibration.t1_update(alpha, beta, survived, wait_ns)[source]#
The posterior Gamma(alpha, beta) over Gamma = 1/T1 (per ns) after one shot that excited the qubit, waited wait_ns (a time, or a number of ns) and found it still excited (survived) or not.
Survival multiplies the prior by exp(-Gamma t), which keeps it a gamma distribution: beta grows by t. A decay multiplies it by 1 - exp(-Gamma t); the posterior is then the difference of two gamma distributions, and the result is the gamma distribution with its mean and variance.
- Parameters:
alpha (float)
beta (float)
survived (bool)
wait_ns (float | Time)
- Return type:
tuple[float, float]
- cudaq_pulse.classical.calibration.t1_wait(alpha, beta, scale=1.0)[source]#
The next wait: scale times the estimated T1 (beta / alpha, in the units of beta).
- Parameters:
alpha (float)
beta (float)
scale (float)
- Return type:
float
- cudaq_pulse.classical.calibration.three_point_decay(p0, p1, p2, spacing)[source]#
T in
p(t) = A exp(-t / T) + Bfrom p at t, t + spacing, t + 2 spacing.The ratio (p1 - p2) / (p0 - p1) is exp(-spacing / T) whatever A and B are. Points that do not decay give
inf. T is in the unit of spacing: ns when it is a time.- Parameters:
p0 (float)
p1 (float)
p2 (float)
spacing (float | Time)
- Return type:
float
- cudaq_pulse.classical.calibration.three_point_phase(p_minus, p_zero, p_plus, theta, delta)[source]#
The phase error e in
p = a - b cos(theta + e), from p measured at theta - delta, theta and theta + delta (radians), whatever a and b are.p+ - p- = 2 b sin(delta) sin(theta + e) and p+ + p- - 2 p0 = 2 b (1 - cos(delta)) cos(theta + e).
- Parameters:
p_minus (float)
p_zero (float)
p_plus (float)
theta (float)
delta (float)
- Return type:
float
Loops between shots#
Closed loops between shots: the parameters a program runs with, and the log of what was estimated.
A loop compiles its kernel once and runs it with the store’s current
values each iteration, without compiling again. Amplitudes, phases and
frequencies can be float parameters of the kernel, passed each iteration. A
quantity that shapes the timeline, such as a wait, is read at run time
instead: store.reader("wait_ns") is a classical function that answers
with the store’s current value (on hardware, a read of a controller
register), and a variable wait takes its length from the answer:
store = ParameterStore(amplitude=0.157, wait_ns=2000.0)
read_wait = store.reader("wait_ns", bounds=(0.0, 40000.0))
@pulse.kernel
def probe(q, amplitude: float):
...
wait(d, read_wait.submit().result(), bounds=(0, 80000))
log = EstimateLog()
compiled = pulse.compile(probe, quantum_system=qs)
for i in range(10_000):
scheduled = compiled.lower(q, store["amplitude"])
outcome = ... # run or simulate it
estimate = update(...) # the estimator, outside the kernel
store.set("amplitude", estimate, iteration=i)
log.record(i, "amplitude", estimate, uncertainty=..., truth=...)
The estimators of cudaq_pulse.classical.calibration serve both inside
kernels (as the bodies of classical functions) and in such loops.
-
class cudaq_pulse.classical.loop.Estimate(
)[source]#iteration,name,value,uncertainty=None,truth=None,time_s=None,
Bases:
objectOne estimate of a quantity, with what was true if known.
- Parameters:
iteration (int)
name (str)
value (float)
uncertainty (float | None)
truth (float | None)
time_s (float | None)
- iteration: int#
- name: str#
- value: float#
- uncertainty: float | None = None#
- truth: float | None = None#
- time_s: float | None = None#
- class cudaq_pulse.classical.loop.EstimateLog[source]#
Bases:
objectEvery estimate a loop made, by quantity.
-
record(
)[source]#iteration,name,value,*,uncertainty=None,truth=None,time_s=None,
Add an
Estimateof name made at iteration, with its uncertainty, truth and time_s if given.- Parameters:
iteration (int)
name (str)
value (float)
uncertainty (float | None)
truth (float | None)
time_s (float | None)
- Return type:
None
- series(name)[source]#
The estimates of name, in the order they were recorded.
- Parameters:
name (str)
- Return type:
list[Estimate]
- tracking_error(name)[source]#
The root-mean-square of estimate minus truth over the estimates of name that have a truth.
- Parameters:
name (str)
- Return type:
float
- to_json()[source]#
The log as a JSON array with an object of fields per estimate, which
from_jsonreads back.- Return type:
str
-
record(
- class cudaq_pulse.classical.loop.ParameterStore(values=None, /, **named)[source]#
Bases:
objectNamed calibration parameters, versioned on every change.
store[name]reads one;values(*names)reads several in order, for a kernel’s float arguments;setandupdatechange them and bumpversion;historylists every change.- Parameters:
values (Mapping[str, float] | None)
named (float)
- values(*names)[source]#
The current values of names, in that order, as a kernel’s float arguments take them. A name the store does not have raises
NotFoundError.- Parameters:
names (str)
- Return type:
tuple[float, …]
- set(name, value, *, iteration=None)[source]#
Set name to value, bump
versionand add the change, with the loop iteration that made it, tohistory. A non-finite value raisesInvalidValueErrorand changes nothing.- Parameters:
name (str)
value (float)
iteration (int | None)
- Return type:
None
- update(values, *, iteration=None)[source]#
seteach of values in turn, all with the same iteration; each bumpsversion. A non-finite value raisesInvalidValueError, and the values before it stay set.- Parameters:
values (Mapping[str, float])
iteration (int | None)
- Return type:
None
-
reader(
)[source]#name,*,link=0,max_latency_ns=0.0,bounds=None,
A classical function of no arguments that answers with the current value of name (in clock cycles if it is a wait’s length), so a program compiled once reads each iteration’s value at run time. With bounds the value is clamped to them. On hardware it is a read of a controller register named like the function,
read_<name>.- Parameters:
name (str)
link (int | str)
max_latency_ns (float | Time)
bounds (tuple[float, float] | None)
- Return type:
ClassicalFunction[…, Any]
- class cudaq_pulse.classical.loop.Update(name, value, version, iteration)[source]#
Bases:
objectOne change of a parameter: its new value, the store’s version after it, and the loop iteration that made it.
- Parameters:
name (str)
value (float)
version (int)
iteration (int | None)
- name: str#
- value: float#
- version: int#
- iteration: int | None#