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/aihub.py ADDED
@@ -0,0 +1,456 @@
1
+ """The device run on Qualcomm AI Hub: compile a build, run iterations on a device, keep states."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ import hashlib
7
+ import json
8
+ import logging
9
+ from collections.abc import Callable
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ import numpy as np
15
+
16
+ from .host import _answer, _start_session
17
+ from .model import Spec
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+ SCHEMA = 1
22
+ # The value of AI Hub's --target_runtime for each toolchain.
23
+ TOOLCHAINS = {"qnn": "qnn_dlc", "tflite": "tflite"}
24
+ # The check reads the hidden state after iteration 2, so a device run has at least 2 iterations.
25
+ ITERATIONS = 2
26
+ # The arrays of the states file that are not states; a state cannot have one of these names.
27
+ RESERVED = {"iteration_1", "iteration_2", "predictions", "halt", "toolchain", "toolchain_version"}
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class DeviceRun:
32
+ """The result of a device run.
33
+
34
+ Parameters
35
+ ----------
36
+ states : Path
37
+ The file that ``firstlight check --states`` reads.
38
+ jobs : Path
39
+ The file of the AI Hub job ids.
40
+ ms_per_iteration : tuple[float, ...]
41
+ The time of one iteration on the device for each iteration, in milliseconds, from the
42
+ profile of its inference job.
43
+ job_ids : tuple[str, ...]
44
+ The compile job and the inference job of each iteration.
45
+ toolchain_version : str | None
46
+ The toolchain version that the compile job used, from the compiled model, or None when
47
+ AI Hub does not give it (TFLite).
48
+ """
49
+
50
+ states: Path
51
+ jobs: Path
52
+ ms_per_iteration: tuple[float, ...]
53
+ job_ids: tuple[str, ...]
54
+ toolchain_version: str | None
55
+
56
+
57
+ def jobs_path(states: str | Path) -> Path:
58
+ """Return the file of the job ids for the states file ``states``: ``<name>.jobs.json``."""
59
+ states = Path(states)
60
+ return states.with_name(f"{states.stem}.jobs.json")
61
+
62
+
63
+ def device_run(
64
+ spec: Spec,
65
+ build: str | Path,
66
+ device: str,
67
+ inputs: dict[str, np.ndarray],
68
+ out: str | Path,
69
+ toolchain: str = "qnn",
70
+ compile_job: str | None = None,
71
+ iterations: int = ITERATIONS,
72
+ ) -> DeviceRun:
73
+ """Compile ``build`` on AI Hub, run ``iterations`` iterations on ``device``, write the states.
74
+
75
+ Each iteration is one inference job on all the inputs. The host gives the hidden state that
76
+ the device returned after an iteration to the job of the next iteration. The job ids go to
77
+ ``<out stem>.jobs.json`` when each job starts, so a second call with the same arguments
78
+ uses the jobs that finished and starts only the others. A job that failed starts again.
79
+
80
+ When the compiled build takes an input as an integer type with a scale and a zero point, the
81
+ float feed is quantized with them. An integer output with a scale is dequantized, so the
82
+ states are float32 in the units of the host run.
83
+
84
+ Parameters
85
+ ----------
86
+ spec : Spec
87
+ The looped model. Its start gives the hidden state before iteration 1.
88
+ build : str | Path
89
+ The ONNX graph of one iteration to compile. It takes and gives the names of ``spec``.
90
+ device : str
91
+ The name of the device on AI Hub, for example "Samsung Galaxy S25".
92
+ inputs : dict[str, np.ndarray]
93
+ One array for each task input, with the N inputs on axis 0.
94
+ out : str | Path
95
+ The .npz file to write: ``iteration_1`` and ``iteration_2``, the check state with N on
96
+ axis 0 and no batch axis; one array for each state of the spec, by its name, with the
97
+ state after the last iteration (N on axis 0, then the shape that the graph takes), which
98
+ ``firstlight repair`` continues from; and ``predictions`` of shape (iterations, N, ...)
99
+ when the build gives ``logits``; ``halt`` of shape (iterations, N) when the spec has a
100
+ halting output.
101
+ toolchain : str
102
+ A key of ``TOOLCHAINS``.
103
+ compile_job : str | None
104
+ The id of a finished compile job to use in place of a compile of ``build``. Then
105
+ ``build`` gives only the names and the order of the outputs.
106
+ iterations : int
107
+ The number of iterations on the device, at least 2. The jobs of the first iterations of
108
+ an earlier run with the same job file are used again.
109
+
110
+ Returns
111
+ -------
112
+ DeviceRun
113
+ The paths of the two files, the time per iteration and the job ids.
114
+
115
+ Raises
116
+ ------
117
+ ImportError
118
+ If ``qai_hub`` is not installed.
119
+ ValueError
120
+ If the toolchain is unknown, ``iterations`` is less than 2, the inputs do not fit the
121
+ spec, the job file holds jobs of
122
+ other arguments, or the device gives outputs or dtypes that the build does not have.
123
+ RuntimeError
124
+ If an AI Hub job fails.
125
+ """
126
+ try:
127
+ import qai_hub as hub
128
+ except ImportError as error:
129
+ raise ImportError(
130
+ "The device run needs qai_hub. Install it with: pip install 'firstlight[aihub]'"
131
+ ) from error
132
+ if toolchain not in TOOLCHAINS:
133
+ raise ValueError(f"The toolchain {toolchain!r} is not one of {sorted(TOOLCHAINS)}.")
134
+ if iterations < ITERATIONS:
135
+ raise ValueError(
136
+ f"The device run needs at least {ITERATIONS} iterations, not {iterations}."
137
+ )
138
+ import onnx
139
+
140
+ build, out = Path(build), Path(out)
141
+ if clash := set(spec.states) & RESERVED:
142
+ raise ValueError(
143
+ f"The states {sorted(clash)} have the names of other arrays of the states file."
144
+ )
145
+ spec, feed, n = _first_feed(spec, build, inputs)
146
+ graph = onnx.load(build, load_external_data=False).graph
147
+ names = [o.name for o in graph.output]
148
+
149
+ path = jobs_path(out)
150
+ key = {
151
+ "device": device,
152
+ "toolchain": toolchain,
153
+ "build_sha256": _build_digest(build, graph),
154
+ "feed_sha256": _digest(feed),
155
+ "compile_job": compile_job,
156
+ }
157
+ record = _load(path, key, str(hub.__version__))
158
+ if compile_job is not None and "compile" not in record:
159
+ record["compile"] = compile_job
160
+ target = TOOLCHAINS[toolchain]
161
+ target_device = hub.Device(device)
162
+ compiled = _finished(
163
+ hub,
164
+ record,
165
+ path,
166
+ "compile",
167
+ lambda: (
168
+ _given_failed(compile_job)
169
+ if compile_job is not None
170
+ else hub.submit_compile_job(
171
+ model=str(build),
172
+ device=target_device,
173
+ options=f"--target_runtime {target}",
174
+ name=f"firstlight_{build.stem}_{target}",
175
+ )
176
+ ),
177
+ )
178
+ if "toolchain_version" not in record:
179
+ metadata = compiled.get_target_model().metadata
180
+ # The keys are members of qai_hub's ModelMetadataKey; their names end the text.
181
+ by_name = {str(k).split(".")[-1]: v for k, v in metadata.items()}
182
+ version = by_name.get("QAIRT_SDK_VERSION")
183
+ if version is None and toolchain == "qnn":
184
+ raise RuntimeError(
185
+ f"The QNN compile job {record['compile']} gives no QAIRT_SDK_VERSION in the "
186
+ f"metadata of its model: {sorted(by_name)}."
187
+ )
188
+ record["toolchain_version"] = version
189
+ _save(path, record)
190
+ shapes = compiled.get_target_shapes()
191
+ model = compiled.get_target_model()
192
+ in_specs, out_specs = _tensor_specs(model.input_spec), _tensor_specs(model.output_spec)
193
+ kept, answers, halts, ms = [], [], [], []
194
+ for it in range(1, iterations + 1):
195
+ ordered = {}
196
+ for name, (_, dtype) in shapes.items():
197
+ if name not in feed:
198
+ raise ValueError(
199
+ f"The compiled build {build} takes the input {name!r}, which is not a state "
200
+ f"or a task input of the spec: {sorted(feed)}."
201
+ )
202
+ given = feed[name]
203
+ want = np.dtype(dtype)
204
+ if want.kind in "iu" and all(a.dtype.kind == "f" for a in given):
205
+ given = [_quantize(a, in_specs.get(name), name, want) for a in given]
206
+ got = {a.dtype for a in given}
207
+ if got != {np.dtype(dtype)}:
208
+ raise ValueError(
209
+ f"The compiled build takes {name!r} as {dtype}, but the feed of iteration "
210
+ f"{it} gives {sorted(map(str, got))}."
211
+ )
212
+ ordered[name] = given
213
+ job = _finished(
214
+ hub,
215
+ record,
216
+ path,
217
+ f"iteration_{it}",
218
+ lambda ordered=ordered, it=it: hub.submit_inference_job(
219
+ model=model,
220
+ device=target_device,
221
+ inputs=ordered,
222
+ name=f"firstlight_{build.stem}_{target}_iteration_{it}",
223
+ ),
224
+ )
225
+ given = _named(job.download_output_data(), names, n)
226
+ states_out = {f"{s}_out" for s in spec.states}
227
+ given = {
228
+ name: [
229
+ _dequantize(
230
+ x, out_specs.get(name, out_specs.get(f"output_{k}")), name, name in states_out
231
+ )
232
+ for x in given[name]
233
+ ]
234
+ for k, name in enumerate(names)
235
+ }
236
+ state = {s: [x.astype(np.float32) for x in given[f"{s}_out"]] for s in spec.states}
237
+ if it <= ITERATIONS:
238
+ kept.append(np.stack([x[0] for x in state[spec.check_state]]))
239
+ if "logits" in given:
240
+ answers.append(np.stack([_answer(x, spec.classes_axis) for x in given["logits"]]))
241
+ if spec.halt and spec.halt in given:
242
+ halts.append(np.array([float(x.reshape(-1)[0]) for x in given[spec.halt]]))
243
+ profile = job.download_profile()
244
+ ms.append(profile["execution_summary"]["estimated_inference_time"] / 1000)
245
+ feed.update(state)
246
+ arrays = {"iteration_1": kept[0], "iteration_2": kept[1]}
247
+ arrays.update({s: np.stack(feed[s]) for s in spec.states})
248
+ if answers:
249
+ arrays["predictions"] = np.stack(answers)
250
+ if halts:
251
+ arrays["halt"] = np.stack(halts)
252
+ arrays["toolchain"] = np.array(toolchain)
253
+ if record["toolchain_version"] is not None:
254
+ arrays["toolchain_version"] = np.array(record["toolchain_version"])
255
+ out.parent.mkdir(parents=True, exist_ok=True)
256
+ np.savez(out, **arrays)
257
+ ids = tuple(record[k] for k in ("compile", *(f"iteration_{i + 1}" for i in range(iterations))))
258
+ return DeviceRun(
259
+ states=out,
260
+ jobs=path,
261
+ ms_per_iteration=tuple(ms),
262
+ job_ids=ids,
263
+ toolchain_version=record["toolchain_version"],
264
+ )
265
+
266
+
267
+ def _first_feed(
268
+ spec: Spec, build: Path, inputs: dict[str, np.ndarray]
269
+ ) -> tuple[Spec, dict[str, list[np.ndarray]], int]:
270
+ """Return the spec of ``build``, the feed of iteration 1 for each input, and the input count.
271
+
272
+ Raises
273
+ ------
274
+ ValueError
275
+ If ``build`` does not obey the spec, or the inputs miss a task input or have different
276
+ counts.
277
+ """
278
+ spec = dataclasses.replace(spec, graph=build)
279
+ spec.validate()
280
+ if missing := set(spec.inputs) - set(inputs):
281
+ raise ValueError(f"The inputs miss the task inputs {sorted(missing)}.")
282
+ counts = {k: len(inputs[k]) for k in spec.inputs}
283
+ if len(set(counts.values())) != 1:
284
+ raise ValueError(f"The inputs have different counts: {counts}.")
285
+ n = next(iter(counts.values()))
286
+ start = _start_session(spec)
287
+ feed = {k: [inputs[k][i] for i in range(n)] for k in spec.inputs}
288
+ firsts = [start({k: inputs[k][i] for k in spec.inputs}) for i in range(n)]
289
+ feed.update({s: [f[s] for f in firsts] for s in spec.states})
290
+ return spec, feed, n
291
+
292
+
293
+ def _tensor_specs(spec: dict[Any, list[Any]]) -> dict[str, Any]:
294
+ """Return the tensor specs of a compiled model by tensor name, from all of its graphs."""
295
+ return {t.name: t for tensors in spec.values() for t in tensors}
296
+
297
+
298
+ def _quantize(x: np.ndarray, tensor: Any, name: str, dtype: np.dtype) -> np.ndarray:
299
+ """Return ``x`` on the integer grid of ``tensor``: round(x / scale) + zero point, clipped.
300
+
301
+ A zero point that the compiled model does not give is 0.
302
+
303
+ Raises
304
+ ------
305
+ ValueError
306
+ If the compiled model gives no scale for the input ``name``.
307
+ """
308
+ if tensor is None or tensor.scale is None:
309
+ raise ValueError(
310
+ f"The compiled build takes {name!r} as {dtype}, but gives no scale and zero point "
311
+ "for it, so the float feed cannot be quantized."
312
+ )
313
+ info = np.iinfo(dtype)
314
+ q = np.round(x / tensor.scale) + (tensor.zero_point or 0)
315
+ return np.clip(q, info.min, info.max).astype(dtype)
316
+
317
+
318
+ def _dequantize(x: np.ndarray, tensor: Any, name: str, state: bool) -> np.ndarray:
319
+ """Return an integer output with a scale as (x - zero point) * scale, else ``x`` unchanged.
320
+
321
+ A zero point that the compiled model does not give is 0.
322
+
323
+ Raises
324
+ ------
325
+ ValueError
326
+ If ``name`` is an output of the hidden state, is an integer type, and has no scale: its
327
+ raw integers are not in the units of the host run.
328
+ """
329
+ if x.dtype.kind not in "iu":
330
+ return x
331
+ if tensor is None or tensor.scale is None:
332
+ if state:
333
+ raise ValueError(
334
+ f"The device gave the state output {name!r} as {x.dtype}, but the compiled "
335
+ "model gives no scale for it, so it cannot be dequantized."
336
+ )
337
+ return x
338
+ zero = tensor.zero_point or 0
339
+ return ((x.astype(np.float32) - zero) * tensor.scale).astype(np.float32)
340
+
341
+
342
+ def _given_failed(job_id: str) -> Any:
343
+ """Stop the run: the compile job that the caller gave did not succeed.
344
+
345
+ Raises
346
+ ------
347
+ RuntimeError
348
+ Always, with the id of the job.
349
+ """
350
+ raise RuntimeError(
351
+ f"The compile job {job_id} did not succeed. The device run does not compile the build "
352
+ "in its place."
353
+ )
354
+
355
+
356
+ def _build_digest(build: Path, graph: Any) -> str:
357
+ """Return the sha256 of the graph file and of each external data file that it names."""
358
+ h = hashlib.sha256(build.read_bytes())
359
+ locations = {
360
+ entry.value
361
+ for t in graph.initializer
362
+ if t.data_location == t.EXTERNAL
363
+ for entry in t.external_data
364
+ if entry.key == "location"
365
+ }
366
+ for location in sorted(locations):
367
+ h.update(location.encode())
368
+ h.update((build.parent / location).read_bytes())
369
+ return h.hexdigest()
370
+
371
+
372
+ def _digest(feed: dict[str, list[np.ndarray]]) -> str:
373
+ """Return the sha256 of the arrays of a feed, by name, dtype, shape and bytes."""
374
+ h = hashlib.sha256()
375
+ for name in sorted(feed):
376
+ for a in feed[name]:
377
+ h.update(f"{name}|{a.dtype}|{a.shape}|".encode())
378
+ h.update(np.ascontiguousarray(a).tobytes())
379
+ return h.hexdigest()
380
+
381
+
382
+ def _load(path: Path, key: dict[str, str], version: str) -> dict[str, Any]:
383
+ """Read the job record at ``path``, or start one; refuse a record of other arguments."""
384
+ if not path.exists():
385
+ return {"schema": SCHEMA, "qai_hub_version": version, **key, "failed": []}
386
+ record = json.loads(path.read_text())
387
+ if record.get("schema") != SCHEMA:
388
+ raise ValueError(
389
+ f"{path} has the schema {record.get('schema')!r}, not {SCHEMA}. Remove the file."
390
+ )
391
+ for k, v in key.items():
392
+ if record.get(k) != v:
393
+ raise ValueError(
394
+ f"{path} holds the jobs of another run: its {k} is {record.get(k)!r}, this "
395
+ f"run has {v!r}. Give another output file, or remove {path}."
396
+ )
397
+ return record
398
+
399
+
400
+ def _save(path: Path, record: dict[str, Any]) -> None:
401
+ """Write the job record, so that an interrupted run keeps each job that started."""
402
+ path.parent.mkdir(parents=True, exist_ok=True)
403
+ tmp = path.with_suffix(".tmp")
404
+ tmp.write_text(json.dumps(record, indent=1) + "\n")
405
+ tmp.replace(path)
406
+
407
+
408
+ def _finished(
409
+ hub: Any, record: dict[str, Any], path: Path, name: str, submit: Callable[[], Any]
410
+ ) -> Any:
411
+ """Return the finished job ``name`` of the record, or start it and wait for it.
412
+
413
+ Raises
414
+ ------
415
+ RuntimeError
416
+ If the job fails. Its id stays in the record, and the next run starts it again.
417
+ """
418
+ if job_id := record.get(name):
419
+ job = hub.get_job(job_id)
420
+ status = job.wait()
421
+ if status.success:
422
+ logger.info("use the finished job %s (%s)", job_id, name)
423
+ return job
424
+ record["failed"].append({"name": name, "job_id": job_id, "message": status.message})
425
+ logger.warning("the job %s (%s) failed; start it again", job_id, name)
426
+ job = submit()
427
+ record[name] = job.job_id
428
+ _save(path, record)
429
+ status = job.wait()
430
+ if not status.success:
431
+ raise RuntimeError(f"The AI Hub job {job.job_id} ({name}) failed: {status.message}")
432
+ return job
433
+
434
+
435
+ def _named(data: dict[str, list[np.ndarray]], names: list[str], n: int) -> dict[str, Any]:
436
+ """Return the outputs of an inference job by the names of the build's outputs.
437
+
438
+ QNN gives the outputs as ``output_0``, ``output_1``, and so on, in the order of the graph.
439
+
440
+ Raises
441
+ ------
442
+ ValueError
443
+ If the names are neither the build's names nor ``output_<k>`` for each output, or an
444
+ output does not hold one array for each input.
445
+ """
446
+ if set(data) != set(names):
447
+ numbered = [f"output_{k}" for k in range(len(names))]
448
+ if set(data) != set(numbered):
449
+ raise ValueError(
450
+ f"The device gave the outputs {sorted(data)}, but the build gives {names}."
451
+ )
452
+ data = {name: data[k] for name, k in zip(names, numbered)}
453
+ for name, arrays in data.items():
454
+ if len(arrays) != n:
455
+ raise ValueError(f"The device gave {len(arrays)} arrays of {name!r} for {n} inputs.")
456
+ return data
firstlight/bench.py ADDED
@@ -0,0 +1,127 @@
1
+ """Score a detector on the builds of the benchmark, with the paper's baselines as detectors."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib
6
+ import importlib.util
7
+ import json
8
+ from collections.abc import Callable
9
+ from pathlib import Path
10
+
11
+ from .check import calibrate
12
+ from .replay import Misses, _misses
13
+
14
+ DATA = Path(__file__).parent / "data"
15
+ # Each set: the builds that set the threshold, then the held-out builds that the threshold scores.
16
+ SETS = {
17
+ "phones": ("phones_threshold", "phones_held_out"),
18
+ "a100": ("gpus_threshold", "gpus_held_out"),
19
+ }
20
+
21
+ Detector = Callable[[dict[str, float]], float]
22
+
23
+
24
+ def census() -> list[dict]:
25
+ """Return the records of the 280 builds of the paper's census.
26
+
27
+ Returns
28
+ -------
29
+ list[dict]
30
+ One dict for each build, with its ``set``, ``label`` and ``signals`` (docs/dataset.md).
31
+ """
32
+ return json.loads((DATA / "build_census.json").read_text())["rows"]
33
+
34
+
35
+ def load(name: str) -> Detector:
36
+ """Return the detector that ``name`` gives.
37
+
38
+ Parameters
39
+ ----------
40
+ name : str
41
+ ``module:function`` for an importable module, or ``path/to/file.py:function``.
42
+
43
+ Returns
44
+ -------
45
+ Detector
46
+ A function that gives a score to the signals of one build. A higher score means
47
+ that the build is more likely correct.
48
+
49
+ Raises
50
+ ------
51
+ ValueError
52
+ If ``name`` has no ``:`` or the function is not in the module.
53
+ """
54
+ source, _, function = name.rpartition(":")
55
+ if not source or not function:
56
+ raise ValueError(f"Give the detector as module:function or file.py:function, not {name!r}.")
57
+ if source.endswith(".py"):
58
+ spec = importlib.util.spec_from_file_location(Path(source).stem, source)
59
+ if spec is None or spec.loader is None:
60
+ raise ValueError(f"Cannot read the detector file {source!r}.")
61
+ module = importlib.util.module_from_spec(spec)
62
+ spec.loader.exec_module(module)
63
+ else:
64
+ module = importlib.import_module(source)
65
+ if not callable(found := getattr(module, function, None)):
66
+ raise ValueError(f"{source!r} has no function {function!r}.")
67
+ return found
68
+
69
+
70
+ def bench(detector: Detector) -> dict[str, tuple[float, Misses] | None]:
71
+ """Return the threshold and the misses of a detector on each set of the benchmark.
72
+
73
+ The threshold is the lowest score of a correct build of the threshold builds of the set.
74
+ A broken held-out build is missed when its score is at or above the threshold; a correct
75
+ held-out build is flagged when its score is below it.
76
+
77
+ Parameters
78
+ ----------
79
+ detector : Detector
80
+ A function of the signals of one build (a dict). A higher score means more likely
81
+ correct. A ``KeyError`` means that a signal that it reads is not recorded for the set.
82
+
83
+ Returns
84
+ -------
85
+ dict[str, tuple[float, Misses] | None]
86
+ For each set, the threshold and the misses, or None when the detector reads a signal
87
+ that a build of the set does not have.
88
+ """
89
+ rows = census()
90
+ out: dict[str, tuple[float, Misses] | None] = {}
91
+ for name, (train, test) in SETS.items():
92
+ try:
93
+ scored = {
94
+ part: [(detector(dict(r["signals"])), r["label"]) for r in rows if r["set"] == part]
95
+ for part in (train, test)
96
+ }
97
+ except KeyError:
98
+ out[name] = None
99
+ continue
100
+ out[name] = (calibrate(scored[train]), _misses(scored[train], scored[test]))
101
+ return out
102
+
103
+
104
+ def hidden_state_2(signals: dict[str, float]) -> float:
105
+ """Return the cosine after iteration 2: the check of FirstLight."""
106
+ return signals["cosine_2"]
107
+
108
+
109
+ def hidden_state_1(signals: dict[str, float]) -> float:
110
+ """Return the cosine after iteration 1."""
111
+ return signals["cosine_1"]
112
+
113
+
114
+ def output_agreement_2(signals: dict[str, float]) -> float:
115
+ """Return the output agreement after iteration 2."""
116
+ return signals["output_agreement_2"]
117
+
118
+
119
+ def output_agreement_1(signals: dict[str, float]) -> float:
120
+ """Return the output agreement after iteration 1."""
121
+ return signals["output_agreement_1"]
122
+
123
+
124
+ def projected_distance_8(signals: dict[str, float]) -> float:
125
+ """Return minus the DiFR distance after iteration 8 (Karvonen et al., 2025): a distance is
126
+ higher on a broken build."""
127
+ return -signals["projected_distance_8"]