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/__init__.py +24 -0
- firstlight/__main__.py +870 -0
- firstlight/aihub.py +456 -0
- firstlight/bench.py +127 -0
- firstlight/check.py +224 -0
- firstlight/contract.py +187 -0
- firstlight/data/build_census.json +4326 -0
- firstlight/data/gpu_builds.json +3933 -0
- firstlight/data/host_simulation.json +110 -0
- firstlight/data/paper_graphs.json +9 -0
- firstlight/data/phone_first_set.json +5702 -0
- firstlight/data/phone_held_out.json +1487 -0
- firstlight/data/pricing.json +2743 -0
- firstlight/host.py +314 -0
- firstlight/model.py +198 -0
- firstlight/price.py +160 -0
- firstlight/replay.py +104 -0
- firstlight/trt.py +668 -0
- firstlight-0.1.0.dev0.dist-info/METADATA +58 -0
- firstlight-0.1.0.dev0.dist-info/RECORD +25 -0
- firstlight-0.1.0.dev0.dist-info/WHEEL +5 -0
- firstlight-0.1.0.dev0.dist-info/entry_points.txt +2 -0
- firstlight-0.1.0.dev0.dist-info/licenses/LICENSE +202 -0
- firstlight-0.1.0.dev0.dist-info/licenses/LICENSE-data +7 -0
- firstlight-0.1.0.dev0.dist-info/top_level.txt +1 -0
firstlight/__main__.py
ADDED
|
@@ -0,0 +1,870 @@
|
|
|
1
|
+
"""The command line: ``check``, ``calibrate``, ``replay``, ``bench``, ``device``, ``repair``,
|
|
2
|
+
``energy``. Exit 0, 1 or 2."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
import dataclasses
|
|
8
|
+
import json
|
|
9
|
+
import math
|
|
10
|
+
import sys
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
# The paper set its thresholds on 65 phone builds and 29 L40S builds whose correct cosines
|
|
16
|
+
# spread from about 0.82 to 1.0; fewer builds, or builds closer together, give a narrower threshold.
|
|
17
|
+
FEW_BUILDS = 10
|
|
18
|
+
NARROW_SPREAD = 0.01
|
|
19
|
+
# The paper's correct builds never fell below about 0.82, so a build below this is rarely correct.
|
|
20
|
+
LOW_COSINE = 0.5
|
|
21
|
+
# The paper labels each build by its accuracy relative to the reference.
|
|
22
|
+
CORRECT_SHARE = 0.95
|
|
23
|
+
BROKEN_SHARE = 0.5
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _cosine_value(text: str) -> float:
|
|
27
|
+
"""Return the number in ``text`` if it is from -1 to 1, the range of a cosine.
|
|
28
|
+
|
|
29
|
+
Raises
|
|
30
|
+
------
|
|
31
|
+
argparse.ArgumentTypeError
|
|
32
|
+
If ``text`` is not a number from -1 to 1.
|
|
33
|
+
"""
|
|
34
|
+
try:
|
|
35
|
+
value = float(text)
|
|
36
|
+
except ValueError:
|
|
37
|
+
value = None
|
|
38
|
+
if value is None or not -1 <= value <= 1:
|
|
39
|
+
raise argparse.ArgumentTypeError(f"{text!r} is not a number from -1 to 1.")
|
|
40
|
+
return value
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _share(text: str) -> float:
|
|
44
|
+
"""Return the number in ``text`` if it is from 0 to 1, the range of an output agreement.
|
|
45
|
+
|
|
46
|
+
Raises
|
|
47
|
+
------
|
|
48
|
+
argparse.ArgumentTypeError
|
|
49
|
+
If ``text`` is not a number from 0 to 1.
|
|
50
|
+
"""
|
|
51
|
+
try:
|
|
52
|
+
value = float(text)
|
|
53
|
+
except ValueError:
|
|
54
|
+
value = None
|
|
55
|
+
if value is None or not 0 <= value <= 1:
|
|
56
|
+
raise argparse.ArgumentTypeError(f"{text!r} is not a number from 0 to 1.")
|
|
57
|
+
return value
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _label(solved: int, base: int) -> str:
|
|
61
|
+
"""Return the label of a build from the inputs it solves and the inputs the reference solves."""
|
|
62
|
+
if solved >= CORRECT_SHARE * base:
|
|
63
|
+
return "correct"
|
|
64
|
+
return "broken" if solved < BROKEN_SHARE * base else "degraded"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _agreement(reference: np.ndarray | None, build: np.ndarray | None) -> float | None:
|
|
68
|
+
"""Return the output agreement after iteration 2, or None when either run has no answers.
|
|
69
|
+
|
|
70
|
+
Every position counts, with or without correct answers, so that a threshold from calibrate
|
|
71
|
+
holds in check whichever options each is given.
|
|
72
|
+
"""
|
|
73
|
+
if reference is None or build is None:
|
|
74
|
+
return None
|
|
75
|
+
return float((reference[1] == build[1]).mean())
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _parsers() -> tuple[argparse.ArgumentParser, dict[str, argparse.ArgumentParser]]:
|
|
79
|
+
"""Return the parser of the program and the parser of each command."""
|
|
80
|
+
parser = argparse.ArgumentParser(prog="firstlight")
|
|
81
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
82
|
+
check = commands.add_parser(
|
|
83
|
+
"check",
|
|
84
|
+
help="Do the check on one build.",
|
|
85
|
+
description="Run the graph of SPEC in fp32 and BUILD under ONNX Runtime for 2 iterations "
|
|
86
|
+
"on the same inputs, or read the states of the build from --states. Compare the check "
|
|
87
|
+
"state after iteration 2 with the threshold.",
|
|
88
|
+
)
|
|
89
|
+
calibrate = commands.add_parser(
|
|
90
|
+
"calibrate",
|
|
91
|
+
help="Set a threshold from builds that you know are correct.",
|
|
92
|
+
description="Give the cosine of each correct build and the lowest cosine as the threshold.",
|
|
93
|
+
)
|
|
94
|
+
commands.add_parser(
|
|
95
|
+
"replay",
|
|
96
|
+
help="Give the misses of each signal on the paper's held-out builds.",
|
|
97
|
+
description="Read the paper's records in the package. Set each threshold on the first "
|
|
98
|
+
"phone set and on the L40S builds. Give the broken builds that each signal misses and "
|
|
99
|
+
"the correct builds that it flags on the held-out phones and on the A100. With pricing, "
|
|
100
|
+
"give the cost rule's median error per device, the FLOP estimate's shortfall, and the "
|
|
101
|
+
"Sudoku-MLP accuracy within 100 ms and 1 s on each recorded device.",
|
|
102
|
+
).add_argument("what", nargs="?", choices=("check", "pricing"), default="check")
|
|
103
|
+
bench = commands.add_parser(
|
|
104
|
+
"bench",
|
|
105
|
+
help="Give the misses of a detector on the builds of the benchmark.",
|
|
106
|
+
description="Give the signals of each build to DETECTOR. Set the threshold at the lowest "
|
|
107
|
+
"score of a correct build of the first phone set and of the L40S builds. Give the broken "
|
|
108
|
+
"builds that the detector misses and the correct builds that it flags on the held-out "
|
|
109
|
+
"phones and on the A100.",
|
|
110
|
+
)
|
|
111
|
+
bench.add_argument(
|
|
112
|
+
"detector",
|
|
113
|
+
help="module:function or file.py:function. The function gets a dict of signals and "
|
|
114
|
+
"gives a score. A higher score means a correct build. Example: "
|
|
115
|
+
"firstlight.bench:hidden_state_2.",
|
|
116
|
+
)
|
|
117
|
+
device = commands.add_parser(
|
|
118
|
+
"device",
|
|
119
|
+
help="Run a build on a device through Qualcomm AI Hub or TensorRT and write its states.",
|
|
120
|
+
description="Compile BUILD for the device on Qualcomm AI Hub, or with TensorRT on this "
|
|
121
|
+
"GPU. Run 2 iterations (or --iterations, AI Hub only) on the device. Write the file "
|
|
122
|
+
"that check --states reads, and give "
|
|
123
|
+
"the time of each iteration. The AI Hub job ids go to OUT.jobs.json; the TensorRT engine "
|
|
124
|
+
"file goes to OUT.engine. If the command stops, run it again: it uses the jobs that "
|
|
125
|
+
"finished, or the engine file. To use a different AI Hub account file, set "
|
|
126
|
+
"QAIHUB_CLIENT_INI.",
|
|
127
|
+
)
|
|
128
|
+
repair = commands.add_parser(
|
|
129
|
+
"repair",
|
|
130
|
+
help="Continue a device run with fp32 iterations and give the accuracy.",
|
|
131
|
+
description="Read the state after the last iteration of a device run from --states. Run "
|
|
132
|
+
"K more iterations of the graph of SPEC in fp32 under ONNX Runtime from that state. Give "
|
|
133
|
+
"the accuracy after each of them with --answers, and write the answers with -o.",
|
|
134
|
+
)
|
|
135
|
+
energy = commands.add_parser(
|
|
136
|
+
"energy",
|
|
137
|
+
help="Give the energy of one iteration of a build on this NVIDIA GPU.",
|
|
138
|
+
description="Build BUILD with TensorRT on this GPU, or load --engine. Run -n iterations "
|
|
139
|
+
"at batch size 1, 3 times, after 10 s of the same work. Read the GPU's total-energy "
|
|
140
|
+
"counter (NVML) before and after each repeat, and give the energy and time of one "
|
|
141
|
+
"iteration and the mean power. The energy is the whole card's, with no idle power "
|
|
142
|
+
"subtracted. The engine file goes to <BUILD stem>_<precision>.engine in this folder.",
|
|
143
|
+
)
|
|
144
|
+
for cmd in (check, calibrate, device, repair, energy):
|
|
145
|
+
cmd.add_argument("spec", help="The spec file of the looped model.")
|
|
146
|
+
cmd.add_argument(
|
|
147
|
+
"-i",
|
|
148
|
+
"--inputs",
|
|
149
|
+
help="An .npz file: one array per input. The default is inputs.npz next to SPEC.",
|
|
150
|
+
)
|
|
151
|
+
device.add_argument("build", help="The ONNX graph of one iteration to compile.")
|
|
152
|
+
device.add_argument(
|
|
153
|
+
"--device",
|
|
154
|
+
required=True,
|
|
155
|
+
help='The device name on AI Hub, e.g. "Samsung Galaxy S25". For tensorrt, a part of the '
|
|
156
|
+
'GPU name, e.g. "L40S": the run stops on another GPU.',
|
|
157
|
+
)
|
|
158
|
+
device.add_argument(
|
|
159
|
+
"-o", "--output", required=True, help="The .npz file of states to write for check."
|
|
160
|
+
)
|
|
161
|
+
device.add_argument(
|
|
162
|
+
"--toolchain",
|
|
163
|
+
choices=["qnn", "tflite", "tensorrt"],
|
|
164
|
+
default="qnn",
|
|
165
|
+
help="The toolchain that compiles the build (default: qnn).",
|
|
166
|
+
)
|
|
167
|
+
device.add_argument(
|
|
168
|
+
"--iterations",
|
|
169
|
+
type=int,
|
|
170
|
+
default=2,
|
|
171
|
+
help="The number of iterations on the device, at least 2 (default: 2). Run the build "
|
|
172
|
+
"to its limit before firstlight repair.",
|
|
173
|
+
)
|
|
174
|
+
device.add_argument(
|
|
175
|
+
"--compile-job",
|
|
176
|
+
help="The id of a finished AI Hub compile job of your account. The device runs its "
|
|
177
|
+
"compiled model, and BUILD gives only the names and the order of the outputs.",
|
|
178
|
+
)
|
|
179
|
+
device.add_argument(
|
|
180
|
+
"--precision",
|
|
181
|
+
choices=["fp32", "fp16", "int8"],
|
|
182
|
+
help="For tensorrt: the precision of the build. int8 needs a graph with QuantizeLinear "
|
|
183
|
+
"nodes (explicit INT8).",
|
|
184
|
+
)
|
|
185
|
+
device.add_argument(
|
|
186
|
+
"--engine",
|
|
187
|
+
help="For tensorrt: an engine file to run in place of a build of BUILD. BUILD gives "
|
|
188
|
+
"only the names.",
|
|
189
|
+
)
|
|
190
|
+
energy.add_argument("build", help="The ONNX graph of one iteration to build.")
|
|
191
|
+
energy.add_argument(
|
|
192
|
+
"--toolchain",
|
|
193
|
+
required=True,
|
|
194
|
+
help="The toolchain. Only tensorrt has an energy reader in this release.",
|
|
195
|
+
)
|
|
196
|
+
energy.add_argument(
|
|
197
|
+
"--precision",
|
|
198
|
+
choices=["fp32", "fp16", "int8"],
|
|
199
|
+
help="The precision of the build. int8 needs a graph with QuantizeLinear nodes.",
|
|
200
|
+
)
|
|
201
|
+
energy.add_argument(
|
|
202
|
+
"--engine",
|
|
203
|
+
help="An engine file to run in place of a build of BUILD. BUILD gives only the names.",
|
|
204
|
+
)
|
|
205
|
+
energy.add_argument(
|
|
206
|
+
"-n",
|
|
207
|
+
"--iterations",
|
|
208
|
+
type=int,
|
|
209
|
+
default=10000,
|
|
210
|
+
help="The iterations in each repeat (default: 10000). The paper's L40S windows lasted "
|
|
211
|
+
"60 s or more.",
|
|
212
|
+
)
|
|
213
|
+
check.add_argument("build", nargs="?", help="The ONNX graph of the build.")
|
|
214
|
+
check.add_argument(
|
|
215
|
+
"-t",
|
|
216
|
+
"--threshold",
|
|
217
|
+
type=_cosine_value,
|
|
218
|
+
help="The threshold. Get it from calibrate. Without it, check stops with exit code 2.",
|
|
219
|
+
)
|
|
220
|
+
check.add_argument(
|
|
221
|
+
"--agreement",
|
|
222
|
+
type=_share,
|
|
223
|
+
help="The output agreement threshold: the build also fails when its output agreement "
|
|
224
|
+
"after iteration 2 is below it.",
|
|
225
|
+
)
|
|
226
|
+
check.add_argument(
|
|
227
|
+
"--states",
|
|
228
|
+
help="An .npz file with the check state of the build after iterations 1 and 2, made on a "
|
|
229
|
+
"device: arrays iteration_1 and iteration_2, and optionally predictions, the answers "
|
|
230
|
+
"after iterations 1 and 2 for the output agreement. With it, the build is not run.",
|
|
231
|
+
)
|
|
232
|
+
check.add_argument(
|
|
233
|
+
"--save-reference",
|
|
234
|
+
help="An .npz file to write the reference to, with a record of the graph and the limit. "
|
|
235
|
+
"Reference.load reads it back.",
|
|
236
|
+
)
|
|
237
|
+
calibrate.add_argument("build", nargs="*", help="The ONNX graph of a correct build.")
|
|
238
|
+
calibrate.add_argument(
|
|
239
|
+
"--states", nargs="+", default=[], help="An .npz file of states for each correct build."
|
|
240
|
+
)
|
|
241
|
+
for cmd in (check, calibrate):
|
|
242
|
+
cmd.add_argument(
|
|
243
|
+
"--answers",
|
|
244
|
+
help="An .npz file with one array: the correct answer of each input on axis 0. "
|
|
245
|
+
"Also run to the limit of the spec and give the accuracy. calibrate then uses only "
|
|
246
|
+
"the builds that are correct by their accuracy.",
|
|
247
|
+
)
|
|
248
|
+
repair.add_argument(
|
|
249
|
+
"--states", required=True, help="The states file that firstlight device wrote."
|
|
250
|
+
)
|
|
251
|
+
repair.add_argument(
|
|
252
|
+
"-k", "--iterations", type=int, required=True, help="The number of fp32 iterations."
|
|
253
|
+
)
|
|
254
|
+
repair.add_argument(
|
|
255
|
+
"--answers", help="An .npz file with one array: the correct answer of each input."
|
|
256
|
+
)
|
|
257
|
+
repair.add_argument("-o", "--output", help="An .npz file to write the answers to.")
|
|
258
|
+
return parser, {
|
|
259
|
+
"check": check,
|
|
260
|
+
"calibrate": calibrate,
|
|
261
|
+
"replay": commands.choices["replay"],
|
|
262
|
+
"bench": bench,
|
|
263
|
+
"device": device,
|
|
264
|
+
"repair": repair,
|
|
265
|
+
"energy": energy,
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _recorded_toolchain(path: str) -> tuple[str, str] | None:
|
|
270
|
+
"""Return the toolchain and its version recorded with a states file, or None.
|
|
271
|
+
|
|
272
|
+
The states file holds them as the arrays ``toolchain`` and ``toolchain_version``. A file from
|
|
273
|
+
``firstlight device`` also has them in the file ``<name>.jobs.json`` beside it.
|
|
274
|
+
"""
|
|
275
|
+
with np.load(path) as z:
|
|
276
|
+
if {"toolchain", "toolchain_version"} <= set(z.files):
|
|
277
|
+
return str(z["toolchain"]), str(z["toolchain_version"])
|
|
278
|
+
jobs = Path(path).with_name(f"{Path(path).stem}.jobs.json")
|
|
279
|
+
if jobs.exists():
|
|
280
|
+
record = json.loads(jobs.read_text())
|
|
281
|
+
if record.get("toolchain") and record.get("toolchain_version"):
|
|
282
|
+
return record["toolchain"], record["toolchain_version"]
|
|
283
|
+
return None
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _same_toolchain(a: tuple[str, str], b: tuple[str, str]) -> bool:
|
|
287
|
+
"""Return True when two (toolchain, version) pairs are one toolchain and release.
|
|
288
|
+
|
|
289
|
+
Host runs under ONNX Runtime compare by name only: a new ONNX Runtime does not change the
|
|
290
|
+
host's fp32 result enough to need a new threshold.
|
|
291
|
+
"""
|
|
292
|
+
from .check import same_release
|
|
293
|
+
|
|
294
|
+
return a[0] == b[0] and (a[0] == "onnxruntime" or same_release(a[1], b[1]))
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _read_states(
|
|
298
|
+
path: str, reference: np.ndarray, answers: np.ndarray | None
|
|
299
|
+
) -> tuple[np.ndarray, np.ndarray | None]:
|
|
300
|
+
"""Return the states of a build from a file, in the shape of the reference's (2, N, ...).
|
|
301
|
+
|
|
302
|
+
Also return the build's answers after iterations 1 and 2 from the optional array
|
|
303
|
+
``predictions`` (its first two rows), in the shape of the reference's first two, or None when
|
|
304
|
+
the file has none.
|
|
305
|
+
"""
|
|
306
|
+
with np.load(path) as z:
|
|
307
|
+
out = []
|
|
308
|
+
for k, want in (("iteration_1", reference[0]), ("iteration_2", reference[1])):
|
|
309
|
+
if z[k].shape != want.shape:
|
|
310
|
+
raise ValueError(
|
|
311
|
+
f"The array {k!r} in {path} has the shape {z[k].shape}, but the reference "
|
|
312
|
+
f"has {want.shape}: N inputs and the check state with no batch axis."
|
|
313
|
+
)
|
|
314
|
+
out.append(z[k])
|
|
315
|
+
if "predictions" not in z.files:
|
|
316
|
+
return np.array(out), None
|
|
317
|
+
if answers is None:
|
|
318
|
+
raise ValueError(
|
|
319
|
+
f"{path} has the array 'predictions', but the graph gives no output 'logits'."
|
|
320
|
+
)
|
|
321
|
+
given = z["predictions"]
|
|
322
|
+
# A device run of more than 2 iterations gives the answers after each of them.
|
|
323
|
+
if given.ndim < 1 or given.shape[0] < 2 or given.shape[1:] != answers.shape[1:]:
|
|
324
|
+
raise ValueError(
|
|
325
|
+
f"The array 'predictions' in {path} has the shape {given.shape}, but the "
|
|
326
|
+
f"reference's answers after iterations 1 and 2 have {answers[:2].shape}."
|
|
327
|
+
)
|
|
328
|
+
return np.array(out), given[:2]
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _scores(states: np.ndarray, reference: np.ndarray) -> tuple[float, str]:
|
|
332
|
+
"""Return the cosine after iteration 2 and a line with iteration 1 and the lowest input."""
|
|
333
|
+
from . import cosine
|
|
334
|
+
|
|
335
|
+
n = len(states[1])
|
|
336
|
+
# A state with inf gives inf / inf; the caller reports the cosine that is not finite.
|
|
337
|
+
with np.errstate(invalid="ignore", over="ignore"):
|
|
338
|
+
lowest = min(cosine(states[1][i : i + 1], reference[1][i : i + 1]) for i in range(n))
|
|
339
|
+
first = cosine(states[0], reference[0])
|
|
340
|
+
score = cosine(states[1], reference[1])
|
|
341
|
+
line = f"iteration 1 cosine {first:.4f} lowest input cosine {lowest:.4f} (iteration 2)"
|
|
342
|
+
return score, line
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _print_replay() -> None:
|
|
346
|
+
"""Print the misses of each signal as a table, with one line for the check at the end."""
|
|
347
|
+
from .replay import replay
|
|
348
|
+
|
|
349
|
+
def cell(m, count):
|
|
350
|
+
return "-" if m is None else f"{count(m)[0]} of {count(m)[1]}"
|
|
351
|
+
|
|
352
|
+
rows = replay()
|
|
353
|
+
head = ("signal", "broken missed, phones", "broken missed, A100", "correct flagged")
|
|
354
|
+
lines = [head]
|
|
355
|
+
for signal, sets in rows.items():
|
|
356
|
+
phones, a100 = sets.get("phones"), sets.get("a100")
|
|
357
|
+
tested = [m for m in (phones, a100) if m is not None and m.correct]
|
|
358
|
+
flagged = (
|
|
359
|
+
f"{sum(m.flagged for m in tested)} of {sum(m.correct for m in tested)}"
|
|
360
|
+
if tested
|
|
361
|
+
else "-"
|
|
362
|
+
)
|
|
363
|
+
missed = cell(phones, lambda m: (m.missed, m.broken))
|
|
364
|
+
if signal == "host simulation":
|
|
365
|
+
missed += " simulated"
|
|
366
|
+
lines.append((signal, missed, cell(a100, lambda m: (m.missed, m.broken)), flagged))
|
|
367
|
+
widths = [max(len(line[k]) for line in lines) for k in range(len(head))]
|
|
368
|
+
for line in lines:
|
|
369
|
+
print(" ".join(v.ljust(w) for v, w in zip(line, widths)).rstrip())
|
|
370
|
+
sets = rows["hidden state, iteration 2"].values()
|
|
371
|
+
broken, missed = sum(m.broken for m in sets), sum(m.missed for m in sets)
|
|
372
|
+
print(
|
|
373
|
+
f"the check caught {broken - missed} of {broken} broken builds and flagged "
|
|
374
|
+
f"{sum(m.flagged for m in sets)} of {sum(m.correct for m in sets)} correct builds"
|
|
375
|
+
)
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def _bench(name: str) -> int:
|
|
379
|
+
"""Print the threshold and the misses of the detector NAME on each set; return the exit code."""
|
|
380
|
+
from .bench import bench, load
|
|
381
|
+
|
|
382
|
+
try:
|
|
383
|
+
result = bench(load(name))
|
|
384
|
+
except Exception as error:
|
|
385
|
+
print(f"error: {error}", file=sys.stderr)
|
|
386
|
+
return 2
|
|
387
|
+
lines = [("set", "threshold", "broken missed", "correct flagged")]
|
|
388
|
+
for part, scored in result.items():
|
|
389
|
+
if scored is None:
|
|
390
|
+
lines.append((part, "-", "-", "-"))
|
|
391
|
+
continue
|
|
392
|
+
t, m = scored
|
|
393
|
+
lines.append((part, f"{t:.4f}", f"{m.missed} of {m.broken}", f"{m.flagged} of {m.correct}"))
|
|
394
|
+
widths = [max(len(line[k]) for line in lines) for k in range(4)]
|
|
395
|
+
for line in lines:
|
|
396
|
+
print(" ".join(v.ljust(w) for v, w in zip(line, widths)).rstrip())
|
|
397
|
+
return 0
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def _device(args: argparse.Namespace) -> int:
|
|
401
|
+
"""Run the build on the device, print the time of each iteration, and return the exit code."""
|
|
402
|
+
from . import Spec
|
|
403
|
+
|
|
404
|
+
trt = args.toolchain == "tensorrt"
|
|
405
|
+
wrong = ["--compile-job"] if trt else ["--precision", "--engine"]
|
|
406
|
+
for flag in wrong:
|
|
407
|
+
if getattr(args, flag[2:].replace("-", "_")) is not None:
|
|
408
|
+
print(
|
|
409
|
+
f"error: {flag} does not apply to the toolchain {args.toolchain}", file=sys.stderr
|
|
410
|
+
)
|
|
411
|
+
return 2
|
|
412
|
+
if trt and args.iterations != 2:
|
|
413
|
+
print("error: --iterations applies only to the AI Hub toolchains", file=sys.stderr)
|
|
414
|
+
return 2
|
|
415
|
+
try:
|
|
416
|
+
spec = Spec.load(args.spec)
|
|
417
|
+
with np.load(args.inputs) as z:
|
|
418
|
+
inputs = {k: z[k] for k in z.files}
|
|
419
|
+
if trt:
|
|
420
|
+
from .trt import gpu_run
|
|
421
|
+
|
|
422
|
+
gpu = gpu_run(
|
|
423
|
+
spec, args.build, args.device, inputs, args.output, args.precision, args.engine
|
|
424
|
+
)
|
|
425
|
+
else:
|
|
426
|
+
from .aihub import device_run
|
|
427
|
+
|
|
428
|
+
run = device_run(
|
|
429
|
+
spec,
|
|
430
|
+
args.build,
|
|
431
|
+
args.device,
|
|
432
|
+
inputs,
|
|
433
|
+
args.output,
|
|
434
|
+
args.toolchain,
|
|
435
|
+
compile_job=args.compile_job,
|
|
436
|
+
iterations=args.iterations,
|
|
437
|
+
)
|
|
438
|
+
except Exception as error:
|
|
439
|
+
print(f"error: {error}", file=sys.stderr)
|
|
440
|
+
return 2
|
|
441
|
+
if trt:
|
|
442
|
+
print(f"engine {gpu.engine} tensorrt {gpu.toolchain_version} on {gpu.gpu}")
|
|
443
|
+
for it, ms in enumerate(gpu.ms_per_iteration, start=1):
|
|
444
|
+
print(f"iteration {it}: {ms:.3f} ms on the device, tensorrt {gpu.toolchain_version}")
|
|
445
|
+
print(f"wrote {gpu.states} and {gpu.record}")
|
|
446
|
+
from . import default_threshold
|
|
447
|
+
|
|
448
|
+
known = spec.thresholds or default_threshold("tensorrt", gpu.toolchain_version)
|
|
449
|
+
flag = "" if known else " -t T"
|
|
450
|
+
print(
|
|
451
|
+
f"check with: firstlight check {args.spec} -i {args.inputs} --states {gpu.states}{flag}"
|
|
452
|
+
)
|
|
453
|
+
return 0
|
|
454
|
+
version = run.toolchain_version or "version not given by AI Hub"
|
|
455
|
+
print(f"compile job {run.job_ids[0]} {args.toolchain} {version} for {args.device}")
|
|
456
|
+
for it, (ms, job) in enumerate(zip(run.ms_per_iteration, run.job_ids[1:]), start=1):
|
|
457
|
+
tool = f"{args.toolchain} {version}"
|
|
458
|
+
print(f"iteration {it}: {ms:.3f} ms on the device, {tool} (inference job {job})")
|
|
459
|
+
print(f"wrote {run.states} and {run.jobs}")
|
|
460
|
+
from . import default_threshold
|
|
461
|
+
|
|
462
|
+
known = spec.thresholds or (
|
|
463
|
+
run.toolchain_version and default_threshold(args.toolchain, run.toolchain_version)
|
|
464
|
+
)
|
|
465
|
+
flag = "" if known else " -t T"
|
|
466
|
+
print(f"check with: firstlight check {args.spec} -i {args.inputs} --states {run.states}{flag}")
|
|
467
|
+
return 0
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
def _energy(args: argparse.Namespace) -> int:
|
|
471
|
+
"""Run the build on this GPU, print the energy of one iteration, and return the exit code."""
|
|
472
|
+
from . import Spec
|
|
473
|
+
|
|
474
|
+
if args.toolchain != "tensorrt":
|
|
475
|
+
print(
|
|
476
|
+
f"error: energy runs only with the toolchain tensorrt, not {args.toolchain!r}",
|
|
477
|
+
file=sys.stderr,
|
|
478
|
+
)
|
|
479
|
+
return 2
|
|
480
|
+
try:
|
|
481
|
+
from .trt import gpu_energy
|
|
482
|
+
|
|
483
|
+
spec = Spec.load(args.spec)
|
|
484
|
+
with np.load(args.inputs) as z:
|
|
485
|
+
inputs = {k: z[k] for k in z.files}
|
|
486
|
+
run = gpu_energy(spec, args.build, inputs, args.precision, args.engine, args.iterations)
|
|
487
|
+
except Exception as error:
|
|
488
|
+
print(f"error: {error}", file=sys.stderr)
|
|
489
|
+
return 2
|
|
490
|
+
print(f"engine {run.engine} tensorrt {run.toolchain_version} on {run.gpu}")
|
|
491
|
+
for r, (mj, ms, w) in enumerate(
|
|
492
|
+
zip(run.mj_per_iteration, run.ms_per_iteration, run.watts), start=1
|
|
493
|
+
):
|
|
494
|
+
print(
|
|
495
|
+
f"repeat {r}: {mj:.2f} mJ per iteration {ms:.3f} ms per iteration {w:.1f} W "
|
|
496
|
+
f"({run.iterations} iterations)"
|
|
497
|
+
)
|
|
498
|
+
mj = sorted(run.mj_per_iteration)
|
|
499
|
+
print(
|
|
500
|
+
f"energy {float(np.median(mj)):.2f} mJ per iteration, median of {len(mj)} repeats "
|
|
501
|
+
f"(spread {mj[0]:.2f} to {mj[-1]:.2f}); {float(np.median(run.ms_per_iteration)):.3f} ms, "
|
|
502
|
+
f"{float(np.median(run.watts)):.1f} W"
|
|
503
|
+
)
|
|
504
|
+
return 0
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def _repair(args: argparse.Namespace) -> int:
|
|
508
|
+
"""Continue the device run with fp32 iterations, print the accuracy, return the exit code."""
|
|
509
|
+
import onnxruntime
|
|
510
|
+
|
|
511
|
+
from . import Spec, repair
|
|
512
|
+
|
|
513
|
+
onnxruntime.set_default_logger_severity(3)
|
|
514
|
+
try:
|
|
515
|
+
spec = Spec.load(args.spec)
|
|
516
|
+
with np.load(args.inputs) as z:
|
|
517
|
+
inputs = {k: z[k] for k in z.files}
|
|
518
|
+
with np.load(args.states) as z:
|
|
519
|
+
if missing := set(spec.states) - set(z.files):
|
|
520
|
+
raise ValueError(
|
|
521
|
+
f"{args.states} has no state {sorted(missing)}. Write it with "
|
|
522
|
+
"firstlight device, which keeps the state after the last iteration."
|
|
523
|
+
)
|
|
524
|
+
states = {s: z[s] for s in spec.states}
|
|
525
|
+
given = z["predictions"] if "predictions" in z.files else None
|
|
526
|
+
answers = None
|
|
527
|
+
if args.answers:
|
|
528
|
+
with np.load(args.answers) as z:
|
|
529
|
+
answers = z[z.files[0]]
|
|
530
|
+
result = repair(spec, states, inputs, args.iterations, answers)
|
|
531
|
+
except Exception as error:
|
|
532
|
+
print(f"error: {error}", file=sys.stderr)
|
|
533
|
+
return 2
|
|
534
|
+
n = len(result.predictions[0])
|
|
535
|
+
if answers is not None:
|
|
536
|
+
if given is not None:
|
|
537
|
+
from .host import _accuracy
|
|
538
|
+
|
|
539
|
+
solved = round(_accuracy(given[-1:], answers)[0] * n)
|
|
540
|
+
print(f"device, {len(given)} iterations: {solved} of {n} correct")
|
|
541
|
+
for k, acc in enumerate(result.accuracy, start=1):
|
|
542
|
+
print(f"fp32 iteration {k}: {round(acc * n)} of {n} correct")
|
|
543
|
+
if args.output:
|
|
544
|
+
np.savez(args.output, predictions=result.predictions)
|
|
545
|
+
print(f"wrote {args.output}")
|
|
546
|
+
return 0
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
def main(argv: list[str] | None = None) -> int:
|
|
550
|
+
"""Run the command.
|
|
551
|
+
|
|
552
|
+
Parameters
|
|
553
|
+
----------
|
|
554
|
+
argv : list[str] | None
|
|
555
|
+
The arguments after the program name, or None to read them from ``sys.argv``.
|
|
556
|
+
|
|
557
|
+
Returns
|
|
558
|
+
-------
|
|
559
|
+
int
|
|
560
|
+
0 when the build passes the check, after a calibration or after a device run; 1 when
|
|
561
|
+
the build fails; 2 on an error, or when check has no threshold.
|
|
562
|
+
"""
|
|
563
|
+
argv = sys.argv[1:] if argv is None else argv
|
|
564
|
+
parser, commands = _parsers()
|
|
565
|
+
if not argv or argv[0] not in commands:
|
|
566
|
+
parser.parse_args(argv)
|
|
567
|
+
name, cmd = argv[0], commands[argv[0]]
|
|
568
|
+
if name == "bench":
|
|
569
|
+
return _bench(cmd.parse_args(argv[1:]).detector)
|
|
570
|
+
if name == "replay":
|
|
571
|
+
if cmd.parse_args(argv[1:]).what == "pricing":
|
|
572
|
+
from .price import print_replay
|
|
573
|
+
|
|
574
|
+
print_replay()
|
|
575
|
+
else:
|
|
576
|
+
_print_replay()
|
|
577
|
+
return 0
|
|
578
|
+
# parse_args on Python 3.10 drops an optional BUILD that comes after -i; this does not.
|
|
579
|
+
args = cmd.parse_intermixed_args(argv[1:])
|
|
580
|
+
if args.inputs is None:
|
|
581
|
+
args.inputs = str(Path(args.spec).parent / "inputs.npz")
|
|
582
|
+
if name == "device":
|
|
583
|
+
return _device(args)
|
|
584
|
+
if name == "energy":
|
|
585
|
+
return _energy(args)
|
|
586
|
+
if name == "repair":
|
|
587
|
+
if not (args.answers or args.output):
|
|
588
|
+
cmd.error("give --answers, -o, or both")
|
|
589
|
+
return _repair(args)
|
|
590
|
+
answer_file = getattr(args, "answers", None)
|
|
591
|
+
if name == "check" and (args.build is None) == (args.states is None):
|
|
592
|
+
cmd.error("give one BUILD or --states, not both")
|
|
593
|
+
if args.states and answer_file:
|
|
594
|
+
cmd.error("--answers needs a build to run; --states gives no answers")
|
|
595
|
+
if name == "calibrate" and not (args.build or args.states):
|
|
596
|
+
cmd.error("give at least one BUILD or --states file")
|
|
597
|
+
builds = args.build if name == "calibrate" else [args.build] if args.build else []
|
|
598
|
+
files = args.states if name == "calibrate" else [args.states] if args.states else []
|
|
599
|
+
|
|
600
|
+
import onnxruntime
|
|
601
|
+
|
|
602
|
+
from . import DEFAULTS, Spec, calibrate, check, default_threshold, host_run
|
|
603
|
+
from .check import paper_model, release_of
|
|
604
|
+
|
|
605
|
+
# ONNX Runtime 1.23.2 warns once for each unused initializer of a quantized graph (26 lines).
|
|
606
|
+
onnxruntime.set_default_logger_severity(3)
|
|
607
|
+
# Any error is exit code 2, so that a CI job can tell it from a build that fails the check.
|
|
608
|
+
# ONNX Runtime 1.23.2's load errors are not subclasses of RuntimeError, so the catch is wide.
|
|
609
|
+
try:
|
|
610
|
+
spec = Spec.load(args.spec)
|
|
611
|
+
if name == "check":
|
|
612
|
+
stored = spec.thresholds or {}
|
|
613
|
+
# With -t, the spec's thresholds do not apply: they can be from another toolchain.
|
|
614
|
+
from_spec = args.threshold is None and "cosine" in stored
|
|
615
|
+
if args.threshold is None:
|
|
616
|
+
args.threshold = stored.get("cosine")
|
|
617
|
+
found = _recorded_toolchain(args.states) if args.states else None
|
|
618
|
+
ran = found or (("onnxruntime", onnxruntime.__version__) if builds else None)
|
|
619
|
+
if from_spec and "toolchain" in stored:
|
|
620
|
+
if ran is None:
|
|
621
|
+
print(
|
|
622
|
+
f"warning: no toolchain recorded with {args.states}; its thresholds "
|
|
623
|
+
f"were set on {stored['toolchain']} {stored['version']}.",
|
|
624
|
+
file=sys.stderr,
|
|
625
|
+
)
|
|
626
|
+
elif not _same_toolchain(ran, (stored["toolchain"], stored["version"])):
|
|
627
|
+
raise ValueError(
|
|
628
|
+
f"The thresholds in {args.spec} were set on {stored['toolchain']} "
|
|
629
|
+
f"{stored['version']}, but {args.states or builds[0]} was recorded with "
|
|
630
|
+
f"{ran[0]} {ran[1]}. Run calibrate on builds of that toolchain, or give -t."
|
|
631
|
+
)
|
|
632
|
+
elif from_spec and args.states:
|
|
633
|
+
print(
|
|
634
|
+
f"warning: the thresholds in {args.spec} do not record the toolchain they "
|
|
635
|
+
"were set on, so they are not compared with the states.",
|
|
636
|
+
file=sys.stderr,
|
|
637
|
+
)
|
|
638
|
+
default = None
|
|
639
|
+
if args.threshold is None and found is not None:
|
|
640
|
+
default = default_threshold(*found)
|
|
641
|
+
if default is not None:
|
|
642
|
+
args.threshold = default.cosine
|
|
643
|
+
if paper_model(spec.graph) is None:
|
|
644
|
+
print(
|
|
645
|
+
f"note: the default threshold for {default.toolchain} {default.version} "
|
|
646
|
+
"was set on the paper's models and this graph is not one of them; "
|
|
647
|
+
"calibrate sets a threshold on your own builds.",
|
|
648
|
+
file=sys.stderr,
|
|
649
|
+
)
|
|
650
|
+
if args.threshold is None:
|
|
651
|
+
if found is not None:
|
|
652
|
+
where = (
|
|
653
|
+
f"no default threshold for {found[0]} {found[1]}, recorded with the states"
|
|
654
|
+
)
|
|
655
|
+
elif args.states:
|
|
656
|
+
where = f"no toolchain recorded with {args.states}, so no default threshold"
|
|
657
|
+
else:
|
|
658
|
+
where = "no default threshold for a build run under ONNX Runtime"
|
|
659
|
+
known = ", ".join(f"{name} {release}" for name, release in DEFAULTS)
|
|
660
|
+
raise ValueError(
|
|
661
|
+
f"The spec {args.spec} has no threshold, no -t is given, and there is {where} "
|
|
662
|
+
f"(defaults exist for {known}). Set the threshold with calibrate on builds "
|
|
663
|
+
"that you know are correct:\n "
|
|
664
|
+
f"firstlight calibrate {args.spec} -i {args.inputs} BUILD [BUILD ...] "
|
|
665
|
+
"--answers ANSWERS.npz"
|
|
666
|
+
)
|
|
667
|
+
# The stored agreement threshold applies only when both runs give answers.
|
|
668
|
+
stored_agreement = stored.get("agreement") if from_spec else None
|
|
669
|
+
if default is not None:
|
|
670
|
+
stored_agreement = default.agreement
|
|
671
|
+
with np.load(args.inputs) as z:
|
|
672
|
+
inputs = {k: z[k] for k in z.files}
|
|
673
|
+
answers = None
|
|
674
|
+
if answer_file:
|
|
675
|
+
if spec.limit is None:
|
|
676
|
+
raise ValueError(f"The spec {args.spec} gives no 'limit'; --answers needs one.")
|
|
677
|
+
with np.load(answer_file) as z:
|
|
678
|
+
answers = z[z.files[0]]
|
|
679
|
+
else:
|
|
680
|
+
spec = dataclasses.replace(spec, limit=2)
|
|
681
|
+
reference = host_run(spec, inputs, answers)
|
|
682
|
+
if getattr(args, "save_reference", None):
|
|
683
|
+
reference.save(args.save_reference, spec)
|
|
684
|
+
runs = [host_run(dataclasses.replace(spec, graph=Path(b)), inputs, answers) for b in builds]
|
|
685
|
+
read = [_read_states(f, reference.states, reference.predictions) for f in files]
|
|
686
|
+
states = [r.states for r in runs] + [r[0] for r in read]
|
|
687
|
+
scores = [_scores(s, reference.states) for s in states]
|
|
688
|
+
for (score, _), source in zip(scores, [*builds, *files]):
|
|
689
|
+
if not math.isfinite(score):
|
|
690
|
+
raise ValueError(
|
|
691
|
+
f"The cosine of {source} is {score}: its hidden state holds a value that is "
|
|
692
|
+
"not finite (nan or inf)."
|
|
693
|
+
)
|
|
694
|
+
predictions = [r.predictions for r in runs] + [r[1] for r in read]
|
|
695
|
+
agreements = [_agreement(reference.predictions, p) for p in predictions]
|
|
696
|
+
if getattr(args, "agreement", None) is not None and agreements[0] is None:
|
|
697
|
+
raise ValueError(
|
|
698
|
+
"--agreement needs the answers of the build: run the build with a graph that "
|
|
699
|
+
"gives the output 'logits', or give the array 'predictions' in --states."
|
|
700
|
+
)
|
|
701
|
+
except Exception as error:
|
|
702
|
+
print(f"error: {error}", file=sys.stderr)
|
|
703
|
+
return 2
|
|
704
|
+
n = len(reference.states[1])
|
|
705
|
+
if name == "calibrate":
|
|
706
|
+
sources = [*builds, *files]
|
|
707
|
+
shown = ["n/a" if a is None else f"{a:.4f}" for a in agreements]
|
|
708
|
+
labels = ["correct"] * len(scores)
|
|
709
|
+
if answers is not None:
|
|
710
|
+
base = round(reference.accuracy[-1] * n)
|
|
711
|
+
solved = [round(r.accuracy[-1] * n) for r in runs]
|
|
712
|
+
labels = [_label(k, base) for k in solved]
|
|
713
|
+
for (score, _), a, k, label, source in zip(scores, shown, solved, labels, sources):
|
|
714
|
+
print(f"cosine {score:.4f} agreement {a} accuracy {k} of {n} {label} {source}")
|
|
715
|
+
for k, label, source in zip(solved, labels, sources):
|
|
716
|
+
if label != "correct":
|
|
717
|
+
print(
|
|
718
|
+
f"left out {source} ({label}: accuracy {k} of {n}, below "
|
|
719
|
+
f"{CORRECT_SHARE:.0%} of the reference's {base} of {n})"
|
|
720
|
+
)
|
|
721
|
+
else:
|
|
722
|
+
for (score, _), a, source in zip(scores, shown, sources):
|
|
723
|
+
print(f"cosine {score:.4f} agreement {a} {source}")
|
|
724
|
+
if "correct" not in labels:
|
|
725
|
+
print(
|
|
726
|
+
f"error: no build is correct by its accuracy: {', '.join(sources)}",
|
|
727
|
+
file=sys.stderr,
|
|
728
|
+
)
|
|
729
|
+
return 2
|
|
730
|
+
kept = [score for (score, _), label in zip(scores, labels) if label == "correct"]
|
|
731
|
+
agreed = [a for a, label in zip(agreements, labels) if label == "correct"]
|
|
732
|
+
low = calibrate((score, "correct") for score in kept)
|
|
733
|
+
high, count = max(kept), len(kept)
|
|
734
|
+
warnings = []
|
|
735
|
+
command = f"firstlight check {args.spec} BUILD -i {args.inputs}"
|
|
736
|
+
if None in agreed and any(a is not None for a in agreed):
|
|
737
|
+
warnings.append(
|
|
738
|
+
f"no output agreement threshold: {agreed.count(None)} of the {count} correct "
|
|
739
|
+
"builds give no answers (a --states file without the array predictions)."
|
|
740
|
+
)
|
|
741
|
+
if None not in agreed:
|
|
742
|
+
a_low, a_high = min(agreed), max(agreed)
|
|
743
|
+
# Rounded down, as the threshold below.
|
|
744
|
+
a_threshold = math.floor(a_low * 1e4) / 1e4
|
|
745
|
+
command += f" --agreement {a_threshold:.4f}"
|
|
746
|
+
print(
|
|
747
|
+
f"agreement threshold {a_threshold:.4f} (builds: {count}; "
|
|
748
|
+
f"lowest {a_low:.6f}, highest {a_high:.6f}; iteration 2, {n} inputs)"
|
|
749
|
+
)
|
|
750
|
+
# No spread warning for agreement: correct builds often agree on every position, so a
|
|
751
|
+
# narrow spread is normal for it and the warning would fire on most calibrations.
|
|
752
|
+
if a_low < LOW_COSINE:
|
|
753
|
+
warnings.append(
|
|
754
|
+
f"the lowest output agreement, {a_low:.6f}, is below {LOW_COSINE}. Confirm "
|
|
755
|
+
"the accuracy of that build with check --answers."
|
|
756
|
+
)
|
|
757
|
+
# Rounded down, so that the printed threshold passes every build it came from.
|
|
758
|
+
threshold = math.floor(low * 1e4) / 1e4
|
|
759
|
+
raw = json.loads(Path(args.spec).read_text())
|
|
760
|
+
raw["thresholds"] = {"cosine": threshold}
|
|
761
|
+
if None not in agreed:
|
|
762
|
+
raw["thresholds"]["agreement"] = a_threshold
|
|
763
|
+
how = ["run"] * len(builds) + ["states"] * len(files)
|
|
764
|
+
recorded = {
|
|
765
|
+
found
|
|
766
|
+
for f, lab in zip(files, labels[len(builds) :])
|
|
767
|
+
if lab == "correct" and (found := _recorded_toolchain(f)) is not None
|
|
768
|
+
}
|
|
769
|
+
if "correct" in labels[: len(builds)]:
|
|
770
|
+
recorded.add(("onnxruntime", onnxruntime.__version__))
|
|
771
|
+
names = {name for name, _ in recorded}
|
|
772
|
+
releases = {v if name == "onnxruntime" else release_of(v) for name, v in recorded}
|
|
773
|
+
if len(names) > 1 or (names != {"onnxruntime"} and len(releases) > 1):
|
|
774
|
+
print(
|
|
775
|
+
"error: the correct builds were recorded with different toolchain versions: "
|
|
776
|
+
+ ", ".join(f"{name} {v}" for name, v in sorted(recorded)),
|
|
777
|
+
file=sys.stderr,
|
|
778
|
+
)
|
|
779
|
+
return 2
|
|
780
|
+
if recorded:
|
|
781
|
+
versions = sorted({v for _, v in recorded})
|
|
782
|
+
raw["thresholds"]["toolchain"] = names.pop()
|
|
783
|
+
raw["thresholds"]["version"] = (
|
|
784
|
+
versions[0] if len(versions) == 1 else release_of(versions[0])
|
|
785
|
+
)
|
|
786
|
+
raw["thresholds"]["set_on"] = [
|
|
787
|
+
{"file": f, "how": h} for f, h, lab in zip(sources, how, labels) if lab == "correct"
|
|
788
|
+
]
|
|
789
|
+
try:
|
|
790
|
+
Path(args.spec).write_text(json.dumps(raw, indent=1) + "\n")
|
|
791
|
+
except OSError as error:
|
|
792
|
+
print(f"error: {error}", file=sys.stderr)
|
|
793
|
+
return 2
|
|
794
|
+
print(
|
|
795
|
+
f"threshold {threshold:.4f} (builds: {count}; lowest {low:.6f}, "
|
|
796
|
+
f"highest {high:.6f}; iteration 2, {n} inputs) written to {args.spec}"
|
|
797
|
+
)
|
|
798
|
+
print(f"check with: {command} -t {threshold:.4f}")
|
|
799
|
+
risk = (
|
|
800
|
+
"The threshold is only as wide as these builds: a correct build that differs more "
|
|
801
|
+
"from fp32 than any of them can fail. See docs/reference.md#calibrate."
|
|
802
|
+
)
|
|
803
|
+
if count < FEW_BUILDS:
|
|
804
|
+
noun = "build" if count == 1 else "builds"
|
|
805
|
+
warnings.append(f"only {count} {noun} (fewer than {FEW_BUILDS}). {risk}")
|
|
806
|
+
if high - low < NARROW_SPREAD:
|
|
807
|
+
warnings.append(
|
|
808
|
+
f"the cosines lie within {high - low:.4f} of each other "
|
|
809
|
+
f"(less than {NARROW_SPREAD}). {risk}"
|
|
810
|
+
)
|
|
811
|
+
if low < LOW_COSINE:
|
|
812
|
+
warnings.append(
|
|
813
|
+
f"the lowest cosine, {low:.6f}, is below {LOW_COSINE}. A build this far from fp32 "
|
|
814
|
+
"is rarely correct. Confirm its accuracy with check --answers before you use "
|
|
815
|
+
"this threshold."
|
|
816
|
+
)
|
|
817
|
+
for warning in warnings:
|
|
818
|
+
print(f"warning: {warning}", file=sys.stderr)
|
|
819
|
+
return 0
|
|
820
|
+
score, line = scores[0]
|
|
821
|
+
agreement, agree_at = agreements[0], args.agreement
|
|
822
|
+
if agree_at is None and agreement is not None:
|
|
823
|
+
agree_at = stored_agreement
|
|
824
|
+
fails, label = [], None
|
|
825
|
+
if not check(score, args.threshold).passed:
|
|
826
|
+
fails.append("cosine")
|
|
827
|
+
if agree_at is not None and agreement < agree_at:
|
|
828
|
+
fails.append("output agreement")
|
|
829
|
+
if answers is not None:
|
|
830
|
+
solved = [round(r.accuracy[-1] * n) for r in (reference, runs[0])]
|
|
831
|
+
label = _label(solved[1], solved[0])
|
|
832
|
+
if label == "broken":
|
|
833
|
+
fails.append("accuracy")
|
|
834
|
+
first = f"cosine {score:.4f} threshold {args.threshold:.4f} margin "
|
|
835
|
+
first += f"{score - args.threshold:+.4f} (iteration 2, {n} inputs)"
|
|
836
|
+
why = f" fails on: {', '.join(fails)}" if fails else ""
|
|
837
|
+
why = why or (" accuracy: degraded" if label == "degraded" else "")
|
|
838
|
+
print(f"{'fail' if fails else 'pass'} {first}{why}")
|
|
839
|
+
print(line)
|
|
840
|
+
if agreement is None:
|
|
841
|
+
print(
|
|
842
|
+
"output agreement not available (no answers of the build: no 'logits', or no "
|
|
843
|
+
"'predictions' in --states)"
|
|
844
|
+
)
|
|
845
|
+
else:
|
|
846
|
+
agree = f"output agreement {agreement:.4f} (iteration 2, all positions)"
|
|
847
|
+
if agree_at is not None:
|
|
848
|
+
agree += f" threshold {agree_at:.4f} margin {agreement - agree_at:+.4f}"
|
|
849
|
+
print(agree)
|
|
850
|
+
if answers is not None:
|
|
851
|
+
print(
|
|
852
|
+
f"accuracy at iteration {spec.limit}: reference {solved[0]} of {n}, "
|
|
853
|
+
f"build {solved[1]} of {n} ({label})"
|
|
854
|
+
)
|
|
855
|
+
if default is not None:
|
|
856
|
+
agree = (
|
|
857
|
+
"" if default.agreement is None else f", agreement threshold {default.agreement:.4f}"
|
|
858
|
+
)
|
|
859
|
+
print(
|
|
860
|
+
f"threshold {default.cosine:.4f}{agree}: default for {default.toolchain} "
|
|
861
|
+
f"{default.version} (set on {default.source})"
|
|
862
|
+
)
|
|
863
|
+
if from_spec:
|
|
864
|
+
on = ", ".join(f"{b['file']} ({b['how']})" for b in stored.get("set_on", []))
|
|
865
|
+
print(f"thresholds from {args.spec}, set on: {on or 'not recorded'}")
|
|
866
|
+
return 1 if fails else 0
|
|
867
|
+
|
|
868
|
+
|
|
869
|
+
if __name__ == "__main__":
|
|
870
|
+
sys.exit(main())
|