torchbase 0.2.0__tar.gz → 0.3.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: torchbase
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: A minimalist base for ML projects in PyTorch
5
5
  License-Expression: Apache-2.0
6
6
  License-File: LICENSE
@@ -13,6 +13,7 @@ Classifier: Programming Language :: Python :: 3.11
13
13
  Classifier: Programming Language :: Python :: 3.12
14
14
  Classifier: Programming Language :: Python :: 3.13
15
15
  Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Programming Language :: Python :: 3.15
16
17
  Requires-Dist: datasets
17
18
  Requires-Dist: numpy
18
19
  Requires-Dist: scikit-learn
@@ -285,6 +286,120 @@ For a custom whole-epoch metric, override `BaseMetricsClass.get_epoch_metric(nam
285
286
  with keyword-only `update`, `compute`, `reset`, `state_dict` and `load_state_dict` methods. Its state is checkpointed
286
287
  and resets at the start of its dataset's next epoch, not when resuming inside an epoch.
287
288
 
289
+ Set `config["session"]["max_grad_norm"] = 1.0` to clip dense gradients by their global L2 norm immediately before each
290
+ optimizer step. The limit must be a positive finite number and defaults to `None` (disabled). With clipping enabled,
291
+ TensorBoard shows the pre-clipping norm under `training/optimizer/grad_norm`, and a non-finite norm raises a
292
+ `RuntimeError` before the optimizer step. Use the same limit when resuming the run.
293
+
294
+ ### Learning-rate schedules
295
+
296
+ Scheduling is disabled by default. To enable it, override `init_scheduler()` and choose a cadence in the session config:
297
+
298
+ ```python
299
+ class ScheduledSession(MyTrainingSession):
300
+ def init_scheduler(self):
301
+ return torch.optim.lr_scheduler.StepLR(self.optimizer, step_size=5, gamma=0.5)
302
+
303
+ config["session"]["scheduler_interval"] = "epoch"
304
+ ```
305
+
306
+ Use `"update"` to step immediately after each optimizer update or `"epoch"` to step after all validation datasets
307
+ finish for an epoch. For `ReduceLROnPlateau`, use `"epoch"` and configure `scheduler_monitor` in the `session` section:
308
+
309
+ ```python
310
+ config["session"]["scheduler_monitor"] = {
311
+ "dataset": "valid", # name from ValidationDatasetsDict
312
+ "metric": "loss",
313
+ "aggregation": "batch_mean",
314
+ }
315
+ ```
316
+
317
+ `"batch_mean"` selects the sample-weighted mean of mini-batch values, including loss. `"epoch"` selects the result of
318
+ a registered whole-epoch metric. TensorBoard logs each group's learning rate after the scheduler step, under
319
+ `training/optimizer/lr_group_0`, `training/optimizer/lr_group_1`, and so on. The step axis counts optimizer updates
320
+ or completed epochs according to the configured cadence.
321
+
322
+ Checkpoints restore the scheduler, optimizer, and update count together. Use the same scheduler setup, cadence, and
323
+ monitor when resuming, including any callables used by the scheduler. To apply a new schedule to existing weights,
324
+ start a fresh run from those weights.
325
+
326
+ ### Gradient accumulation
327
+
328
+ Set `config["session"]["accumulation_steps"] = 4` to collect gradients from up to four training mini-batches before
329
+ each optimizer update. The setting must be a positive integer and defaults to `1`, which updates on every mini-batch.
330
+ The session also updates on any remaining mini-batches before validation. Gradient clipping and update-based learning-rate
331
+ schedules run once per optimizer update. Training loss and metrics still describe each mini-batch.
332
+
333
+ Use a scalar loss that is the mean of equally weighted per-sample losses. Each mini-batch contributes in proportion to
334
+ its sample count, including when batch sizes differ or the last window is short. Token- or mask-normalized losses with
335
+ varying denominators need a training loop with an explicit normalizer. BatchNorm, batch-dependent losses, and stochastic
336
+ operations can produce different results from a single forward pass over the combined batch.
337
+
338
+ `checkpoint_interval` still counts mini-batches. An in-window checkpoint stores pending optimizer gradients and the
339
+ window's mini-batch and sample counts. With dense gradients this can add roughly the size of one gradient tensor per
340
+ optimizer parameter. Resume with the same `accumulation_steps` and optimizer parameter groups.
341
+
342
+ ### Numerical debugging
343
+
344
+ In a typical deep learning experiment, the loss can suddenly become `NaN` or infinite. To track down the cause, you
345
+ may want to catch the first mini-batch with an invalid loss or gradient and see whether the problem recurs in a short
346
+ run. `torchbase` provides a debug mode for these checks.
347
+
348
+ Set `config["session"]["debug"] = {}` to check training and validation losses for NaN and infinity. Debug mode also
349
+ checks parameters' gradient buffers after every backward pass, even inside a gradient accumulation window. Validation
350
+ checks any gradients already present and runs its usual forward pass without calculating new gradients. Failures report
351
+ the phase, epoch, mini-batch, and value or parameter that failed the check.
352
+
353
+ - Set `check_inputs`, `check_outputs`, or `check_parameters` to `True` in the `debug` dictionary for extra finite-value
354
+ checks. Parameter checks run before the forward pass and after each optimizer update. Leave the input and output
355
+ checks disabled when those tensors deliberately contain values such as `-inf` attention masks.
356
+ - Set `anomaly_detection` to `True` to enable PyTorch autograd anomaly detection during the training forward and
357
+ backward passes. It can show the forward traceback for a failing backward operation. Detection slows training and
358
+ only covers errors PyTorch's autograd can trace. [PyTorch autograd docs](https://docs.pytorch.org/docs/stable/autograd.html#debugging-and-anomaly-detection)
359
+ - Set `deterministic` to `True` to require PyTorch deterministic algorithms during session setup and training. Fresh
360
+ runs seed Python, NumPy, and PyTorch once with `seed` (default `0` in deterministic mode). You can also set `seed`
361
+ without enabling strict algorithms. Resuming uses the saved RNG states as usual. PyTorch may require extra backend
362
+ configuration for some operations, and reproducibility depends on the environment. [PyTorch reproducibility docs](https://docs.pytorch.org/docs/stable/notes/randomness.html)
363
+
364
+ For a short diagnostic run, set one of these options in `debug`:
365
+
366
+ - `{"max_batches": 2}` runs one training pass and one pass per validation dataset, each capped at two mini-batches.
367
+ - `{"overfit_batches": 20}` repeats the first collated training batch 20 times. The count is in mini-batches, so accumulation
368
+ can reduce the number of optimizer updates. Fixed-batch runs skip validation and epoch-based scheduling.
369
+
370
+ Both modes require `create_run_dir_afresh=True`. They log to a fresh `debug`-marked directory and skip checkpoint and
371
+ best-model writes. To start from production weights, pass the production run's `source_run_dir_tag`. Full debug runs
372
+ without either limit use normal checkpointing and can resume in place.
373
+
374
+ ### Capturing and replaying a failed training batch
375
+
376
+ Set `config["session"]["debug"]["capture_failure"] = True` to keep a snapshot before each training mini-batch's
377
+ forward pass. If the iteration raises an exception, torchbase writes an artifact under `failures/` in that run
378
+ and reports its path. The last recovery checkpoint remains available for normal resumption.
379
+
380
+ Call `replay_failure()` on the training subclass you used for the run:
381
+
382
+ ```python
383
+ MyTrainingSession.replay_failure("path/to/run/failures/training-<id>.pth", runs_parent_dir="replays")
384
+ ```
385
+
386
+ Replay runs that one mini-batch in a fresh directory with the saved debug settings. It restores the collated batch,
387
+ model parameters and buffers, optimizer and scheduler state, pending gradients, progress, and the RNG states from
388
+ before the forward pass. The original seed describes the starting RNG sequence. A later failure can happen after
389
+ many draws and in-place mutations, so the seed or the RNG state saved after the failure is insufficient to recreate it.
390
+
391
+ Capture defaults to disabled. It serializes the batch and state into memory on every training mini-batch, which adds
392
+ memory and processing overhead. A failure also incurs a disk write. Artifacts contain the actual batch and model
393
+ state. Replay covers single-process CPU or CUDA sessions and requires the same session subclass, compatible code and
394
+ data, and the same PyTorch version and device.
395
+ Batch and state values must be compatible with PyTorch's `weights_only=True` loader, such as ordinary tensors and
396
+ Python containers. Use `prepare(session)` to reinstall experiment-owned hooks, Python state, or custom RNG generators
397
+ before replay. The replay boundary is the base training iteration after collation, including forward, loss, backward,
398
+ and any update in that iteration. Loader failures, validation, final epoch flushes, and nondeterministic or external
399
+ effects are outside this boundary.
400
+
401
+ ### Resuming a run
402
+
288
403
  For various reasons, you may sometimes want to suspend the training process before it is finalized. `torchbase` provides
289
404
  you with the possibility to take over from the latest saved iteration of a past experiment, whether it was training
290
405
  or validating:
@@ -260,6 +260,120 @@ For a custom whole-epoch metric, override `BaseMetricsClass.get_epoch_metric(nam
260
260
  with keyword-only `update`, `compute`, `reset`, `state_dict` and `load_state_dict` methods. Its state is checkpointed
261
261
  and resets at the start of its dataset's next epoch, not when resuming inside an epoch.
262
262
 
263
+ Set `config["session"]["max_grad_norm"] = 1.0` to clip dense gradients by their global L2 norm immediately before each
264
+ optimizer step. The limit must be a positive finite number and defaults to `None` (disabled). With clipping enabled,
265
+ TensorBoard shows the pre-clipping norm under `training/optimizer/grad_norm`, and a non-finite norm raises a
266
+ `RuntimeError` before the optimizer step. Use the same limit when resuming the run.
267
+
268
+ ### Learning-rate schedules
269
+
270
+ Scheduling is disabled by default. To enable it, override `init_scheduler()` and choose a cadence in the session config:
271
+
272
+ ```python
273
+ class ScheduledSession(MyTrainingSession):
274
+ def init_scheduler(self):
275
+ return torch.optim.lr_scheduler.StepLR(self.optimizer, step_size=5, gamma=0.5)
276
+
277
+ config["session"]["scheduler_interval"] = "epoch"
278
+ ```
279
+
280
+ Use `"update"` to step immediately after each optimizer update or `"epoch"` to step after all validation datasets
281
+ finish for an epoch. For `ReduceLROnPlateau`, use `"epoch"` and configure `scheduler_monitor` in the `session` section:
282
+
283
+ ```python
284
+ config["session"]["scheduler_monitor"] = {
285
+ "dataset": "valid", # name from ValidationDatasetsDict
286
+ "metric": "loss",
287
+ "aggregation": "batch_mean",
288
+ }
289
+ ```
290
+
291
+ `"batch_mean"` selects the sample-weighted mean of mini-batch values, including loss. `"epoch"` selects the result of
292
+ a registered whole-epoch metric. TensorBoard logs each group's learning rate after the scheduler step, under
293
+ `training/optimizer/lr_group_0`, `training/optimizer/lr_group_1`, and so on. The step axis counts optimizer updates
294
+ or completed epochs according to the configured cadence.
295
+
296
+ Checkpoints restore the scheduler, optimizer, and update count together. Use the same scheduler setup, cadence, and
297
+ monitor when resuming, including any callables used by the scheduler. To apply a new schedule to existing weights,
298
+ start a fresh run from those weights.
299
+
300
+ ### Gradient accumulation
301
+
302
+ Set `config["session"]["accumulation_steps"] = 4` to collect gradients from up to four training mini-batches before
303
+ each optimizer update. The setting must be a positive integer and defaults to `1`, which updates on every mini-batch.
304
+ The session also updates on any remaining mini-batches before validation. Gradient clipping and update-based learning-rate
305
+ schedules run once per optimizer update. Training loss and metrics still describe each mini-batch.
306
+
307
+ Use a scalar loss that is the mean of equally weighted per-sample losses. Each mini-batch contributes in proportion to
308
+ its sample count, including when batch sizes differ or the last window is short. Token- or mask-normalized losses with
309
+ varying denominators need a training loop with an explicit normalizer. BatchNorm, batch-dependent losses, and stochastic
310
+ operations can produce different results from a single forward pass over the combined batch.
311
+
312
+ `checkpoint_interval` still counts mini-batches. An in-window checkpoint stores pending optimizer gradients and the
313
+ window's mini-batch and sample counts. With dense gradients this can add roughly the size of one gradient tensor per
314
+ optimizer parameter. Resume with the same `accumulation_steps` and optimizer parameter groups.
315
+
316
+ ### Numerical debugging
317
+
318
+ In a typical deep learning experiment, the loss can suddenly become `NaN` or infinite. To track down the cause, you
319
+ may want to catch the first mini-batch with an invalid loss or gradient and see whether the problem recurs in a short
320
+ run. `torchbase` provides a debug mode for these checks.
321
+
322
+ Set `config["session"]["debug"] = {}` to check training and validation losses for NaN and infinity. Debug mode also
323
+ checks parameters' gradient buffers after every backward pass, even inside a gradient accumulation window. Validation
324
+ checks any gradients already present and runs its usual forward pass without calculating new gradients. Failures report
325
+ the phase, epoch, mini-batch, and value or parameter that failed the check.
326
+
327
+ - Set `check_inputs`, `check_outputs`, or `check_parameters` to `True` in the `debug` dictionary for extra finite-value
328
+ checks. Parameter checks run before the forward pass and after each optimizer update. Leave the input and output
329
+ checks disabled when those tensors deliberately contain values such as `-inf` attention masks.
330
+ - Set `anomaly_detection` to `True` to enable PyTorch autograd anomaly detection during the training forward and
331
+ backward passes. It can show the forward traceback for a failing backward operation. Detection slows training and
332
+ only covers errors PyTorch's autograd can trace. [PyTorch autograd docs](https://docs.pytorch.org/docs/stable/autograd.html#debugging-and-anomaly-detection)
333
+ - Set `deterministic` to `True` to require PyTorch deterministic algorithms during session setup and training. Fresh
334
+ runs seed Python, NumPy, and PyTorch once with `seed` (default `0` in deterministic mode). You can also set `seed`
335
+ without enabling strict algorithms. Resuming uses the saved RNG states as usual. PyTorch may require extra backend
336
+ configuration for some operations, and reproducibility depends on the environment. [PyTorch reproducibility docs](https://docs.pytorch.org/docs/stable/notes/randomness.html)
337
+
338
+ For a short diagnostic run, set one of these options in `debug`:
339
+
340
+ - `{"max_batches": 2}` runs one training pass and one pass per validation dataset, each capped at two mini-batches.
341
+ - `{"overfit_batches": 20}` repeats the first collated training batch 20 times. The count is in mini-batches, so accumulation
342
+ can reduce the number of optimizer updates. Fixed-batch runs skip validation and epoch-based scheduling.
343
+
344
+ Both modes require `create_run_dir_afresh=True`. They log to a fresh `debug`-marked directory and skip checkpoint and
345
+ best-model writes. To start from production weights, pass the production run's `source_run_dir_tag`. Full debug runs
346
+ without either limit use normal checkpointing and can resume in place.
347
+
348
+ ### Capturing and replaying a failed training batch
349
+
350
+ Set `config["session"]["debug"]["capture_failure"] = True` to keep a snapshot before each training mini-batch's
351
+ forward pass. If the iteration raises an exception, torchbase writes an artifact under `failures/` in that run
352
+ and reports its path. The last recovery checkpoint remains available for normal resumption.
353
+
354
+ Call `replay_failure()` on the training subclass you used for the run:
355
+
356
+ ```python
357
+ MyTrainingSession.replay_failure("path/to/run/failures/training-<id>.pth", runs_parent_dir="replays")
358
+ ```
359
+
360
+ Replay runs that one mini-batch in a fresh directory with the saved debug settings. It restores the collated batch,
361
+ model parameters and buffers, optimizer and scheduler state, pending gradients, progress, and the RNG states from
362
+ before the forward pass. The original seed describes the starting RNG sequence. A later failure can happen after
363
+ many draws and in-place mutations, so the seed or the RNG state saved after the failure is insufficient to recreate it.
364
+
365
+ Capture defaults to disabled. It serializes the batch and state into memory on every training mini-batch, which adds
366
+ memory and processing overhead. A failure also incurs a disk write. Artifacts contain the actual batch and model
367
+ state. Replay covers single-process CPU or CUDA sessions and requires the same session subclass, compatible code and
368
+ data, and the same PyTorch version and device.
369
+ Batch and state values must be compatible with PyTorch's `weights_only=True` loader, such as ordinary tensors and
370
+ Python containers. Use `prepare(session)` to reinstall experiment-owned hooks, Python state, or custom RNG generators
371
+ before replay. The replay boundary is the base training iteration after collation, including forward, loss, backward,
372
+ and any update in that iteration. Loader failures, validation, final epoch flushes, and nondeterministic or external
373
+ effects are outside this boundary.
374
+
375
+ ### Resuming a run
376
+
263
377
  For various reasons, you may sometimes want to suspend the training process before it is finalized. `torchbase` provides
264
378
  you with the possibility to take over from the latest saved iteration of a past experiment, whether it was training
265
379
  or validating:
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "torchbase"
3
- version = "0.2.0"
3
+ version = "0.3.0"
4
4
  description = "A minimalist base for ML projects in PyTorch"
5
5
  authors = [{ name = "Sohrab Ferdowsi", email = "sohrab.ferdowsi@gmail.com" }]
6
6
  license = "Apache-2.0"
@@ -5,9 +5,12 @@ from torchbase.utils.data import ValidationDatasetsDict
5
5
  from torchbase.utils.metrics import BaseMetricsClass, _keyword_arguments
6
6
  from torchbase.utils.logger import ProgressManager, ValuesLogger, LoggableParams
7
7
  from torchbase.utils.checkpoint import atomic_torch_save
8
+ from torchbase.utils.debug import check_finite
9
+ from torchbase.utils.failure import capture_training_failure, replay_training_failure
8
10
 
9
11
  import numpy as np
10
12
  import torch
13
+ from torch.optim.lr_scheduler import LRScheduler, ReduceLROnPlateau
11
14
  from torch.utils.tensorboard import SummaryWriter
12
15
  from torchdata.stateful_dataloader import StatefulDataLoader
13
16
  from torch.utils.data import Dataset as TorchDataset
@@ -15,11 +18,16 @@ from torch.utils.data import Dataset as TorchDataset
15
18
  from datasets import Dataset
16
19
 
17
20
  from abc import ABC, abstractmethod
21
+ from contextlib import nullcontext
22
+ from copy import deepcopy
23
+ from itertools import islice
18
24
  from typing import Dict, List, Tuple, Any, Callable
25
+ from uuid import uuid4
19
26
  import os
20
27
  import random
21
28
  import json
22
29
  import shutil
30
+ import sys
23
31
 
24
32
  SAVED_NETWORK_NAME = "network.pth"
25
33
  SAVED_RNG_NAME = "rng_states.json"
@@ -35,12 +43,41 @@ class TrainingBaseSession(ABC):
35
43
  tag_postfix: None | str = None):
36
44
 
37
45
  self.config_session, self.config_data, self.config_metrics, self.config_network = self.setup_configs(config)
46
+ debug = self.config_session.debug
47
+ if (debug is not None and debug.capture_failure
48
+ and torch.device(self.config_session.device_name).type not in ("cpu", "cuda")):
49
+ raise ValueError("Failure capture requires a CPU or CUDA session.")
50
+ if self._bounded_debug:
51
+ if not create_run_dir_afresh:
52
+ raise ValueError("A bounded debug run requires create_run_dir_afresh=True.")
53
+ if tag_postfix is not None and not isinstance(tag_postfix, str):
54
+ raise TypeError("tag_postfix must be a string.")
55
+ suffix = f"_{tag_postfix}" if tag_postfix else ""
56
+ tag_postfix = f"debug-{uuid4().hex[:8]}{suffix}"
57
+ with self._debug_execution():
58
+ self._initialize_run(runs_parent_dir, create_run_dir_afresh, source_run_dir_tag, tag_postfix)
59
+
60
+ @property
61
+ def _bounded_debug(self) -> bool:
62
+ debug = self.config_session.debug
63
+ return debug is not None and debug.bounded
64
+
65
+ def _debug_execution(self):
66
+ debug = self.config_session.debug
67
+ return nullcontext() if debug is None else debug.execution(self.config_session.device_name)
68
+
69
+ def _initialize_run(self, runs_parent_dir: str | None, create_run_dir_afresh: bool,
70
+ source_run_dir_tag: str | None, tag_postfix: str | None) -> None:
38
71
  self.run_dir = self.setup_run_dir_for_logging(runs_parent_dir,
39
72
  create_run_dir_afresh,
40
73
  source_run_dir_tag,
41
74
  tag_postfix)
42
75
 
76
+ if create_run_dir_afresh and self.config_session.debug is not None:
77
+ self.config_session.debug.seed_fresh_run()
43
78
  self.configure_states_dir_and_randomness_sources(self.run_dir, create_run_dir_afresh)
79
+ if self.config_session.debug is not None and self.config_session.debug.capture_failure:
80
+ self._failure_setup_rng = RandomnessGeneratorStates().to_dict()
44
81
  self.save_config_to_run_dir(create_run_dir_afresh)
45
82
 
46
83
  self.device = torch.device(self.config_session.device_name) # TODO
@@ -53,6 +90,12 @@ class TrainingBaseSession(ABC):
53
90
  self.network = self._init_network()
54
91
 
55
92
  self.optimizer = self.init_optimizer()
93
+ self.scheduler = self._init_scheduler()
94
+ self.optimizer_updates = 0
95
+ self._accumulated_batches = 0
96
+ self._accumulated_samples = 0
97
+ if self.config_session.accumulation_steps > 1:
98
+ self.optimizer.zero_grad(set_to_none=True)
56
99
 
57
100
  self._loaded_checkpoint = None
58
101
  self.best_model_epoch = None
@@ -97,14 +140,15 @@ class TrainingBaseSession(ABC):
97
140
 
98
141
  self.hparams_dict = self.init_hparams_dict()
99
142
 
100
- if not create_run_dir_afresh:
101
- try:
143
+ try:
144
+ self._validate_scheduler_monitor()
145
+ if not create_run_dir_afresh:
102
146
  # Initialization consumes randomness while rebuilding data and
103
147
  # the network. Restore continuation randomness only afterwards.
104
148
  self._restore_training_state()
105
- except Exception:
106
- self.writer.close()
107
- raise
149
+ except Exception:
150
+ self.writer.close()
151
+ raise
108
152
  self._loaded_checkpoint = None
109
153
 
110
154
  @staticmethod
@@ -213,20 +257,22 @@ class TrainingBaseSession(ABC):
213
257
  rng = RandomnessGeneratorStates.load(os.path.join(states_dir, SAVED_RNG_NAME))
214
258
  rng.apply()
215
259
 
216
- def save_config_to_run_dir(self, create_run_dir_afresh: bool) -> None:
217
- config = {
260
+ def _config_dict(self) -> dict:
261
+ return {
218
262
  "session": self.config_session.to_dict(),
219
263
  "data": self.config_data,
220
264
  "metrics": self.config_metrics,
221
265
  "network": self.config_network
222
266
  }
267
+
268
+ def save_config_to_run_dir(self, create_run_dir_afresh: bool) -> None:
223
269
  if create_run_dir_afresh:
224
270
  _postfix = ""
225
271
  else:
226
272
  _postfix = "_{}".format(generate_log_dir_tag(None))
227
273
 
228
274
  with open(os.path.join(self.run_dir, "config{}.json".format(_postfix)), "w") as file:
229
- json.dump(config, file, indent=2)
275
+ json.dump(self._config_dict(), file, indent=2)
230
276
 
231
277
  @abstractmethod
232
278
  def init_datasets(self) -> Tuple[Dataset, ValidationDatasetsDict]:
@@ -290,6 +336,68 @@ class TrainingBaseSession(ABC):
290
336
 
291
337
  return optimizer
292
338
 
339
+ def init_scheduler(self) -> LRScheduler | None:
340
+ """Return an optional native PyTorch scheduler bound to self.optimizer."""
341
+ return None
342
+
343
+ def _init_scheduler(self) -> LRScheduler | None:
344
+ scheduler = self.init_scheduler()
345
+ interval = self.config_session.scheduler_interval
346
+ monitor = self.config_session.scheduler_monitor
347
+ if (scheduler is None) != (interval is None):
348
+ raise ValueError("An init_scheduler() result and scheduler_interval must be supplied together.")
349
+ if scheduler is not None:
350
+ if not isinstance(scheduler, LRScheduler) or scheduler.optimizer is not self.optimizer:
351
+ raise ValueError("init_scheduler() must return a PyTorch LRScheduler bound to self.optimizer.")
352
+ if isinstance(scheduler, ReduceLROnPlateau) != (monitor is not None):
353
+ raise ValueError("scheduler_monitor is required for ReduceLROnPlateau and allowed only for it.")
354
+ return scheduler
355
+
356
+ def _validate_scheduler_monitor(self) -> None:
357
+ monitor = self.config_session.scheduler_monitor
358
+ if monitor is not None:
359
+ dataset, metric = monitor["dataset"], monitor["metric"]
360
+ if dataset not in self.value_logger_valid_dict:
361
+ raise ValueError(f"scheduler_monitor refers to an unknown validation dataset: {dataset!r}.")
362
+ logger = self.value_logger_valid_dict[dataset]
363
+ available = logger.epoch_metrics if monitor["aggregation"] == "epoch" else logger.average_of_epoch
364
+ if metric not in available:
365
+ raise ValueError(f"scheduler_monitor metric {metric!r} is unavailable with "
366
+ f"{monitor['aggregation']!r} aggregation for validation dataset {dataset!r}.")
367
+
368
+ def _scheduler_settings(self) -> dict | None:
369
+ if self.scheduler is None:
370
+ return None
371
+ scheduler_type = type(self.scheduler)
372
+ return {"type": f"{scheduler_type.__module__}.{scheduler_type.__qualname__}",
373
+ "interval": self.config_session.scheduler_interval, "monitor": self.config_session.scheduler_monitor}
374
+
375
+ def _optimizer_state(self) -> dict:
376
+ return {"optimizer": self.optimizer.state_dict(), "optimizer_updates": self.optimizer_updates,
377
+ "scheduler": (None if self.scheduler is None else
378
+ {"settings": self._scheduler_settings(), "state": self.scheduler.state_dict()})}
379
+
380
+ def _restore_scheduler(self, checkpoint: dict) -> None:
381
+ if self.scheduler is None and "scheduler" not in checkpoint and "optimizer_updates" not in checkpoint:
382
+ # Checkpoints predating schedulers used one optimizer update per training mini-batch.
383
+ updates = checkpoint["progress_train"]["iter_total"]
384
+ else:
385
+ if "scheduler" not in checkpoint or "optimizer_updates" not in checkpoint:
386
+ raise ValueError("Invalid checkpoint: required scheduling state is missing.")
387
+ updates = checkpoint["optimizer_updates"]
388
+ saved = checkpoint["scheduler"]
389
+ if self.scheduler is not None:
390
+ if (not isinstance(saved, dict) or saved.get("settings") != self._scheduler_settings()
391
+ or not isinstance(saved.get("state"), dict)
392
+ or not self.scheduler.state_dict().keys() <= saved["state"].keys()):
393
+ raise ValueError("Checkpoint scheduler type, settings or state do not match the current session.")
394
+ self.scheduler.load_state_dict(saved["state"])
395
+ elif saved is not None:
396
+ raise ValueError("Checkpoint scheduler does not match the current session without a scheduler.")
397
+ if type(updates) is not int or updates < 0:
398
+ raise ValueError("Invalid checkpoint optimizer update count.")
399
+ self.optimizer_updates = updates
400
+
293
401
  def load_network_and_optimizer_states_if_relevant(self, source_run_dir_tag: None | str,
294
402
  create_run_dir_afresh: bool) -> None:
295
403
  if source_run_dir_tag is None:
@@ -307,6 +415,8 @@ class TrainingBaseSession(ABC):
307
415
  raise ValueError("Invalid checkpoint: required training state is missing.")
308
416
  self.network.load_state_dict(checkpoint["network"])
309
417
  if not create_run_dir_afresh:
418
+ # The scheduler is constructed and restored before loading the optimizer's saved learning rates.
419
+ self._restore_scheduler(checkpoint)
310
420
  self.optimizer.load_state_dict(checkpoint["optimizer"])
311
421
  self._loaded_checkpoint = checkpoint
312
422
 
@@ -329,12 +439,45 @@ class TrainingBaseSession(ABC):
329
439
  self.progress_valid_dict[name])
330
440
  self._phase = checkpoint["phase"]
331
441
  self._validation_index = checkpoint["validation_index"]
442
+ self._restore_accumulation(checkpoint)
332
443
  self._check_loop_state()
333
444
  self.best_model_epoch = checkpoint["best_model_epoch"]
334
445
  if checkpoint["best_model"] is not None:
335
446
  atomic_torch_save(checkpoint["best_model"], os.path.join(self.run_dir, SAVED_NETWORK_NAME))
336
447
  RandomnessGeneratorStates.from_dict(checkpoint["rng_state"]).apply()
337
448
 
449
+ def _optimizer_parameters(self) -> list[torch.Tensor]:
450
+ return list(dict.fromkeys(parameter for group in self.optimizer.param_groups for parameter in group["params"]))
451
+
452
+ def _restore_accumulation(self, checkpoint: dict) -> None:
453
+ steps = self.config_session.accumulation_steps
454
+ if steps == 1 and "accumulation" not in checkpoint:
455
+ return
456
+ state = checkpoint.get("accumulation")
457
+ if (steps == 1 or not isinstance(state, dict)
458
+ or not {"steps", "batches", "samples", "gradients"} <= state.keys()
459
+ or type(state["steps"]) is not int or state["steps"] != steps):
460
+ raise ValueError("Checkpoint accumulation state does not match the configured accumulation_steps.")
461
+
462
+ batches, samples, gradients = state["batches"], state["samples"], state["gradients"]
463
+ if type(batches) is not int or type(samples) is not int:
464
+ raise ValueError("Invalid checkpoint accumulation progress.")
465
+ self._accumulated_batches = batches
466
+ self._accumulated_samples = samples
467
+ if batches == 0:
468
+ if gradients is not None:
469
+ raise ValueError("Invalid checkpoint gradients for an empty accumulation window.")
470
+ return
471
+
472
+ parameters = self._optimizer_parameters()
473
+ if not isinstance(gradients, list) or len(gradients) != len(parameters):
474
+ raise ValueError("Invalid checkpoint gradients for the optimizer parameters.")
475
+ for parameter, gradient in zip(parameters, gradients):
476
+ if gradient is not None and (not isinstance(gradient, torch.Tensor)
477
+ or gradient.shape != parameter.shape or gradient.dtype != parameter.dtype):
478
+ raise ValueError("A checkpoint gradient does not match its optimizer parameter.")
479
+ parameter.grad = None if gradient is None else gradient.to(parameter.device)
480
+
338
481
  @staticmethod
339
482
  def _dataloader_settings(loader) -> Dict:
340
483
  if not isinstance(loader, StatefulDataLoader) or loader.generator is None or not loader.in_order:
@@ -388,6 +531,11 @@ class TrainingBaseSession(ABC):
388
531
  if self._phase != "training" and (epoch == 0 or self.progress_train.iter_current_epoch != 0
389
532
  or self.progress_train.samples_current_epoch != 0):
390
533
  raise ValueError("Inconsistent checkpoint training progress.")
534
+ batches, samples = self._accumulated_batches, self._accumulated_samples
535
+ if (batches != self.progress_train.iter_current_epoch % self.config_session.accumulation_steps
536
+ or (samples == 0) != (batches == 0)
537
+ or not batches <= samples <= self.progress_train.samples_current_epoch):
538
+ raise ValueError("Inconsistent checkpoint accumulation progress.")
391
539
  for ind, name in enumerate(self.datasets_valid_dict.names):
392
540
  progress = self.progress_valid_dict[name]
393
541
  expected_epoch = epoch - int(self._phase == "validation" and ind >= index)
@@ -420,7 +568,7 @@ class TrainingBaseSession(ABC):
420
568
  "validation_index": self._validation_index,
421
569
  "validation_names": list(self.datasets_valid_dict.names),
422
570
  "network": network_state,
423
- "optimizer": self.optimizer.state_dict(),
571
+ **self._optimizer_state(),
424
572
  "progress_train": self.progress_train.state_dict(),
425
573
  "values_logger_train": self.value_logger_train.state_dict(),
426
574
  "dataloader_train": self._dataloader_state(self.dataloader_train, self.progress_train),
@@ -434,6 +582,13 @@ class TrainingBaseSession(ABC):
434
582
  "best_model_epoch": best_model_epoch,
435
583
  "rng_state": RandomnessGeneratorStates().to_dict(),
436
584
  }
585
+ if self.config_session.accumulation_steps > 1:
586
+ gradients = None
587
+ if self._accumulated_batches:
588
+ gradients = [parameter.grad for parameter in self._optimizer_parameters()]
589
+ checkpoint["accumulation"] = {"steps": self.config_session.accumulation_steps,
590
+ "batches": self._accumulated_batches, "samples": self._accumulated_samples,
591
+ "gradients": gradients}
437
592
  atomic_torch_save(checkpoint, checkpoint_path)
438
593
  self.best_model_epoch = best_model_epoch
439
594
  if is_best:
@@ -541,17 +696,135 @@ class TrainingBaseSession(ABC):
541
696
 
542
697
  return mini_batch_size
543
698
 
699
+ def _step_scheduler(self, step: int) -> None:
700
+ monitor = self.config_session.scheduler_monitor
701
+ if monitor is None:
702
+ self.scheduler.step()
703
+ else:
704
+ logger = self.value_logger_valid_dict[monitor["dataset"]]
705
+ values = logger.epoch_values if monitor["aggregation"] == "epoch" else logger.average_of_epoch
706
+ self.scheduler.step(values[monitor["metric"]])
707
+ for index, group in enumerate(self.optimizer.param_groups):
708
+ self.writer.add_scalar(f"training/optimizer/lr_group_{index}", group["lr"], step)
709
+
710
+ def _batch_location(self, valid_dataset_name: str | None = None, *, offset: int = 1) -> str:
711
+ if valid_dataset_name is None:
712
+ phase, progress = "training", self.progress_train
713
+ else:
714
+ phase, progress = f"validation {valid_dataset_name!r}", self.progress_valid_dict[valid_dataset_name]
715
+ return f"{phase}, epoch {progress.epoch + 1}, mini-batch {progress.iter_current_epoch + offset}"
716
+
717
+ def _check_debug_parameters(self, location: str, *, gradients: bool = False) -> None:
718
+ parameters = {param: name for name, param in self.network.named_parameters()}
719
+ for index, param in enumerate(self._optimizer_parameters()):
720
+ parameters.setdefault(param, f"optimizer parameter {index}")
721
+ for param, name in parameters.items():
722
+ if gradients:
723
+ check_finite(param.grad, location, f"gradient for {name!r}")
724
+ else:
725
+ check_finite(param, location, f"parameter {name!r}")
726
+
727
+ def _forward_pass_checked(self, mini_batch, location):
728
+ debug = self.config_session.debug
729
+ if debug is None:
730
+ return self.forward_pass(mini_batch)
731
+ if debug.check_parameters:
732
+ self._check_debug_parameters(location)
733
+ if debug.check_inputs:
734
+ check_finite(mini_batch, location, "input")
735
+ try:
736
+ outputs = self.forward_pass(mini_batch)
737
+ except RuntimeError as error:
738
+ raise RuntimeError(f"{location}: forward failed: {error}") from error
739
+ if debug.check_outputs:
740
+ check_finite(outputs, location, "output")
741
+ return outputs
742
+
743
+ def _backward_checked(self, loss, location):
744
+ debug = self.config_session.debug
745
+ if debug is None:
746
+ loss.backward()
747
+ return
748
+ try:
749
+ loss.backward()
750
+ except RuntimeError as error:
751
+ raise RuntimeError(f"{location}: backward failed: {error}") from error
752
+ self._check_debug_parameters(location, gradients=True)
753
+
754
+ def _step_optimizer(self, location: str) -> None:
755
+ debug = self.config_session.debug
756
+ grad_norm = None
757
+ if self.config_session.max_grad_norm is not None:
758
+ try:
759
+ grad_norm = torch.nn.utils.clip_grad_norm_(self._optimizer_parameters(),
760
+ self.config_session.max_grad_norm, error_if_nonfinite=True)
761
+ except RuntimeError as error:
762
+ if debug is None:
763
+ raise
764
+ raise RuntimeError(f"{location}: gradient clipping failed: {error}") from error
765
+ self.optimizer.step()
766
+ if debug is not None and debug.check_parameters:
767
+ self._check_debug_parameters(location)
768
+ self.optimizer_updates += 1
769
+ if self.config_session.scheduler_interval == "update":
770
+ self._step_scheduler(self.optimizer_updates)
771
+ if grad_norm is not None:
772
+ self.writer.add_scalar("training/optimizer/grad_norm", grad_norm, self.optimizer_updates)
773
+
774
+ def _finish_accumulation(self, location: str) -> None:
775
+ with torch.no_grad():
776
+ for parameter in self._optimizer_parameters():
777
+ if parameter.grad is not None:
778
+ parameter.grad.div_(self._accumulated_samples)
779
+ if self.config_session.debug is not None:
780
+ self._check_debug_parameters(location, gradients=True)
781
+ self._step_optimizer(location)
782
+ self.optimizer.zero_grad(set_to_none=True)
783
+ self._accumulated_batches = 0
784
+ self._accumulated_samples = 0
785
+
544
786
  def do_one_training_iteration(self, mini_batch: Dict[str, Any | torch.Tensor]) -> None:
545
- self.network.train()
546
- outs_dict = self.forward_pass(mini_batch)
547
- loss = self.loss_function(**_keyword_arguments(self.loss_function, outs_dict))
548
- assert not torch.isnan(loss), "A NaN value detected during loss function evaluation."
787
+ debug = self.config_session.debug
788
+ if debug is not None and debug.capture_failure:
789
+ with capture_training_failure(self, mini_batch):
790
+ self._run_training_iteration(mini_batch)
791
+ else:
792
+ self._run_training_iteration(mini_batch)
549
793
 
550
- self.optimizer.zero_grad()
551
- loss.backward()
552
- # TODO: torch.nn.utils.clip_grad_norm_(self.network.parameters(), max_norm=1.0)
553
- self.optimizer.step()
554
- self.progress_train.increment_iter(self.infer_mini_batch_size(mini_batch))
794
+ @classmethod
795
+ def replay_failure(cls, artifact, *, runs_parent_dir: str | None = None,
796
+ prepare: Callable[["TrainingBaseSession"], None] | None = None) -> None:
797
+ """Replay one saved training mini-batch in a fresh run of this subclass."""
798
+ replay_training_failure(cls, artifact, runs_parent_dir, prepare)
799
+
800
+ def _run_training_iteration(self, mini_batch: Dict[str, Any | torch.Tensor]) -> None:
801
+ self.network.train()
802
+ location = self._batch_location()
803
+ debug = self.config_session.debug
804
+ with torch.autograd.set_detect_anomaly(True) if debug is not None and debug.anomaly_detection else nullcontext():
805
+ outs_dict = self._forward_pass_checked(mini_batch, location)
806
+ loss = self.loss_function(**_keyword_arguments(self.loss_function, outs_dict))
807
+ if debug is not None:
808
+ check_finite(loss, location, "loss")
809
+ elif torch.isnan(loss).any().item():
810
+ raise FloatingPointError(f"{location}: NaN loss.")
811
+
812
+ if self.config_session.accumulation_steps == 1:
813
+ self.optimizer.zero_grad()
814
+ self._backward_checked(loss, location)
815
+ self._step_optimizer(location)
816
+ mini_batch_size = self.infer_mini_batch_size(mini_batch)
817
+ else:
818
+ mini_batch_size = self.infer_mini_batch_size(mini_batch)
819
+ if mini_batch_size <= 0:
820
+ raise ValueError("Gradient accumulation requires a nonempty mini-batch.")
821
+ # Accumulate summed gradients for the sample-mean loss.
822
+ self._backward_checked(loss * mini_batch_size, location)
823
+ self._accumulated_batches += 1
824
+ self._accumulated_samples += mini_batch_size
825
+ if self._accumulated_batches == self.config_session.accumulation_steps:
826
+ self._finish_accumulation(location)
827
+ self.progress_train.increment_iter(mini_batch_size)
555
828
  # `outs_dict` is supposed to have all key-value pairs required by functionals in metrics.
556
829
  self.value_logger_train.update(self.loggable_train(**{"loss_tensor": loss}, **outs_dict),
557
830
  metric_inputs=outs_dict)
@@ -563,10 +836,14 @@ class TrainingBaseSession(ABC):
563
836
 
564
837
  def do_one_validation_iteration(self, mini_batch: Dict[str, Any | torch.Tensor], valid_dataset_name: str) -> None:
565
838
  self.network.eval()
839
+ location = self._batch_location(valid_dataset_name)
566
840
  with torch.no_grad():
567
- outs_dict = self.forward_pass(mini_batch)
841
+ outs_dict = self._forward_pass_checked(mini_batch, location)
568
842
 
569
843
  loss = self.loss_function(**_keyword_arguments(self.loss_function, outs_dict))
844
+ if self.config_session.debug is not None:
845
+ check_finite(loss, location, "loss")
846
+ self._check_debug_parameters(location, gradients=True)
570
847
  self.progress_valid_dict[valid_dataset_name].increment_iter(self.infer_mini_batch_size(mini_batch))
571
848
  self.value_logger_valid_dict[valid_dataset_name].update(
572
849
  self.loggable_valid_dict[valid_dataset_name](**{"loss_tensor": loss}, **outs_dict), metric_inputs=outs_dict)
@@ -584,50 +861,89 @@ class TrainingBaseSession(ABC):
584
861
  for name, value in logger.epoch_values.items():
585
862
  self.writer.add_scalar("{}/{}/epochs".format(prefix, name), value, epoch)
586
863
 
864
+ def _limit_debug_batches(self, batches):
865
+ debug = self.config_session.debug
866
+ if debug is not None and debug.max_batches is not None:
867
+ return islice(batches, min(debug.max_batches, sys.maxsize))
868
+ return batches
869
+
870
+ def _training_batches(self):
871
+ batches = self._dataloader_iterator(self.dataloader_train)
872
+ debug = self.config_session.debug
873
+ if debug is not None and debug.overfit_batches is not None:
874
+ first = next(batches, None)
875
+ if first is None:
876
+ raise RuntimeError("A fixed-batch debug run requires at least one training mini-batch.")
877
+ return (deepcopy(first) for _ in range(debug.overfit_batches))
878
+ return self._limit_debug_batches(batches)
879
+
880
+ def _report_batch_progress(self, phase: str, progress: ProgressManager, logger: ValuesLogger, batches: int) -> None:
881
+ debug = self.config_session.debug
882
+ epochs = self.config_session.num_epochs
883
+ if self._bounded_debug:
884
+ epochs = 1
885
+ batches = debug.overfit_batches if debug.overfit_batches is not None else min(batches, debug.max_batches)
886
+ epoch_width = len(str(max(1, epochs - 1)))
887
+ batch_width = len(str(max(1, batches - 1)))
888
+ self.print(f"{phase} | epoch = {progress.epoch + 1:0{epoch_width}d}/{epochs}\t"
889
+ f"iter = {progress.iter_current_epoch:0{batch_width}d}/{batches}\t"
890
+ f"loss = {logger.current_values['loss']:.5f}")
891
+
587
892
  def do_one_training_epoch(self) -> None:
588
893
  # TODO (#13): Progress bar à la tqdm?
589
- for (ind, mini_batch) in enumerate(self._dataloader_iterator(self.dataloader_train)):
894
+ for mini_batch in self._training_batches():
590
895
  self.do_one_training_iteration(mini_batch)
591
- if self.progress_train.iter_current_epoch % self.config_session.checkpoint_interval == 0:
896
+ if (not self._bounded_debug
897
+ and self.progress_train.iter_current_epoch % self.config_session.checkpoint_interval == 0):
592
898
  self._save_checkpoint()
593
- self.print("training | epoch = {:0{}d}/{}\t"
594
- "iter = {:0{}d}/{}\t"
595
- "loss = {:.5f}".format(self.progress_train.epoch + 1,
596
- int(np.ceil(np.log10(self.config_session.num_epochs))),
597
- self.config_session.num_epochs,
598
- self.progress_train.iter_current_epoch,
599
- int(np.ceil(np.log10(len(self.dataloader_train)))),
600
- len(self.dataloader_train),
601
- self.value_logger_train.current_values["loss"]))
899
+ self._report_batch_progress("training", self.progress_train, self.value_logger_train,
900
+ len(self.dataloader_train))
602
901
 
902
+ # The last mini-batch checkpoint can still contain a partial window. On
903
+ # recovery the exhausted loader leads back here to apply that update once.
904
+ if self._accumulated_batches:
905
+ self._finish_accumulation(self._batch_location(offset=0))
603
906
  self._write_epoch_metrics(self.value_logger_train, "training", self.progress_train.epoch + 1)
604
907
  self.progress_train.increment_epoch()
605
908
 
606
909
  def do_one_validation_epoch(self, valid_dataset_name: str) -> None:
607
- for (ind, mini_batch) in enumerate(self._dataloader_iterator(self.dataloader_valid_dict[valid_dataset_name])):
910
+ loader = self.dataloader_valid_dict[valid_dataset_name]
911
+ progress = self.progress_valid_dict[valid_dataset_name]
912
+ logger = self.value_logger_valid_dict[valid_dataset_name]
913
+ for mini_batch in self._limit_debug_batches(self._dataloader_iterator(loader)):
608
914
  self.do_one_validation_iteration(mini_batch, valid_dataset_name)
609
- if (self.progress_valid_dict[valid_dataset_name].iter_current_epoch
610
- % self.config_session.checkpoint_interval == 0):
915
+ if not self._bounded_debug and progress.iter_current_epoch % self.config_session.checkpoint_interval == 0:
611
916
  self._save_checkpoint()
612
-
613
- self.print("validation-{} | epoch = {:0{}d}/{}\t"
614
- "iter = {:0{}d}/{}\t"
615
- "loss = {:.5f}".format(valid_dataset_name,
616
- self.progress_valid_dict[valid_dataset_name].epoch + 1,
617
- int(np.ceil(np.log10(self.config_session.num_epochs))),
618
- self.config_session.num_epochs,
619
- self.progress_valid_dict[valid_dataset_name].iter_current_epoch,
620
- int(np.ceil(
621
- np.log10(len(self.dataloader_valid_dict[valid_dataset_name])))),
622
- len(self.dataloader_valid_dict[valid_dataset_name]),
623
- self.value_logger_valid_dict[valid_dataset_name].current_values["loss"]))
624
-
625
- self._write_epoch_metrics(self.value_logger_valid_dict[valid_dataset_name],
626
- "validation-{}".format(valid_dataset_name),
627
- self.progress_valid_dict[valid_dataset_name].epoch + 1)
628
- self.progress_valid_dict[valid_dataset_name].increment_epoch()
917
+ self._report_batch_progress(f"validation-{valid_dataset_name}", progress, logger, len(loader))
918
+
919
+ self._write_epoch_metrics(logger, f"validation-{valid_dataset_name}", progress.epoch + 1)
920
+ progress.increment_epoch()
921
+
922
+ def _run_bounded_debug(self):
923
+ self.value_logger_train.reset_epoch()
924
+ self.do_one_training_epoch()
925
+ if self.config_session.debug.overfit_batches is None:
926
+ self._phase = "validation"
927
+ for index, name in enumerate(self.datasets_valid_dict.names):
928
+ self._validation_index = index
929
+ self.value_logger_valid_dict[name].reset_epoch()
930
+ self.do_one_validation_epoch(name)
931
+ if self.config_session.scheduler_interval == "epoch":
932
+ self._step_scheduler(self.progress_train.epoch)
933
+ self._phase = "training"
934
+ self._validation_index = 0
629
935
 
630
936
  def train(self):
937
+ with self._debug_execution():
938
+ if self._bounded_debug:
939
+ try:
940
+ self._run_bounded_debug()
941
+ finally:
942
+ self.writer.close()
943
+ else:
944
+ self._run_checkpointed_training()
945
+
946
+ def _run_checkpointed_training(self):
631
947
  # Preserve the initialized state too, so an interrupted first epoch can restart.
632
948
  if not os.path.exists(os.path.join(self.run_dir, "states", SAVED_CHECKPOINT_NAME)):
633
949
  self._save_checkpoint()
@@ -659,6 +975,10 @@ class TrainingBaseSession(ABC):
659
975
  # Individual best records must not change until every validation set
660
976
  # has finished, so interrupted validation cannot change the votes.
661
977
  self._phase = "selection"
978
+ # The selection checkpoint precedes the epoch scheduler step. The next
979
+ # checkpoint commits both the updated scheduler and the next epoch's phase.
980
+ if self.config_session.scheduler_interval == "epoch":
981
+ self._step_scheduler(self.progress_train.epoch)
662
982
  i_epoch = self.progress_train.epoch - 1
663
983
  vote_for_epoch_as_successful: List[bool] = []
664
984
  for ind_set, valid_dataset_name in enumerate(self.datasets_valid_dict.names):
@@ -0,0 +1,99 @@
1
+ """Options and finite-value checks for numerical diagnostics."""
2
+
3
+ from collections.abc import Mapping
4
+ from contextlib import contextmanager, nullcontext
5
+ from dataclasses import dataclass, fields
6
+ import random
7
+
8
+ import numpy as np
9
+ import torch
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class DebugOptions:
14
+ seed: int | None = None
15
+ deterministic: bool = False
16
+ anomaly_detection: bool = False
17
+ check_inputs: bool = False
18
+ check_outputs: bool = False
19
+ check_parameters: bool = False
20
+ capture_failure: bool = False
21
+ max_batches: int | None = None
22
+ overfit_batches: int | None = None
23
+
24
+ @classmethod
25
+ def from_dict(cls, config: dict | None) -> "DebugOptions | None":
26
+ if config is None:
27
+ return None
28
+ if not isinstance(config, dict):
29
+ raise ValueError("debug must be a dictionary or None.")
30
+ unknown = config.keys() - {option.name for option in fields(cls)}
31
+ if unknown:
32
+ raise ValueError(f"Unknown debug options: {', '.join(sorted(map(str, unknown)))}.")
33
+ options = cls(**config)
34
+ for name in ("deterministic", "anomaly_detection", "check_inputs", "check_outputs", "check_parameters",
35
+ "capture_failure"):
36
+ if type(getattr(options, name)) is not bool:
37
+ raise ValueError(f"debug.{name} must be a boolean.")
38
+ if options.seed is not None and (type(options.seed) is not int or not 0 <= options.seed < 2**32):
39
+ raise ValueError("debug.seed must be an integer in [0, 2**32).")
40
+ for name in ("max_batches", "overfit_batches"):
41
+ limit = getattr(options, name)
42
+ if limit is not None and (type(limit) is not int or limit <= 0):
43
+ raise ValueError(f"debug.{name} must be a positive integer.")
44
+ if options.max_batches is not None and options.overfit_batches is not None:
45
+ raise ValueError("Choose either debug.max_batches or debug.overfit_batches.")
46
+ return options
47
+
48
+ @property
49
+ def bounded(self) -> bool:
50
+ return self.max_batches is not None or self.overfit_batches is not None
51
+
52
+ def seed_fresh_run(self) -> None:
53
+ seed = 0 if self.seed is None and self.deterministic else self.seed
54
+ if seed is not None:
55
+ random.seed(seed)
56
+ np.random.seed(seed)
57
+ torch.manual_seed(seed)
58
+
59
+ @contextmanager
60
+ def execution(self, device_name: str):
61
+ device = torch.device(device_name)
62
+ # The checkpoint RNG helpers capture the current CUDA device.
63
+ with torch.cuda.device(device) if device.type == "cuda" else nullcontext():
64
+ if not self.deterministic:
65
+ yield
66
+ return
67
+ enabled = torch.are_deterministic_algorithms_enabled()
68
+ warn_only = torch.is_deterministic_algorithms_warn_only_enabled()
69
+ benchmark = torch.backends.cudnn.benchmark
70
+ try:
71
+ torch.use_deterministic_algorithms(True)
72
+ torch.backends.cudnn.benchmark = False
73
+ yield
74
+ finally:
75
+ torch.use_deterministic_algorithms(enabled, warn_only=warn_only)
76
+ torch.backends.cudnn.benchmark = benchmark
77
+
78
+
79
+ def check_finite(value, location: str, name: str) -> None:
80
+ """Check numerical leaves without modifying the batch or its autograd graph."""
81
+ if isinstance(value, torch.Tensor) and (value.is_floating_point() or value.is_complex()):
82
+ tensor = value.detach()
83
+ if tensor.layout == torch.sparse_coo:
84
+ tensor = tensor.coalesce().values()
85
+ elif tensor.layout in (torch.sparse_csr, torch.sparse_csc, torch.sparse_bsr, torch.sparse_bsc):
86
+ tensor = tensor.values()
87
+ elif tensor.layout != torch.strided:
88
+ tensor = tensor.to_dense()
89
+ if not torch.isfinite(tensor).all().item():
90
+ raise FloatingPointError(f"{location}: non-finite {name} (NaN or infinity).")
91
+ elif isinstance(value, (float, complex, np.inexact)) or (isinstance(value, np.ndarray) and value.dtype.kind in "fc"):
92
+ if not np.isfinite(value).all():
93
+ raise FloatingPointError(f"{location}: non-finite {name} (NaN or infinity).")
94
+ elif isinstance(value, Mapping):
95
+ for key, item in value.items():
96
+ check_finite(item, location, f"{name}[{key!r}]")
97
+ elif isinstance(value, (tuple, list)):
98
+ for index, item in enumerate(value):
99
+ check_finite(item, location, f"{name}[{index}]")
@@ -0,0 +1,196 @@
1
+ """Capture and replay one training iteration, without a recovery checkpoint."""
2
+
3
+ from contextlib import contextmanager, nullcontext
4
+ from io import BytesIO
5
+ import logging
6
+ from pathlib import Path
7
+ import platform
8
+ from uuid import uuid4
9
+
10
+ import numpy as np
11
+ import torch
12
+
13
+ from torchbase.utils.checkpoint import atomic_torch_save
14
+ from torchbase.utils.session import RandomnessGeneratorStates
15
+
16
+
17
+ _FORMAT = "torchbase.training_failure.v1"
18
+ _log = logging.getLogger(__name__)
19
+
20
+
21
+ def _qualified_name(cls):
22
+ return f"{cls.__module__}.{cls.__qualname__}"
23
+
24
+
25
+ def _encode(value):
26
+ # Serialize before running the iteration so in-place mutations cannot affect the snapshot.
27
+ stream = BytesIO()
28
+ torch.save(value, stream)
29
+ return stream.getvalue()
30
+
31
+
32
+ def _snapshot(session, batch):
33
+ rng = RandomnessGeneratorStates().to_dict()
34
+ device = session.device
35
+ if device.type == "cuda" and device.index is None:
36
+ device = torch.device("cuda", torch.cuda.current_device())
37
+ parameters = dict(session.network.named_parameters())
38
+ model_parameters = set(parameters.values())
39
+ state = {
40
+ "config": session._config_dict(),
41
+ "network": session.network.state_dict(),
42
+ "buffers": dict(session.network.named_buffers()),
43
+ "module_modes": {name: module.training for name, module in session.network.named_modules()},
44
+ "gradients": {name: parameter.grad for name, parameter in parameters.items()},
45
+ "optimizer_only_parameters": {index: (parameter.detach(), parameter.grad)
46
+ for index, parameter in enumerate(session._optimizer_parameters())
47
+ if parameter not in model_parameters},
48
+ **session._optimizer_state(),
49
+ "accumulated_batches": session._accumulated_batches,
50
+ "accumulated_samples": session._accumulated_samples,
51
+ "phase": session._phase,
52
+ "validation_index": session._validation_index,
53
+ "progress_train": session.progress_train.state_dict(),
54
+ "values_logger_train": session.value_logger_train.state_dict(),
55
+ "validation": {name: {"progress": progress.state_dict(),
56
+ "values_logger": session.value_logger_valid_dict[name].state_dict()}
57
+ for name, progress in session.progress_valid_dict.items()},
58
+ "best_validation_loss_dict": session.best_validation_loss_dict,
59
+ "best_model_epoch": session.best_model_epoch,
60
+ "setup_rng": session._failure_setup_rng,
61
+ "rng": rng,
62
+ }
63
+ return {
64
+ "format": _FORMAT,
65
+ "metadata": {"session_class": _qualified_name(type(session)), "location": session._batch_location(),
66
+ "device": str(device), "python": platform.python_version(), "torch": str(torch.__version__),
67
+ "numpy": str(np.__version__), "deterministic_mode": torch.get_deterministic_debug_mode(),
68
+ "cudnn_benchmark": torch.backends.cudnn.benchmark, "grad_enabled": torch.is_grad_enabled(),
69
+ "anomaly_enabled": torch.is_anomaly_enabled(), "anomaly_check_nan": torch.is_anomaly_check_nan_enabled()},
70
+ # Model and optimizer tensors can load on CPU. The batch retains its original devices and tensor views.
71
+ "state": _encode(state),
72
+ "batch": _encode(batch),
73
+ }
74
+
75
+
76
+ @contextmanager
77
+ def capture_training_failure(session, batch):
78
+ try:
79
+ artifact = _snapshot(session, batch)
80
+ except Exception as error:
81
+ _log.warning("Could not snapshot %s for failure replay: %s", session._batch_location(), error)
82
+ artifact = None
83
+ try:
84
+ yield
85
+ except Exception as failure:
86
+ if artifact is not None:
87
+ try:
88
+ directory = Path(session.run_dir, "failures")
89
+ directory.mkdir(exist_ok=True)
90
+ path = directory / f"training-{uuid4().hex}.pth"
91
+ artifact["metadata"]["exception"] = {"type": _qualified_name(type(failure)), "message": str(failure)}
92
+ atomic_torch_save(artifact, path)
93
+ except Exception as error:
94
+ _log.warning("Could not write the training failure snapshot: %s", error)
95
+ else:
96
+ if hasattr(failure, "add_note"):
97
+ failure.add_note(f"torchbase failure snapshot saved to {path}")
98
+ _log.warning("Training failure snapshot saved to %s", path)
99
+ raise
100
+
101
+
102
+ def _restore_iteration(session, state):
103
+ session.network.load_state_dict(state["network"])
104
+ session._restore_scheduler(state)
105
+ session.optimizer.load_state_dict(state["optimizer"])
106
+
107
+ parameters = dict(session.network.named_parameters())
108
+ buffers = dict(session.network.named_buffers())
109
+ modules = dict(session.network.named_modules())
110
+ optimizer_parameters = session._optimizer_parameters()
111
+ model_parameters = set(parameters.values())
112
+ optimizer_only = {index: parameter for index, parameter in enumerate(optimizer_parameters)
113
+ if parameter not in model_parameters}
114
+ if (parameters.keys() != state["gradients"].keys() or buffers.keys() != state["buffers"].keys()
115
+ or modules.keys() != state["module_modes"].keys()
116
+ or optimizer_only.keys() != state["optimizer_only_parameters"].keys()):
117
+ raise ValueError("Failure snapshot does not match the replay model or optimizer parameters.")
118
+ with torch.no_grad():
119
+ for name, buffer in buffers.items():
120
+ saved = state["buffers"][name]
121
+ if saved.shape != buffer.shape or saved.dtype != buffer.dtype:
122
+ raise ValueError(f"Failure snapshot buffer {name!r} does not match the replay model.")
123
+ buffer.copy_(saved)
124
+ for name, parameter in parameters.items():
125
+ gradient = state["gradients"][name]
126
+ parameter.grad = None if gradient is None else gradient.to(parameter.device)
127
+ for index, parameter in optimizer_only.items():
128
+ value, gradient = state["optimizer_only_parameters"][index]
129
+ if value.shape != parameter.shape or value.dtype != parameter.dtype:
130
+ raise ValueError("Failure snapshot has an incompatible optimizer parameter.")
131
+ parameter.copy_(value)
132
+ parameter.grad = None if gradient is None else gradient.to(parameter.device)
133
+ for name, module in modules.items():
134
+ module.training = state["module_modes"][name]
135
+
136
+ session._accumulated_batches = state["accumulated_batches"]
137
+ session._accumulated_samples = state["accumulated_samples"]
138
+ session._phase = state["phase"]
139
+ session._validation_index = state["validation_index"]
140
+ session.progress_train.load_state_dict(state["progress_train"])
141
+ session.value_logger_train.load_state_dict(state["values_logger_train"])
142
+ for name, validation in state["validation"].items():
143
+ session.progress_valid_dict[name].load_state_dict(validation["progress"])
144
+ session.value_logger_valid_dict[name].load_state_dict(validation["values_logger"])
145
+ session.best_validation_loss_dict = state["best_validation_loss_dict"]
146
+ session.best_model_epoch = state["best_model_epoch"]
147
+ session._check_loop_state()
148
+
149
+
150
+ @contextmanager
151
+ def _replay_environment(metadata):
152
+ device = torch.device(metadata["device"])
153
+ with torch.cuda.device(device) if device.type == "cuda" else nullcontext():
154
+ rng = RandomnessGeneratorStates()
155
+ deterministic_mode = torch.get_deterministic_debug_mode()
156
+ benchmark = torch.backends.cudnn.benchmark
157
+ try:
158
+ torch.set_deterministic_debug_mode(metadata["deterministic_mode"])
159
+ torch.backends.cudnn.benchmark = metadata["cudnn_benchmark"]
160
+ with torch.set_grad_enabled(metadata["grad_enabled"]), torch.autograd.set_detect_anomaly(
161
+ metadata["anomaly_enabled"], check_nan=metadata["anomaly_check_nan"]):
162
+ yield
163
+ finally:
164
+ torch.set_deterministic_debug_mode(deterministic_mode)
165
+ torch.backends.cudnn.benchmark = benchmark
166
+ rng.apply()
167
+
168
+
169
+ def replay_training_failure(session_class, path, runs_parent_dir, prepare):
170
+ """Rebuild the experiment and execute the captured iteration without reading a loader."""
171
+ artifact = torch.load(path, map_location="cpu", weights_only=True)
172
+ if (not isinstance(artifact, dict) or artifact.get("format") != _FORMAT
173
+ or not isinstance(artifact.get("metadata"), dict)
174
+ or not isinstance(artifact.get("state"), bytes) or not isinstance(artifact.get("batch"), bytes)):
175
+ raise ValueError("Expected a torchbase training failure snapshot.")
176
+ metadata = artifact["metadata"]
177
+ if metadata["session_class"] != _qualified_name(session_class):
178
+ raise ValueError(f"This failure snapshot requires the session class {metadata['session_class']}.")
179
+ if metadata["torch"] != str(torch.__version__):
180
+ raise ValueError(f"This failure snapshot requires PyTorch {metadata['torch']}.")
181
+
182
+ state = torch.load(BytesIO(artifact["state"]), map_location="cpu", weights_only=True)
183
+ config = state["config"]
184
+ config["session"]["debug"].update(capture_failure=False, max_batches=None, overfit_batches=None)
185
+ with _replay_environment(metadata):
186
+ RandomnessGeneratorStates.from_dict(state["setup_rng"]).apply()
187
+ session = session_class(config, runs_parent_dir=runs_parent_dir, tag_postfix=f"replay-{uuid4().hex[:8]}")
188
+ try:
189
+ _restore_iteration(session, state)
190
+ if prepare is not None:
191
+ prepare(session)
192
+ batch = torch.load(BytesIO(artifact["batch"]), weights_only=True)
193
+ RandomnessGeneratorStates.from_dict(state["rng"]).apply()
194
+ session._run_training_iteration(batch)
195
+ finally:
196
+ session.writer.close()
@@ -1,8 +1,11 @@
1
1
  from dataclasses import dataclass, fields, field, asdict, MISSING
2
2
  from copy import deepcopy
3
3
  import math
4
+ from sys import float_info
4
5
  from typing import Dict, Tuple
5
6
 
7
+ from torchbase.utils.debug import DebugOptions
8
+
6
9
  import torch
7
10
  import numpy as np
8
11
  import random
@@ -105,6 +108,11 @@ class TrainingConfigSessionDict:
105
108
  dataloader_num_workers: int = 0
106
109
  checkpoint_interval: int = 100
107
110
  loss_function_params: None | dict = None
111
+ max_grad_norm: int | float | None = None
112
+ scheduler_interval: str | None = None
113
+ scheduler_monitor: dict[str, str] | None = None
114
+ accumulation_steps: int = 1
115
+ debug: DebugOptions | None = None
108
116
 
109
117
  def __init__(self, config: dict):
110
118
  if not isinstance(config, dict):
@@ -119,11 +127,14 @@ class TrainingConfigSessionDict:
119
127
  raise ValueError("Missing required session config fields: {}".format(", ".join(missing)))
120
128
  for field_info in fields(self):
121
129
  setattr(self, field_info.name, config.get(field_info.name, field_info.default))
130
+ self.debug = DebugOptions.from_dict(self.debug)
122
131
  invalid = self._invalid_fields()
123
132
  if invalid:
124
133
  raise ValueError("Invalid session config fields: {}".format(", ".join(invalid)))
125
134
  if self.loss_function_params is not None:
126
135
  self.loss_function_params = _copy_config(self.loss_function_params)
136
+ if self.scheduler_monitor is not None:
137
+ self.scheduler_monitor = self.scheduler_monitor.copy()
127
138
 
128
139
  def to_dict(self) -> dict:
129
140
  return asdict(self)
@@ -132,6 +143,10 @@ class TrainingConfigSessionDict:
132
143
  return not self._invalid_fields()
133
144
 
134
145
  def _invalid_fields(self) -> list[str]:
146
+ max_grad_norm = self.max_grad_norm
147
+ interval = self.scheduler_interval
148
+ monitor = self.scheduler_monitor
149
+ interval_valid = interval is None or isinstance(interval, str) and interval in ("update", "epoch")
135
150
  checks = {
136
151
  "device_name": isinstance(self.device_name, str) and bool(self.device_name),
137
152
  "num_epochs": type(self.num_epochs) is int and self.num_epochs > 0,
@@ -143,6 +158,16 @@ class TrainingConfigSessionDict:
143
158
  "dataloader_num_workers": type(self.dataloader_num_workers) is int and self.dataloader_num_workers >= 0,
144
159
  "checkpoint_interval": type(self.checkpoint_interval) is int and self.checkpoint_interval > 0,
145
160
  "loss_function_params": self.loss_function_params is None or isinstance(self.loss_function_params, dict),
161
+ "max_grad_norm": max_grad_norm is None or (
162
+ type(max_grad_norm) in (int, float) and 0 < max_grad_norm <= float_info.max),
163
+ "scheduler_interval": interval_valid,
164
+ "scheduler_monitor": monitor is None or (
165
+ interval_valid and interval == "epoch" and isinstance(monitor, dict)
166
+ and monitor.keys() == {"dataset", "metric", "aggregation"}
167
+ and all(isinstance(value, str) and value for value in monitor.values())
168
+ and monitor["aggregation"] in ("batch_mean", "epoch")),
169
+ "accumulation_steps": type(self.accumulation_steps) is int and self.accumulation_steps > 0,
170
+ "debug": self.debug is None or isinstance(self.debug, DebugOptions),
146
171
  }
147
172
  return [name for name, valid in checks.items() if not valid]
148
173
 
File without changes