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.
Files changed (92) hide show
  1. torchstack64/__init__.py +101 -0
  2. torchstack64/artifacts/__init__.py +78 -0
  3. torchstack64/artifacts/bundle/__init__.py +50 -0
  4. torchstack64/artifacts/bundle/files.py +106 -0
  5. torchstack64/artifacts/bundle/folder.py +385 -0
  6. torchstack64/artifacts/bundle/tensors.py +75 -0
  7. torchstack64/artifacts/code/__init__.py +103 -0
  8. torchstack64/artifacts/code/copy.py +149 -0
  9. torchstack64/artifacts/code/importing.py +204 -0
  10. torchstack64/artifacts/code/inspection.py +351 -0
  11. torchstack64/artifacts/code/notebook.py +373 -0
  12. torchstack64/artifacts/code/objects.py +401 -0
  13. torchstack64/artifacts/loading.py +117 -0
  14. torchstack64/artifacts/manifest.py +220 -0
  15. torchstack64/artifacts/predictor/__init__.py +45 -0
  16. torchstack64/artifacts/predictor/bundle_predictor.py +193 -0
  17. torchstack64/artifacts/predictor/output_reading.py +96 -0
  18. torchstack64/artifacts/predictor/torch_classifier.py +106 -0
  19. torchstack64/artifacts/predictor/torch_predictor.py +247 -0
  20. torchstack64/artifacts/proofs/__init__.py +83 -0
  21. torchstack64/artifacts/proofs/answers.py +159 -0
  22. torchstack64/artifacts/proofs/example.py +248 -0
  23. torchstack64/artifacts/proofs/modules.py +260 -0
  24. torchstack64/artifacts/proofs/suite.py +560 -0
  25. torchstack64/artifacts/saving.py +461 -0
  26. torchstack64/artifacts/sources.py +166 -0
  27. torchstack64/callbacks/__init__.py +22 -0
  28. torchstack64/callbacks/base.py +43 -0
  29. torchstack64/callbacks/checkpointing.py +40 -0
  30. torchstack64/callbacks/history_plot.py +160 -0
  31. torchstack64/callbacks/mlflow_logger.py +217 -0
  32. torchstack64/callbacks/model_checks.py +295 -0
  33. torchstack64/callbacks/progress.py +132 -0
  34. torchstack64/callbacks/stack.py +85 -0
  35. torchstack64/core/__init__.py +59 -0
  36. torchstack64/core/errors.py +121 -0
  37. torchstack64/core/evaluation.py +52 -0
  38. torchstack64/core/extras.py +36 -0
  39. torchstack64/core/inference.py +42 -0
  40. torchstack64/core/labels.py +201 -0
  41. torchstack64/core/logging.py +110 -0
  42. torchstack64/data/__init__.py +10 -0
  43. torchstack64/data/base.py +256 -0
  44. torchstack64/data/labeled.py +128 -0
  45. torchstack64/devices/__init__.py +38 -0
  46. torchstack64/devices/hardware.py +43 -0
  47. torchstack64/devices/selection.py +82 -0
  48. torchstack64/metrics/__init__.py +21 -0
  49. torchstack64/metrics/classification.py +93 -0
  50. torchstack64/py.typed +0 -0
  51. torchstack64/training/__init__.py +83 -0
  52. torchstack64/training/config/__init__.py +17 -0
  53. torchstack64/training/config/fit.py +60 -0
  54. torchstack64/training/config/monitor.py +63 -0
  55. torchstack64/training/config/optim.py +49 -0
  56. torchstack64/training/config/params.py +55 -0
  57. torchstack64/training/config/search.py +49 -0
  58. torchstack64/training/results/__init__.py +19 -0
  59. torchstack64/training/results/fit.py +37 -0
  60. torchstack64/training/results/history.py +74 -0
  61. torchstack64/training/results/predictions.py +81 -0
  62. torchstack64/training/runtime/__init__.py +18 -0
  63. torchstack64/training/runtime/precision.py +139 -0
  64. torchstack64/training/runtime/randomness.py +142 -0
  65. torchstack64/training/runtime/runtime.py +75 -0
  66. torchstack64/training/runtime/transfer.py +49 -0
  67. torchstack64/training/runtime/weights.py +43 -0
  68. torchstack64/training/task/__init__.py +11 -0
  69. torchstack64/training/task/optim/__init__.py +9 -0
  70. torchstack64/training/task/optim/optimization.py +70 -0
  71. torchstack64/training/task/optim/schedules.py +27 -0
  72. torchstack64/training/task/protocol.py +58 -0
  73. torchstack64/training/task/supervised.py +113 -0
  74. torchstack64/training/trainer/__init__.py +8 -0
  75. torchstack64/training/trainer/adapters.py +122 -0
  76. torchstack64/training/trainer/contracts.py +81 -0
  77. torchstack64/training/trainer/hooks.py +47 -0
  78. torchstack64/training/trainer/meters.py +150 -0
  79. torchstack64/training/trainer/state.py +117 -0
  80. torchstack64/training/trainer/trainer.py +586 -0
  81. torchstack64/training/tuner/__init__.py +3 -0
  82. torchstack64/training/tuner/callback.py +38 -0
  83. torchstack64/training/tuner/space.py +82 -0
  84. torchstack64/training/tuner/tuner.py +137 -0
  85. torchstack64/utils/__init__.py +21 -0
  86. torchstack64/utils/logging.py +85 -0
  87. torchstack64/utils/mlflow.py +127 -0
  88. torchstack64-0.3.0.dist-info/METADATA +622 -0
  89. torchstack64-0.3.0.dist-info/RECORD +92 -0
  90. torchstack64-0.3.0.dist-info/WHEEL +5 -0
  91. torchstack64-0.3.0.dist-info/licenses/LICENSE +21 -0
  92. torchstack64-0.3.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,248 @@
1
+ """The example a bundle is proved on: a few validation inputs, in the four forms the proofs compare.
2
+
3
+ The proofs compare the way training saw the data with the way serving will. Each form is one side of a
4
+ comparison:
5
+
6
+ - `inputs`: the raw inputs, as a request carries them (JSON). What the service receives.
7
+ - `prepared`: what the preparation of the training process gives for those inputs: what the preparation
8
+ read back from the bundle must give too.
9
+ - `labels`: the true answers, as the service would give them.
10
+ - `targets`: what the loss received for them. The labels and the targets together say in which order
11
+ training put the classes, and in which units a regression was trained.
12
+
13
+ Nobody writes one by hand: the data's `example()` draws it from the validation data training used (data
14
+ without labels gives an example without labels and targets, and the proofs that compare them do not run).
15
+ `Example.sample` draws the same rows of the four, with a fixed seed, so the same data always proves with
16
+ the same example, and the example is not stuck on the first rows of a data set that may be sorted.
17
+
18
+ Only the standard library is used here: the contract imports without PyTorch or NumPy, whose arrays and
19
+ tensors are told apart by their type's module.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ import random
26
+ from collections.abc import Mapping, Sequence
27
+ from dataclasses import dataclass
28
+ from typing import Any
29
+
30
+ EXAMPLE_SIZE = 32
31
+ EXAMPLE_FILE = "proofs/example.json"
32
+
33
+
34
+ @dataclass(frozen=True, slots=True)
35
+ class Example:
36
+ """Validation inputs in four forms: `inputs` (raw, as a request carries them), `prepared` (what the
37
+ network receives for them), `labels` (the true answers) and `targets` (what the loss received).
38
+
39
+ `prepared` and `targets` may be functions, applied to the inputs and to the labels.
40
+
41
+ The inputs and the labels become JSON when the example is made (arrays become lists, NumPy scalars
42
+ Python numbers), because they are what a request carries and what a service answers; the bundle keeps
43
+ the inputs. A value JSON cannot hold is refused. The data's `example()` (a `PreparedData`, or a
44
+ `LabeledData` with its labels and targets) makes the one a bundle is proved on, with
45
+ `Example.sample(...)`, which draws the rows.
46
+ """
47
+
48
+ inputs: list[Any]
49
+ prepared: Any = None
50
+ labels: list[Any] | None = None
51
+ targets: Any = None
52
+
53
+ def __post_init__(self) -> None:
54
+ raw = self.inputs
55
+ if isinstance(raw, str | bytes | Mapping) or not (isinstance(raw, Sequence) or _is_array(raw)):
56
+ raise ValueError(
57
+ f"an example's inputs are a sequence of inputs, one per row; got a {type(raw).__name__}"
58
+ )
59
+ size = rows_of(raw, "inputs")
60
+ if size < 2:
61
+ raise ValueError(
62
+ "an example needs at least 2 inputs, so the batch proof can compare an input alone with the "
63
+ f"same input among others; got {size}"
64
+ )
65
+ labels = self.labels
66
+ if callable(self.targets) and not _is_array(self.targets) and labels is None:
67
+ raise ValueError("targets is a function of the labels, so the example needs labels too")
68
+ prepared = _applied(self.prepared, raw)
69
+ targets = _applied(self.targets, labels)
70
+ for name, value in (("prepared", prepared), ("labels", labels), ("targets", targets)):
71
+ if value is not None and rows_of(value, name) != size:
72
+ raise ValueError(
73
+ f"an example's forms are the same rows: inputs has {size}, and {name} has "
74
+ f"{rows_of(value, name)}"
75
+ )
76
+ object.__setattr__(self, "inputs", [as_request(row, f"inputs[{n}]") for n, row in enumerate(raw)])
77
+ object.__setattr__(self, "prepared", prepared)
78
+ if labels is not None:
79
+ object.__setattr__(self, "labels", [as_json(row, f"labels[{n}]") for n, row in enumerate(labels)])
80
+ object.__setattr__(self, "targets", targets)
81
+
82
+ def __len__(self) -> int:
83
+ return len(self.inputs)
84
+
85
+ def __repr__(self) -> str:
86
+ given = [name for name in ("prepared", "labels", "targets") if getattr(self, name) is not None]
87
+ return f"Example({len(self.inputs)} inputs{', with ' + ', '.join(given) if given else ''})"
88
+
89
+ @classmethod
90
+ def sample(
91
+ cls,
92
+ *,
93
+ inputs: Any,
94
+ prepared: Any = None,
95
+ labels: Any = None,
96
+ targets: Any = None,
97
+ size: int = EXAMPLE_SIZE,
98
+ seed: int = 0,
99
+ ) -> Example:
100
+ """`size` rows drawn with `seed` from validation data, the same rows in each form given, in a
101
+ random order.
102
+
103
+ Each form is a list, a tuple, a NumPy array, a PyTorch tensor, or a dict of them (a tokenizer's
104
+ output), indexed by its first dimension; forms of different lengths are a `ValueError` that says
105
+ each length. `prepared` and `targets` may also be functions, applied to the drawn inputs and labels.
106
+ All the rows are taken when there are fewer than `size`.
107
+ """
108
+ if isinstance(size, bool) or not isinstance(size, int) or size < 2:
109
+ raise ValueError(f"size is how many rows the example draws, at least 2; got {size!r}")
110
+ total = rows_of(inputs, "inputs")
111
+ for name, value in (("prepared", prepared), ("labels", labels), ("targets", targets)):
112
+ if value is not None and not _is_function(value) and rows_of(value, name) != total:
113
+ raise ValueError(
114
+ f"the forms must have the same rows: inputs has {total}, and {name} has "
115
+ f"{rows_of(value, name)}"
116
+ )
117
+ if _is_function(targets) and labels is None:
118
+ raise ValueError("targets is a function of the labels, so the example needs labels too")
119
+ # A random order, not a sorted one: a data set sorted by length would otherwise give a sorted
120
+ # example, and a predictor that sorts a call and forgets to put it back would go unseen.
121
+ rows = random.Random(seed).sample(range(total), min(size, total))
122
+ drawn_inputs = take(inputs, rows)
123
+ drawn_labels = take(labels, rows) if labels is not None else None
124
+ return cls(
125
+ inputs=drawn_inputs,
126
+ prepared=_applied(prepared, drawn_inputs) if _is_function(prepared) else _taken(prepared, rows),
127
+ labels=drawn_labels,
128
+ targets=_applied(targets, drawn_labels) if _is_function(targets) else _taken(targets, rows),
129
+ )
130
+
131
+
132
+ def _is_function(value: Any) -> bool:
133
+ return callable(value) and not _is_array(value)
134
+
135
+
136
+ def _applied(value: Any, argument: Any) -> Any:
137
+ """`value(argument)` when `value` is a function, else `value` as it is."""
138
+ return value(argument) if _is_function(value) else value
139
+
140
+
141
+ def _taken(value: Any, rows: list[int]) -> Any:
142
+ return take(value, rows) if value is not None else None
143
+
144
+
145
+ def _module(value: Any) -> str:
146
+ return type(value).__module__.split(".")[0]
147
+
148
+
149
+ def _is_array(value: Any) -> bool:
150
+ """A NumPy array or a PyTorch tensor."""
151
+ return (_module(value) == "numpy" and type(value).__name__ == "ndarray") or (
152
+ _module(value) == "torch" and hasattr(value, "shape") and hasattr(value, "tolist")
153
+ )
154
+
155
+
156
+ def rows_of(value: Any, name: str) -> int:
157
+ """How many rows a form has: its length, the first dimension of an array, or that of every value of a
158
+ dict, which must agree."""
159
+ if isinstance(value, Mapping):
160
+ lengths = {key: rows_of(item, f"{name}[{key!r}]") for key, item in value.items()}
161
+ if not lengths:
162
+ raise ValueError(f"{name} is an empty dict")
163
+ if len(set(lengths.values())) > 1:
164
+ raise ValueError(f"the values of {name} have different lengths: {lengths}")
165
+ return next(iter(lengths.values()))
166
+ if _is_array(value):
167
+ shape = tuple(value.shape)
168
+ if not shape:
169
+ raise ValueError(f"{name} is a single value, not one row per input")
170
+ return int(shape[0])
171
+ if isinstance(value, str | bytes) or not isinstance(value, Sequence):
172
+ hint = (
173
+ " (for a DataFrame, pass df.to_numpy() or a list of its rows)"
174
+ if _module(value) == "pandas"
175
+ else ""
176
+ )
177
+ raise ValueError(
178
+ f"{name} must be a list, a tuple, an array, a tensor or a dict of them{hint}; got a "
179
+ f"{type(value).__name__}"
180
+ )
181
+ return len(value)
182
+
183
+
184
+ def take(value: Any, rows: list[int]) -> Any:
185
+ """The rows `rows` of a form, in that order, in the form's own kind (a list for a sequence)."""
186
+ if isinstance(value, Mapping):
187
+ return {key: take(item, rows) for key, item in value.items()}
188
+ if _is_array(value):
189
+ if _module(value) == "torch":
190
+ import torch # the tensor is here, so PyTorch is installed and imported already
191
+
192
+ return value[torch.as_tensor(rows, dtype=torch.long, device=value.device)]
193
+ return value[list(rows)]
194
+ return [value[row] for row in rows]
195
+
196
+
197
+ def as_json(value: Any, where: str = "the value") -> Any:
198
+ """`value` as JSON holds it: arrays and tensors become lists, NumPy and PyTorch scalars Python numbers,
199
+ tuples lists. Anything JSON cannot hold is a `ValueError` that says where it is."""
200
+ if _module(value) in {"numpy", "torch"} and hasattr(value, "tolist"):
201
+ found = value.detach().cpu().tolist() if _module(value) == "torch" else value.tolist()
202
+ return as_json(found, where)
203
+ if value is None or isinstance(value, bool | str | int | float):
204
+ return value
205
+ if isinstance(value, Mapping):
206
+ converted = {}
207
+ for key, item in value.items():
208
+ if not isinstance(key, str):
209
+ raise ValueError(f"{where} has the key {key!r}, and the keys of a JSON object are texts")
210
+ converted[key] = as_json(item, f"{where}[{key!r}]")
211
+ return converted
212
+ if isinstance(value, list | tuple):
213
+ return [as_json(item, f"{where}[{index}]") for index, item in enumerate(value)]
214
+ raise ValueError(
215
+ f"{where} is a {type(value).__module__}.{type(value).__qualname__}, which JSON cannot hold"
216
+ )
217
+
218
+
219
+ def as_request(value: Any, where: str) -> Any:
220
+ """An example's input as a request carries it: `as_json`, with the reason in its refusal."""
221
+ try:
222
+ return as_json(value, where)
223
+ except ValueError as error:
224
+ raise ValueError(
225
+ f"an example's inputs are what a request carries, so they must be JSON: {error}; convert it "
226
+ "(a list of numbers, a text)"
227
+ ) from None
228
+
229
+
230
+ def example_file(inputs: list[Any], answers: Mapping[str, list[Any]]) -> str:
231
+ """The text of `proofs/example.json`: the example's inputs and the bundle's answers to them."""
232
+ return json.dumps({"inputs": inputs, **answers}, ensure_ascii=False) + "\n"
233
+
234
+
235
+ def read_example_file(text: str) -> dict[str, Any]:
236
+ """What `example_file` wrote, checked: the inputs, and the answers recorded for them."""
237
+ data = json.loads(text)
238
+ if not (
239
+ isinstance(data, dict)
240
+ and isinstance(data.get("inputs"), list)
241
+ and isinstance(data.get("predict"), list)
242
+ ):
243
+ raise ValueError("an example file holds an object with the lists 'inputs' and 'predict'")
244
+ rows = len(data["inputs"])
245
+ probabilities = data.get("predict_proba", data["predict"])
246
+ if len(data["predict"]) != rows or not isinstance(probabilities, list) or len(probabilities) != rows:
247
+ raise ValueError("an example file has one answer per input")
248
+ return data
@@ -0,0 +1,260 @@
1
+ """The network side of the proofs: a network fed the way training fed it, in evaluation mode, on its device,
2
+ and two prepared inputs or two outputs compared number by number. The only module of `artifacts` that uses
3
+ PyTorch, and only inside its functions, which run only for a bundle whose model is a PyTorch network.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import contextlib
9
+ import math
10
+ from collections.abc import Iterator, Mapping
11
+ from typing import Any
12
+
13
+
14
+ def network_of(model: Any) -> Any:
15
+ """The module a `torch.compile` wrapper holds, or the module itself."""
16
+ return getattr(model, "_orig_mod", model)
17
+
18
+
19
+ def device_of(network: Any) -> str:
20
+ """Where a network's weights are: the device of its first parameter or buffer, or the CPU."""
21
+ for tensor in _tensors_of(network):
22
+ return str(tensor.device)
23
+ return "cpu"
24
+
25
+
26
+ def _tensors_of(network: Any) -> Iterator[Any]:
27
+ yield from network.parameters()
28
+ yield from network.buffers()
29
+
30
+
31
+ def floating_dtype_of(network: Any) -> Any:
32
+ """The type of a network's floating weights, which its floating inputs are converted to."""
33
+ import torch
34
+
35
+ for tensor in _tensors_of(network):
36
+ if tensor.is_floating_point():
37
+ return tensor.dtype
38
+ return torch.get_default_dtype()
39
+
40
+
41
+ def on_device(value: Any, device: str, dtype: Any = None) -> Any:
42
+ """`value` on `device`: tensors moved, NumPy arrays turned into tensors there, and dicts, lists and
43
+ tuples of them followed. With `dtype`, floating tensors take that type (the weights' own), so a
44
+ `float64` array reaches a `float32` network as it would after `.float()`; integer ones (token ids) stay
45
+ as they are."""
46
+ import torch
47
+
48
+ if isinstance(value, torch.Tensor):
49
+ moved = value.to(device)
50
+ return moved.to(dtype) if dtype is not None and moved.is_floating_point() else moved
51
+ if type(value).__module__.split(".")[0] == "numpy" and type(value).__name__ == "ndarray":
52
+ return on_device(torch.as_tensor(value), device, dtype)
53
+ if isinstance(value, Mapping):
54
+ return {key: on_device(item, device, dtype) for key, item in value.items()}
55
+ if isinstance(value, tuple) and hasattr(value, "_fields"): # a named tuple takes its fields one by one
56
+ return type(value)(*(on_device(item, device, dtype) for item in value))
57
+ if isinstance(value, list | tuple):
58
+ return type(value)(on_device(item, device, dtype) for item in value)
59
+ return value
60
+
61
+
62
+ def feed(network: Any, prepared: Any) -> Any:
63
+ """The network's outputs for `prepared`, fed the way `SupervisedTask` feeds a batch: a dict as keyword
64
+ arguments, anything else as one argument; on the network's device, floating inputs in its type, with
65
+ gradients off. Whatever mode the network is in is the caller's."""
66
+ import torch
67
+
68
+ moved = on_device(prepared, device_of(network), floating_dtype_of(network))
69
+ with torch.inference_mode():
70
+ return network(**moved) if isinstance(moved, Mapping) else network(moved)
71
+
72
+
73
+ @contextlib.contextmanager
74
+ def evaluated(network: Any) -> Iterator[Any]:
75
+ """The network in evaluation mode for the time of the block, and every submodule back in the mode it
76
+ had after it: a save must not change the model it was given."""
77
+ modes = {name: module.training for name, module in network.named_modules()}
78
+ network.eval()
79
+ try:
80
+ yield network
81
+ finally:
82
+ for name, module in network.named_modules():
83
+ module.train(modes.get(name, module.training))
84
+
85
+
86
+ @contextlib.contextmanager
87
+ def exact_arithmetic(device: str) -> Iterator[None]:
88
+ """On a GPU, the reduced precision PyTorch may use for float32 matrix products and convolutions (TF32)
89
+ turned off for the time of the block, and back as it was after it, so two runs compare in float32."""
90
+ if not device.startswith("cuda"):
91
+ yield
92
+ return
93
+ import torch
94
+
95
+ saved = (torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32)
96
+ precision = torch.get_float32_matmul_precision()
97
+ torch.backends.cuda.matmul.allow_tf32 = False
98
+ torch.backends.cudnn.allow_tf32 = False
99
+ torch.set_float32_matmul_precision("highest")
100
+ try:
101
+ yield
102
+ finally:
103
+ torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32 = saved
104
+ torch.set_float32_matmul_precision(precision)
105
+
106
+
107
+ # -- prepared inputs and outputs ----------------------------------------------------------------------
108
+
109
+
110
+ def as_floats(value: Any) -> Any:
111
+ """A prepared input or an output as a float64 tensor on the CPU, for a comparison; dicts, tuples and
112
+ lists followed. Anything else stays as it is."""
113
+ import torch
114
+
115
+ if isinstance(value, torch.Tensor):
116
+ return value.detach().cpu().to(torch.float64)
117
+ if _is_numpy_array(value):
118
+ return torch.as_tensor(value).to(torch.float64)
119
+ if isinstance(value, Mapping):
120
+ return {key: as_floats(item) for key, item in value.items()}
121
+ if isinstance(value, list | tuple) and value and all(_is_tensor(v) or _is_numpy_array(v) for v in value):
122
+ return tuple(as_floats(item) for item in value)
123
+ if isinstance(value, list | tuple):
124
+ try:
125
+ return torch.as_tensor(value, dtype=torch.float64)
126
+ except (TypeError, ValueError, RuntimeError):
127
+ return value
128
+ return value
129
+
130
+
131
+ def largest_difference(
132
+ expected: Any, found: Any, *, atol: float, rtol: float = 0.0, where: str = ""
133
+ ) -> dict[str, Any] | None:
134
+ """Where two prepared inputs or two outputs differ beyond `atol + rtol * |expected|`: the place, the
135
+ example (the first dimension), the largest difference and both values there; `None` when they agree.
136
+ Shapes and dict keys must match."""
137
+ import torch
138
+
139
+ one, other = as_floats(expected), as_floats(found)
140
+ if isinstance(one, Mapping) or isinstance(other, Mapping):
141
+ if not (isinstance(one, Mapping) and isinstance(other, Mapping)):
142
+ return {
143
+ "where": where or "the value",
144
+ "reason": f"a {type(expected).__name__} and a {type(found).__name__}",
145
+ }
146
+ if one.keys() != other.keys():
147
+ return {"where": where or "the dict", "reason": f"the keys {sorted(one)} and {sorted(other)}"}
148
+ for key in one:
149
+ difference = largest_difference(
150
+ one[key], other[key], atol=atol, rtol=rtol, where=f"{where}[{key!r}]"
151
+ )
152
+ if difference is not None:
153
+ return difference
154
+ return None
155
+ if isinstance(one, tuple) or isinstance(other, tuple):
156
+ if not (isinstance(one, tuple) and isinstance(other, tuple)) or len(one) != len(other):
157
+ return {"where": where or "the value", "reason": "a different number of parts"}
158
+ for index, (left, right) in enumerate(zip(one, other, strict=True)):
159
+ difference = largest_difference(left, right, atol=atol, rtol=rtol, where=f"{where}[{index}]")
160
+ if difference is not None:
161
+ return difference
162
+ return None
163
+ if not (isinstance(one, torch.Tensor) and isinstance(other, torch.Tensor)):
164
+ same = one == other
165
+ return None if same is True else {"where": where or "the value", "reason": f"{one!r} and {other!r}"}
166
+ if one.shape != other.shape:
167
+ return {
168
+ "where": where or "the value",
169
+ "reason": f"the shapes {tuple(one.shape)} and {tuple(other.shape)}",
170
+ }
171
+ if one.numel() == 0:
172
+ return None
173
+ nan_one, nan_other = one.isnan(), other.isnan()
174
+ gap = (one.nan_to_num() - other.nan_to_num()).abs()
175
+ gap = torch.where(nan_one ^ nan_other, torch.full_like(gap, math.inf), gap)
176
+ allowed = atol + rtol * one.nan_to_num().abs()
177
+ beyond = gap > allowed
178
+ if not bool(beyond.any()):
179
+ return None
180
+ flat = int(torch.argmax(torch.where(beyond, gap, torch.zeros_like(gap))).item())
181
+ position = list(_unravel(flat, tuple(one.shape)))
182
+ return {
183
+ "where": where,
184
+ "example": position[0] if position else None,
185
+ "position": position[1:],
186
+ "largest": float(gap.max().item()),
187
+ "expected": float(one.reshape(-1)[flat].item()),
188
+ "found": float(other.reshape(-1)[flat].item()),
189
+ }
190
+
191
+
192
+ def _unravel(flat: int, shape: tuple[int, ...]) -> Iterator[int]:
193
+ places = []
194
+ for size in reversed(shape):
195
+ places.append(flat % size)
196
+ flat //= size
197
+ return reversed(places)
198
+
199
+
200
+ def probability_defect(outputs: Any, *, atol: float = 1e-4) -> str | None:
201
+ """Why a network's outputs on the example are not probabilities, or `None` when they look like them.
202
+
203
+ - With two columns or more: every row is in [0, 1] and sums to 1, as after a softmax.
204
+ - With one column: every value is in [0, 1], as after a sigmoid. A binary network that answers logits
205
+ gives the negatives values below 0 once it separates the classes; measured on binary networks trained
206
+ to separate them, no 32-row example of their logits was ever all in [0, 1].
207
+
208
+ A row sums to 1 only as far as its type holds (`sum_tolerance`).
209
+ """
210
+ import torch
211
+
212
+ if not isinstance(outputs, torch.Tensor) or outputs.dim() not in (1, 2) or not len(outputs):
213
+ return "they are not a tensor with a row per input"
214
+ values = outputs.detach().cpu()
215
+ tolerance = sum_tolerance(values.dtype, atol)
216
+ values = values.to(torch.float64)
217
+ if values.dim() == 1:
218
+ values = values.unsqueeze(1)
219
+ outside = ~((values >= 0) & (values <= 1))
220
+ if bool(outside.any()):
221
+ row = int(outside.any(dim=1).nonzero()[0])
222
+ return f"row {row} has values outside [0, 1]: {_shown_row(values[row])}"
223
+ if values.shape[1] > 1:
224
+ sums = values.sum(dim=1)
225
+ off = (sums - 1).abs() > tolerance
226
+ if bool(off.any()):
227
+ row = int(off.nonzero()[0])
228
+ return f"row {row} sums to {float(sums[row]):.4g}, not 1: {_shown_row(values[row])}"
229
+ return None
230
+
231
+
232
+ def sum_tolerance(dtype: Any, atol: float) -> float:
233
+ """How far a row of probabilities in `dtype` may be from summing to 1: `atol`, or the type's epsilon
234
+ when that is larger. After a softmax in half precision the rounded values sum to 1 only that closely
235
+ (about 1e-3 in `float16`, 8e-3 in `bfloat16`)."""
236
+ import torch
237
+
238
+ return max(atol, torch.finfo(dtype).eps) if dtype.is_floating_point else atol
239
+
240
+
241
+ def looks_like_probabilities(outputs: Any, *, atol: float = 1e-4) -> bool:
242
+ """Whether a network's outputs on the example already look like probabilities (`probability_defect`)."""
243
+ return probability_defect(outputs, atol=atol) is None
244
+
245
+
246
+ def _shown_row(row: Any, *, most: int = 6) -> str:
247
+ numbers = [f"{value:.4g}" for value in row.tolist()[:most]]
248
+ return "[" + ", ".join(numbers) + (", ...]" if len(row) > most else "]")
249
+
250
+
251
+ def _is_tensor(value: Any) -> bool:
252
+ return (
253
+ type(value).__module__.split(".")[0] == "torch"
254
+ and hasattr(value, "shape")
255
+ and hasattr(value, "dtype")
256
+ )
257
+
258
+
259
+ def _is_numpy_array(value: Any) -> bool:
260
+ return type(value).__module__.split(".")[0] == "numpy" and type(value).__name__ == "ndarray"