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,461 @@
1
+ """From a trained model to a bundle that is proved before it exists: `save_bundle`.
2
+
3
+ save_bundle(model, "outputs/digits", data=val, predictor=TorchClassifier)
4
+
5
+ `model` is what training produced, `data` the validation data training used: a `LabeledData` (the raw
6
+ inputs, the labels, the preparation and the classes), or a `PreparedData` (the raw inputs and the
7
+ preparation) for a network trained without labels; and `predictor` the class that serves the model once
8
+ loaded, which is always said: `TorchClassifier` for a classifier, a class based on `TorchPredictor` for
9
+ any other PyTorch network, or a class based on `BundlePredictor` for a model the of the project's own
10
+ for any other answer.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import contextlib
16
+ import functools
17
+ import importlib
18
+ import logging
19
+ import os
20
+ import sys
21
+ from collections.abc import Callable, Iterator, Mapping
22
+ from pathlib import Path
23
+ from typing import Any, Literal
24
+
25
+ from torchstack64.artifacts.bundle import ArtifactBundle, BundleFile, as_bundle_file, write_bundle
26
+ from torchstack64.artifacts.code import (
27
+ LIBRARY,
28
+ code_for_class,
29
+ code_for_objects,
30
+ distributions,
31
+ requirements,
32
+ tensors_set_aside,
33
+ )
34
+ from torchstack64.artifacts.manifest import ProofRecord
35
+ from torchstack64.artifacts.predictor import (
36
+ NETWORK,
37
+ OUTPUTS,
38
+ PREPARE,
39
+ READING,
40
+ SAVE_ATOL,
41
+ WEIGHTS,
42
+ BundlePredictor,
43
+ OutputReading,
44
+ Outputs,
45
+ TorchClassifier,
46
+ TorchPredictor,
47
+ check_atol,
48
+ classes_of,
49
+ )
50
+ from torchstack64.artifacts.proofs import (
51
+ Example,
52
+ Proved,
53
+ Subject,
54
+ device_of,
55
+ network_of,
56
+ prove_on_example,
57
+ shown_names,
58
+ )
59
+ from torchstack64.core import LabelSchema, ProofError
60
+ from torchstack64.devices import current_device
61
+
62
+ logger = logging.getLogger(__name__)
63
+
64
+ LIBRARY_PREDICTOR = "torchstack64.artifacts:TorchClassifier.load"
65
+
66
+
67
+ def save_bundle(
68
+ model: Any,
69
+ folder: str | os.PathLike[str],
70
+ *,
71
+ data: Any,
72
+ predictor: type[BundlePredictor[Any, Any]] | None = None,
73
+ outputs: Outputs | None = None,
74
+ batch_dependent: bool = False,
75
+ metrics: Mapping[str, float] | None = None,
76
+ metadata: Mapping[str, Any] | None = None,
77
+ overwrite: bool = False,
78
+ atol: float = SAVE_ATOL,
79
+ ) -> ArtifactBundle:
80
+ """Writes the bundle of `model` at `folder`, proved on a sample of `data`, and returns it.
81
+
82
+ - `data`: the validation data, as training used it: a `LabeledData`, or a `PreparedData` for a network
83
+ trained without labels. Its preparation and its schema (none, without labels) go in the bundle, and
84
+ its rows are what the bundle is proved on.
85
+ - `predictor`: the class that serves the model once the bundle is loaded, always given. The library's
86
+ own `TorchClassifier` serves a PyTorch classifier, whose data has classes. A class of the project's own
87
+ serves any other answer: for a PyTorch network, a `TorchPredictor` subclass that writes `predict`; it
88
+ travels in the bundle. For any other model, a `BundlePredictor` subclass with `pack`, `unpack`,
89
+ `predict` and `trained_predict` (what the trained model answers, which the bundle is proved against).
90
+ - `outputs`: how a classifier's network outputs are read, `"logits"` (a network trained with
91
+ `CrossEntropyLoss` or `BCEWithLogitsLoss`, and what is read when this is left out) or
92
+ `"probabilities"` (one that ends in a softmax or a sigmoid). The proofs check it on the example in
93
+ both directions, and the log says which reading the bundle got and whether it was the default.
94
+ - `batch_dependent=True`: the model's answer to an input depends, on purpose, on the rest of its call;
95
+ the batch proof is skipped, and the bundle says so at every load.
96
+ - `atol`: how far apart two numbers may be in the proofs' comparisons.
97
+
98
+ A folder with files in it is refused unless `overwrite=True`; a proof that fails leaves no bundle, and
99
+ the folder as it was, even then. The model is given back in the mode it was in (training or evaluation).
100
+ """
101
+ data = _prepared_data(data)
102
+ check_atol(atol)
103
+ if outputs is not None and outputs not in OUTPUTS:
104
+ raise ValueError(f"outputs is one of {OUTPUTS}; got {outputs!r}")
105
+ if not isinstance(batch_dependent, bool):
106
+ raise TypeError(f"batch_dependent is True or False; got {batch_dependent!r}")
107
+ if predictor is None:
108
+ raise TypeError(
109
+ "save_bundle needs predictor=, the class that serves the model: TorchClassifier for a PyTorch "
110
+ "classifier; a TorchPredictor subclass of yours that writes predict, for any other PyTorch "
111
+ "network; a BundlePredictor subclass of yours, with pack, unpack, predict and trained_predict, "
112
+ "for a model the library does not run (scikit-learn, LightGBM, a rule)"
113
+ )
114
+ if not (isinstance(predictor, type) and issubclass(predictor, BundlePredictor)):
115
+ raise TypeError(
116
+ "predictor is TorchClassifier, or a predictor class of your own: a subclass of TorchPredictor "
117
+ f"(for a network) or of BundlePredictor (for any other model); got {predictor!r}"
118
+ )
119
+ if issubclass(predictor, TorchPredictor):
120
+ if outputs is not None and not issubclass(predictor, TorchClassifier):
121
+ raise ValueError(
122
+ f"outputs= says how the library reads a classifier's outputs, and {predictor.__name__} reads "
123
+ "its network's outputs itself"
124
+ )
125
+ return _save_network(
126
+ model,
127
+ Path(folder),
128
+ data=data,
129
+ cls=predictor,
130
+ outputs=outputs or "logits",
131
+ outputs_declared=outputs is not None,
132
+ batch_dependent=batch_dependent,
133
+ metrics=metrics,
134
+ metadata=metadata,
135
+ overwrite=overwrite,
136
+ atol=atol,
137
+ )
138
+ if outputs not in (None, "logits"):
139
+ raise ValueError(
140
+ f"outputs= says how the library reads a network's outputs, and {predictor.__name__} reads its "
141
+ "model's answers itself"
142
+ )
143
+ return _save_with_class(
144
+ model,
145
+ Path(folder),
146
+ data=data,
147
+ cls=predictor,
148
+ batch_dependent=batch_dependent,
149
+ metrics=metrics,
150
+ metadata=metadata,
151
+ overwrite=overwrite,
152
+ atol=atol,
153
+ )
154
+
155
+
156
+ # -- a PyTorch network ---------------------------------------------------------------------------------------
157
+
158
+
159
+ def _save_network(
160
+ model: Any,
161
+ folder: Path,
162
+ *,
163
+ data: Any,
164
+ cls: type[TorchPredictor[Any, Any]],
165
+ outputs: Outputs,
166
+ outputs_declared: bool,
167
+ batch_dependent: bool,
168
+ metrics: Mapping[str, float] | None,
169
+ metadata: Mapping[str, Any] | None,
170
+ overwrite: bool,
171
+ atol: float,
172
+ ) -> ArtifactBundle:
173
+ network = network_of(model)
174
+ if not _is_module(network):
175
+ raise TypeError(
176
+ f"{cls.__name__} serves a trained PyTorch network, an nn.Module; got {type(model).__name__}. A "
177
+ "model of another kind is saved with predictor= a BundlePredictor class of your own"
178
+ )
179
+ schema = data.schema
180
+ cls._refuse_if_incomplete("saved")
181
+ cls._refuse_if_cannot_answer(schema)
182
+ reading = cls._reading_to_prove(outputs) if issubclass(cls, TorchClassifier) else None
183
+ skipped = {}
184
+ if reading is None:
185
+ skipped["outputs"] = (
186
+ "the predictor reads its network's outputs itself"
187
+ if schema is not None
188
+ else "no label schema: the predictor answers no classes"
189
+ )
190
+ example = data.example()
191
+ device = device_of(network)
192
+ installed = distributions()
193
+ with tensors_set_aside(network) as tensors:
194
+ objects = code_for_objects(
195
+ {"the network": network, "the preparation": data.prepare},
196
+ installed=installed,
197
+ classes=[] if cls is TorchClassifier else [cls],
198
+ )
199
+ structure = objects.pickled(network)
200
+ preparation = objects.pickled(data.prepare)
201
+ files = {
202
+ NETWORK: BundleFile("network.pt", functools.partial(_write_bytes, data=structure)),
203
+ WEIGHTS: BundleFile.tensors("weights.safetensors", tensors.tensors, metadata=tensors.metadata()),
204
+ PREPARE: BundleFile("prepare.pt", functools.partial(_write_bytes, data=preparation)),
205
+ }
206
+ if issubclass(cls, TorchClassifier): # only a classifier's outputs are read by the library
207
+ files[READING] = BundleFile.json("reading.json", OutputReading(outputs).to_json())
208
+ reader = LIBRARY_PREDICTOR if cls is TorchClassifier else f"{objects.where(cls)}:{cls.__qualname__}.load"
209
+ needs = {**objects.requires, **requirements({LIBRARY, "safetensors", "torch"}, installed)}
210
+ subject = Subject(cls.__name__, schema, batch_dependent=batch_dependent, network=network, reading=reading)
211
+ found: list[Proved] = []
212
+
213
+ def prove(staged: ArtifactBundle) -> tuple[ProofRecord, Mapping[str, Any]]:
214
+ with _imported_from(staged.root):
215
+ proved = prove_on_example(
216
+ staged,
217
+ load=functools.partial(cls._from_bundle, device=device),
218
+ subject=subject,
219
+ example=example,
220
+ atol=atol,
221
+ device=device,
222
+ skipped=skipped,
223
+ )
224
+ found.append(proved)
225
+ return proved.record, proved.files
226
+
227
+ bundle = write_bundle(
228
+ folder,
229
+ files=files,
230
+ label_schema=schema,
231
+ code=objects.code,
232
+ predictor=reader,
233
+ requires=needs,
234
+ metrics=metrics,
235
+ metadata=metadata,
236
+ overwrite=overwrite,
237
+ installed=installed,
238
+ prove=prove,
239
+ )
240
+ _log_saved(bundle, found[0], len(example), reading, declared=outputs_declared)
241
+ return bundle
242
+
243
+
244
+ def _write_bytes(path: Path, *, data: bytes) -> None:
245
+ path.write_bytes(data)
246
+
247
+
248
+ @contextlib.contextmanager
249
+ def _imported_from(root: Path) -> Iterator[None]:
250
+ """For the time of the block, the bundle's code may be imported from `root`, the staging folder, without
251
+ Python writing its bytecode there; after it, what was imported from there leaves `sys.modules` and `root`
252
+ leaves the import path, so the bundle, once moved into place, is imported from its own folder the next
253
+ time it is loaded."""
254
+ inside = root.resolve()
255
+ path = list(sys.path)
256
+ bytecode = sys.dont_write_bytecode
257
+ sys.dont_write_bytecode = True
258
+ try:
259
+ yield
260
+ finally:
261
+ sys.dont_write_bytecode = bytecode
262
+ for name, module in list(sys.modules.items()):
263
+ where = getattr(module, "__file__", None)
264
+ if where and Path(where).resolve().is_relative_to(inside):
265
+ del sys.modules[name]
266
+ sys.path[:] = [entry for entry in sys.path if entry in path]
267
+ importlib.invalidate_caches()
268
+
269
+
270
+ def _is_module(value: Any) -> bool:
271
+ return any(
272
+ kind.__name__ == "Module" and kind.__module__ == "torch.nn.modules.module"
273
+ for kind in type(value).__mro__
274
+ )
275
+
276
+
277
+ # -- a model of its own class -------------------------------------------------------------------------------
278
+
279
+
280
+ def _save_with_class(
281
+ model: Any,
282
+ folder: Path,
283
+ *,
284
+ data: Any,
285
+ cls: type[BundlePredictor[Any, Any]],
286
+ batch_dependent: bool,
287
+ metrics: Mapping[str, float] | None,
288
+ metadata: Mapping[str, Any] | None,
289
+ overwrite: bool,
290
+ atol: float,
291
+ ) -> ArtifactBundle:
292
+ cls._refuse_if_incomplete("saved")
293
+ schema, by_classes = _schema_for(cls, model, data.schema)
294
+ cls._refuse_if_cannot_answer(schema)
295
+ example = data.example()
296
+ answers = _trained_answers(cls, model, example)
297
+ passed = ["labels"] if by_classes else []
298
+ skipped = {"outputs": "a model of its own class: it reads its model's answers itself"}
299
+ subject = Subject(cls.__name__, schema, trained=answers, batch_dependent=batch_dependent)
300
+ installed = distributions()
301
+ code, reader = code_for_class(cls, installed=installed)
302
+ values = cls.pack(model)
303
+ if not isinstance(values, Mapping):
304
+ raise TypeError(
305
+ f"{cls.__name__}.pack must return a mapping of logical names to values; got "
306
+ f"{type(values).__name__}"
307
+ )
308
+ files = {str(name): as_bundle_file(str(name), value) for name, value in values.items()}
309
+ device = current_device(None)
310
+ found: list[Proved] = []
311
+
312
+ def prove(staged: ArtifactBundle) -> tuple[ProofRecord, Mapping[str, Any]]:
313
+ proved = prove_on_example(
314
+ staged,
315
+ load=functools.partial(cls._from_bundle, device=device),
316
+ subject=subject,
317
+ example=example,
318
+ atol=atol,
319
+ device=device,
320
+ passed=passed,
321
+ skipped=skipped,
322
+ )
323
+ found.append(proved)
324
+ return proved.record, proved.files
325
+
326
+ bundle = write_bundle(
327
+ folder,
328
+ files=files,
329
+ label_schema=schema,
330
+ code=code,
331
+ predictor=reader,
332
+ metrics=metrics,
333
+ metadata=metadata,
334
+ overwrite=overwrite,
335
+ installed=installed,
336
+ prove=prove,
337
+ )
338
+ _log_saved(bundle, found[0], len(example))
339
+ return bundle
340
+
341
+
342
+ def _schema_for(
343
+ cls: type[BundlePredictor[Any, Any]], model: Any, given: LabelSchema | None
344
+ ) -> tuple[LabelSchema | None, bool]:
345
+ """This fit's schema: the data's, or the class's; or, for a model that keeps the order of its columns in
346
+ `classes_` (scikit-learn, LightGBM), derived from it, and checked against it. Says whether `classes_`
347
+ proved the order."""
348
+ schema = given if given is not None else cls.label_schema
349
+ if schema is not None and not isinstance(schema, LabelSchema):
350
+ raise TypeError(f"{cls.__name__}'s label_schema must be a LabelSchema or None; got {schema!r}")
351
+ classes = classes_of(model)
352
+ if classes is not None and schema is None:
353
+ kind: Literal["binary", "categorical"] = "binary" if len(classes) == 2 else "categorical"
354
+ schema = LabelSchema(kind, classes, threshold=0.5 if kind == "binary" else None)
355
+ elif classes is not None and schema is not None and tuple(schema.classes) != classes:
356
+ raise ProofError(
357
+ f"the schema's classes {schema.classes} are not in the order of the model's classes_ "
358
+ f"{classes}, which is the order of its columns: write the schema in that order, "
359
+ f"LabelSchema(..., {classes})",
360
+ proof="labels",
361
+ )
362
+ return schema, classes is not None
363
+
364
+
365
+ def _trained_answers(
366
+ cls: type[BundlePredictor[Any, Any]], model: Any, example: Example
367
+ ) -> dict[str, list[Any]]:
368
+ """What the trained model answers for the example's prepared rows, as the class says it: `predict`, and
369
+ the probabilities when the class says those too."""
370
+ answers = {"predict": _as_list(cls.trained_predict(model, example.prepared), cls, "trained_predict")}
371
+ probabilities = cls.trained_predict_proba(model, example.prepared)
372
+ if probabilities is not None:
373
+ answers["predict_proba"] = _as_list(probabilities, cls, "trained_predict_proba")
374
+ return answers
375
+
376
+
377
+ def _as_list(found: Any, cls: type[BundlePredictor[Any, Any]], method: str) -> list[Any]:
378
+ try:
379
+ return found.tolist() if hasattr(found, "tolist") else list(found)
380
+ except TypeError:
381
+ raise TypeError(
382
+ f"{cls.__name__}.{method} gives one answer per row, as a list or an array; got "
383
+ f"{type(found).__name__}"
384
+ ) from None
385
+
386
+
387
+ # -- shared --------------------------------------------------------------------------------------------------
388
+
389
+
390
+ def _prepared_data(data: Any) -> Any:
391
+ """`data` when it is a `PreparedData` (a `LabeledData` is one), told without importing PyTorch: neither
392
+ can exist without it."""
393
+ module = sys.modules.get("torchstack64.data.base")
394
+ kind = getattr(module, "PreparedData", None) if module is not None else None
395
+ if kind is None or not isinstance(data, kind):
396
+ raise TypeError(
397
+ "data is the validation data training used: a LabeledData(inputs, labels, prepare=..., "
398
+ "schema=...), or a PreparedData(inputs, prepare=...) for a network trained without labels; got "
399
+ f"{type(data).__name__}"
400
+ )
401
+ return data
402
+
403
+
404
+ def _log_saved(
405
+ bundle: ArtifactBundle,
406
+ proved: Proved,
407
+ size: int,
408
+ reading: OutputReading | None = None,
409
+ *,
410
+ declared: bool = False,
411
+ ) -> None:
412
+ """The save's one line: what was proved, the accuracy on the example and, when the library reads the
413
+ network's outputs, how it read them and whether `outputs=` said so or it was the default."""
414
+ accuracy = proved.accuracy
415
+ logger.info(
416
+ "bundle at %s proved on %d examples: %s%s%s",
417
+ bundle.root,
418
+ size,
419
+ shown_names(proved.record.passed),
420
+ f" (served accuracy on the example {accuracy:.3f})" if accuracy is not None else "",
421
+ f"; outputs read as {reading.outputs} ({'declared' if declared else 'the default'})"
422
+ if reading is not None
423
+ else "",
424
+ )
425
+
426
+
427
+ def writer_of(writer: Any) -> tuple[Callable[..., Any], dict[str, Any]]:
428
+ """The function a writer calls, with the keywords `functools.partial` gave it, the outer ones winning."""
429
+ keywords: dict[str, Any] = {}
430
+ target = writer
431
+ while isinstance(target, functools.partial):
432
+ keywords = {**target.keywords, **keywords}
433
+ target = target.func
434
+ return target, keywords
435
+
436
+
437
+ def missing_evidence(writer: Any) -> str | None:
438
+ """Why `writer` could not prove the bundles it writes, or `None`.
439
+
440
+ `writer` is what an `MLflowLogger` is given to write the bundle at the end of the fit. `save_bundle`
441
+ needs the validation data then, so one given without it is refused before the first epoch, not after
442
+ the last. Any other function (a project's own writer) is not checked.
443
+ """
444
+ target, keywords = writer_of(writer)
445
+ if target is not save_bundle:
446
+ return None
447
+ if "data" not in keywords:
448
+ return (
449
+ "bundle=save_bundle cannot prove the bundles it writes: pass "
450
+ "bundle=functools.partial(save_bundle, data=val, predictor=TorchClassifier)"
451
+ )
452
+ try:
453
+ _prepared_data(keywords["data"])
454
+ except TypeError as error:
455
+ return f"bundle=save_bundle cannot prove the bundles it writes: {error}"
456
+ if keywords.get("predictor") is None:
457
+ return (
458
+ "bundle=save_bundle cannot prove the bundles it writes without predictor=, the class that serves "
459
+ "the model: pass bundle=functools.partial(save_bundle, data=val, predictor=TorchClassifier)"
460
+ )
461
+ return None
@@ -0,0 +1,166 @@
1
+ """Where a bundle lives, and the local folder each source puts it in.
2
+
3
+ A source can also be named by a text, which is what a configuration file or an environment variable can
4
+ hold: `hf://<repo>@<revision>[/<subfolder>]` for the Hugging Face Hub, `runs:/<run id>/<path>` (MLflow's
5
+ own scheme) for an MLflow run, and any other text for a folder on this machine.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ from collections.abc import Sequence
12
+ from pathlib import Path
13
+ from typing import Protocol, runtime_checkable
14
+
15
+ from torchstack64.core import require
16
+
17
+ HF_HUB_SCHEME = "hf://"
18
+ MLFLOW_RUNS_SCHEME = "runs:/"
19
+
20
+
21
+ @runtime_checkable
22
+ class ModelSource(Protocol):
23
+ """Anything that can put a bundle in a local folder and say where."""
24
+
25
+ def resolve(self) -> Path:
26
+ """Returns a local folder holding `bundle.json` and the bundle's files."""
27
+ ...
28
+
29
+
30
+ class LocalPathSource:
31
+ """A bundle already on this machine."""
32
+
33
+ def __init__(self, path: str | Path) -> None:
34
+ self.path = Path(path)
35
+
36
+ def __repr__(self) -> str:
37
+ return f"LocalPathSource({str(self.path)!r})"
38
+
39
+ def resolve(self) -> Path:
40
+ return self.path
41
+
42
+
43
+ class MLflowRunSource:
44
+ """A bundle logged as artifacts of an MLflow run.
45
+
46
+ The tracking server is passed to the download itself, so resolving a source never changes the
47
+ tracking URI of the whole process (which the notebook may be using for something else).
48
+ """
49
+
50
+ def __init__(
51
+ self,
52
+ run_id: str,
53
+ artifact_path: str = "model",
54
+ tracking_uri: str | None = None,
55
+ dst_path: str | Path | None = None,
56
+ ) -> None:
57
+ self.run_id = run_id
58
+ self.artifact_path = artifact_path
59
+ self.tracking_uri = tracking_uri
60
+ self.dst_path = dst_path
61
+
62
+ def __repr__(self) -> str:
63
+ return f"MLflowRunSource(run_id={self.run_id!r}, artifact_path={self.artifact_path!r})"
64
+
65
+ def resolve(self) -> Path:
66
+ mlflow = require("mlflow", extra="mlflow", purpose="MLflowRunSource")
67
+ local = mlflow.artifacts.download_artifacts(
68
+ run_id=self.run_id,
69
+ artifact_path=self.artifact_path,
70
+ tracking_uri=self.tracking_uri,
71
+ dst_path=None if self.dst_path is None else str(self.dst_path),
72
+ )
73
+ return Path(local)
74
+
75
+
76
+ class HubSource:
77
+ """A bundle in a Hugging Face Hub repository, at an exact revision.
78
+
79
+ The revision is required, with no `"main"` default: a service pins a tag or a commit, so the model it
80
+ serves cannot change under it when someone pushes. `subfolder` reads a bundle that is one folder of
81
+ the repository; only that folder is downloaded unless `allow_patterns` says otherwise.
82
+ """
83
+
84
+ def __init__(
85
+ self,
86
+ repo_id: str,
87
+ revision: str,
88
+ *,
89
+ subfolder: str | None = None,
90
+ allow_patterns: Sequence[str] | None = None,
91
+ token: str | None = None,
92
+ cache_dir: str | Path | None = None,
93
+ repo_type: str = "model",
94
+ ) -> None:
95
+ if not revision:
96
+ raise ValueError(
97
+ "HubSource needs an exact revision (a tag or a commit), so what is served is fixed"
98
+ )
99
+ self.repo_id = repo_id
100
+ self.revision = revision
101
+ self.subfolder = subfolder.strip("/") if subfolder else None
102
+ self.allow_patterns = list(allow_patterns) if allow_patterns is not None else None
103
+ self._token = token
104
+ self.cache_dir = cache_dir
105
+ self.repo_type = repo_type
106
+
107
+ def __repr__(self) -> str: # never shows the token
108
+ return f"HubSource({self.repo_id!r}, revision={self.revision!r}, subfolder={self.subfolder!r})"
109
+
110
+ def resolve(self) -> Path:
111
+ hub = require("huggingface_hub", extra="hub", purpose="HubSource")
112
+ patterns = self.allow_patterns
113
+ if patterns is None and self.subfolder:
114
+ patterns = [f"{self.subfolder}/*"]
115
+ local = hub.snapshot_download(
116
+ repo_id=self.repo_id,
117
+ revision=self.revision,
118
+ repo_type=self.repo_type,
119
+ allow_patterns=patterns,
120
+ token=self._token,
121
+ cache_dir=None if self.cache_dir is None else str(self.cache_dir),
122
+ )
123
+ path = Path(local)
124
+ return path / self.subfolder if self.subfolder else path
125
+
126
+
127
+ def as_source(value: ModelSource | str | os.PathLike[str]) -> ModelSource:
128
+ """The source `value` names: a `ModelSource` as it is; a text starting with `hf://` or `runs:/`, the
129
+ Hub or an MLflow run; any other text, or a path, a folder on this machine.
130
+
131
+ Only those two schemes are read, so a Windows path (`C:\\models\\digits`) is never taken for one. The
132
+ Hub's token never goes in the text: `huggingface_hub` reads it from `HF_TOKEN`. An MLflow run is read
133
+ from the tracking server this process uses (`MLFLOW_TRACKING_URI`, or `mlflow.set_tracking_uri`).
134
+ """
135
+ if isinstance(value, str):
136
+ if value.startswith(HF_HUB_SCHEME):
137
+ return _hub_source(value)
138
+ if value.startswith(MLFLOW_RUNS_SCHEME):
139
+ return _run_source(value)
140
+ return LocalPathSource(value)
141
+ if isinstance(value, os.PathLike):
142
+ return LocalPathSource(os.fspath(value))
143
+ if isinstance(value, ModelSource):
144
+ return value
145
+ raise TypeError(
146
+ "a bundle's source is a folder, a text such as 'hf://<repo>@<revision>' or 'runs:/<run id>/<path>', "
147
+ f"or a ModelSource; got {type(value).__name__}"
148
+ )
149
+
150
+
151
+ def _hub_source(text: str) -> HubSource:
152
+ repo, at, rest = text[len(HF_HUB_SCHEME) :].partition("@")
153
+ revision, _, subfolder = rest.partition("/")
154
+ if not at or not repo.strip("/") or not revision:
155
+ raise ValueError(
156
+ "a Hugging Face Hub source names its revision, so what is served cannot change under the "
157
+ f"service: hf://<repo>@<tag or commit>[/<subfolder>]; got {text!r}"
158
+ )
159
+ return HubSource(repo.strip("/"), revision, subfolder=subfolder.strip("/") or None)
160
+
161
+
162
+ def _run_source(text: str) -> MLflowRunSource:
163
+ run_id, _, path = text[len(MLFLOW_RUNS_SCHEME) :].lstrip("/").partition("/")
164
+ if not run_id:
165
+ raise ValueError(f"an MLflow run source is runs:/<run id>/<artifact path>; got {text!r}")
166
+ return MLflowRunSource(run_id, artifact_path=path.strip("/") or "model")
@@ -0,0 +1,22 @@
1
+ """Callbacks: what runs around a fit without being part of the loop. Each optional dependency is
2
+ imported by the constructor of the callback that needs it. `training_curves` draws the figure
3
+ `HistoryPlot` draws, for any history; `ModelChecks` checks the training set-up on the first batch."""
4
+
5
+ from torchstack64.callbacks.base import Callback
6
+ from torchstack64.callbacks.checkpointing import Checkpointing
7
+ from torchstack64.callbacks.history_plot import HistoryPlot, training_curves
8
+ from torchstack64.callbacks.mlflow_logger import MLflowLogger
9
+ from torchstack64.callbacks.model_checks import ModelChecks
10
+ from torchstack64.callbacks.progress import RichProgress
11
+ from torchstack64.callbacks.stack import default_stack
12
+
13
+ __all__ = [
14
+ "Callback",
15
+ "Checkpointing",
16
+ "HistoryPlot",
17
+ "MLflowLogger",
18
+ "ModelChecks",
19
+ "RichProgress",
20
+ "default_stack",
21
+ "training_curves",
22
+ ]
@@ -0,0 +1,43 @@
1
+ """The callback hooks. Override only the ones you need; the trainer is handed whole, to read anything.
2
+
3
+ A callback changes the fit only through the trainer's own methods (`request_stop`), never by raising.
4
+ Callbacks run in the order of the list. If one fails in `on_train_end`, the others still run, and its
5
+ error is raised after them.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import TYPE_CHECKING, Any
11
+
12
+ if TYPE_CHECKING:
13
+ from torchstack64.training.results import EpochResult, Evaluation, FitResult, OptimizationStepRecord
14
+ from torchstack64.training.trainer import StepContext, Trainer
15
+
16
+
17
+ class Callback:
18
+ """No-op hooks: subclass it and override what you need. Any object with these methods works too."""
19
+
20
+ def on_train_begin(self, trainer: Trainer[Any]) -> None:
21
+ """Before the first epoch (after a resumed state is loaded)."""
22
+
23
+ def on_epoch_begin(self, trainer: Trainer[Any], epoch: int) -> None:
24
+ """Before each training epoch."""
25
+
26
+ def on_train_batch_begin(self, trainer: Trainer[Any], batch: Any, ctx: StepContext) -> None:
27
+ """Before each training batch's step, with the batch already on the fit's device. Read the batch;
28
+ never change it. A task that runs its own epoch (`train_epoch`) passes no batch through here."""
29
+
30
+ def on_optimization_step_end(self, trainer: Trainer[Any], record: OptimizationStepRecord) -> None:
31
+ """After each optimization step."""
32
+
33
+ def on_validation_begin(self, trainer: Trainer[Any]) -> None:
34
+ """Before each validation pass of a fit."""
35
+
36
+ def on_validation_end(self, trainer: Trainer[Any], evaluation: Evaluation) -> None:
37
+ """After each validation pass of a fit, with its loss, predictions and monitored value."""
38
+
39
+ def on_epoch_end(self, trainer: Trainer[Any], result: EpochResult) -> None:
40
+ """After each epoch, with its metrics, whether it was the best, and the patience."""
41
+
42
+ def on_train_end(self, trainer: Trainer[Any], result: FitResult) -> None:
43
+ """After the fit, however it ended: `result.status` says how."""