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,351 @@
1
+ """What a project's code needs, read without running it.
2
+
3
+ - The modules the code imports, from its syntax tree: an `import` inside a function counts too.
4
+ - Where each of them comes from: Python itself, the bundle's own code, an installed distribution, the
5
+ interpreter's folders, the project's folders on disk (code that must travel), or nowhere.
6
+ - The distributions that install them, with the versions installed here: what a service has to install.
7
+ - Whether a module already imported still matches its file on disk. Python keeps what it imported; a file
8
+ edited afterwards is not what this process runs, and a bundle copied from the disk would carry code that
9
+ never ran here.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import ast
15
+ import importlib.util
16
+ import logging
17
+ import os
18
+ import site
19
+ import struct
20
+ import sys
21
+ from collections.abc import Iterable, Mapping, Sequence
22
+ from enum import StrEnum
23
+ from importlib import metadata
24
+ from pathlib import Path
25
+
26
+ from torchstack64.artifacts.code.copy import BundleCode, code_names, skipped
27
+ from torchstack64.artifacts.code.notebook import export_module, module_name_for
28
+ from torchstack64.core import BundleError
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+ Distributions = Mapping[str, Sequence[str]]
33
+ """Top-level import name to the installed distributions that provide it, as
34
+ `importlib.metadata.packages_distributions()` returns it."""
35
+
36
+
37
+ class Origin(StrEnum):
38
+ """Where a top-level module comes from, as seen from the process that asks."""
39
+
40
+ STDLIB = "stdlib"
41
+ OWN = "own" # a module of the code being inspected
42
+ INSTALLED = "installed" # an installed distribution provides it
43
+ INTERPRETER = "interpreter" # inside the interpreter's own folders, with no distribution
44
+ LOCAL = "local" # on disk outside the interpreter's folders, with no distribution: the project's code
45
+ MISSING = "missing"
46
+
47
+
48
+ class _Installed:
49
+ """The map of installed distributions, read once and kept while nothing was installed or removed.
50
+
51
+ Reading it takes most of a second on some machines, and every save reads it. It is kept while the import
52
+ path stays the same and no folder of it where Python installs packages changes: installing or removing a
53
+ package adds or removes an entry in one, which changes the folder's time.
54
+ """
55
+
56
+ def __init__(self) -> None:
57
+ self._state: tuple[object, ...] | None = None
58
+ self._found: Distributions = {}
59
+
60
+ def read(self) -> Distributions:
61
+ state = self._install_state()
62
+ if state != self._state:
63
+ self._found, self._state = metadata.packages_distributions(), state
64
+ return self._found
65
+
66
+ @staticmethod
67
+ def _install_state() -> tuple[object, ...]:
68
+ inside = interpreter_folders()
69
+ times = []
70
+ for entry in sys.path:
71
+ try:
72
+ where = Path(entry or ".").resolve()
73
+ if any(where.is_relative_to(folder) for folder in inside):
74
+ times.append(os.stat(where).st_mtime_ns)
75
+ except OSError:
76
+ times.append(-1)
77
+ # the reader itself is part of the state: a test that replaces it gets its own answer
78
+ return (metadata.packages_distributions, tuple(sys.path), tuple(times))
79
+
80
+
81
+ _installed = _Installed()
82
+
83
+
84
+ def distributions() -> Distributions:
85
+ """Which installed distributions provide each top-level import name, as installed now."""
86
+ return _installed.read()
87
+
88
+
89
+ def python_files(root: Path) -> list[Path]:
90
+ """The Python files of a package folder or of a single module, bytecode and hidden files left out."""
91
+ if root.is_file():
92
+ return [root] if root.suffix == ".py" else []
93
+ return sorted(
94
+ path for path in root.rglob("*.py") if not any(skipped(part) for part in path.relative_to(root).parts)
95
+ )
96
+
97
+
98
+ def imports_in_source(text: str, *, filename: str = "<source>") -> set[str]:
99
+ """The top-level names of every absolute import in `text`: `import a.b`, `from a import b`, and
100
+ `importlib.import_module("a")` or `__import__("a")` with a literal name. Relative imports are the
101
+ code's own and are left out."""
102
+ try:
103
+ tree = ast.parse(text, filename=filename)
104
+ except SyntaxError as error:
105
+ raise BundleError(f"{filename} is not valid Python: {error}", file=filename) from error
106
+ names: set[str] = set()
107
+ for node in ast.walk(tree):
108
+ if isinstance(node, ast.Import):
109
+ names.update(alias.name.split(".")[0] for alias in node.names)
110
+ elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:
111
+ names.add(node.module.split(".")[0])
112
+ elif isinstance(node, ast.Call) and _imports_by_name(node):
113
+ names.add(node.args[0].value.split(".")[0]) # type: ignore[attr-defined]
114
+ return names
115
+
116
+
117
+ def _imports_by_name(node: ast.Call) -> bool:
118
+ """`importlib.import_module("literal")` or `__import__("literal")`."""
119
+ function = node.func
120
+ called = function.attr if isinstance(function, ast.Attribute) else getattr(function, "id", None)
121
+ return (
122
+ called in {"import_module", "__import__"}
123
+ and bool(node.args)
124
+ and isinstance(node.args[0], ast.Constant)
125
+ and isinstance(node.args[0].value, str)
126
+ and bool(node.args[0].value)
127
+ )
128
+
129
+
130
+ def top_level_imports(roots: Path | Iterable[Path]) -> set[str]:
131
+ """The top-level names imported by every Python file under `roots` (packages or modules)."""
132
+ names: set[str] = set()
133
+ for root in [roots] if isinstance(roots, Path) else roots:
134
+ for path in python_files(root):
135
+ names |= imports_in_source(path.read_text(encoding="utf-8"), filename=str(path))
136
+ return names
137
+
138
+
139
+ def interpreter_folders() -> list[Path]:
140
+ """Where Python and the packages installed for it live: the standard library and the site-packages of
141
+ this interpreter and of its base, and the user's site-packages."""
142
+ places = {sys.prefix, sys.base_prefix, sys.exec_prefix, sys.base_exec_prefix, site.getusersitepackages()}
143
+ return [Path(place).resolve() for place in places]
144
+
145
+
146
+ def module_location(name: str) -> Path | None:
147
+ """The folder of a package or the file of a module named `name`, found without importing it."""
148
+ loaded = sys.modules.get(name)
149
+ if loaded is not None:
150
+ where = getattr(loaded, "__path__", None)
151
+ if where:
152
+ return Path(next(iter(where))).resolve()
153
+ file = getattr(loaded, "__file__", None)
154
+ return Path(file).resolve() if file else None
155
+ try:
156
+ spec = importlib.util.find_spec(name)
157
+ except (ImportError, ValueError):
158
+ return None
159
+ if spec is None:
160
+ return None
161
+ if spec.submodule_search_locations:
162
+ return Path(next(iter(spec.submodule_search_locations))).resolve()
163
+ if spec.origin and spec.origin not in {"built-in", "frozen"}:
164
+ return Path(spec.origin).resolve()
165
+ return None
166
+
167
+
168
+ def origin(
169
+ name: str, *, installed: Distributions, own: Iterable[str] = (), folders: Sequence[Path] | None = None
170
+ ) -> tuple[Origin, Path | None]:
171
+ """Where the top-level module `name` comes from, and its folder or file when that is on disk."""
172
+ if name in set(own):
173
+ return Origin.OWN, None
174
+ if name in sys.stdlib_module_names or name in sys.builtin_module_names:
175
+ return Origin.STDLIB, None
176
+ if name in installed:
177
+ return Origin.INSTALLED, None
178
+ location = module_location(name)
179
+ if location is None:
180
+ return Origin.MISSING, None
181
+ inside = interpreter_folders() if folders is None else folders
182
+ if any(location.is_relative_to(folder) for folder in inside):
183
+ return Origin.INTERPRETER, location
184
+ return Origin.LOCAL, location
185
+
186
+
187
+ def requirements(names: Iterable[str], installed: Distributions) -> dict[str, str]:
188
+ """The distributions that install `names`, each with the version installed here, sorted by name."""
189
+ found: dict[str, str] = {}
190
+ for name in sorted(set(names)):
191
+ for distribution in installed.get(name, ()):
192
+ if distribution in found:
193
+ continue
194
+ try:
195
+ found[distribution] = metadata.version(distribution)
196
+ except metadata.PackageNotFoundError:
197
+ continue
198
+ return dict(sorted(found.items(), key=lambda item: item[0].lower()))
199
+
200
+
201
+ def code_requirements(code_root: Path, installed: Distributions) -> dict[str, str]:
202
+ """What a bundle's code folder needs installed: the distributions of every name it imports that is
203
+ neither Python's own nor one of the folder's modules, with the versions installed here."""
204
+ own = set(code_names(code_root))
205
+ names = {
206
+ name
207
+ for name in top_level_imports(code_root)
208
+ if name not in own and name not in sys.stdlib_module_names and name not in sys.builtin_module_names
209
+ }
210
+ return requirements(names, installed)
211
+
212
+
213
+ def local_modules(
214
+ imported: Iterable[str], *, installed: Distributions, own: Iterable[str] = ()
215
+ ) -> tuple[list[Path], list[str]]:
216
+ """The project's own modules a piece of code needs, found from the names it imports.
217
+
218
+ Each imported name that comes from a folder of the project (on disk, outside the interpreter's
219
+ folders, installed by no distribution) is followed, and the names its files import are followed
220
+ too. Returns the folders and files to carry, sorted by name, and the names found nowhere, which a
221
+ service will have to provide itself.
222
+ """
223
+ skip = set(own)
224
+ found: dict[str, Path] = {}
225
+ missing: set[str] = set()
226
+ pending = sorted(set(imported))
227
+ while pending:
228
+ name = pending.pop()
229
+ if name in skip:
230
+ continue
231
+ skip.add(name)
232
+ kind, where = origin(name, installed=installed)
233
+ if kind is Origin.LOCAL and where is not None:
234
+ found[name] = where
235
+ pending.extend(sorted(top_level_imports(where) - skip))
236
+ elif kind is Origin.MISSING:
237
+ missing.add(name)
238
+ return [found[name] for name in sorted(found)], sorted(missing)
239
+
240
+
241
+ def project_package(top: str, *, installed: Distributions) -> tuple[list[Path], list[str]]:
242
+ """The project's own top-level package (or module) `top`, as it is on disk, with the project's other
243
+ modules its code imports: the folders and files to carry, and the names imported that were found
244
+ nowhere here, which a service will have to provide itself."""
245
+ spread = list(getattr(sys.modules.get(top), "__path__", None) or [])
246
+ if len(spread) > 1:
247
+ raise BundleError(
248
+ f"{top!r} is a package without an __init__.py, spread over {len(spread)} folders; give it an "
249
+ "__init__.py, so the bundle can carry it as one folder",
250
+ name=top,
251
+ )
252
+ root = module_location(top)
253
+ if root is None:
254
+ raise BundleError(f"{top!r} has no folder or file to copy", name=top)
255
+ paths, missing = local_modules(top_level_imports(root), installed=installed, own={top})
256
+ return [root, *paths], missing
257
+
258
+
259
+ def code_for_class(cls: type, *, installed: Distributions) -> tuple[BundleCode, str]:
260
+ """The code a bundle carries so a service can build `cls` again, found from the class itself, and the
261
+ predictor the manifest names in it (`"module:Class.load"`).
262
+
263
+ - A class imported from a module brings the top-level package (or module) it was imported from, as it
264
+ is on disk, and the project's own modules that code imports.
265
+ - A class defined in `__main__` (a notebook cell, or the script being run) brings a module written
266
+ from the code that defined it, with what it takes from the other cells, and the project's own
267
+ modules that module imports.
268
+
269
+ Warns when a file the bundle carries changed on disk after this process imported it, and logs the
270
+ imported names found nowhere here.
271
+ """
272
+ if "<locals>" in cls.__qualname__:
273
+ raise BundleError(
274
+ f"{cls.__name__} is defined inside a function ({cls.__qualname__}); define it at the top level "
275
+ "of a module or of a cell, so the service can import it by name",
276
+ name=cls.__qualname__,
277
+ )
278
+ if cls.__module__ == "__main__":
279
+ name = module_name_for(cls)
280
+ text = export_module(cls)
281
+ paths, missing = local_modules(imports_in_source(text), installed=installed, own={name})
282
+ code = BundleCode(paths, modules={name: text})
283
+ predictor = f"{name}:{cls.__qualname__}.load"
284
+ else:
285
+ paths, missing = project_package(cls.__module__.split(".")[0], installed=installed)
286
+ code = BundleCode(paths)
287
+ predictor = f"{cls.__module__}:{cls.__qualname__}.load"
288
+ report_code(code, missing, owner=cls.__name__)
289
+ return code, predictor
290
+
291
+
292
+ def report_code(code: BundleCode, missing: Sequence[str], *, owner: str) -> None:
293
+ """Warns about a file the bundle carries that changed on disk after this process imported it, and
294
+ about the names its code imports that were found nowhere here."""
295
+ edited = edited_after_import(code.paths)
296
+ if edited:
297
+ logger.warning(
298
+ "%s changed on disk after this process imported %s: the bundle carries the files as they are "
299
+ "now, while this process runs them as they were when imported. If the change touched the model, "
300
+ "restart the kernel and train again",
301
+ ", ".join(str(path) for path in edited),
302
+ "it" if len(edited) == 1 else "them",
303
+ )
304
+ if missing:
305
+ logger.warning(
306
+ "the code of %s imports %s, found nowhere here: the service will have to provide %s",
307
+ owner,
308
+ ", ".join(missing),
309
+ "it" if len(missing) == 1 else "them",
310
+ )
311
+
312
+
313
+ def edited_after_import(roots: Path | Iterable[Path]) -> list[Path]:
314
+ """The source files under `roots` of modules this process already imported, and that changed on disk
315
+ after they were compiled.
316
+
317
+ Python records, in the header of a module's `.pyc`, the time and size of the source it compiled (or its
318
+ hash). A source that no longer matches was edited after this process, or the last one to import it,
319
+ compiled it. Without a `.pyc` (bytecode turned off, a folder that cannot be written) nothing is known,
320
+ and nothing is reported.
321
+ """
322
+ folders = [root.resolve() for root in ([roots] if isinstance(roots, Path) else roots)]
323
+ # Only a module whose file has the name of one of these files can be one of them: the costly part,
324
+ # resolving each module's path, is left for those.
325
+ names = {path.name for folder in folders for path in python_files(folder)}
326
+ edited: set[Path] = set()
327
+ for module in list(sys.modules.values()):
328
+ file = getattr(module, "__file__", None)
329
+ if not file or not str(file).endswith(".py") or os.path.basename(file) not in names:
330
+ continue
331
+ source = Path(file).resolve()
332
+ if any(source == folder or source.is_relative_to(folder) for folder in folders):
333
+ if _changed_since_compiled(source):
334
+ edited.add(source)
335
+ return sorted(edited)
336
+
337
+
338
+ def _changed_since_compiled(source: Path) -> bool:
339
+ try:
340
+ cached = Path(importlib.util.cache_from_source(str(source)))
341
+ header = cached.read_bytes()[:16]
342
+ stat = source.stat()
343
+ except (NotImplementedError, ValueError, OSError):
344
+ return False
345
+ if len(header) < 16 or header[:4] != importlib.util.MAGIC_NUMBER:
346
+ return False
347
+ flags = int.from_bytes(header[4:8], "little")
348
+ if flags & 0b1: # a hash-based .pyc (PEP 552) records the source's hash instead of its time and size
349
+ return header[8:16] != importlib.util.source_hash(source.read_bytes())
350
+ mtime, size = struct.unpack("<II", header[8:16])
351
+ return (int(stat.st_mtime) & 0xFFFFFFFF, stat.st_size & 0xFFFFFFFF) != (mtime, size)