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/check.py ADDED
@@ -0,0 +1,224 @@
1
+ """The check: compare a build's hidden state with the reference's, against a threshold."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import re
8
+ from collections.abc import Iterable
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+
12
+ import numpy as np
13
+
14
+ LABELS = {"correct", "degraded", "broken"}
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Verdict:
19
+ """The result of the check on one build.
20
+
21
+ Parameters
22
+ ----------
23
+ passed : bool
24
+ True when the cosine is at or above the threshold.
25
+ cosine : float
26
+ The cosine of the build's hidden state with the reference's.
27
+ threshold : float
28
+ The threshold of the build's toolchain.
29
+ """
30
+
31
+ passed: bool
32
+ cosine: float
33
+ threshold: float
34
+
35
+ @property
36
+ def margin(self) -> float:
37
+ """Return the cosine minus the threshold. A negative margin means that the build failed."""
38
+ return self.cosine - self.threshold
39
+
40
+
41
+ def cosine(device: np.ndarray, reference: np.ndarray) -> float:
42
+ """Return the cosine of two hidden states, as a mean over the inputs.
43
+
44
+ Parameters
45
+ ----------
46
+ device : np.ndarray
47
+ The hidden state of the build, with the inputs on the first axis.
48
+ reference : np.ndarray
49
+ The hidden state of the reference, with the same shape.
50
+
51
+ Returns
52
+ -------
53
+ float
54
+ The cosine of each input's flattened states, averaged over the inputs.
55
+
56
+ Raises
57
+ ------
58
+ ValueError
59
+ If the shapes are different, or if a state of an input is all zeros.
60
+ """
61
+ if device.shape != reference.shape:
62
+ raise ValueError(f"The shape {device.shape} is not the reference shape {reference.shape}.")
63
+ a = device.reshape(len(device), -1).astype(np.float64)
64
+ b = reference.reshape(len(reference), -1).astype(np.float64)
65
+ norms = np.linalg.norm(a, axis=1) * np.linalg.norm(b, axis=1)
66
+ zero = np.flatnonzero(norms == 0)
67
+ if zero.size:
68
+ raise ValueError(
69
+ f"The hidden state of input {int(zero[0])} is all zeros; its cosine is not defined."
70
+ )
71
+ return float(((a * b).sum(axis=1) / norms).mean())
72
+
73
+
74
+ def check(score: float, threshold: float) -> Verdict:
75
+ """Return the verdict for a build from its cosine and its toolchain's threshold.
76
+
77
+ Parameters
78
+ ----------
79
+ score : float
80
+ The cosine of the build's hidden state with the reference's.
81
+ threshold : float
82
+ The threshold of the build's toolchain.
83
+
84
+ Returns
85
+ -------
86
+ Verdict
87
+ A pass when the cosine is at or above the threshold.
88
+ """
89
+ return Verdict(passed=score >= threshold, cosine=score, threshold=threshold)
90
+
91
+
92
+ def calibrate(builds: Iterable[tuple[float, str]]) -> float:
93
+ """Return the threshold of a toolchain: the lowest cosine of a correct build.
94
+
95
+ Parameters
96
+ ----------
97
+ builds : Iterable[tuple[float, str]]
98
+ One (cosine, label) pair for each build whose accuracy is known. The label is
99
+ ``correct``, ``degraded`` or ``broken``.
100
+
101
+ Returns
102
+ -------
103
+ float
104
+ The lowest cosine of a build with the label ``correct``.
105
+
106
+ Raises
107
+ ------
108
+ ValueError
109
+ If a label is not one of the three, or if no build has the label ``correct``.
110
+ """
111
+ builds = list(builds)
112
+ labels = {label for _, label in builds}
113
+ if unknown := labels - LABELS:
114
+ raise ValueError(f"The labels {sorted(unknown)} are not one of {sorted(LABELS)}.")
115
+ scores = [s for s, label in builds if label == "correct"]
116
+ if not scores:
117
+ raise ValueError(f"No build has the label correct (labels found: {sorted(labels)}).")
118
+ return min(scores)
119
+
120
+
121
+ @dataclass(frozen=True)
122
+ class DefaultThreshold:
123
+ """The paper's thresholds for one toolchain version.
124
+
125
+ Parameters
126
+ ----------
127
+ toolchain : str
128
+ The toolchain, as ``firstlight device --toolchain`` names it: ``qnn`` or ``tensorrt``.
129
+ version : str
130
+ The release of the toolchain. A recorded version matches when it is the release, or the
131
+ release and a build stamp after a dot (QAIRT gives ``2.45.0.260326154327``).
132
+ cosine : float
133
+ The lowest cosine of a correct build after iteration 2.
134
+ agreement : float | None
135
+ The lowest output agreement of a correct build after iteration 2, or None.
136
+ source : str
137
+ The builds that set the thresholds.
138
+ """
139
+
140
+ toolchain: str
141
+ version: str
142
+ cosine: float
143
+ agreement: float | None
144
+ source: str
145
+
146
+
147
+ # The values are the lowest scores of the correct builds in firstlight/data, unrounded, so that
148
+ # each default equals the paper's threshold (plan/targets.yaml: phone_threshold, gpu_threshold).
149
+ DEFAULTS: dict[tuple[str, str], DefaultThreshold] = {
150
+ ("qnn", "2.45.0"): DefaultThreshold(
151
+ toolchain="qnn",
152
+ version="2.45.0",
153
+ cosine=0.8206705575659003,
154
+ agreement=0.7997530864197531,
155
+ source="65 correct phone builds of the paper (phone_first_set.json)",
156
+ ),
157
+ ("qnn", "2.51.0"): DefaultThreshold(
158
+ toolchain="qnn",
159
+ version="2.51.0",
160
+ cosine=0.8206705575659003,
161
+ agreement=0.7997530864197531,
162
+ source="the QAIRT 2.45.0 values, which separate 4 correct from 5 broken S24 and S25 builds "
163
+ "compiled with QAIRT 2.51 (records/qairt_251_threshold.md)",
164
+ ),
165
+ ("tensorrt", "10.13.3.9"): DefaultThreshold(
166
+ toolchain="tensorrt",
167
+ version="10.13.3.9",
168
+ cosine=0.8557187052779881,
169
+ agreement=0.385,
170
+ source="29 correct L40S builds of the paper (gpu_builds.json)",
171
+ ),
172
+ }
173
+
174
+
175
+ def same_version(recorded: str, release: str) -> bool:
176
+ """Return True when a recorded version is the release, or the release and a build stamp.
177
+
178
+ The build stamp follows a dot (QAIRT gives ``2.45.0.260326154327``).
179
+ """
180
+ return recorded == release or recorded.startswith(release + ".")
181
+
182
+
183
+ def release_of(version: str) -> str:
184
+ """Return a version without its build stamp, a last component of 10 or more digits."""
185
+ return re.sub(r"\.\d{10,}$", "", version)
186
+
187
+
188
+ def same_release(a: str, b: str) -> bool:
189
+ """Return True when two recorded versions are of one release, whatever their build stamps."""
190
+ return release_of(a) == release_of(b) or same_version(a, b) or same_version(b, a)
191
+
192
+
193
+ def paper_model(graph: str | Path) -> str | None:
194
+ """Return the name of the paper's model that a graph is, or None for any other graph.
195
+
196
+ The graph is recognised by the sha256 of its file, listed in ``data/paper_graphs.json``.
197
+ """
198
+ listed = json.loads((Path(__file__).parent / "data" / "paper_graphs.json").read_text())
199
+ digest = hashlib.sha256(Path(graph).read_bytes()).hexdigest()
200
+ return listed["graphs"].get(digest)
201
+
202
+
203
+ def default_threshold(toolchain: str, version: str) -> DefaultThreshold | None:
204
+ """Return the paper's thresholds for a toolchain version, or None when there are none.
205
+
206
+ Parameters
207
+ ----------
208
+ toolchain : str
209
+ The toolchain that made the states.
210
+ version : str
211
+ The version of the toolchain, as recorded.
212
+
213
+ Returns
214
+ -------
215
+ DefaultThreshold | None
216
+ The entry of the toolchain whose release matches the version; the longest release when
217
+ several match.
218
+ """
219
+ matches = [
220
+ (release, entry)
221
+ for (name, release), entry in DEFAULTS.items()
222
+ if name == toolchain and same_version(version, release)
223
+ ]
224
+ return max(matches, key=lambda m: len(m[0]))[1] if matches else None
firstlight/contract.py ADDED
@@ -0,0 +1,187 @@
1
+ """Write the iteration contract (graph, start and spec) from a PyTorch function of one iteration."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Callable, Mapping
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import numpy as np
11
+
12
+ from .model import Spec
13
+
14
+
15
+ def export(
16
+ iteration: Callable[[dict[str, Any], dict[str, Any]], Mapping[str, Any]],
17
+ example_state: Mapping[str, Any],
18
+ example_inputs: Mapping[str, Any],
19
+ folder: str | Path,
20
+ *,
21
+ start: Callable[[dict[str, Any]], Mapping[str, Any]] | None = None,
22
+ check_state: str | None = None,
23
+ halt: str | None = None,
24
+ limit: int | None = None,
25
+ classes_axis: int = -1,
26
+ ) -> Spec:
27
+ """Export one iteration of a PyTorch looped model as the graph, start and spec of the contract.
28
+
29
+ Parameters
30
+ ----------
31
+ iteration : callable
32
+ One iteration, a function or a method of a ``torch.nn.Module``.
33
+ ``iteration(state, inputs)`` takes two dicts of tensors, the hidden state and the task
34
+ inputs, and returns a dict that holds each tensor of the hidden state by the same name,
35
+ and optionally ``logits`` and the halting output ``halt``.
36
+ example_state : Mapping[str, torch.Tensor]
37
+ Each tensor of the hidden state, with a batch axis of 1. Without ``start``, this is the
38
+ hidden state before iteration 1, and it is written to ``start.npz``.
39
+ example_inputs : Mapping[str, torch.Tensor]
40
+ Each task input, with a batch axis of 1.
41
+ folder : str | Path
42
+ The folder that gets ``step.onnx``, ``start.npz`` or ``start.onnx``, and ``spec.json``.
43
+ start : callable | None
44
+ For a hidden state that depends on the inputs: ``start(inputs)`` returns the hidden state
45
+ before iteration 1 as a dict. It is exported to ``start.onnx``.
46
+ check_state : str | None
47
+ The tensor of the hidden state that the check compares. It can be left out only when the
48
+ hidden state has one tensor.
49
+ halt, limit, classes_axis
50
+ Written to the spec as they are (see the keys of the spec in the README).
51
+
52
+ Returns
53
+ -------
54
+ Spec
55
+ The spec as ``Spec.load`` reads it, after ``Spec.validate``.
56
+
57
+ Raises
58
+ ------
59
+ ValueError
60
+ If ``check_state`` is missing with more than one tensor of the hidden state, if
61
+ ``iteration`` does not return each tensor of the hidden state, or the halting output, or
62
+ if the exported graph does not give the output of ``iteration`` over 2 iterations.
63
+ """
64
+ import torch
65
+
66
+ folder = Path(folder)
67
+ folder.mkdir(parents=True, exist_ok=True)
68
+ states, inputs = list(example_state), list(example_inputs)
69
+ if check_state is None:
70
+ if len(states) != 1:
71
+ raise ValueError(
72
+ f"Give check_state: the hidden state has {len(states)} tensors {states}."
73
+ )
74
+ check_state = states[0]
75
+ with torch.no_grad():
76
+ first = dict(iteration(dict(example_state), dict(example_inputs)))
77
+ if missing := set(states) - set(first):
78
+ raise ValueError(f"The iteration does not return the tensors {sorted(missing)}.")
79
+ if halt is not None and halt not in first:
80
+ raise ValueError(f"The iteration does not return the halting output {halt!r}.")
81
+ extra = [k for k in ("logits", halt) if k is not None and k in first]
82
+ outputs = [*states, *extra]
83
+
84
+ class Iteration(torch.nn.Module):
85
+ def __init__(self) -> None:
86
+ super().__init__()
87
+ # The weights of a method's module go into the graph as weights, not as constants.
88
+ self.owner = _module(iteration)
89
+
90
+ def forward(self, *tensors):
91
+ out = iteration(dict(zip(states, tensors)), dict(zip(inputs, tensors[len(states) :])))
92
+ return tuple(out[k] for k in outputs)
93
+
94
+ args = (*example_state.values(), *example_inputs.values())
95
+ torch.onnx.export(
96
+ Iteration().eval(), args, str(folder / "step.onnx"), dynamo=False,
97
+ input_names=[*states, *inputs],
98
+ output_names=[f"{s}_out" for s in states] + extra,
99
+ ) # fmt: skip
100
+ _keep_inputs(folder / "step.onnx", example_inputs)
101
+ if start is None:
102
+ start_file = "start.npz"
103
+ np.savez(folder / start_file, **{k: v.detach().numpy() for k, v in example_state.items()})
104
+ else:
105
+ start_file = "start.onnx"
106
+
107
+ class Start(torch.nn.Module):
108
+ def __init__(self) -> None:
109
+ super().__init__()
110
+ self.owner = _module(start)
111
+
112
+ def forward(self, *tensors):
113
+ out = start(dict(zip(inputs, tensors)))
114
+ return tuple(out[k] for k in states)
115
+
116
+ torch.onnx.export(
117
+ Start().eval(), tuple(example_inputs.values()), str(folder / start_file),
118
+ dynamo=False, input_names=inputs, output_names=states,
119
+ ) # fmt: skip
120
+ spec = {
121
+ "graph": "step.onnx",
122
+ "states": states,
123
+ "inputs": inputs,
124
+ "check_state": check_state,
125
+ "start": start_file,
126
+ "halt": halt,
127
+ "limit": limit,
128
+ "classes_axis": classes_axis,
129
+ }
130
+ (folder / "spec.json").write_text(json.dumps(spec, indent=1) + "\n")
131
+ loaded = Spec.load(folder / "spec.json")
132
+ loaded.validate()
133
+ _compare(loaded, iteration, start, example_state, example_inputs)
134
+ return loaded
135
+
136
+
137
+ def _keep_inputs(path: Path, example_inputs: Mapping[str, Any]) -> None:
138
+ """Add each task input that the iteration does not use to the graph: the contract needs it.
139
+
140
+ In a Universal Transformer, for example, the input tokens enter only the start.
141
+ """
142
+ import onnx
143
+ from onnx import helper
144
+
145
+ model = onnx.load(path)
146
+ have = {i.name for i in model.graph.input}
147
+ for name, value in example_inputs.items():
148
+ if name not in have:
149
+ array = value.detach().numpy()
150
+ kind = helper.np_dtype_to_tensor_dtype(array.dtype)
151
+ model.graph.input.append(helper.make_tensor_value_info(name, kind, list(array.shape)))
152
+ onnx.save(model, path)
153
+
154
+
155
+ def _module(function):
156
+ """Return the torch.nn.Module of a bound method, or None."""
157
+ import torch
158
+
159
+ owner = getattr(function, "__self__", None)
160
+ return owner if isinstance(owner, torch.nn.Module) else None
161
+
162
+
163
+ def _compare(spec, iteration, start, example_state, example_inputs) -> None:
164
+ """Run 2 iterations in PyTorch and in ONNX Runtime from the start; raise if they differ."""
165
+ import onnxruntime as ort
166
+ import torch
167
+
168
+ from .host import _start_session
169
+
170
+ feed = {k: v.detach().numpy() for k, v in example_inputs.items()}
171
+ session = ort.InferenceSession(str(spec.graph), providers=["CPUExecutionProvider"])
172
+ names = [f"{s}_out" for s in spec.states]
173
+ graph_state = _start_session(spec)(feed)
174
+ with torch.no_grad():
175
+ state = dict(start(dict(example_inputs)) if start else example_state)
176
+ for it in (1, 2):
177
+ state = {s: dict(iteration(state, dict(example_inputs)))[s] for s in spec.states}
178
+ graph_state = dict(zip(spec.states, session.run(names, {**graph_state, **feed})))
179
+ want, got = state[spec.check_state].numpy(), graph_state[spec.check_state]
180
+ diff = float(np.abs(want - got).max())
181
+ if diff > 1e-4 * max(1.0, float(np.abs(want).max())):
182
+ raise ValueError(
183
+ f"The exported graph gives {spec.check_state!r} after iteration {it} with a "
184
+ f"largest difference of {diff:.3g} from the PyTorch iteration. Control flow "
185
+ "that depends on tensor values, and random numbers, do not export; write them "
186
+ "as tensor operations and fixed tensors."
187
+ )