qtiming 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- qtiming/__init__.py +0 -0
- qtiming/bench/__init__.py +327 -0
- qtiming/bench/diff.py +230 -0
- qtiming/bench/report.py +161 -0
- qtiming/bench/truth.py +88 -0
- qtiming/cli/__init__.py +0 -0
- qtiming/cli/cmd_evidence.py +35 -0
- qtiming/cli/main.py +398 -0
- qtiming/contract/__init__.py +0 -0
- qtiming/contract/compat.py +49 -0
- qtiming/contract/instances/README.md +30 -0
- qtiming/contract/instances/artiq.toml +45 -0
- qtiming/contract/instances/ibm_heron.toml +62 -0
- qtiming/contract/instances/ibm_heron_snapshot.json +22 -0
- qtiming/contract/instances/q1.toml +88 -0
- qtiming/contract/instances/qua.toml +65 -0
- qtiming/contract/loader.py +355 -0
- qtiming/contract/model.py +123 -0
- qtiming/contract/schema.py +106 -0
- qtiming/contract/target_import.py +46 -0
- qtiming/core/__init__.py +0 -0
- qtiming/core/ast.py +140 -0
- qtiming/core/errors.py +36 -0
- qtiming/core/ids.py +34 -0
- qtiming/core/labels.py +121 -0
- qtiming/core/provenance.py +77 -0
- qtiming/core/time.py +96 -0
- qtiming/dispatch/__init__.py +22 -0
- qtiming/dispatch/artiq.py +70 -0
- qtiming/dispatch/ibm.py +83 -0
- qtiming/dispatch/q1.py +102 -0
- qtiming/dispatch/qua.py +88 -0
- qtiming/elab/__init__.py +360 -0
- qtiming/evidence/__init__.py +15 -0
- qtiming/evidence/ingest.py +235 -0
- qtiming/exec/__init__.py +0 -0
- qtiming/exec/artiq.py +100 -0
- qtiming/exec/engine.py +235 -0
- qtiming/exec/explore.py +43 -0
- qtiming/exec/ibm.py +117 -0
- qtiming/exec/oracle.py +88 -0
- qtiming/exec/q1.py +95 -0
- qtiming/exec/qua.py +95 -0
- qtiming/frontend/__init__.py +40 -0
- qtiming/frontend/_shared.py +149 -0
- qtiming/frontend/annotations.py +81 -0
- qtiming/frontend/lint.py +116 -0
- qtiming/frontend/payload.py +113 -0
- qtiming/frontend/program.py +51 -0
- qtiming/frontend/qasm3_fe.py +341 -0
- qtiming/frontend/qiskit_expr.py +89 -0
- qtiming/frontend/qiskit_fe.py +220 -0
- qtiming/frontend/serialise.py +63 -0
- qtiming/frontend/stretch.py +71 -0
- qtiming/graph/__init__.py +0 -0
- qtiming/graph/builder.py +245 -0
- qtiming/graph/export.py +25 -0
- qtiming/graph/invariants.py +67 -0
- qtiming/graph/lteg.py +153 -0
- qtiming/graph/window.py +120 -0
- qtiming/oblig/__init__.py +0 -0
- qtiming/oblig/generate.py +145 -0
- qtiming/oblig/model.py +76 -0
- qtiming/py.typed +0 -0
- qtiming/qiskit_pass/__init__.py +7 -0
- qtiming/qiskit_pass/_common.py +21 -0
- qtiming/qiskit_pass/equalize.py +171 -0
- qtiming/qiskit_pass/plugin.py +23 -0
- qtiming/qiskit_pass/strip.py +42 -0
- qtiming/qiskit_pass/timing_check.py +40 -0
- qtiming/repair/__init__.py +0 -0
- qtiming/repair/suggest.py +146 -0
- qtiming/solve/__init__.py +0 -0
- qtiming/solve/concrete.py +148 -0
- qtiming/solve/dispatcher.py +55 -0
- qtiming/solve/interval.py +185 -0
- qtiming/solve/smt.py +167 -0
- qtiming/solve/smt_o5.py +1 -0
- qtiming/solve/synth/__init__.py +0 -0
- qtiming/solve/synth/bruteforce_dc.py +156 -0
- qtiming/solve/synth/model.py +59 -0
- qtiming/solve/synth/relax.py +93 -0
- qtiming/solve/synth/rigid.py +33 -0
- qtiming/solve/synth/sc.py +55 -0
- qtiming/solve/synth/stn.py +74 -0
- qtiming/solve/synth/stnu_dc.py +93 -0
- qtiming/verdict/__init__.py +0 -0
- qtiming/verdict/minimise.py +45 -0
- qtiming/verdict/model.py +107 -0
- qtiming/verdict/render.py +72 -0
- qtiming/verdict/render_html.py +80 -0
- qtiming/verdict/render_json.py +12 -0
- qtiming/verdict/render_sarif.py +104 -0
- qtiming/verdict/replay.py +77 -0
- qtiming/verdict/run.py +174 -0
- qtiming/verdict/rus.py +53 -0
- qtiming-0.1.0.dist-info/METADATA +262 -0
- qtiming-0.1.0.dist-info/RECORD +102 -0
- qtiming-0.1.0.dist-info/WHEEL +4 -0
- qtiming-0.1.0.dist-info/entry_points.txt +6 -0
- qtiming-0.1.0.dist-info/licenses/LICENSE +177 -0
- qtiming-0.1.0.dist-info/licenses/NOTICE +8 -0
qtiming/exec/artiq.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""ARTIQ personality (exposed cursor + CPU clock). Spec: docs/personality-spec/artiq.md.
|
|
2
|
+
|
|
3
|
+
Written separately from the graph builder and the symbolic O5 encoding on purpose: all three are
|
|
4
|
+
checked against the same golden traces.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from fractions import Fraction
|
|
10
|
+
|
|
11
|
+
from qtiming.core.ast import Barrier, Delay, Gate, If, Measure
|
|
12
|
+
from qtiming.core.errors import QtError
|
|
13
|
+
|
|
14
|
+
from .engine import Engine, SilentDrop
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ArtiqExec(Engine):
|
|
18
|
+
personality = "artiq"
|
|
19
|
+
|
|
20
|
+
def start(self) -> None:
|
|
21
|
+
c = self.contract
|
|
22
|
+
self.lanes = int(c.cap("lanes", 8)) # type: ignore[call-overload]
|
|
23
|
+
self.coarse = int(c.cap("coarse_mu", 8)) # type: ignore[call-overload]
|
|
24
|
+
self.cost = Fraction(c.cost("cpu_issue"))
|
|
25
|
+
self.cursor = Fraction(0)
|
|
26
|
+
self.cpu = Fraction(0)
|
|
27
|
+
self.top: list[Fraction | None] = [None] * self.lanes
|
|
28
|
+
self.cur = 0
|
|
29
|
+
self.by_slot: dict[tuple[str, int], Fraction] = {}
|
|
30
|
+
self.busy_until: dict[str, Fraction] = {}
|
|
31
|
+
|
|
32
|
+
def gate(self, s: Gate) -> None:
|
|
33
|
+
lead = self.contract.commit_lead
|
|
34
|
+
if lead is None:
|
|
35
|
+
raise QtError(
|
|
36
|
+
"E-EXEC-PARAM",
|
|
37
|
+
"ARTIQ commit_lead is unspecified; the executor will not guess it",
|
|
38
|
+
s.loc,
|
|
39
|
+
hint="pass --assume timeline.commit_lead=<ns>",
|
|
40
|
+
)
|
|
41
|
+
self.cpu += self.cost
|
|
42
|
+
issue, t = self.cpu, self.cursor
|
|
43
|
+
self.rec(s.nid, "issue", issue)
|
|
44
|
+
self.rec(s.nid, "commit", t)
|
|
45
|
+
slack = t - issue
|
|
46
|
+
if slack < lead:
|
|
47
|
+
self.violate("underflow", s.nid, issue, lead - slack, "RTIO event stamped too late")
|
|
48
|
+
self.halt()
|
|
49
|
+
return
|
|
50
|
+
ch = "q" + "_".join(map(str, s.qubits))
|
|
51
|
+
self._commit(s.nid, ch, t, s.dur, issue)
|
|
52
|
+
self.cursor += s.dur
|
|
53
|
+
|
|
54
|
+
def _commit(self, nid: int, ch: str, t: Fraction, busy: int, issue: Fraction) -> None:
|
|
55
|
+
coarse, fine = divmod(int(t), self.coarse)
|
|
56
|
+
now_c = int(issue) // self.coarse
|
|
57
|
+
for step in range(self.lanes):
|
|
58
|
+
lane = (self.cur + step) % self.lanes
|
|
59
|
+
top = self.top[lane]
|
|
60
|
+
if top is None or top <= now_c or coarse > top:
|
|
61
|
+
self.top[lane] = Fraction(coarse)
|
|
62
|
+
self.cur = lane
|
|
63
|
+
break
|
|
64
|
+
else:
|
|
65
|
+
self.drops.append(SilentDrop("sequence", nid, t, ch))
|
|
66
|
+
return
|
|
67
|
+
if self.by_slot.get((ch, coarse), Fraction(fine)) != fine:
|
|
68
|
+
self.drops.append(SilentDrop("collision", nid, t, ch))
|
|
69
|
+
return
|
|
70
|
+
if t < self.busy_until.get(ch, Fraction(-1)):
|
|
71
|
+
self.drops.append(SilentDrop("busy", nid, t, ch))
|
|
72
|
+
return
|
|
73
|
+
self.by_slot[(ch, coarse)] = Fraction(fine)
|
|
74
|
+
self.busy_until[ch] = t + busy
|
|
75
|
+
self.rec(nid, "emit", t, ch, "event")
|
|
76
|
+
|
|
77
|
+
def delay(self, s: Delay) -> None:
|
|
78
|
+
self.cpu += self.cost
|
|
79
|
+
self.cursor += s.dur
|
|
80
|
+
self.rec(s.nid, "end", self.cursor)
|
|
81
|
+
|
|
82
|
+
def barrier(self, s: Barrier) -> None:
|
|
83
|
+
return
|
|
84
|
+
|
|
85
|
+
def measure(self, s: Measure) -> None:
|
|
86
|
+
dur = self.contract.duration("measure")
|
|
87
|
+
self.rec(s.nid, "start", self.cursor)
|
|
88
|
+
self.cursor += dur
|
|
89
|
+
self.rec(s.nid, "end", self.cursor)
|
|
90
|
+
prop = self.record_outcome(s)
|
|
91
|
+
theta = self.draw("input", "cpu", s.tier, s.nid)
|
|
92
|
+
self.cpu = max(self.cpu + self.cost, self.cursor + theta) # CPU blocks for the data
|
|
93
|
+
self.valid[prop] = self.cpu
|
|
94
|
+
self.rec(s.nid, "valid", self.cpu)
|
|
95
|
+
|
|
96
|
+
def if_(self, s: If) -> None:
|
|
97
|
+
self.cpu += self.cost
|
|
98
|
+
arm = s.then_ if self.cond_value(s.cond) else s.else_
|
|
99
|
+
if arm is not None:
|
|
100
|
+
self.exec_stmt(arm)
|
qtiming/exec/engine.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"""Reference executor core: the deterministic interpreter of an ELABORATED TQ program.
|
|
2
|
+
|
|
3
|
+
Independent second implementation of each personality's dispatch spec (plan principle 9): it
|
|
4
|
+
imports only `core` and the loaded Contract, never graph/solver/elab code. Time is `Fraction` dt.
|
|
5
|
+
Nothing quantum is simulated; outcomes come from the oracle.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from fractions import Fraction
|
|
12
|
+
|
|
13
|
+
from qtiming.contract.model import Contract
|
|
14
|
+
from qtiming.core.ast import (
|
|
15
|
+
Assign,
|
|
16
|
+
Barrier,
|
|
17
|
+
Box,
|
|
18
|
+
Call,
|
|
19
|
+
Delay,
|
|
20
|
+
For,
|
|
21
|
+
Gate,
|
|
22
|
+
If,
|
|
23
|
+
Measure,
|
|
24
|
+
Reset,
|
|
25
|
+
Seq,
|
|
26
|
+
Stmt,
|
|
27
|
+
Switch,
|
|
28
|
+
While,
|
|
29
|
+
Within,
|
|
30
|
+
)
|
|
31
|
+
from qtiming.core.errors import QtError
|
|
32
|
+
from qtiming.core.ids import lat_occurrence
|
|
33
|
+
from qtiming.core.labels import EBin, EBit, EUn, Expr, evaluate
|
|
34
|
+
from qtiming.core.time import Interval
|
|
35
|
+
|
|
36
|
+
from .oracle import Oracle
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True, slots=True)
|
|
40
|
+
class Violation:
|
|
41
|
+
# underflow, underflow-halt, stale-read, stall, deadline, gap, capacity, grid, sync-spread
|
|
42
|
+
kind: str
|
|
43
|
+
nid: int
|
|
44
|
+
t: Fraction
|
|
45
|
+
shortfall: Fraction | None
|
|
46
|
+
detail: str
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True, slots=True)
|
|
50
|
+
class SilentDrop:
|
|
51
|
+
kind: str # sequence, collision, busy
|
|
52
|
+
nid: int
|
|
53
|
+
t: Fraction
|
|
54
|
+
channel: str
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass(frozen=True, slots=True)
|
|
58
|
+
class TraceEvent:
|
|
59
|
+
t: Fraction
|
|
60
|
+
resource: str
|
|
61
|
+
op: str
|
|
62
|
+
nid: int
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True, slots=True)
|
|
66
|
+
class ExecResult:
|
|
67
|
+
trace: tuple[TraceEvent, ...]
|
|
68
|
+
violations: tuple[Violation, ...]
|
|
69
|
+
drops: tuple[SilentDrop, ...]
|
|
70
|
+
times: dict[tuple[int, str], Fraction] # (nid, tag) -> time, for replay comparison
|
|
71
|
+
halted: bool
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def props_of(e: Expr) -> list[str]:
|
|
75
|
+
if isinstance(e, EBit):
|
|
76
|
+
return [e.prop]
|
|
77
|
+
if isinstance(e, EUn):
|
|
78
|
+
return props_of(e.a)
|
|
79
|
+
if isinstance(e, EBin):
|
|
80
|
+
return props_of(e.a) + props_of(e.b)
|
|
81
|
+
return []
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def touched(s: Stmt) -> set[int]:
|
|
85
|
+
"""Qubits touched by a statement (static)."""
|
|
86
|
+
if isinstance(s, (Gate, Delay, Barrier)):
|
|
87
|
+
return set(s.qubits)
|
|
88
|
+
if isinstance(s, (Measure, Reset)):
|
|
89
|
+
return {s.qubit}
|
|
90
|
+
if isinstance(s, Seq):
|
|
91
|
+
return set().union(*(touched(x) for x in s.stmts)) if s.stmts else set()
|
|
92
|
+
if isinstance(s, Box):
|
|
93
|
+
return touched(s.body)
|
|
94
|
+
if isinstance(s, If):
|
|
95
|
+
return touched(s.then_) | (touched(s.else_) if s.else_ else set())
|
|
96
|
+
return set()
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class Engine:
|
|
100
|
+
"""Shared machinery. Subclasses implement the personality's statement semantics."""
|
|
101
|
+
|
|
102
|
+
personality = ""
|
|
103
|
+
|
|
104
|
+
def __init__(self, prog: Stmt, contract: Contract, oracle: Oracle) -> None:
|
|
105
|
+
if contract.personality != self.personality:
|
|
106
|
+
raise QtError(
|
|
107
|
+
"E-EXEC-PERSONALITY",
|
|
108
|
+
f"contract {contract.name!r} is for {contract.personality!r}, "
|
|
109
|
+
f"not {self.personality!r}",
|
|
110
|
+
)
|
|
111
|
+
self.prog, self.contract, self.oracle = prog, contract, oracle
|
|
112
|
+
self.sigma: dict[str, int] = {}
|
|
113
|
+
self.valid: dict[str, Fraction] = {}
|
|
114
|
+
self.times: dict[tuple[int, str], Fraction] = {}
|
|
115
|
+
self.trace: list[TraceEvent] = []
|
|
116
|
+
self.violations: list[Violation] = []
|
|
117
|
+
self.drops: list[SilentDrop] = []
|
|
118
|
+
self.halted = False
|
|
119
|
+
|
|
120
|
+
# -- services ---------------------------------------------------------------------
|
|
121
|
+
def rec(self, nid: int, tag: str, t: Fraction | int, resource: str = "", op: str = "") -> None:
|
|
122
|
+
self.times[(nid, tag)] = Fraction(t)
|
|
123
|
+
if resource:
|
|
124
|
+
self.trace.append(TraceEvent(Fraction(t), resource, op or tag, nid))
|
|
125
|
+
|
|
126
|
+
def violate(
|
|
127
|
+
self, kind: str, nid: int, t: Fraction, shortfall: Fraction | None, detail: str
|
|
128
|
+
) -> None:
|
|
129
|
+
self.violations.append(Violation(kind, nid, Fraction(t), shortfall, detail))
|
|
130
|
+
|
|
131
|
+
def halt(self) -> None:
|
|
132
|
+
self.halted = True
|
|
133
|
+
|
|
134
|
+
def draw(self, src: str, dst: str, tier: str, nid: int) -> Fraction:
|
|
135
|
+
"""Realise the contract latency src->dst for `tier`, occurrence keyed by node `nid`."""
|
|
136
|
+
cl = self.contract.find_latency(src, dst, tier)
|
|
137
|
+
iv = Interval(cl.latency.iv.lo, cl.latency.iv.hi)
|
|
138
|
+
return Fraction(self.oracle.latency(lat_occurrence(cl.latency.key, nid), iv))
|
|
139
|
+
|
|
140
|
+
def record_outcome(self, m: Measure) -> str:
|
|
141
|
+
from qtiming.core.ids import bit_prop
|
|
142
|
+
|
|
143
|
+
prop = bit_prop(m.cbit.reg, m.cbit.idx, m.nid)
|
|
144
|
+
self.sigma[prop] = int(self.oracle.outcome(prop))
|
|
145
|
+
return prop
|
|
146
|
+
|
|
147
|
+
def cond_value(self, cond: Expr) -> bool:
|
|
148
|
+
ps = props_of(cond)
|
|
149
|
+
missing = [p for p in ps if p not in self.sigma]
|
|
150
|
+
if missing:
|
|
151
|
+
raise QtError("E-EXEC-UNBOUND", f"condition reads {missing[0]!r} before it is measured")
|
|
152
|
+
return bool(evaluate(cond, {p: self.sigma[p] for p in ps}))
|
|
153
|
+
|
|
154
|
+
def cond_valid(self, cond: Expr) -> Fraction:
|
|
155
|
+
return max((self.valid[p] for p in props_of(cond)), default=Fraction(0))
|
|
156
|
+
|
|
157
|
+
# -- driver -------------------------------------------------------------------------
|
|
158
|
+
def run(self) -> ExecResult:
|
|
159
|
+
self.start()
|
|
160
|
+
self.exec_stmt(self.prog)
|
|
161
|
+
self.finish()
|
|
162
|
+
return ExecResult(
|
|
163
|
+
tuple(self.trace), tuple(self.violations), tuple(self.drops), dict(self.times),
|
|
164
|
+
self.halted,
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
def start(self) -> None:
|
|
168
|
+
"""Personality hook: initialise state."""
|
|
169
|
+
|
|
170
|
+
def finish(self) -> None:
|
|
171
|
+
"""Personality hook: after the last statement."""
|
|
172
|
+
|
|
173
|
+
def exec_stmt(self, s: Stmt) -> None:
|
|
174
|
+
if self.halted:
|
|
175
|
+
return
|
|
176
|
+
if isinstance(s, Seq):
|
|
177
|
+
for x in s.stmts:
|
|
178
|
+
self.exec_stmt(x)
|
|
179
|
+
elif isinstance(s, Box):
|
|
180
|
+
self.exec_stmt(s.body)
|
|
181
|
+
elif isinstance(s, Gate):
|
|
182
|
+
self.gate(s)
|
|
183
|
+
elif isinstance(s, Delay):
|
|
184
|
+
self.delay(s)
|
|
185
|
+
elif isinstance(s, Barrier):
|
|
186
|
+
self.barrier(s)
|
|
187
|
+
elif isinstance(s, Measure):
|
|
188
|
+
self.measure(s)
|
|
189
|
+
elif isinstance(s, Reset):
|
|
190
|
+
self.reset(s)
|
|
191
|
+
elif isinstance(s, If):
|
|
192
|
+
self.if_(s)
|
|
193
|
+
elif isinstance(s, (For, While, Switch, Assign, Call, Within)):
|
|
194
|
+
raise QtError(
|
|
195
|
+
"E-EXEC-UNSUPPORTED",
|
|
196
|
+
f"{type(s).__name__} is not executable: elaborate (unroll/lower) the program first",
|
|
197
|
+
s.loc,
|
|
198
|
+
)
|
|
199
|
+
else: # pragma: no cover
|
|
200
|
+
raise QtError("E-EXEC-UNSUPPORTED", f"unknown statement {type(s).__name__}")
|
|
201
|
+
|
|
202
|
+
def gate(self, s: Gate) -> None:
|
|
203
|
+
raise NotImplementedError
|
|
204
|
+
|
|
205
|
+
def delay(self, s: Delay) -> None:
|
|
206
|
+
raise NotImplementedError
|
|
207
|
+
|
|
208
|
+
def barrier(self, s: Barrier) -> None:
|
|
209
|
+
raise NotImplementedError
|
|
210
|
+
|
|
211
|
+
def measure(self, s: Measure) -> None:
|
|
212
|
+
raise NotImplementedError
|
|
213
|
+
|
|
214
|
+
def reset(self, s: Reset) -> None:
|
|
215
|
+
self.gate(
|
|
216
|
+
Gate(nid=s.nid, loc=s.loc, name="reset", qubits=(s.qubit,),
|
|
217
|
+
dur=self.contract.duration("reset"))
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
def if_(self, s: If) -> None:
|
|
221
|
+
raise NotImplementedError
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def execute(prog: Stmt, contract: Contract, oracle: Oracle | None = None) -> ExecResult:
|
|
225
|
+
"""Run `prog` under the contract's personality. Default oracle: `Fixed()` (all-zero bits)."""
|
|
226
|
+
from .artiq import ArtiqExec
|
|
227
|
+
from .ibm import IbmExec
|
|
228
|
+
from .oracle import Fixed
|
|
229
|
+
from .q1 import Q1Exec
|
|
230
|
+
from .qua import QuaExec
|
|
231
|
+
|
|
232
|
+
cls: dict[str, type[Engine]] = {
|
|
233
|
+
"ibm": IbmExec, "q1": Q1Exec, "artiq": ArtiqExec, "qua": QuaExec,
|
|
234
|
+
}
|
|
235
|
+
return cls[contract.personality](prog, contract, oracle or Fixed()).run()
|
qtiming/exec/explore.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Exhaustive oracle: every outcome assignment times every vertex of the latency box.
|
|
2
|
+
|
|
3
|
+
Discovery is lazy: run with a strict `Fixed`; each time the run asks for a value it was not given,
|
|
4
|
+
branch on it (bit: 0/1, latency: lo/hi). Exact ground truth for small programs (hypothesis H2).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Iterator
|
|
10
|
+
from fractions import Fraction
|
|
11
|
+
|
|
12
|
+
from qtiming.contract.model import Contract
|
|
13
|
+
from qtiming.core.ast import Stmt
|
|
14
|
+
from qtiming.core.errors import QtError
|
|
15
|
+
|
|
16
|
+
from .engine import ExecResult, execute
|
|
17
|
+
from .oracle import Fixed, NeedChoice
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def exhaustive(
|
|
21
|
+
prog: Stmt, contract: Contract, *, k_max: int = 12, K_max: int = 10
|
|
22
|
+
) -> Iterator[tuple[dict[str, int], dict[str, Fraction], ExecResult]]:
|
|
23
|
+
stack: list[tuple[dict[str, int], dict[str, Fraction]]] = [({}, {})]
|
|
24
|
+
while stack:
|
|
25
|
+
omega, theta = stack.pop()
|
|
26
|
+
try:
|
|
27
|
+
res = execute(prog, contract, Fixed(omega, theta, strict=True))
|
|
28
|
+
except NeedChoice as need:
|
|
29
|
+
if need.kind == "bit":
|
|
30
|
+
if len(omega) >= k_max:
|
|
31
|
+
raise QtError("E-EXEC-EXHAUSTIVE", f"more than {k_max} outcome bits") from None
|
|
32
|
+
stack += [({**omega, need.key: 0}, theta), ({**omega, need.key: 1}, theta)]
|
|
33
|
+
else:
|
|
34
|
+
iv = need.iv
|
|
35
|
+
assert iv is not None
|
|
36
|
+
if iv.hi is None:
|
|
37
|
+
raise QtError("E-EXEC-UNBOUNDED", f"{need.key}: unbounded latency") from None
|
|
38
|
+
if len(theta) >= K_max:
|
|
39
|
+
raise QtError("E-EXEC-EXHAUSTIVE", f"more than {K_max} latencies") from None
|
|
40
|
+
for v in sorted({iv.lo, iv.hi}):
|
|
41
|
+
stack.append((omega, {**theta, need.key: Fraction(v)}))
|
|
42
|
+
continue
|
|
43
|
+
yield omega, theta, res
|
qtiming/exec/ibm.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""IBM personality (restricted block model). Spec: docs/personality-spec/ibm.md."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import defaultdict
|
|
6
|
+
from fractions import Fraction
|
|
7
|
+
|
|
8
|
+
from qtiming.core.ast import Barrier, Box, Delay, Gate, If, Measure, Seq, Stmt
|
|
9
|
+
from qtiming.core.errors import QtError
|
|
10
|
+
|
|
11
|
+
from .engine import Engine, touched
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def chain_durations(s: Stmt) -> dict[int, int]:
|
|
15
|
+
"""Static per-qubit duration of an arm made only of gates, delays and barriers."""
|
|
16
|
+
clock: dict[int, int] = defaultdict(int)
|
|
17
|
+
|
|
18
|
+
def go(x: Stmt) -> None:
|
|
19
|
+
if isinstance(x, Seq):
|
|
20
|
+
for y in x.stmts:
|
|
21
|
+
go(y)
|
|
22
|
+
elif isinstance(x, Box):
|
|
23
|
+
go(x.body)
|
|
24
|
+
elif isinstance(x, (Gate, Delay)):
|
|
25
|
+
start = max(clock[q] for q in x.qubits)
|
|
26
|
+
for q in x.qubits:
|
|
27
|
+
clock[q] = start + x.dur
|
|
28
|
+
elif isinstance(x, Barrier):
|
|
29
|
+
j = max((clock[q] for q in x.qubits), default=0)
|
|
30
|
+
for q in x.qubits:
|
|
31
|
+
clock[q] = j
|
|
32
|
+
else:
|
|
33
|
+
raise QtError("E-EXEC-UNSUPPORTED", f"IBM arms may not contain {type(x).__name__}")
|
|
34
|
+
|
|
35
|
+
go(s)
|
|
36
|
+
return dict(clock)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class IbmExec(Engine):
|
|
40
|
+
personality = "ibm"
|
|
41
|
+
|
|
42
|
+
def start(self) -> None:
|
|
43
|
+
self.clock: dict[int, Fraction] = defaultdict(Fraction)
|
|
44
|
+
|
|
45
|
+
def _span(self, qubits: tuple[int, ...], dur: int, nid: int, op: str) -> Fraction:
|
|
46
|
+
start = max(self.clock[q] for q in qubits)
|
|
47
|
+
end = start + dur
|
|
48
|
+
for q in qubits:
|
|
49
|
+
self.clock[q] = end
|
|
50
|
+
self.rec(nid, "start", start)
|
|
51
|
+
for q in qubits:
|
|
52
|
+
self.rec(nid, "end", end, f"q{q}", op)
|
|
53
|
+
return end
|
|
54
|
+
|
|
55
|
+
def gate(self, s: Gate) -> None:
|
|
56
|
+
self._span(s.qubits, s.dur, s.nid, s.name)
|
|
57
|
+
|
|
58
|
+
def delay(self, s: Delay) -> None:
|
|
59
|
+
self._span(s.qubits, s.dur, s.nid, "delay")
|
|
60
|
+
|
|
61
|
+
def barrier(self, s: Barrier) -> None:
|
|
62
|
+
j = max((self.clock[q] for q in s.qubits), default=Fraction(0))
|
|
63
|
+
for q in s.qubits:
|
|
64
|
+
self.clock[q] = j
|
|
65
|
+
self.rec(s.nid, "join", j)
|
|
66
|
+
|
|
67
|
+
def measure(self, s: Measure) -> None:
|
|
68
|
+
end = self._span((s.qubit,), self.contract.duration(
|
|
69
|
+
"measure_2" if s.variant == "mid" else "measure"), s.nid, "measure")
|
|
70
|
+
prop = self.record_outcome(s)
|
|
71
|
+
self.valid[prop] = end + self.draw("measure", "branch", s.tier, s.nid)
|
|
72
|
+
self.rec(s.nid, "valid", self.valid[prop])
|
|
73
|
+
|
|
74
|
+
def if_(self, s: If) -> None:
|
|
75
|
+
br = self.contract.branch
|
|
76
|
+
for arm in (s.then_, s.else_):
|
|
77
|
+
if arm is not None and not br.allow_nested and _has_if_or_measure(arm):
|
|
78
|
+
raise QtError("E-EXEC-UNSUPPORTED", "IBM arms may not nest ifs or measure", s.loc)
|
|
79
|
+
res = sorted(touched(s.then_) | (touched(s.else_) if s.else_ else set()))
|
|
80
|
+
v = self.cond_valid(s.cond)
|
|
81
|
+
self.rec(s.nid, "bready", max([Fraction(0), *(self.clock[q] for q in res)]))
|
|
82
|
+
mode = self.contract.param("ibm", "block_start", "all_resources")
|
|
83
|
+
if mode != "all_resources":
|
|
84
|
+
raise QtError("E-EXEC-UNSUPPORTED", "only block_start = all_resources is implemented")
|
|
85
|
+
join = self.contract.param("ibm", "join_behavior", "pad_to_longest_block")
|
|
86
|
+
if mode == "all_resources":
|
|
87
|
+
b = max([v, *(self.clock[q] for q in res)])
|
|
88
|
+
starts = {q: b for q in res}
|
|
89
|
+
else: # per_resource
|
|
90
|
+
starts = {q: max(v, self.clock[q]) for q in res}
|
|
91
|
+
b = min(starts.values()) if starts else v
|
|
92
|
+
taken = bool(self.cond_value(s.cond))
|
|
93
|
+
arm = s.then_ if taken else s.else_
|
|
94
|
+
dmax = max(
|
|
95
|
+
(max(chain_durations(a).values(), default=0) for a in (s.then_, s.else_) if a),
|
|
96
|
+
default=0,
|
|
97
|
+
)
|
|
98
|
+
for q in res:
|
|
99
|
+
self.clock[q] = starts[q]
|
|
100
|
+
self.rec(s.nid, "bstart", b)
|
|
101
|
+
if arm is not None:
|
|
102
|
+
self.exec_stmt(arm)
|
|
103
|
+
d_taken = max((self.clock[q] - starts[q] for q in res), default=Fraction(0))
|
|
104
|
+
bend = b + (dmax if join == "pad_to_longest_block" else d_taken)
|
|
105
|
+
for q in res:
|
|
106
|
+
self.clock[q] = bend
|
|
107
|
+
self.rec(s.nid, "bend", bend)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _has_if_or_measure(s: Stmt) -> bool:
|
|
111
|
+
if isinstance(s, (If, Measure)):
|
|
112
|
+
return True
|
|
113
|
+
if isinstance(s, Seq):
|
|
114
|
+
return any(_has_if_or_measure(x) for x in s.stmts)
|
|
115
|
+
if isinstance(s, Box):
|
|
116
|
+
return _has_if_or_measure(s.body)
|
|
117
|
+
return False
|
qtiming/exec/oracle.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Oracles: where outcomes (bits) and latency realisations come from during a run."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import random
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from fractions import Fraction
|
|
8
|
+
from typing import Protocol
|
|
9
|
+
|
|
10
|
+
from qtiming.core.errors import QtError
|
|
11
|
+
from qtiming.core.time import Interval
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Oracle(Protocol):
|
|
15
|
+
def outcome(self, prop: str) -> int: ...
|
|
16
|
+
def latency(self, occurrence: str, iv: Interval) -> Fraction: ...
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class NeedChoice(Exception):
|
|
20
|
+
"""Raised by a strict `Fixed` when a run asks for a value the assignment does not give."""
|
|
21
|
+
|
|
22
|
+
def __init__(self, kind: str, key: str, iv: Interval | None = None) -> None:
|
|
23
|
+
super().__init__(kind, key)
|
|
24
|
+
self.kind, self.key, self.iv = kind, key, iv
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Fixed:
|
|
28
|
+
"""Replays a counterexample. Unspecified latencies take the interval midpoint, unspecified
|
|
29
|
+
bits 0, and the defaults used are recorded in `defaulted`. `strict` raises `NeedChoice`."""
|
|
30
|
+
|
|
31
|
+
def __init__(
|
|
32
|
+
self,
|
|
33
|
+
omega: Mapping[str, int] | None = None,
|
|
34
|
+
theta: Mapping[str, Fraction | int] | None = None,
|
|
35
|
+
*,
|
|
36
|
+
strict: bool = False,
|
|
37
|
+
) -> None:
|
|
38
|
+
self.omega, self.theta, self.strict = dict(omega or {}), dict(theta or {}), strict
|
|
39
|
+
self.defaulted: list[str] = []
|
|
40
|
+
|
|
41
|
+
def outcome(self, prop: str) -> int:
|
|
42
|
+
if prop in self.omega:
|
|
43
|
+
return int(self.omega[prop])
|
|
44
|
+
if self.strict:
|
|
45
|
+
raise NeedChoice("bit", prop)
|
|
46
|
+
self.defaulted.append(prop)
|
|
47
|
+
return 0
|
|
48
|
+
|
|
49
|
+
def latency(self, occurrence: str, iv: Interval) -> Fraction:
|
|
50
|
+
if occurrence in self.theta:
|
|
51
|
+
v = Fraction(self.theta[occurrence])
|
|
52
|
+
if not iv.contains(v):
|
|
53
|
+
raise QtError("E-EXEC-THETA", f"{occurrence} = {v} outside [{iv.lo}, {iv.hi}]")
|
|
54
|
+
return v
|
|
55
|
+
if self.strict:
|
|
56
|
+
raise NeedChoice("lat", occurrence, iv)
|
|
57
|
+
self.defaulted.append(occurrence)
|
|
58
|
+
return Fraction(iv.lo) if iv.hi is None else Fraction(iv.lo + iv.hi, 2)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class Random:
|
|
62
|
+
"""Seeded coin outcomes; latencies uniform on a 1/8 dt grid inside [lo, hi]."""
|
|
63
|
+
|
|
64
|
+
def __init__(self, seed: int) -> None:
|
|
65
|
+
self._r = random.Random(seed)
|
|
66
|
+
|
|
67
|
+
def outcome(self, prop: str) -> int:
|
|
68
|
+
return self._r.getrandbits(1)
|
|
69
|
+
|
|
70
|
+
def latency(self, occurrence: str, iv: Interval) -> Fraction:
|
|
71
|
+
if iv.hi is None:
|
|
72
|
+
raise QtError("E-EXEC-UNBOUNDED", f"{occurrence}: unbounded latency, use Fixed")
|
|
73
|
+
return Fraction(self._r.randint(iv.lo * 8, iv.hi * 8), 8)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class Extreme:
|
|
77
|
+
"""Every latency at `lo` or `hi` (`pick`), bits from `omega` (default 0)."""
|
|
78
|
+
|
|
79
|
+
def __init__(self, pick: str = "hi", omega: Mapping[str, int] | None = None) -> None:
|
|
80
|
+
self.pick, self.omega = pick, dict(omega or {})
|
|
81
|
+
|
|
82
|
+
def outcome(self, prop: str) -> int:
|
|
83
|
+
return int(self.omega.get(prop, 0))
|
|
84
|
+
|
|
85
|
+
def latency(self, occurrence: str, iv: Interval) -> Fraction:
|
|
86
|
+
if self.pick == "hi" and iv.hi is not None:
|
|
87
|
+
return Fraction(iv.hi)
|
|
88
|
+
return Fraction(iv.lo)
|
qtiming/exec/q1.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Q1 personality (predicated, RT queue). Spec: docs/personality-spec/q1.md.
|
|
2
|
+
|
|
3
|
+
One sequencer: the classical Q1 core issues instructions in program order into a FIFO that the
|
|
4
|
+
real-time (RT) core drains on a rigid timeline.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from fractions import Fraction
|
|
10
|
+
|
|
11
|
+
from qtiming.core.ast import Barrier, Box, Delay, Gate, If, Measure, Seq, Stmt
|
|
12
|
+
from qtiming.core.errors import QtError
|
|
13
|
+
from qtiming.core.labels import Expr
|
|
14
|
+
|
|
15
|
+
from .engine import Engine
|
|
16
|
+
|
|
17
|
+
Cond = tuple[Expr, bool] # (condition, polarity under which the instruction executes)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _rt_instrs(s: Stmt | None) -> list[Gate | Delay]:
|
|
21
|
+
if s is None:
|
|
22
|
+
return []
|
|
23
|
+
if isinstance(s, Seq):
|
|
24
|
+
return [i for x in s.stmts for i in _rt_instrs(x)]
|
|
25
|
+
if isinstance(s, Box):
|
|
26
|
+
return _rt_instrs(s.body)
|
|
27
|
+
if isinstance(s, (Gate, Delay)):
|
|
28
|
+
return [s]
|
|
29
|
+
if isinstance(s, Barrier):
|
|
30
|
+
return []
|
|
31
|
+
raise QtError("E-EXEC-UNSUPPORTED", f"Q1 conditional arms may not contain {type(s).__name__}")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Q1Exec(Engine):
|
|
35
|
+
personality = "q1"
|
|
36
|
+
|
|
37
|
+
def start(self) -> None:
|
|
38
|
+
self.nop = Fraction(self.contract.cost("nop"))
|
|
39
|
+
self.depth = int(self.contract.cap("rt_queue_depth", 32)) # type: ignore[call-overload]
|
|
40
|
+
self.else_time = Fraction(
|
|
41
|
+
self.contract.param("q1", "else_time_dt", 1) # type: ignore[call-overload]
|
|
42
|
+
)
|
|
43
|
+
self.ic = Fraction(0) # Q1-core issue clock
|
|
44
|
+
self.starts: list[Fraction] = [] # RT start time of each instruction so far
|
|
45
|
+
self.prev_end = Fraction(0) # RT time at which the next instruction would start
|
|
46
|
+
|
|
47
|
+
def _rt(self, nid: int, dur: int, op: str, cond: Cond | None) -> None:
|
|
48
|
+
k = len(self.starts)
|
|
49
|
+
ic = self.ic + self.nop
|
|
50
|
+
if k >= self.depth: # queue full: the Q1 core stalls until a slot frees up
|
|
51
|
+
ic = max(ic, self.starts[k - self.depth])
|
|
52
|
+
self.ic = ic
|
|
53
|
+
ex = ic if k == 0 else self.prev_end
|
|
54
|
+
self.rec(nid, "issue", ic)
|
|
55
|
+
executed = True
|
|
56
|
+
if cond is not None:
|
|
57
|
+
executed = self.cond_value(cond[0]) == cond[1]
|
|
58
|
+
v = self.cond_valid(cond[0])
|
|
59
|
+
if ex < v:
|
|
60
|
+
self.violate("stale-read", nid, ex, v - ex, "condition read before result valid")
|
|
61
|
+
if ex < ic:
|
|
62
|
+
self.violate("underflow-halt", nid, ex, ic - ex, "RT queue empty when needed")
|
|
63
|
+
self.halt()
|
|
64
|
+
return
|
|
65
|
+
self.rec(nid, "exec", ex, "rt", op)
|
|
66
|
+
self.starts.append(ex)
|
|
67
|
+
self.prev_end = ex + (dur if executed else self.else_time)
|
|
68
|
+
|
|
69
|
+
def gate(self, s: Gate) -> None:
|
|
70
|
+
self._rt(s.nid, s.dur, s.name, None)
|
|
71
|
+
|
|
72
|
+
def delay(self, s: Delay) -> None:
|
|
73
|
+
self._rt(s.nid, s.dur, "wait", None)
|
|
74
|
+
|
|
75
|
+
def barrier(self, s: Barrier) -> None: # single sequencer: nothing to join
|
|
76
|
+
return
|
|
77
|
+
|
|
78
|
+
def measure(self, s: Measure) -> None:
|
|
79
|
+
self._rt(s.nid, self.contract.duration("measure"), "acquire", None)
|
|
80
|
+
if self.halted:
|
|
81
|
+
return
|
|
82
|
+
end = self.times[(s.nid, "exec")] + self.contract.duration("measure")
|
|
83
|
+
prop = self.record_outcome(s)
|
|
84
|
+
self.valid[prop] = end + self.draw("measure", "branch", s.tier, s.nid)
|
|
85
|
+
self.rec(s.nid, "valid", self.valid[prop])
|
|
86
|
+
|
|
87
|
+
def if_(self, s: If) -> None:
|
|
88
|
+
for arm, pol in ((s.then_, True), (s.else_, False)):
|
|
89
|
+
if arm is None:
|
|
90
|
+
continue
|
|
91
|
+
self.ic += self.nop # the set_cond instruction itself runs on the Q1 core
|
|
92
|
+
self.rec(s.nid, "set_cond" if pol else "set_cond_else", self.ic)
|
|
93
|
+
for ins in _rt_instrs(arm):
|
|
94
|
+
self._rt(ins.nid, ins.dur, ins.name if isinstance(ins, Gate) else "wait",
|
|
95
|
+
(s.cond, pol))
|