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,401 @@
1
+ """Objects a bundle keeps as they are, the trained network and the preparation, with the code they need.
2
+
3
+ A trained network is an object: its structure (the layers, their sizes, a dropout's rate, a temperature set
4
+ after training) and its weights. A preparation is an object too: a function, or one that holds what it
5
+ learned from the training data (a vocabulary, a tokenizer). Python writes an object with `pickle` (here
6
+ through `torch.save`): the object's own data, and, for each class and function it is made of, only a
7
+ reference by name, such as "the class `Residual` of the module `__main__`". Reading it back imports each of
8
+ those names. So the code behind the names has to travel with the object, or be installed where it is read:
9
+
10
+ - a class or function of the notebook (`__main__`) is written as a module of the bundle, from the cells
11
+ that defined it (`notebook.py`), and the object is written naming that module instead of `__main__`,
12
+ which in a service is another program;
13
+ - one from the project's own package on disk travels with that package (`inspection.project_package`);
14
+ - one from an installed library (PyTorch, transformers) is not copied: the manifest's `requires` asks the
15
+ service to install it, at the version that wrote the bundle.
16
+
17
+ The network is written in two files: its structure, with every tensor replaced by an empty one on PyTorch's
18
+ `meta` device, and every tensor in safetensors, by name, its parameters and all its buffers, those the
19
+ `state_dict` leaves out included. Weights read from safetensors never run code, a service that does not
20
+ read pickles at all can still take them, and a tensor shared by two names (tied embeddings) is written once,
21
+ with the other name in the file's metadata.
22
+
23
+ Reading the structure or the preparation back runs code: unpickling imports and calls what the object
24
+ names. A loader does it only for a bundle it was told to trust.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import contextlib
30
+ import hashlib
31
+ import io
32
+ import json
33
+ import pickle
34
+ import sys
35
+ import types
36
+ from collections.abc import Iterator, Mapping, Sequence
37
+ from dataclasses import dataclass
38
+ from pathlib import Path
39
+ from typing import Any
40
+
41
+ from torchstack64.artifacts.code.copy import LIBRARY, BundleCode
42
+ from torchstack64.artifacts.code.inspection import (
43
+ Distributions,
44
+ Origin,
45
+ imports_in_source,
46
+ local_modules,
47
+ origin,
48
+ project_package,
49
+ report_code,
50
+ requirements,
51
+ )
52
+ from torchstack64.artifacts.code.notebook import export_module
53
+ from torchstack64.core import BundleError
54
+
55
+ NOTEBOOK_PREFIX = "notebook_"
56
+ ALIASES_KEY = "torchstack64.aliases" # the safetensors metadata that names the tensors shared by two names
57
+ _MAIN = "__main__"
58
+ _LAMBDA = "<lambda>"
59
+
60
+
61
+ @dataclass(frozen=True, slots=True)
62
+ class ObjectCode:
63
+ """What a set of objects needs to be read back in another program.
64
+
65
+ - `code`: the project's own code to carry: the module written from the notebook, the project's
66
+ packages; `None` when everything comes from installed libraries.
67
+ - `requires`: the installed distributions the objects name, with the versions installed here.
68
+ - `module`: the name of the module written from the notebook, or `None`.
69
+ - `main`: the classes and functions of the notebook that module defines, whose references the
70
+ objects are written with.
71
+ """
72
+
73
+ code: BundleCode | None
74
+ requires: dict[str, str]
75
+ module: str | None
76
+ main: tuple[Any, ...]
77
+
78
+ def pickled(self, value: Any) -> bytes:
79
+ """`value` written by `torch.save`, every class and function of the notebook named as one of
80
+ `module`, the module the bundle carries, instead of `__main__`."""
81
+ import torch
82
+
83
+ buffer = io.BytesIO()
84
+ with _named_from(self.main, self.module):
85
+ torch.save(value, buffer)
86
+ return buffer.getvalue()
87
+
88
+ def where(self, cls: type) -> str:
89
+ """The module a class is imported from in the bundle: the notebook's module for a class of the
90
+ notebook, its own module otherwise."""
91
+ if cls.__module__ == _MAIN:
92
+ assert self.module is not None, "a class of the notebook is in the module written for it"
93
+ return self.module
94
+ return cls.__module__
95
+
96
+
97
+ def code_for_objects(
98
+ objects: Mapping[str, Any], *, installed: Distributions, classes: Sequence[type] = ()
99
+ ) -> ObjectCode:
100
+ """The code and the distributions `objects` need to be read back elsewhere, found by writing them once
101
+ and noting every class and function they name; `classes` adds classes to carry (a predictor class of
102
+ the project's own, which reads the bundle).
103
+
104
+ Refuses, before anything is written, what a service could not import by name: a lambda, a function or a
105
+ class made inside another function, and a name of the notebook whose code cannot be written.
106
+ """
107
+ found: dict[int, Any] = {}
108
+ for role, value in objects.items():
109
+ for named in references(value, role=role):
110
+ found.setdefault(id(named), named)
111
+ for cls in classes:
112
+ found.setdefault(id(cls), cls)
113
+ main = tuple(named for named in found.values() if named.__module__ == _MAIN)
114
+ tops = {named.__module__.split(".")[0] for named in found.values() if named.__module__ != _MAIN}
115
+ tops.discard(LIBRARY) # the library reads every bundle: it is installed wherever one is read
116
+ paths: list[Path] = []
117
+ missing: list[str] = []
118
+ installed_names: set[str] = set()
119
+ for top in sorted(tops):
120
+ kind, _ = origin(top, installed=installed)
121
+ if kind is Origin.LOCAL:
122
+ carried, absent = project_package(top, installed=installed)
123
+ paths.extend(path for path in carried if path not in paths)
124
+ missing.extend(absent)
125
+ elif kind is Origin.INSTALLED:
126
+ installed_names.add(top)
127
+ elif kind is Origin.MISSING and top != LIBRARY:
128
+ missing.append(top)
129
+ modules: dict[str, str] = {}
130
+ module = None
131
+ if main:
132
+ text = export_module(*main)
133
+ module = NOTEBOOK_PREFIX + hashlib.sha256(text.encode("utf-8")).hexdigest()[:8]
134
+ modules[module] = text
135
+ carried, absent = local_modules(imports_in_source(text), installed=installed, own={module})
136
+ paths.extend(path for path in carried if path not in paths)
137
+ missing.extend(absent)
138
+ code = BundleCode(paths, modules=modules) if paths or modules else None
139
+ owner = ", ".join(sorted(objects))
140
+ if code is not None:
141
+ report_code(code, sorted(set(missing)), owner=owner)
142
+ return ObjectCode(code, requirements(installed_names, installed), module, main)
143
+
144
+
145
+ def references(value: Any, *, role: str = "the object") -> list[Any]:
146
+ """Every class and function `value` names when it is written, as pickling it would, in the order
147
+ found; a lambda or a function made inside another is refused, naming `role`."""
148
+ import torch
149
+
150
+ seen: list[Any] = []
151
+ refused: list[str] = []
152
+ made: list[_Recording] = []
153
+
154
+ class Noted(_Recording): # torch.save subclasses pickle_module.Pickler: it must be a class
155
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
156
+ super().__init__(*args, **kwargs)
157
+ self.seen, self.refused = seen, refused
158
+ made.append(self)
159
+
160
+ recording = types.ModuleType("torchstack64_recording_pickle")
161
+ vars(recording).update({name: getattr(pickle, name) for name in dir(pickle) if not name.startswith("__")})
162
+ recording.Pickler = Noted # type: ignore[attr-defined]
163
+ try:
164
+ torch.save(value, io.BytesIO(), pickle_module=recording)
165
+ except (pickle.PicklingError, TypeError, AttributeError) as error:
166
+ if refused:
167
+ raise BundleError(f"{role} cannot travel in a bundle: {refused[0]}", refused=refused) from None
168
+ raise BundleError(
169
+ f"{role} cannot be written: {error}. An object a bundle keeps is written with pickle, so what it "
170
+ "holds must be picklable (no open file, no lock, no generator)",
171
+ role=role,
172
+ ) from error
173
+ if refused:
174
+ raise BundleError(f"{role} cannot travel in a bundle: {refused[0]}", refused=refused)
175
+ return seen
176
+
177
+
178
+ class _Recording(pickle.Pickler):
179
+ """A pickler that notes every class and function it writes by name, and refuses the ones a service could
180
+ not import by name. It only looks: each name is written as a stand-in, so a name this process could not
181
+ look up (a class of a notebook simulated in a test) is still noted, and the rest of the object, its data,
182
+ is written as pickle writes it, so what cannot be pickled at all is found too."""
183
+
184
+ seen: list[Any]
185
+ refused: list[str]
186
+
187
+ def reducer_override(self, obj: Any) -> Any:
188
+ if not isinstance(obj, type | types.FunctionType) or obj is _named or obj.__module__ == "builtins":
189
+ return NotImplemented
190
+ name = getattr(obj, "__qualname__", "")
191
+ if name == _LAMBDA or name.endswith("." + _LAMBDA):
192
+ self.refused.append(
193
+ "it is, or holds, a lambda, which has no name a service could import it by: write it "
194
+ "with def, at the top of a cell or a module"
195
+ )
196
+ elif "<locals>" in name:
197
+ self.refused.append(
198
+ f"{name} is defined inside a function: define it at the top of a cell or a module, so a "
199
+ "service can import it by name"
200
+ )
201
+ elif all(obj is not known for known in self.seen):
202
+ self.seen.append(obj)
203
+ return _named, (f"{obj.__module__}.{name}",)
204
+
205
+
206
+ def _named(name: str) -> str:
207
+ """What a class or function is written as while `references` looks for names: its name, nothing more."""
208
+ return name
209
+
210
+
211
+ @contextlib.contextmanager
212
+ def _named_from(main: Sequence[Any], module: str | None) -> Iterator[None]:
213
+ """For the time of the block, the classes and functions of the notebook say they come from `module`, a
214
+ module that holds them, so pickle writes them under that name; everything goes back after it."""
215
+ if not main:
216
+ yield
217
+ return
218
+ assert module is not None
219
+ stand_in = types.ModuleType(module)
220
+ for named in main:
221
+ setattr(stand_in, named.__name__, named)
222
+ previous = sys.modules.get(module)
223
+ saved = {id(named): named.__module__ for named in main}
224
+ sys.modules[module] = stand_in
225
+ try:
226
+ for named in main:
227
+ named.__module__ = module
228
+ yield
229
+ finally:
230
+ for named in main:
231
+ named.__module__ = saved[id(named)]
232
+ if previous is None:
233
+ sys.modules.pop(module, None)
234
+ else:
235
+ sys.modules[module] = previous
236
+
237
+
238
+ # -- the network: the structure and the tensors, apart ------------------------------------------------------
239
+
240
+
241
+ @dataclass(frozen=True, slots=True)
242
+ class NetworkTensors:
243
+ """The tensors of a network by name, each written once, and the other names of a tensor shared by two."""
244
+
245
+ tensors: dict[str, Any]
246
+ aliases: dict[str, str]
247
+
248
+ def metadata(self) -> dict[str, str]:
249
+ """What the safetensors file keeps beside the tensors: the shared names."""
250
+ return {ALIASES_KEY: json.dumps(self.aliases, sort_keys=True)} if self.aliases else {}
251
+
252
+
253
+ @contextlib.contextmanager
254
+ def tensors_set_aside(network: Any) -> Iterator[NetworkTensors]:
255
+ """For the time of the block, every parameter and buffer of `network` is an empty tensor of the same
256
+ shape and type on PyTorch's `meta` device, so the network can be written without its weights; the
257
+ tensors are handed to the block, and put back after it, the same objects, whatever happens.
258
+
259
+ A tensor shared by two names stays shared: both names hold the same empty tensor, and the second one is
260
+ an alias of the first. Nothing is copied: the weights are in memory once.
261
+ """
262
+ import torch
263
+ from torch import nn
264
+
265
+ places = list(_tensor_places(network))
266
+ first: dict[int, str] = {}
267
+ tensors: dict[str, Any] = {}
268
+ aliases: dict[str, str] = {}
269
+ empty: dict[int, Any] = {}
270
+ for name, _, _, tensor, is_parameter in places:
271
+ key = id(tensor)
272
+ if key in first:
273
+ aliases[name] = first[key]
274
+ continue
275
+ first[key] = name
276
+ tensors[name] = tensor
277
+ stand_in = torch.empty_like(tensor, device="meta")
278
+ empty[key] = nn.Parameter(stand_in, requires_grad=tensor.requires_grad) if is_parameter else stand_in
279
+ try:
280
+ for _, owner, leaf, tensor, _ in places:
281
+ setattr(owner, leaf, empty[id(tensor)])
282
+ yield NetworkTensors(tensors, aliases)
283
+ finally:
284
+ for _, owner, leaf, tensor, _ in places:
285
+ setattr(owner, leaf, tensor)
286
+
287
+
288
+ def _tensor_places(network: Any) -> Iterator[tuple[str, Any, str, Any, bool]]:
289
+ """Every parameter and buffer of `network`, shared ones under each of their names: the full name, the
290
+ module that holds it, its name there, the tensor, and whether it is a parameter."""
291
+ for owner_name, owner in network.named_modules(remove_duplicate=False):
292
+ for leaf, tensor in list(owner._parameters.items()):
293
+ if tensor is not None:
294
+ yield (f"{owner_name}.{leaf}" if owner_name else leaf), owner, leaf, tensor, True
295
+ for leaf, tensor in list(owner._buffers.items()):
296
+ if tensor is not None:
297
+ yield (f"{owner_name}.{leaf}" if owner_name else leaf), owner, leaf, tensor, False
298
+
299
+
300
+ def read_object(path: Path, *, on_cpu: bool = True) -> Any:
301
+ """An object written by `ObjectCode.pickled`, its tensors on the CPU (`on_cpu=False` leaves them where
302
+ they were written: the empty ones of a network's structure stay empty). This runs code: the bundle must
303
+ be trusted, and its code already importable (`importing.import_bundle_code`)."""
304
+ import torch
305
+
306
+ with path.open("rb") as handle:
307
+ return torch.load(handle, map_location="cpu" if on_cpu else None, weights_only=False)
308
+
309
+
310
+ def read_network(structure: Path, tensors: Mapping[str, Any], metadata: Mapping[str, str]) -> Any:
311
+ """The network written by `tensors_set_aside` and `ObjectCode.pickled`: its structure read back, and
312
+ each tensor put in its place, the shared ones shared again. Refuses a structure with a place no tensor
313
+ filled. This runs code, as `read_object` does."""
314
+ import torch
315
+ from torch import nn
316
+
317
+ network = read_object(structure, on_cpu=False)
318
+ if not isinstance(network, nn.Module):
319
+ raise BundleError(f"{structure.name} holds a {type(network).__name__}, not a network")
320
+ place_tensors(network, tensors, metadata)
321
+ empty = sorted(
322
+ name
323
+ for name, owner, leaf, _, _ in _tensor_places(network)
324
+ if isinstance(getattr(owner, leaf), torch.Tensor) and getattr(owner, leaf).is_meta
325
+ )
326
+ if empty:
327
+ raise BundleError(f"the bundle's weights leave places of the network empty: {empty[:5]}", empty=empty)
328
+ return network
329
+
330
+
331
+ def place_tensors(
332
+ network: Any, tensors: Mapping[str, Any], metadata: Mapping[str, str], *, must_fit: bool = False
333
+ ) -> None:
334
+ """Puts each tensor of a bundle's weights in its place in `network`, by name, and shares again the
335
+ tensors the bundle wrote once for two names.
336
+
337
+ The network keeps what the bundle says: the tensors' values and types, and which names share one tensor.
338
+ With `must_fit=True`, for a network somebody else built, the names (both ways) and the shapes are checked
339
+ first, and a network that does not fit is refused, naming what differs, before anything is changed: a
340
+ network of another shape would otherwise take the bundle's weights and quietly become the bundle's
341
+ network, while the code that built it says something else.
342
+ """
343
+ from torch import nn
344
+
345
+ places = {
346
+ name: (owner, leaf, is_parameter) for name, owner, leaf, _, is_parameter in _tensor_places(network)
347
+ }
348
+ aliases = json.loads(metadata.get(ALIASES_KEY, "{}"))
349
+ if must_fit:
350
+ _refuse_a_network_that_does_not_fit(places, tensors, aliases)
351
+ unknown = sorted((set(tensors) | set(aliases) | set(aliases.values())) - set(places))
352
+ if unknown:
353
+ raise BundleError(f"the weights name tensors the network does not have: {unknown[:5]}")
354
+ for name, tensor in tensors.items():
355
+ owner, leaf, is_parameter = places[name]
356
+ old = getattr(owner, leaf)
357
+ value = nn.Parameter(tensor, requires_grad=old.requires_grad) if is_parameter else tensor
358
+ setattr(owner, leaf, value)
359
+ for name, target in aliases.items():
360
+ owner, leaf, _ = places[name]
361
+ target_owner, target_leaf, _ = places[target]
362
+ setattr(owner, leaf, getattr(target_owner, target_leaf))
363
+
364
+
365
+ def _refuse_a_network_that_does_not_fit(
366
+ places: Mapping[str, tuple[Any, str, bool]], tensors: Mapping[str, Any], aliases: Mapping[str, str]
367
+ ) -> None:
368
+ """The names the network and the bundle do not share, and the tensors whose shapes differ."""
369
+ given = set(tensors) | set(aliases)
370
+ own_only = sorted(set(places) - given)
371
+ bundle_only = sorted(given - set(places))
372
+ shapes: list[str] = []
373
+ for name in sorted(set(places) & given):
374
+ owner, leaf, _ = places[name]
375
+ theirs = tensors[aliases.get(name, name)]
376
+ ours = getattr(owner, leaf)
377
+ if tuple(ours.shape) != tuple(theirs.shape):
378
+ shapes.append(
379
+ f"{name} is {tuple(theirs.shape)} in the bundle and {tuple(ours.shape)} in your network"
380
+ )
381
+ if not (own_only or bundle_only or shapes):
382
+ return
383
+ parts = [
384
+ *_listed(shapes),
385
+ *_listed([f"{name} is in your network and not in the bundle" for name in own_only]),
386
+ *_listed([f"{name} is in the bundle and not in your network" for name in bundle_only]),
387
+ ]
388
+ raise BundleError(
389
+ "the network you passed does not fit the bundle's weights: " + "; ".join(parts),
390
+ shapes=shapes,
391
+ only_in_network=own_only,
392
+ only_in_bundle=bundle_only,
393
+ )
394
+
395
+
396
+ def _listed(lines: list[str]) -> list[str]:
397
+ """At most five of `lines`, and how many more there are."""
398
+ shown = lines[:5]
399
+ if len(lines) > 5:
400
+ shown.append(f"and {len(lines) - 5} more like these")
401
+ return shown
@@ -0,0 +1,117 @@
1
+ """From a bundle to a ready predictor, for a bundle you trust: a service, a command, an HTTP layer.
2
+
3
+ predictor = load_trusted_predictor("outputs/digits")
4
+
5
+ The manifest says the predictor that reads the bundle: the library's own `TorchClassifier`, for a
6
+ classifier's network and its preparation, or a class in the bundle's own code. This door builds it with the
7
+ bundle's code, so it runs that code: the objects are read back and the predictor imported, after every file
8
+ matched its checksum and the packages the bundle needs were found installed. Use it for a bundle from a
9
+ source you trust.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+ import os
16
+ from collections.abc import Callable
17
+ from typing import Any
18
+
19
+ from torchstack64.artifacts.bundle import ArtifactBundle
20
+ from torchstack64.artifacts.code import import_predictor_factory
21
+ from torchstack64.artifacts.predictor import LOAD_ATOL, BundlePredictor, TorchPredictor, check_atol
22
+ from torchstack64.artifacts.proofs import examine
23
+ from torchstack64.artifacts.sources import ModelSource
24
+ from torchstack64.core import BundleError, Predictor
25
+ from torchstack64.devices import current_device
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ _Builder = Callable[[ArtifactBundle, str], Predictor[Any, Any]]
30
+ """Builds a predictor from a bundle and a device name; a predictor class's `load` is one."""
31
+
32
+
33
+ def load_trusted_predictor(
34
+ source: ModelSource | str | os.PathLike[str],
35
+ *,
36
+ device: str | None = None,
37
+ check_example: bool = True,
38
+ atol: float = LOAD_ATOL,
39
+ ) -> Predictor[Any, Any]:
40
+ """The predictor of the bundle `source` names, on `device` (the library's default when `None`), after
41
+ it answered the bundle's example as the bundle did when it was written. **It runs the bundle's code**
42
+ (its objects are read back, its predictor imported): use it for a bundle from a source you trust.
43
+
44
+ `source` is a folder, a `ModelSource`, or a text: `"hf://<repo>@<revision>"`, `"runs:/<run id>/model"`.
45
+ The predictor is the one the manifest names (the library's own `TorchClassifier`, or a class in the
46
+ bundle's code). The bundle's files are checked against their checksums before any of its code runs. A
47
+ predictor loaded this way keeps the bundle it came from in `bundle`. For a bundle you do not trust, bring
48
+ the code yourself: `TorchClassifier.load(folder, network=..., prepare=...)`.
49
+
50
+ The example is checked once: an answer that differs beyond `atol` is a `ProofError` that says what
51
+ changed since the save; `check_example=False` skips it, and the log says so. A bundle written without
52
+ proofs loads with a warning.
53
+ """
54
+ bundle = ArtifactBundle.read(source, verify=True)
55
+ builder = _builder_of(bundle)
56
+ resolved = current_device(device)
57
+ predictor = _build_predictor(builder, bundle, resolved)
58
+ outcome = examine(predictor, bundle, check_example=check_example, atol=atol)
59
+ logger.info(
60
+ "loaded the bundle at %s on %s, with %s; %s",
61
+ bundle.root,
62
+ resolved,
63
+ bundle.predictor,
64
+ outcome,
65
+ )
66
+ return predictor
67
+
68
+
69
+ def check_example(predictor: Any, bundle: ArtifactBundle, *, atol: float = LOAD_ATOL) -> None:
70
+ """Checks a predictor you built yourself against the bundle's example: it answers the example's inputs,
71
+ and must answer what the bundle answered when it was written. Raises `ProofError`, saying what changed,
72
+ when it does not. Every other door does this on its own; this one is for a predictor made some other way
73
+ (a network run by another engine, say) from a bundle read with `ArtifactBundle.read(folder, verify=True)`.
74
+
75
+ A bundle written without proofs has no example to check: this warns, as loading it does.
76
+ """
77
+ check_atol(atol)
78
+ examine(predictor, bundle, check_example=True, atol=atol)
79
+
80
+
81
+ def _builder_of(bundle: ArtifactBundle) -> _Builder:
82
+ """What builds the bundle's predictor: the predictor its manifest names, imported now (which runs the
83
+ bundle's code); `BundleError` when the manifest names none."""
84
+ if bundle.predictor is None:
85
+ raise BundleError(
86
+ f"the bundle at {bundle.root} names no predictor to read it: load it with the class that wrote "
87
+ "it, MyClass.load(folder)",
88
+ root=str(bundle.root),
89
+ )
90
+ return import_predictor_factory(bundle)
91
+
92
+
93
+ def _predictor_class_of(factory: _Builder) -> type[BundlePredictor[Any, Any]] | None:
94
+ """The predictor class whose own, unchanged `load` `factory` is, or `None`."""
95
+ owner = getattr(factory, "__self__", None)
96
+ function = getattr(factory, "__func__", None)
97
+ if isinstance(owner, type) and issubclass(owner, BundlePredictor) and function in _CLASS_LOADS:
98
+ return owner
99
+ return None
100
+
101
+
102
+ # The functions behind every class's own `load`: the base's, and the one every PyTorch predictor inherits
103
+ # (`TorchClassifier`'s too), which asks for trust when called by hand; here the loader has already decided.
104
+ _CLASS_LOADS = (vars(BundlePredictor)["load"].__func__, vars(TorchPredictor)["load"].__func__)
105
+
106
+
107
+ def _build_predictor(builder: _Builder, bundle: ArtifactBundle, device: str) -> Predictor[Any, Any]:
108
+ """What `builder` builds from the bundle on `device`, refused when it cannot answer `predict`. A
109
+ predictor class's own `load` builds it without checking the example, which the loader checks once."""
110
+ owner = _predictor_class_of(builder)
111
+ predictor = owner._from_bundle(bundle, device) if owner is not None else builder(bundle, device)
112
+ if not callable(getattr(predictor, "predict", None)):
113
+ raise BundleError(
114
+ f"{bundle.predictor} returned {type(predictor).__name__}, which has no predict method",
115
+ root=str(bundle.root),
116
+ )
117
+ return predictor