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,373 @@
1
+ """Classes and functions defined in a notebook, or in the script Python runs as `__main__`, turned back into
2
+ a module.
3
+
4
+ A bundle carries files, and a notebook's cells are not files: what a cell defines lives in the kernel's
5
+ memory, next to the functions, constants and imports of the other cells it uses. A bundle that keeps an
6
+ object made from such a class (a network), or such a function (a preparation), must carry their code, or a
7
+ service could not read the object back. This module writes all of that as one Python module, without
8
+ running anything:
9
+
10
+ 1. it finds each one's own code (the kernel keeps each executed cell, so the code found is the code that
11
+ ran, even when the cell was edited afterwards without being run again);
12
+ 2. it reads which names that code takes from the notebook (the compiler's own analysis, `symtable`);
13
+ 3. it writes each one again: a module as an `import` (with the submodules the code reaches through it,
14
+ `lab.utils.double(x)`, which `import lab` alone does not bring), a function or class from another module
15
+ as a `from ... import`, a function or class of the notebook as its code (followed the same way), and a
16
+ literal constant as its value;
17
+ 4. it refuses, naming each one, what has no code to write: an object built at run time (a fitted
18
+ scaler, a tokenizer), a `lambda`, a name the notebook does not define. Such a value travels as the
19
+ state of an object instead (an argument of `functools.partial`, an attribute of the network).
20
+
21
+ This is the one place in the library that writes Python as text, and it checks what it writes: every
22
+ value is read back with `ast.literal_eval`, and the whole module is compiled before anyone writes it.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import ast
28
+ import builtins
29
+ import inspect
30
+ import linecache
31
+ import re
32
+ import symtable
33
+ import sys
34
+ import textwrap
35
+ import types
36
+ from collections.abc import Iterable, Iterator, Mapping
37
+ from typing import Any
38
+
39
+ from torchstack64.core import BundleError
40
+
41
+ HEADER = (
42
+ "# Generated by torchstack64 from the notebook cells that define {name}, when the bundle was written.\n"
43
+ "# Edit the notebook, not this file.\n"
44
+ )
45
+ _LAMBDA = "<lambda>"
46
+ _BUILTINS = frozenset(dir(builtins))
47
+
48
+
49
+ def module_name_for(cls: type) -> str:
50
+ """The name the generated module is imported by: the class's name in snake case."""
51
+ words = re.sub(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])", "_", cls.__name__).lower()
52
+ name = re.sub(r"\W", "_", words) or "notebook_code"
53
+ if name in sys.stdlib_module_names or name in {"torchstack64", "code"} or not name.isidentifier():
54
+ name = f"{name}_module"
55
+ return name
56
+
57
+
58
+ def export_module(*roots: Any) -> str:
59
+ """The source of one module that defines `roots` (classes and functions of the notebook) and everything
60
+ they take from it.
61
+
62
+ Raises `BundleError` naming each name that cannot be written as code.
63
+ """
64
+ if not roots:
65
+ raise ValueError("export_module needs at least one class or function to write")
66
+ for root in roots:
67
+ qualname = getattr(root, "__qualname__", "")
68
+ if getattr(root, "__name__", "") == _LAMBDA:
69
+ raise BundleError(
70
+ "a lambda has no name a service could import it by: write it with def, at the top of a cell",
71
+ name=_LAMBDA,
72
+ )
73
+ if "<locals>" in qualname:
74
+ raise BundleError(
75
+ f"{root.__name__} is defined inside a function ({qualname}); define it at the top of a "
76
+ "cell, so a service can import it by name",
77
+ name=qualname,
78
+ )
79
+ exporter = _Exporter(_namespace_of(roots[0]), owner=", ".join(root.__name__ for root in roots))
80
+ for root in roots:
81
+ exporter.add_root(root)
82
+ return exporter.text()
83
+
84
+
85
+ def class_source(cls: type) -> str:
86
+ """The code of a class, decorators included.
87
+
88
+ It is looked for, in order: in the cell (or file) its own functions were compiled from, around the
89
+ line they start on, which is the code that ran; through `inspect`, for a script; and, for a class
90
+ without functions of its own, as the newest cell that defines a class of that name. Whatever is found
91
+ must define exactly that class.
92
+ """
93
+ for function in _functions_of(cls):
94
+ code = function.__code__
95
+ found = _definition_in(code.co_filename, cls.__name__, line=code.co_firstlineno)
96
+ if found is not None:
97
+ return found
98
+ try:
99
+ found = textwrap.dedent(inspect.getsource(cls))
100
+ except (OSError, TypeError):
101
+ found = None
102
+ if found is not None and _defines(found, cls.__name__):
103
+ return found
104
+ for filename in reversed(list(linecache.cache)): # the newest cell first: a class defined twice
105
+ found = _definition_in(filename, cls.__name__)
106
+ if found is not None:
107
+ return found
108
+ raise BundleError(
109
+ f"the code of {cls.__name__} cannot be found: write it in a file with %%writefile, and import it",
110
+ name=cls.__name__,
111
+ )
112
+
113
+
114
+ def _defines(source: str, name: str) -> bool:
115
+ try:
116
+ body = ast.parse(source).body
117
+ except SyntaxError:
118
+ return False
119
+ return len(body) == 1 and isinstance(body[0], ast.ClassDef) and body[0].name == name
120
+
121
+
122
+ def free_names(source: str) -> list[str]:
123
+ """The names `source` reads from the module it lives in, which some other code has to define: what
124
+ the compiler itself resolves as globals, less what `source` defines and the built-in names."""
125
+ top = symtable.symtable(source, "<cell>", "exec")
126
+ defined = {
127
+ symbol.get_name() for symbol in top.get_symbols() if symbol.is_assigned() or symbol.is_imported()
128
+ }
129
+ found = {symbol.get_name() for symbol in top.get_symbols() if symbol.is_referenced()}
130
+ pending = list(top.get_children())
131
+ while pending:
132
+ table = pending.pop()
133
+ pending.extend(table.get_children())
134
+ found |= {
135
+ symbol.get_name()
136
+ for symbol in table.get_symbols()
137
+ if symbol.is_global() and symbol.is_referenced()
138
+ }
139
+ return sorted(name for name in found - defined - _BUILTINS if not name.startswith("__"))
140
+
141
+
142
+ class _Exporter:
143
+ def __init__(self, namespace: Mapping[str, Any], *, owner: str) -> None:
144
+ self.namespace = namespace
145
+ self.owner = owner
146
+ self.imports: set[str] = set()
147
+ self.blocks: list[str] = []
148
+ self.seen: set[str] = set()
149
+ self.refused: list[str] = []
150
+
151
+ def add_source(self, source: str) -> None:
152
+ names = free_names(source)
153
+ for name in names:
154
+ self.add_name(name)
155
+ self.imports.update(_submodule_imports(source, names, self.namespace))
156
+ self.blocks.append(source.strip("\n"))
157
+
158
+ def add_root(self, value: Any) -> None:
159
+ """A class or function the module is written for: its own code, whatever its name holds now."""
160
+ name = value.__name__
161
+ if name in self.seen:
162
+ return
163
+ self.seen.add(name)
164
+ self._add_definition(name, value)
165
+
166
+ def add_name(self, name: str) -> None:
167
+ if name in self.seen:
168
+ return
169
+ self.seen.add(name)
170
+ if name not in self.namespace:
171
+ self.refused.append(f"{name} is not defined in the notebook")
172
+ return
173
+ value = self.namespace[name]
174
+ if isinstance(value, types.ModuleType):
175
+ module = value.__name__
176
+ if module == "__main__":
177
+ self.refused.append(f"{name} is the notebook itself")
178
+ else:
179
+ self.imports.add(f"import {module}" if module == name else f"import {module} as {name}")
180
+ elif _defined_here(value):
181
+ self._add_definition(name, value)
182
+ elif (where := _importable(value, name)) is not None:
183
+ module, attribute = where
184
+ self.imports.add(
185
+ f"from {module} import {attribute}" + ("" if attribute == name else f" as {name}")
186
+ )
187
+ elif _is_literal(value):
188
+ self.blocks.append(f"{name} = {value!r}")
189
+ else:
190
+ self.refused.append(f"{name} is a {type(value).__name__} built at run time")
191
+
192
+ def _add_definition(self, name: str, value: Any) -> None:
193
+ if getattr(value, "__name__", "") == _LAMBDA:
194
+ self.refused.append(f"{name} is a lambda: define it with def")
195
+ return
196
+ if "<locals>" in getattr(value, "__qualname__", ""):
197
+ self.refused.append(f"{name} is defined inside a function")
198
+ return
199
+ try:
200
+ source = class_source(value) if isinstance(value, type) else _function_source(value)
201
+ except (BundleError, OSError, TypeError):
202
+ self.refused.append(f"the code of {name} cannot be found")
203
+ return
204
+ self.add_source(source)
205
+ if value.__name__ != name:
206
+ self.blocks.append(f"{name} = {value.__name__}")
207
+
208
+ def text(self) -> str:
209
+ if self.refused:
210
+ raise BundleError(
211
+ f"{self.owner} cannot travel in the bundle from the notebook: {'; '.join(self.refused)}. "
212
+ "A value built at run time travels as the state of an object: give it to the function "
213
+ "(functools.partial(function, name=value)), keep it in an attribute of the network, or, in a "
214
+ "predictor class of your own, return it from pack(); or define it in a file the code imports",
215
+ refused=list(self.refused),
216
+ )
217
+ imports = "\n".join(sorted(self.imports, key=lambda line: (line.startswith("from "), line)))
218
+ body = "\n\n\n".join(self.blocks)
219
+ text = (
220
+ HEADER.format(name=self.owner) + ("\n" + imports + "\n" if imports else "") + "\n\n" + body + "\n"
221
+ )
222
+ try:
223
+ compile(text, f"<{self.owner} from the notebook>", "exec", dont_inherit=True)
224
+ except SyntaxError as error:
225
+ raise BundleError(
226
+ f"the module written from the notebook for {self.owner} does not compile ({error}); a cell "
227
+ "that uses IPython's own syntax (a magic, a shell command) inside the class cannot travel: "
228
+ "write that code in a file with %%writefile",
229
+ name=self.owner,
230
+ ) from error
231
+ return text
232
+
233
+
234
+ def _submodule_imports(source: str, names: Iterable[str], namespace: Mapping[str, Any]) -> set[str]:
235
+ """The `import a.b` lines for the submodules of a module that `source` reaches through attributes.
236
+
237
+ `import lab` does not import `lab.utils`. The notebook has `lab.utils` because some cell imported it,
238
+ but a service that reads the written module only has what the module itself imports, and
239
+ `lab.utils.double(x)` would fail there with an `AttributeError`. A submodule is one the attribute holds
240
+ and whose own name is the package's name plus the attribute; an alias (`os.path`) or a function is not.
241
+ """
242
+ roots = {
243
+ name
244
+ for name in names
245
+ if isinstance(namespace.get(name), types.ModuleType) and namespace[name].__name__ != "__main__"
246
+ }
247
+ if not roots:
248
+ return set()
249
+ found: set[str] = set()
250
+ for node in ast.walk(ast.parse(source)):
251
+ parts = _dotted(node) if isinstance(node, ast.Attribute) else None
252
+ if parts is None or parts[0] not in roots:
253
+ continue
254
+ module = namespace[parts[0]]
255
+ for part in parts[1:]:
256
+ child = vars(module).get(part) # vars, not getattr: a lazy attribute must not import
257
+ if not isinstance(child, types.ModuleType) or child.__name__ != f"{module.__name__}.{part}":
258
+ break
259
+ module = child
260
+ found.add(module.__name__)
261
+ # `import a.b.c` brings `a.b` too: only the deepest of each chain is written
262
+ return {f"import {name}" for name in found if not any(other.startswith(name + ".") for other in found)}
263
+
264
+
265
+ def _dotted(node: ast.Attribute) -> list[str] | None:
266
+ """`a.b.c` as `["a", "b", "c"]`; `None` when the chain does not start at a plain name (`f().b`)."""
267
+ parts: list[str] = []
268
+ value: ast.expr = node
269
+ while isinstance(value, ast.Attribute):
270
+ parts.append(value.attr)
271
+ value = value.value
272
+ if not isinstance(value, ast.Name):
273
+ return None
274
+ return [value.id, *reversed(parts)]
275
+
276
+
277
+ def _namespace_of(root: Any) -> Mapping[str, Any]:
278
+ """The globals a function or a class's functions run with: the notebook's namespace, or the script's
279
+ module."""
280
+ if isinstance(root, types.FunctionType):
281
+ return root.__globals__
282
+ if isinstance(root, type):
283
+ for function in _functions_of(root):
284
+ return function.__globals__
285
+ wrapped = inspect.unwrap(root) if callable(root) else None
286
+ if isinstance(wrapped, types.FunctionType):
287
+ return wrapped.__globals__
288
+ return vars(sys.modules[root.__module__])
289
+
290
+
291
+ def _functions_of(cls: type) -> Iterator[types.FunctionType]:
292
+ """The functions written in the class's own body. A function only set on it (`rule = some_function`) is
293
+ left out: it was compiled elsewhere, with another module's names."""
294
+ for value in vars(cls).values():
295
+ if isinstance(value, staticmethod | classmethod):
296
+ value = value.__func__
297
+ elif isinstance(value, property):
298
+ value = value.fget
299
+ if isinstance(value, types.FunctionType) and value.__qualname__.startswith(cls.__qualname__ + "."):
300
+ yield value
301
+
302
+
303
+ def _definition_in(filename: str, name: str, *, line: int | None = None) -> str | None:
304
+ """The code of the top-level class `name` in the cached file `filename`: the one around `line` when
305
+ given, else the last one, decorators included."""
306
+ text = "".join(linecache.getlines(filename))
307
+ if f"class {name}" not in text:
308
+ return None
309
+ try:
310
+ tree = ast.parse(text)
311
+ except SyntaxError:
312
+ return None
313
+ lines = text.splitlines(keepends=True)
314
+ found = None
315
+ for node in tree.body:
316
+ if isinstance(node, ast.ClassDef) and node.name == name:
317
+ end = node.end_lineno or node.lineno
318
+ if line is None or node.lineno <= line <= end:
319
+ start = min([node.lineno, *(decorator.lineno for decorator in node.decorator_list)])
320
+ found = "".join(lines[start - 1 : end])
321
+ return found
322
+
323
+
324
+ def _function_source(function: Any) -> str:
325
+ """A function's code, its decorators included; `inspect` follows a decorator's `__wrapped__`."""
326
+ return textwrap.dedent(inspect.getsource(function))
327
+
328
+
329
+ def _defined_here(value: Any) -> bool:
330
+ """A function or class the notebook (or the script being run) defined itself, decorated or not: a
331
+ decorator such as `functools.lru_cache` hands back an object that keeps the function in `__wrapped__`."""
332
+ if getattr(value, "__module__", None) != "__main__":
333
+ return False
334
+ return isinstance(value, types.FunctionType | type) or isinstance(
335
+ inspect.unwrap(value) if callable(value) else None, types.FunctionType
336
+ )
337
+
338
+
339
+ def _importable(value: Any, name: str) -> tuple[str, str] | None:
340
+ """Where `value` can be imported from: the shortest module on its own module's path that holds it
341
+ under one of its names, or `None` when it is not something any module offers."""
342
+ module = getattr(value, "__module__", None)
343
+ if not isinstance(module, str) or module == "__main__" or isinstance(value, types.ModuleType):
344
+ return None
345
+ attributes = [
346
+ candidate
347
+ for candidate in (getattr(value, "__qualname__", None), getattr(value, "__name__", None), name)
348
+ if isinstance(candidate, str) and candidate.isidentifier()
349
+ ]
350
+ parts = module.split(".")
351
+ for size in range(1, len(parts) + 1):
352
+ holder = sys.modules.get(".".join(parts[:size]))
353
+ if holder is None:
354
+ continue
355
+ for attribute in attributes:
356
+ try:
357
+ if getattr(holder, attribute, None) is value:
358
+ return ".".join(parts[:size]), attribute
359
+ except Exception: # a module whose lazy attributes fail to import offers nothing here
360
+ continue
361
+ return None
362
+
363
+
364
+ def _is_literal(value: Any) -> bool:
365
+ """A value Python can write as source and read back the same: numbers, text, and containers of them."""
366
+ if not isinstance(
367
+ value, int | float | complex | str | bytes | bool | type(None) | tuple | list | dict | set
368
+ ):
369
+ return False
370
+ try:
371
+ return bool(ast.literal_eval(repr(value)) == value)
372
+ except (ValueError, SyntaxError, TypeError, MemoryError, RecursionError):
373
+ return False