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,220 @@
1
+ """The manifest of a bundle (`bundle.json`): what is in the folder, and how to read it back.
2
+
3
+ The classes it records are a `LabelSchema`, which lives in `torchstack64.core`: training and serving use it
4
+ beyond the manifest.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from collections.abc import Mapping
11
+ from dataclasses import dataclass, field, fields
12
+ from pathlib import PurePosixPath
13
+ from typing import Any
14
+
15
+ from torchstack64.core import BundleError, LabelSchema
16
+
17
+ BUNDLE_FORMAT = "torchstack64.bundle"
18
+ BUNDLE_VERSION = "1"
19
+
20
+ _SHA256 = re.compile(r"^[0-9a-f]{64}$")
21
+
22
+
23
+ def split_predictor_path(text: str) -> tuple[str, str]:
24
+ """`"package.module:Class.load"` as `("package.module", "Class.load")`, or `ValueError` saying why.
25
+
26
+ It is how a manifest names the predictor that reads the bundle: the module to import, and the attribute
27
+ in it that builds the predictor from the bundle."""
28
+ module, colon, attribute = str(text).partition(":")
29
+ parts = [*module.split("."), *attribute.split(".")]
30
+ if not colon or not all(part.isidentifier() for part in parts):
31
+ raise ValueError(
32
+ "a predictor is named as 'module:attribute', such as 'my_project.serving:MyPredictor.load'; got "
33
+ f"{text!r}"
34
+ )
35
+ return module, attribute
36
+
37
+
38
+ def safe_relative_path(path: str) -> str:
39
+ """`path` as a POSIX path inside the bundle, or `BundleError` if it would point outside it."""
40
+ text = str(path).replace("\\", "/").strip()
41
+ pure = PurePosixPath(text)
42
+ if not text or pure.is_absolute() or re.match(r"^[A-Za-z]:", text) or ".." in pure.parts:
43
+ raise BundleError(
44
+ f"a bundle path must be relative and stay inside the bundle; got {path!r}", path=path
45
+ )
46
+ normalized = pure.as_posix()
47
+ if normalized in {"", "."}:
48
+ raise BundleError(f"a bundle path must name a file or a folder; got {path!r}", path=path)
49
+ return normalized
50
+
51
+
52
+ @dataclass(frozen=True, slots=True, kw_only=True)
53
+ class ProofRecord:
54
+ """What `save_bundle` proved about the bundle, and what it did not, with the reason.
55
+
56
+ - `passed`: the proofs that ran and passed, in the order they ran;
57
+ - `skipped`: each proof that did not run, and why (a model the library does not run, a regression);
58
+ - `example`: where the bundle keeps the example it was proved on, with its answers;
59
+ - `batch_dependent`: the save said that an answer depends on the rest of its call, on purpose;
60
+ - `device`: where the proofs ran.
61
+ """
62
+
63
+ passed: tuple[str, ...] = ()
64
+ skipped: dict[str, str] = field(default_factory=dict)
65
+ example: str = "proofs/example.json"
66
+ batch_dependent: bool = False
67
+ device: str | None = None
68
+
69
+ def to_json(self) -> dict[str, Any]:
70
+ return {
71
+ "passed": list(self.passed),
72
+ "skipped": dict(self.skipped),
73
+ "example": self.example,
74
+ "batch_dependent": self.batch_dependent,
75
+ "device": self.device,
76
+ }
77
+
78
+ @classmethod
79
+ def from_json(cls, data: object) -> ProofRecord:
80
+ """Reads a record as `to_json` writes it, checking every field: it comes from the disk."""
81
+ if not isinstance(data, Mapping):
82
+ raise BundleError("bundle.json 'proofs' must be null, or an object")
83
+ missing = [f.name for f in fields(cls) if f.name not in data]
84
+ if missing:
85
+ raise BundleError(f"bundle.json 'proofs' lacks {', '.join(missing)}", missing=missing)
86
+ passed, skipped = data["passed"], data["skipped"]
87
+ if not isinstance(passed, list) or not all(isinstance(name, str) for name in passed):
88
+ raise BundleError("bundle.json 'proofs.passed' must list the names of the proofs that passed")
89
+ if not isinstance(skipped, Mapping) or not all(
90
+ isinstance(k, str) and isinstance(v, str) for k, v in skipped.items()
91
+ ):
92
+ raise BundleError("bundle.json 'proofs.skipped' must map each proof that did not run to why")
93
+ example, device = data["example"], data["device"]
94
+ if not isinstance(example, str):
95
+ raise BundleError("bundle.json 'proofs.example' must be the path of the example in the bundle")
96
+ if device is not None and not isinstance(device, str):
97
+ raise BundleError("bundle.json 'proofs.device' must be null or a string")
98
+ if not isinstance(data["batch_dependent"], bool):
99
+ raise BundleError("bundle.json 'proofs.batch_dependent' must be true or false")
100
+ return cls(
101
+ passed=tuple(passed),
102
+ skipped=dict(skipped),
103
+ example=safe_relative_path(example),
104
+ batch_dependent=data["batch_dependent"],
105
+ device=device,
106
+ )
107
+
108
+
109
+ @dataclass(frozen=True, slots=True, kw_only=True)
110
+ class BundleManifest:
111
+ """What `bundle.json` says.
112
+
113
+ - `artifacts`: each file of the bundle, by its logical name (`"weights"`) and relative path.
114
+ - `label_schema`: the classes the predictor answers with, in the order of the model's columns.
115
+ - `predictor`: the predictor that reads the bundle, as `"module:attribute"`: the library's own
116
+ `TorchClassifier`, or a class in the bundle's code. `None` for a bundle written without one.
117
+ - `code`: the folder, inside the bundle, of the project's own code that travels with it, or `None`.
118
+ - `requires`: the installed distributions that code and the saved objects need, each with the version
119
+ that wrote the bundle: what a service installs. `created_with` is wider: every distribution the
120
+ writing process had imported, notebook tools included.
121
+ - `proofs`: what `save_bundle` proved about the bundle; `None` for a bundle written without it
122
+ (`ArtifactBundle.write`), which nothing proved.
123
+ """
124
+
125
+ artifacts: dict[str, str]
126
+ label_schema: LabelSchema | None = None
127
+ predictor: str | None = None
128
+ code: str | None = None
129
+ requires: dict[str, str] = field(default_factory=dict)
130
+ proofs: ProofRecord | None = None
131
+ metrics: dict[str, float] = field(default_factory=dict)
132
+ checksums: dict[str, str] = field(default_factory=dict)
133
+ metadata: dict[str, Any] = field(default_factory=dict)
134
+ created_at: str | None = None
135
+ created_with: dict[str, str] = field(default_factory=dict)
136
+
137
+ def to_json(self) -> dict[str, Any]:
138
+ data: dict[str, Any] = {
139
+ "format": BUNDLE_FORMAT,
140
+ "bundle_version": BUNDLE_VERSION,
141
+ "label_schema": self.label_schema.to_json() if self.label_schema is not None else None,
142
+ "predictor": self.predictor,
143
+ "code": self.code,
144
+ "requires": dict(self.requires),
145
+ "proofs": self.proofs.to_json() if self.proofs is not None else None,
146
+ "artifacts": dict(self.artifacts),
147
+ "checksums": dict(sorted(self.checksums.items())),
148
+ "metrics": dict(self.metrics),
149
+ "metadata": dict(self.metadata),
150
+ "created_at": self.created_at,
151
+ "created_with": dict(self.created_with),
152
+ }
153
+ return data
154
+
155
+ @classmethod
156
+ def from_json(cls, data: object) -> BundleManifest:
157
+ """Reads a manifest as `to_json` writes it, checking every field: it comes from the disk."""
158
+ if not isinstance(data, Mapping):
159
+ raise BundleError("bundle.json must hold a JSON object")
160
+ fmt = data.get("format")
161
+ if fmt != BUNDLE_FORMAT:
162
+ raise BundleError(f"bundle.json is not a torchstack64 manifest (format {fmt!r})", format=fmt)
163
+ version = data.get("bundle_version")
164
+ if version != BUNDLE_VERSION:
165
+ raise BundleError(
166
+ f"this bundle was written with manifest version {version!r}, and this torchstack64 reads "
167
+ f"version {BUNDLE_VERSION!r}: upgrade torchstack64",
168
+ bundle_version=version,
169
+ )
170
+ # `format` and `bundle_version` are present, checked above; every field with a default is
171
+ # still required on the disk, because `to_json` always writes it.
172
+ missing = [f.name for f in fields(cls) if f.name not in data]
173
+ if missing:
174
+ raise BundleError(f"bundle.json lacks {', '.join(missing)}", missing=missing)
175
+ artifacts = data["artifacts"]
176
+ if not isinstance(artifacts, Mapping) or not all(isinstance(v, str) for v in artifacts.values()):
177
+ raise BundleError("bundle.json must map each artifact name to a relative path")
178
+ checksums = data["checksums"]
179
+ if not isinstance(checksums, Mapping) or not all(
180
+ isinstance(v, str) and _SHA256.match(v) for v in checksums.values()
181
+ ):
182
+ raise BundleError("bundle.json has checksums that are not SHA-256 hex digests")
183
+ for name in ("metrics", "metadata", "created_with"):
184
+ if not isinstance(data[name], Mapping):
185
+ raise BundleError(f"bundle.json '{name}' must be an object")
186
+ requires = data["requires"]
187
+ if not isinstance(requires, Mapping) or not all(
188
+ isinstance(k, str) and isinstance(v, str) for k, v in requires.items()
189
+ ):
190
+ raise BundleError("bundle.json 'requires' must map each distribution's name to its version")
191
+ created_at = data["created_at"]
192
+ if created_at is not None and not isinstance(created_at, str):
193
+ raise BundleError("bundle.json 'created_at' must be a string")
194
+ predictor, code = data["predictor"], data["code"]
195
+ if predictor is not None and not isinstance(predictor, str):
196
+ raise BundleError("bundle.json 'predictor' must be null, or 'module:attribute'")
197
+ if code is not None and not isinstance(code, str):
198
+ raise BundleError("bundle.json 'code' must be null, or the folder of the bundle's code")
199
+ proofs = ProofRecord.from_json(data["proofs"]) if data["proofs"] is not None else None
200
+ schema = data["label_schema"]
201
+ try:
202
+ label_schema = LabelSchema.from_json(schema) if schema is not None else None
203
+ if predictor is not None:
204
+ split_predictor_path(predictor)
205
+ metrics = {str(k): float(v) for k, v in data["metrics"].items()}
206
+ except (KeyError, TypeError, ValueError) as error:
207
+ raise BundleError(f"bundle.json has an invalid field: {error}") from error
208
+ return cls(
209
+ artifacts={str(name): safe_relative_path(path) for name, path in artifacts.items()},
210
+ label_schema=label_schema,
211
+ predictor=predictor,
212
+ code=safe_relative_path(code) if code is not None else None,
213
+ requires=dict(requires),
214
+ proofs=proofs,
215
+ metrics=metrics,
216
+ checksums={safe_relative_path(path): str(digest) for path, digest in checksums.items()},
217
+ metadata=dict(data["metadata"]),
218
+ created_at=created_at,
219
+ created_with={str(k): str(v) for k, v in data["created_with"].items()},
220
+ )
@@ -0,0 +1,45 @@
1
+ """The predictors a bundle is read back into: what serving code calls, raw inputs in, answers out.
2
+
3
+ - `bundle_predictor`: `BundlePredictor`, the base every predictor loaded from a bundle shares, and the class
4
+ a project writes for a model the library does not run itself: it writes `pack`, `unpack` and `predict`.
5
+ - `torch_predictor`: `TorchPredictor`, the base for a PyTorch network: the network and its preparation come
6
+ from the bundle, and a subclass writes `predict`, for an answer the schema does not derive.
7
+ - `torch_classifier`: `TorchClassifier`, the library's own predictor for a PyTorch classifier: the schema
8
+ and the reading of the outputs come from the bundle too, and `predict` and `predict_proba` are derived.
9
+ - `output_reading`: how a classifier's outputs are read: as logits, by default, or as probabilities.
10
+ """
11
+
12
+ from torchstack64.artifacts.predictor.bundle_predictor import (
13
+ LOAD_ATOL,
14
+ SAVE_ATOL,
15
+ BundlePredictor,
16
+ check_atol,
17
+ classes_of,
18
+ )
19
+ from torchstack64.artifacts.predictor.output_reading import OUTPUTS, OutputReading, Outputs
20
+ from torchstack64.artifacts.predictor.torch_classifier import READING, TorchClassifier
21
+ from torchstack64.artifacts.predictor.torch_predictor import (
22
+ NETWORK,
23
+ PREPARE,
24
+ WEIGHTS,
25
+ TorchPredictor,
26
+ untrusted_message,
27
+ )
28
+
29
+ __all__ = [
30
+ "LOAD_ATOL",
31
+ "NETWORK",
32
+ "OUTPUTS",
33
+ "PREPARE",
34
+ "READING",
35
+ "SAVE_ATOL",
36
+ "WEIGHTS",
37
+ "BundlePredictor",
38
+ "OutputReading",
39
+ "Outputs",
40
+ "TorchClassifier",
41
+ "TorchPredictor",
42
+ "check_atol",
43
+ "classes_of",
44
+ "untrusted_message",
45
+ ]
@@ -0,0 +1,193 @@
1
+ """`BundlePredictor`: the base of every predictor that is loaded from a bundle, and the class a project writes
2
+ for a model the library does not run itself (scikit-learn, LightGBM, a rule).
3
+
4
+ A predictor is what serving code calls: raw inputs in, one answer per input out (`core.Predictor`). For a
5
+ PyTorch classifier, the library has its own, `TorchClassifier`, and nothing needs to be written; any other
6
+ answer from a PyTorch network is a `TorchPredictor` subclass that writes `predict`. For any other model, a
7
+ subclass of this class says four things the library cannot know:
8
+
9
+ - `pack(model)`: what of the trained model goes in the bundle, by logical name (a state dict becomes
10
+ safetensors, a dict JSON, a text a text file);
11
+ - `unpack(bundle, device)`: how those files become the predictor again;
12
+ - `predict(inputs)`: how it answers, raw inputs in;
13
+ - `trained_predict(model, rows)`: what the trained model answers, for the save to prove the bundle against.
14
+
15
+ `save_bundle(model, folder, data=val, predictor=MyPredictor)` writes the bundle and proves it before it
16
+ exists; `MyPredictor.load(folder)` reads it back with the class's own code, after it
17
+ answered the bundle's example as it did when it was written.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import inspect
23
+ import logging
24
+ import math
25
+ import os
26
+ from abc import abstractmethod
27
+ from collections.abc import Callable, Mapping, Sequence
28
+ from typing import Any, Self
29
+
30
+ from torchstack64.artifacts.bundle import ArtifactBundle
31
+ from torchstack64.artifacts.proofs import examine
32
+ from torchstack64.artifacts.sources import ModelSource
33
+ from torchstack64.core import BundleError, LabelSchema, Predictor
34
+ from torchstack64.devices import current_device
35
+
36
+ logger = logging.getLogger(__name__)
37
+
38
+ SAVE_ATOL = 1e-5 # two runs on one device: the noise measured on a CPU is about 2e-7
39
+ LOAD_ATOL = 1e-4 # maybe another machine, another version, another device
40
+
41
+
42
+ class BundlePredictor[InputT, OutputT](Predictor[InputT, OutputT]):
43
+ """A predictor that loads itself from a bundle, checking the bundle's example first.
44
+
45
+ A subclass for a model of its own writes `pack`, `unpack`, `predict` and `trained_predict` (and
46
+ `predict_proba`, if it can say how sure it is, with `trained_predict_proba`), and, for a classifier,
47
+ sets `label_schema`. Then:
48
+
49
+ save_bundle(model, "outputs/my-model", data=val, predictor=MyPredictor)
50
+ predictor = MyPredictor.load("outputs/my-model") # or a ModelSource, "hf://...", "runs:/..."
51
+ predictor.predict(inputs)
52
+
53
+ A class reads the bundles it wrote: the bundle records the class's path (`bundle.predictor`), and the
54
+ files `unpack` asks for by name must be in it. A bundle another class wrote lacks some of them, and the
55
+ `UnknownArtifactError` that says so lists what the bundle does have.
56
+ """
57
+
58
+ label_schema: LabelSchema | None = None
59
+ bundle: ArtifactBundle
60
+
61
+ @classmethod
62
+ @abstractmethod
63
+ def pack(cls, model: Any) -> Mapping[str, Any]:
64
+ """What of a trained model goes in the bundle, by logical name: a state dict becomes safetensors,
65
+ a `str` text, a `Path` a copy, anything JSON can hold a JSON file (`as_bundle_file`)."""
66
+
67
+ @classmethod
68
+ @abstractmethod
69
+ def unpack(cls, bundle: ArtifactBundle, device: str) -> Self:
70
+ """The predictor, built from a bundle this class saved, on `device`."""
71
+
72
+ @abstractmethod
73
+ def predict(self, inputs: Sequence[InputT]) -> list[OutputT]:
74
+ """One answer per input, in the same order; everything before the model (cleaning, tokenizing,
75
+ batching) happens here, because a service only ever passes raw inputs."""
76
+
77
+ @classmethod
78
+ @abstractmethod
79
+ def trained_predict(cls, model: Any, rows: Any) -> Sequence[Any]:
80
+ """What the trained `model` answers for `rows`, the example's inputs after the project's preparation,
81
+ one answer per row. Only `save_bundle` calls it, with the model it was given: the bundle is proved
82
+ against these answers, and refused if it answers differently. A PyTorch network needs none, because
83
+ the library runs it itself."""
84
+
85
+ @classmethod
86
+ def trained_predict_proba(cls, model: Any, rows: Any) -> Sequence[Any] | None:
87
+ """What the trained `model` gives as probabilities for `rows`, one row per example, when this class
88
+ writes `predict_proba`; `None` otherwise, and then only `predict` is proved."""
89
+ return None
90
+
91
+ # -- load --------------------------------------------------------------------------------------------
92
+
93
+ @classmethod
94
+ def load(
95
+ cls,
96
+ source: ArtifactBundle | ModelSource | str | os.PathLike[str],
97
+ device: str | None = None,
98
+ *,
99
+ verify: bool = True,
100
+ check_example: bool = True,
101
+ atol: float = LOAD_ATOL,
102
+ ) -> Self:
103
+ """The predictor built from the bundle `source` names, on `device` (the library's default when
104
+ `None`), after it answered the bundle's example as the bundle did when it was written.
105
+
106
+ `source` is a folder, a `ModelSource`, a text (`"hf://<repo>@<revision>"`, `"runs:/<run id>/model"`)
107
+ or a bundle already read. The bundle's files are checked against their checksums first, unless
108
+ `verify=False`. This class's own code builds the predictor: the code the bundle carries is not
109
+ imported, so nothing needs to be trusted. A different answer to the example, beyond `atol`, is a
110
+ `ProofError` that says what changed since the save; `check_example=False` skips the check, and the
111
+ log says so.
112
+ """
113
+ return cls._load_with(
114
+ cls._from_bundle, source, device, verify=verify, check_example=check_example, atol=atol
115
+ )
116
+
117
+ @classmethod
118
+ def _load_with(
119
+ cls,
120
+ build: Callable[[ArtifactBundle, str], Self],
121
+ source: ArtifactBundle | ModelSource | str | os.PathLike[str],
122
+ device: str | None,
123
+ *,
124
+ verify: bool,
125
+ check_example: bool,
126
+ atol: float,
127
+ ) -> Self:
128
+ """What every `load` does around the way it builds the predictor: refuse an incomplete class, read the
129
+ bundle (and check its files), build, and check the example."""
130
+ cls._refuse_if_incomplete("loaded")
131
+ check_atol(atol)
132
+ if isinstance(source, ArtifactBundle):
133
+ bundle, read_here = source, False # a loader read and verified it already
134
+ else:
135
+ bundle, read_here = ArtifactBundle.read(source, verify=verify), True
136
+ resolved = current_device(device)
137
+ predictor = build(bundle, resolved)
138
+ outcome = examine(predictor, bundle, check_example=check_example, atol=atol)
139
+ logger.log(
140
+ logging.INFO if read_here else logging.DEBUG,
141
+ "loaded the bundle at %s on %s with %s; %s",
142
+ bundle.root,
143
+ resolved,
144
+ cls.__qualname__,
145
+ outcome,
146
+ )
147
+ return predictor
148
+
149
+ @classmethod
150
+ def _from_bundle(cls, bundle: ArtifactBundle, device: str) -> Self:
151
+ """The predictor of a bundle already read, on `device`, without the example's check: what `load`
152
+ builds before checking it, and what `load_trusted_predictor` builds before checking it once."""
153
+ cls._refuse_if_incomplete("loaded")
154
+ cls._refuse_if_cannot_answer(bundle.label_schema)
155
+ predictor = cls.unpack(bundle, device)
156
+ if not isinstance(predictor, cls):
157
+ raise BundleError(
158
+ f"{cls.__name__}.unpack returned {type(predictor).__name__}, not a {cls.__name__}",
159
+ root=str(bundle.root),
160
+ )
161
+ predictor.bundle = bundle
162
+ if not isinstance(inspect.getattr_static(cls, "label_schema", None), property):
163
+ predictor.label_schema = bundle.label_schema # what these weights were trained on
164
+ return predictor
165
+
166
+ @classmethod
167
+ def _refuse_if_cannot_answer(cls, schema: LabelSchema | None) -> None:
168
+ """A class that leaves something to derive and lacks what it is derived from. Nothing here."""
169
+
170
+ @classmethod
171
+ def _refuse_if_incomplete(cls, action: str) -> None:
172
+ missing = sorted(getattr(cls, "__abstractmethods__", ()))
173
+ if missing:
174
+ raise TypeError(f"{cls.__name__} cannot be {action}: it does not write {', '.join(missing)}")
175
+
176
+
177
+ def classes_of(model: Any) -> tuple[Any, ...] | None:
178
+ """The order of a model's columns, when it keeps it (`classes_`, as scikit-learn does), as Python."""
179
+ try:
180
+ classes = getattr(model, "classes_", None)
181
+ except Exception: # a model whose attributes fail to compute keeps nothing here
182
+ return None
183
+ if classes is None or isinstance(classes, str | bytes):
184
+ return None
185
+ try:
186
+ return tuple(value.item() if hasattr(value, "item") else value for value in classes)
187
+ except TypeError:
188
+ return None
189
+
190
+
191
+ def check_atol(atol: float) -> None:
192
+ if isinstance(atol, bool) or not isinstance(atol, int | float) or not math.isfinite(atol) or atol < 0:
193
+ raise ValueError(f"atol is how far apart two numbers may be, a number of 0 or more; got {atol!r}")
@@ -0,0 +1,96 @@
1
+ """How a classifier's network outputs become probabilities, in `TorchClassifier.predict_proba`.
2
+
3
+ A network trained with `CrossEntropyLoss` or `BCEWithLogitsLoss` answers logits: raw numbers, one per
4
+ column. A network that ends in a softmax or a sigmoid answers probabilities. `save_bundle(outputs=...)` says
5
+ which, and `"logits"`, what almost every classifier is trained to answer, is the default; the bundle keeps
6
+ it in `reading.json`, and the save's log says which one it applied and whether it was the default. The
7
+ columns say the rest:
8
+
9
+ | `outputs` | The network answers | The reading |
10
+ |---|---|---|
11
+ | `"logits"` | one column per class | a softmax over the columns |
12
+ | `"logits"` | one column, for a binary schema | a sigmoid over the column: `[1 - p, p]` |
13
+ | `"probabilities"` | one column per class | the columns as they are |
14
+ | `"probabilities"` | one column, for a binary schema | the column as it is: `[1 - p, p]` |
15
+ | any | another number of columns | refused |
16
+
17
+ The save proves the reading on the example, in both directions: outputs read as logits that already look
18
+ like probabilities are refused, and so are outputs read as probabilities that are not (the `outputs` proof
19
+ names the one to pass instead). A network that ends in a `log_softmax` is read as logits: the softmax of its
20
+ outputs gives its probabilities back.
21
+
22
+ Who calls it: `TorchClassifier` applies the reading in `predict_proba`, and tells the save which one to
23
+ prove; the outputs proof checks it on the example; a loaded classifier reads it back from `reading.json`.
24
+ Nothing outside the library needs it: the one thing a user says is `save_bundle(outputs=...)`, and only for a
25
+ network that already ends in a softmax or a sigmoid.
26
+
27
+ An ordinal schema never reaches it (`TorchClassifier` refuses one, since there are too many conventions to
28
+ pick one silently), nor do multi-label networks and regressions: a `TorchPredictor` subclass of their own
29
+ writes `predict` (and `predict_proba`).
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ from collections.abc import Mapping
35
+ from dataclasses import dataclass
36
+ from typing import Any, Literal, get_args
37
+
38
+ from torchstack64.core import LabelSchema, ProofError
39
+
40
+ Outputs = Literal["logits", "probabilities"]
41
+ OUTPUTS: tuple[str, ...] = get_args(Outputs)
42
+
43
+
44
+ @dataclass(frozen=True, slots=True)
45
+ class OutputReading:
46
+ """How the outputs of a classifier's network are read: as `logits` or as `probabilities`. The bundle
47
+ keeps it, so a service reads them as they were read when the bundle was written."""
48
+
49
+ outputs: Outputs
50
+
51
+ def to_json(self) -> dict[str, Any]:
52
+ return {"outputs": self.outputs}
53
+
54
+ @classmethod
55
+ def from_json(cls, data: Mapping[str, Any]) -> OutputReading:
56
+ outputs = data.get("outputs")
57
+ if outputs not in OUTPUTS:
58
+ raise ValueError(f"an output reading is one of {OUTPUTS}; got {outputs!r}")
59
+ return cls(outputs) # type: ignore[arg-type]
60
+
61
+ def probabilities(self, outputs: Any, schema: LabelSchema, *, subject: str) -> Any:
62
+ """The network's `outputs` as one row of probabilities per input, one column per class, as a
63
+ tensor; or `ProofError` naming the shape received and the one expected."""
64
+ import torch
65
+
66
+ if not isinstance(outputs, torch.Tensor):
67
+ raise ProofError(
68
+ f"the network of {subject} answers a {type(outputs).__name__}, and the derived reading needs "
69
+ "one tensor with a row per input and a column per class: write predict_proba (and predict) "
70
+ "to read it",
71
+ proof="outputs",
72
+ )
73
+ values = outputs.detach()
74
+ if not values.is_floating_point() or values.dtype in (torch.float16, torch.bfloat16):
75
+ values = values.float() # a softmax in half precision loses what the comparisons look at
76
+ if values.dim() == 1:
77
+ values = values.unsqueeze(1) # one logit per input, as a binary network often answers
78
+ classes = len(schema.classes)
79
+ if values.dim() != 2:
80
+ raise ProofError(
81
+ f"the network of {subject} answers a tensor of shape {tuple(outputs.shape)}, and the derived "
82
+ f"reading needs one row per input and one column per class ({classes}): write predict_proba",
83
+ proof="outputs",
84
+ )
85
+ columns = values.shape[1]
86
+ if columns == classes:
87
+ return values.softmax(dim=1) if self.outputs == "logits" else values
88
+ if columns == 1 and schema.kind == "binary":
89
+ positive = values[:, 0].sigmoid() if self.outputs == "logits" else values[:, 0]
90
+ return torch.stack([1 - positive, positive], dim=1)
91
+ raise ProofError(
92
+ f"the network of {subject} answers {columns} column{'s' if columns != 1 else ''} per input, and "
93
+ f"the schema has {classes} classes {schema.classes}"
94
+ + (": a binary schema takes one column, or one per class" if schema.kind == "binary" else ""),
95
+ proof="outputs",
96
+ )
@@ -0,0 +1,106 @@
1
+ """`TorchClassifier`: the library's own predictor for a PyTorch classifier, the one `save_bundle` is given
2
+ (`predictor=TorchClassifier`) when the data has classes and the network answers them.
3
+
4
+ A subclass changes `batch_size`, or writes `predict_proba` to read the probabilities another way (an average
5
+ over shifted copies of each input, say), and `predict` still decides over them. An answer the schema does
6
+ not derive (an ordinal scale, a regression) is not a classifier's: a `TorchPredictor` subclass writes it.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Callable, Sequence
12
+ from typing import TYPE_CHECKING, Any, ClassVar
13
+
14
+ from torchstack64.artifacts.bundle import ArtifactBundle
15
+ from torchstack64.artifacts.predictor.output_reading import OUTPUTS, OutputReading, Outputs
16
+ from torchstack64.artifacts.predictor.torch_predictor import TorchPredictor
17
+ from torchstack64.artifacts.proofs import feed
18
+ from torchstack64.core import LabelSchema
19
+
20
+ if TYPE_CHECKING:
21
+ from torch import nn
22
+
23
+ READING = "reading" # how the network's outputs are read: reading.json
24
+
25
+
26
+ class TorchClassifier[InputT, OutputT](TorchPredictor[InputT, OutputT]):
27
+ """The predictor of a bundle `save_bundle` wrote from a PyTorch classifier: the network, the preparation,
28
+ the label schema and the reading of the outputs, all from the bundle; `predict_proba` and `predict`
29
+ derived from them.
30
+
31
+ `batch_size` is how many inputs `predict_proba` gives the network at once.
32
+ """
33
+
34
+ batch_size: ClassVar[int] = 256
35
+ label_schema: LabelSchema
36
+
37
+ def __init__(
38
+ self,
39
+ network: nn.Module,
40
+ prepare: Callable[[list[Any]], Any],
41
+ label_schema: LabelSchema,
42
+ *,
43
+ outputs: Outputs = "logits",
44
+ device: str = "cpu",
45
+ ) -> None:
46
+ if outputs not in OUTPUTS:
47
+ raise ValueError(f"outputs is one of {OUTPUTS}; got {outputs!r}")
48
+ type(self)._refuse_if_cannot_answer(label_schema)
49
+ super().__init__(network, prepare, label_schema, device=device)
50
+ self.reading = OutputReading(outputs)
51
+
52
+ def __init_subclass__(cls, **kwargs: Any) -> None:
53
+ super().__init_subclass__(**kwargs)
54
+ size = vars(cls).get("batch_size", 1)
55
+ if isinstance(size, bool) or not isinstance(size, int) or size < 1:
56
+ raise TypeError(
57
+ f"{cls.__name__}.batch_size is a whole number of inputs, at least 1; got {size!r}"
58
+ )
59
+
60
+ def predict_proba(self, inputs: Sequence[InputT]) -> list[list[float]]:
61
+ """One row of probabilities per input, one column per class in the schema's order, read from the
62
+ network's outputs as the bundle says."""
63
+ rows: list[list[float]] = []
64
+ for start in range(0, len(inputs), self.batch_size):
65
+ outputs = feed(self.network, self.prepare(list(inputs[start : start + self.batch_size])))
66
+ rows.extend(
67
+ self.reading.probabilities(outputs, self.label_schema, subject=type(self).__name__).tolist()
68
+ )
69
+ return rows
70
+
71
+ def predict(self, inputs: Sequence[InputT]) -> list[OutputT]:
72
+ """One class per input: the schema's decision over `predict_proba`, the most probable class or the
73
+ threshold of a binary schema."""
74
+ return self.label_schema.decide(self.predict_proba(inputs)) # type: ignore[return-value]
75
+
76
+ # -- what the save and the load ask ---------------------------------------------------------------------
77
+
78
+ @classmethod
79
+ def _refuse_if_cannot_answer(cls, schema: LabelSchema | None) -> None:
80
+ """A classifier answers one of the schema's classes, so it needs a schema, and one with a single rule
81
+ from outputs to answers."""
82
+ if schema is None:
83
+ raise TypeError(
84
+ f"{cls.__name__} answers one of a label schema's classes, and there is none (a network "
85
+ "trained without labels, or LabeledData without schema=): write predict in a TorchPredictor "
86
+ "subclass, and give it to save_bundle(..., predictor=)"
87
+ )
88
+ if schema.kind == "ordinal":
89
+ raise TypeError(
90
+ "the schema is ordinal, which has no single rule to read a network's outputs (cumulative "
91
+ "logits, a plain softmax) nor to turn them into an answer: write predict (and predict_proba) "
92
+ "in a TorchPredictor subclass, and give it to save_bundle(..., predictor=)"
93
+ )
94
+
95
+ @classmethod
96
+ def _reading_to_prove(cls, outputs: Outputs) -> OutputReading | None:
97
+ """How the save reads the network's outputs, for the outputs proof: `None` when a subclass writes its
98
+ own `predict_proba`, and reads them itself."""
99
+ if cls.predict_proba is not TorchClassifier.predict_proba:
100
+ return None
101
+ return OutputReading(outputs)
102
+
103
+ @classmethod
104
+ def _keywords_from(cls, bundle: ArtifactBundle) -> dict[str, Any]:
105
+ """The reading of the outputs the bundle recorded, for the constructor."""
106
+ return {"outputs": OutputReading.from_json(bundle.read_json(READING)).outputs}