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,247 @@
|
|
|
1
|
+
"""Base predictor for PyTorch bundles.
|
|
2
|
+
|
|
3
|
+
`save_bundle` stores the trained network and its preparation. Loading restores them as
|
|
4
|
+
`self.network` and `self.prepare`. Subclasses implement `predict` and, optionally,
|
|
5
|
+
`predict_proba`. Classifiers should use `TorchClassifier`.
|
|
6
|
+
|
|
7
|
+
A bundle is read in one of two ways. With `trust_code=True` the bundle's own pickles are read, which runs
|
|
8
|
+
the code they name. Or the service brings the code, `load(folder, network=..., prepare=...)`: the weights go
|
|
9
|
+
in the network it built, the preparation is its own, and nothing the bundle carries as code is read.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import functools
|
|
15
|
+
import os
|
|
16
|
+
from collections.abc import Callable, Mapping
|
|
17
|
+
from typing import TYPE_CHECKING, Any, Self
|
|
18
|
+
|
|
19
|
+
from torchstack64.artifacts.bundle import ArtifactBundle, read_tensor_metadata
|
|
20
|
+
from torchstack64.artifacts.code import import_bundle_code, place_tensors, read_network, read_object
|
|
21
|
+
from torchstack64.artifacts.predictor.bundle_predictor import LOAD_ATOL, BundlePredictor
|
|
22
|
+
from torchstack64.artifacts.proofs import floating_dtype_of, on_device
|
|
23
|
+
from torchstack64.artifacts.sources import ModelSource
|
|
24
|
+
from torchstack64.core import BundleError, LabelSchema, TrustRequiredError
|
|
25
|
+
|
|
26
|
+
if TYPE_CHECKING:
|
|
27
|
+
from torch import nn
|
|
28
|
+
|
|
29
|
+
NETWORK = "network" # the network's structure, every tensor empty: network.pt
|
|
30
|
+
WEIGHTS = "weights" # every tensor of the network, by name: weights.safetensors
|
|
31
|
+
PREPARE = "prepare" # the preparation, with its state: prepare.pt
|
|
32
|
+
|
|
33
|
+
# What a subclass may not write: the network and the preparation come from the bundle, as objects.
|
|
34
|
+
_NOT_WRITTEN = ("architecture", "prepare", "build", "config", "pack", "unpack", "unchecked")
|
|
35
|
+
# What the library does for a network, so a subclass has nothing to say about it.
|
|
36
|
+
_RUN_BY_THE_LIBRARY = ("trained_predict", "trained_predict_proba")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class TorchPredictor[InputT, OutputT](BundlePredictor[InputT, OutputT]):
|
|
40
|
+
"""The predictor of a bundle `save_bundle` wrote from a PyTorch network: the network, the preparation and,
|
|
41
|
+
when the data had classes, the label schema, all from the bundle. A subclass writes `predict` (and
|
|
42
|
+
`predict_proba`).
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
def __init__(
|
|
46
|
+
self,
|
|
47
|
+
network: nn.Module,
|
|
48
|
+
prepare: Callable[[list[Any]], Any],
|
|
49
|
+
label_schema: LabelSchema | None = None,
|
|
50
|
+
*,
|
|
51
|
+
device: str = "cpu",
|
|
52
|
+
) -> None:
|
|
53
|
+
self.network = network
|
|
54
|
+
self.prepare = prepare
|
|
55
|
+
self.label_schema = label_schema
|
|
56
|
+
self.device = device
|
|
57
|
+
|
|
58
|
+
def __init_subclass__(cls, **kwargs: Any) -> None:
|
|
59
|
+
super().__init_subclass__(**kwargs)
|
|
60
|
+
written = [name for name in _NOT_WRITTEN if name in vars(cls)]
|
|
61
|
+
if written:
|
|
62
|
+
raise TypeError(
|
|
63
|
+
f"{cls.__name__} writes {', '.join(written)}, which TorchPredictor no longer takes: the "
|
|
64
|
+
"network and the preparation travel as objects. Train the network as it is, give the "
|
|
65
|
+
"preparation to LabeledData(..., prepare=...), and save with save_bundle(model, folder, "
|
|
66
|
+
"data=val, predictor=...); a subclass writes only predict (and predict_proba)"
|
|
67
|
+
)
|
|
68
|
+
reference = [name for name in _RUN_BY_THE_LIBRARY if name in vars(cls)]
|
|
69
|
+
if reference:
|
|
70
|
+
raise TypeError(
|
|
71
|
+
f"{cls.__name__} writes {', '.join(reference)}, which a PyTorch network does not take: the "
|
|
72
|
+
"library runs the network itself, so a subclass writes only predict (and predict_proba)"
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
def forward(self, *inputs: Any, **named: Any) -> Any:
|
|
76
|
+
"""The network's output for `inputs`, each moved to the device (tensors, NumPy arrays, and lists,
|
|
77
|
+
tuples and dicts of them), floating ones in the weights' type, with gradients off."""
|
|
78
|
+
import torch
|
|
79
|
+
|
|
80
|
+
dtype = floating_dtype_of(self.network)
|
|
81
|
+
with torch.inference_mode():
|
|
82
|
+
return self.network(
|
|
83
|
+
*on_device(inputs, self.device, dtype), **on_device(named, self.device, dtype)
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
# -- the bundle ----------------------------------------------------------------------------------------
|
|
87
|
+
|
|
88
|
+
@classmethod
|
|
89
|
+
def pack(cls, model: Any) -> Mapping[str, Any]:
|
|
90
|
+
"""Not how a PyTorch network is saved: `save_bundle` writes it, with its preparation."""
|
|
91
|
+
raise TypeError("a PyTorch network is saved with save_bundle(model, folder, data=val, predictor=...)")
|
|
92
|
+
|
|
93
|
+
@classmethod
|
|
94
|
+
def trained_predict(cls, model: Any, rows: Any) -> Any:
|
|
95
|
+
"""Not asked of a PyTorch network: the library runs it itself, so `save_bundle` never calls this."""
|
|
96
|
+
raise TypeError(
|
|
97
|
+
"the library runs a PyTorch network itself, so it asks no trained_predict of its class"
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
@classmethod
|
|
101
|
+
def unpack(cls, bundle: ArtifactBundle, device: str) -> Self:
|
|
102
|
+
"""The network and the preparation read back from the bundle, the network on `device` in evaluation
|
|
103
|
+
mode. This runs the bundle's code: the bundle must be trusted."""
|
|
104
|
+
import_bundle_code(bundle)
|
|
105
|
+
weights = bundle.path_for(WEIGHTS)
|
|
106
|
+
network = read_network(
|
|
107
|
+
bundle.path_for(NETWORK),
|
|
108
|
+
bundle.read_tensors(WEIGHTS, device=device),
|
|
109
|
+
read_tensor_metadata(weights),
|
|
110
|
+
)
|
|
111
|
+
prepare = read_object(bundle.path_for(PREPARE))
|
|
112
|
+
return cls(
|
|
113
|
+
network.to(device).eval(),
|
|
114
|
+
prepare,
|
|
115
|
+
bundle.label_schema,
|
|
116
|
+
device=device,
|
|
117
|
+
**cls._keywords_from(bundle),
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
@classmethod
|
|
121
|
+
def _keywords_from(cls, bundle: ArtifactBundle) -> dict[str, Any]:
|
|
122
|
+
"""What the constructor takes from the bundle besides the network, the preparation, the schema and the
|
|
123
|
+
device: nothing, here; a classifier's reading of its outputs."""
|
|
124
|
+
return {}
|
|
125
|
+
|
|
126
|
+
@classmethod
|
|
127
|
+
def load( # type: ignore[override]
|
|
128
|
+
cls,
|
|
129
|
+
source: ArtifactBundle | ModelSource | str | os.PathLike[str],
|
|
130
|
+
device: str | None = None,
|
|
131
|
+
*,
|
|
132
|
+
network: nn.Module | None = None,
|
|
133
|
+
prepare: Callable[[list[Any]], Any] | None = None,
|
|
134
|
+
trust_code: bool = False,
|
|
135
|
+
verify: bool = True,
|
|
136
|
+
check_example: bool = True,
|
|
137
|
+
atol: float = LOAD_ATOL,
|
|
138
|
+
) -> Self:
|
|
139
|
+
"""The predictor of the bundle `source` names, on `device`, after it answered the bundle's example
|
|
140
|
+
as the bundle did when it was written. `load_trusted_predictor(source)` does the same without the
|
|
141
|
+
class at hand.
|
|
142
|
+
|
|
143
|
+
The code comes from one of two places, and one must be given:
|
|
144
|
+
|
|
145
|
+
- `network=` and `prepare=`: the network the service built (its layers, with any weights) and its
|
|
146
|
+
preparation. The bundle's weights are placed in that network, which must have the same tensor names
|
|
147
|
+
and shapes, and which is the object that is filled; nothing the bundle carries as code is read, so
|
|
148
|
+
nothing needs to be trusted. If the preparation learned something in training (a vocabulary, a
|
|
149
|
+
scaler), it has to be the same one.
|
|
150
|
+
- `trust_code=True`: the bundle's own network and preparation are read, which runs its code, for a
|
|
151
|
+
bundle from a source you trust, after its files matched their checksums.
|
|
152
|
+
"""
|
|
153
|
+
if network is not None or prepare is not None:
|
|
154
|
+
if network is None or prepare is None:
|
|
155
|
+
raise ValueError(
|
|
156
|
+
"network= and prepare= come together: they are what the bundle's own code would have "
|
|
157
|
+
"built"
|
|
158
|
+
)
|
|
159
|
+
if trust_code:
|
|
160
|
+
raise ValueError(
|
|
161
|
+
"trust_code=True runs the bundle's code, and network= and prepare= replace it: pass one "
|
|
162
|
+
"or the other"
|
|
163
|
+
)
|
|
164
|
+
_refuse_what_is_not_code(network, prepare)
|
|
165
|
+
|
|
166
|
+
build = functools.partial(cls._from_objects, network=network, prepare=prepare)
|
|
167
|
+
return cls._load_with(
|
|
168
|
+
build, source, device, verify=verify, check_example=check_example, atol=atol
|
|
169
|
+
)
|
|
170
|
+
if not trust_code:
|
|
171
|
+
raise TrustRequiredError(untrusted_message(source, cls.__name__))
|
|
172
|
+
if not verify:
|
|
173
|
+
raise ValueError(
|
|
174
|
+
"trust_code=True needs verify=True: the bundle's code runs only after its files match "
|
|
175
|
+
"their checksums"
|
|
176
|
+
)
|
|
177
|
+
return super().load(source, device, verify=verify, check_example=check_example, atol=atol)
|
|
178
|
+
|
|
179
|
+
@classmethod
|
|
180
|
+
def _from_objects(
|
|
181
|
+
cls, bundle: ArtifactBundle, device: str, *, network: nn.Module, prepare: Callable[[list[Any]], Any]
|
|
182
|
+
) -> Self:
|
|
183
|
+
"""The predictor of a bundle already read, built from a network and a preparation the caller brought:
|
|
184
|
+
the bundle's weights are placed in the network, and nothing the bundle carries as code is read."""
|
|
185
|
+
if WEIGHTS not in bundle.manifest.artifacts:
|
|
186
|
+
raise BundleError(
|
|
187
|
+
f"the bundle at {bundle.root} keeps no weights for {cls.__name__} to place in your network",
|
|
188
|
+
root=str(bundle.root),
|
|
189
|
+
)
|
|
190
|
+
cls._refuse_if_incomplete("loaded")
|
|
191
|
+
cls._refuse_if_cannot_answer(bundle.label_schema)
|
|
192
|
+
place_tensors(
|
|
193
|
+
network,
|
|
194
|
+
bundle.read_tensors(WEIGHTS, device=device),
|
|
195
|
+
read_tensor_metadata(bundle.path_for(WEIGHTS)),
|
|
196
|
+
must_fit=True,
|
|
197
|
+
)
|
|
198
|
+
predictor = cls(
|
|
199
|
+
network.to(device).eval(),
|
|
200
|
+
prepare,
|
|
201
|
+
bundle.label_schema,
|
|
202
|
+
device=device,
|
|
203
|
+
**cls._keywords_from(bundle),
|
|
204
|
+
)
|
|
205
|
+
predictor.bundle = bundle
|
|
206
|
+
return predictor
|
|
207
|
+
|
|
208
|
+
@classmethod
|
|
209
|
+
def _from_bundle(cls, bundle: ArtifactBundle, device: str) -> Self:
|
|
210
|
+
"""The predictor of a bundle already read and trusted, on `device`, without the example's check. Any
|
|
211
|
+
bundle that keeps a network and its preparation is read."""
|
|
212
|
+
if NETWORK not in bundle.manifest.artifacts or PREPARE not in bundle.manifest.artifacts:
|
|
213
|
+
raise BundleError(
|
|
214
|
+
f"the bundle at {bundle.root} keeps no network and preparation for {cls.__name__} to read",
|
|
215
|
+
root=str(bundle.root),
|
|
216
|
+
)
|
|
217
|
+
cls._refuse_if_incomplete("loaded")
|
|
218
|
+
cls._refuse_if_cannot_answer(bundle.label_schema)
|
|
219
|
+
predictor = cls.unpack(bundle, device)
|
|
220
|
+
predictor.bundle = bundle
|
|
221
|
+
return predictor
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def untrusted_message(source: Any, class_name: str = "TorchClassifier") -> str:
|
|
225
|
+
"""Why a bundle that keeps objects is not read without trust, and the two calls that read it: with trust,
|
|
226
|
+
or with the code the caller brings, through the class that reads the bundle."""
|
|
227
|
+
where = source.root if isinstance(source, ArtifactBundle) else source # a Path has a `root` of its own
|
|
228
|
+
return (
|
|
229
|
+
f"the bundle at {where} keeps the network and its preparation as Python objects, and reading them "
|
|
230
|
+
f'runs code. If you trust where it came from: load_trusted_predictor("{where}"). If not, '
|
|
231
|
+
f'bring the code yourself: {class_name}.load("{where}", network=<your network>, '
|
|
232
|
+
"prepare=<your preparation>)"
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _refuse_what_is_not_code(network: Any, prepare: Any) -> None:
|
|
237
|
+
"""`network=` is a PyTorch module and `prepare=` a function; anything else fails later, far from here."""
|
|
238
|
+
from torch import nn
|
|
239
|
+
|
|
240
|
+
if not isinstance(network, nn.Module):
|
|
241
|
+
raise TypeError(
|
|
242
|
+
f"network= is the torch.nn.Module the bundle's weights go in; got {type(network).__name__}"
|
|
243
|
+
)
|
|
244
|
+
if not callable(prepare):
|
|
245
|
+
raise TypeError(
|
|
246
|
+
f"prepare= is the function that turns raw inputs into what the network takes; got {prepare!r}"
|
|
247
|
+
)
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Does the bundle answer like the model that was trained? The proofs that say so, before the bundle exists
|
|
2
|
+
and every time it is loaded.
|
|
3
|
+
|
|
4
|
+
- `example`: the `Example` a bundle is proved on, drawn from validation data in the four forms the proofs
|
|
5
|
+
compare, and the file the bundle keeps it in, with its answers.
|
|
6
|
+
- `answers`: two sets of answers compared, with the rule for a near tie; the same comparison when a
|
|
7
|
+
bundle is saved, when it is loaded, and in a project's tests.
|
|
8
|
+
- `modules`: the network side, for a PyTorch model: a network fed the way training fed it, and two
|
|
9
|
+
prepared inputs or two outputs compared number by number. PyTorch is imported inside its functions only.
|
|
10
|
+
- `suite`: the proofs in their order, on a bundle written in its staging folder, and the check of the
|
|
11
|
+
example every load makes.
|
|
12
|
+
|
|
13
|
+
Nothing here knows the predictor classes: the proofs take the trained model and the predictor loaded from
|
|
14
|
+
the bundle as objects, so `save_bundle` and the classes can use them without a cycle.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from torchstack64.artifacts.proofs.answers import Difference, answers_of, compare_answers
|
|
18
|
+
from torchstack64.artifacts.proofs.example import (
|
|
19
|
+
EXAMPLE_FILE,
|
|
20
|
+
EXAMPLE_SIZE,
|
|
21
|
+
Example,
|
|
22
|
+
as_json,
|
|
23
|
+
example_file,
|
|
24
|
+
read_example_file,
|
|
25
|
+
rows_of,
|
|
26
|
+
take,
|
|
27
|
+
)
|
|
28
|
+
from torchstack64.artifacts.proofs.modules import (
|
|
29
|
+
device_of,
|
|
30
|
+
evaluated,
|
|
31
|
+
exact_arithmetic,
|
|
32
|
+
feed,
|
|
33
|
+
floating_dtype_of,
|
|
34
|
+
largest_difference,
|
|
35
|
+
looks_like_probabilities,
|
|
36
|
+
network_of,
|
|
37
|
+
on_device,
|
|
38
|
+
)
|
|
39
|
+
from torchstack64.artifacts.proofs.suite import (
|
|
40
|
+
PREPARED_ATOL,
|
|
41
|
+
PREPARED_RTOL,
|
|
42
|
+
PROOF_ORDER,
|
|
43
|
+
Proved,
|
|
44
|
+
Subject,
|
|
45
|
+
describe_difference,
|
|
46
|
+
examine,
|
|
47
|
+
prove_on_example,
|
|
48
|
+
shown_names,
|
|
49
|
+
target_columns,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
__all__ = [
|
|
53
|
+
"EXAMPLE_FILE",
|
|
54
|
+
"EXAMPLE_SIZE",
|
|
55
|
+
"PREPARED_ATOL",
|
|
56
|
+
"PREPARED_RTOL",
|
|
57
|
+
"PROOF_ORDER",
|
|
58
|
+
"Difference",
|
|
59
|
+
"Example",
|
|
60
|
+
"Proved",
|
|
61
|
+
"Subject",
|
|
62
|
+
"answers_of",
|
|
63
|
+
"as_json",
|
|
64
|
+
"compare_answers",
|
|
65
|
+
"describe_difference",
|
|
66
|
+
"device_of",
|
|
67
|
+
"evaluated",
|
|
68
|
+
"exact_arithmetic",
|
|
69
|
+
"examine",
|
|
70
|
+
"example_file",
|
|
71
|
+
"feed",
|
|
72
|
+
"floating_dtype_of",
|
|
73
|
+
"largest_difference",
|
|
74
|
+
"looks_like_probabilities",
|
|
75
|
+
"network_of",
|
|
76
|
+
"on_device",
|
|
77
|
+
"prove_on_example",
|
|
78
|
+
"read_example_file",
|
|
79
|
+
"rows_of",
|
|
80
|
+
"shown_names",
|
|
81
|
+
"take",
|
|
82
|
+
"target_columns",
|
|
83
|
+
]
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""Two sets of answers compared: what a predictor answered once, and what it, or another, answers now.
|
|
2
|
+
|
|
3
|
+
The same comparison runs when a bundle is saved, when it is loaded, and in a project's tests, so it is
|
|
4
|
+
written once, here, with the standard library only.
|
|
5
|
+
|
|
6
|
+
- Labels must be equal; numbers equal within `atol`; texts, booleans and `None` exactly equal.
|
|
7
|
+
- A label may differ at a near tie: when the recorded probabilities put the two labels so close that
|
|
8
|
+
another arithmetic (another machine, another version of a library) can legitimately swap them. The
|
|
9
|
+
probabilities themselves are still compared within `atol`, so a near tie can never hide a real change.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import math
|
|
15
|
+
from collections.abc import Mapping, Sequence
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from torchstack64.artifacts.proofs.example import as_json
|
|
20
|
+
from torchstack64.core import LabelSchema
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def answers_of(predictor: Any, inputs: Sequence[Any]) -> dict[str, list[Any]]:
|
|
24
|
+
"""What a predictor answers for `inputs`, as JSON: its answers under `predict`, and its rows of
|
|
25
|
+
probabilities under `predict_proba` when it gives them."""
|
|
26
|
+
answers = predictor.predict(inputs)
|
|
27
|
+
found: dict[str, list[Any]] = {"predict": [as_json(a, f"answer {n}") for n, a in enumerate(answers)]}
|
|
28
|
+
predict_proba = getattr(predictor, "predict_proba", None)
|
|
29
|
+
if callable(predict_proba):
|
|
30
|
+
rows = predict_proba(inputs)
|
|
31
|
+
found["predict_proba"] = [as_json(row, f"row {n} of probabilities") for n, row in enumerate(rows)]
|
|
32
|
+
return found
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True, slots=True)
|
|
36
|
+
class Difference:
|
|
37
|
+
"""Where two sets of answers part: the first example that differs, what each side says there, how many
|
|
38
|
+
examples differ, and the largest difference between numbers."""
|
|
39
|
+
|
|
40
|
+
part: str # "predict" or "predict_proba"
|
|
41
|
+
example: int | None # None when the two do not even have the same examples
|
|
42
|
+
reference: Any
|
|
43
|
+
found: Any
|
|
44
|
+
count: int
|
|
45
|
+
largest: float | None
|
|
46
|
+
|
|
47
|
+
def describe(self, *, reference: str = "before", found: str = "now") -> str:
|
|
48
|
+
"""`example 7's answer: 3 when it was written, 8 now`, with the two moments a caller names. Numbers
|
|
49
|
+
are shown to four decimals: enough to see a difference, short enough to read."""
|
|
50
|
+
if self.example is None:
|
|
51
|
+
return f"{self.part}: {self.reference} {reference}, {self.found} {found}"
|
|
52
|
+
what = "probabilities" if self.part == "predict_proba" else "answer"
|
|
53
|
+
return (
|
|
54
|
+
f"example {self.example}'s {what}: {rounded(self.reference)!r} {reference}, "
|
|
55
|
+
f"{rounded(self.found)!r} {found}"
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def rounded(value: Any) -> Any:
|
|
60
|
+
"""An answer with its numbers to four decimals, for a message."""
|
|
61
|
+
if isinstance(value, float):
|
|
62
|
+
return round(value, 4)
|
|
63
|
+
if isinstance(value, list | tuple):
|
|
64
|
+
return [rounded(item) for item in value]
|
|
65
|
+
if isinstance(value, Mapping):
|
|
66
|
+
return {key: rounded(item) for key, item in value.items()}
|
|
67
|
+
return value
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def compare_answers(
|
|
71
|
+
reference: Mapping[str, Sequence[Any]],
|
|
72
|
+
found: Mapping[str, Sequence[Any]],
|
|
73
|
+
*,
|
|
74
|
+
atol: float,
|
|
75
|
+
schema: LabelSchema | None = None,
|
|
76
|
+
) -> Difference | None:
|
|
77
|
+
"""The first place where `found` parts from `reference`, or `None` when they agree.
|
|
78
|
+
|
|
79
|
+
Every part `reference` has must be in `found`. With a `schema` and recorded probabilities, a label
|
|
80
|
+
that differs only at a near tie is accepted: for a categorical schema, when the recorded probabilities
|
|
81
|
+
of the two labels are within `2 * atol` of each other (each can move by `atol`); for a binary one,
|
|
82
|
+
when the recorded probability of the positive class is within `atol` of the threshold.
|
|
83
|
+
"""
|
|
84
|
+
for part in ("predict_proba", "predict"):
|
|
85
|
+
if part not in reference:
|
|
86
|
+
continue
|
|
87
|
+
expected = list(reference[part])
|
|
88
|
+
if part not in found:
|
|
89
|
+
return Difference(part, None, "given", "not given", len(expected), None)
|
|
90
|
+
given = list(found[part])
|
|
91
|
+
if len(given) != len(expected):
|
|
92
|
+
return Difference(part, None, f"{len(expected)} rows", f"{len(given)} rows", len(expected), None)
|
|
93
|
+
first: int | None = None
|
|
94
|
+
count = 0
|
|
95
|
+
largest = 0.0
|
|
96
|
+
for index, (one, other) in enumerate(zip(expected, given, strict=True)):
|
|
97
|
+
gap = _gap(one, other)
|
|
98
|
+
if gap is not None and math.isfinite(gap):
|
|
99
|
+
largest = max(largest, gap)
|
|
100
|
+
if _agree(one, other, atol) or (
|
|
101
|
+
part == "predict" and _near_tie(reference, index, one, other, schema, atol)
|
|
102
|
+
):
|
|
103
|
+
continue
|
|
104
|
+
count += 1
|
|
105
|
+
if first is None:
|
|
106
|
+
first = index
|
|
107
|
+
if first is not None:
|
|
108
|
+
return Difference(part, first, expected[first], given[first], count, largest or None)
|
|
109
|
+
return None
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _agree(one: Any, other: Any, atol: float) -> bool:
|
|
113
|
+
if isinstance(one, bool) or isinstance(other, bool) or one is None or other is None:
|
|
114
|
+
return type(one) is type(other) and one == other
|
|
115
|
+
if isinstance(one, int | float) and isinstance(other, int | float):
|
|
116
|
+
if math.isnan(one) or math.isnan(other):
|
|
117
|
+
return math.isnan(one) and math.isnan(other)
|
|
118
|
+
return abs(one - other) <= atol
|
|
119
|
+
if isinstance(one, Mapping) and isinstance(other, Mapping):
|
|
120
|
+
return one.keys() == other.keys() and all(_agree(one[key], other[key], atol) for key in one)
|
|
121
|
+
if isinstance(one, list | tuple) and isinstance(other, list | tuple):
|
|
122
|
+
return len(one) == len(other) and all(_agree(a, b, atol) for a, b in zip(one, other, strict=True))
|
|
123
|
+
return bool(type(one) is type(other) and one == other)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _gap(one: Any, other: Any) -> float | None:
|
|
127
|
+
"""The largest difference between the numbers of two answers of the same shape, or `None`."""
|
|
128
|
+
if isinstance(one, bool) or isinstance(other, bool):
|
|
129
|
+
return None
|
|
130
|
+
if isinstance(one, int | float) and isinstance(other, int | float):
|
|
131
|
+
return abs(float(one) - float(other))
|
|
132
|
+
if isinstance(one, list | tuple) and isinstance(other, list | tuple) and len(one) == len(other):
|
|
133
|
+
gaps = [gap for a, b in zip(one, other, strict=True) if (gap := _gap(a, b)) is not None]
|
|
134
|
+
return max(gaps) if gaps else None
|
|
135
|
+
return None
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _near_tie(
|
|
139
|
+
reference: Mapping[str, Sequence[Any]],
|
|
140
|
+
index: int,
|
|
141
|
+
label: Any,
|
|
142
|
+
other: Any,
|
|
143
|
+
schema: LabelSchema | None,
|
|
144
|
+
atol: float,
|
|
145
|
+
) -> bool:
|
|
146
|
+
rows = reference.get("predict_proba")
|
|
147
|
+
if schema is None or rows is None or schema.kind == "ordinal":
|
|
148
|
+
return False
|
|
149
|
+
try:
|
|
150
|
+
row = [float(value) for value in rows[index]]
|
|
151
|
+
columns = schema.encode([label, other])
|
|
152
|
+
except (TypeError, ValueError, IndexError):
|
|
153
|
+
return False
|
|
154
|
+
if len(row) != len(schema.classes):
|
|
155
|
+
return False
|
|
156
|
+
if schema.kind == "binary":
|
|
157
|
+
assert schema.threshold is not None
|
|
158
|
+
return abs(row[1] - schema.threshold) <= atol
|
|
159
|
+
return abs(row[columns[0]] - row[columns[1]]) <= 2 * atol
|