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,385 @@
1
+ """The bundle as a folder: written atomically, read and checked field by field, verified file by file."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ import hashlib
7
+ import json
8
+ import logging
9
+ import os
10
+ import platform
11
+ import shutil
12
+ import sys
13
+ import uuid
14
+ from collections.abc import Callable, Mapping
15
+ from datetime import UTC, datetime
16
+ from importlib import metadata
17
+ from pathlib import Path
18
+ from typing import Any, Literal
19
+
20
+ from torchstack64.artifacts.bundle.files import BundleFile
21
+ from torchstack64.artifacts.bundle.tensors import load_tensors
22
+ from torchstack64.artifacts.code import (
23
+ BYTECODE_FOLDER,
24
+ CODE_ROOT,
25
+ BundleCode,
26
+ Distributions,
27
+ check_predictor,
28
+ code_requirements,
29
+ distributions,
30
+ write_code,
31
+ )
32
+ from torchstack64.artifacts.manifest import (
33
+ BundleManifest,
34
+ ProofRecord,
35
+ safe_relative_path,
36
+ split_predictor_path,
37
+ )
38
+ from torchstack64.artifacts.sources import ModelSource, as_source
39
+ from torchstack64.core import (
40
+ BundleError,
41
+ BundleExistsError,
42
+ BundleIntegrityError,
43
+ BundleNotFoundError,
44
+ LabelSchema,
45
+ UnknownArtifactError,
46
+ )
47
+
48
+ logger = logging.getLogger(__name__)
49
+
50
+ MANIFEST_FILENAME = "bundle.json"
51
+ PROOFS_ROOT = "proofs"
52
+ _CHUNK = 1 << 20
53
+
54
+ Proving = Callable[["ArtifactBundle"], tuple[ProofRecord, Mapping[str, BundleFile]]]
55
+ """Proves a bundle written in the staging folder: returns the record of what it proved, and the files it
56
+ adds under `proofs/`. It raises to refuse the bundle."""
57
+
58
+
59
+ def sha256_of(path: Path) -> str:
60
+ digest = hashlib.sha256()
61
+ with path.open("rb") as handle:
62
+ while chunk := handle.read(_CHUNK):
63
+ digest.update(chunk)
64
+ return digest.hexdigest()
65
+
66
+
67
+ def hash_tree(root: Path) -> dict[str, str]:
68
+ """The SHA-256 of every file under `root`, by POSIX relative path, the manifest excluded.
69
+
70
+ Bytecode caches are not part of a bundle: Python writes a `__pycache__` beside the bundle's code when
71
+ it imports it, and that must not read as a changed bundle.
72
+ """
73
+ checksums: dict[str, str] = {}
74
+ for path in sorted(p for p in root.rglob("*") if p.is_file()):
75
+ relative = path.relative_to(root)
76
+ if relative.as_posix() != MANIFEST_FILENAME and BYTECODE_FOLDER not in relative.parts:
77
+ checksums[relative.as_posix()] = sha256_of(path)
78
+ return checksums
79
+
80
+
81
+ def provenance(installed: Distributions | None = None) -> dict[str, str]:
82
+ """What wrote the bundle: Python, and each installed package the process has imported, by the
83
+ name it is installed under. Nothing is imported for this."""
84
+ from torchstack64 import __version__
85
+
86
+ owners = distributions() if installed is None else installed
87
+ found = {"torchstack64": __version__, "python": platform.python_version()}
88
+ for name in sorted(sys.modules):
89
+ if "." in name or name.startswith("_") or name in sys.stdlib_module_names:
90
+ continue
91
+ for distribution in owners.get(name, ()):
92
+ found.setdefault(distribution, metadata.version(distribution))
93
+ return found
94
+
95
+
96
+ class ArtifactBundle:
97
+ """A folder holding a `bundle.json` manifest and the files it describes."""
98
+
99
+ MANIFEST_FILENAME = MANIFEST_FILENAME
100
+
101
+ def __init__(self, root: str | Path, manifest: BundleManifest) -> None:
102
+ self.root = Path(root)
103
+ self.manifest = manifest
104
+
105
+ def __repr__(self) -> str:
106
+ return f"ArtifactBundle(root={str(self.root)!r})"
107
+
108
+ @property
109
+ def label_schema(self) -> LabelSchema | None:
110
+ return self.manifest.label_schema
111
+
112
+ @property
113
+ def predictor(self) -> str | None:
114
+ """The predictor that reads the bundle, as `"module:attribute"`, or `None`."""
115
+ return self.manifest.predictor
116
+
117
+ @property
118
+ def code(self) -> str | None:
119
+ """The folder, inside the bundle, of the project's own code that travels with it, or `None`."""
120
+ return self.manifest.code
121
+
122
+ @property
123
+ def proofs(self) -> ProofRecord | None:
124
+ """What `save_bundle` proved about the bundle, or `None` when nothing did."""
125
+ return self.manifest.proofs
126
+
127
+ @property
128
+ def metrics(self) -> dict[str, float]:
129
+ return self.manifest.metrics
130
+
131
+ @property
132
+ def metadata(self) -> dict[str, Any]:
133
+ return self.manifest.metadata
134
+
135
+ def path_for(self, logical_name: str) -> Path:
136
+ """The file (or folder) on disk behind a logical name such as `"weights"`."""
137
+ try:
138
+ relative = self.manifest.artifacts[logical_name]
139
+ except KeyError:
140
+ raise UnknownArtifactError(logical_name, list(self.manifest.artifacts), self.root) from None
141
+ return self.root / relative
142
+
143
+ def read_json(self, logical_name: str) -> Any:
144
+ return json.loads(self.path_for(logical_name).read_text(encoding="utf-8"))
145
+
146
+ def read_text(self, logical_name: str) -> str:
147
+ return self.path_for(logical_name).read_text(encoding="utf-8")
148
+
149
+ def read_tensors(
150
+ self, logical_name: str, *, device: str = "cpu", framework: Literal["pt", "np"] = "pt"
151
+ ) -> dict[str, Any]:
152
+ """The tensors a safetensors artifact holds, as PyTorch tensors on `device`, or as NumPy arrays
153
+ (`framework="np"`). Reading them never runs code."""
154
+ return load_tensors(self.path_for(logical_name), device=device, framework=framework)
155
+
156
+ def verify(self, *, strict: bool = False) -> None:
157
+ """Checks every file against the SHA-256 the manifest recorded when the bundle was written.
158
+
159
+ A missing or changed file raises `BundleIntegrityError`. A file the manifest does not know (a
160
+ model card the Hub added, an editor's backup) is only logged, unless `strict=True`.
161
+ """
162
+ expected = self.manifest.checksums
163
+ found = hash_tree(self.root)
164
+ missing = sorted(set(expected) - set(found))
165
+ changed = sorted(p for p in set(expected) & set(found) if expected[p] != found[p])
166
+ unexpected = sorted(set(found) - set(expected))
167
+ if missing or changed or (strict and unexpected):
168
+ parts = [
169
+ f"{label}: {names}" for label, names in [("missing", missing), ("changed", changed)] if names
170
+ ]
171
+ if strict and unexpected:
172
+ parts.append(f"unexpected: {unexpected}")
173
+ raise BundleIntegrityError(
174
+ f"the bundle at {self.root} does not match its manifest ({'; '.join(parts)})",
175
+ missing=missing,
176
+ changed=changed,
177
+ unexpected=unexpected if strict else (),
178
+ )
179
+ if unexpected:
180
+ logger.warning(
181
+ "bundle at %s has files its manifest does not list: %s", self.root, unexpected[:10]
182
+ )
183
+ logger.debug("bundle at %s verified: %d files", self.root, len(expected))
184
+
185
+ @classmethod
186
+ def write(
187
+ cls,
188
+ root: str | os.PathLike[str],
189
+ *,
190
+ files: Mapping[str, BundleFile],
191
+ label_schema: LabelSchema | None = None,
192
+ code: BundleCode | None = None,
193
+ predictor: str | None = None,
194
+ metrics: Mapping[str, float] | None = None,
195
+ metadata: Mapping[str, Any] | None = None,
196
+ overwrite: bool = False,
197
+ ) -> ArtifactBundle:
198
+ """Writes every file in a staging folder next to `root`, hashes them, writes the manifest, and
199
+ only then moves the folder into place.
200
+
201
+ A writer that fails, or a process that dies halfway, leaves no half bundle at `root`. A folder
202
+ that already has files is never written over unless `overwrite=True`. With `code`, the project's
203
+ own code goes into `code/`, checksummed like every other file, and the manifest lists the
204
+ distributions that code imports (`requires`), so the service knows what to install. `predictor`
205
+ names the predictor that reads the bundle (`"module:Class.load"`), in that code or in the library,
206
+ so a service can load the bundle with `load_trusted_predictor(folder)`.
207
+
208
+ Nothing proves a bundle written this way: its manifest records no proofs, and every load says so.
209
+ `save_bundle` writes a bundle it proved first.
210
+ """
211
+ return write_bundle(
212
+ root,
213
+ files=files,
214
+ label_schema=label_schema,
215
+ code=code,
216
+ predictor=predictor,
217
+ metrics=metrics,
218
+ metadata=metadata,
219
+ overwrite=overwrite,
220
+ )
221
+
222
+ @classmethod
223
+ def read(cls, source: str | os.PathLike[str] | ModelSource, *, verify: bool = False) -> ArtifactBundle:
224
+ """Reads the manifest of the bundle `source` names, checks every artifact it lists exists, and with
225
+ `verify=True` checks every file's SHA-256. Nothing in the bundle runs.
226
+
227
+ `source` is a folder, a `ModelSource`, or a text such as `"hf://<repo>@<revision>"` or
228
+ `"runs:/<run id>/model"`: reading a bundle before trusting its code is one line.
229
+ """
230
+ root = Path(as_source(source).resolve())
231
+ manifest_path = root / MANIFEST_FILENAME
232
+ if not manifest_path.is_file():
233
+ raise BundleNotFoundError(f"no {MANIFEST_FILENAME} at {root}", root=str(root))
234
+ try:
235
+ data = json.loads(manifest_path.read_text(encoding="utf-8"))
236
+ except json.JSONDecodeError as error:
237
+ raise BundleError(f"{manifest_path} is not valid JSON: {error}", root=str(root)) from error
238
+ bundle = cls(root, BundleManifest.from_json(data))
239
+ missing = sorted(p for p in bundle.manifest.artifacts.values() if not (root / p).exists())
240
+ if missing:
241
+ raise BundleIntegrityError(
242
+ f"the bundle at {root} is missing artifacts: {missing}", missing=missing
243
+ )
244
+ if verify:
245
+ bundle.verify()
246
+ return bundle
247
+
248
+
249
+ def write_bundle(
250
+ root: str | os.PathLike[str],
251
+ *,
252
+ files: Mapping[str, BundleFile],
253
+ label_schema: LabelSchema | None = None,
254
+ code: BundleCode | None = None,
255
+ predictor: str | None = None,
256
+ requires: Mapping[str, str] | None = None,
257
+ metrics: Mapping[str, float] | None = None,
258
+ metadata: Mapping[str, Any] | None = None,
259
+ overwrite: bool = False,
260
+ installed: Distributions | None = None,
261
+ proofs: ProofRecord | None = None,
262
+ prove: Proving | None = None,
263
+ ) -> ArtifactBundle:
264
+ """`ArtifactBundle.write`, for a caller that already read the map of installed distributions
265
+ (`installed`): reading it takes a fraction of a second, and the provenance and `requires` both use it.
266
+ `requires` adds distributions the bundle needs besides what its code imports: the libraries its saved
267
+ objects are made of.
268
+
269
+ `prove`, when given, receives the bundle as it is in the staging folder, files, code and manifest
270
+ written, before anything is moved into place: what it proves is what a service will load. It returns
271
+ the record of what it proved and the files it adds under `proofs/` (the example, with its answers),
272
+ which are checksummed with the rest. A `prove` that raises leaves no bundle anywhere, and the folder at
273
+ `root` as it was, even with `overwrite=True`: a bundle that does not prove itself never replaces one.
274
+ Without `prove`, `proofs` is the record the manifest keeps (`None`: nothing was proved).
275
+ """
276
+ if prove is not None and proofs is not None:
277
+ raise ValueError("pass the proofs a bundle already has, or the function that proves it, not both")
278
+ root = Path(root)
279
+ if predictor is not None:
280
+ split_predictor_path(predictor)
281
+ if root.exists() and (not root.is_dir() or any(root.iterdir())) and not overwrite:
282
+ raise BundleExistsError(
283
+ f"{root} already exists and is not empty; choose another folder or pass overwrite=True",
284
+ root=str(root),
285
+ )
286
+ owners = distributions() if installed is None else installed
287
+ root.parent.mkdir(parents=True, exist_ok=True)
288
+ staging = root.parent / f".{root.name}.{uuid.uuid4().hex[:8]}.staging"
289
+ staging.mkdir()
290
+ try:
291
+ artifacts: dict[str, str] = {}
292
+ for logical_name, bundle_file in files.items():
293
+ relative = safe_relative_path(bundle_file.relative_path)
294
+ if relative == MANIFEST_FILENAME:
295
+ raise BundleError(f"{MANIFEST_FILENAME} is the manifest's own name; pick another path")
296
+ if code is not None and relative.split("/")[0] == CODE_ROOT:
297
+ raise BundleError(
298
+ f"{CODE_ROOT}/ holds the bundle's code; put {logical_name!r} somewhere else",
299
+ artifact=logical_name,
300
+ )
301
+ if relative.split("/")[0] == PROOFS_ROOT:
302
+ raise BundleError(
303
+ f"{PROOFS_ROOT}/ holds what the library proved about the bundle; put {logical_name!r} "
304
+ "somewhere else",
305
+ artifact=logical_name,
306
+ )
307
+ target = staging / relative
308
+ target.parent.mkdir(parents=True, exist_ok=True)
309
+ bundle_file.write(target)
310
+ if not target.exists():
311
+ raise BundleError(
312
+ f"the writer of {logical_name!r} did not create {relative}", artifact=logical_name
313
+ )
314
+ artifacts[logical_name] = relative
315
+ code_root = write_code(code, staging) if code is not None else None
316
+ if predictor is not None:
317
+ check_predictor(predictor, staging, code_root)
318
+ needed = code_requirements(staging / CODE_ROOT, owners) if code_root is not None else {}
319
+ manifest = BundleManifest(
320
+ artifacts=artifacts,
321
+ label_schema=label_schema,
322
+ predictor=predictor,
323
+ code=code_root,
324
+ requires=dict(sorted({**needed, **(requires or {})}.items(), key=lambda item: item[0].lower())),
325
+ proofs=proofs,
326
+ metrics={str(k): float(v) for k, v in (metrics or {}).items()},
327
+ checksums=hash_tree(staging),
328
+ metadata=dict(metadata or {}),
329
+ created_at=datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"),
330
+ created_with=provenance(owners),
331
+ )
332
+ _write_manifest(staging, manifest)
333
+ if prove is not None:
334
+ record, added = prove(ArtifactBundle(staging, manifest))
335
+ for name, bundle_file in added.items():
336
+ relative = safe_relative_path(bundle_file.relative_path)
337
+ if relative.split("/")[0] != PROOFS_ROOT:
338
+ raise BundleError(
339
+ f"a proof writes under {PROOFS_ROOT}/ only; {name!r} went to {relative}"
340
+ )
341
+ target = staging / relative
342
+ target.parent.mkdir(parents=True, exist_ok=True)
343
+ bundle_file.write(target)
344
+ manifest = dataclasses.replace(manifest, proofs=record, checksums=hash_tree(staging))
345
+ _write_manifest(staging, manifest)
346
+ _move_into_place(staging, root)
347
+ except BaseException:
348
+ shutil.rmtree(staging, ignore_errors=True)
349
+ raise
350
+ logger.info(
351
+ "bundle written to %s: %d artifacts, %d files%s",
352
+ root,
353
+ len(artifacts),
354
+ len(manifest.checksums),
355
+ f", read by {predictor}" if predictor is not None else "",
356
+ )
357
+ return ArtifactBundle(root, manifest)
358
+
359
+
360
+ def _write_manifest(folder: Path, manifest: BundleManifest) -> None:
361
+ try:
362
+ text = json.dumps(manifest.to_json(), indent=2, ensure_ascii=False)
363
+ except TypeError as error:
364
+ raise BundleError(f"the bundle's metadata must be JSON: {error}") from error
365
+ (folder / MANIFEST_FILENAME).write_text(text + "\n", encoding="utf-8")
366
+
367
+
368
+ def _move_into_place(staging: Path, root: Path) -> None:
369
+ """Renames the finished staging folder to `root`, replacing what is there (already allowed)."""
370
+ if root.is_dir() and not any(root.iterdir()):
371
+ root.rmdir()
372
+ if not root.exists():
373
+ os.replace(staging, root)
374
+ return
375
+ retired = root.parent / f".{root.name}.{uuid.uuid4().hex[:8]}.old"
376
+ os.replace(root, retired)
377
+ try:
378
+ os.replace(staging, root)
379
+ except BaseException:
380
+ os.replace(retired, root)
381
+ raise
382
+ if retired.is_dir():
383
+ shutil.rmtree(retired, ignore_errors=True)
384
+ else:
385
+ retired.unlink(missing_ok=True)
@@ -0,0 +1,75 @@
1
+ """Tensors on disk in safetensors: a flat table of arrays and a JSON header, and nothing to execute.
2
+
3
+ A network's weights are kept this way, apart from its structure: reading them never runs code, so they can
4
+ be read from a bundle nobody trusted yet, by a service that builds the network with its own code, and
5
+ without PyTorch at all (NumPy), by one that runs the model elsewhere (ONNX). What does run code, the
6
+ structure and the preparation written with pickle, is read only from a trusted bundle.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from collections.abc import Mapping
13
+ from pathlib import Path
14
+ from typing import Any, Literal
15
+
16
+ from torchstack64.core import require
17
+
18
+
19
+ def save_tensors(
20
+ path: str | Path, tensors: Mapping[str, Any], *, metadata: Mapping[str, str] | None = None
21
+ ) -> None:
22
+ """Writes PyTorch tensors (or NumPy arrays) to `path`.
23
+
24
+ Tensors that share memory, like tied input and output embeddings, are written as separate copies:
25
+ safetensors refuses shared storage, and `load_state_dict` fills both names from the copies. Every
26
+ array is written in C order: safetensors writes an array's memory as it is, and an array in Fortran
27
+ order (scikit-learn keeps `coef_` so) would come back with its values in the wrong places, and no
28
+ error.
29
+ """
30
+ require("safetensors", extra="safetensors", purpose="Writing tensors in safetensors")
31
+ header = {str(k): str(v) for k, v in (metadata or {}).items()} or None
32
+ values = list(tensors.values())
33
+ if values and type(values[0]).__module__.split(".")[0] == "numpy":
34
+ import numpy
35
+ from safetensors.numpy import save_file as save_numpy
36
+
37
+ arrays = {str(name): numpy.ascontiguousarray(value) for name, value in tensors.items()}
38
+ save_numpy(arrays, str(path), metadata=header)
39
+ return
40
+ from safetensors.torch import save_file as save_torch
41
+
42
+ prepared: dict[str, Any] = {}
43
+ seen: set[int] = set()
44
+ for name, tensor in tensors.items():
45
+ value = tensor.detach().to("cpu").contiguous()
46
+ pointer = value.untyped_storage().data_ptr()
47
+ if pointer in seen:
48
+ value = value.clone()
49
+ seen.add(pointer)
50
+ prepared[str(name)] = value
51
+ save_torch(prepared, str(path), metadata=header)
52
+
53
+
54
+ def load_tensors(
55
+ path: str | Path, *, device: str = "cpu", framework: Literal["pt", "np"] = "pt"
56
+ ) -> dict[str, Any]:
57
+ """Reads a safetensors file as PyTorch tensors on `device`, or as NumPy arrays (`framework="np"`)."""
58
+ require("safetensors", extra="safetensors", purpose="Reading tensors in safetensors")
59
+ if framework == "np":
60
+ from safetensors.numpy import load_file as load_numpy
61
+
62
+ return dict(load_numpy(str(path)))
63
+ from safetensors.torch import load_file as load_torch
64
+
65
+ return dict(load_torch(str(path), device=device))
66
+
67
+
68
+ def read_tensor_metadata(path: str | Path) -> dict[str, str]:
69
+ """The metadata a safetensors file keeps beside its tensors (texts by name), read from its header alone:
70
+ eight bytes that give the header's length, then the header, JSON, whose `__metadata__` it is."""
71
+ with Path(path).open("rb") as handle:
72
+ size = int.from_bytes(handle.read(8), "little")
73
+ header = json.loads(handle.read(size).decode("utf-8"))
74
+ found = header.get("__metadata__") or {}
75
+ return {str(key): str(value) for key, value in found.items()}
@@ -0,0 +1,103 @@
1
+ """The project's own code inside a bundle: copied when the bundle is written, imported when it is served.
2
+
3
+ A bundle keeps objects (a trained network, a preparation) and, sometimes, a predictor class of the project's
4
+ own; reading them back needs the code they are made of. That code travels inside the bundle, so a service
5
+ needs only the bundle and the packages the manifest's `requires` names. Reading and verifying a bundle never
6
+ runs that code. Importing it, and reading the objects, does, so the loader does both only when asked to
7
+ (`load_trusted_predictor`, or `trust_code=True` on a class), and only after every file matched its checksum.
8
+
9
+ - `copy`: the write side, in the training process: what is copied, under which name, what is refused.
10
+ - `inspection`: read without running anything, on both sides: what the code imports, where each module
11
+ comes from, which distributions install it, whether a module in memory still matches its file, and
12
+ which code a predictor class needs.
13
+ - `notebook`: classes and functions defined in notebook cells, written back as a module the bundle carries.
14
+ - `objects`: objects kept as they are, the network and the preparation: the code they name, found by
15
+ writing them, the network's structure apart from its tensors, and both read back.
16
+ - `importing`: the read side, in the service: making the bundle's code importable, importing the
17
+ predictor, and refusing the modules it conflicts with.
18
+ """
19
+
20
+ from torchstack64.artifacts.code.copy import (
21
+ BYTECODE_FOLDER,
22
+ CODE_ROOT,
23
+ LIBRARY,
24
+ BundleCode,
25
+ check_predictor,
26
+ code_names,
27
+ skipped,
28
+ write_code,
29
+ )
30
+ from torchstack64.artifacts.code.importing import import_bundle_code, import_predictor_factory
31
+ from torchstack64.artifacts.code.inspection import (
32
+ Distributions,
33
+ Origin,
34
+ code_for_class,
35
+ code_requirements,
36
+ distributions,
37
+ edited_after_import,
38
+ imports_in_source,
39
+ interpreter_folders,
40
+ local_modules,
41
+ module_location,
42
+ origin,
43
+ project_package,
44
+ python_files,
45
+ report_code,
46
+ requirements,
47
+ top_level_imports,
48
+ )
49
+ from torchstack64.artifacts.code.notebook import export_module, free_names, module_name_for
50
+ from torchstack64.artifacts.code.objects import (
51
+ ALIASES_KEY,
52
+ NOTEBOOK_PREFIX,
53
+ NetworkTensors,
54
+ ObjectCode,
55
+ code_for_objects,
56
+ place_tensors,
57
+ read_network,
58
+ read_object,
59
+ references,
60
+ tensors_set_aside,
61
+ )
62
+
63
+ __all__ = [
64
+ "ALIASES_KEY",
65
+ "BYTECODE_FOLDER",
66
+ "CODE_ROOT",
67
+ "LIBRARY",
68
+ "NOTEBOOK_PREFIX",
69
+ "BundleCode",
70
+ "Distributions",
71
+ "NetworkTensors",
72
+ "ObjectCode",
73
+ "Origin",
74
+ "check_predictor",
75
+ "code_for_class",
76
+ "code_for_objects",
77
+ "code_names",
78
+ "code_requirements",
79
+ "distributions",
80
+ "edited_after_import",
81
+ "export_module",
82
+ "free_names",
83
+ "import_bundle_code",
84
+ "import_predictor_factory",
85
+ "imports_in_source",
86
+ "interpreter_folders",
87
+ "local_modules",
88
+ "module_location",
89
+ "module_name_for",
90
+ "origin",
91
+ "place_tensors",
92
+ "project_package",
93
+ "python_files",
94
+ "read_network",
95
+ "read_object",
96
+ "references",
97
+ "report_code",
98
+ "requirements",
99
+ "skipped",
100
+ "tensors_set_aside",
101
+ "top_level_imports",
102
+ "write_code",
103
+ ]