firstlight 0.1.0.dev0__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.
firstlight/host.py ADDED
@@ -0,0 +1,314 @@
1
+ """The fp32 host run: run a looped model to its limit; keep what the check and pricing need."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from collections.abc import Callable
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+
13
+ from .model import Spec
14
+
15
+ SCHEMA = 1
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class Reference:
20
+ """The record of a host run on N inputs.
21
+
22
+ Parameters
23
+ ----------
24
+ predictions : np.ndarray | None
25
+ The answer after each iteration, shape (limit, N, ...): the argmax of ``logits`` on its
26
+ classes axis, or None for a graph with no ``logits``.
27
+ accuracy : np.ndarray | None
28
+ The fraction of inputs answered correctly after each iteration, shape (limit,), or None
29
+ with no answers. An answer is correct when every position equals the correct answer. A
30
+ position whose correct answer is negative is not scored.
31
+ halt : np.ndarray | None
32
+ The halting output after each iteration, shape (limit, N), or None for a model with no
33
+ halting output.
34
+ states : np.ndarray
35
+ The check state after iterations 1 and 2, shape (2, N, ...).
36
+ """
37
+
38
+ predictions: np.ndarray | None
39
+ accuracy: np.ndarray | None
40
+ halt: np.ndarray | None
41
+ states: np.ndarray
42
+
43
+ def save(self, path: str | Path, spec: Spec) -> None:
44
+ """Write the reference to an .npz file with a record of how it was made.
45
+
46
+ The record is one line of JSON in the array ``record``: the schema version, the
47
+ versions of FirstLight and ONNX Runtime, the sha256 of the graph, the limit, and the
48
+ number of inputs. The file holds no pickled object.
49
+ """
50
+ from importlib.metadata import version
51
+
52
+ record = {
53
+ "schema": SCHEMA,
54
+ "firstlight_version": version("firstlight"),
55
+ "onnxruntime_version": version("onnxruntime"),
56
+ "graph_sha256": _sha256(spec.graph),
57
+ "limit": spec.limit,
58
+ "inputs": len(self.states[0]),
59
+ }
60
+ arrays = {k: getattr(self, k) for k in ("predictions", "accuracy", "halt", "states")}
61
+ np.savez(
62
+ path,
63
+ record=np.array(json.dumps(record)),
64
+ **{k: v for k, v in arrays.items() if v is not None},
65
+ )
66
+
67
+ @classmethod
68
+ def load(cls, path: str | Path, spec: Spec) -> Reference:
69
+ """Read a reference that ``save`` wrote for the graph and the limit of ``spec``.
70
+
71
+ Raises
72
+ ------
73
+ ValueError
74
+ If the file has no record, a schema version other than the current one, or was made
75
+ from another graph or with another limit.
76
+ """
77
+ with np.load(path, allow_pickle=False) as z:
78
+ if "record" not in z.files:
79
+ raise ValueError(f"{path} holds no record; it was not written by Reference.save.")
80
+ record = json.loads(str(z["record"]))
81
+ arrays = {
82
+ k: z[k] if k in z.files else None for k in ("predictions", "accuracy", "halt")
83
+ }
84
+ states = z["states"]
85
+ if record.get("schema") != SCHEMA:
86
+ raise ValueError(
87
+ f"{path} has the schema {record.get('schema')!r}, not {SCHEMA}. Run the host again."
88
+ )
89
+ if record["graph_sha256"] != (sha := _sha256(spec.graph)):
90
+ raise ValueError(
91
+ f"{path} was made from a graph with sha256 {record['graph_sha256']}, but "
92
+ f"{spec.graph} has {sha}."
93
+ )
94
+ if record["limit"] != spec.limit:
95
+ raise ValueError(
96
+ f"{path} was made with the limit {record['limit']}, "
97
+ f"but the spec gives {spec.limit}."
98
+ )
99
+ return cls(states=states, **arrays)
100
+
101
+
102
+ def host_run(
103
+ spec: Spec, inputs: dict[str, np.ndarray], answers: np.ndarray | None = None
104
+ ) -> Reference:
105
+ """Run the graph of ``spec`` in fp32 with ONNX Runtime, one input at a time, to its limit.
106
+
107
+ Parameters
108
+ ----------
109
+ spec : Spec
110
+ The looped model.
111
+ inputs : dict[str, np.ndarray]
112
+ One array for each task input, with the N inputs on axis 0. Each item along axis 0 has
113
+ the shape that the graph takes.
114
+ answers : np.ndarray | None
115
+ The correct answer of each input, shape (N, ...), or None.
116
+
117
+ Returns
118
+ -------
119
+ Reference
120
+ The answers, the accuracy and the halting output after each iteration, and the check
121
+ state after iterations 1 and 2.
122
+
123
+ Raises
124
+ ------
125
+ ValueError
126
+ If ``inputs`` does not hold each task input of the spec, if an input does not have the
127
+ shape that the graph takes, if the inputs or the answers have different counts, or if the
128
+ limit is missing or less than 2 (the check reads iteration 2), or if there are answers
129
+ and the graph gives no ``logits``.
130
+ """
131
+ import onnxruntime as ort
132
+
133
+ spec.validate()
134
+ if spec.limit is None:
135
+ raise ValueError("The spec gives no 'limit'; the host run needs one.")
136
+ if spec.limit < 2:
137
+ raise ValueError(f"The limit is {spec.limit}; the host run needs at least 2 iterations.")
138
+ if missing := set(spec.inputs) - set(inputs):
139
+ raise ValueError(f"The inputs miss the task inputs {sorted(missing)}.")
140
+ counts = {k: len(inputs[k]) for k in spec.inputs}
141
+ if len(set(counts.values())) != 1:
142
+ raise ValueError(f"The inputs have different counts: {counts}.")
143
+ n = next(iter(counts.values()))
144
+ if answers is not None and len(answers) != n:
145
+ raise ValueError(f"There are {len(answers)} answers for {n} inputs.")
146
+ session = ort.InferenceSession(str(spec.graph), providers=["CPUExecutionProvider"])
147
+ for i in session.get_inputs():
148
+ if i.name not in spec.inputs:
149
+ continue
150
+ per, want = inputs[i.name].shape[1:], [d if isinstance(d, int) else None for d in i.shape]
151
+ if len(per) != len(want) or any(w is not None and w != p for p, w in zip(per, want)):
152
+ raise ValueError(
153
+ f"The input {i.name!r} has the shape {per} for each input, but the graph takes "
154
+ f"{want}. Stack one array of the graph's shape (with its batch axis of 1) for "
155
+ f"each input on axis 0."
156
+ )
157
+ logits = ["logits"] if "logits" in {o.name for o in session.get_outputs()} else []
158
+ if answers is not None and not logits:
159
+ raise ValueError("The graph gives no output 'logits'; the accuracy needs it.")
160
+ first = _start_session(spec)
161
+ names = [f"{s}_out" for s in spec.states] + logits + ([spec.halt] if spec.halt else [])
162
+ predictions, halt, states = [], [], []
163
+ for i in range(n):
164
+ feed = {k: inputs[k][i] for k in spec.inputs}
165
+ state = first(feed)
166
+ p, h, kept = [], [], []
167
+ for it in range(spec.limit):
168
+ out = dict(zip(names, session.run(names, {**state, **feed})))
169
+ state = {s: out[f"{s}_out"] for s in spec.states}
170
+ if logits:
171
+ p.append(_answer(out["logits"], spec.classes_axis))
172
+ if spec.halt:
173
+ h.append(float(out[spec.halt].reshape(-1)[0]))
174
+ if it < 2:
175
+ kept.append(state[spec.check_state][0])
176
+ predictions.append(p)
177
+ halt.append(h)
178
+ states.append(kept)
179
+ pred = np.array(predictions).swapaxes(0, 1) if logits else None
180
+ accuracy = None if answers is None else _accuracy(pred, answers)
181
+ return Reference(
182
+ predictions=pred,
183
+ accuracy=accuracy,
184
+ halt=np.array(halt).T if spec.halt else None,
185
+ states=np.array(states).swapaxes(0, 1),
186
+ )
187
+
188
+
189
+ def _sha256(path: Path) -> str:
190
+ """Return the sha256 of a file."""
191
+ return hashlib.sha256(Path(path).read_bytes()).hexdigest()
192
+
193
+
194
+ @dataclass(frozen=True)
195
+ class Repair:
196
+ """The answers of a repair: fp32 iterations that continue a build's run.
197
+
198
+ Parameters
199
+ ----------
200
+ predictions : np.ndarray
201
+ The answer after each fp32 iteration, shape (iterations, N, ...).
202
+ accuracy : np.ndarray | None
203
+ The fraction of inputs answered correctly after each fp32 iteration, shape
204
+ (iterations,), or None with no answers. It is scored as in ``host_run``.
205
+ """
206
+
207
+ predictions: np.ndarray
208
+ accuracy: np.ndarray | None
209
+
210
+
211
+ def repair(
212
+ spec: Spec,
213
+ states: dict[str, np.ndarray],
214
+ inputs: dict[str, np.ndarray],
215
+ iterations: int,
216
+ answers: np.ndarray | None = None,
217
+ threads: int = 0,
218
+ ) -> Repair:
219
+ """Continue a build's run with ``iterations`` fp32 iterations of the graph of ``spec``.
220
+
221
+ The fp32 iterations start from the state that the build gave after its last iteration, for
222
+ example the state arrays of a ``firstlight device`` states file, and run in ONNX Runtime on
223
+ the host, one input at a time.
224
+
225
+ Parameters
226
+ ----------
227
+ spec : Spec
228
+ The looped model. Its graph is the fp32 graph.
229
+ states : dict[str, np.ndarray]
230
+ One array for each state of the spec, with the N inputs on axis 0. Each item along axis
231
+ 0 has the shape that the graph takes.
232
+ inputs : dict[str, np.ndarray]
233
+ One array for each task input, with the N inputs on axis 0.
234
+ iterations : int
235
+ The number of fp32 iterations, at least 1.
236
+ answers : np.ndarray | None
237
+ The correct answer of each input, shape (N, ...), or None.
238
+ threads : int
239
+ The number of ONNX Runtime threads; 0 lets ONNX Runtime choose.
240
+
241
+ Returns
242
+ -------
243
+ Repair
244
+ The answer and the accuracy after each fp32 iteration.
245
+
246
+ Raises
247
+ ------
248
+ ValueError
249
+ If a state or a task input is missing, the counts differ, ``iterations`` is less than 1,
250
+ or the graph gives no ``logits``.
251
+ """
252
+ import onnxruntime as ort
253
+
254
+ spec.validate()
255
+ if iterations < 1:
256
+ raise ValueError(f"The repair needs at least 1 fp32 iteration, not {iterations}.")
257
+ if missing := (set(spec.states) - set(states)) | (set(spec.inputs) - set(inputs)):
258
+ raise ValueError(f"The repair misses the states or task inputs {sorted(missing)}.")
259
+ counts = {
260
+ k: len(v) for k, v in {**states, **inputs}.items() if k in (*spec.states, *spec.inputs)
261
+ }
262
+ if answers is not None:
263
+ counts["answers"] = len(answers)
264
+ if len(set(counts.values())) != 1:
265
+ raise ValueError(f"The states, inputs and answers have different counts: {counts}.")
266
+ n = next(iter(counts.values()))
267
+ options = ort.SessionOptions()
268
+ options.intra_op_num_threads = threads
269
+ session = ort.InferenceSession(str(spec.graph), options, providers=["CPUExecutionProvider"])
270
+ if "logits" not in {o.name for o in session.get_outputs()}:
271
+ raise ValueError("The graph gives no output 'logits'; the repair gives answers from it.")
272
+ names = [f"{s}_out" for s in spec.states] + ["logits"]
273
+ predictions = []
274
+ for i in range(n):
275
+ feed = {k: inputs[k][i] for k in spec.inputs}
276
+ state = {s: states[s][i].astype(np.float32) for s in spec.states}
277
+ p = []
278
+ for _ in range(iterations):
279
+ out = dict(zip(names, session.run(names, {**state, **feed})))
280
+ state = {s: out[f"{s}_out"] for s in spec.states}
281
+ p.append(_answer(out["logits"], spec.classes_axis))
282
+ predictions.append(p)
283
+ pred = np.array(predictions).swapaxes(0, 1)
284
+ return Repair(pred, None if answers is None else _accuracy(pred, answers))
285
+
286
+
287
+ def _accuracy(pred: np.ndarray, answers: np.ndarray) -> np.ndarray:
288
+ """Return the fraction of inputs with every scored position correct, for each iteration.
289
+
290
+ ``pred`` has the shape (iterations, N, ...). A position whose correct answer is negative is
291
+ not scored.
292
+ """
293
+ hits = (pred == answers[None]) | (answers[None] < 0)
294
+ return hits.reshape(len(pred), len(answers), -1).all(-1).mean(1)
295
+
296
+
297
+ def _answer(logits: np.ndarray, classes_axis: int) -> np.ndarray:
298
+ """Return the answer of one input from its ``logits``, which have a batch axis of 1."""
299
+ return logits.argmax(classes_axis)[0]
300
+
301
+
302
+ def _start_session(spec: Spec) -> Callable[[dict[str, np.ndarray]], dict[str, np.ndarray]]:
303
+ """Return a function from one input's task inputs to the hidden state before iteration 1."""
304
+ if spec.start.suffix.lower() == ".onnx":
305
+ import onnxruntime as ort
306
+
307
+ session = ort.InferenceSession(str(spec.start), providers=["CPUExecutionProvider"])
308
+ wanted = [i.name for i in session.get_inputs()]
309
+ return lambda feed: dict(
310
+ zip(spec.states, session.run(list(spec.states), {k: feed[k] for k in wanted}))
311
+ )
312
+ with np.load(spec.start) as z:
313
+ start = {s: z[s] for s in spec.states}
314
+ return lambda feed: dict(start)
firstlight/model.py ADDED
@@ -0,0 +1,198 @@
1
+ """The iteration contract: one ONNX graph of one iteration, described by a spec file."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ import json
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Spec:
15
+ """A looped model as FirstLight runs it.
16
+
17
+ Parameters
18
+ ----------
19
+ graph : Path
20
+ The ONNX graph of one iteration. It takes each state and each input by name, and gives
21
+ ``<state>_out`` for each state, the halting output if there is one, and ``logits`` when
22
+ the accuracy is measured.
23
+ states : tuple[str, ...]
24
+ The names of the tensors that make up the hidden state.
25
+ inputs : tuple[str, ...]
26
+ The names of the task inputs, which stay the same in each iteration.
27
+ check_state : str
28
+ The tensor of the hidden state that the check compares with the reference.
29
+ start : Path
30
+ The hidden state before the first iteration: an .npz file with one array for each tensor,
31
+ or an ONNX graph that takes task inputs and gives each tensor by its name.
32
+ halt : str | None
33
+ The output that halts an input when it is more than 0, or None for a model with no halting.
34
+ limit : int | None
35
+ The maximum number of iterations, at least 1, or None. The check does not need it.
36
+ classes_axis : int
37
+ The axis of ``logits`` that holds the classes.
38
+ thresholds : dict | None
39
+ The thresholds that the last ``firstlight calibrate`` wrote: ``cosine``, ``agreement``
40
+ when the graph gives ``logits``, and ``set_on``, the files of the correct builds and
41
+ whether each was run or read from ``--states``. ``toolchain`` and ``version`` name the
42
+ toolchain and version that the states were recorded with, when ``calibrate`` read them.
43
+ None before a calibration.
44
+ """
45
+
46
+ graph: Path
47
+ states: tuple[str, ...]
48
+ inputs: tuple[str, ...]
49
+ check_state: str
50
+ start: Path
51
+ halt: str | None = None
52
+ limit: int | None = None
53
+ classes_axis: int = -1
54
+ thresholds: dict | None = None
55
+
56
+ @classmethod
57
+ def load(cls, path: str | Path) -> Spec:
58
+ """Read a spec file. Relative paths in it are relative to the folder of the file.
59
+
60
+ Raises
61
+ ------
62
+ ValueError
63
+ If the file has a key that is not a field of the spec, misses one of the five that
64
+ the check needs, or has a limit that is not a whole number of at least 1.
65
+ """
66
+ path = Path(path)
67
+ raw = json.loads(path.read_text())
68
+ fields = {f.name for f in dataclasses.fields(cls)}
69
+ if unknown := set(raw) - fields:
70
+ raise ValueError(f"The spec {path} has unknown keys {sorted(unknown)}.")
71
+ if missing := {"graph", "states", "inputs", "check_state", "start"} - set(raw):
72
+ raise ValueError(f"The spec {path} misses the keys {sorted(missing)}.")
73
+ limit = raw.get("limit")
74
+ if limit is not None and (
75
+ not isinstance(limit, int) or isinstance(limit, bool) or limit < 1
76
+ ):
77
+ raise ValueError(
78
+ f"The limit in {path} must be a whole number of at least 1, not {limit!r}."
79
+ )
80
+ thresholds = raw.get("thresholds")
81
+ if thresholds is not None:
82
+ ranges = {"cosine": (-1, 1), "agreement": (0, 1)}
83
+ values = (
84
+ {k: v for k, v in thresholds.items() if k not in ("set_on", "toolchain", "version")}
85
+ if isinstance(thresholds, dict)
86
+ else {}
87
+ )
88
+ if (
89
+ not isinstance(thresholds, dict)
90
+ or "cosine" not in thresholds
91
+ or set(values) - set(ranges)
92
+ or not isinstance(thresholds.get("set_on", []), list)
93
+ or any(not isinstance(thresholds.get(k, ""), str) for k in ("toolchain", "version"))
94
+ or ("version" in thresholds) != ("toolchain" in thresholds)
95
+ or any(
96
+ not isinstance(v, (int, float))
97
+ or isinstance(v, bool)
98
+ or not ranges[k][0] <= v <= ranges[k][1]
99
+ for k, v in values.items()
100
+ )
101
+ ):
102
+ raise ValueError(
103
+ f"The thresholds in {path} must hold 'cosine' from -1 to 1 and optionally "
104
+ f"'agreement' from 0 to 1, a list 'set_on', and the strings 'toolchain' and "
105
+ f"'version' together, not {thresholds!r}."
106
+ )
107
+ return cls(
108
+ graph=path.parent / raw["graph"],
109
+ states=tuple(raw["states"]),
110
+ inputs=tuple(raw["inputs"]),
111
+ check_state=raw["check_state"],
112
+ start=path.parent / raw["start"],
113
+ halt=raw.get("halt"),
114
+ limit=limit,
115
+ classes_axis=raw.get("classes_axis", -1),
116
+ thresholds=thresholds,
117
+ )
118
+
119
+ def validate(self) -> None:
120
+ """Make sure that the graph and the start file obey the contract.
121
+
122
+ A dimension that the graph names but does not fix is not compared.
123
+
124
+ Raises
125
+ ------
126
+ ValueError
127
+ If a name of the spec is not in the graph or repeats, if a tensor of the hidden state
128
+ and its ``_out`` tensor have different fixed shapes, or if the start does not give
129
+ each tensor with the graph's fixed shape. A start graph must also take only task
130
+ inputs, with the shapes that the graph gives them.
131
+ """
132
+ import onnx
133
+
134
+ model = onnx.load(self.graph, load_external_data=False)
135
+
136
+ def dims(values):
137
+ return {
138
+ v.name: [d.dim_value or None for d in v.type.tensor_type.shape.dim] for v in values
139
+ }
140
+
141
+ def fits(a, b):
142
+ return len(a) == len(b) and all(x is None or y is None or x == y for x, y in zip(a, b))
143
+
144
+ ins, outs = dims(model.graph.input), dims(model.graph.output)
145
+ if self.check_state not in self.states:
146
+ raise ValueError(
147
+ f"check_state {self.check_state!r} is not one of the states {self.states}."
148
+ )
149
+ names = (*self.states, *self.inputs)
150
+ if len(set(names)) != len(names):
151
+ raise ValueError(f"The states {self.states} and inputs {self.inputs} repeat a name.")
152
+ for name in names:
153
+ if name not in ins:
154
+ raise ValueError(f"The graph has no input {name!r}; its inputs are {sorted(ins)}.")
155
+ for name in (*(f"{s}_out" for s in self.states), *([self.halt] if self.halt else [])):
156
+ if name not in outs:
157
+ raise ValueError(
158
+ f"The graph has no output {name!r}; its outputs are {sorted(outs)}."
159
+ )
160
+ for s in self.states:
161
+ if not fits(ins[s], outs[f"{s}_out"]):
162
+ raise ValueError(
163
+ f"The input {s!r} has the shape {ins[s]}, "
164
+ f"but {s}_out has the shape {outs[f'{s}_out']}."
165
+ )
166
+ if self.start.suffix.lower() == ".onnx":
167
+ first = onnx.load(self.start, load_external_data=False)
168
+ s_ins, s_outs = dims(first.graph.input), dims(first.graph.output)
169
+ if extra := set(s_ins) - set(self.inputs):
170
+ raise ValueError(
171
+ f"The start graph takes {sorted(extra)}, which are not task inputs."
172
+ )
173
+ for name, shape in s_ins.items():
174
+ if not fits(ins[name], shape):
175
+ raise ValueError(
176
+ f"The start graph takes {name!r} with the shape {shape}, "
177
+ f"but the graph takes it with the shape {ins[name]}."
178
+ )
179
+ for s in self.states:
180
+ if s not in s_outs:
181
+ raise ValueError(
182
+ f"The start graph has no output {s!r}; its outputs are {sorted(s_outs)}."
183
+ )
184
+ if not fits(ins[s], s_outs[s]):
185
+ raise ValueError(
186
+ f"The start graph gives {s!r} the shape {s_outs[s]}, "
187
+ f"but the graph input {s!r} has the shape {ins[s]}."
188
+ )
189
+ return
190
+ with np.load(self.start) as start:
191
+ if missing := set(self.states) - set(start.files):
192
+ raise ValueError(f"The start file {self.start} has no array for {sorted(missing)}.")
193
+ for s in self.states:
194
+ if not fits(ins[s], list(start[s].shape)):
195
+ raise ValueError(
196
+ f"The start array {s!r} has the shape {list(start[s].shape)}, "
197
+ f"but the graph input {s!r} has the shape {ins[s]}."
198
+ )
firstlight/price.py ADDED
@@ -0,0 +1,160 @@
1
+ """Price a run from the energy of one iteration, and read the accuracy within a latency budget.
2
+
3
+ The cost rule: a run with a mean of n iterations per input and accuracy acc(n) costs
4
+ n * e / acc(n) per correct answer on a device whose iteration costs e. The budget read: within a
5
+ budget, a device runs as many iterations as fit at its time per iteration, and a correct build is
6
+ as accurate as the host after that many iterations. ``replay_cost`` and ``replay_budget`` apply
7
+ both to the paper's records in ``firstlight/data/pricing.json``.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import statistics
14
+ from collections.abc import Mapping, Sequence
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+
18
+ DATA = Path(__file__).parent / "data" / "pricing.json"
19
+
20
+
21
+ def cost_per_correct(iterations: float, energy: float, accuracy: float) -> float:
22
+ """Return the energy per correct answer of a run, in the unit of ``energy``.
23
+
24
+ Parameters
25
+ ----------
26
+ iterations : float
27
+ The mean number of iterations per input.
28
+ energy : float
29
+ The energy of one iteration on the device.
30
+ accuracy : float
31
+ The share of inputs answered correctly, above 0.
32
+ """
33
+ if accuracy <= 0:
34
+ raise ValueError("A run with no correct answer has no energy per correct answer.")
35
+ return iterations * energy / accuracy
36
+
37
+
38
+ def within_budget(
39
+ curve: Sequence[float] | Mapping[int, float], ms_per_iteration: float, budget_ms: float
40
+ ) -> tuple[int, float]:
41
+ """Return the iterations that fit in the budget and the host's accuracy after them.
42
+
43
+ Parameters
44
+ ----------
45
+ curve : sequence of float, or mapping of int to float
46
+ The host's accuracy after each iteration: a sequence starts at iteration 1 (as
47
+ ``host_run`` gives it); a mapping may skip iterations.
48
+ ms_per_iteration : float
49
+ The measured time of one iteration on the device, in ms.
50
+ budget_ms : float
51
+ The latency budget, in ms.
52
+
53
+ Returns
54
+ -------
55
+ tuple[int, float]
56
+ The iterations that the device runs, at most the curve's last recorded iteration, and the
57
+ accuracy after the last recorded iteration not above that count; the accuracy is 0.0
58
+ when no recorded iteration fits.
59
+ """
60
+ if ms_per_iteration <= 0:
61
+ raise ValueError("The time per iteration must be above 0.")
62
+ points = dict(enumerate(curve, start=1)) if not isinstance(curve, Mapping) else dict(curve)
63
+ points = {int(k): float(v) for k, v in points.items()}
64
+ n = min(int(budget_ms // ms_per_iteration), max(points))
65
+ done = [k for k in points if k <= n]
66
+ return n, points[max(done)] if done else 0.0
67
+
68
+
69
+ @dataclass(frozen=True)
70
+ class CostReplay:
71
+ """The cost rule and the FLOP estimate on the paper's runs.
72
+
73
+ Attributes
74
+ ----------
75
+ median_error : dict[str, float]
76
+ For each device, the median of |measured / predicted - 1| over its runs.
77
+ runs : dict[str, int]
78
+ For each device, the number of runs.
79
+ flop_low, flop_high : float
80
+ The smallest and largest ratio of measured energy to the FLOP estimate, over the
81
+ configurations that have runs.
82
+ flop_runs : int
83
+ The runs whose configuration has a FLOP estimate.
84
+ """
85
+
86
+ median_error: dict[str, float]
87
+ runs: dict[str, int]
88
+ flop_low: float
89
+ flop_high: float
90
+ flop_runs: int
91
+
92
+
93
+ def _read() -> dict:
94
+ return json.loads(DATA.read_text())
95
+
96
+
97
+ def _flop_ratio(f: dict) -> float:
98
+ """Return measured over FLOP-estimated energy: FLOPs / peak throughput x rated power."""
99
+ if "measured_over_estimate" in f:
100
+ return f["measured_over_estimate"]
101
+ estimate_mj = f["GFLOP_per_step"] / f["peak_TFLOPS"] * f["rated_W"]
102
+ return f["measured_mJ_per_step"] / estimate_mj
103
+
104
+
105
+ def replay_cost() -> CostReplay:
106
+ """Predict every recorded run from the energy of an iteration in its anchor run.
107
+
108
+ Returns
109
+ -------
110
+ CostReplay
111
+ The median error per device and the range of the FLOP estimate's shortfall.
112
+ """
113
+ cost = _read()["cost"]
114
+ errors: dict[str, list[float]] = {}
115
+ ratios = []
116
+ for r in cost["runs"]:
117
+ e = cost["anchors"][r["anchor"]]["mJ_per_step"] / 1000
118
+ predicted = cost_per_correct(r["mean_steps"], e, r["acc"])
119
+ errors.setdefault(r["device"], []).append(abs(r["J_per_correct"] / predicted - 1))
120
+ if r["config"] in cost["flops"]:
121
+ ratios.append(_flop_ratio(cost["flops"][r["config"]]))
122
+ return CostReplay(
123
+ median_error={d: statistics.median(v) for d, v in errors.items()},
124
+ runs={d: len(v) for d, v in errors.items()},
125
+ flop_low=min(ratios),
126
+ flop_high=max(ratios),
127
+ flop_runs=len(ratios),
128
+ )
129
+
130
+
131
+ def replay_budget(budget_ms: float) -> list[tuple[str, float, int, float]]:
132
+ """Return (device, ms per iteration, iterations, accuracy) for each recorded device.
133
+
134
+ The host curve is the paper's Sudoku-MLP fp32 curve; the times are the measured ones.
135
+ """
136
+ b = _read()["budget"]
137
+ curve = {int(k): v for k, v in b["host_curve"].items()}
138
+ out = []
139
+ for d in b["devices"]:
140
+ n, acc = within_budget(curve, d["ms_per_iteration"], budget_ms)
141
+ out.append((d["device"], d["ms_per_iteration"], n, acc))
142
+ return out
143
+
144
+
145
+ def print_replay(budgets_ms: Sequence[float] = (100.0, 1000.0)) -> None:
146
+ """Print the cost rule's median error per device, the FLOP shortfall and the budget reads."""
147
+ cost = replay_cost()
148
+ for device, err in cost.median_error.items():
149
+ print(f"cost rule, {device}: median error {100 * err:.1f}% over {cost.runs[device]} runs")
150
+ print(
151
+ f"FLOP estimate: measured energy is {cost.flop_low:.1f}x to {cost.flop_high:.0f}x the "
152
+ f"estimate over {cost.flop_runs} runs"
153
+ )
154
+ for budget in budgets_ms:
155
+ rows = replay_budget(budget)
156
+ acc = [100 * a for *_, a in rows]
157
+ print(
158
+ f"within {budget:g} ms: Sudoku-MLP solves {min(acc):.0f}% to {max(acc):.0f}% "
159
+ f"on {len(rows)} devices"
160
+ )