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,586 @@
|
|
|
1
|
+
"""The trainer: runs a task on a model, epoch by epoch, and keeps the best epoch.
|
|
2
|
+
|
|
3
|
+
It owns everything that is the same for every model: putting the model and each batch on the device,
|
|
4
|
+
mixed precision, gradient accumulation and clipping, the optimizer and scheduler steps, validation,
|
|
5
|
+
choosing the best epoch, early stopping, the callbacks. It is meant to be used, not subclassed: what
|
|
6
|
+
differs between models lives in the task.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
import os
|
|
13
|
+
import time
|
|
14
|
+
import uuid
|
|
15
|
+
from collections.abc import Iterable, Mapping, Sequence
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import TYPE_CHECKING, Any
|
|
18
|
+
|
|
19
|
+
import torch
|
|
20
|
+
from torch import nn
|
|
21
|
+
|
|
22
|
+
from torchstack64.core import CheckpointError
|
|
23
|
+
from torchstack64.training.config import FitConfig, Monitor, ParamValue
|
|
24
|
+
from torchstack64.training.results import (
|
|
25
|
+
BestCheckpoint,
|
|
26
|
+
EpochResult,
|
|
27
|
+
Evaluation,
|
|
28
|
+
FitResult,
|
|
29
|
+
FitStatus,
|
|
30
|
+
OptimizationStepRecord,
|
|
31
|
+
Predictions,
|
|
32
|
+
TrainingHistory,
|
|
33
|
+
)
|
|
34
|
+
from torchstack64.training.runtime import (
|
|
35
|
+
Randomness,
|
|
36
|
+
Runtime,
|
|
37
|
+
Weights,
|
|
38
|
+
seed_everything,
|
|
39
|
+
)
|
|
40
|
+
from torchstack64.training.trainer.adapters import (
|
|
41
|
+
as_optimization,
|
|
42
|
+
as_step,
|
|
43
|
+
capture_callback_states,
|
|
44
|
+
plan_for,
|
|
45
|
+
restore_callback_states,
|
|
46
|
+
run_params,
|
|
47
|
+
)
|
|
48
|
+
from torchstack64.training.trainer.contracts import FitPlan, Optimization, StepContext
|
|
49
|
+
from torchstack64.training.trainer.hooks import Hook, emit, emit_all
|
|
50
|
+
from torchstack64.training.trainer.meters import PredictionCollector, RunningMeans, batch_size_of
|
|
51
|
+
from torchstack64.training.trainer.state import FitState
|
|
52
|
+
|
|
53
|
+
if TYPE_CHECKING:
|
|
54
|
+
from torchstack64.training.task import EpochTask, Task
|
|
55
|
+
|
|
56
|
+
logger = logging.getLogger(__name__)
|
|
57
|
+
|
|
58
|
+
STATE_FORMAT = "torchstack64.training-state"
|
|
59
|
+
STATE_VERSION = 1
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class Trainer[BatchT]:
|
|
63
|
+
"""Runs `task` on `model` with `config`, calling `callbacks` along the way.
|
|
64
|
+
|
|
65
|
+
Creating a trainer has no side effect: the model moves to the device, and the optimizer is built,
|
|
66
|
+
when `fit()` starts. Every `fit()` starts from a clean state, so one trainer can run several folds
|
|
67
|
+
or seeds in a row without anything leaking from one to the next.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
def __init__(
|
|
71
|
+
self,
|
|
72
|
+
model: nn.Module,
|
|
73
|
+
task: Task[BatchT] | EpochTask[BatchT],
|
|
74
|
+
config: FitConfig | None = None,
|
|
75
|
+
callbacks: Sequence[Any] = (),
|
|
76
|
+
) -> None:
|
|
77
|
+
self.model = model
|
|
78
|
+
self.task = task
|
|
79
|
+
self.config = config if config is not None else FitConfig()
|
|
80
|
+
self.callbacks = list(callbacks)
|
|
81
|
+
self.runtime: Runtime | None = None
|
|
82
|
+
self.plan: FitPlan | None = None
|
|
83
|
+
self.optimization: Optimization | None = None
|
|
84
|
+
self.params: dict[str, ParamValue] = {} # how the running fit was set up; see `FitResult.params`
|
|
85
|
+
self.state = FitState()
|
|
86
|
+
self._train_logs = RunningMeans()
|
|
87
|
+
self._group_loss: torch.Tensor | None = None
|
|
88
|
+
self._group_count = 0
|
|
89
|
+
self._last_logs: Mapping[str, torch.Tensor | float] = {}
|
|
90
|
+
self._started = 0.0
|
|
91
|
+
self._randomness = Randomness() # the fit's generators, its loaders' own included
|
|
92
|
+
|
|
93
|
+
def __repr__(self) -> str:
|
|
94
|
+
return (
|
|
95
|
+
f"Trainer(model={type(self.model).__name__}, task={type(self.task).__name__}, "
|
|
96
|
+
f"callbacks={[type(c).__name__ for c in self.callbacks]})"
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def monitor(self) -> Monitor:
|
|
101
|
+
return self.config.monitor
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def history(self) -> TrainingHistory:
|
|
105
|
+
return self.state.history
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def best(self) -> BestCheckpoint | None:
|
|
109
|
+
return self.state.best
|
|
110
|
+
|
|
111
|
+
@property
|
|
112
|
+
def lr(self) -> float:
|
|
113
|
+
"""The largest learning rate among the optimizer's groups (the head's, if layers go slower)."""
|
|
114
|
+
if self.optimization is None:
|
|
115
|
+
return float("nan")
|
|
116
|
+
return max(float(group["lr"]) for group in self.optimization.optimizer.param_groups)
|
|
117
|
+
|
|
118
|
+
# -- fit -------------------------------------------------------------------------------------
|
|
119
|
+
|
|
120
|
+
def fit(
|
|
121
|
+
self,
|
|
122
|
+
train: Iterable[BatchT],
|
|
123
|
+
val: Iterable[BatchT] | None = None,
|
|
124
|
+
*,
|
|
125
|
+
resume_from: str | Path | None = None,
|
|
126
|
+
) -> FitResult:
|
|
127
|
+
"""Trains for `config.epochs` epochs, or until early stopping, and returns the `FitResult`.
|
|
128
|
+
|
|
129
|
+
The model ends with the weights of the best epoch, not the last one, whatever way the fit ends
|
|
130
|
+
(an exception and the notebook's stop button included). Without `val` there is no validation:
|
|
131
|
+
every epoch runs, and the model keeps its last weights. `resume_from` continues a fit saved by
|
|
132
|
+
`save_state` (the `Checkpointing` callback writes one).
|
|
133
|
+
"""
|
|
134
|
+
cfg = self.config
|
|
135
|
+
self.state = FitState()
|
|
136
|
+
self._randomness = Randomness({"train": train} if val is None else {"train": train, "val": val})
|
|
137
|
+
self._started = time.perf_counter()
|
|
138
|
+
if cfg.seed is not None:
|
|
139
|
+
seed_everything(cfg.seed)
|
|
140
|
+
self.runtime = Runtime(cfg.device, cfg.precision)
|
|
141
|
+
self.model.to(self.runtime.device)
|
|
142
|
+
self.plan = plan_for(train, cfg.epochs, cfg.accumulate)
|
|
143
|
+
self.optimization = as_optimization(self.task.configure_optimization(self.model, self.plan))
|
|
144
|
+
self.params = run_params(self)
|
|
145
|
+
callback_states: dict[str, Any] = {}
|
|
146
|
+
if resume_from is not None:
|
|
147
|
+
callback_states = self.load_state(resume_from)
|
|
148
|
+
self.optimization.optimizer.zero_grad(set_to_none=True)
|
|
149
|
+
self._log_start(val is not None, resume_from)
|
|
150
|
+
try:
|
|
151
|
+
emit(self, Hook.TRAIN_BEGIN)
|
|
152
|
+
if callback_states:
|
|
153
|
+
restore_callback_states(self, callback_states)
|
|
154
|
+
for epoch in range(self.state.epoch + 1, cfg.epochs + 1):
|
|
155
|
+
self._run_epoch(epoch, train, val)
|
|
156
|
+
if self.state.should_stop:
|
|
157
|
+
break
|
|
158
|
+
if self.state.status is FitStatus.RUNNING:
|
|
159
|
+
self.state.status = FitStatus.COMPLETED
|
|
160
|
+
except BaseException as error:
|
|
161
|
+
self.state.fail(error)
|
|
162
|
+
raise
|
|
163
|
+
finally:
|
|
164
|
+
result = self._finish()
|
|
165
|
+
return result
|
|
166
|
+
|
|
167
|
+
def _run_epoch(self, epoch: int, train: Iterable[BatchT], val: Iterable[BatchT] | None) -> None:
|
|
168
|
+
self.state.epoch = epoch
|
|
169
|
+
started = time.perf_counter()
|
|
170
|
+
emit(self, Hook.EPOCH_BEGIN, epoch)
|
|
171
|
+
train_loss, train_logs = self._train_epoch(train)
|
|
172
|
+
evaluation = self._validate(val, notify=True) if val is not None else None
|
|
173
|
+
result = self._close_epoch(epoch, train_loss, train_logs, evaluation, time.perf_counter() - started)
|
|
174
|
+
self._step_scheduler("epoch", evaluation)
|
|
175
|
+
emit(self, Hook.EPOCH_END, result)
|
|
176
|
+
logger.debug(
|
|
177
|
+
"epoch %d/%d: %s%s",
|
|
178
|
+
epoch,
|
|
179
|
+
self.config.epochs,
|
|
180
|
+
", ".join(f"{k}={v:.4g}" for k, v in result.metrics.items()),
|
|
181
|
+
" (best)" if result.improved else "",
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
def _train_epoch(self, loader: Iterable[BatchT]) -> tuple[float, dict[str, float]]:
|
|
185
|
+
assert self.runtime is not None and self.plan is not None
|
|
186
|
+
self._train_logs = RunningMeans()
|
|
187
|
+
self.model.train()
|
|
188
|
+
train_epoch = getattr(self.task, "train_epoch", None)
|
|
189
|
+
if callable(train_epoch): # the task runs the epoch itself
|
|
190
|
+
return float(train_epoch(self, loader)), self._train_logs.means()
|
|
191
|
+
runtime = self.runtime
|
|
192
|
+
total = torch.zeros((), device=runtime.device)
|
|
193
|
+
seen = 0
|
|
194
|
+
self._reset_group()
|
|
195
|
+
for index, batch in enumerate(loader):
|
|
196
|
+
divisor = self._micro_batches_in_group(index)
|
|
197
|
+
ctx = StepContext(
|
|
198
|
+
self.state.epoch, self.state.optimization_step, index, True, runtime.device, self.plan
|
|
199
|
+
)
|
|
200
|
+
batch = runtime.to_device(batch)
|
|
201
|
+
emit(self, Hook.TRAIN_BATCH_BEGIN, batch, ctx)
|
|
202
|
+
with runtime.autocast():
|
|
203
|
+
step = as_step(self.task.training_step(self.model, batch, ctx)) # type: ignore[union-attr]
|
|
204
|
+
if step.loss is None:
|
|
205
|
+
raise ValueError("training_step must return a loss")
|
|
206
|
+
runtime.backward(step.loss / divisor)
|
|
207
|
+
loss = step.loss.detach().float()
|
|
208
|
+
total += loss
|
|
209
|
+
seen += 1
|
|
210
|
+
self._train_logs.add(step.logs)
|
|
211
|
+
self._accumulate(loss, step.logs)
|
|
212
|
+
if self._group_count == divisor:
|
|
213
|
+
self._take_optimization_step(index)
|
|
214
|
+
if self.state.should_stop:
|
|
215
|
+
break
|
|
216
|
+
if self._group_count: # what is left when the loader's length is unknown
|
|
217
|
+
self._take_optimization_step(seen - 1)
|
|
218
|
+
return (total / max(seen, 1)).item(), self._train_logs.means() # one wait for the GPU per epoch
|
|
219
|
+
|
|
220
|
+
def _micro_batches_in_group(self, index: int) -> int:
|
|
221
|
+
"""How many micro-batches the group of `index` has: `accumulate`, except the epoch's last group,
|
|
222
|
+
which may be shorter. Dividing each loss by its own group's size keeps the gradient of every
|
|
223
|
+
optimization step a true mean, the last one included."""
|
|
224
|
+
assert self.plan is not None
|
|
225
|
+
accumulate = self.config.accumulate
|
|
226
|
+
batches = self.plan.batches_per_epoch
|
|
227
|
+
if accumulate == 1 or batches is None:
|
|
228
|
+
return accumulate
|
|
229
|
+
full = (batches // accumulate) * accumulate
|
|
230
|
+
return accumulate if index < full else batches - full
|
|
231
|
+
|
|
232
|
+
def _accumulate(self, loss: torch.Tensor, logs: Mapping[str, torch.Tensor | float]) -> None:
|
|
233
|
+
self._group_loss = loss if self._group_loss is None else self._group_loss + loss
|
|
234
|
+
self._group_count += 1
|
|
235
|
+
self._last_logs = logs
|
|
236
|
+
|
|
237
|
+
def _reset_group(self) -> None:
|
|
238
|
+
self._group_loss = None
|
|
239
|
+
self._group_count = 0
|
|
240
|
+
self._last_logs = {}
|
|
241
|
+
|
|
242
|
+
def _take_optimization_step(self, batch_index: int) -> None:
|
|
243
|
+
loss = self._group_loss / self._group_count if self._group_loss is not None else None
|
|
244
|
+
self.optimization_step(loss, batch_index=batch_index, logs=self._last_logs)
|
|
245
|
+
|
|
246
|
+
def optimization_step(
|
|
247
|
+
self,
|
|
248
|
+
loss: torch.Tensor | None = None,
|
|
249
|
+
*,
|
|
250
|
+
batch_index: int = -1,
|
|
251
|
+
logs: Mapping[str, torch.Tensor | float] | None = None,
|
|
252
|
+
) -> OptimizationStepRecord:
|
|
253
|
+
"""Clips, applies the gradients, zeroes them, steps a per-step scheduler, counts the optimization
|
|
254
|
+
step and calls `on_optimization_step_end`. The trainer calls it; a task that runs its own epoch
|
|
255
|
+
calls it too.
|
|
256
|
+
|
|
257
|
+
From an `EpochTask`, `logs` are also averaged into the epoch's history.
|
|
258
|
+
"""
|
|
259
|
+
assert self.runtime is not None and self.optimization is not None
|
|
260
|
+
optimizer = self.optimization.optimizer
|
|
261
|
+
grad_norm = self.runtime.clip(self.model.parameters(), self.config.clip_grad_norm, optimizer)
|
|
262
|
+
stepped = self.runtime.step(optimizer)
|
|
263
|
+
optimizer.zero_grad(set_to_none=True)
|
|
264
|
+
if stepped:
|
|
265
|
+
self._step_scheduler("step", None)
|
|
266
|
+
self.state.optimization_step += 1
|
|
267
|
+
if logs and self._group_count == 0: # called by an EpochTask, not by the trainer's own loop
|
|
268
|
+
self._train_logs.add(logs)
|
|
269
|
+
record = OptimizationStepRecord(
|
|
270
|
+
optimization_step=self.state.optimization_step,
|
|
271
|
+
epoch=self.state.epoch,
|
|
272
|
+
batch_index=batch_index,
|
|
273
|
+
loss=loss.detach() if loss is not None else torch.full((), float("nan")),
|
|
274
|
+
lr=self.lr,
|
|
275
|
+
grad_norm=grad_norm,
|
|
276
|
+
skipped=not stepped,
|
|
277
|
+
logs=dict(logs or {}),
|
|
278
|
+
)
|
|
279
|
+
self._reset_group()
|
|
280
|
+
emit(self, Hook.OPTIMIZATION_STEP_END, record)
|
|
281
|
+
return record
|
|
282
|
+
|
|
283
|
+
def _step_scheduler(self, interval: str, evaluation: Evaluation | None) -> None:
|
|
284
|
+
opt = self.optimization
|
|
285
|
+
if opt is None or opt.scheduler is None or opt.interval != interval:
|
|
286
|
+
return
|
|
287
|
+
if isinstance(opt.scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau):
|
|
288
|
+
if evaluation is not None and evaluation.score is not None:
|
|
289
|
+
opt.scheduler.step(evaluation.score)
|
|
290
|
+
return
|
|
291
|
+
opt.scheduler.step()
|
|
292
|
+
|
|
293
|
+
# -- validation, evaluation, prediction ------------------------------------------------------
|
|
294
|
+
|
|
295
|
+
def _validate(self, loader: Iterable[BatchT], *, notify: bool, predict: bool = False) -> Evaluation:
|
|
296
|
+
assert self.runtime is not None
|
|
297
|
+
runtime = self.runtime
|
|
298
|
+
model = self.model
|
|
299
|
+
was_training = model.training
|
|
300
|
+
model.eval()
|
|
301
|
+
if notify:
|
|
302
|
+
emit(self, Hook.VALIDATION_BEGIN)
|
|
303
|
+
step_fn = getattr(self.task, "predict_step", None) if predict else None
|
|
304
|
+
if not callable(step_fn):
|
|
305
|
+
step_fn = self.task.validation_step
|
|
306
|
+
collector = PredictionCollector()
|
|
307
|
+
logs = RunningMeans()
|
|
308
|
+
loss_sum = torch.zeros((), device=runtime.device)
|
|
309
|
+
weight = 0
|
|
310
|
+
try:
|
|
311
|
+
with torch.inference_mode():
|
|
312
|
+
for index, batch in enumerate(loader):
|
|
313
|
+
ctx = StepContext(
|
|
314
|
+
self.state.epoch,
|
|
315
|
+
self.state.optimization_step,
|
|
316
|
+
index,
|
|
317
|
+
False,
|
|
318
|
+
runtime.device,
|
|
319
|
+
self.plan,
|
|
320
|
+
)
|
|
321
|
+
batch = runtime.to_device(batch)
|
|
322
|
+
with runtime.autocast():
|
|
323
|
+
step = as_step(step_fn(model, batch, ctx))
|
|
324
|
+
count = batch_size_of(step.targets, step.preds)
|
|
325
|
+
if step.loss is not None:
|
|
326
|
+
loss_sum += step.loss.detach().float() * count
|
|
327
|
+
weight += count
|
|
328
|
+
collector.add(step.preds, step.targets, step.ids)
|
|
329
|
+
logs.add(step.logs)
|
|
330
|
+
finally:
|
|
331
|
+
model.train(was_training)
|
|
332
|
+
predictions = collector.result()
|
|
333
|
+
loss = (loss_sum / weight).item() if weight else None
|
|
334
|
+
score = None if predict else self._score(loss, predictions)
|
|
335
|
+
evaluation = Evaluation(loss=loss, predictions=predictions, score=score, logs=logs.means())
|
|
336
|
+
if notify:
|
|
337
|
+
emit(self, Hook.VALIDATION_END, evaluation)
|
|
338
|
+
return evaluation
|
|
339
|
+
|
|
340
|
+
def _score(self, loss: float | None, predictions: Predictions) -> float | None:
|
|
341
|
+
monitor = self.monitor
|
|
342
|
+
if monitor.watches_loss:
|
|
343
|
+
if loss is None:
|
|
344
|
+
raise ValueError(
|
|
345
|
+
"the monitor watches the validation loss, but validation_step returned no loss"
|
|
346
|
+
)
|
|
347
|
+
return loss
|
|
348
|
+
if predictions.targets is None or not predictions.outputs:
|
|
349
|
+
raise ValueError(
|
|
350
|
+
f"the monitor computes {monitor.name}, so validation_step must return preds and targets"
|
|
351
|
+
)
|
|
352
|
+
y_pred = predictions.select(monitor.output).tolist()
|
|
353
|
+
return monitor.score(loss, predictions.targets.tolist(), y_pred)
|
|
354
|
+
|
|
355
|
+
def _prepare(self) -> Runtime:
|
|
356
|
+
if self.runtime is None:
|
|
357
|
+
self.runtime = Runtime(self.config.device, self.config.precision)
|
|
358
|
+
self.model.to(self.runtime.device)
|
|
359
|
+
return self.runtime
|
|
360
|
+
|
|
361
|
+
def evaluate(self, loader: Iterable[BatchT]) -> Evaluation:
|
|
362
|
+
"""The loss, predictions and monitored value of `loader`, with `validation_step` (no callbacks)."""
|
|
363
|
+
self._prepare()
|
|
364
|
+
return self._validate(loader, notify=False)
|
|
365
|
+
|
|
366
|
+
def predict(self, loader: Iterable[BatchT]) -> Predictions:
|
|
367
|
+
"""Predictions over any loader, with the task's `predict_step` if it has one, else
|
|
368
|
+
`validation_step`. Batches without targets work when the task allows them."""
|
|
369
|
+
self._prepare()
|
|
370
|
+
return self._validate(loader, notify=False, predict=True).predictions
|
|
371
|
+
|
|
372
|
+
def request_stop(self, reason: str) -> None:
|
|
373
|
+
"""Ends the fit: the current epoch stops at its next optimization step, is validated, and the fit
|
|
374
|
+
returns. What a callback calls instead of raising."""
|
|
375
|
+
if not self.state.should_stop:
|
|
376
|
+
logger.info("stop requested: %s", reason)
|
|
377
|
+
self.state.request_stop(reason)
|
|
378
|
+
|
|
379
|
+
# -- saving and resuming a fit -----------------------------------------------------------------
|
|
380
|
+
|
|
381
|
+
def save_state(self, path: str | Path) -> Path:
|
|
382
|
+
"""Writes the training state to `path`, atomically: a crash while writing leaves the previous file.
|
|
383
|
+
|
|
384
|
+
A training state is everything the next epoch depends on: the weights, the optimizer's moments,
|
|
385
|
+
the scheduler's position, the fp16 scaler, the history and the best epoch so far, the patience,
|
|
386
|
+
every random generator (a data loader's own included), and the state of the callbacks that have
|
|
387
|
+
one. `fit(resume_from=...)` continues from it, at an epoch boundary. It needs a fit in progress:
|
|
388
|
+
call it from a callback, during `fit()`.
|
|
389
|
+
|
|
390
|
+
The file is written by `torch.save` and read with `weights_only=True`: only tensors and plain
|
|
391
|
+
Python values come back, so loading a state never runs code.
|
|
392
|
+
"""
|
|
393
|
+
from torchstack64 import __version__
|
|
394
|
+
|
|
395
|
+
if self.optimization is None or self.runtime is None:
|
|
396
|
+
raise CheckpointError("save_state needs a fit in progress: call it from a callback, during fit()")
|
|
397
|
+
optimization = self.optimization
|
|
398
|
+
elapsed = time.perf_counter() - self._started if self._started else 0.0
|
|
399
|
+
payload: dict[str, Any] = {
|
|
400
|
+
"format": STATE_FORMAT,
|
|
401
|
+
"version": STATE_VERSION,
|
|
402
|
+
"torchstack64": __version__,
|
|
403
|
+
"model_class": type(self.model).__qualname__,
|
|
404
|
+
**self.state.state_dict(elapsed),
|
|
405
|
+
"model": Weights(self.model).cpu_copy(),
|
|
406
|
+
"optimizer": optimization.optimizer.state_dict(),
|
|
407
|
+
"scheduler": optimization.scheduler.state_dict() if optimization.scheduler is not None else None,
|
|
408
|
+
"runtime": self.runtime.state_dict(),
|
|
409
|
+
"rng": self._randomness.state_dict(),
|
|
410
|
+
"callbacks": capture_callback_states(self),
|
|
411
|
+
}
|
|
412
|
+
path = Path(path)
|
|
413
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
414
|
+
partial = path.with_name(f".{path.name}.{uuid.uuid4().hex[:8]}.partial")
|
|
415
|
+
try:
|
|
416
|
+
torch.save(payload, partial)
|
|
417
|
+
os.replace(partial, path)
|
|
418
|
+
except BaseException:
|
|
419
|
+
partial.unlink(missing_ok=True)
|
|
420
|
+
raise
|
|
421
|
+
logger.debug(
|
|
422
|
+
"training state saved to %s at epoch %d (optimization step %d)",
|
|
423
|
+
path,
|
|
424
|
+
self.state.epoch,
|
|
425
|
+
self.state.optimization_step,
|
|
426
|
+
)
|
|
427
|
+
return path
|
|
428
|
+
|
|
429
|
+
def load_state(self, path: str | Path) -> dict[str, Any]:
|
|
430
|
+
"""Restores what `save_state` wrote, into a fit that has just built its optimizer.
|
|
431
|
+
|
|
432
|
+
`fit(resume_from=...)` calls it. It returns the callbacks' states, which the trainer hands back
|
|
433
|
+
to them once they have begun.
|
|
434
|
+
"""
|
|
435
|
+
path = Path(path)
|
|
436
|
+
if not path.is_file():
|
|
437
|
+
raise CheckpointError(f"no training state at {path}", path=str(path))
|
|
438
|
+
if self.optimization is None or self.runtime is None:
|
|
439
|
+
raise CheckpointError(
|
|
440
|
+
"load_state needs a fit that has built its optimizer; use fit(resume_from=...)"
|
|
441
|
+
)
|
|
442
|
+
payload = torch.load(path, map_location="cpu", weights_only=True)
|
|
443
|
+
if not isinstance(payload, dict) or payload.get("format") != STATE_FORMAT:
|
|
444
|
+
raise CheckpointError(f"{path} is not a torchstack64 training state", path=str(path))
|
|
445
|
+
if payload.get("version") != STATE_VERSION:
|
|
446
|
+
raise CheckpointError(
|
|
447
|
+
f"{path} has training-state version {payload.get('version')}, not {STATE_VERSION}"
|
|
448
|
+
)
|
|
449
|
+
try:
|
|
450
|
+
self.model.load_state_dict(payload["model"])
|
|
451
|
+
self.optimization.optimizer.load_state_dict(payload["optimizer"])
|
|
452
|
+
except (RuntimeError, ValueError, KeyError) as error:
|
|
453
|
+
raise CheckpointError(
|
|
454
|
+
f"{path} was saved from another model or optimizer ({payload.get('model_class')}): {error}",
|
|
455
|
+
path=str(path),
|
|
456
|
+
) from error
|
|
457
|
+
scheduler = self.optimization.scheduler
|
|
458
|
+
if (scheduler is None) != (payload["scheduler"] is None):
|
|
459
|
+
raise CheckpointError(f"{path} and this task disagree on having a learning-rate scheduler")
|
|
460
|
+
if scheduler is not None:
|
|
461
|
+
scheduler.load_state_dict(payload["scheduler"])
|
|
462
|
+
self.runtime.load_state_dict(payload["runtime"])
|
|
463
|
+
self.state.load_state_dict(
|
|
464
|
+
payload, device=self.runtime.device if self.config.keep_best == "device" else None
|
|
465
|
+
)
|
|
466
|
+
self._randomness.load_state_dict(payload["rng"])
|
|
467
|
+
logger.info("training state loaded from %s: resuming after epoch %d", path, self.state.epoch)
|
|
468
|
+
return dict(payload.get("callbacks") or {})
|
|
469
|
+
|
|
470
|
+
# -- the end of an epoch, and of the fit -------------------------------------------------------
|
|
471
|
+
|
|
472
|
+
def _close_epoch(
|
|
473
|
+
self,
|
|
474
|
+
epoch: int,
|
|
475
|
+
train_loss: float,
|
|
476
|
+
train_logs: Mapping[str, float],
|
|
477
|
+
evaluation: Evaluation | None,
|
|
478
|
+
seconds: float,
|
|
479
|
+
) -> EpochResult:
|
|
480
|
+
monitor = self.monitor
|
|
481
|
+
metrics: dict[str, float] = {"train_loss": train_loss}
|
|
482
|
+
metrics.update({f"train_{name}": value for name, value in train_logs.items()})
|
|
483
|
+
improved = False
|
|
484
|
+
if evaluation is not None:
|
|
485
|
+
if evaluation.loss is not None:
|
|
486
|
+
metrics["val_loss"] = evaluation.loss
|
|
487
|
+
metrics.update({f"val_{name}": value for name, value in evaluation.logs.items()})
|
|
488
|
+
if evaluation.score is not None:
|
|
489
|
+
metrics[monitor.name] = evaluation.score
|
|
490
|
+
improved = self._judge(epoch, evaluation)
|
|
491
|
+
metrics["lr"] = self.lr
|
|
492
|
+
self.state.history.entries.append({"epoch": float(epoch), **metrics, "seconds": seconds})
|
|
493
|
+
return EpochResult(
|
|
494
|
+
epoch=epoch,
|
|
495
|
+
metrics=metrics,
|
|
496
|
+
improved=improved,
|
|
497
|
+
patience=self.state.patience,
|
|
498
|
+
best=self.state.best,
|
|
499
|
+
seconds=seconds,
|
|
500
|
+
)
|
|
501
|
+
|
|
502
|
+
def _judge(self, epoch: int, evaluation: Evaluation) -> bool:
|
|
503
|
+
monitor = self.monitor
|
|
504
|
+
best = self.state.best
|
|
505
|
+
score = evaluation.score
|
|
506
|
+
if score is None or score != score or score in (float("inf"), float("-inf")):
|
|
507
|
+
self.request_stop(f"{monitor.name} is not a finite number ({score}): the training diverged")
|
|
508
|
+
return False
|
|
509
|
+
if monitor.improved(score, best.score if best is not None else None):
|
|
510
|
+
kept = Weights(self.model)
|
|
511
|
+
weights = kept.cpu_copy() if self.config.keep_best == "cpu" else kept.device_copy()
|
|
512
|
+
self.state.best = BestCheckpoint(epoch, score, weights, evaluation.predictions)
|
|
513
|
+
self.state.patience = 0
|
|
514
|
+
return True
|
|
515
|
+
self.state.patience += 1
|
|
516
|
+
patience = self.config.early_stopping_patience
|
|
517
|
+
if patience is not None and self.state.patience >= patience:
|
|
518
|
+
self.state.request_stop(
|
|
519
|
+
f"{monitor.name} did not improve for {patience} epochs", FitStatus.STOPPED_EARLY
|
|
520
|
+
)
|
|
521
|
+
return False
|
|
522
|
+
|
|
523
|
+
def _finish(self) -> FitResult:
|
|
524
|
+
failed = self.state.status in (FitStatus.FAILED, FitStatus.INTERRUPTED)
|
|
525
|
+
if self.state.best is not None:
|
|
526
|
+
try:
|
|
527
|
+
self.model.load_state_dict(self.state.best.state)
|
|
528
|
+
except Exception:
|
|
529
|
+
if not failed:
|
|
530
|
+
raise
|
|
531
|
+
logger.exception("could not restore the best epoch's weights after the fit failed")
|
|
532
|
+
self.optimization = None # the optimizer's state (two copies of the weights with Adam) is freed
|
|
533
|
+
seconds = self.state.seconds + time.perf_counter() - self._started
|
|
534
|
+
result = self.state.result(self.monitor.name, seconds, self.params)
|
|
535
|
+
errors = emit_all(self, Hook.TRAIN_END, result)
|
|
536
|
+
self._log_end(result)
|
|
537
|
+
if errors:
|
|
538
|
+
if failed:
|
|
539
|
+
for error in errors:
|
|
540
|
+
logger.error("a callback failed in on_train_end: %r", error, exc_info=error)
|
|
541
|
+
else:
|
|
542
|
+
raise errors[0]
|
|
543
|
+
return result
|
|
544
|
+
|
|
545
|
+
# -- logging -----------------------------------------------------------------------------------
|
|
546
|
+
|
|
547
|
+
def _log_start(self, validates: bool, resume_from: str | Path | None) -> None:
|
|
548
|
+
if not logger.isEnabledFor(logging.INFO):
|
|
549
|
+
return
|
|
550
|
+
assert self.runtime is not None and self.plan is not None
|
|
551
|
+
total, trainable = Weights(self.model).count()
|
|
552
|
+
logger.info(
|
|
553
|
+
"fit started%s: %s, %d epochs, %s optimization steps per epoch, %s, %s, accumulate %d, "
|
|
554
|
+
"%s parameters (%s trainable), %s, %d callbacks",
|
|
555
|
+
f" from epoch {self.state.epoch} ({resume_from})" if resume_from is not None else "",
|
|
556
|
+
type(self.model).__name__,
|
|
557
|
+
self.config.epochs,
|
|
558
|
+
self.plan.optimization_steps_per_epoch
|
|
559
|
+
if self.plan.optimization_steps_per_epoch is not None
|
|
560
|
+
else "unknown",
|
|
561
|
+
self.runtime.device,
|
|
562
|
+
self.runtime.precision,
|
|
563
|
+
self.config.accumulate,
|
|
564
|
+
f"{total:,}",
|
|
565
|
+
f"{trainable:,}",
|
|
566
|
+
f"monitoring {self.monitor.name}" if validates else "no validation",
|
|
567
|
+
len(self.callbacks),
|
|
568
|
+
)
|
|
569
|
+
|
|
570
|
+
def _log_end(self, result: FitResult) -> None:
|
|
571
|
+
best = (
|
|
572
|
+
f"best epoch {result.best_epoch} with {result.monitor}={result.best_score:.4g}"
|
|
573
|
+
if result.best_epoch is not None and result.best_score is not None
|
|
574
|
+
else "no best epoch"
|
|
575
|
+
)
|
|
576
|
+
level = logging.ERROR if result.status is FitStatus.FAILED else logging.INFO
|
|
577
|
+
logger.log(
|
|
578
|
+
level,
|
|
579
|
+
"fit %s after %d epochs (%d optimization steps) in %.1fs; %s%s",
|
|
580
|
+
result.status.value,
|
|
581
|
+
result.epochs_run,
|
|
582
|
+
result.optimization_steps,
|
|
583
|
+
result.seconds,
|
|
584
|
+
best,
|
|
585
|
+
f"; {result.stop_reason}" if result.stop_reason else "",
|
|
586
|
+
)
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""One trial, heard from inside its fit."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING, Any
|
|
6
|
+
|
|
7
|
+
from torchstack64.training.config import flatten_params
|
|
8
|
+
from torchstack64.training.results import EpochResult, FitStatus
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
import optuna
|
|
12
|
+
|
|
13
|
+
from torchstack64.training.trainer import Trainer
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class TrialCallback:
|
|
17
|
+
"""Says in the fit's parameters which trial it is, reports each epoch's score to the study, and stops
|
|
18
|
+
the fit when the study gives the trial up.
|
|
19
|
+
|
|
20
|
+
It stops it as any callback does, with a request: the epoch ends, the other callbacks hear it, and the
|
|
21
|
+
fit returns with the status `pruned`. The tuner tells Optuna afterwards.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __init__(self, trial: optuna.Trial) -> None:
|
|
25
|
+
self.trial = trial
|
|
26
|
+
|
|
27
|
+
def on_train_begin(self, trainer: Trainer[Any]) -> None:
|
|
28
|
+
# The task's and the loop's values are in the parameters already; the network's arguments are not.
|
|
29
|
+
arguments = {name: value for name, value in self.trial.params.items() if name.startswith("model.")}
|
|
30
|
+
trainer.params.update({"trial.number": self.trial.number, **flatten_params(arguments)})
|
|
31
|
+
|
|
32
|
+
def on_epoch_end(self, trainer: Trainer[Any], result: EpochResult) -> None:
|
|
33
|
+
name = trainer.monitor.name
|
|
34
|
+
score = result.metrics[name]
|
|
35
|
+
self.trial.report(score, step=result.epoch)
|
|
36
|
+
if self.trial.should_prune():
|
|
37
|
+
reason = f"pruned by Optuna at epoch {result.epoch} ({name}={score:.4g})"
|
|
38
|
+
trainer.state.request_stop(reason, FitStatus.PRUNED)
|