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,295 @@
|
|
|
1
|
+
"""`ModelChecks`: torchtest2's checks on the first batch of a fit, before its first step.
|
|
2
|
+
|
|
3
|
+
They find what keeps a network from learning while it still costs a fraction of a second: a layer that gets
|
|
4
|
+
no gradient (never called, or behind a `.detach()`), parameters the optimizer leaves out, a sample that leaks
|
|
5
|
+
into the others, dropout that stays on in evaluation, a network that cannot learn even one batch. The bundle
|
|
6
|
+
proofs check the served model when it is saved; these check the training set-up when the fit begins, before
|
|
7
|
+
the fit is spent.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import dataclasses
|
|
13
|
+
import logging
|
|
14
|
+
import time
|
|
15
|
+
from collections.abc import Iterable, Iterator, Mapping
|
|
16
|
+
from contextlib import contextmanager
|
|
17
|
+
from typing import TYPE_CHECKING, Any
|
|
18
|
+
|
|
19
|
+
from torchstack64.callbacks.base import Callback
|
|
20
|
+
from torchstack64.core import require
|
|
21
|
+
|
|
22
|
+
if TYPE_CHECKING:
|
|
23
|
+
from torchstack64.training.trainer import StepContext, Trainer
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
_PROBLEMS = ("WARN", "FAIL")
|
|
28
|
+
_SET_BY_THE_CALLBACK = frozenset(
|
|
29
|
+
{"model", "inputs", "targets", "loss_fn", "optimizer", "forward_fn", "eval_forward_fn", "verbose"}
|
|
30
|
+
)
|
|
31
|
+
_COVERAGE_HINT = " Was the optimizer created before these layers were added/replaced?"
|
|
32
|
+
# Tasks currently do not provide the info required for these checks:
|
|
33
|
+
_LEFT_OUT = ("input_dependency", "initial_loss")
|
|
34
|
+
_WITHOUT_PREDICTIONS = (
|
|
35
|
+
"left out: output_varies and batch_independence, because the task's validation_step returns no "
|
|
36
|
+
"predictions: its loss stood in for the outputs"
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class ModelChecks(Callback):
|
|
41
|
+
"""Runs torchtest2's checks once per fit, on the first training batch, and says only what is wrong.
|
|
42
|
+
|
|
43
|
+
A healthy network shows nothing: the summary is an INFO record of the library's log, hidden unless you
|
|
44
|
+
raise the verbosity. Problems are one WARNING record, a line per check that warned or failed, before the
|
|
45
|
+
first step. The whole report stays in `report` (a torchtest2 `Report`: `report.ok`, `report.failures`,
|
|
46
|
+
`report.to_dict()`).
|
|
47
|
+
|
|
48
|
+
It works with any task, through the task's own `training_step` and `validation_step`: the batch goes to
|
|
49
|
+
them whole, as the trainer drew it, and nothing else is asked of the task. `input_dependency` and
|
|
50
|
+
`initial_loss` are always left out, since a task says neither which part of a batch is the input nor
|
|
51
|
+
which loss the network's raw output feeds. A task with `train_epoch` passes no batch through the trainer,
|
|
52
|
+
and is not checked.
|
|
53
|
+
|
|
54
|
+
- `rows`: the batch is cut to its first `rows` samples, at least 2, which the batch checks need.
|
|
55
|
+
- `skip`: names of checks to leave out (`torchtest2.CHECKS`).
|
|
56
|
+
- `stop=True`: a failed check asks the fit to stop, with the names of the failures as the reason.
|
|
57
|
+
- `overfit_steps`: the steps `overfit_batch` may take, the slowest check; `0` leaves it out.
|
|
58
|
+
- Any other keyword goes to `torchtest2.check_model` as is: `output_shape=`, `output_range=`, `frozen=`...
|
|
59
|
+
|
|
60
|
+
It runs again in every fit and every trial of a search; a fit whose problems were all reported before, by
|
|
61
|
+
this callback, is an INFO record instead of a warning. A resumed fit is not checked again. If torchtest2
|
|
62
|
+
itself fails, the fit goes on with a warning: the checks never break a training run.
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
def __init__(
|
|
66
|
+
self,
|
|
67
|
+
*,
|
|
68
|
+
rows: int = 32,
|
|
69
|
+
skip: Iterable[str] = (),
|
|
70
|
+
stop: bool = False,
|
|
71
|
+
overfit_steps: int = 200,
|
|
72
|
+
**options: Any,
|
|
73
|
+
) -> None:
|
|
74
|
+
torchtest2 = require("torchtest2", extra="checks", purpose="ModelChecks")
|
|
75
|
+
if isinstance(rows, bool) or not isinstance(rows, int) or rows < 2:
|
|
76
|
+
raise ValueError(
|
|
77
|
+
f"rows is a number of samples, at least 2 (the batch checks compare two); got {rows!r}"
|
|
78
|
+
)
|
|
79
|
+
if isinstance(skip, str):
|
|
80
|
+
raise TypeError(f"skip takes names of checks, as a tuple: skip=({skip!r},)")
|
|
81
|
+
skipped = tuple(skip)
|
|
82
|
+
unknown = [name for name in skipped if name not in torchtest2.CHECKS]
|
|
83
|
+
if unknown:
|
|
84
|
+
raise ValueError(
|
|
85
|
+
f"no check named {', '.join(map(repr, unknown))}; the checks are {list(torchtest2.CHECKS)}"
|
|
86
|
+
)
|
|
87
|
+
if not isinstance(stop, bool):
|
|
88
|
+
raise TypeError(f"stop is True or False; got {stop!r}")
|
|
89
|
+
if isinstance(overfit_steps, bool) or not isinstance(overfit_steps, int) or overfit_steps < 0:
|
|
90
|
+
raise ValueError(f"overfit_steps is a number of steps, 0 or more; got {overfit_steps!r}")
|
|
91
|
+
reserved = sorted(set(options) & _SET_BY_THE_CALLBACK)
|
|
92
|
+
if reserved:
|
|
93
|
+
raise TypeError(
|
|
94
|
+
f"ModelChecks sets {', '.join(reserved)} itself, from the trainer and its task; "
|
|
95
|
+
"the other options of torchtest2.check_model are passed on"
|
|
96
|
+
)
|
|
97
|
+
self.rows = rows
|
|
98
|
+
self.skip = skipped
|
|
99
|
+
self.stop = stop
|
|
100
|
+
self.overfit_steps = overfit_steps
|
|
101
|
+
self.options = options
|
|
102
|
+
self.report: Any = None
|
|
103
|
+
self.seconds: float | None = None
|
|
104
|
+
self._pending = False
|
|
105
|
+
self._without_predictions = False
|
|
106
|
+
self._reported: set[tuple[str, str]] = set() # each problem is warned about once per callback
|
|
107
|
+
self._fits_with_problems = 0
|
|
108
|
+
|
|
109
|
+
def __repr__(self) -> str:
|
|
110
|
+
return f"ModelChecks(rows={self.rows}, skip={self.skip}, stop={self.stop})"
|
|
111
|
+
|
|
112
|
+
def on_train_begin(self, trainer: Trainer[Any]) -> None:
|
|
113
|
+
self.report, self.seconds, self._pending = None, None, False
|
|
114
|
+
if callable(getattr(trainer.task, "train_epoch", None)):
|
|
115
|
+
logger.info(
|
|
116
|
+
"model checks skipped: the task runs its own epoch (train_epoch), "
|
|
117
|
+
"so no batch passes through the trainer"
|
|
118
|
+
)
|
|
119
|
+
return
|
|
120
|
+
if trainer.state.epoch > 0:
|
|
121
|
+
logger.info(
|
|
122
|
+
"model checks skipped: the fit resumes after epoch %d, "
|
|
123
|
+
"and its set-up was checked when it began",
|
|
124
|
+
trainer.state.epoch,
|
|
125
|
+
)
|
|
126
|
+
return
|
|
127
|
+
self._pending = True
|
|
128
|
+
|
|
129
|
+
def on_train_batch_begin(self, trainer: Trainer[Any], batch: Any, ctx: StepContext) -> None:
|
|
130
|
+
if not self._pending:
|
|
131
|
+
return
|
|
132
|
+
self._pending = False
|
|
133
|
+
import torchtest2
|
|
134
|
+
|
|
135
|
+
try:
|
|
136
|
+
arguments = self._arguments(trainer, batch, ctx)
|
|
137
|
+
started = time.perf_counter()
|
|
138
|
+
with _scheduled_rates(arguments["optimizer"]):
|
|
139
|
+
report = torchtest2.check_model(trainer.model, **arguments)
|
|
140
|
+
self.seconds = time.perf_counter() - started
|
|
141
|
+
except Exception as error:
|
|
142
|
+
logger.warning(
|
|
143
|
+
"model checks could not run, and the fit goes on without them: %s: %s",
|
|
144
|
+
type(error).__name__,
|
|
145
|
+
error,
|
|
146
|
+
)
|
|
147
|
+
return
|
|
148
|
+
self.report = report
|
|
149
|
+
self._tell(report)
|
|
150
|
+
failures = [result.name for result in report.failures]
|
|
151
|
+
if self.stop and failures:
|
|
152
|
+
trainer.request_stop("model checks failed: " + ", ".join(failures))
|
|
153
|
+
|
|
154
|
+
# -- the bridge: how torchtest2 sees the trainer and its task ----------------------------------------
|
|
155
|
+
|
|
156
|
+
def _arguments(self, trainer: Trainer[Any], batch: Any, ctx: StepContext) -> dict[str, Any]:
|
|
157
|
+
"""What `check_model` is given: the batch whole, the task's own steps, the optimizer of this fit."""
|
|
158
|
+
task = trainer.task
|
|
159
|
+
evaluating = dataclasses.replace(ctx, training=False)
|
|
160
|
+
self._without_predictions = False
|
|
161
|
+
|
|
162
|
+
def outputs(model: Any, whole: Any) -> Any:
|
|
163
|
+
step = task.validation_step(model, whole, evaluating)
|
|
164
|
+
predictions = getattr(step, "preds", step)
|
|
165
|
+
if predictions is None: # a task that only reports a loss: the loss is what can be compared
|
|
166
|
+
self._without_predictions = True
|
|
167
|
+
return getattr(step, "loss", None)
|
|
168
|
+
return predictions
|
|
169
|
+
|
|
170
|
+
return {
|
|
171
|
+
"inputs": _first_rows(batch, self.rows),
|
|
172
|
+
"targets": None,
|
|
173
|
+
"loss_fn": _loss_of,
|
|
174
|
+
# a task with train_epoch never gets here: on_train_begin leaves it unchecked
|
|
175
|
+
"forward_fn": lambda model, whole, targets: task.training_step(model, whole, ctx), # type: ignore[union-attr]
|
|
176
|
+
"eval_forward_fn": outputs,
|
|
177
|
+
"optimizer": trainer.optimization.optimizer if trainer.optimization is not None else None,
|
|
178
|
+
"overfit_steps": self.overfit_steps,
|
|
179
|
+
"skip": [*self.skip, *(name for name in _LEFT_OUT if name not in self.skip)],
|
|
180
|
+
**self.options,
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
# -- what is said ------------------------------------------------------------------------------------
|
|
184
|
+
|
|
185
|
+
def _tell(self, report: Any) -> None:
|
|
186
|
+
problems = [result for result in report.results if result.status.name in _PROBLEMS]
|
|
187
|
+
took = f"{self.seconds:.2f} s"
|
|
188
|
+
note = _WITHOUT_PREDICTIONS if self._without_predictions else None
|
|
189
|
+
if not problems:
|
|
190
|
+
text = (
|
|
191
|
+
f"model checks passed in {took}: {len(report.passed)} passed, {len(report.skipped)} skipped"
|
|
192
|
+
)
|
|
193
|
+
if note:
|
|
194
|
+
text += "; " + note
|
|
195
|
+
logger.info(text)
|
|
196
|
+
return
|
|
197
|
+
found = {(result.name, result.status.name) for result in problems}
|
|
198
|
+
earlier = self._fits_with_problems
|
|
199
|
+
self._fits_with_problems += 1
|
|
200
|
+
if found <= self._reported:
|
|
201
|
+
names = ", ".join(f"{result.name} {result.status.name}" for result in problems)
|
|
202
|
+
logger.info(
|
|
203
|
+
"model checks: only problems already reported, in %d earlier fit(s): %s", earlier, names
|
|
204
|
+
)
|
|
205
|
+
return
|
|
206
|
+
self._reported |= found
|
|
207
|
+
failed = {result.name for result in report.failures}
|
|
208
|
+
counts = [
|
|
209
|
+
_counted(number, word)
|
|
210
|
+
for number, word in ((len(failed), "failure"), (len(problems) - len(failed), "warning"))
|
|
211
|
+
if number
|
|
212
|
+
]
|
|
213
|
+
lines = [
|
|
214
|
+
f"model checks found {' and '.join(counts)} in {took} "
|
|
215
|
+
"(the whole report is in this callback's `report`):"
|
|
216
|
+
]
|
|
217
|
+
lines += [f" {result.status.name} {result.name}: {_explained(result)}" for result in problems]
|
|
218
|
+
if note:
|
|
219
|
+
lines.append(" " + note)
|
|
220
|
+
logger.warning("\n".join(lines))
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _explained(result: Any) -> str:
|
|
224
|
+
"""torchtest2's message, with what it means in this library where its own hint would mislead: the task
|
|
225
|
+
builds the optimizer at the start of every fit, so it is never made before the layers."""
|
|
226
|
+
message = str(result.message)
|
|
227
|
+
if result.name == "optimizer_coverage" and message.endswith(_COVERAGE_HINT):
|
|
228
|
+
message = message[: -len(_COVERAGE_HINT)] + (
|
|
229
|
+
" The task builds the optimizer at the start of every fit: do the param groups its "
|
|
230
|
+
"configure_optimization passes leave them out?"
|
|
231
|
+
)
|
|
232
|
+
return message
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
@contextmanager
|
|
236
|
+
def _scheduled_rates(optimizer: Any) -> Iterator[None]:
|
|
237
|
+
"""Gives each param group the rate its schedule starts from (`initial_lr`), and the fit's back after.
|
|
238
|
+
|
|
239
|
+
A warm-up begins at a rate of zero: checked with it, every weight would "not change" after a step, and a
|
|
240
|
+
healthy network would fail `params_change` and `overfit_batch`. The checks see the rate the warm-up rises
|
|
241
|
+
to; the fit, its own rate as it was.
|
|
242
|
+
"""
|
|
243
|
+
if optimizer is None:
|
|
244
|
+
yield
|
|
245
|
+
return
|
|
246
|
+
rates = [group["lr"] for group in optimizer.param_groups]
|
|
247
|
+
for group in optimizer.param_groups:
|
|
248
|
+
group["lr"] = group.get("initial_lr", group["lr"])
|
|
249
|
+
try:
|
|
250
|
+
yield
|
|
251
|
+
finally: # the checks may have loaded the optimizer's state back: set the rates on its groups as they are
|
|
252
|
+
for group, rate in zip(optimizer.param_groups, rates, strict=True):
|
|
253
|
+
group["lr"] = rate
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _first_rows(value: Any, rows: int) -> Any:
|
|
257
|
+
"""`value` with every tensor cut to its first `rows` samples, when the batch is longer than that.
|
|
258
|
+
|
|
259
|
+
The structure (tuples, named tuples, lists, mappings) is kept; a short batch comes back as it is."""
|
|
260
|
+
import torch
|
|
261
|
+
|
|
262
|
+
def size(item: Any) -> int | None:
|
|
263
|
+
if isinstance(item, torch.Tensor):
|
|
264
|
+
return int(item.shape[0]) if item.ndim else None
|
|
265
|
+
children = (
|
|
266
|
+
item.values() if isinstance(item, Mapping) else item if isinstance(item, tuple | list) else ()
|
|
267
|
+
)
|
|
268
|
+
for child in children:
|
|
269
|
+
found = size(child)
|
|
270
|
+
if found is not None:
|
|
271
|
+
return found
|
|
272
|
+
return None
|
|
273
|
+
|
|
274
|
+
def cut(item: Any) -> Any:
|
|
275
|
+
if isinstance(item, torch.Tensor):
|
|
276
|
+
return item[:rows] if item.ndim else item
|
|
277
|
+
if isinstance(item, Mapping):
|
|
278
|
+
return {key: cut(child) for key, child in item.items()}
|
|
279
|
+
if isinstance(item, tuple) and hasattr(item, "_fields"):
|
|
280
|
+
return type(item)(*(cut(child) for child in item))
|
|
281
|
+
if isinstance(item, tuple | list):
|
|
282
|
+
return type(item)(cut(child) for child in item)
|
|
283
|
+
return item
|
|
284
|
+
|
|
285
|
+
found = size(value)
|
|
286
|
+
return cut(value) if found is not None and found > rows else value
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _loss_of(outputs: Any) -> Any:
|
|
290
|
+
"""The loss a `training_step` returned: the tensor itself, or a `Step`'s `loss`."""
|
|
291
|
+
return getattr(outputs, "loss", outputs)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _counted(number: int, word: str) -> str:
|
|
295
|
+
return f"{number} {word}" if number == 1 else f"{number} {word}s"
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""A live panel of the fit, in the terminal or in a notebook's output, with Rich."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING, Any
|
|
6
|
+
|
|
7
|
+
from torchstack64.callbacks.base import Callback
|
|
8
|
+
from torchstack64.core import require
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from torchstack64.training.results import EpochResult, FitResult, OptimizationStepRecord
|
|
12
|
+
from torchstack64.training.trainer import Trainer
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class RichProgress(Callback):
|
|
16
|
+
"""Shows, after each epoch, the losses, the monitored value, the best epoch, the patience, the
|
|
17
|
+
learning rate and the epoch's duration. With `steps=True` it also shows a bar of the optimization steps
|
|
18
|
+
inside the epoch, reading the loss only every `every_n_steps` steps (each read waits for the GPU).
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
*,
|
|
24
|
+
steps: bool = False,
|
|
25
|
+
every_n_steps: int = 10,
|
|
26
|
+
refresh_per_second: int = 4,
|
|
27
|
+
console: Any = None,
|
|
28
|
+
) -> None:
|
|
29
|
+
require("rich", extra="progress", purpose="RichProgress")
|
|
30
|
+
from rich.console import Console
|
|
31
|
+
|
|
32
|
+
self.console = console if console is not None else Console()
|
|
33
|
+
self.steps = steps
|
|
34
|
+
self.every_n_steps = max(1, every_n_steps)
|
|
35
|
+
self.refresh_per_second = refresh_per_second
|
|
36
|
+
self.live: Any = None
|
|
37
|
+
self.last_table: Any = None
|
|
38
|
+
self._bar: Any = None
|
|
39
|
+
self._task_id: Any = None
|
|
40
|
+
self._first_optimization_step = 0
|
|
41
|
+
|
|
42
|
+
def on_train_begin(self, trainer: Trainer[Any]) -> None:
|
|
43
|
+
from rich.live import Live
|
|
44
|
+
|
|
45
|
+
if self.steps:
|
|
46
|
+
from rich.progress import BarColumn, MofNCompleteColumn, Progress, TextColumn, TimeElapsedColumn
|
|
47
|
+
|
|
48
|
+
self._bar = Progress(
|
|
49
|
+
TextColumn("{task.description}"),
|
|
50
|
+
BarColumn(),
|
|
51
|
+
MofNCompleteColumn(),
|
|
52
|
+
TextColumn("loss {task.fields[loss]}"),
|
|
53
|
+
TimeElapsedColumn(),
|
|
54
|
+
)
|
|
55
|
+
self._task_id = self._bar.add_task("epoch", total=None, loss="-")
|
|
56
|
+
self.live = Live(console=self.console, refresh_per_second=self.refresh_per_second)
|
|
57
|
+
self.live.start()
|
|
58
|
+
|
|
59
|
+
def on_epoch_begin(self, trainer: Trainer[Any], epoch: int) -> None:
|
|
60
|
+
if self._bar is None:
|
|
61
|
+
return
|
|
62
|
+
self._first_optimization_step = trainer.state.optimization_step
|
|
63
|
+
total = trainer.plan.optimization_steps_per_epoch if trainer.plan is not None else None
|
|
64
|
+
self._bar.reset(
|
|
65
|
+
self._task_id, total=total, description=f"epoch {epoch}/{trainer.config.epochs}", loss="-"
|
|
66
|
+
)
|
|
67
|
+
self._render()
|
|
68
|
+
|
|
69
|
+
def on_optimization_step_end(self, trainer: Trainer[Any], record: OptimizationStepRecord) -> None:
|
|
70
|
+
if self._bar is None or record.optimization_step % self.every_n_steps:
|
|
71
|
+
return
|
|
72
|
+
self._bar.update(
|
|
73
|
+
self._task_id,
|
|
74
|
+
completed=record.optimization_step - self._first_optimization_step,
|
|
75
|
+
loss=f"{record.loss.item():.4f}",
|
|
76
|
+
)
|
|
77
|
+
self._render()
|
|
78
|
+
|
|
79
|
+
def on_epoch_end(self, trainer: Trainer[Any], result: EpochResult) -> None:
|
|
80
|
+
self.last_table = self._build_table(trainer, result)
|
|
81
|
+
self._render()
|
|
82
|
+
|
|
83
|
+
def on_train_end(self, trainer: Trainer[Any], result: FitResult) -> None:
|
|
84
|
+
if self.live is not None:
|
|
85
|
+
self.live.stop()
|
|
86
|
+
if self.last_table is not None:
|
|
87
|
+
self.console.print(self.last_table)
|
|
88
|
+
|
|
89
|
+
def _render(self) -> None:
|
|
90
|
+
if self.live is None:
|
|
91
|
+
return
|
|
92
|
+
if self._bar is not None:
|
|
93
|
+
from rich.console import Group
|
|
94
|
+
|
|
95
|
+
parts = [part for part in (self.last_table, self._bar) if part is not None]
|
|
96
|
+
self.live.update(Group(*parts))
|
|
97
|
+
elif self.last_table is not None:
|
|
98
|
+
self.live.update(self.last_table)
|
|
99
|
+
|
|
100
|
+
@staticmethod
|
|
101
|
+
def _format(value: object) -> str:
|
|
102
|
+
try:
|
|
103
|
+
return f"{float(value):.4f}" # type: ignore[arg-type]
|
|
104
|
+
except (TypeError, ValueError):
|
|
105
|
+
return str(value)
|
|
106
|
+
|
|
107
|
+
def _build_table(self, trainer: Trainer[Any], result: EpochResult) -> Any:
|
|
108
|
+
from rich.panel import Panel
|
|
109
|
+
from rich.table import Table
|
|
110
|
+
|
|
111
|
+
name = trainer.config.monitor.name
|
|
112
|
+
metrics = result.metrics
|
|
113
|
+
best = result.best
|
|
114
|
+
best_score = self._format(best.score) if best is not None else "n/a"
|
|
115
|
+
if result.improved:
|
|
116
|
+
best_score += " ✓"
|
|
117
|
+
patience = trainer.config.early_stopping_patience
|
|
118
|
+
table = Table.grid(padding=(0, 2))
|
|
119
|
+
table.add_column(style="cyan")
|
|
120
|
+
table.add_column(justify="right")
|
|
121
|
+
table.add_row("Epoch", f"{result.epoch}/{trainer.config.epochs}")
|
|
122
|
+
table.add_row("Train Loss", self._format(metrics.get("train_loss", "n/a")))
|
|
123
|
+
if "val_loss" in metrics:
|
|
124
|
+
table.add_row("Val Loss", self._format(metrics["val_loss"]))
|
|
125
|
+
if name != "val_loss" and name in metrics:
|
|
126
|
+
table.add_row(name, self._format(metrics[name]))
|
|
127
|
+
table.add_row(f"Best {name}", best_score)
|
|
128
|
+
table.add_row("Best Epoch", str(best.epoch) if best is not None else "n/a")
|
|
129
|
+
table.add_row("Patience", f"{result.patience}/{patience if patience is not None else '-'}")
|
|
130
|
+
table.add_row("LR", f"{metrics.get('lr', float('nan')):.3g}")
|
|
131
|
+
table.add_row("Time", f"{result.seconds:.1f}s")
|
|
132
|
+
return Panel(table, title="Training Progress")
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""The usual set of callbacks, from a few switches."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Literal
|
|
8
|
+
|
|
9
|
+
from torchstack64.callbacks.base import Callback
|
|
10
|
+
from torchstack64.callbacks.checkpointing import Checkpointing
|
|
11
|
+
from torchstack64.callbacks.history_plot import HistoryPlot
|
|
12
|
+
from torchstack64.callbacks.mlflow_logger import MLflowLogger
|
|
13
|
+
from torchstack64.callbacks.model_checks import ModelChecks
|
|
14
|
+
from torchstack64.callbacks.progress import RichProgress
|
|
15
|
+
from torchstack64.core import is_installed
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def default_stack(
|
|
19
|
+
*,
|
|
20
|
+
mlflow: bool | Literal["auto"] | MLflowLogger = "auto",
|
|
21
|
+
progress: bool = True,
|
|
22
|
+
plot: bool = True,
|
|
23
|
+
checkpointing: str | Path | Checkpointing | None = None,
|
|
24
|
+
plot_dir: str | Path | None = None,
|
|
25
|
+
mlflow_params: Mapping[str, Any] | Any = None,
|
|
26
|
+
mlflow_tags: Mapping[str, str] | None = None,
|
|
27
|
+
checks: bool | ModelChecks = False,
|
|
28
|
+
) -> list[Callback]:
|
|
29
|
+
"""The usual callbacks of a fit, in the order they run.
|
|
30
|
+
|
|
31
|
+
On unless switched off are the ones that only watch the fit: a progress panel, the training curves and
|
|
32
|
+
MLflow logging. Off unless asked for is the one that writes files: `checkpointing` writes the training
|
|
33
|
+
state in a folder every epoch.
|
|
34
|
+
|
|
35
|
+
`mlflow` takes `True` for the callback with its defaults, or the callback itself, configured:
|
|
36
|
+
`mlflow=MLflowLogger(bundle=...)`. `checkpointing` takes a folder or a `Checkpointing`, never `True`:
|
|
37
|
+
nothing is written where it was not asked.
|
|
38
|
+
|
|
39
|
+
`mlflow="auto"` (the default) adds the logger only when MLflow is installed, and the logger itself
|
|
40
|
+
stays silent unless a run is active when the fit begins: the same notebook runs with or without a
|
|
41
|
+
tracking server. `mlflow=True` insists on a run; `mlflow=False` leaves MLflow out. `mlflow_params` and
|
|
42
|
+
`mlflow_tags` configure the logger built here; a logger given whole brings its own.
|
|
43
|
+
|
|
44
|
+
`checks=True` adds `ModelChecks` with its defaults; give it configured for more:
|
|
45
|
+
`checks=ModelChecks(stop=True)`. It needs the `checks` extra, and runs torchtest2 on the first batch of
|
|
46
|
+
every fit; off unless asked for.
|
|
47
|
+
|
|
48
|
+
The model checks come first, so what they find is said before the progress panel starts. The MLflow
|
|
49
|
+
logger comes last: in a search it closes the trial's run when the fit ends, and the curves are logged
|
|
50
|
+
before that.
|
|
51
|
+
"""
|
|
52
|
+
if isinstance(mlflow, MLflowLogger) and (mlflow_params is not None or mlflow_tags is not None):
|
|
53
|
+
raise TypeError(
|
|
54
|
+
"mlflow_params and mlflow_tags configure the logger default_stack builds; "
|
|
55
|
+
"give params= and tags= to your MLflowLogger instead"
|
|
56
|
+
)
|
|
57
|
+
if isinstance(checkpointing, bool):
|
|
58
|
+
raise TypeError("checkpointing takes the folder to write in, or a Checkpointing; None leaves it out")
|
|
59
|
+
if not isinstance(checks, bool | ModelChecks):
|
|
60
|
+
raise TypeError(f"checks is True, False or a ModelChecks; got {checks!r}")
|
|
61
|
+
callbacks: list[Callback] = []
|
|
62
|
+
if isinstance(checks, ModelChecks):
|
|
63
|
+
callbacks.append(checks)
|
|
64
|
+
elif checks:
|
|
65
|
+
callbacks.append(ModelChecks())
|
|
66
|
+
if progress:
|
|
67
|
+
callbacks.append(RichProgress())
|
|
68
|
+
if plot:
|
|
69
|
+
callbacks.append(HistoryPlot(save_dir=plot_dir, log_to_mlflow=_plot_to_mlflow(mlflow)))
|
|
70
|
+
if isinstance(checkpointing, Checkpointing):
|
|
71
|
+
callbacks.append(checkpointing)
|
|
72
|
+
elif checkpointing is not None:
|
|
73
|
+
callbacks.append(Checkpointing(checkpointing))
|
|
74
|
+
if isinstance(mlflow, MLflowLogger):
|
|
75
|
+
callbacks.append(mlflow)
|
|
76
|
+
elif mlflow is True or (mlflow == "auto" and is_installed("mlflow")):
|
|
77
|
+
callbacks.append(MLflowLogger(params=mlflow_params, tags=mlflow_tags, required=mlflow is True))
|
|
78
|
+
return callbacks
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _plot_to_mlflow(mlflow: bool | Literal["auto"] | MLflowLogger) -> bool | Literal["auto"]:
|
|
82
|
+
"""The curves go to MLflow when the logger does: always with a logger that insists on a run."""
|
|
83
|
+
if isinstance(mlflow, MLflowLogger):
|
|
84
|
+
return True if mlflow.required else "auto"
|
|
85
|
+
return mlflow
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
from torchstack64.core.errors import (
|
|
2
|
+
BundleError,
|
|
3
|
+
BundleExistsError,
|
|
4
|
+
BundleIntegrityError,
|
|
5
|
+
BundleNotFoundError,
|
|
6
|
+
CheckpointError,
|
|
7
|
+
CodeConflictError,
|
|
8
|
+
DeviceUnavailableError,
|
|
9
|
+
MissingDependencyError,
|
|
10
|
+
MissingExtraError,
|
|
11
|
+
NoActiveRunError,
|
|
12
|
+
ProofError,
|
|
13
|
+
TorchstackError,
|
|
14
|
+
TrustRequiredError,
|
|
15
|
+
UnknownArtifactError,
|
|
16
|
+
)
|
|
17
|
+
from torchstack64.core.evaluation import EvaluationResult, Evaluator, Metric
|
|
18
|
+
from torchstack64.core.extras import is_installed, require
|
|
19
|
+
from torchstack64.core.inference import Predictor, ProbabilisticPredictor
|
|
20
|
+
from torchstack64.core.labels import LabelSchema
|
|
21
|
+
from torchstack64.core.logging import (
|
|
22
|
+
DEFAULT_FORMAT,
|
|
23
|
+
LOGGER_NAME,
|
|
24
|
+
LogLevel,
|
|
25
|
+
configure_logging,
|
|
26
|
+
log_level,
|
|
27
|
+
warn_once,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"DEFAULT_FORMAT",
|
|
32
|
+
"LOGGER_NAME",
|
|
33
|
+
"BundleError",
|
|
34
|
+
"BundleExistsError",
|
|
35
|
+
"BundleIntegrityError",
|
|
36
|
+
"BundleNotFoundError",
|
|
37
|
+
"CheckpointError",
|
|
38
|
+
"CodeConflictError",
|
|
39
|
+
"DeviceUnavailableError",
|
|
40
|
+
"EvaluationResult",
|
|
41
|
+
"Evaluator",
|
|
42
|
+
"LabelSchema",
|
|
43
|
+
"LogLevel",
|
|
44
|
+
"Metric",
|
|
45
|
+
"MissingDependencyError",
|
|
46
|
+
"MissingExtraError",
|
|
47
|
+
"NoActiveRunError",
|
|
48
|
+
"Predictor",
|
|
49
|
+
"ProbabilisticPredictor",
|
|
50
|
+
"ProofError",
|
|
51
|
+
"TorchstackError",
|
|
52
|
+
"TrustRequiredError",
|
|
53
|
+
"UnknownArtifactError",
|
|
54
|
+
"configure_logging",
|
|
55
|
+
"is_installed",
|
|
56
|
+
"log_level",
|
|
57
|
+
"require",
|
|
58
|
+
"warn_once",
|
|
59
|
+
]
|