Source code for cudaq_pulse._timing

# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""``ScheduledKernel.timing``: where a compiled program's timing is exact and
where it can move while it runs. One row per kernel line, read from the
scheduled module op by op, so the work grows with the program's operations
and not with how often they run. Loaded with the first report read."""

from __future__ import annotations

import os
from dataclasses import dataclass
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from .compiler import ScheduledKernel

__all__ = ["ReservedAnswer", "Timing", "TimingBreak"]


[docs] @dataclass(frozen=True) class TimingBreak: """One point where a program's timing can move while it runs, from ``ScheduledKernel.timing``: a kernel line, however often it runs. Where no kernel line is recorded (an answer waited for as long as it takes, a program read from MLIR text) it is every such point of one function that holds the same lines, and ``trips`` counts them all. ``cause`` is ``"wait"``, a wait whose length is an answer of a classical call, on line ``wait_line`` with ``bounds_cycles`` its lowest and highest length (``None``: no highest); or ``"answer"``, an answer waited for as long as it takes. ``function`` is the classical function whose answer decides it, as the kernel calls it (empty for a length taken from a value carried around a loop). ``source_file`` and ``source_line`` are the kernel line (``None`` and 0 where the program does not know it: one read from MLIR text, or an answer of a function declared ``latency_mode="blocking"``); every other ``line`` here is a control line, numbered as ``ScheduledEvent.line`` numbers them. The schedule places the point at its lowest length, first at cycle ``first_cycles``, in the schedule of the call's own values where the program is a call that binds wait lengths. Each time it runs, what follows on ``held_lines`` starts later by a number of cycles within ``shift_cycles`` (the upper end ``None``: no limit); it runs ``trips`` times. The held lines wait for the point and move together, so they stay exact relative to each other. ``free_lines`` are the lines that have a drive, readout or wait after the point in the program, or in a loop around it, and are not held: they keep their scheduled time, whatever the point takes. Lines are numbered as ``ScheduledEvent.line`` numbers them. """ cause: str source_file: str | None source_line: int function: str wait_line: int | None bounds_cycles: tuple[int, int | None] | None shift_cycles: tuple[int, int | None] held_lines: tuple[int, ...] free_lines: tuple[int, ...] trips: int first_cycles: int
[docs] @dataclass(frozen=True) class ReservedAnswer: """The time a program's schedule reserves for the answers of one classical function, from ``ScheduledKernel.timing.reserved``: ``calls`` executions, each with at most ``cycles`` from the start of its submission to when its answer is due. Reserved time is part of the schedule: nothing moves when an answer comes earlier. How long each execution holds back a pulse is in ``classical_report()``.""" function: str calls: int cycles: int
[docs] class Timing: """Where a compiled program's timing is exact and where it can move (``ScheduledKernel.timing``); ``print`` it. ``exact`` is whether no point of the program can move its timing; ``breaks`` are the points that can, one ``TimingBreak`` per kernel line in program order (those without a recorded kernel line: one per function and the lines it holds); ``lines`` gives each of the program's lines as (role, qudit), in the order ``ScheduledEvent.line`` numbers them, whether or not the program calls a classical function; ``reserved`` is what the schedule keeps for answers, one ``ReservedAnswer`` per classical function the program calls, in the order of their first calls. """ __slots__ = ("_ends", "_moves", "_program", "breaks", "lines", "reserved") def __init__( self, program: ScheduledKernel, lines: tuple[tuple[str, int], ...], breaks: tuple[TimingBreak, ...], reserved: tuple[ReservedAnswer, ...] = (), ends: tuple[int, ...] = (), moves: tuple[tuple[int, ...], ...] = (), ) -> None: self._program = program # Each line's latest end as scheduled (-1: none), and per break the # lines that end later when it takes longer. self._ends = ends self._moves = moves self.lines = lines self.breaks = breaks self.reserved = reserved @property def exact(self) -> bool: """Whether the program's timing cannot move while it runs.""" return not self.breaks @property def latest_end_cycles(self) -> int | None: """The latest cycle the program can end at: the latest any line can, each ending later by what the points that hold it back add, and never before the program's length as scheduled; ``None`` when a point has no limit.""" added = [0] * len(self._ends) for point, moved in zip(self.breaks, self._moves, strict=True): most = point.shift_cycles[1] if most is None: return None for line in moved: added[line] += most * point.trips program = self._program latest = round(float(program.duration) * program.quantum_system.clock_ghz) # A line nothing is scheduled on ends at -1 and nothing moves it. for end, more in zip(self._ends, added, strict=True): latest = max(latest, end + more) return latest def _name(self, line: int | None) -> str: if line is None or not 0 <= line < len(self.lines): return "a line" role, qudit = self.lines[line] return f"q{qudit}.{role}" def _names(self, lines: tuple[int, ...]) -> str: return ", ".join(self._name(line) for line in lines) def __repr__(self) -> str: if self.exact: return "<Timing exact>" return f"<Timing elastic: {_count(len(self.breaks))}>" def __str__(self) -> str: out: list[str] = [] if self.exact: out.append("exact: no point where timing can move") else: first = min(point.first_cycles for point in self.breaks) points = "1 point" if len(self.breaks) == 1 else f"{len(self.breaks)} points" out.append(f"elastic: timing can move at {points}; exact up to cycle {first}") for point in self.breaks: where = "(no kernel line)" if point.source_file is not None: where = f"{os.path.basename(point.source_file)}:{point.source_line}" source = f"an answer of {point.function}" if point.function else "an answer" if point.cause == "wait": assert point.bounds_cycles is not None lowest, highest = point.bounds_cycles within = f"{lowest} cycles or more" if highest is not None: within = f"{lowest} to {highest} cycles" out.append( f" {where} wait on {self._name(point.wait_line)}, its length {source} " f"({within})" ) else: out.append(f" {where} {source}, waited for as long as it takes") least, most = point.shift_cycles trips = point.trips later = "what follows starts later by any number of cycles (no upper bound)" if most is not None: later = f"what follows starts {least} to {most} cycles later" if trips > 1: later += f", {least * trips} to {most * trips} in all" if trips > 1: later = f"{trips} times: {later}" out.append(f" {later}") out.append(f" held back, moving together: {self._names(point.held_lines) or '-'}") if point.free_lines: out.append( f" not held, keeping their scheduled time: {self._names(point.free_lines)}" ) if not self.exact: end = self.latest_end_cycles out.append("latest end: none" if end is None else f"latest end: cycle {end}") if self.reserved: out.append("reserved for answers, part of the schedule:") for row in self.reserved: times = f" x {row.calls}" if row.calls > 1 else "" out.append(f" {row.function}{times}: {row.cycles} cycles from submit to answer") return "\n".join(out)
def _count(breaks: int) -> str: return "1 break" if breaks == 1 else f"{breaks} breaks" def _sites(program: ScheduledKernel) -> dict[int, tuple[str, int]]: """The kernel line of each site index of *program*, from the table its compile kept with the routes of its calls (a program read from a pickle has it beside them).""" called = program.classical if not called: return {} table = called.__dict__.get("break_sites") if table is None: table = getattr(called.__dict__.get("routes"), "sites", None) if not table: return {} return {index: place for place, index in table.items()} def report(program: ScheduledKernel) -> Timing: """``ScheduledKernel.timing`` of *program*.""" # A call that binds wait lengths is read in its own schedule, as its # duration and its events are. module = program._concrete() if program.rescheduled or program.carriers else program._module with program._lock: lines, found, calls = module.timing_breaks() sites = _sites(program) called = program.classical or () names = {getattr(f, "name", None): getattr(f, "base_name", None) for f in called} breaks: list[TimingBreak] = [] moves: list[tuple[int, ...]] = [] for kind, site, where, symbol, lowest, highest, trips, start, held, free, moved in found: file, line = sites.get(site, (None, 0)) if not line: file = None top = None if highest < 0 else highest wait = kind == "wait" breaks.append( TimingBreak( cause=kind, source_file=file, source_line=line if file is not None else 0, function=names.get(symbol) or symbol, wait_line=where if wait and where >= 0 else None, bounds_cycles=(lowest, top) if wait else None, shift_cycles=(0, None if top is None or not wait else top - lowest), held_lines=tuple(held), free_lines=tuple(free), trips=trips, first_cycles=start, ) ) moves.append(tuple(moved)) # The versions of one function are one row. rows: dict[str, list[int]] = {} for symbol, count, cycles in calls: row = rows.setdefault(names.get(symbol) or symbol, [0, 0]) row[0] += count row[1] = max(row[1], cycles) return Timing( program, tuple((role, qudit) for role, qudit, _ in lines), tuple(breaks), tuple( ReservedAnswer(function, count, cycles) for function, (count, cycles) in rows.items() ), tuple(end for _, _, end in lines), tuple(moves), )