torchstack64 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- torchstack64/__init__.py +101 -0
- torchstack64/artifacts/__init__.py +78 -0
- torchstack64/artifacts/bundle/__init__.py +50 -0
- torchstack64/artifacts/bundle/files.py +106 -0
- torchstack64/artifacts/bundle/folder.py +385 -0
- torchstack64/artifacts/bundle/tensors.py +75 -0
- torchstack64/artifacts/code/__init__.py +103 -0
- torchstack64/artifacts/code/copy.py +149 -0
- torchstack64/artifacts/code/importing.py +204 -0
- torchstack64/artifacts/code/inspection.py +351 -0
- torchstack64/artifacts/code/notebook.py +373 -0
- torchstack64/artifacts/code/objects.py +401 -0
- torchstack64/artifacts/loading.py +117 -0
- torchstack64/artifacts/manifest.py +220 -0
- torchstack64/artifacts/predictor/__init__.py +45 -0
- torchstack64/artifacts/predictor/bundle_predictor.py +193 -0
- torchstack64/artifacts/predictor/output_reading.py +96 -0
- torchstack64/artifacts/predictor/torch_classifier.py +106 -0
- torchstack64/artifacts/predictor/torch_predictor.py +247 -0
- torchstack64/artifacts/proofs/__init__.py +83 -0
- torchstack64/artifacts/proofs/answers.py +159 -0
- torchstack64/artifacts/proofs/example.py +248 -0
- torchstack64/artifacts/proofs/modules.py +260 -0
- torchstack64/artifacts/proofs/suite.py +560 -0
- torchstack64/artifacts/saving.py +461 -0
- torchstack64/artifacts/sources.py +166 -0
- torchstack64/callbacks/__init__.py +22 -0
- torchstack64/callbacks/base.py +43 -0
- torchstack64/callbacks/checkpointing.py +40 -0
- torchstack64/callbacks/history_plot.py +160 -0
- torchstack64/callbacks/mlflow_logger.py +217 -0
- torchstack64/callbacks/model_checks.py +295 -0
- torchstack64/callbacks/progress.py +132 -0
- torchstack64/callbacks/stack.py +85 -0
- torchstack64/core/__init__.py +59 -0
- torchstack64/core/errors.py +121 -0
- torchstack64/core/evaluation.py +52 -0
- torchstack64/core/extras.py +36 -0
- torchstack64/core/inference.py +42 -0
- torchstack64/core/labels.py +201 -0
- torchstack64/core/logging.py +110 -0
- torchstack64/data/__init__.py +10 -0
- torchstack64/data/base.py +256 -0
- torchstack64/data/labeled.py +128 -0
- torchstack64/devices/__init__.py +38 -0
- torchstack64/devices/hardware.py +43 -0
- torchstack64/devices/selection.py +82 -0
- torchstack64/metrics/__init__.py +21 -0
- torchstack64/metrics/classification.py +93 -0
- torchstack64/py.typed +0 -0
- torchstack64/training/__init__.py +83 -0
- torchstack64/training/config/__init__.py +17 -0
- torchstack64/training/config/fit.py +60 -0
- torchstack64/training/config/monitor.py +63 -0
- torchstack64/training/config/optim.py +49 -0
- torchstack64/training/config/params.py +55 -0
- torchstack64/training/config/search.py +49 -0
- torchstack64/training/results/__init__.py +19 -0
- torchstack64/training/results/fit.py +37 -0
- torchstack64/training/results/history.py +74 -0
- torchstack64/training/results/predictions.py +81 -0
- torchstack64/training/runtime/__init__.py +18 -0
- torchstack64/training/runtime/precision.py +139 -0
- torchstack64/training/runtime/randomness.py +142 -0
- torchstack64/training/runtime/runtime.py +75 -0
- torchstack64/training/runtime/transfer.py +49 -0
- torchstack64/training/runtime/weights.py +43 -0
- torchstack64/training/task/__init__.py +11 -0
- torchstack64/training/task/optim/__init__.py +9 -0
- torchstack64/training/task/optim/optimization.py +70 -0
- torchstack64/training/task/optim/schedules.py +27 -0
- torchstack64/training/task/protocol.py +58 -0
- torchstack64/training/task/supervised.py +113 -0
- torchstack64/training/trainer/__init__.py +8 -0
- torchstack64/training/trainer/adapters.py +122 -0
- torchstack64/training/trainer/contracts.py +81 -0
- torchstack64/training/trainer/hooks.py +47 -0
- torchstack64/training/trainer/meters.py +150 -0
- torchstack64/training/trainer/state.py +117 -0
- torchstack64/training/trainer/trainer.py +586 -0
- torchstack64/training/tuner/__init__.py +3 -0
- torchstack64/training/tuner/callback.py +38 -0
- torchstack64/training/tuner/space.py +82 -0
- torchstack64/training/tuner/tuner.py +137 -0
- torchstack64/utils/__init__.py +21 -0
- torchstack64/utils/logging.py +85 -0
- torchstack64/utils/mlflow.py +127 -0
- torchstack64-0.3.0.dist-info/METADATA +622 -0
- torchstack64-0.3.0.dist-info/RECORD +92 -0
- torchstack64-0.3.0.dist-info/WHEEL +5 -0
- torchstack64-0.3.0.dist-info/licenses/LICENSE +21 -0
- torchstack64-0.3.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,622 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: torchstack64
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: A small PyTorch training loop with callbacks and plots, plus the contract that packs and serves what it trains.
|
|
5
|
+
Author: José Enrico Tavares
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/joseenricotavares/torchstack64
|
|
8
|
+
Project-URL: Repository, https://github.com/joseenricotavares/torchstack64
|
|
9
|
+
Project-URL: Changelog, https://github.com/joseenricotavares/torchstack64/blob/main/CHANGELOG.md
|
|
10
|
+
Keywords: pytorch,training-loop,deep-learning,mlflow,model-serving
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.12
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Provides-Extra: training
|
|
23
|
+
Requires-Dist: torch<3,>=2.8; extra == "training"
|
|
24
|
+
Provides-Extra: metrics
|
|
25
|
+
Requires-Dist: scikit-learn<2,>=1.4; extra == "metrics"
|
|
26
|
+
Provides-Extra: mlflow
|
|
27
|
+
Requires-Dist: mlflow<4,>=3; extra == "mlflow"
|
|
28
|
+
Provides-Extra: progress
|
|
29
|
+
Requires-Dist: rich>=13; extra == "progress"
|
|
30
|
+
Provides-Extra: optuna
|
|
31
|
+
Requires-Dist: optuna>=4; extra == "optuna"
|
|
32
|
+
Provides-Extra: plots
|
|
33
|
+
Requires-Dist: matplotlib>=3.8; extra == "plots"
|
|
34
|
+
Provides-Extra: hub
|
|
35
|
+
Requires-Dist: huggingface_hub<3,>=1; extra == "hub"
|
|
36
|
+
Provides-Extra: safetensors
|
|
37
|
+
Requires-Dist: safetensors>=0.4; extra == "safetensors"
|
|
38
|
+
Provides-Extra: checks
|
|
39
|
+
Requires-Dist: torchtest2<0.2,>=0.1; extra == "checks"
|
|
40
|
+
Provides-Extra: all
|
|
41
|
+
Requires-Dist: torchstack64[checks,hub,metrics,mlflow,optuna,plots,progress,safetensors,training]; extra == "all"
|
|
42
|
+
Provides-Extra: dev
|
|
43
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
44
|
+
Requires-Dist: pytest-cov>=5; extra == "dev"
|
|
45
|
+
Requires-Dist: ruff>=0.6; extra == "dev"
|
|
46
|
+
Requires-Dist: mypy>=1.11; extra == "dev"
|
|
47
|
+
Requires-Dist: build>=1; extra == "dev"
|
|
48
|
+
Dynamic: license-file
|
|
49
|
+
|
|
50
|
+
<p align="center">
|
|
51
|
+
<img src="https://raw.githubusercontent.com/joseenricotavares/torchstack64/main/docs/logo.png" alt="A torch in an inventory slot, sixty-four of them" width="180">
|
|
52
|
+
</p>
|
|
53
|
+
|
|
54
|
+
# TorchStack64
|
|
55
|
+
|
|
56
|
+
A torch is a stick and a piece of coal, and the game hands you four at a time. Stack them to
|
|
57
|
+
sixty-four and you stop thinking about crafting them at all. This library is that stack for PyTorch
|
|
58
|
+
work: made once, carried everywhere. The training loop, the precision and memory tricks, the logging, the curves, the way a trained
|
|
59
|
+
model is packed and later served: the parts that are the same in every project, carried once, so that
|
|
60
|
+
each new model only asks for what is new about it.
|
|
61
|
+
|
|
62
|
+
It grew out of writing the same epoch loop and the same "how does this model get into an API" plumbing
|
|
63
|
+
in project after project. It is deliberately small and written to one person's taste; it is not a
|
|
64
|
+
framework that tries to cover every case.
|
|
65
|
+
|
|
66
|
+
```text
|
|
67
|
+
what you write what torchstack64 runs
|
|
68
|
+
┌──────────────────────────────┐ ┌──────────────────────────────────────────────┐
|
|
69
|
+
│ a Task: │ │ the Trainer: epochs, batches, the device, │
|
|
70
|
+
│ how a batch becomes a loss, │──►│ bf16/fp16, accumulation, clipping, the │
|
|
71
|
+
│ how it becomes predictions, │ │ scheduler, validation, the best epoch, early │
|
|
72
|
+
│ which optimizer │ │ stopping, callbacks (MLflow, progress, plots,│
|
|
73
|
+
└──────────────────────────────┘ │ EMA, checkpoints), resuming │
|
|
74
|
+
┌──────────────────────────────┐ │ │
|
|
75
|
+
│ your data, a LabeledData: │──►│ it trains on the data's batches │
|
|
76
|
+
│ raw inputs, labels, how an │ └──────────────────────┬───────────────────────┘
|
|
77
|
+
│ input is prepared, classes │ │ save_bundle(model, folder, data=val, predictor=...):
|
|
78
|
+
└──────────────┬───────────────┘ │ the trained model, and the data's
|
|
79
|
+
└─────────────────────────────────────────►│ preparation, classes and example
|
|
80
|
+
▼ proved before it exists
|
|
81
|
+
┌──────────────────────────────────────────────┐
|
|
82
|
+
│ a bundle: the network and the preparation as │
|
|
83
|
+
│ they are, the code they need, safetensors, │
|
|
84
|
+
│ what was proved and the example it answered, │
|
|
85
|
+
│ a manifest with the SHA-256 of every file │
|
|
86
|
+
└──────────────────────────────────────────────┘
|
|
87
|
+
serving: load_trusted_predictor(source), anywhere, with nothing of the training process
|
|
88
|
+
(a folder, MLflow, the Hugging Face Hub), each load checking the example again
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Words
|
|
92
|
+
|
|
93
|
+
| Word | What it is |
|
|
94
|
+
|---|---|
|
|
95
|
+
| **Task** | Your code: `configure_optimization`, `training_step`, `validation_step`. Any object with these methods; a dataclass, so its fields are recorded |
|
|
96
|
+
| **OptimConfig** | The optimizer's settings a task holds: learning rate, optimizer, weight decay, warm-up |
|
|
97
|
+
| **Step** | What a step returns: the loss, and while validating the predictions, the targets, the ids and extra `logs` |
|
|
98
|
+
| **Trainer** | Runs a task on a model. |
|
|
99
|
+
| **FitConfig** | The loop's knobs only: epochs, monitor, patience, precision, accumulation, clipping, device, seed |
|
|
100
|
+
| **Monitor** | What picks the best epoch and stops early: the validation loss, or any `Metric` |
|
|
101
|
+
| **Callback** | Code around the fit, on eight hooks: logging, progress, plots, checkpoints, model checks |
|
|
102
|
+
| **Tuner** | Runs a hyperparameter search: one fit per trial, with Optuna's values, keeping the best trial's trainer |
|
|
103
|
+
| **SearchConfig** | What a search varies (its space), in how many trials, and what prunes them |
|
|
104
|
+
| **LabeledData** | The data a network is trained on, kept with what made it: raw inputs, labels, the preparation and the label schema. It serves the trainer its batches and gives a bundle the rest |
|
|
105
|
+
| **PreparedData** | The same without labels, and the base of `LabeledData`: raw inputs and the preparation, for a network trained on its inputs alone (an autoencoder, an encoder) |
|
|
106
|
+
| **Bundle** | A folder with a `bundle.json` that names each file and records its checksum: the network and the preparation as they are, the code they need, and what was proved; the training–serving contract |
|
|
107
|
+
| **Proofs** | What `save_bundle` checks on a few validation rows before the bundle exists, and every load checks again: that the bundle answers like the model that was trained |
|
|
108
|
+
| **Predictor** | What serving calls: `predict(inputs)`, one answer per raw input. For a classifier's network, the library's own `TorchClassifier`; for an answer the schema does not derive, a `TorchPredictor` subclass of your own that writes `predict` |
|
|
109
|
+
|
|
110
|
+
## Installing
|
|
111
|
+
|
|
112
|
+
```bash
|
|
113
|
+
pip install torchstack64 # the contract only: bundles, predictors, metrics protocol
|
|
114
|
+
pip install "torchstack64[training]" # + PyTorch: the trainer
|
|
115
|
+
pip install "torchstack64[all]" # every extra
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
Extras: `training` (PyTorch), `metrics` (scikit-learn), `mlflow`, `progress` (Rich), `optuna`,
|
|
119
|
+
`plots` (matplotlib), `hub` (Hugging Face Hub), `safetensors`, `checks` (torchtest2). Each heavy dependency is
|
|
120
|
+
imported only by the code that uses it, and a missing one is reported with the `pip` line that installs it.
|
|
121
|
+
|
|
122
|
+
**On a GPU machine, install PyTorch first** from the index that
|
|
123
|
+
[pytorch.org](https://pytorch.org/get-started/locally/) gives for your system: the default wheel on
|
|
124
|
+
Windows only runs on the CPU.
|
|
125
|
+
|
|
126
|
+
## Training, in four floors
|
|
127
|
+
|
|
128
|
+
Each floor gives full control of the one below, and the one below stays reachable.
|
|
129
|
+
|
|
130
|
+
**1. One line**, for `(inputs, targets)` batches and a model that returns logits:
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
from torch import nn
|
|
134
|
+
from torchstack64 import FitConfig, Monitor, OptimConfig, SupervisedTask, Trainer, default_stack
|
|
135
|
+
from torchstack64.metrics import F1Metric
|
|
136
|
+
|
|
137
|
+
task = SupervisedTask(
|
|
138
|
+
nn.CrossEntropyLoss(),
|
|
139
|
+
optim=OptimConfig(lr=1e-3, warmup=0.1),
|
|
140
|
+
to_preds=lambda logits: logits.argmax(dim=1),
|
|
141
|
+
)
|
|
142
|
+
config = FitConfig(epochs=20, monitor=Monitor(F1Metric("macro"), mode="max"), precision="bf16")
|
|
143
|
+
result = Trainer(model, task, config, default_stack()).fit(train_loader, val_loader)
|
|
144
|
+
|
|
145
|
+
result.status, result.best_epoch, result.best_score # the model now holds the best epoch's weights
|
|
146
|
+
result.params["task.optim.lr"] # how the fit was set up, recorded with or without MLflow
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
`SupervisedTask` reads a batch by position, as a tuple, a list or a named tuple: `(inputs,)`,
|
|
150
|
+
`(inputs, targets)` or `(inputs, targets, ids)`. Two elements are always inputs and targets, so
|
|
151
|
+
`(inputs, ids)` for an unlabeled set would be read as targets. For that, and for any other shape (a dict
|
|
152
|
+
that carries its labels, extra elements), say where the parts are with `unpack`, a function from the
|
|
153
|
+
batch to `(inputs, targets, ids)`:
|
|
154
|
+
|
|
155
|
+
```python
|
|
156
|
+
SupervisedTask(nn.CrossEntropyLoss(), unpack=lambda batch: (batch[0], None, batch[1])) # (inputs, ids)
|
|
157
|
+
SupervisedTask(nn.CrossEntropyLoss(), unpack=lambda b: (b["x"], b["labels"], None)) # a dict
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
A configuration is a frozen value: an arm of an experiment is `dataclasses.replace(config, precision="fp32")`,
|
|
161
|
+
and the same trainer can run fold after fold, seed after seed, with nothing carried over between fits.
|
|
162
|
+
Every fit records how it was set up in `result.params`, flat: the `FitConfig`, the task's fields, the
|
|
163
|
+
device, the model's size. `MLflowLogger` logs the same parameters; without it they are still there.
|
|
164
|
+
|
|
165
|
+
**2. Your task**, for anything else: dict batches, several heads, a loss that changes after a warm-up.
|
|
166
|
+
The library never opens the batch; it moves it to the device and hands it to you.
|
|
167
|
+
|
|
168
|
+
```python
|
|
169
|
+
from dataclasses import dataclass
|
|
170
|
+
import torch.nn.functional as F
|
|
171
|
+
from torchstack64.training import (
|
|
172
|
+
FitPlan,
|
|
173
|
+
OptimConfig,
|
|
174
|
+
Optimization,
|
|
175
|
+
Step,
|
|
176
|
+
StepContext,
|
|
177
|
+
build_optimization,
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
@dataclass
|
|
182
|
+
class TwoHeadTask:
|
|
183
|
+
optim: OptimConfig = OptimConfig(lr=2e-5, weight_decay=0.01, warmup=0.06)
|
|
184
|
+
ratio: float = 0.5 # the first layer's rate over the last one's
|
|
185
|
+
aux_weight: float = 0.3
|
|
186
|
+
|
|
187
|
+
def configure_optimization(self, model, plan: FitPlan) -> Optimization:
|
|
188
|
+
lr, blocks = self.optim.lr, list(model.encoder.layers)
|
|
189
|
+
span = len(blocks) - 1
|
|
190
|
+
# Param groups: the first block trains at lr * ratio, the last at lr, geometrically in between.
|
|
191
|
+
# Every trainable weight must be in some group, the embeddings and the heads included.
|
|
192
|
+
groups = [{"params": list(model.encoder.embeddings.parameters()), "lr": lr * self.ratio}]
|
|
193
|
+
for i, block in enumerate(blocks):
|
|
194
|
+
rate = lr * self.ratio ** ((span - i) / max(span, 1))
|
|
195
|
+
groups.append({"params": list(block.parameters()), "lr": rate})
|
|
196
|
+
groups.append({"params": list(model.heads.parameters()), "lr": lr})
|
|
197
|
+
return build_optimization(self.optim, groups, plan)
|
|
198
|
+
|
|
199
|
+
def training_step(self, model, batch, ctx: StepContext) -> Step:
|
|
200
|
+
out = model(batch["input_ids"], batch["attention_mask"])
|
|
201
|
+
main = F.binary_cross_entropy_with_logits(out["main"], batch["label"])
|
|
202
|
+
aux = F.binary_cross_entropy_with_logits(out["aux"], batch["aux_label"])
|
|
203
|
+
return Step(loss=main + self.aux_weight * aux, logs={"main": main, "aux": aux})
|
|
204
|
+
|
|
205
|
+
def validation_step(self, model, batch, ctx: StepContext) -> Step:
|
|
206
|
+
out = model(batch["input_ids"], batch["attention_mask"])
|
|
207
|
+
return Step(
|
|
208
|
+
loss=F.binary_cross_entropy_with_logits(out["main"], batch["label"]),
|
|
209
|
+
preds={"score": out["main"].sigmoid(), "aux": out["aux"].sigmoid()},
|
|
210
|
+
targets=batch["label"],
|
|
211
|
+
ids=batch["post_id"],
|
|
212
|
+
)
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
A task's hyperparameters are its dataclass fields, and its methods hold no number of their own: the fit
|
|
216
|
+
records the fields in `result.params`, and `dataclasses.replace(task, ratio=0.25)` is another arm.
|
|
217
|
+
`OptimConfig` and `build_optimization` cover one optimizer with a warm-up; a task that needs another
|
|
218
|
+
schedule builds it in `configure_optimization`, from fields of its own. A task that is not a dataclass
|
|
219
|
+
still runs, with a warning that its settings go unrecorded.
|
|
220
|
+
|
|
221
|
+
**3. The whole epoch**: a task with `train_epoch(trainer, loader)` runs the epoch itself, and the trainer
|
|
222
|
+
still validates, keeps the best epoch, stops early and calls the callbacks. `trainer.runtime` gives
|
|
223
|
+
`autocast()`, `backward()` and `to_device()`; `trainer.optimization_step(loss)` clips, steps and schedules.
|
|
224
|
+
|
|
225
|
+
**4. Your own loop**, with the same primitives:
|
|
226
|
+
|
|
227
|
+
```python
|
|
228
|
+
from torchstack64.training import Runtime, seed_everything
|
|
229
|
+
|
|
230
|
+
runtime = Runtime(precision="bf16") # the library's default device
|
|
231
|
+
seed_everything(13)
|
|
232
|
+
for batch in loader:
|
|
233
|
+
batch = runtime.to_device(batch)
|
|
234
|
+
with runtime.autocast():
|
|
235
|
+
loss = my_loss(model, batch)
|
|
236
|
+
runtime.backward(loss)
|
|
237
|
+
runtime.clip(model.parameters(), max_norm=1.0, optimizer=optimizer)
|
|
238
|
+
runtime.step(optimizer)
|
|
239
|
+
optimizer.zero_grad(set_to_none=True)
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
## One device setting for everything
|
|
243
|
+
|
|
244
|
+
Every part of the library that places tensors (training, evaluation, prediction, loading a model to
|
|
245
|
+
serve) asks the same place when it is not given a device:
|
|
246
|
+
|
|
247
|
+
```python
|
|
248
|
+
import torchstack64
|
|
249
|
+
|
|
250
|
+
torchstack64.current_device() # "cuda:0" here, "mps" on a Mac, "cpu" elsewhere: "auto" resolved
|
|
251
|
+
torchstack64.set_device("cuda:1") # the default for the whole process
|
|
252
|
+
with torchstack64.use_device("cpu"): # just this block
|
|
253
|
+
predictor = DigitsPredictor.load("artifacts/digits")
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
The environment variable `TORCHSTACK64_DEVICE=cpu` does the same without touching code. An explicit name
|
|
257
|
+
is a request: `"cuda"` on a machine without CUDA fails loudly instead of training on the CPU for hours.
|
|
258
|
+
|
|
259
|
+
## Callbacks
|
|
260
|
+
|
|
261
|
+
`default_stack()` gives what only watches the fit: a Rich progress panel, the training curves, and MLflow
|
|
262
|
+
logging (silent unless a run is active). What writes files stays off until asked for:
|
|
263
|
+
`checkpointing=folder` (resumed with `fit(..., resume_from=...)`).
|
|
264
|
+
`mlflow=` also takes the callback already configured:
|
|
265
|
+
|
|
266
|
+
```python
|
|
267
|
+
from functools import partial
|
|
268
|
+
|
|
269
|
+
from torchstack64 import TorchClassifier, save_bundle
|
|
270
|
+
from torchstack64.callbacks import MLflowLogger, default_stack
|
|
271
|
+
|
|
272
|
+
# val is the validation LabeledData (see "Packing and serving"): every fit logs its bundle, proved
|
|
273
|
+
logger = MLflowLogger(bundle=partial(save_bundle, data=val, predictor=TorchClassifier))
|
|
274
|
+
stack = default_stack(mlflow=logger)
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
`checks=True` adds `ModelChecks` (the `checks` extra): before the first step of every fit, it runs
|
|
278
|
+
[torchtest2](https://github.com/Hrehory/torchtest2)'s checks on the first batch the trainer draws, and finds what
|
|
279
|
+
keeps a network from learning while it still costs a fraction of a second. A layer that gets no gradient (never
|
|
280
|
+
called, or behind a `.detach()`), parameters the optimizer leaves out, a sample that leaks into the others, dropout
|
|
281
|
+
left on in evaluation, a network that cannot learn even one batch:
|
|
282
|
+
|
|
283
|
+
```python
|
|
284
|
+
from torchstack64.callbacks import ModelChecks
|
|
285
|
+
|
|
286
|
+
trainer = Trainer(model, task, config, default_stack(checks=True)) # or [..., ModelChecks(stop=True)]
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
A healthy network shows nothing. Problems are one warning, a line each, before the progress panel:
|
|
290
|
+
|
|
291
|
+
```text
|
|
292
|
+
WARNING torchstack64.callbacks.model_checks: model checks found 2 failures and 1 warning in 0.07 s (the whole report is in this callback's `report`):
|
|
293
|
+
FAIL gradient_flow: 2/4 trainable parameter(s) get no gradient from the loss_fn (...): encoder.0.weight, encoder.0.bias
|
|
294
|
+
FAIL params_change: 2/4 trainable parameter(s) did not change after an optimizer step: encoder.0.weight, encoder.0.bias
|
|
295
|
+
WARN overfit_batch: the loss decreased (0.6817 -> best 0.1728, 25% of the initial value) but did not reach 10% (...)
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
It needs nothing from you and works with any task, through the task's own `training_step` and `validation_step`.
|
|
299
|
+
The fit is the same fit, with or without it; a resumed fit is not checked again, and in a search a problem already
|
|
300
|
+
reported is not repeated. `stop=True` ends the fit on a failure; `skip=` leaves checks out by name. The checks
|
|
301
|
+
never break a fit: if torchtest2 itself fails, the fit goes on with a warning. They look at the training set-up when it starts;
|
|
302
|
+
the bundle proofs look at the served model when it is saved.
|
|
303
|
+
|
|
304
|
+
Writing your own is subclassing `Callback` and overriding the hooks you need:
|
|
305
|
+
|
|
306
|
+
```python
|
|
307
|
+
from torchstack64.callbacks import Callback
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
class StopAfterMinutes(Callback):
|
|
311
|
+
def __init__(self, minutes: float) -> None:
|
|
312
|
+
self.minutes = minutes
|
|
313
|
+
|
|
314
|
+
def on_epoch_end(self, trainer, result) -> None:
|
|
315
|
+
if sum(trainer.history.column("seconds")) > 60 * self.minutes:
|
|
316
|
+
trainer.request_stop(f"time budget of {self.minutes} minutes")
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
## Searching hyperparameters
|
|
320
|
+
|
|
321
|
+
`Tuner` runs a search with the pieces a fit already has. It takes what `Trainer` takes, except that the
|
|
322
|
+
network comes as its class, or as a function that builds one, since each trial needs new weights; a
|
|
323
|
+
`SearchConfig` says what varies, and in how many fits:
|
|
324
|
+
|
|
325
|
+
```python
|
|
326
|
+
from optuna.distributions import FloatDistribution
|
|
327
|
+
from torchstack64 import SearchConfig, Tuner
|
|
328
|
+
|
|
329
|
+
search = SearchConfig(
|
|
330
|
+
space={
|
|
331
|
+
"model.hidden": [64, 128, 256], # an argument of MyNet(hidden=...): options
|
|
332
|
+
"task.optim.lr": FloatDistribution(1e-4, 1e-2, log=True), # a field of the task: a range
|
|
333
|
+
"fit.clip_grad_norm": [None, 1.0], # a field of the FitConfig
|
|
334
|
+
},
|
|
335
|
+
n_trials=20,
|
|
336
|
+
)
|
|
337
|
+
tuner = Tuner(MyNet, task, config, search) # the class itself, not MyNet(...)
|
|
338
|
+
tuner.search(train_loader, val_loader)
|
|
339
|
+
|
|
340
|
+
tuner.best_trainer.model # the best trial's network, with the weights of its best epoch
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
The names are the ones every fit records in `result.params`, and `model.<argument>` for what `MyNet`
|
|
344
|
+
takes (or what a function that builds the network takes), so a task of your own is searched like `SupervisedTask`. A wrong name, or a range whose ends the
|
|
345
|
+
configuration refuses, fails when the tuner is made, before anything trains. Optuna proposes the values and gives
|
|
346
|
+
up a trial that is already worse than the others at the same epoch; `config.seed` makes the same search give
|
|
347
|
+
the same trials.
|
|
348
|
+
|
|
349
|
+
**The best trial is a finished fit**: `best_trainer` evaluates, predicts and goes to `save_bundle` like any
|
|
350
|
+
trainer, and training again with its values gives the same weights. Train again when something changes, such
|
|
351
|
+
as more epochs than the search could afford:
|
|
352
|
+
|
|
353
|
+
```python
|
|
354
|
+
longer = {**tuner.study.best_params, "fit.epochs": 60}
|
|
355
|
+
final = tuner.build_trainer(longer, callbacks=default_stack())
|
|
356
|
+
final.fit(train_loader, val_loader)
|
|
357
|
+
```
|
|
358
|
+
|
|
359
|
+
**What the search found** is in `tuner.study`, Optuna's own study: `trials_dataframe()` has a row per trial,
|
|
360
|
+
with its values, its score and how its fit ended, and Optuna's importances and plots read it. It is there after
|
|
361
|
+
the stop button too, and `tuner.search(train_loader, val_loader, study=tuner.study)` goes on from it. A study of
|
|
362
|
+
your own, kept on disk or with another sampler, goes in the same way.
|
|
363
|
+
|
|
364
|
+
**Callbacks** given to the tuner run in every trial: the ones that change a fit, and the one that records it.
|
|
365
|
+
The tuner itself knows no tracker. For MLflow, open a run and give it the logger, as for a fit:
|
|
366
|
+
|
|
367
|
+
```python
|
|
368
|
+
import mlflow
|
|
369
|
+
from torchstack64.callbacks import MLflowLogger, training_curves
|
|
370
|
+
from torchstack64.utils import child_runs
|
|
371
|
+
|
|
372
|
+
tuner = Tuner(MyNet, task, config, search, [MLflowLogger()])
|
|
373
|
+
with mlflow.start_run(run_name="search") as run:
|
|
374
|
+
tuner.search(train_loader, val_loader)
|
|
375
|
+
|
|
376
|
+
child_runs(run) # one row per trial, each a run of its own nested under this one
|
|
377
|
+
training_curves(tuner.best_trainer.history) # the curves of the best trial alone
|
|
378
|
+
```
|
|
379
|
+
|
|
380
|
+
The logger keeps parameters, curves and predictions, not weights. Save the best network once, at the end, with
|
|
381
|
+
`save_bundle`; `mlflow.log_artifacts(folder, artifact_path="model", run_id=run.info.run_id)` puts that bundle in
|
|
382
|
+
the search's run, where `load_trusted_predictor(f"runs:/{run.info.run_id}/model")` reads it.
|
|
383
|
+
|
|
384
|
+
A search whose space changes from trial to trial, or whose trial is several fits (folds), is an Optuna objective
|
|
385
|
+
of your own around `Trainer`.
|
|
386
|
+
|
|
387
|
+
## Shortcuts for MLflow
|
|
388
|
+
|
|
389
|
+
`torchstack64.utils` does the setup a notebook would otherwise write by hand, and hands back MLflow's own
|
|
390
|
+
objects, so what comes after is plain MLflow:
|
|
391
|
+
|
|
392
|
+
```python
|
|
393
|
+
from dataclasses import replace
|
|
394
|
+
|
|
395
|
+
import mlflow
|
|
396
|
+
from torchstack64 import load_trusted_predictor
|
|
397
|
+
from torchstack64.utils import best_run, child_runs, local_experiment
|
|
398
|
+
|
|
399
|
+
local_experiment("my-project", "outputs") # outputs/mlflow.db, the artifacts in outputs/mlartifacts
|
|
400
|
+
|
|
401
|
+
with mlflow.start_run(run_name="arms") as arms:
|
|
402
|
+
for lr in (1e-3, 3e-3):
|
|
403
|
+
with mlflow.start_run(run_name=f"lr={lr:g}", nested=True):
|
|
404
|
+
arm = replace(task, optim=OptimConfig(lr=lr))
|
|
405
|
+
Trainer(build_model(), arm, config, [logger]).fit(train_loader, val_loader)
|
|
406
|
+
|
|
407
|
+
child_runs(arms) # one row per arm: its parameters, metrics and status
|
|
408
|
+
best = best_run(arms, config.monitor) # the best arm's run; its bundle, since this logger writes one:
|
|
409
|
+
predictor = load_trusted_predictor(f"runs:/{best.info.run_id}/model")
|
|
410
|
+
```
|
|
411
|
+
|
|
412
|
+
`best_run` leaves out the fits that failed, were interrupted or were pruned. `local_experiment` warns when the
|
|
413
|
+
experiment keeps its artifacts somewhere else, as after its folder was moved.
|
|
414
|
+
|
|
415
|
+
## Packing and serving
|
|
416
|
+
|
|
417
|
+
A bundle needs two things, and training already has both: the trained model, and the validation data it
|
|
418
|
+
was trained on. The data is a `LabeledData`: the raw inputs, their labels, the preparation (how a raw input
|
|
419
|
+
becomes what the network receives) and the label schema (the classes, in the order of the network's
|
|
420
|
+
columns). It prepares every input once, gives the trainer its batches, and later gives the bundle the
|
|
421
|
+
preparation, the classes and the rows it is proved on, so nothing is declared twice:
|
|
422
|
+
|
|
423
|
+
```python
|
|
424
|
+
import numpy as np
|
|
425
|
+
import torch
|
|
426
|
+
from torch import nn
|
|
427
|
+
|
|
428
|
+
from torchstack64 import (
|
|
429
|
+
FitConfig,
|
|
430
|
+
LabeledData,
|
|
431
|
+
LabelSchema,
|
|
432
|
+
SupervisedTask,
|
|
433
|
+
TorchClassifier,
|
|
434
|
+
Trainer,
|
|
435
|
+
save_bundle,
|
|
436
|
+
)
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def mlp(hidden=32):
|
|
440
|
+
return nn.Sequential(nn.Linear(64, hidden), nn.ReLU(), nn.Linear(hidden, 10))
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def to_network(images): # raw inputs, 8 x 8 of 0 to 16, to what the network receives: 64 numbers of 0 to 1
|
|
444
|
+
return torch.as_tensor(np.asarray(images, dtype=np.float32).reshape(len(images), 64) / 16.0)
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
data = LabeledData(digits.images, digits.target, prepare=to_network, schema=LabelSchema.of(range(10)))
|
|
448
|
+
train, val = data[train_idx], data[val_idx] # a subset: nothing is prepared again
|
|
449
|
+
|
|
450
|
+
model = mlp(hidden=32)
|
|
451
|
+
task = SupervisedTask(nn.CrossEntropyLoss())
|
|
452
|
+
Trainer(model, task, FitConfig(epochs=15)).fit(
|
|
453
|
+
train.loader(batch_size=64, shuffle=True), val.loader(batch_size=256)
|
|
454
|
+
)
|
|
455
|
+
|
|
456
|
+
bundle = save_bundle(
|
|
457
|
+
model, "artifacts/digits", data=val, predictor=TorchClassifier, metrics={"val_f1_macro": best}
|
|
458
|
+
)
|
|
459
|
+
bundle.proofs.passed # ('determinism', 'preparation', 'round_trip', 'outputs', 'batch', 'contract', 'labels')
|
|
460
|
+
```
|
|
461
|
+
|
|
462
|
+
**What the bundle keeps.** The network and the preparation travel as they are: objects, written with
|
|
463
|
+
PyTorch's own serialization, with the code they need beside them.
|
|
464
|
+
|
|
465
|
+
| File | What it is |
|
|
466
|
+
|---|---|
|
|
467
|
+
| `network.pt` | the network's structure (its layers, a dropout's rate, a temperature set after training), every weight left empty |
|
|
468
|
+
| `weights.safetensors` | every weight and buffer, by name: reading them never runs code |
|
|
469
|
+
| `prepare.pt` | the preparation, with what it learned: a vocabulary, a scaler's mean, a tokenizer |
|
|
470
|
+
| `reading.json` | how a classifier's outputs are read: as logits or as probabilities (a classifier's bundle only) |
|
|
471
|
+
| `code/` | the classes and functions the network and the preparation are made of, when they are the project's: a module written from the notebook's cells, or the project's package as it is on disk |
|
|
472
|
+
| `proofs/example.json` | the rows the bundle was proved on, and what it answered |
|
|
473
|
+
| `bundle.json` | the manifest: the classes, the predictor that reads the bundle, the packages to install (`requires`), what was proved, and the SHA-256 of every file |
|
|
474
|
+
|
|
475
|
+
The function that made the network is not needed: the network carries its own structure. A preparation that
|
|
476
|
+
learned something keeps it inside, `functools.partial(encode, vocabulary=vocabulary)`, or a tokenizer
|
|
477
|
+
object: a value built at run time and read as a global by the code would be what this process holds and
|
|
478
|
+
the bundle does not, so it is refused when the bundle is saved, with the way to pass it.
|
|
479
|
+
|
|
480
|
+
The outputs are read as logits, as a network trained with `CrossEntropyLoss` or `BCEWithLogitsLoss` answers
|
|
481
|
+
them: a softmax over one column per class, a sigmoid over the one column of a binary network. A network
|
|
482
|
+
that ends in a softmax or a sigmoid is saved with `outputs="probabilities"`; without it, the save refuses
|
|
483
|
+
the bundle, because the outputs on the example already look like probabilities, and it refuses the
|
|
484
|
+
opposite mistake too (`outputs="probabilities"` on a network that answers logits), saying which row is not
|
|
485
|
+
one of probabilities. The log line of the save says how the outputs were read and whether `outputs=` said
|
|
486
|
+
so (`outputs read as logits (the default)`). The bundle is read by the library's own `TorchClassifier`,
|
|
487
|
+
whose `predict` and `predict_proba` are derived from the outputs, the schema and its threshold. The class
|
|
488
|
+
that serves the bundle is always said, `predictor=TorchClassifier` here: a network is not assumed to be a
|
|
489
|
+
classifier, so a save without `predictor=` is refused, with the three classes it can be.
|
|
490
|
+
|
|
491
|
+
**`save_bundle` proves the bundle before it exists**, on 32 rows drawn from the data with a fixed seed. The
|
|
492
|
+
bundle is written in a staging folder, read back from there the way a service reads it, and proved
|
|
493
|
+
against the trained model; only then is it moved into place. A proof that fails leaves no bundle, and the
|
|
494
|
+
one already in the folder untouched, and its `ProofError` names the proof, the first example that differs
|
|
495
|
+
and by how much:
|
|
496
|
+
|
|
497
|
+
| Proof | What it refuses |
|
|
498
|
+
|---|---|
|
|
499
|
+
| `determinism` | something random left on when serving (`F.dropout` without `training=self.training`) |
|
|
500
|
+
| `preparation` | a preparation that, read back from the bundle, prepares differently: its state did not travel |
|
|
501
|
+
| `round_trip` | a network that, read back, answers differently: something it computes with did not travel |
|
|
502
|
+
| `outputs` | outputs that do not fit the reading: a softmax or a sigmoid read twice, the wrong number of columns |
|
|
503
|
+
| `answers` | for a model of its own class, what the trained model answers (its `trained_predict`) against the bundle |
|
|
504
|
+
| `batch` | an answer that depends on the rest of the call: a mask that does not reach the network, padding on the side it reads, a BatchNorm in training mode, a scaler fitted on each request |
|
|
505
|
+
| `contract` | one answer per input, labels in the schema, a row of probabilities per input that sums to 1 |
|
|
506
|
+
| `labels` | classes in another order than training encoded them |
|
|
507
|
+
| `units` | a regression that answers in the units its loss saw, not the labels' |
|
|
508
|
+
|
|
509
|
+
Two mistakes the proofs used to catch cannot happen any more. The preparation and the classes are given
|
|
510
|
+
once, to the data training uses: there is no second copy of them to disagree. Whoever prepared the data
|
|
511
|
+
another way says what training fed (`LabeledData(..., prepared=X)`, or `targets=`), and a preparation or a
|
|
512
|
+
schema that does not reproduce it is refused when the data is made, before any training.
|
|
513
|
+
|
|
514
|
+
**Serving.** The bundle is read anywhere, with nothing but the bundle and the packages its manifest lists.
|
|
515
|
+
Who brings the code decides the call:
|
|
516
|
+
|
|
517
|
+
| Who brings the code | How the bundle is loaded |
|
|
518
|
+
|---|---|
|
|
519
|
+
| the bundle, and you trust where it came from | `load_trusted_predictor(folder)` |
|
|
520
|
+
| you (the service), for a network | `TorchClassifier.load(folder, network=..., prepare=...)`, or your own subclass |
|
|
521
|
+
| you, for a model that is not a network | `MyPredictor.load(folder)` |
|
|
522
|
+
| you, with any other way to run the model | `ArtifactBundle.read(folder, verify=True)`, build the predictor, and `check_example(predictor, bundle)` |
|
|
523
|
+
|
|
524
|
+
```python
|
|
525
|
+
from torchstack64 import load_trusted_predictor
|
|
526
|
+
|
|
527
|
+
predictor = load_trusted_predictor("artifacts/digits") # a folder
|
|
528
|
+
predictor = load_trusted_predictor("hf://me/my-model@v0.1.0") # the Hub, at a pinned revision
|
|
529
|
+
predictor = load_trusted_predictor("runs:/<run id>/model") # an MLflow run
|
|
530
|
+
predictor.predict(images) # [3, 7, 1, ...]
|
|
531
|
+
```
|
|
532
|
+
|
|
533
|
+
`load_trusted_predictor` runs the bundle's code, as importing a module does, so it is for a bundle from a
|
|
534
|
+
source you trust; it happens only after every file matched its checksum and every package in `requires` was
|
|
535
|
+
found installed (a missing one is refused with its `pip` line). A service that does not trust the bundle
|
|
536
|
+
brings the code itself:
|
|
537
|
+
|
|
538
|
+
```python
|
|
539
|
+
from torchstack64 import TorchClassifier
|
|
540
|
+
from digits_mlp.model import mlp # the service's own code, installed in it
|
|
541
|
+
from digits_mlp.preparation import to_network
|
|
542
|
+
|
|
543
|
+
predictor = TorchClassifier.load("artifacts/digits", network=mlp(128), prepare=to_network)
|
|
544
|
+
```
|
|
545
|
+
|
|
546
|
+
The bundle's weights go in the network the service built, which must have the same tensor names and shapes
|
|
547
|
+
(a network that does not fit is refused, naming what differs); nothing the bundle carries as code is read.
|
|
548
|
+
If the preparation learned something in training (a vocabulary, a scaler), it has to be the same one.
|
|
549
|
+
**Every load answers the example again** and compares, whoever brought the code: a service whose code, a
|
|
550
|
+
dependency or the device changed since the save (a later version of its network, say) is refused when it
|
|
551
|
+
starts, before it answers anyone.
|
|
552
|
+
|
|
553
|
+
**A class of your own** is written only for an answer the schema does not derive, such as the rule of an
|
|
554
|
+
ordinal scale, and given as `predictor=` in place of `TorchClassifier`: a subclass of `TorchPredictor` (the
|
|
555
|
+
base `TorchClassifier` is built on, and which answers nothing itself) writes `predict` (and
|
|
556
|
+
`predict_proba`), with `self.network`, `self.prepare`, `self.label_schema` and `self.forward` at hand, and
|
|
557
|
+
travels in the bundle: `save_bundle(model, folder, data=val, predictor=Stars)`. A model the library does not run itself
|
|
558
|
+
(scikit-learn, LightGBM) has a `BundlePredictor` subclass: `pack(model)` returns what goes in the bundle by
|
|
559
|
+
logical name (a state dict becomes safetensors, a `dict` JSON, a `str` text, a `Path` a copy),
|
|
560
|
+
`unpack(bundle, device)` builds the predictor back, `predict` answers, and `trained_predict(model, rows)`
|
|
561
|
+
says what the trained model answers, which the save proves the bundle against (a PyTorch network needs
|
|
562
|
+
none: the library runs it itself). `save_bundle(model, folder, data=val, predictor=MyPredictor)` writes it,
|
|
563
|
+
and `MyPredictor.load(folder)` reads it with the class at hand, with nothing to trust.
|
|
564
|
+
|
|
565
|
+
**Data without labels.** A network trained on its inputs alone (an autoencoder, a contrastive encoder, a
|
|
566
|
+
masked language model) takes a `PreparedData`, the base of `LabeledData`: the raw inputs and the
|
|
567
|
+
preparation, prepared once, in batches of `(prepared,)`. The task makes what the loss compares out of the
|
|
568
|
+
inputs; for an autoencoder, `SupervisedTask(nn.MSELoss(), unpack=lambda batch: (batch[0], batch[0], None))`.
|
|
569
|
+
With no classes, a `TorchPredictor` subclass writes what the bundle answers (an embedding, a reconstruction
|
|
570
|
+
error), and the proofs that compare labels say they did not run:
|
|
571
|
+
|
|
572
|
+
```python
|
|
573
|
+
data = PreparedData(images, prepare=to_network)
|
|
574
|
+
train, val = data[train_idx], data[val_idx]
|
|
575
|
+
Trainer(model, task, FitConfig(epochs=15)).fit(
|
|
576
|
+
train.loader(batch_size=64, shuffle=True), val.loader(batch_size=256)
|
|
577
|
+
)
|
|
578
|
+
save_bundle(model, "artifacts/autoencoder", data=val, predictor=ReconstructionError)
|
|
579
|
+
```
|
|
580
|
+
|
|
581
|
+
Every way out is written, kept in the bundle and repeated in the log: `batch_dependent=True` says an answer
|
|
582
|
+
depends on its call on purpose; `load_trusted_predictor(..., check_example=False)` skips the check of one load.
|
|
583
|
+
|
|
584
|
+
Everything works the same in a notebook: the classes and functions of the cells that the network and the
|
|
585
|
+
preparation are made of are written as a module of the bundle, with what they take from the other cells.
|
|
586
|
+
What has no code to write (a lambda, a function made inside another, a value built at run time and read as
|
|
587
|
+
a global) is refused by name when the bundle is saved.
|
|
588
|
+
|
|
589
|
+
To see that a bundle is enough on its own, load it where neither the training process nor your project's
|
|
590
|
+
files are: a new interpreter, started with `python -P` from an empty folder, in an environment that has
|
|
591
|
+
`torchstack64` but not your project (an editable install of the project would make it importable there and
|
|
592
|
+
hide what the bundle lacks). `load_trusted_predictor(folder)` there answers the bundle's own example, and a
|
|
593
|
+
module left out of the bundle, or a value the training process holds and the bundle does not, fails there
|
|
594
|
+
instead of in the service.
|
|
595
|
+
|
|
596
|
+
## Logging
|
|
597
|
+
|
|
598
|
+
The library logs through the standard `logging` module under the `torchstack64` logger, and everything it
|
|
599
|
+
warns about is one of those records. With nothing configured, as in a notebook or a plain script,
|
|
600
|
+
warnings and errors appear on stderr with their level and logger. Once an application configures
|
|
601
|
+
logging, before or after importing the library, its own handlers receive every record and the library's
|
|
602
|
+
stays silent. The root logger is never touched.
|
|
603
|
+
|
|
604
|
+
`TORCHSTACK64_LOG_LEVEL=INFO` shows each fit's start and end without touching code, and `DEBUG` every
|
|
605
|
+
epoch. From a notebook:
|
|
606
|
+
|
|
607
|
+
```python
|
|
608
|
+
import sys
|
|
609
|
+
|
|
610
|
+
import torchstack64.utils
|
|
611
|
+
|
|
612
|
+
torchstack64.utils.set_verbosity("INFO") # the same, from code
|
|
613
|
+
|
|
614
|
+
with torchstack64.utils.quiet(): # a loop of fits: only warnings and errors inside the block
|
|
615
|
+
...
|
|
616
|
+
|
|
617
|
+
torchstack64.utils.enable_console("INFO", stream=sys.stdout) # another stream, or another format
|
|
618
|
+
torchstack64.utils.disable_console() # undoes it, the level included
|
|
619
|
+
```
|
|
620
|
+
|
|
621
|
+
A warning about the setup, which every fit of a loop would repeat (a task that is not a dataclass, a
|
|
622
|
+
loader with no `len()`), is given once per process.
|