torchbase 0.1.4__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.1.4
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,11 +13,13 @@ 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
19
20
  Requires-Dist: tensorboard
20
- Requires-Dist: torch
21
+ Requires-Dist: torch (>=2.6)
22
+ Requires-Dist: torchdata (>=0.11)
21
23
  Project-URL: Issues, https://github.com/sssohrab/torchbase/issues
22
24
  Project-URL: Repository, https://github.com/sssohrab/torchbase
23
25
  Description-Content-Type: text/markdown
@@ -53,6 +55,10 @@ which arguments it requires and whether or not you would like to log certain val
53
55
 
54
56
  This may look something like:
55
57
 
58
+ The example reconstructs binary images and uses `torchvision` for augmentation (`pip install torchvision`).
59
+ See [the runnable version and its walkthrough](https://github.com/sssohrab/torchbase/blob/main/examples/README.md)
60
+ for starting, inspecting and recovering a run.
61
+
56
62
  ```python
57
63
  from torchbase import TrainingBaseSession
58
64
  from torchbase.utils import ValidationDatasetsDict, BaseMetricsClass, split_iterables
@@ -71,9 +77,11 @@ class MyTrainingSession(TrainingBaseSession):
71
77
  Here you define and return your training dataset, as well as validation datasets.
72
78
  They all should be instances of the Huggingface's dataset library, i.e., `datasets.Dataset` objects.
73
79
 
74
- The validation datasets should be wrapped around a `torchbase.ValidationDatasetsDict` object. This forces
80
+ The validation datasets should be wrapped around a `torchbase.utils.ValidationDatasetsDict` object. This forces
75
81
  you to do some extra work, but having multiple validation datasets can be very useful, e.g., to monitor
76
82
  the effect of data augmentation.
83
+ Provide at least one nonempty validation dataset, with equally sized tuples of datasets, demo flags and
84
+ unique names; invalid combinations are rejected before dataloaders are created.
77
85
 
78
86
  You can mark some of the validation datasets as "only for demo". In this case they will not be used for
79
87
  the actual validation process but only logged. This can be useful, e.g., if you are curious how your network
@@ -89,13 +97,17 @@ class MyTrainingSession(TrainingBaseSession):
89
97
  from torchvision.transforms import RandomRotation
90
98
  return RandomRotation(degrees=(-10, 10))(image)
91
99
 
92
- data_train, data_valid = split_iterables([torch.randn((self.config_data["image_size"])) for _ in range(20)],
93
- portions=self.config_data["split_portions"],
100
+ data_train, data_valid = split_iterables([torch.rand((self.config_network["num_ch"],
101
+ *self.config_data["image_size"])).round()
102
+ for _ in range(20)],
103
+ portions=tuple(self.config_data["split_portions"]),
94
104
  shuffle=True)
95
105
 
96
- dataset_train = Dataset.from_dict({"image": data_train}).map(lambda x: augment(x))
97
- dataset_valid = Dataset.from_dict({"image": data_valid})
98
- dataset_valid_aug = Dataset.from_dict({"image": data_valid}).map(lambda x: augment(x))
106
+ dataset_train = Dataset.from_dict({"image": data_train}).with_format("torch").map(
107
+ lambda x: {"image": augment(x["image"])})
108
+ dataset_valid = Dataset.from_dict({"image": data_valid}).with_format("torch")
109
+ dataset_valid_aug = Dataset.from_dict({"image": data_valid}).with_format("torch").map(
110
+ lambda x: {"image": augment(x["image"])})
99
111
 
100
112
  return dataset_train, ValidationDatasetsDict(datasets=(
101
113
  dataset_train, dataset_valid, dataset_valid_aug), only_for_demo=(True, False, False),
@@ -106,9 +118,10 @@ class MyTrainingSession(TrainingBaseSession):
106
118
  def __init__(self, num_ch, num_layers):
107
119
  super().__init__()
108
120
  layers = []
109
- for _ in range(num_layers):
110
- layers.append(torch.nn.Conv2d(num_ch, num_ch, 3))
111
- layers.append(torch.nn.ReLU())
121
+ for i in range(num_layers):
122
+ layers.append(torch.nn.Conv2d(num_ch, num_ch, 3, padding=1))
123
+ if i < num_layers - 1:
124
+ layers.append(torch.nn.ReLU())
112
125
 
113
126
  self.layers = torch.nn.Sequential(*layers)
114
127
 
@@ -136,7 +149,7 @@ class MyTrainingSession(TrainingBaseSession):
136
149
  output_image = self.network(input_image)
137
150
 
138
151
  return {"output": output_image, "target": target_image,
139
- "gt_for_metrics": target_image.sigmoid().round(), "predictions_for_metrics": output_image.sigmoid()}
152
+ "gt_for_metrics": target_image, "predictions_for_metrics": output_image.sigmoid()}
140
153
 
141
154
  def loss_function(self, *, output: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
142
155
  """
@@ -157,7 +170,8 @@ class MyTrainingSession(TrainingBaseSession):
157
170
 
158
171
  Similarly to the `loss_function` above, this function receives all its inputs from the key-value pairs of the
159
172
  `forward_pass`. The `keyword_maps` argument of the `BaseMetricsClass` can translate the keywords between the two,
160
- in case they are different.
173
+ in case they are different. You only need to map the names that differ; other arguments and their defaults
174
+ are kept. Ambiguous mappings are rejected.
161
175
 
162
176
  While you specify the subclasses of `BaseMetricsClass` in this function, which are essentially groups of similar
163
177
  metrics around one particular task, which metrics from every family to log for any particular experiment run is
@@ -220,6 +234,10 @@ config = {
220
234
  - The `"network"` field has only the `"architecture"` subfield as necessary, where you should just specify the name of
221
235
  your network. Here you can specify any hyperparameter your network instantiation would need.
222
236
 
237
+ The session keeps its own copy of these settings without changing your dictionary. Unknown top-level or `"session"`
238
+ fields are rejected; custom settings belong in the other sections or in `"loss_function_params"`.
239
+ Use JSON-compatible values and string dictionary keys. Tuples are also accepted, but load from JSON as lists.
240
+
223
241
  Why do we need this separate config dictionary while we can have it all implemented within the abstract methods of the
224
242
  class? The idea is that the part of the implementation that is less likely to change very frequently will go to the
225
243
  methods implementations as python code. You would want to version-control this part using `git` as the main components
@@ -258,20 +276,193 @@ directory of your experiment runs will launch the web-service from where you cou
258
276
  logged parameters, judge whether you are going over- or under-fit, or decide the best set of hyperparameters across
259
277
  experiments.
260
278
 
279
+ Iteration metrics describe each mini-batch. At epoch completion, their sample-weighted averages are logged under
280
+ `batch_means`, not as whole-dataset scores. Binary precision, recall and F1 also have `epochs` scores computed from four accumulated
281
+ confusion counts, independently for training and each validation dataset. Other metrics, including AUC and PSNR,
282
+ remain batch statistics; no predictions are buffered. `loss/epochs` remains the sample-weighted mean of batch losses
283
+ and assumes a mean-reduced loss.
284
+
285
+ For a custom whole-epoch metric, override `BaseMetricsClass.get_epoch_metric(name)` to return a fresh `EpochMetric`
286
+ with keyword-only `update`, `compute`, `reset`, `state_dict` and `load_state_dict` methods. Its state is checkpointed
287
+ and resets at the start of its dataset's next epoch, not when resuming inside an epoch.
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
+
261
403
  For various reasons, you may sometimes want to suspend the training process before it is finalized. `torchbase` provides
262
- you with the possibility to take-over from a past experiment and recover (almost) exactly what was going on:
404
+ you with the possibility to take over from the latest saved iteration of a past experiment, whether it was training
405
+ or validating:
263
406
 
264
407
  ```python
265
408
  the_recovered_session = MyTrainingSession(same_config_as_before,
266
409
  source_run_dir_tag=the_tag_to_the_suspended_experiment,
267
410
  create_run_dir_afresh=False)
268
411
 
269
- the_recovered_session() # This will continue the suspended session where it stopped without creating a new run dir.
412
+ the_recovered_session() # This will continue after the saved iteration without creating a new run dir.
270
413
  ```
271
414
 
415
+ This recovers not only the network weights and the optimizer, but also the dataloader positions, progress counters and
416
+ logged values for training and each validation dataset, along with the best validation losses and their epochs. Keep
417
+ the experimental setup and its configuration the same, although you may increase `num_epochs` to train for longer.
418
+ This specifies the total number of epochs, not additional ones: if you have finished 10 and now specify 15, another 5
419
+ will be run. Any pending validation and model selection are completed before the experiment is considered finished.
420
+
421
+ The session config's `checkpoint_interval` defaults to 100 and must be a positive integer. It specifies the number of
422
+ completed mini-batches between saves within each training or validation loop. If an epoch has 10,000 iterations and
423
+ the process stops at iteration 9070, an interval of 100 lets you recover at 9000 and continue with 9001, retaining the
424
+ averages accumulated so far. Only work after the last successful save is repeated. You may change the interval when
425
+ recovering a run.
426
+
427
+ Checkpoints are also saved before the first epoch, after training and each validation dataset, and after model
428
+ selection, so recovery skips completed phases. Saves synchronously replace `states/checkpoint.pth` rather than
429
+ accumulating separate files; the interval determines how often serialization and disk I/O interrupt training.
430
+
431
+ The original `states/rng_states.json` reconstructs the initial setup, e.g., the same random split of the data. Afterwards,
432
+ the checkpoint's continuation RNG state takes over. The default dataloaders use TorchData's `StatefulDataLoader`
433
+ (`torchdata>=0.11`, `torch>=2.6`), each with its own random generator, to recover the shuffled order and current position,
434
+ including prefetched worker batches.
435
+
436
+ Recovery is tested on CPU with zero or two workers, keeping the data, code and dependencies unchanged. Worker tests
437
+ use deterministic, indexable datasets, not arbitrary random augmentation. Custom `init_dataloaders` implementations
438
+ must use `StatefulDataLoader` with an explicit `torch.Generator`, `in_order=True` and `persistent_workers=False`.
439
+ Changes to recorded settings, including batch size, dataset sizes, worker counts and validation names/order, raise an
440
+ error on recovery. Dataset contents and custom sampling behavior must also remain unchanged, but are not checked.
441
+
442
+ Custom dataset or worker-transform state needs TorchData's `state_dict()` / `load_state_dict()` hooks, using tensors
443
+ and basic Python types compatible with `torch.load(..., weights_only=True)`. Custom or accelerator-specific randomness
444
+ may require further state handling; these setups are outside the default recovery tests. Worker collation functions
445
+ should be module-level functions or static methods. Do not expect identical results across platforms or PyTorch versions.
446
+
447
+ Checkpoints are written to a temporary file and atomically moved into place, so an interrupted write preserves the
448
+ previous save. Leftover temporary files are ignored. This assumes one writer and a filesystem supporting atomic
449
+ replacement, and does not replace backups against storage failure. TensorBoard event files may still contain entries
450
+ from work repeated after recovery.
451
+
452
+ The checkpoint keeps both the latest training state and the best model. The weights-only `network.pth` under the run
453
+ directory remains available for inference and can be restored from the checkpoint if its export was interrupted.
454
+ Each participating validation dataset keeps its own lowest loss and epoch, but a model is selected only when all
455
+ improve their records in the same epoch; `only_for_demo` datasets do not vote. The selected model's epoch is
456
+ recorded separately as `best_model_epoch` (zero-based, like the loss records). The checkpoint may therefore contain
457
+ two sets of weights when the latest and best models differ.
458
+
459
+ Recovery requires all states expected by the current code; missing or inconsistent states raise an error.
460
+
272
461
  Alternatively, passing the flag `create_run_dir_afresh=True`, but still specifying a `source_run_dir_tag` will create a
273
462
  new experiment starting from scratch but only initializing the weights of the network with the previously-trained ones
274
- from the source run.
463
+ from the source run's latest checkpoint. In this case, you are starting a new experiment rather than continuing
464
+ the old one: the optimizer, progress counters, logged values and best-loss tracking start afresh, and the source run's
465
+ randomness and dataloader states are not restored.
275
466
 
276
467
  As a general note, other than the config parameters which are accessible to all member methods, you may want to pass
277
468
  some new members to the class accessible to all methods. In this case, you can re-implement the `__init__` method with
@@ -288,8 +479,8 @@ class MyTrainingSession(TrainingBaseSession):
288
479
  pass
289
480
  ```
290
481
 
291
- Currently, the `torchbase` project has no documentation other than this readme. The best way to learn about its
292
- different features is to look at the unit-tests, or just looking at the source code.
482
+ For a longer walkthrough, see the [runnable example](https://github.com/sssohrab/torchbase/blob/main/examples/README.md).
483
+ The unit-tests and source code provide further details about the different features.
293
484
 
294
485
  ## The idea behind
295
486
 
@@ -29,6 +29,10 @@ which arguments it requires and whether or not you would like to log certain val
29
29
 
30
30
  This may look something like:
31
31
 
32
+ The example reconstructs binary images and uses `torchvision` for augmentation (`pip install torchvision`).
33
+ See [the runnable version and its walkthrough](https://github.com/sssohrab/torchbase/blob/main/examples/README.md)
34
+ for starting, inspecting and recovering a run.
35
+
32
36
  ```python
33
37
  from torchbase import TrainingBaseSession
34
38
  from torchbase.utils import ValidationDatasetsDict, BaseMetricsClass, split_iterables
@@ -47,9 +51,11 @@ class MyTrainingSession(TrainingBaseSession):
47
51
  Here you define and return your training dataset, as well as validation datasets.
48
52
  They all should be instances of the Huggingface's dataset library, i.e., `datasets.Dataset` objects.
49
53
 
50
- The validation datasets should be wrapped around a `torchbase.ValidationDatasetsDict` object. This forces
54
+ The validation datasets should be wrapped around a `torchbase.utils.ValidationDatasetsDict` object. This forces
51
55
  you to do some extra work, but having multiple validation datasets can be very useful, e.g., to monitor
52
56
  the effect of data augmentation.
57
+ Provide at least one nonempty validation dataset, with equally sized tuples of datasets, demo flags and
58
+ unique names; invalid combinations are rejected before dataloaders are created.
53
59
 
54
60
  You can mark some of the validation datasets as "only for demo". In this case they will not be used for
55
61
  the actual validation process but only logged. This can be useful, e.g., if you are curious how your network
@@ -65,13 +71,17 @@ class MyTrainingSession(TrainingBaseSession):
65
71
  from torchvision.transforms import RandomRotation
66
72
  return RandomRotation(degrees=(-10, 10))(image)
67
73
 
68
- data_train, data_valid = split_iterables([torch.randn((self.config_data["image_size"])) for _ in range(20)],
69
- portions=self.config_data["split_portions"],
74
+ data_train, data_valid = split_iterables([torch.rand((self.config_network["num_ch"],
75
+ *self.config_data["image_size"])).round()
76
+ for _ in range(20)],
77
+ portions=tuple(self.config_data["split_portions"]),
70
78
  shuffle=True)
71
79
 
72
- dataset_train = Dataset.from_dict({"image": data_train}).map(lambda x: augment(x))
73
- dataset_valid = Dataset.from_dict({"image": data_valid})
74
- dataset_valid_aug = Dataset.from_dict({"image": data_valid}).map(lambda x: augment(x))
80
+ dataset_train = Dataset.from_dict({"image": data_train}).with_format("torch").map(
81
+ lambda x: {"image": augment(x["image"])})
82
+ dataset_valid = Dataset.from_dict({"image": data_valid}).with_format("torch")
83
+ dataset_valid_aug = Dataset.from_dict({"image": data_valid}).with_format("torch").map(
84
+ lambda x: {"image": augment(x["image"])})
75
85
 
76
86
  return dataset_train, ValidationDatasetsDict(datasets=(
77
87
  dataset_train, dataset_valid, dataset_valid_aug), only_for_demo=(True, False, False),
@@ -82,9 +92,10 @@ class MyTrainingSession(TrainingBaseSession):
82
92
  def __init__(self, num_ch, num_layers):
83
93
  super().__init__()
84
94
  layers = []
85
- for _ in range(num_layers):
86
- layers.append(torch.nn.Conv2d(num_ch, num_ch, 3))
87
- layers.append(torch.nn.ReLU())
95
+ for i in range(num_layers):
96
+ layers.append(torch.nn.Conv2d(num_ch, num_ch, 3, padding=1))
97
+ if i < num_layers - 1:
98
+ layers.append(torch.nn.ReLU())
88
99
 
89
100
  self.layers = torch.nn.Sequential(*layers)
90
101
 
@@ -112,7 +123,7 @@ class MyTrainingSession(TrainingBaseSession):
112
123
  output_image = self.network(input_image)
113
124
 
114
125
  return {"output": output_image, "target": target_image,
115
- "gt_for_metrics": target_image.sigmoid().round(), "predictions_for_metrics": output_image.sigmoid()}
126
+ "gt_for_metrics": target_image, "predictions_for_metrics": output_image.sigmoid()}
116
127
 
117
128
  def loss_function(self, *, output: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
118
129
  """
@@ -133,7 +144,8 @@ class MyTrainingSession(TrainingBaseSession):
133
144
 
134
145
  Similarly to the `loss_function` above, this function receives all its inputs from the key-value pairs of the
135
146
  `forward_pass`. The `keyword_maps` argument of the `BaseMetricsClass` can translate the keywords between the two,
136
- in case they are different.
147
+ in case they are different. You only need to map the names that differ; other arguments and their defaults
148
+ are kept. Ambiguous mappings are rejected.
137
149
 
138
150
  While you specify the subclasses of `BaseMetricsClass` in this function, which are essentially groups of similar
139
151
  metrics around one particular task, which metrics from every family to log for any particular experiment run is
@@ -196,6 +208,10 @@ config = {
196
208
  - The `"network"` field has only the `"architecture"` subfield as necessary, where you should just specify the name of
197
209
  your network. Here you can specify any hyperparameter your network instantiation would need.
198
210
 
211
+ The session keeps its own copy of these settings without changing your dictionary. Unknown top-level or `"session"`
212
+ fields are rejected; custom settings belong in the other sections or in `"loss_function_params"`.
213
+ Use JSON-compatible values and string dictionary keys. Tuples are also accepted, but load from JSON as lists.
214
+
199
215
  Why do we need this separate config dictionary while we can have it all implemented within the abstract methods of the
200
216
  class? The idea is that the part of the implementation that is less likely to change very frequently will go to the
201
217
  methods implementations as python code. You would want to version-control this part using `git` as the main components
@@ -234,20 +250,193 @@ directory of your experiment runs will launch the web-service from where you cou
234
250
  logged parameters, judge whether you are going over- or under-fit, or decide the best set of hyperparameters across
235
251
  experiments.
236
252
 
253
+ Iteration metrics describe each mini-batch. At epoch completion, their sample-weighted averages are logged under
254
+ `batch_means`, not as whole-dataset scores. Binary precision, recall and F1 also have `epochs` scores computed from four accumulated
255
+ confusion counts, independently for training and each validation dataset. Other metrics, including AUC and PSNR,
256
+ remain batch statistics; no predictions are buffered. `loss/epochs` remains the sample-weighted mean of batch losses
257
+ and assumes a mean-reduced loss.
258
+
259
+ For a custom whole-epoch metric, override `BaseMetricsClass.get_epoch_metric(name)` to return a fresh `EpochMetric`
260
+ with keyword-only `update`, `compute`, `reset`, `state_dict` and `load_state_dict` methods. Its state is checkpointed
261
+ and resets at the start of its dataset's next epoch, not when resuming inside an epoch.
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
+
237
377
  For various reasons, you may sometimes want to suspend the training process before it is finalized. `torchbase` provides
238
- you with the possibility to take-over from a past experiment and recover (almost) exactly what was going on:
378
+ you with the possibility to take over from the latest saved iteration of a past experiment, whether it was training
379
+ or validating:
239
380
 
240
381
  ```python
241
382
  the_recovered_session = MyTrainingSession(same_config_as_before,
242
383
  source_run_dir_tag=the_tag_to_the_suspended_experiment,
243
384
  create_run_dir_afresh=False)
244
385
 
245
- the_recovered_session() # This will continue the suspended session where it stopped without creating a new run dir.
386
+ the_recovered_session() # This will continue after the saved iteration without creating a new run dir.
246
387
  ```
247
388
 
389
+ This recovers not only the network weights and the optimizer, but also the dataloader positions, progress counters and
390
+ logged values for training and each validation dataset, along with the best validation losses and their epochs. Keep
391
+ the experimental setup and its configuration the same, although you may increase `num_epochs` to train for longer.
392
+ This specifies the total number of epochs, not additional ones: if you have finished 10 and now specify 15, another 5
393
+ will be run. Any pending validation and model selection are completed before the experiment is considered finished.
394
+
395
+ The session config's `checkpoint_interval` defaults to 100 and must be a positive integer. It specifies the number of
396
+ completed mini-batches between saves within each training or validation loop. If an epoch has 10,000 iterations and
397
+ the process stops at iteration 9070, an interval of 100 lets you recover at 9000 and continue with 9001, retaining the
398
+ averages accumulated so far. Only work after the last successful save is repeated. You may change the interval when
399
+ recovering a run.
400
+
401
+ Checkpoints are also saved before the first epoch, after training and each validation dataset, and after model
402
+ selection, so recovery skips completed phases. Saves synchronously replace `states/checkpoint.pth` rather than
403
+ accumulating separate files; the interval determines how often serialization and disk I/O interrupt training.
404
+
405
+ The original `states/rng_states.json` reconstructs the initial setup, e.g., the same random split of the data. Afterwards,
406
+ the checkpoint's continuation RNG state takes over. The default dataloaders use TorchData's `StatefulDataLoader`
407
+ (`torchdata>=0.11`, `torch>=2.6`), each with its own random generator, to recover the shuffled order and current position,
408
+ including prefetched worker batches.
409
+
410
+ Recovery is tested on CPU with zero or two workers, keeping the data, code and dependencies unchanged. Worker tests
411
+ use deterministic, indexable datasets, not arbitrary random augmentation. Custom `init_dataloaders` implementations
412
+ must use `StatefulDataLoader` with an explicit `torch.Generator`, `in_order=True` and `persistent_workers=False`.
413
+ Changes to recorded settings, including batch size, dataset sizes, worker counts and validation names/order, raise an
414
+ error on recovery. Dataset contents and custom sampling behavior must also remain unchanged, but are not checked.
415
+
416
+ Custom dataset or worker-transform state needs TorchData's `state_dict()` / `load_state_dict()` hooks, using tensors
417
+ and basic Python types compatible with `torch.load(..., weights_only=True)`. Custom or accelerator-specific randomness
418
+ may require further state handling; these setups are outside the default recovery tests. Worker collation functions
419
+ should be module-level functions or static methods. Do not expect identical results across platforms or PyTorch versions.
420
+
421
+ Checkpoints are written to a temporary file and atomically moved into place, so an interrupted write preserves the
422
+ previous save. Leftover temporary files are ignored. This assumes one writer and a filesystem supporting atomic
423
+ replacement, and does not replace backups against storage failure. TensorBoard event files may still contain entries
424
+ from work repeated after recovery.
425
+
426
+ The checkpoint keeps both the latest training state and the best model. The weights-only `network.pth` under the run
427
+ directory remains available for inference and can be restored from the checkpoint if its export was interrupted.
428
+ Each participating validation dataset keeps its own lowest loss and epoch, but a model is selected only when all
429
+ improve their records in the same epoch; `only_for_demo` datasets do not vote. The selected model's epoch is
430
+ recorded separately as `best_model_epoch` (zero-based, like the loss records). The checkpoint may therefore contain
431
+ two sets of weights when the latest and best models differ.
432
+
433
+ Recovery requires all states expected by the current code; missing or inconsistent states raise an error.
434
+
248
435
  Alternatively, passing the flag `create_run_dir_afresh=True`, but still specifying a `source_run_dir_tag` will create a
249
436
  new experiment starting from scratch but only initializing the weights of the network with the previously-trained ones
250
- from the source run.
437
+ from the source run's latest checkpoint. In this case, you are starting a new experiment rather than continuing
438
+ the old one: the optimizer, progress counters, logged values and best-loss tracking start afresh, and the source run's
439
+ randomness and dataloader states are not restored.
251
440
 
252
441
  As a general note, other than the config parameters which are accessible to all member methods, you may want to pass
253
442
  some new members to the class accessible to all methods. In this case, you can re-implement the `__init__` method with
@@ -264,8 +453,8 @@ class MyTrainingSession(TrainingBaseSession):
264
453
  pass
265
454
  ```
266
455
 
267
- Currently, the `torchbase` project has no documentation other than this readme. The best way to learn about its
268
- different features is to look at the unit-tests, or just looking at the source code.
456
+ For a longer walkthrough, see the [runnable example](https://github.com/sssohrab/torchbase/blob/main/examples/README.md).
457
+ The unit-tests and source code provide further details about the different features.
269
458
 
270
459
  ## The idea behind
271
460
 
@@ -1,12 +1,12 @@
1
1
  [project]
2
2
  name = "torchbase"
3
- version = "0.1.4"
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"
7
7
  readme = "README.md"
8
8
  requires-python = ">=3.10"
9
- dependencies = ["torch", "datasets", "tensorboard", "numpy", "scikit-learn"]
9
+ dependencies = ["torch>=2.6", "torchdata>=0.11", "datasets", "tensorboard", "numpy", "scikit-learn"]
10
10
 
11
11
  [project.urls]
12
12
  Repository = "https://github.com/sssohrab/torchbase"
@@ -14,7 +14,7 @@ Issues = "https://github.com/sssohrab/torchbase/issues"
14
14
 
15
15
  [dependency-groups]
16
16
  dev = ["torchvision", "coverage[toml]>=7.6.10,<8"]
17
- tooling = ["ruff>=0.11,<1", "twine>=6,<7"]
17
+ tooling = ["ruff>=0.11,<1", "twine>=6,<7", "packaging>=24"]
18
18
 
19
19
  # Keep the existing package layout and backend during the tooling migration.
20
20
  [tool.poetry]