torchstack64 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- torchstack64/__init__.py +101 -0
- torchstack64/artifacts/__init__.py +78 -0
- torchstack64/artifacts/bundle/__init__.py +50 -0
- torchstack64/artifacts/bundle/files.py +106 -0
- torchstack64/artifacts/bundle/folder.py +385 -0
- torchstack64/artifacts/bundle/tensors.py +75 -0
- torchstack64/artifacts/code/__init__.py +103 -0
- torchstack64/artifacts/code/copy.py +149 -0
- torchstack64/artifacts/code/importing.py +204 -0
- torchstack64/artifacts/code/inspection.py +351 -0
- torchstack64/artifacts/code/notebook.py +373 -0
- torchstack64/artifacts/code/objects.py +401 -0
- torchstack64/artifacts/loading.py +117 -0
- torchstack64/artifacts/manifest.py +220 -0
- torchstack64/artifacts/predictor/__init__.py +45 -0
- torchstack64/artifacts/predictor/bundle_predictor.py +193 -0
- torchstack64/artifacts/predictor/output_reading.py +96 -0
- torchstack64/artifacts/predictor/torch_classifier.py +106 -0
- torchstack64/artifacts/predictor/torch_predictor.py +247 -0
- torchstack64/artifacts/proofs/__init__.py +83 -0
- torchstack64/artifacts/proofs/answers.py +159 -0
- torchstack64/artifacts/proofs/example.py +248 -0
- torchstack64/artifacts/proofs/modules.py +260 -0
- torchstack64/artifacts/proofs/suite.py +560 -0
- torchstack64/artifacts/saving.py +461 -0
- torchstack64/artifacts/sources.py +166 -0
- torchstack64/callbacks/__init__.py +22 -0
- torchstack64/callbacks/base.py +43 -0
- torchstack64/callbacks/checkpointing.py +40 -0
- torchstack64/callbacks/history_plot.py +160 -0
- torchstack64/callbacks/mlflow_logger.py +217 -0
- torchstack64/callbacks/model_checks.py +295 -0
- torchstack64/callbacks/progress.py +132 -0
- torchstack64/callbacks/stack.py +85 -0
- torchstack64/core/__init__.py +59 -0
- torchstack64/core/errors.py +121 -0
- torchstack64/core/evaluation.py +52 -0
- torchstack64/core/extras.py +36 -0
- torchstack64/core/inference.py +42 -0
- torchstack64/core/labels.py +201 -0
- torchstack64/core/logging.py +110 -0
- torchstack64/data/__init__.py +10 -0
- torchstack64/data/base.py +256 -0
- torchstack64/data/labeled.py +128 -0
- torchstack64/devices/__init__.py +38 -0
- torchstack64/devices/hardware.py +43 -0
- torchstack64/devices/selection.py +82 -0
- torchstack64/metrics/__init__.py +21 -0
- torchstack64/metrics/classification.py +93 -0
- torchstack64/py.typed +0 -0
- torchstack64/training/__init__.py +83 -0
- torchstack64/training/config/__init__.py +17 -0
- torchstack64/training/config/fit.py +60 -0
- torchstack64/training/config/monitor.py +63 -0
- torchstack64/training/config/optim.py +49 -0
- torchstack64/training/config/params.py +55 -0
- torchstack64/training/config/search.py +49 -0
- torchstack64/training/results/__init__.py +19 -0
- torchstack64/training/results/fit.py +37 -0
- torchstack64/training/results/history.py +74 -0
- torchstack64/training/results/predictions.py +81 -0
- torchstack64/training/runtime/__init__.py +18 -0
- torchstack64/training/runtime/precision.py +139 -0
- torchstack64/training/runtime/randomness.py +142 -0
- torchstack64/training/runtime/runtime.py +75 -0
- torchstack64/training/runtime/transfer.py +49 -0
- torchstack64/training/runtime/weights.py +43 -0
- torchstack64/training/task/__init__.py +11 -0
- torchstack64/training/task/optim/__init__.py +9 -0
- torchstack64/training/task/optim/optimization.py +70 -0
- torchstack64/training/task/optim/schedules.py +27 -0
- torchstack64/training/task/protocol.py +58 -0
- torchstack64/training/task/supervised.py +113 -0
- torchstack64/training/trainer/__init__.py +8 -0
- torchstack64/training/trainer/adapters.py +122 -0
- torchstack64/training/trainer/contracts.py +81 -0
- torchstack64/training/trainer/hooks.py +47 -0
- torchstack64/training/trainer/meters.py +150 -0
- torchstack64/training/trainer/state.py +117 -0
- torchstack64/training/trainer/trainer.py +586 -0
- torchstack64/training/tuner/__init__.py +3 -0
- torchstack64/training/tuner/callback.py +38 -0
- torchstack64/training/tuner/space.py +82 -0
- torchstack64/training/tuner/tuner.py +137 -0
- torchstack64/utils/__init__.py +21 -0
- torchstack64/utils/logging.py +85 -0
- torchstack64/utils/mlflow.py +127 -0
- torchstack64-0.3.0.dist-info/METADATA +622 -0
- torchstack64-0.3.0.dist-info/RECORD +92 -0
- torchstack64-0.3.0.dist-info/WHEEL +5 -0
- torchstack64-0.3.0.dist-info/licenses/LICENSE +21 -0
- torchstack64-0.3.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,560 @@
|
|
|
1
|
+
"""The proofs a bundle passes before it exists, in their order, and the check every load makes.
|
|
2
|
+
|
|
3
|
+
`save_bundle` writes the bundle in a staging folder, loads it back from there as a service will, and proves
|
|
4
|
+
the loaded predictor against the trained model on the example (a few validation rows, `example.py`):
|
|
5
|
+
|
|
6
|
+
| # | Proof | What it catches |
|
|
7
|
+
|---|---|---|
|
|
8
|
+
| 1 | `determinism` | something random left on when serving (`F.dropout` without `training=`) |
|
|
9
|
+
| 2 | `preparation` | a preparation whose state did not travel: read back, it prepares differently |
|
|
10
|
+
| 3 | `round_trip` | a network that answers from something that did not travel with it |
|
|
11
|
+
| 4 | `outputs` | a softmax or a sigmoid read twice, logits read as probabilities, columns that do not fit |
|
|
12
|
+
| 5 | `answers` | what `pack` or `unpack` lost, for a model the library does not run (`trained_predict`) |
|
|
13
|
+
| 6 | `batch` | an answer that depends on the rest of its call (a mask, padding, a BatchNorm) |
|
|
14
|
+
| 7 | `contract` | one answer per input, labels in the schema, probabilities that sum to 1 |
|
|
15
|
+
| 8 | `labels` | a schema whose classes are not in the order training encoded them |
|
|
16
|
+
| 9 | `units` | a regression that answers in the units the loss saw, not the labels' |
|
|
17
|
+
|
|
18
|
+
They run in that order and stop at the first refusal, which is a `ProofError` naming the proof, the first
|
|
19
|
+
example that differs and by how much. Nothing is published before the last one passes.
|
|
20
|
+
|
|
21
|
+
Every load then answers the example again, and compares with what the bundle answered when it was written.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import contextlib
|
|
27
|
+
import json
|
|
28
|
+
import logging
|
|
29
|
+
import math
|
|
30
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
31
|
+
from dataclasses import dataclass, field
|
|
32
|
+
from importlib import metadata
|
|
33
|
+
from typing import Any
|
|
34
|
+
|
|
35
|
+
from torchstack64.artifacts.bundle import ArtifactBundle, BundleFile
|
|
36
|
+
from torchstack64.artifacts.manifest import ProofRecord
|
|
37
|
+
from torchstack64.artifacts.proofs.answers import Difference, answers_of, compare_answers, rounded
|
|
38
|
+
from torchstack64.artifacts.proofs.example import (
|
|
39
|
+
EXAMPLE_FILE,
|
|
40
|
+
Example,
|
|
41
|
+
as_json,
|
|
42
|
+
example_file,
|
|
43
|
+
read_example_file,
|
|
44
|
+
)
|
|
45
|
+
from torchstack64.artifacts.proofs.modules import (
|
|
46
|
+
evaluated,
|
|
47
|
+
exact_arithmetic,
|
|
48
|
+
feed,
|
|
49
|
+
floating_dtype_of,
|
|
50
|
+
largest_difference,
|
|
51
|
+
probability_defect,
|
|
52
|
+
sum_tolerance,
|
|
53
|
+
)
|
|
54
|
+
from torchstack64.core import BundleIntegrityError, LabelSchema, ProofError
|
|
55
|
+
|
|
56
|
+
logger = logging.getLogger(__name__)
|
|
57
|
+
|
|
58
|
+
PROOF_ORDER = (
|
|
59
|
+
"determinism",
|
|
60
|
+
"preparation",
|
|
61
|
+
"round_trip",
|
|
62
|
+
"outputs",
|
|
63
|
+
"answers",
|
|
64
|
+
"batch",
|
|
65
|
+
"contract",
|
|
66
|
+
"labels",
|
|
67
|
+
"units",
|
|
68
|
+
)
|
|
69
|
+
"""Every proof's name, as the manifest records it, in the order they run."""
|
|
70
|
+
|
|
71
|
+
PREPARED_ATOL, PREPARED_RTOL = 1e-6, 1e-5 # a preparation is the same arithmetic on the same data
|
|
72
|
+
PROBABILITY_SUM_ATOL = 1e-4
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass(frozen=True, slots=True)
|
|
76
|
+
class Subject:
|
|
77
|
+
"""What the proofs need to know about the model whose bundle they prove, given by `save_bundle`.
|
|
78
|
+
|
|
79
|
+
`name` is the predictor's class, for the messages; `network` the trained PyTorch network, for a bundle
|
|
80
|
+
the library runs itself; `reading` how its outputs are read, when the library reads them (a classifier's
|
|
81
|
+
derived `predict_proba`); `trained` what the trained model answers (`predict`, and `predict_proba` when
|
|
82
|
+
the class says those), for one the library does not run.
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
name: str
|
|
86
|
+
schema: LabelSchema | None
|
|
87
|
+
trained: Mapping[str, Sequence[Any]] | None = None
|
|
88
|
+
batch_dependent: bool = False
|
|
89
|
+
network: Any = None
|
|
90
|
+
reading: Any = None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass(slots=True)
|
|
94
|
+
class Proved:
|
|
95
|
+
"""What the proofs on the example found: the record for the manifest, the files they add to the bundle
|
|
96
|
+
(the example and its answers), and the accuracy the bundle reached on the example."""
|
|
97
|
+
|
|
98
|
+
record: ProofRecord
|
|
99
|
+
files: dict[str, BundleFile] = field(default_factory=dict)
|
|
100
|
+
accuracy: float | None = None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def shown_names(names: Sequence[str], *, last: str = ", ") -> str:
|
|
104
|
+
"""`determinism, outputs, round trip`: proof names as a sentence shows them; `last=" and "` joins the last
|
|
105
|
+
two with a word."""
|
|
106
|
+
shown = [name.replace("_", " ") for name in names]
|
|
107
|
+
return ", ".join(shown[:-1]) + last + shown[-1] if len(shown) > 1 else "".join(shown)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def ordered(names: Sequence[str]) -> tuple[str, ...]:
|
|
111
|
+
return tuple(name for name in PROOF_ORDER if name in set(names))
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def prove_on_example(
|
|
115
|
+
staged: ArtifactBundle,
|
|
116
|
+
*,
|
|
117
|
+
load: Callable[[ArtifactBundle], Any],
|
|
118
|
+
subject: Subject,
|
|
119
|
+
example: Example,
|
|
120
|
+
atol: float,
|
|
121
|
+
device: str,
|
|
122
|
+
passed: Sequence[str] = (),
|
|
123
|
+
skipped: Mapping[str, str] | None = None,
|
|
124
|
+
) -> Proved:
|
|
125
|
+
"""Loads the staged bundle with `load` and proves it on `example`, in order; `passed` and `skipped`
|
|
126
|
+
are what the proofs before writing found. Raises `ProofError` at the first refusal."""
|
|
127
|
+
done, left = list(passed), dict(skipped or {})
|
|
128
|
+
context = exact_arithmetic(device) if subject.network is not None else contextlib.nullcontext()
|
|
129
|
+
with context:
|
|
130
|
+
predictor = load(staged)
|
|
131
|
+
answers = _determinism(predictor, example, subject, atol)
|
|
132
|
+
done.append("determinism")
|
|
133
|
+
if subject.network is not None:
|
|
134
|
+
prepared = _preparation(predictor, example)
|
|
135
|
+
done.append("preparation")
|
|
136
|
+
_round_trip(predictor, prepared, subject, atol)
|
|
137
|
+
done.append("round_trip")
|
|
138
|
+
if subject.reading is not None:
|
|
139
|
+
_outputs(predictor, prepared, subject)
|
|
140
|
+
done.append("outputs")
|
|
141
|
+
else:
|
|
142
|
+
reason = "a model of its own class: the library does not run it"
|
|
143
|
+
left.update({name: reason for name in ("preparation", "round_trip")})
|
|
144
|
+
if subject.trained is not None:
|
|
145
|
+
_answers(answers, subject, atol)
|
|
146
|
+
done.append("answers")
|
|
147
|
+
else:
|
|
148
|
+
left["answers"] = "the library ran the network itself"
|
|
149
|
+
if subject.batch_dependent:
|
|
150
|
+
left["batch"] = (
|
|
151
|
+
"batch_dependent = True: by the class's own declaration, an answer depends on its call"
|
|
152
|
+
)
|
|
153
|
+
else:
|
|
154
|
+
_batch(predictor, example, answers, subject, atol)
|
|
155
|
+
done.append("batch")
|
|
156
|
+
_contract(answers, example, subject)
|
|
157
|
+
done.append("contract")
|
|
158
|
+
accuracy = None
|
|
159
|
+
if subject.schema is not None:
|
|
160
|
+
left["units"] = "the bundle answers classes"
|
|
161
|
+
accuracy, why = _labels(answers, example, subject)
|
|
162
|
+
if why is None:
|
|
163
|
+
done.append("labels")
|
|
164
|
+
elif "labels" not in done:
|
|
165
|
+
left["labels"] = why
|
|
166
|
+
else:
|
|
167
|
+
left["labels"] = "the bundle answers no classes"
|
|
168
|
+
why = _units(answers, example, subject)
|
|
169
|
+
if why is None:
|
|
170
|
+
done.append("units")
|
|
171
|
+
else:
|
|
172
|
+
left["units"] = why
|
|
173
|
+
del predictor # nothing of the staged bundle stays open when it is moved into place
|
|
174
|
+
record = ProofRecord(
|
|
175
|
+
passed=ordered(done),
|
|
176
|
+
skipped={name: reason for name, reason in left.items() if name not in done},
|
|
177
|
+
example=EXAMPLE_FILE,
|
|
178
|
+
batch_dependent=subject.batch_dependent,
|
|
179
|
+
device=device,
|
|
180
|
+
)
|
|
181
|
+
files = {"example": BundleFile.text(EXAMPLE_FILE, example_file(example.inputs, answers))}
|
|
182
|
+
return Proved(record, files, accuracy)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
# -- each proof -------------------------------------------------------------------------------------------
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _determinism(predictor: Any, example: Example, subject: Subject, atol: float) -> dict[str, list[Any]]:
|
|
189
|
+
first = _answering(predictor, example.inputs, subject)
|
|
190
|
+
second = _answering(predictor, example.inputs, subject)
|
|
191
|
+
difference = compare_answers(first, second, atol=atol, schema=subject.schema)
|
|
192
|
+
if difference is not None:
|
|
193
|
+
raise ProofError(
|
|
194
|
+
f"{subject.name} answers the same example differently twice, in evaluation mode "
|
|
195
|
+
f"({difference.describe(reference='the first time', found='the second time')}): something random "
|
|
196
|
+
"is on at inference (F.dropout without training=self.training, a sampling step). The other "
|
|
197
|
+
"proofs did not run, since they compare answers",
|
|
198
|
+
proof="determinism",
|
|
199
|
+
example=difference.example,
|
|
200
|
+
)
|
|
201
|
+
return first
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _answering(predictor: Any, inputs: Sequence[Any], subject: Subject) -> dict[str, list[Any]]:
|
|
205
|
+
try:
|
|
206
|
+
return answers_of(predictor, inputs)
|
|
207
|
+
except ValueError as error:
|
|
208
|
+
if "JSON cannot hold" not in str(error):
|
|
209
|
+
raise
|
|
210
|
+
raise ProofError(
|
|
211
|
+
f"{subject.name}'s answers must be what JSON holds, as a service sends them: {error}",
|
|
212
|
+
proof="contract",
|
|
213
|
+
) from None
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _preparation(predictor: Any, example: Example) -> Any:
|
|
217
|
+
prepared = predictor.prepare(list(example.inputs))
|
|
218
|
+
difference = largest_difference(example.prepared, prepared, atol=PREPARED_ATOL, rtol=PREPARED_RTOL)
|
|
219
|
+
if difference is not None:
|
|
220
|
+
raise ProofError(
|
|
221
|
+
"the preparation read back from the bundle does not give what the preparation of this process "
|
|
222
|
+
f"gives for the same inputs: {describe_difference(difference, 'here', 'from the bundle')}. "
|
|
223
|
+
"What a preparation learned must travel inside it: an object whose pickling leaves part of its "
|
|
224
|
+
"state out (a __getstate__), or a function that reads a value kept outside it, serves "
|
|
225
|
+
"something else. Keep the state in the object (functools.partial(encode, vocabulary=...))",
|
|
226
|
+
proof="preparation",
|
|
227
|
+
example=difference.get("example"),
|
|
228
|
+
)
|
|
229
|
+
return prepared
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _round_trip(predictor: Any, prepared: Any, subject: Subject, atol: float) -> None:
|
|
233
|
+
with evaluated(subject.network):
|
|
234
|
+
trained = feed(subject.network, prepared)
|
|
235
|
+
served = feed(predictor.network, prepared)
|
|
236
|
+
difference = largest_difference(trained, served, atol=atol)
|
|
237
|
+
if difference is not None:
|
|
238
|
+
where = describe_difference(difference, "the trained network gives", "the bundle gives")
|
|
239
|
+
raise ProofError(
|
|
240
|
+
"the network read back from the bundle answers differently from the trained one, on the same "
|
|
241
|
+
f"prepared example ({where}): something it computes with did not travel with it, such as an "
|
|
242
|
+
"attribute its pickling leaves out (a __getstate__), a global variable, or a file. If the "
|
|
243
|
+
f"difference is the arithmetic of a GPU, raise atol (now {atol:g})",
|
|
244
|
+
proof="round_trip",
|
|
245
|
+
example=difference.get("example"),
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _outputs(predictor: Any, prepared: Any, subject: Subject) -> None:
|
|
250
|
+
outputs = feed(predictor.network, prepared)
|
|
251
|
+
reading = subject.reading
|
|
252
|
+
assert subject.schema is not None
|
|
253
|
+
reading.probabilities(outputs, subject.schema, subject=subject.name) # the columns fit the schema
|
|
254
|
+
defect = probability_defect(outputs, atol=PROBABILITY_SUM_ATOL)
|
|
255
|
+
if reading.outputs == "probabilities":
|
|
256
|
+
if defect is not None:
|
|
257
|
+
raise ProofError(
|
|
258
|
+
"the bundle reads the network's outputs as probabilities (outputs='probabilities'), and on "
|
|
259
|
+
f"the example they are not: {defect}. The network answers logits, or the log of "
|
|
260
|
+
"probabilities: read them as logits, which is what save_bundle does unless outputs= says "
|
|
261
|
+
"otherwise",
|
|
262
|
+
proof="outputs",
|
|
263
|
+
)
|
|
264
|
+
return
|
|
265
|
+
if defect is not None:
|
|
266
|
+
return
|
|
267
|
+
if outputs.dim() == 1 or outputs.shape[1] == 1:
|
|
268
|
+
raise ProofError(
|
|
269
|
+
"every output of the network on the example is in [0, 1], and the bundle reads them as logits: "
|
|
270
|
+
"the network ends in a sigmoid, and a second one would put every probability between 0.5 and "
|
|
271
|
+
"0.73. Pass outputs='probabilities' to save_bundle. (A network that does answer "
|
|
272
|
+
"logits gives the negatives logits below 0 once it separates the classes, and this one does not "
|
|
273
|
+
"yet.)",
|
|
274
|
+
proof="outputs",
|
|
275
|
+
)
|
|
276
|
+
raise ProofError(
|
|
277
|
+
"the network's outputs on the example look like probabilities (every row is in [0, 1] and sums to "
|
|
278
|
+
"1), and the bundle reads them as logits: the network ends in a softmax, and a second one would "
|
|
279
|
+
"flatten every row. Pass outputs='probabilities' to save_bundle",
|
|
280
|
+
proof="outputs",
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _answers(answers: dict[str, list[Any]], subject: Subject, atol: float) -> None:
|
|
285
|
+
trained = subject.trained or {}
|
|
286
|
+
reference = {key: as_json(list(value), f"the trained model's {key}") for key, value in trained.items()}
|
|
287
|
+
difference = compare_answers(reference, answers, atol=atol, schema=subject.schema)
|
|
288
|
+
if difference is not None:
|
|
289
|
+
rows = len(answers["predict"])
|
|
290
|
+
where = difference.describe(reference="from the trained model", found="from the bundle")
|
|
291
|
+
raise ProofError(
|
|
292
|
+
f"the bundle answers {difference.count} of the {rows} examples differently from the trained "
|
|
293
|
+
f"model (trained_predict): {where}. The bundle lost something in pack or unpack, or prepares the "
|
|
294
|
+
"inputs differently from training",
|
|
295
|
+
proof="answers",
|
|
296
|
+
example=difference.example,
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _batch(
|
|
301
|
+
predictor: Any, example: Example, answers: dict[str, list[Any]], subject: Subject, atol: float
|
|
302
|
+
) -> None:
|
|
303
|
+
alone: dict[str, list[Any]] = {part: [] for part in answers}
|
|
304
|
+
for item in example.inputs:
|
|
305
|
+
one = answers_of(predictor, [item])
|
|
306
|
+
for part in alone:
|
|
307
|
+
alone[part].extend(one.get(part, []))
|
|
308
|
+
difference = compare_answers(alone, answers, atol=atol, schema=subject.schema)
|
|
309
|
+
if difference is not None:
|
|
310
|
+
raise ProofError(
|
|
311
|
+
f"the answers depend on the rest of the call: example {difference.example} gets "
|
|
312
|
+
f"{rounded(difference.reference)!r} alone, and {rounded(difference.found)!r} inside the call of "
|
|
313
|
+
f"{len(example)}. "
|
|
314
|
+
"The usual causes are a mask that does not reach the network, padding on the side the network "
|
|
315
|
+
"reads, a normalization fitted on the request itself, a BatchNorm in training mode, or a call "
|
|
316
|
+
"reordered and not put back. If the model depends on the call on purpose, pass "
|
|
317
|
+
"batch_dependent=True to save_bundle",
|
|
318
|
+
proof="batch",
|
|
319
|
+
example=difference.example,
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _contract(answers: dict[str, list[Any]], example: Example, subject: Subject) -> None:
|
|
324
|
+
rows, schema = len(example), subject.schema
|
|
325
|
+
predicted = answers["predict"]
|
|
326
|
+
if len(predicted) != rows:
|
|
327
|
+
raise ProofError(f"{subject.name} gave {len(predicted)} answers for {rows} inputs", proof="contract")
|
|
328
|
+
if schema is not None:
|
|
329
|
+
try:
|
|
330
|
+
schema.encode(predicted)
|
|
331
|
+
except ValueError as error:
|
|
332
|
+
raise ProofError(
|
|
333
|
+
f"{subject.name} answers outside its schema: {error}", proof="contract"
|
|
334
|
+
) from None
|
|
335
|
+
tolerance = (
|
|
336
|
+
PROBABILITY_SUM_ATOL
|
|
337
|
+
if subject.network is None
|
|
338
|
+
else sum_tolerance(floating_dtype_of(subject.network), PROBABILITY_SUM_ATOL)
|
|
339
|
+
)
|
|
340
|
+
for index, row in enumerate(answers.get("predict_proba", [])):
|
|
341
|
+
values = row if isinstance(row, list) else [row]
|
|
342
|
+
if not all(isinstance(value, int | float) and not isinstance(value, bool) for value in values):
|
|
343
|
+
raise ProofError(
|
|
344
|
+
f"row {index} of probabilities is {row!r}, not numbers", proof="contract", example=index
|
|
345
|
+
)
|
|
346
|
+
if schema is not None and len(values) != len(schema.classes):
|
|
347
|
+
raise ProofError(
|
|
348
|
+
f"row {index} has {len(values)} probabilities for the {len(schema.classes)} classes "
|
|
349
|
+
f"{schema.classes}: predict_proba gives one column per class, in the schema's order",
|
|
350
|
+
proof="contract",
|
|
351
|
+
example=index,
|
|
352
|
+
)
|
|
353
|
+
if not all(0.0 <= value <= 1.0 for value in values):
|
|
354
|
+
raise ProofError(
|
|
355
|
+
f"row {index} has probabilities outside [0, 1]: {values}", proof="contract", example=index
|
|
356
|
+
)
|
|
357
|
+
if not math.isclose(sum(values), 1.0, abs_tol=tolerance):
|
|
358
|
+
raise ProofError(
|
|
359
|
+
f"row {index} of probabilities sums to {sum(values)}, not 1", proof="contract", example=index
|
|
360
|
+
)
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _labels(
|
|
364
|
+
answers: dict[str, list[Any]], example: Example, subject: Subject
|
|
365
|
+
) -> tuple[float | None, str | None]:
|
|
366
|
+
"""The labels proof (`None` when it ran), and the accuracy on the example when the labels are known."""
|
|
367
|
+
schema = subject.schema
|
|
368
|
+
assert schema is not None
|
|
369
|
+
labels, targets = example.labels, example.targets
|
|
370
|
+
if labels is None or targets is None:
|
|
371
|
+
return None, "no labels and targets in the example"
|
|
372
|
+
accuracy = sum(a == b for a, b in zip(answers["predict"], labels, strict=True)) / len(labels)
|
|
373
|
+
encoded = schema.encode(labels)
|
|
374
|
+
try:
|
|
375
|
+
columns = target_columns(targets, len(schema.classes))
|
|
376
|
+
except ValueError as error:
|
|
377
|
+
raise ProofError(f"the labels proof cannot read the targets: {error}", proof="labels") from None
|
|
378
|
+
for index, (column, target) in enumerate(zip(encoded, columns, strict=True)):
|
|
379
|
+
if column != target:
|
|
380
|
+
raise ProofError(
|
|
381
|
+
f"the schema encodes the labels differently from training: it puts {labels[index]!r} at "
|
|
382
|
+
f"column {column}, and training put it at column {target} (example {index}). Encode the "
|
|
383
|
+
"training targets with the schema (LabeledData does, unless targets= says otherwise), or "
|
|
384
|
+
"write the schema in the order training used",
|
|
385
|
+
proof="labels",
|
|
386
|
+
example=index,
|
|
387
|
+
)
|
|
388
|
+
return accuracy, None
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def target_columns(targets: Any, classes: int) -> list[int]:
|
|
392
|
+
"""The column of each target, from a tensor, an array or a list of class indices (or of 0.0 and 1.0,
|
|
393
|
+
as a binary loss takes them, one per row or in a column of one). Anything else is a `ValueError` that
|
|
394
|
+
says which target and why."""
|
|
395
|
+
values = as_json(targets, "targets")
|
|
396
|
+
if isinstance(values, list) and values and all(isinstance(row, list) for row in values):
|
|
397
|
+
if all(len(row) == 1 for row in values):
|
|
398
|
+
values = [row[0] for row in values] # a column of targets, (n, 1)
|
|
399
|
+
else:
|
|
400
|
+
raise ValueError(
|
|
401
|
+
f"the targets have {len(values[0])} values per row, and one class index per row is "
|
|
402
|
+
"expected: for one-hot targets, pass targets=y.argmax(1)"
|
|
403
|
+
)
|
|
404
|
+
columns = []
|
|
405
|
+
for index, value in enumerate(values if isinstance(values, list) else [values]):
|
|
406
|
+
if isinstance(value, bool) or not isinstance(value, int | float) or not float(value).is_integer():
|
|
407
|
+
raise ValueError(f"target {index} is {value!r}, not the index of a class")
|
|
408
|
+
if not 0 <= int(value) < classes:
|
|
409
|
+
raise ValueError(f"target {index} is {value!r}, outside the {classes} columns")
|
|
410
|
+
columns.append(int(value))
|
|
411
|
+
return columns
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def _units(answers: dict[str, list[Any]], example: Example, subject: Subject) -> str | None:
|
|
415
|
+
"""The units proof, or why it did not run."""
|
|
416
|
+
labels, targets = example.labels, example.targets
|
|
417
|
+
if labels is None or targets is None:
|
|
418
|
+
return "no labels and targets in the example"
|
|
419
|
+
truth, seen, predicted = (
|
|
420
|
+
_numbers(labels),
|
|
421
|
+
_numbers(as_json(targets, "targets")),
|
|
422
|
+
_numbers(answers["predict"]),
|
|
423
|
+
)
|
|
424
|
+
if truth is None or seen is None or predicted is None:
|
|
425
|
+
return "the answers, the labels or the targets are not numbers"
|
|
426
|
+
if not (len(truth) == len(seen) == len(predicted)):
|
|
427
|
+
return "the answers, the labels and the targets have different sizes"
|
|
428
|
+
if all(math.isclose(a, b, rel_tol=1e-9, abs_tol=1e-12) for a, b in zip(truth, seen, strict=True)):
|
|
429
|
+
return "the labels and the targets are the same: the loss saw the labels' own units"
|
|
430
|
+
to_labels = sum(abs(p - t) for p, t in zip(predicted, truth, strict=True)) / len(truth)
|
|
431
|
+
to_targets = sum(abs(p - t) for p, t in zip(predicted, seen, strict=True)) / len(seen)
|
|
432
|
+
if to_targets < to_labels:
|
|
433
|
+
raise ProofError(
|
|
434
|
+
f"the predictions are closer to the training targets ({to_targets:.4g} on average) than to the "
|
|
435
|
+
f"labels ({to_labels:.4g}): they are in the units the loss saw. Undo the target's transform in "
|
|
436
|
+
"predict, so the bundle answers in the labels' units",
|
|
437
|
+
proof="units",
|
|
438
|
+
)
|
|
439
|
+
return None
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def _numbers(values: Any) -> list[float] | None:
|
|
443
|
+
flat: list[float] = []
|
|
444
|
+
|
|
445
|
+
def walk(value: Any) -> bool:
|
|
446
|
+
if isinstance(value, bool):
|
|
447
|
+
return False
|
|
448
|
+
if isinstance(value, int | float):
|
|
449
|
+
flat.append(float(value))
|
|
450
|
+
return True
|
|
451
|
+
if isinstance(value, list):
|
|
452
|
+
return all(walk(item) for item in value)
|
|
453
|
+
return False
|
|
454
|
+
|
|
455
|
+
return flat if walk(values) else None
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def describe_difference(
|
|
459
|
+
difference: Mapping[str, Any], expected: str, found: str, *, place: str = "example"
|
|
460
|
+
) -> str:
|
|
461
|
+
"""Where two prepared inputs or two outputs differ, from `largest_difference`, in a few words: the
|
|
462
|
+
largest difference, the row (`place`) and the position in it, and what each side has there."""
|
|
463
|
+
if "reason" in difference:
|
|
464
|
+
return f"{difference['where'] or 'the value'} differs: {difference['reason']}"
|
|
465
|
+
where = difference.get("where") or ""
|
|
466
|
+
position = difference.get("position") or []
|
|
467
|
+
at = f"{place} {difference['example']}" + (
|
|
468
|
+
f", position {position[0] if len(position) == 1 else tuple(position)}" if position else ""
|
|
469
|
+
)
|
|
470
|
+
return (
|
|
471
|
+
f"the largest difference is {difference['largest']:.4g}{' in ' + where if where else ''}, at {at} "
|
|
472
|
+
f"({expected} {difference['expected']:.6g}, {found} {difference['found']:.6g})"
|
|
473
|
+
)
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
# -- every load ----------------------------------------------------------------------------------------------
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def examine(predictor: Any, bundle: ArtifactBundle, *, check_example: bool, atol: float) -> str:
|
|
480
|
+
"""What a load says about the bundle's proofs, and the check of its example: the predictor answers the
|
|
481
|
+
example again, and must answer what the bundle answered when it was written.
|
|
482
|
+
|
|
483
|
+
A bundle without proofs loads with a warning, every time. Returns a few words for the load's log line.
|
|
484
|
+
"""
|
|
485
|
+
record = bundle.manifest.proofs
|
|
486
|
+
if record is None:
|
|
487
|
+
logger.warning(
|
|
488
|
+
"the bundle at %s was written without proofs (by ArtifactBundle.write), so nothing shows it "
|
|
489
|
+
"answers like the model that was trained",
|
|
490
|
+
bundle.root,
|
|
491
|
+
)
|
|
492
|
+
return "written without proofs"
|
|
493
|
+
if record.batch_dependent:
|
|
494
|
+
logger.info(
|
|
495
|
+
"the bundle at %s answers each input depending on the rest of its call, as it was saved "
|
|
496
|
+
"(batch_dependent=True)",
|
|
497
|
+
bundle.root,
|
|
498
|
+
)
|
|
499
|
+
if not check_example:
|
|
500
|
+
logger.info("example not checked (check_example=False) for the bundle at %s", bundle.root)
|
|
501
|
+
return "example not checked"
|
|
502
|
+
recorded = _recorded_example(bundle, record.example)
|
|
503
|
+
found = answers_of(predictor, recorded["inputs"])
|
|
504
|
+
reference: dict[str, Any] = {
|
|
505
|
+
part: recorded[part] for part in ("predict", "predict_proba") if part in recorded
|
|
506
|
+
}
|
|
507
|
+
difference = compare_answers(reference, found, atol=atol, schema=bundle.label_schema)
|
|
508
|
+
if difference is not None:
|
|
509
|
+
raise ProofError(
|
|
510
|
+
_changed_since_written(bundle, difference, atol),
|
|
511
|
+
proof="answers_at_load",
|
|
512
|
+
example=difference.example,
|
|
513
|
+
)
|
|
514
|
+
return f"the example's {len(recorded['inputs'])} answers match"
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def _recorded_example(bundle: ArtifactBundle, relative: str) -> dict[str, Any]:
|
|
518
|
+
path = bundle.root / relative
|
|
519
|
+
if not path.is_file():
|
|
520
|
+
raise BundleIntegrityError(
|
|
521
|
+
f"the bundle at {bundle.root} has no {relative}, which its manifest names", missing=[relative]
|
|
522
|
+
)
|
|
523
|
+
try:
|
|
524
|
+
return read_example_file(path.read_text(encoding="utf-8"))
|
|
525
|
+
except (ValueError, json.JSONDecodeError) as error:
|
|
526
|
+
raise BundleIntegrityError(
|
|
527
|
+
f"the bundle's {relative} cannot be read: {error}", changed=[relative]
|
|
528
|
+
) from None
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
def _changed_since_written(bundle: ArtifactBundle, difference: Difference, atol: float) -> str:
|
|
532
|
+
what = difference.describe(reference="when it was written", found="now")
|
|
533
|
+
if difference.largest is not None:
|
|
534
|
+
what += f" (its answers differ by up to {difference.largest:.4g})"
|
|
535
|
+
versions = _versions_since(bundle.manifest.created_with)
|
|
536
|
+
wrote = bundle.manifest.proofs.device if bundle.manifest.proofs is not None else None
|
|
537
|
+
return (
|
|
538
|
+
f"this bundle answered its example differently when it was written: {what}. Something changed "
|
|
539
|
+
f"between the save and this load: the code that builds the predictor, a dependency ({versions}), or "
|
|
540
|
+
f"the device{f' (it was proved on {wrote})' if wrote else ''}. Load it where it was written, or pass "
|
|
541
|
+
f"check_example=False if you know why (the tolerance is atol={atol:g})"
|
|
542
|
+
)
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def _versions_since(created_with: Mapping[str, str]) -> str:
|
|
546
|
+
"""The distributions whose version here differs from the one that wrote the bundle."""
|
|
547
|
+
import platform
|
|
548
|
+
|
|
549
|
+
changed = []
|
|
550
|
+
for name, wrote in created_with.items():
|
|
551
|
+
if name == "python":
|
|
552
|
+
here = platform.python_version()
|
|
553
|
+
else:
|
|
554
|
+
try:
|
|
555
|
+
here = metadata.version(name)
|
|
556
|
+
except metadata.PackageNotFoundError:
|
|
557
|
+
continue
|
|
558
|
+
if here != wrote:
|
|
559
|
+
changed.append(f"{name} {wrote} wrote it, {name} {here} reads it")
|
|
560
|
+
return "; ".join(changed[:5]) if changed else "the same versions wrote it and read it"
|