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,256 @@
1
+ """Raw inputs and the preparation that turns them into network inputs.
2
+
3
+ `PreparedData` keeps inputs and preparation together, preparing the rows once and serving them in batches.
4
+ It also supplies the preparation and example data saved in a bundle. Use `LabeledData` from
5
+ `torchstack64.data.labeled` when the task needs labels and targets.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ from collections.abc import Callable, Mapping
12
+ from typing import Any, Self
13
+
14
+ import torch
15
+ from torch.utils.data import DataLoader, Dataset
16
+
17
+ from torchstack64.artifacts.proofs import (
18
+ EXAMPLE_SIZE,
19
+ PREPARED_ATOL,
20
+ PREPARED_RTOL,
21
+ Example,
22
+ describe_difference,
23
+ largest_difference,
24
+ rows_of,
25
+ take,
26
+ )
27
+ from torchstack64.core import LabelSchema
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ class PreparedData:
33
+ """Raw inputs paired with the tensors or dictionaries sent to the network.
34
+
35
+ `inputs` holds one raw value per row. `prepare` converts all rows at once and may be a function or a
36
+ callable that retains learned state, such as a vocabulary. The result is cached in `prepared`.
37
+
38
+ Pass a previously prepared result with `prepared=` to check that it matches `prepare(inputs)`.
39
+ Slicing with `data[rows]` does not prepare the rows again.
40
+
41
+ data = PreparedData(images, prepare=to_network)
42
+ train, val = data[train_rows], data[val_rows]
43
+
44
+ `save_bundle` uses `prepare`, `schema`, and `example()` from the data. Without labels, `schema` is
45
+ `None`; use `predictor=` to define the bundle's answer, such as an embedding or reconstruction error.
46
+ """
47
+
48
+ __slots__ = ("_inputs", "_prepare", "_prepared")
49
+
50
+ def __init__(self, inputs: Any, *, prepare: Callable[[list[Any]], Any], prepared: Any = None) -> None:
51
+ if not callable(prepare):
52
+ raise TypeError(
53
+ f"prepare is what turns a list of raw inputs into what the network receives, a function or "
54
+ f"an object that can be called; got {type(prepare).__name__}"
55
+ )
56
+ size = rows_of(inputs, "inputs")
57
+ if size < 1:
58
+ raise ValueError(f"a {type(self).__name__} needs at least one row")
59
+ _warn_if_it_cannot_travel(prepare)
60
+ made = as_tensors(prepare(rows_list(inputs)), "what prepare gave")
61
+ if rows_of(made, "what prepare gave") != size:
62
+ raise ValueError(
63
+ f"prepare gave {rows_of(made, 'what prepare gave')} rows for {size} inputs: it must give one "
64
+ "row per input, in the same order"
65
+ )
66
+ if prepared is not None:
67
+ given = as_tensors(prepared, "prepared")
68
+ difference = largest_difference(given, made, atol=PREPARED_ATOL, rtol=PREPARED_RTOL)
69
+ if difference is not None:
70
+ raise ValueError(
71
+ "prepared is not what prepare gives for these inputs: "
72
+ f"{describe_difference(difference, 'prepared has', 'prepare gives', place='row')}. "
73
+ "Pass the function that made prepared, or leave prepared out and train on data.loader()"
74
+ )
75
+ made = given
76
+ self._inputs = inputs
77
+ self._prepare = prepare
78
+ self._prepared = made
79
+
80
+ # -- what it holds -------------------------------------------------------------------------------------
81
+
82
+ @property
83
+ def inputs(self) -> Any:
84
+ """The raw inputs, one per row, as they were given."""
85
+ return self._inputs
86
+
87
+ @property
88
+ def prepare(self) -> Callable[[list[Any]], Any]:
89
+ """The preparation: a list of raw inputs in, what the network receives out."""
90
+ return self._prepare
91
+
92
+ @property
93
+ def prepared(self) -> Any:
94
+ """What the network receives for every row: a tensor, or a dict of tensors."""
95
+ return self._prepared
96
+
97
+ @property
98
+ def schema(self) -> LabelSchema | None:
99
+ """The classes, in the order of the network's columns: none, for data without labels. What
100
+ `save_bundle` writes in the bundle; a `LabeledData` has its own."""
101
+ return None
102
+
103
+ def __len__(self) -> int:
104
+ return rows_of(self._prepared, "prepared")
105
+
106
+ def __repr__(self) -> str:
107
+ return f"{type(self).__name__}({len(self)} rows; prepared {described(self._prepared)})"
108
+
109
+ # -- a subset, and the batches ---------------------------------------------------------------------------
110
+
111
+ def __getitem__(self, rows: Any) -> Self:
112
+ """The rows `rows` (a slice, a list or an array of positions, or a mask of booleans), as data of
113
+ the same kind, with the same preparation; nothing is prepared again."""
114
+ return self._taken(_positions(rows, len(self)))
115
+
116
+ def _taken(self, picked: list[int]) -> Self:
117
+ """The rows `picked`, already prepared and checked: nothing is prepared or checked again. A
118
+ subclass takes its own values of each row too."""
119
+ made = object.__new__(type(self))
120
+ made._inputs, made._prepare = take(self._inputs, picked), self._prepare
121
+ made._prepared = take(self._prepared, picked)
122
+ return made
123
+
124
+ def loader(self, batch_size: int, *, shuffle: bool = False, **dataloader_args: Any) -> DataLoader[Any]:
125
+ """A `DataLoader` of batches of the prepared rows, stacked (a dict stays a dict): `(prepared,)`
126
+ here, and `(prepared, targets)` in a `LabeledData`. `dataloader_args` go to the `DataLoader`
127
+ as they are (`generator=`, `num_workers=`, `drop_last=`)."""
128
+ if isinstance(batch_size, bool) or not isinstance(batch_size, int) or batch_size < 1:
129
+ raise ValueError(f"batch_size is how many rows a batch has, at least 1; got {batch_size!r}")
130
+ rows = _Rows(self._batch_parts())
131
+ return DataLoader(rows, batch_size=batch_size, shuffle=shuffle, **dataloader_args)
132
+
133
+ def _batch_parts(self) -> tuple[Any, ...]:
134
+ """What each batch carries, in order: the prepared rows."""
135
+ return (self._prepared,)
136
+
137
+ # -- the rows a bundle is proved on ----------------------------------------------------------------------
138
+
139
+ def example(self, size: int = EXAMPLE_SIZE, *, seed: int = 0) -> Example:
140
+ """`size` rows drawn with `seed`, in the forms the proofs of a bundle compare: the raw inputs (as
141
+ JSON, what a request carries) and what the preparation gives for exactly those inputs; in a
142
+ `LabeledData`, their labels and targets too. All the rows when there are fewer than `size`.
143
+
144
+ The prepared rows are made again from the drawn inputs, as a service will make them: a preparation
145
+ whose width depends on the call (a tokenizer that pads to the longest text) gives the width of
146
+ these rows, not the one of the whole data."""
147
+ if len(self) < 2:
148
+ raise ValueError(
149
+ f"a bundle is proved on at least 2 rows, so the batch proof can compare one input alone with "
150
+ f"the same input among others; this data has {len(self)}"
151
+ )
152
+ drawn = self._drawn(size, seed)
153
+ return Example(
154
+ inputs=drawn.inputs,
155
+ prepared=as_tensors(self._prepare(list(drawn.inputs)), "what prepare gave"),
156
+ labels=drawn.labels,
157
+ targets=drawn.targets,
158
+ )
159
+
160
+ def _drawn(self, size: int, seed: int) -> Example:
161
+ """The example's rows as drawn, before they are prepared again: the inputs."""
162
+ return Example.sample(inputs=self._inputs, size=size, seed=seed)
163
+
164
+
165
+ class _Rows(Dataset[Any]):
166
+ """Values with one row per position, the prepared rows first: one tuple of rows per position, what
167
+ `loader` iterates."""
168
+
169
+ def __init__(self, parts: tuple[Any, ...]) -> None:
170
+ self.parts = parts
171
+ self.size = rows_of(parts[0], "prepared")
172
+
173
+ def __len__(self) -> int:
174
+ return self.size
175
+
176
+ def __getitem__(self, index: int) -> tuple[Any, ...]:
177
+ return tuple(_row(part, index) for part in self.parts)
178
+
179
+
180
+ def _row(value: Any, index: int) -> Any:
181
+ if isinstance(value, Mapping):
182
+ return {key: item[index] for key, item in value.items()}
183
+ return value[index]
184
+
185
+
186
+ def rows_list(inputs: Any) -> list[Any]:
187
+ """The inputs as a list of rows: what a preparation receives, here as in a service."""
188
+ if isinstance(inputs, list):
189
+ return inputs
190
+ return list(inputs)
191
+
192
+
193
+ def as_tensors(value: Any, name: str) -> Any:
194
+ """What a preparation gave, as PyTorch tensors when it can be one: a tensor as it is, a NumPy array or a
195
+ list of numbers turned into one, a dict (a tokenizer's output) turned into a dict of them. A list that is
196
+ no tensor (texts, for a model of its own class that takes them) stays a list, one row per input."""
197
+ if isinstance(value, torch.Tensor):
198
+ return value
199
+ if isinstance(value, Mapping):
200
+ return {str(key): as_tensors(item, f"{name}[{key!r}]") for key, item in value.items()}
201
+ try:
202
+ return torch.as_tensor(value)
203
+ except (TypeError, ValueError, RuntimeError) as error:
204
+ if isinstance(value, list | tuple):
205
+ return list(value)
206
+ raise TypeError(
207
+ f"{name} must be a tensor, an array, a list, or a dict of them, one row per input; got "
208
+ f"{type(value).__name__} ({error})"
209
+ ) from None
210
+
211
+
212
+ def described(value: Any) -> str:
213
+ """The prepared rows in a few words, for a `repr`: the kind, the shape and the type."""
214
+ if isinstance(value, Mapping):
215
+ return "{" + ", ".join(f"{key!r}: {described(item)}" for key, item in value.items()) + "}"
216
+ if isinstance(value, torch.Tensor):
217
+ shape = ", ".join(str(size) for size in value.shape)
218
+ return f"Tensor ({shape}) {str(value.dtype).removeprefix('torch.')}"
219
+ return type(value).__name__
220
+
221
+
222
+ def _positions(rows: Any, size: int) -> list[int]:
223
+ """Positions from a slice, an integer sequence or array, or a boolean mask of every row."""
224
+ if isinstance(rows, slice):
225
+ return list(range(size))[rows]
226
+ if isinstance(rows, bool) or isinstance(rows, int):
227
+ raise TypeError(
228
+ "data[rows] takes several rows (a slice, a list of positions, a mask); got one number"
229
+ )
230
+ values = rows.tolist() if hasattr(rows, "tolist") else list(rows)
231
+ if values and all(isinstance(value, bool) for value in values):
232
+ if len(values) != size:
233
+ raise ValueError(f"a mask has one boolean per row: {len(values)} for {size} rows")
234
+ return [index for index, keep in enumerate(values) if keep]
235
+ picked = []
236
+ for value in values:
237
+ if isinstance(value, bool) or not isinstance(value, int) or not -size <= value < size:
238
+ raise IndexError(f"row {value!r} is not a position among the {size} rows")
239
+ picked.append(value % size)
240
+ return picked
241
+
242
+
243
+ def _warn_if_it_cannot_travel(prepare: Any) -> None:
244
+ """A preparation a bundle cannot carry (a lambda, a function made inside another) trains fine, and is
245
+ refused only when the bundle is saved, after the training: said now, while it is cheap to change."""
246
+ target = prepare
247
+ while hasattr(target, "func") and callable(getattr(target, "func", None)):
248
+ target = target.func # functools.partial, possibly nested
249
+ name = getattr(target, "__qualname__", "")
250
+ if name.endswith("<lambda>") or "<locals>" in name:
251
+ kind = "a lambda" if name.endswith("<lambda>") else f"defined inside a function ({name})"
252
+ logger.warning(
253
+ "the preparation is %s: training works, and save_bundle will refuse it, since a service could "
254
+ "not import it by name; write it with def, at the top of a cell or a module",
255
+ kind,
256
+ )
@@ -0,0 +1,128 @@
1
+ """Raw inputs and labels prepared for supervised training.
2
+
3
+ `LabeledData` extends `PreparedData` with a label schema and encoded targets. It keeps the classes,
4
+ network inputs, labels, and targets together, so training batches and saved bundles use the same data
5
+ contract.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Callable
11
+ from typing import Any, Self
12
+
13
+ import torch
14
+
15
+ from torchstack64.artifacts.proofs import Example, rows_of, take, target_columns
16
+ from torchstack64.core import LabelSchema
17
+ from torchstack64.data.base import PreparedData, as_tensors, described, rows_list
18
+
19
+
20
+ class LabeledData(PreparedData):
21
+ """Adds labels and loss targets to `PreparedData`.
22
+
23
+ `labels` holds the true answer for each row. `schema` lists the classes in network-column order;
24
+ when present, it encodes labels into targets. Use `targets=` for a different target format, such as
25
+ binary values for `BCEWithLogitsLoss`.
26
+
27
+ `loader()` returns `(prepared, targets)` batches.
28
+
29
+ data = LabeledData(images, labels, prepare=to_network, schema=LabelSchema.of(range(10)))
30
+ """
31
+
32
+ __slots__ = ("_labels", "_schema", "_targets")
33
+
34
+ def __init__(
35
+ self,
36
+ inputs: Any,
37
+ labels: Any,
38
+ *,
39
+ prepare: Callable[[list[Any]], Any],
40
+ schema: LabelSchema | None = None,
41
+ prepared: Any = None,
42
+ targets: Any = None,
43
+ ) -> None:
44
+ if schema is not None and not isinstance(schema, LabelSchema):
45
+ raise TypeError(f"schema is a LabelSchema (LabelSchema.of(labels)) or None; got {schema!r}")
46
+ size = rows_of(inputs, "inputs")
47
+ if rows_of(labels, "labels") != size:
48
+ raise ValueError(f"inputs has {size} rows, and labels has {rows_of(labels, 'labels')}")
49
+ super().__init__(inputs, prepare=prepare, prepared=prepared)
50
+ self._labels = labels
51
+ self._schema = schema
52
+ self._targets = _targets_of(labels, schema, targets, size)
53
+
54
+ # -- what it holds, beyond the prepared inputs -----------------------------------------------------------
55
+
56
+ @property
57
+ def labels(self) -> Any:
58
+ """The true answer of each row, as they were given."""
59
+ return self._labels
60
+
61
+ @property
62
+ def schema(self) -> LabelSchema | None:
63
+ """The classes, in the order of the network's columns, or `None`."""
64
+ return self._schema
65
+
66
+ @property
67
+ def targets(self) -> Any:
68
+ """What the loss receives for every row: the column of each label, unless `targets=` said so."""
69
+ return self._targets
70
+
71
+ def __repr__(self) -> str:
72
+ if self._schema is None:
73
+ classes = "no schema"
74
+ else:
75
+ shown = ", ".join(repr(c) for c in self._schema.classes[:4])
76
+ more = ", ..." if len(self._schema.classes) > 4 else ""
77
+ classes = f"{self._schema.kind} schema of {len(self._schema.classes)} classes ({shown}{more})"
78
+ return f"LabeledData({len(self)} rows; prepared {described(self._prepared)}; {classes})"
79
+
80
+ # -- what a subset, a batch and the example carry beyond the prepared inputs -----------------------------
81
+
82
+ def _taken(self, picked: list[int]) -> Self:
83
+ """The rows `picked`, with their labels and targets, and the same schema."""
84
+ made = super()._taken(picked)
85
+ made._labels, made._schema = take(self._labels, picked), self._schema
86
+ made._targets = take(self._targets, picked)
87
+ return made
88
+
89
+ def _batch_parts(self) -> tuple[Any, ...]:
90
+ """What each batch carries, in order: the prepared rows and their targets."""
91
+ return self._prepared, self._targets
92
+
93
+ def _drawn(self, size: int, seed: int) -> Example:
94
+ """The example's rows as drawn, before they are prepared again: the inputs, their labels and their
95
+ targets."""
96
+ return Example.sample(
97
+ inputs=self._inputs, labels=self._labels, targets=self._targets, size=size, seed=seed
98
+ )
99
+
100
+
101
+ def _targets_of(labels: Any, schema: LabelSchema | None, targets: Any, size: int) -> Any:
102
+ if schema is None:
103
+ if targets is None:
104
+ raise ValueError(
105
+ "without a schema, pass targets=: what the loss receives for each label. A classifier gives "
106
+ "schema=LabelSchema.of(labels) instead; data without labels is a PreparedData"
107
+ )
108
+ given = as_tensors(targets, "targets")
109
+ if rows_of(given, "targets") != size:
110
+ raise ValueError(f"inputs has {size} rows, and targets has {rows_of(given, 'targets')}")
111
+ return given
112
+ columns = schema.encode(rows_list(labels))
113
+ if targets is None:
114
+ return torch.as_tensor(columns, dtype=torch.long)
115
+ given = as_tensors(targets, "targets")
116
+ if rows_of(given, "targets") != size:
117
+ raise ValueError(f"inputs has {size} rows, and targets has {rows_of(given, 'targets')}")
118
+ found = target_columns(given, len(schema.classes))
119
+ for index, (column, target) in enumerate(zip(columns, found, strict=True)):
120
+ if column != target:
121
+ label = rows_list(labels)[index]
122
+ label = label.item() if hasattr(label, "item") else label # a NumPy or PyTorch scalar, as Python
123
+ raise ValueError(
124
+ f"targets does not encode the labels the way the schema does: the schema puts {label!r} at "
125
+ f"column {column}, and targets has {target} (row {index}). Leave targets out, so they are "
126
+ "schema.encode(labels), or write the schema in the order the targets use"
127
+ )
128
+ return given
@@ -0,0 +1,38 @@
1
+ """The one place where the library decides which device to compute on.
2
+
3
+ Every part of the library that places tensors (training, evaluation, prediction, loading a model to
4
+ serve) takes a `device` argument whose default is `None`, and `None` means "ask this package". The
5
+ answer comes from the first of these that is set:
6
+
7
+ 1. `use_device("cpu")`, a context manager for one block of code (one thread, one task);
8
+ 2. `set_device("cuda:1")`, the default for the whole process;
9
+ 3. the environment variable `TORCHSTACK64_DEVICE`, so a notebook can run on the CPU in CI without
10
+ being edited;
11
+ 4. `"auto"`: the best accelerator this machine has (CUDA, then any other PyTorch accelerator, then
12
+ Apple's MPS), and the CPU when there is none.
13
+
14
+ Which function answers which question:
15
+
16
+ - `current_device(device=None)`: the concrete name to use now: `device` itself when given, else the one
17
+ the chain above picks, with `"auto"` replaced by what this machine has.
18
+ - `resolve_torch_device(device=None)`: the same, as a `torch.device` that this machine really has.
19
+ - `validate_device_name(device)`: checks a name without resolving it, so a config can fail early.
20
+
21
+ Inside the package, `hardware.best_available()` is what `"auto"` becomes.
22
+ """
23
+
24
+ from torchstack64.devices.selection import (
25
+ current_device,
26
+ resolve_torch_device,
27
+ set_device,
28
+ use_device,
29
+ validate_device_name,
30
+ )
31
+
32
+ __all__ = [
33
+ "current_device",
34
+ "resolve_torch_device",
35
+ "set_device",
36
+ "use_device",
37
+ "validate_device_name",
38
+ ]
@@ -0,0 +1,43 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from torchstack64.core import is_installed
6
+
7
+ if TYPE_CHECKING:
8
+ import torch
9
+
10
+
11
+ def best_available() -> str:
12
+ """The best accelerator PyTorch sees on this machine, or `"cpu"` (also when PyTorch is absent)."""
13
+ if not is_installed("torch"):
14
+ return "cpu"
15
+ import torch
16
+
17
+ found = torch.accelerator.current_accelerator() if torch.accelerator.is_available() else None
18
+ if found is None:
19
+ return "cpu"
20
+ if found.type in ("cuda", "xpu"):
21
+ return f"{found.type}:{torch.accelerator.current_device_index()}"
22
+ return "mps" if found.type == "mps" else "cpu"
23
+
24
+
25
+ def why_unavailable(device: torch.device) -> str | None:
26
+ """Why this machine cannot give `device`, or `None` when it can. Needs PyTorch."""
27
+ import torch
28
+
29
+ if device.type == "cuda":
30
+ if not torch.cuda.is_available():
31
+ return (
32
+ f"PyTorch sees no CUDA GPU here (PyTorch {torch.__version__}). "
33
+ "Use 'auto' or 'cpu', or install the CUDA build of PyTorch"
34
+ )
35
+ if device.index is not None and device.index >= torch.cuda.device_count():
36
+ return f"there are {torch.cuda.device_count()} CUDA devices"
37
+ elif device.type == "mps":
38
+ if not torch.backends.mps.is_available():
39
+ return "MPS is not available here"
40
+ elif device.type == "xpu":
41
+ if not (hasattr(torch, "xpu") and torch.xpu.is_available()):
42
+ return "no XPU is available here"
43
+ return None
@@ -0,0 +1,82 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import re
5
+ from collections.abc import Iterator
6
+ from contextlib import contextmanager
7
+ from contextvars import ContextVar
8
+ from typing import TYPE_CHECKING
9
+
10
+ from torchstack64.core import DeviceUnavailableError, require
11
+ from torchstack64.devices.hardware import best_available, why_unavailable
12
+
13
+ if TYPE_CHECKING:
14
+ import torch
15
+
16
+ ENV_VAR = "TORCHSTACK64_DEVICE"
17
+ AUTO = "auto"
18
+
19
+ _DEVICE_NAME = re.compile(r"^(?:auto|cpu|mps|(?:cuda|xpu)(?::\d+)?)$")
20
+
21
+ _process_default: str | None = None
22
+ _scoped: ContextVar[str | None] = ContextVar("torchstack64_device", default=None)
23
+
24
+
25
+ def validate_device_name(device: str, *, source: str = "device") -> str:
26
+ """Returns `device` if it is a name this library understands; raises `ValueError` otherwise."""
27
+ name = str(device).strip().lower()
28
+ if not _DEVICE_NAME.match(name):
29
+ raise ValueError(
30
+ f"{source} must be 'auto', 'cpu', 'mps', 'cuda', 'cuda:<index>', 'xpu' or 'xpu:<index>'; "
31
+ f"got {device!r}"
32
+ )
33
+ return name
34
+
35
+
36
+ def set_device(device: str | None) -> None:
37
+ """Sets the device the whole process uses when a call is not given one. `None` goes back to the
38
+ environment variable, or to `"auto"`."""
39
+ global _process_default
40
+ _process_default = None if device is None else validate_device_name(device)
41
+
42
+
43
+ @contextmanager
44
+ def use_device(device: str) -> Iterator[str]:
45
+ """Uses `device` for everything inside the `with` block, then goes back to what was there."""
46
+ token = _scoped.set(validate_device_name(device))
47
+ try:
48
+ yield current_device()
49
+ finally:
50
+ _scoped.reset(token)
51
+
52
+
53
+ def current_device(device: str | None = None) -> str:
54
+ """The concrete device name to use now, with `"auto"` replaced by what this machine has (`"cuda:0"`,
55
+ `"mps"` or `"cpu"`). It comes from the first of these that is set: `device`, the innermost
56
+ `use_device` block, `set_device`, the environment variable, `"auto"`."""
57
+ if device is not None:
58
+ name = validate_device_name(device)
59
+ elif (scoped := _scoped.get()) is not None:
60
+ name = scoped
61
+ elif _process_default is not None:
62
+ name = _process_default
63
+ elif from_env := os.environ.get(ENV_VAR, "").strip():
64
+ name = validate_device_name(from_env, source=f"the environment variable {ENV_VAR}")
65
+ else:
66
+ name = AUTO
67
+ return best_available() if name == AUTO else name
68
+
69
+
70
+ def resolve_torch_device(device: str | torch.device | None = None) -> torch.device:
71
+ """The `torch.device` to use: `device`, or the library's default; and a clear error if this machine
72
+ does not have it."""
73
+ require("torch", extra="training", purpose="Resolving a torch device")
74
+ import torch
75
+
76
+ resolved = device if isinstance(device, torch.device) else torch.device(current_device(device))
77
+ problem = why_unavailable(resolved)
78
+ if problem is not None:
79
+ raise DeviceUnavailableError(
80
+ f"device {str(resolved)!r} was asked for, but {problem}", device=str(resolved)
81
+ )
82
+ return resolved
@@ -0,0 +1,21 @@
1
+ """Generic metrics, each one a `Metric` like a project's own.
2
+
3
+ Importing this package costs only the standard library; scikit-learn is imported when a metric that
4
+ uses it is computed. The `Metric` protocol and the `Evaluator` are in `torchstack64.core`.
5
+ """
6
+
7
+ from torchstack64.metrics.classification import (
8
+ AccuracyMetric,
9
+ F1Metric,
10
+ PrecisionMetric,
11
+ RecallMetric,
12
+ Thresholded,
13
+ )
14
+
15
+ __all__ = [
16
+ "AccuracyMetric",
17
+ "F1Metric",
18
+ "PrecisionMetric",
19
+ "RecallMetric",
20
+ "Thresholded",
21
+ ]
@@ -0,0 +1,93 @@
1
+ """Generic classification metrics on top of scikit-learn, imported only when a metric is computed."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ from dataclasses import dataclass
7
+ from typing import Any, Literal
8
+
9
+ from torchstack64.core import Metric, require
10
+
11
+ Average = Literal["macro", "micro", "weighted", "binary"]
12
+
13
+
14
+ def _sklearn_metrics() -> Any:
15
+ return require("sklearn.metrics", extra="metrics", purpose="The classification metrics")
16
+
17
+
18
+ @dataclass(slots=True)
19
+ class AccuracyMetric:
20
+ """The share of predictions that match: works for binary and multiclass alike."""
21
+
22
+ name: str = "accuracy"
23
+
24
+ def compute(self, y_true: Sequence, y_pred: Sequence) -> float:
25
+ return float(_sklearn_metrics().accuracy_score(y_true, y_pred))
26
+
27
+
28
+ @dataclass(slots=True)
29
+ class F1Metric:
30
+ """The harmonic mean of precision and recall, averaged over classes as `average` says."""
31
+
32
+ average: Average = "macro"
33
+ name: str = ""
34
+
35
+ def __post_init__(self) -> None:
36
+ if not self.name:
37
+ self.name = f"f1_{self.average}"
38
+
39
+ def compute(self, y_true: Sequence, y_pred: Sequence) -> float:
40
+ return float(_sklearn_metrics().f1_score(y_true, y_pred, average=self.average, zero_division=0))
41
+
42
+
43
+ @dataclass(slots=True)
44
+ class PrecisionMetric:
45
+ """Of what was predicted positive, the share that was."""
46
+
47
+ average: Average = "macro"
48
+ name: str = ""
49
+
50
+ def __post_init__(self) -> None:
51
+ if not self.name:
52
+ self.name = f"precision_{self.average}"
53
+
54
+ def compute(self, y_true: Sequence, y_pred: Sequence) -> float:
55
+ return float(
56
+ _sklearn_metrics().precision_score(y_true, y_pred, average=self.average, zero_division=0)
57
+ )
58
+
59
+
60
+ @dataclass(slots=True)
61
+ class RecallMetric:
62
+ """Of what was positive, the share that was found."""
63
+
64
+ average: Average = "macro"
65
+ name: str = ""
66
+
67
+ def __post_init__(self) -> None:
68
+ if not self.name:
69
+ self.name = f"recall_{self.average}"
70
+
71
+ def compute(self, y_true: Sequence, y_pred: Sequence) -> float:
72
+ return float(_sklearn_metrics().recall_score(y_true, y_pred, average=self.average, zero_division=0))
73
+
74
+
75
+ @dataclass(slots=True)
76
+ class Thresholded:
77
+ """Applies a label metric to scores: a score at or above `threshold` counts as the positive class.
78
+
79
+ `Thresholded(F1Metric("binary"))` measures the F1 of a model that outputs probabilities. The name
80
+ says the threshold (`"f1_binary_at_0.5"`), so two thresholds can be logged side by side.
81
+ """
82
+
83
+ metric: Metric
84
+ threshold: float = 0.5
85
+ name: str = ""
86
+
87
+ def __post_init__(self) -> None:
88
+ if not self.name:
89
+ self.name = f"{self.metric.name}_at_{self.threshold:g}"
90
+
91
+ def compute(self, y_true: Sequence, y_pred: Sequence) -> float:
92
+ labels = [int(float(score) >= self.threshold) for score in y_pred]
93
+ return self.metric.compute(y_true, labels)
torchstack64/py.typed ADDED
File without changes