torchstack64 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- torchstack64/__init__.py +101 -0
- torchstack64/artifacts/__init__.py +78 -0
- torchstack64/artifacts/bundle/__init__.py +50 -0
- torchstack64/artifacts/bundle/files.py +106 -0
- torchstack64/artifacts/bundle/folder.py +385 -0
- torchstack64/artifacts/bundle/tensors.py +75 -0
- torchstack64/artifacts/code/__init__.py +103 -0
- torchstack64/artifacts/code/copy.py +149 -0
- torchstack64/artifacts/code/importing.py +204 -0
- torchstack64/artifacts/code/inspection.py +351 -0
- torchstack64/artifacts/code/notebook.py +373 -0
- torchstack64/artifacts/code/objects.py +401 -0
- torchstack64/artifacts/loading.py +117 -0
- torchstack64/artifacts/manifest.py +220 -0
- torchstack64/artifacts/predictor/__init__.py +45 -0
- torchstack64/artifacts/predictor/bundle_predictor.py +193 -0
- torchstack64/artifacts/predictor/output_reading.py +96 -0
- torchstack64/artifacts/predictor/torch_classifier.py +106 -0
- torchstack64/artifacts/predictor/torch_predictor.py +247 -0
- torchstack64/artifacts/proofs/__init__.py +83 -0
- torchstack64/artifacts/proofs/answers.py +159 -0
- torchstack64/artifacts/proofs/example.py +248 -0
- torchstack64/artifacts/proofs/modules.py +260 -0
- torchstack64/artifacts/proofs/suite.py +560 -0
- torchstack64/artifacts/saving.py +461 -0
- torchstack64/artifacts/sources.py +166 -0
- torchstack64/callbacks/__init__.py +22 -0
- torchstack64/callbacks/base.py +43 -0
- torchstack64/callbacks/checkpointing.py +40 -0
- torchstack64/callbacks/history_plot.py +160 -0
- torchstack64/callbacks/mlflow_logger.py +217 -0
- torchstack64/callbacks/model_checks.py +295 -0
- torchstack64/callbacks/progress.py +132 -0
- torchstack64/callbacks/stack.py +85 -0
- torchstack64/core/__init__.py +59 -0
- torchstack64/core/errors.py +121 -0
- torchstack64/core/evaluation.py +52 -0
- torchstack64/core/extras.py +36 -0
- torchstack64/core/inference.py +42 -0
- torchstack64/core/labels.py +201 -0
- torchstack64/core/logging.py +110 -0
- torchstack64/data/__init__.py +10 -0
- torchstack64/data/base.py +256 -0
- torchstack64/data/labeled.py +128 -0
- torchstack64/devices/__init__.py +38 -0
- torchstack64/devices/hardware.py +43 -0
- torchstack64/devices/selection.py +82 -0
- torchstack64/metrics/__init__.py +21 -0
- torchstack64/metrics/classification.py +93 -0
- torchstack64/py.typed +0 -0
- torchstack64/training/__init__.py +83 -0
- torchstack64/training/config/__init__.py +17 -0
- torchstack64/training/config/fit.py +60 -0
- torchstack64/training/config/monitor.py +63 -0
- torchstack64/training/config/optim.py +49 -0
- torchstack64/training/config/params.py +55 -0
- torchstack64/training/config/search.py +49 -0
- torchstack64/training/results/__init__.py +19 -0
- torchstack64/training/results/fit.py +37 -0
- torchstack64/training/results/history.py +74 -0
- torchstack64/training/results/predictions.py +81 -0
- torchstack64/training/runtime/__init__.py +18 -0
- torchstack64/training/runtime/precision.py +139 -0
- torchstack64/training/runtime/randomness.py +142 -0
- torchstack64/training/runtime/runtime.py +75 -0
- torchstack64/training/runtime/transfer.py +49 -0
- torchstack64/training/runtime/weights.py +43 -0
- torchstack64/training/task/__init__.py +11 -0
- torchstack64/training/task/optim/__init__.py +9 -0
- torchstack64/training/task/optim/optimization.py +70 -0
- torchstack64/training/task/optim/schedules.py +27 -0
- torchstack64/training/task/protocol.py +58 -0
- torchstack64/training/task/supervised.py +113 -0
- torchstack64/training/trainer/__init__.py +8 -0
- torchstack64/training/trainer/adapters.py +122 -0
- torchstack64/training/trainer/contracts.py +81 -0
- torchstack64/training/trainer/hooks.py +47 -0
- torchstack64/training/trainer/meters.py +150 -0
- torchstack64/training/trainer/state.py +117 -0
- torchstack64/training/trainer/trainer.py +586 -0
- torchstack64/training/tuner/__init__.py +3 -0
- torchstack64/training/tuner/callback.py +38 -0
- torchstack64/training/tuner/space.py +82 -0
- torchstack64/training/tuner/tuner.py +137 -0
- torchstack64/utils/__init__.py +21 -0
- torchstack64/utils/logging.py +85 -0
- torchstack64/utils/mlflow.py +127 -0
- torchstack64-0.3.0.dist-info/METADATA +622 -0
- torchstack64-0.3.0.dist-info/RECORD +92 -0
- torchstack64-0.3.0.dist-info/WHEEL +5 -0
- torchstack64-0.3.0.dist-info/licenses/LICENSE +21 -0
- torchstack64-0.3.0.dist-info/top_level.txt +1 -0
torchstack64/__init__.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import importlib
|
|
4
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
5
|
+
from typing import TYPE_CHECKING
|
|
6
|
+
|
|
7
|
+
from torchstack64.core import configure_logging as _configure_logging
|
|
8
|
+
from torchstack64.devices import current_device, set_device, use_device
|
|
9
|
+
|
|
10
|
+
try:
|
|
11
|
+
__version__ = version("torchstack64")
|
|
12
|
+
except PackageNotFoundError: # a source tree that was never installed
|
|
13
|
+
__version__ = "0.0.0"
|
|
14
|
+
|
|
15
|
+
# Python runs this file before any submodule, so the policy is in place before any record is made.
|
|
16
|
+
_configure_logging()
|
|
17
|
+
|
|
18
|
+
_LAZY_NAMES = {
|
|
19
|
+
"Trainer": "torchstack64.training",
|
|
20
|
+
"FitConfig": "torchstack64.training",
|
|
21
|
+
"SupervisedTask": "torchstack64.training",
|
|
22
|
+
"OptimConfig": "torchstack64.training",
|
|
23
|
+
"Monitor": "torchstack64.training",
|
|
24
|
+
"SearchConfig": "torchstack64.training",
|
|
25
|
+
"Tuner": "torchstack64.training",
|
|
26
|
+
"BundlePredictor": "torchstack64.artifacts",
|
|
27
|
+
"LabelSchema": "torchstack64.core",
|
|
28
|
+
"LabeledData": "torchstack64.data",
|
|
29
|
+
"PreparedData": "torchstack64.data",
|
|
30
|
+
"TorchClassifier": "torchstack64.artifacts",
|
|
31
|
+
"TorchPredictor": "torchstack64.artifacts",
|
|
32
|
+
"load_trusted_predictor": "torchstack64.artifacts",
|
|
33
|
+
"save_bundle": "torchstack64.artifacts",
|
|
34
|
+
"default_stack": "torchstack64.callbacks",
|
|
35
|
+
}
|
|
36
|
+
_SUBMODULES = {
|
|
37
|
+
"artifacts",
|
|
38
|
+
"callbacks",
|
|
39
|
+
"core",
|
|
40
|
+
"data",
|
|
41
|
+
"devices",
|
|
42
|
+
"metrics",
|
|
43
|
+
"training",
|
|
44
|
+
"utils",
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
__all__ = [
|
|
48
|
+
"BundlePredictor",
|
|
49
|
+
"FitConfig",
|
|
50
|
+
"LabelSchema",
|
|
51
|
+
"LabeledData",
|
|
52
|
+
"Monitor",
|
|
53
|
+
"OptimConfig",
|
|
54
|
+
"PreparedData",
|
|
55
|
+
"SearchConfig",
|
|
56
|
+
"SupervisedTask",
|
|
57
|
+
"TorchClassifier",
|
|
58
|
+
"TorchPredictor",
|
|
59
|
+
"Trainer",
|
|
60
|
+
"Tuner",
|
|
61
|
+
"__version__",
|
|
62
|
+
"current_device",
|
|
63
|
+
"default_stack",
|
|
64
|
+
"load_trusted_predictor",
|
|
65
|
+
"save_bundle",
|
|
66
|
+
"set_device",
|
|
67
|
+
"use_device",
|
|
68
|
+
]
|
|
69
|
+
|
|
70
|
+
if TYPE_CHECKING: # what type checkers and editors see; at runtime these arrive through __getattr__
|
|
71
|
+
from torchstack64.artifacts import (
|
|
72
|
+
BundlePredictor,
|
|
73
|
+
TorchClassifier,
|
|
74
|
+
TorchPredictor,
|
|
75
|
+
load_trusted_predictor,
|
|
76
|
+
save_bundle,
|
|
77
|
+
)
|
|
78
|
+
from torchstack64.callbacks import default_stack
|
|
79
|
+
from torchstack64.core import LabelSchema
|
|
80
|
+
from torchstack64.data import LabeledData, PreparedData
|
|
81
|
+
from torchstack64.training import (
|
|
82
|
+
FitConfig,
|
|
83
|
+
Monitor,
|
|
84
|
+
OptimConfig,
|
|
85
|
+
SearchConfig,
|
|
86
|
+
SupervisedTask,
|
|
87
|
+
Trainer,
|
|
88
|
+
Tuner,
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def __getattr__(name: str) -> object:
|
|
93
|
+
if name in _LAZY_NAMES:
|
|
94
|
+
return getattr(importlib.import_module(_LAZY_NAMES[name]), name)
|
|
95
|
+
if name in _SUBMODULES:
|
|
96
|
+
return importlib.import_module(f"{__name__}.{name}")
|
|
97
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def __dir__() -> list[str]:
|
|
101
|
+
return sorted({*globals(), *_LAZY_NAMES, *_SUBMODULES})
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""The contract between training and serving: a trained model written as a bundle that is proved before it
|
|
2
|
+
exists, and read back as a predictor, raw inputs in, answers out.
|
|
3
|
+
|
|
4
|
+
data = LabeledData(images, labels, prepare=to_network, schema=LabelSchema.of(range(10)))
|
|
5
|
+
... # training, on data[train_rows].loader(...)
|
|
6
|
+
save_bundle(model, "outputs/digits", data=val, predictor=TorchClassifier) # proved before it exists
|
|
7
|
+
load_trusted_predictor("outputs/digits").predict(images) # in a service, anywhere
|
|
8
|
+
|
|
9
|
+
A bundle is a folder: the trained network (its structure and, apart, its weights), the preparation, the
|
|
10
|
+
classes, the project's code they need, the example it was proved on, and a manifest that lists every file
|
|
11
|
+
with its checksum. Nothing in it is declared by hand: it all comes from the model and the data training used.
|
|
12
|
+
|
|
13
|
+
One floor down:
|
|
14
|
+
|
|
15
|
+
- `torchstack64.artifacts.bundle`: the format on disk: the manifest, the atomic write, the files, the
|
|
16
|
+
tensors;
|
|
17
|
+
- `torchstack64.artifacts.code`: the project's code inside a bundle: what is copied, what the saved objects
|
|
18
|
+
need, how both are read back;
|
|
19
|
+
- `torchstack64.artifacts.proofs`: what shows a bundle answers like the model that was trained;
|
|
20
|
+
- `torchstack64.artifacts.predictor`: the predictors a bundle is read back into;
|
|
21
|
+
- `saving` and `loading`: the two doors, `save_bundle` and `load_trusted_predictor`; `check_example`, for a
|
|
22
|
+
predictor made some other way; and `missing_evidence`, which the `MLflowLogger` asks, before a fit, whether
|
|
23
|
+
the writer it was given can prove the bundles it writes.
|
|
24
|
+
|
|
25
|
+
Only the standard library is needed to import this package and to read a bundle's manifest; PyTorch,
|
|
26
|
+
safetensors, MLflow and the Hub are imported inside the functions that use them.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from torchstack64.artifacts.bundle import ArtifactBundle, BundleFile
|
|
30
|
+
from torchstack64.artifacts.loading import check_example, load_trusted_predictor
|
|
31
|
+
from torchstack64.artifacts.predictor import BundlePredictor, TorchClassifier, TorchPredictor
|
|
32
|
+
from torchstack64.artifacts.saving import missing_evidence, save_bundle
|
|
33
|
+
from torchstack64.artifacts.sources import (
|
|
34
|
+
HubSource,
|
|
35
|
+
LocalPathSource,
|
|
36
|
+
MLflowRunSource,
|
|
37
|
+
ModelSource,
|
|
38
|
+
as_source,
|
|
39
|
+
)
|
|
40
|
+
from torchstack64.core import (
|
|
41
|
+
BundleError,
|
|
42
|
+
BundleExistsError,
|
|
43
|
+
BundleIntegrityError,
|
|
44
|
+
BundleNotFoundError,
|
|
45
|
+
CodeConflictError,
|
|
46
|
+
LabelSchema,
|
|
47
|
+
MissingDependencyError,
|
|
48
|
+
ProofError,
|
|
49
|
+
TrustRequiredError,
|
|
50
|
+
UnknownArtifactError,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
__all__ = [
|
|
54
|
+
"ArtifactBundle",
|
|
55
|
+
"BundleError",
|
|
56
|
+
"BundleExistsError",
|
|
57
|
+
"BundleFile",
|
|
58
|
+
"BundleIntegrityError",
|
|
59
|
+
"BundleNotFoundError",
|
|
60
|
+
"BundlePredictor",
|
|
61
|
+
"CodeConflictError",
|
|
62
|
+
"HubSource",
|
|
63
|
+
"LabelSchema",
|
|
64
|
+
"LocalPathSource",
|
|
65
|
+
"MLflowRunSource",
|
|
66
|
+
"MissingDependencyError",
|
|
67
|
+
"ModelSource",
|
|
68
|
+
"ProofError",
|
|
69
|
+
"TorchClassifier",
|
|
70
|
+
"TorchPredictor",
|
|
71
|
+
"TrustRequiredError",
|
|
72
|
+
"UnknownArtifactError",
|
|
73
|
+
"as_source",
|
|
74
|
+
"check_example",
|
|
75
|
+
"load_trusted_predictor",
|
|
76
|
+
"missing_evidence",
|
|
77
|
+
"save_bundle",
|
|
78
|
+
]
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""What a bundle is on disk: its manifest, the folder and its atomic write, the files it is written from,
|
|
2
|
+
the tensors.
|
|
3
|
+
|
|
4
|
+
The manifest's code lives next to this package, in `torchstack64.artifacts.manifest`, because the code a
|
|
5
|
+
bundle carries (`torchstack64.artifacts.code`) needs it too and this package needs that code; its names are
|
|
6
|
+
offered here, with the rest of the format.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from torchstack64.artifacts.bundle.files import BundleFile, as_bundle_file
|
|
10
|
+
from torchstack64.artifacts.bundle.folder import (
|
|
11
|
+
MANIFEST_FILENAME,
|
|
12
|
+
PROOFS_ROOT,
|
|
13
|
+
ArtifactBundle,
|
|
14
|
+
Proving,
|
|
15
|
+
hash_tree,
|
|
16
|
+
provenance,
|
|
17
|
+
sha256_of,
|
|
18
|
+
write_bundle,
|
|
19
|
+
)
|
|
20
|
+
from torchstack64.artifacts.bundle.tensors import load_tensors, read_tensor_metadata, save_tensors
|
|
21
|
+
from torchstack64.artifacts.manifest import (
|
|
22
|
+
BUNDLE_FORMAT,
|
|
23
|
+
BUNDLE_VERSION,
|
|
24
|
+
BundleManifest,
|
|
25
|
+
ProofRecord,
|
|
26
|
+
safe_relative_path,
|
|
27
|
+
split_predictor_path,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"BUNDLE_FORMAT",
|
|
32
|
+
"BUNDLE_VERSION",
|
|
33
|
+
"MANIFEST_FILENAME",
|
|
34
|
+
"PROOFS_ROOT",
|
|
35
|
+
"ArtifactBundle",
|
|
36
|
+
"BundleFile",
|
|
37
|
+
"BundleManifest",
|
|
38
|
+
"ProofRecord",
|
|
39
|
+
"Proving",
|
|
40
|
+
"as_bundle_file",
|
|
41
|
+
"hash_tree",
|
|
42
|
+
"load_tensors",
|
|
43
|
+
"provenance",
|
|
44
|
+
"read_tensor_metadata",
|
|
45
|
+
"safe_relative_path",
|
|
46
|
+
"save_tensors",
|
|
47
|
+
"sha256_of",
|
|
48
|
+
"split_predictor_path",
|
|
49
|
+
"write_bundle",
|
|
50
|
+
]
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""The files a bundle is written from: where each one goes, and a function that writes it there."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import shutil
|
|
7
|
+
from collections.abc import Callable, Mapping
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, NamedTuple
|
|
10
|
+
|
|
11
|
+
from torchstack64.core import BundleError
|
|
12
|
+
|
|
13
|
+
TENSORS_SUFFIX = ".safetensors"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class BundleFile(NamedTuple):
|
|
17
|
+
"""One file, or folder, to put in a bundle: where it goes, and a function that writes it there.
|
|
18
|
+
|
|
19
|
+
Any `write(path)` works; the constructors below cover the usual cases.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
relative_path: str
|
|
23
|
+
write: Callable[[Path], object] # what it returns is ignored: `lambda p: p.write_bytes(data)` works
|
|
24
|
+
|
|
25
|
+
@classmethod
|
|
26
|
+
def json(cls, relative_path: str, obj: Any, *, indent: int = 2) -> BundleFile:
|
|
27
|
+
text = json.dumps(obj, indent=indent, ensure_ascii=False)
|
|
28
|
+
return cls(relative_path, lambda path: path.write_text(text + "\n", encoding="utf-8"))
|
|
29
|
+
|
|
30
|
+
@classmethod
|
|
31
|
+
def text(cls, relative_path: str, text: str) -> BundleFile:
|
|
32
|
+
return cls(relative_path, lambda path: path.write_text(text, encoding="utf-8"))
|
|
33
|
+
|
|
34
|
+
@classmethod
|
|
35
|
+
def copy(cls, relative_path: str, source: str | Path) -> BundleFile:
|
|
36
|
+
"""A file or a whole folder already on disk."""
|
|
37
|
+
source = Path(source)
|
|
38
|
+
|
|
39
|
+
def write(path: Path) -> None:
|
|
40
|
+
if source.is_dir():
|
|
41
|
+
shutil.copytree(source, path)
|
|
42
|
+
elif source.is_file():
|
|
43
|
+
shutil.copy2(source, path)
|
|
44
|
+
else:
|
|
45
|
+
raise BundleError(f"nothing to copy at {source}", source=str(source))
|
|
46
|
+
|
|
47
|
+
return cls(relative_path, write)
|
|
48
|
+
|
|
49
|
+
@classmethod
|
|
50
|
+
def tensors(
|
|
51
|
+
cls, relative_path: str, tensors: Mapping[str, Any], *, metadata: Mapping[str, str] | None = None
|
|
52
|
+
) -> BundleFile:
|
|
53
|
+
"""A state dict (or any name-to-tensor mapping) in safetensors: loading it never runs code."""
|
|
54
|
+
from torchstack64.artifacts.bundle.tensors import save_tensors
|
|
55
|
+
|
|
56
|
+
return cls(relative_path, lambda path: save_tensors(path, tensors, metadata=metadata))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def as_bundle_file(name: str, value: Any) -> BundleFile:
|
|
60
|
+
"""The file a value becomes in a bundle, chosen by its type, under its logical name:
|
|
61
|
+
|
|
62
|
+
- a mapping whose values are all tensors or NumPy arrays (a state dict): `<name>.safetensors`;
|
|
63
|
+
- a `str`: text, `<name>.txt`;
|
|
64
|
+
- a `Path`: that file, or folder, copied, `<name>` with the file's suffix;
|
|
65
|
+
- a `BundleFile`: itself, for a format none of these covers;
|
|
66
|
+
- anything JSON can hold (a dict of sizes, a list of classes, a number): `<name>.json`.
|
|
67
|
+
"""
|
|
68
|
+
if isinstance(value, BundleFile):
|
|
69
|
+
return value
|
|
70
|
+
if isinstance(value, Path):
|
|
71
|
+
return BundleFile.copy(name + (value.suffix if value.is_file() else ""), value)
|
|
72
|
+
if isinstance(value, str):
|
|
73
|
+
return BundleFile.text(f"{name}.txt", value)
|
|
74
|
+
if isinstance(value, Mapping) and value:
|
|
75
|
+
arrays = {key for key, item in value.items() if _is_array(item)}
|
|
76
|
+
if len(arrays) == len(value):
|
|
77
|
+
return BundleFile.tensors(name + TENSORS_SUFFIX, value)
|
|
78
|
+
if arrays:
|
|
79
|
+
others = sorted(str(key) for key in value if key not in arrays)
|
|
80
|
+
raise BundleError(
|
|
81
|
+
f"{name!r} mixes tensors with other values ({', '.join(others[:5])}): return the tensors "
|
|
82
|
+
"under one name and the rest under another",
|
|
83
|
+
artifact=name,
|
|
84
|
+
)
|
|
85
|
+
if _is_array(value):
|
|
86
|
+
raise BundleError(
|
|
87
|
+
f"{name!r} is a single {type(value).__name__}: put it in a mapping, {{{name!r}: value}}, and it "
|
|
88
|
+
"is written in safetensors",
|
|
89
|
+
artifact=name,
|
|
90
|
+
)
|
|
91
|
+
try:
|
|
92
|
+
return BundleFile.json(f"{name}.json", value)
|
|
93
|
+
except (TypeError, ValueError) as error:
|
|
94
|
+
raise BundleError(
|
|
95
|
+
f"{name!r} is a {type(value).__name__}, which is not tensors, text, a path or JSON ({error}); "
|
|
96
|
+
"return a BundleFile for another format",
|
|
97
|
+
artifact=name,
|
|
98
|
+
) from error
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _is_array(value: Any) -> bool:
|
|
102
|
+
"""A PyTorch tensor (a parameter included) or a NumPy array, told apart without importing either."""
|
|
103
|
+
module = type(value).__module__.split(".")[0]
|
|
104
|
+
return (module == "torch" and hasattr(value, "shape")) or (
|
|
105
|
+
module == "numpy" and type(value).__name__ == "ndarray"
|
|
106
|
+
)
|