torchbase 0.1.3__tar.gz → 0.2.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,3 +1,28 @@
1
+ Metadata-Version: 2.4
2
+ Name: torchbase
3
+ Version: 0.2.0
4
+ Summary: A minimalist base for ML projects in PyTorch
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Author: Sohrab Ferdowsi
8
+ Author-email: sohrab.ferdowsi@gmail.com
9
+ Requires-Python: >=3.10
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Requires-Dist: datasets
17
+ Requires-Dist: numpy
18
+ Requires-Dist: scikit-learn
19
+ Requires-Dist: tensorboard
20
+ Requires-Dist: torch (>=2.6)
21
+ Requires-Dist: torchdata (>=0.11)
22
+ Project-URL: Issues, https://github.com/sssohrab/torchbase/issues
23
+ Project-URL: Repository, https://github.com/sssohrab/torchbase
24
+ Description-Content-Type: text/markdown
25
+
1
26
  # `torchbase`
2
27
 
3
28
  A minimalist base for ML projects in PyTorch
@@ -29,6 +54,10 @@ which arguments it requires and whether or not you would like to log certain val
29
54
 
30
55
  This may look something like:
31
56
 
57
+ The example reconstructs binary images and uses `torchvision` for augmentation (`pip install torchvision`).
58
+ See [the runnable version and its walkthrough](https://github.com/sssohrab/torchbase/blob/main/examples/README.md)
59
+ for starting, inspecting and recovering a run.
60
+
32
61
  ```python
33
62
  from torchbase import TrainingBaseSession
34
63
  from torchbase.utils import ValidationDatasetsDict, BaseMetricsClass, split_iterables
@@ -47,9 +76,11 @@ class MyTrainingSession(TrainingBaseSession):
47
76
  Here you define and return your training dataset, as well as validation datasets.
48
77
  They all should be instances of the Huggingface's dataset library, i.e., `datasets.Dataset` objects.
49
78
 
50
- The validation datasets should be wrapped around a `torchbase.ValidationDatasetsDict` object. This forces
79
+ The validation datasets should be wrapped around a `torchbase.utils.ValidationDatasetsDict` object. This forces
51
80
  you to do some extra work, but having multiple validation datasets can be very useful, e.g., to monitor
52
81
  the effect of data augmentation.
82
+ Provide at least one nonempty validation dataset, with equally sized tuples of datasets, demo flags and
83
+ unique names; invalid combinations are rejected before dataloaders are created.
53
84
 
54
85
  You can mark some of the validation datasets as "only for demo". In this case they will not be used for
55
86
  the actual validation process but only logged. This can be useful, e.g., if you are curious how your network
@@ -65,13 +96,17 @@ class MyTrainingSession(TrainingBaseSession):
65
96
  from torchvision.transforms import RandomRotation
66
97
  return RandomRotation(degrees=(-10, 10))(image)
67
98
 
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"],
99
+ data_train, data_valid = split_iterables([torch.rand((self.config_network["num_ch"],
100
+ *self.config_data["image_size"])).round()
101
+ for _ in range(20)],
102
+ portions=tuple(self.config_data["split_portions"]),
70
103
  shuffle=True)
71
104
 
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))
105
+ dataset_train = Dataset.from_dict({"image": data_train}).with_format("torch").map(
106
+ lambda x: {"image": augment(x["image"])})
107
+ dataset_valid = Dataset.from_dict({"image": data_valid}).with_format("torch")
108
+ dataset_valid_aug = Dataset.from_dict({"image": data_valid}).with_format("torch").map(
109
+ lambda x: {"image": augment(x["image"])})
75
110
 
76
111
  return dataset_train, ValidationDatasetsDict(datasets=(
77
112
  dataset_train, dataset_valid, dataset_valid_aug), only_for_demo=(True, False, False),
@@ -82,9 +117,10 @@ class MyTrainingSession(TrainingBaseSession):
82
117
  def __init__(self, num_ch, num_layers):
83
118
  super().__init__()
84
119
  layers = []
85
- for _ in range(num_layers):
86
- layers.append(torch.nn.Conv2d(num_ch, num_ch, 3))
87
- layers.append(torch.nn.ReLU())
120
+ for i in range(num_layers):
121
+ layers.append(torch.nn.Conv2d(num_ch, num_ch, 3, padding=1))
122
+ if i < num_layers - 1:
123
+ layers.append(torch.nn.ReLU())
88
124
 
89
125
  self.layers = torch.nn.Sequential(*layers)
90
126
 
@@ -112,7 +148,7 @@ class MyTrainingSession(TrainingBaseSession):
112
148
  output_image = self.network(input_image)
113
149
 
114
150
  return {"output": output_image, "target": target_image,
115
- "gt_for_metrics": target_image.sigmoid().round(), "predictions_for_metrics": output_image.sigmoid()}
151
+ "gt_for_metrics": target_image, "predictions_for_metrics": output_image.sigmoid()}
116
152
 
117
153
  def loss_function(self, *, output: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
118
154
  """
@@ -133,7 +169,8 @@ class MyTrainingSession(TrainingBaseSession):
133
169
 
134
170
  Similarly to the `loss_function` above, this function receives all its inputs from the key-value pairs of the
135
171
  `forward_pass`. The `keyword_maps` argument of the `BaseMetricsClass` can translate the keywords between the two,
136
- in case they are different.
172
+ in case they are different. You only need to map the names that differ; other arguments and their defaults
173
+ are kept. Ambiguous mappings are rejected.
137
174
 
138
175
  While you specify the subclasses of `BaseMetricsClass` in this function, which are essentially groups of similar
139
176
  metrics around one particular task, which metrics from every family to log for any particular experiment run is
@@ -196,6 +233,10 @@ config = {
196
233
  - The `"network"` field has only the `"architecture"` subfield as necessary, where you should just specify the name of
197
234
  your network. Here you can specify any hyperparameter your network instantiation would need.
198
235
 
236
+ The session keeps its own copy of these settings without changing your dictionary. Unknown top-level or `"session"`
237
+ fields are rejected; custom settings belong in the other sections or in `"loss_function_params"`.
238
+ Use JSON-compatible values and string dictionary keys. Tuples are also accepted, but load from JSON as lists.
239
+
199
240
  Why do we need this separate config dictionary while we can have it all implemented within the abstract methods of the
200
241
  class? The idea is that the part of the implementation that is less likely to change very frequently will go to the
201
242
  methods implementations as python code. You would want to version-control this part using `git` as the main components
@@ -234,20 +275,79 @@ directory of your experiment runs will launch the web-service from where you cou
234
275
  logged parameters, judge whether you are going over- or under-fit, or decide the best set of hyperparameters across
235
276
  experiments.
236
277
 
278
+ Iteration metrics describe each mini-batch. At epoch completion, their sample-weighted averages are logged under
279
+ `batch_means`, not as whole-dataset scores. Binary precision, recall and F1 also have `epochs` scores computed from four accumulated
280
+ confusion counts, independently for training and each validation dataset. Other metrics, including AUC and PSNR,
281
+ remain batch statistics; no predictions are buffered. `loss/epochs` remains the sample-weighted mean of batch losses
282
+ and assumes a mean-reduced loss.
283
+
284
+ For a custom whole-epoch metric, override `BaseMetricsClass.get_epoch_metric(name)` to return a fresh `EpochMetric`
285
+ with keyword-only `update`, `compute`, `reset`, `state_dict` and `load_state_dict` methods. Its state is checkpointed
286
+ and resets at the start of its dataset's next epoch, not when resuming inside an epoch.
287
+
237
288
  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:
289
+ you with the possibility to take over from the latest saved iteration of a past experiment, whether it was training
290
+ or validating:
239
291
 
240
292
  ```python
241
293
  the_recovered_session = MyTrainingSession(same_config_as_before,
242
294
  source_run_dir_tag=the_tag_to_the_suspended_experiment,
243
295
  create_run_dir_afresh=False)
244
296
 
245
- the_recovered_session() # This will continue the suspended session where it stopped without creating a new run dir.
297
+ the_recovered_session() # This will continue after the saved iteration without creating a new run dir.
246
298
  ```
247
299
 
300
+ This recovers not only the network weights and the optimizer, but also the dataloader positions, progress counters and
301
+ logged values for training and each validation dataset, along with the best validation losses and their epochs. Keep
302
+ the experimental setup and its configuration the same, although you may increase `num_epochs` to train for longer.
303
+ This specifies the total number of epochs, not additional ones: if you have finished 10 and now specify 15, another 5
304
+ will be run. Any pending validation and model selection are completed before the experiment is considered finished.
305
+
306
+ The session config's `checkpoint_interval` defaults to 100 and must be a positive integer. It specifies the number of
307
+ completed mini-batches between saves within each training or validation loop. If an epoch has 10,000 iterations and
308
+ the process stops at iteration 9070, an interval of 100 lets you recover at 9000 and continue with 9001, retaining the
309
+ averages accumulated so far. Only work after the last successful save is repeated. You may change the interval when
310
+ recovering a run.
311
+
312
+ Checkpoints are also saved before the first epoch, after training and each validation dataset, and after model
313
+ selection, so recovery skips completed phases. Saves synchronously replace `states/checkpoint.pth` rather than
314
+ accumulating separate files; the interval determines how often serialization and disk I/O interrupt training.
315
+
316
+ The original `states/rng_states.json` reconstructs the initial setup, e.g., the same random split of the data. Afterwards,
317
+ the checkpoint's continuation RNG state takes over. The default dataloaders use TorchData's `StatefulDataLoader`
318
+ (`torchdata>=0.11`, `torch>=2.6`), each with its own random generator, to recover the shuffled order and current position,
319
+ including prefetched worker batches.
320
+
321
+ Recovery is tested on CPU with zero or two workers, keeping the data, code and dependencies unchanged. Worker tests
322
+ use deterministic, indexable datasets, not arbitrary random augmentation. Custom `init_dataloaders` implementations
323
+ must use `StatefulDataLoader` with an explicit `torch.Generator`, `in_order=True` and `persistent_workers=False`.
324
+ Changes to recorded settings, including batch size, dataset sizes, worker counts and validation names/order, raise an
325
+ error on recovery. Dataset contents and custom sampling behavior must also remain unchanged, but are not checked.
326
+
327
+ Custom dataset or worker-transform state needs TorchData's `state_dict()` / `load_state_dict()` hooks, using tensors
328
+ and basic Python types compatible with `torch.load(..., weights_only=True)`. Custom or accelerator-specific randomness
329
+ may require further state handling; these setups are outside the default recovery tests. Worker collation functions
330
+ should be module-level functions or static methods. Do not expect identical results across platforms or PyTorch versions.
331
+
332
+ Checkpoints are written to a temporary file and atomically moved into place, so an interrupted write preserves the
333
+ previous save. Leftover temporary files are ignored. This assumes one writer and a filesystem supporting atomic
334
+ replacement, and does not replace backups against storage failure. TensorBoard event files may still contain entries
335
+ from work repeated after recovery.
336
+
337
+ The checkpoint keeps both the latest training state and the best model. The weights-only `network.pth` under the run
338
+ directory remains available for inference and can be restored from the checkpoint if its export was interrupted.
339
+ Each participating validation dataset keeps its own lowest loss and epoch, but a model is selected only when all
340
+ improve their records in the same epoch; `only_for_demo` datasets do not vote. The selected model's epoch is
341
+ recorded separately as `best_model_epoch` (zero-based, like the loss records). The checkpoint may therefore contain
342
+ two sets of weights when the latest and best models differ.
343
+
344
+ Recovery requires all states expected by the current code; missing or inconsistent states raise an error.
345
+
248
346
  Alternatively, passing the flag `create_run_dir_afresh=True`, but still specifying a `source_run_dir_tag` will create a
249
347
  new experiment starting from scratch but only initializing the weights of the network with the previously-trained ones
250
- from the source run.
348
+ from the source run's latest checkpoint. In this case, you are starting a new experiment rather than continuing
349
+ the old one: the optimizer, progress counters, logged values and best-loss tracking start afresh, and the source run's
350
+ randomness and dataloader states are not restored.
251
351
 
252
352
  As a general note, other than the config parameters which are accessible to all member methods, you may want to pass
253
353
  some new members to the class accessible to all methods. In this case, you can re-implement the `__init__` method with
@@ -264,8 +364,8 @@ class MyTrainingSession(TrainingBaseSession):
264
364
  pass
265
365
  ```
266
366
 
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.
367
+ For a longer walkthrough, see the [runnable example](https://github.com/sssohrab/torchbase/blob/main/examples/README.md).
368
+ The unit-tests and source code provide further details about the different features.
269
369
 
270
370
  ## The idea behind
271
371
 
@@ -382,10 +482,14 @@ any other library mentioned above.
382
482
 
383
483
  ## Contributing
384
484
 
485
+ See the [contributor guide](https://github.com/sssohrab/torchbase/blob/main/CONTRIBUTING.md)
486
+ for development setup, the [release guide](https://github.com/sssohrab/torchbase/blob/main/RELEASING.md)
487
+ for publishing, and the [changelog](https://github.com/sssohrab/torchbase/blob/main/CHANGELOG.md)
488
+ for release history.
489
+
385
490
  This is an early stage project and welcomes community contributions and improvement proposals. Feel free to:
386
491
 
387
492
  - Open a [GitHub issue](https://github.com/sssohrab/torchbase/issues).
388
493
  - Submit a pull request with your proposed changes.
389
494
  - Reach out directly to the owner of the project via [email](mailto:sohrab.ferdowsi@gmail.com).
390
495
 
391
-
@@ -1,24 +1,3 @@
1
- Metadata-Version: 2.3
2
- Name: torchbase
3
- Version: 0.1.3
4
- Summary: A minimalist base for ML projects in PyTorch
5
- License: Apache-2.0
6
- Author: Sohrab Ferdowsi
7
- Author-email: sohrab.ferdowsi@gmail.com
8
- Requires-Python: >=3.10
9
- Classifier: License :: OSI Approved :: Apache Software License
10
- Classifier: Programming Language :: Python :: 3
11
- Classifier: Programming Language :: Python :: 3.10
12
- Classifier: Programming Language :: Python :: 3.11
13
- Classifier: Programming Language :: Python :: 3.12
14
- Classifier: Programming Language :: Python :: 3.13
15
- Requires-Dist: datasets
16
- Requires-Dist: numpy
17
- Requires-Dist: scikit-learn
18
- Requires-Dist: tensorboard
19
- Requires-Dist: torch
20
- Description-Content-Type: text/markdown
21
-
22
1
  # `torchbase`
23
2
 
24
3
  A minimalist base for ML projects in PyTorch
@@ -50,6 +29,10 @@ which arguments it requires and whether or not you would like to log certain val
50
29
 
51
30
  This may look something like:
52
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
+
53
36
  ```python
54
37
  from torchbase import TrainingBaseSession
55
38
  from torchbase.utils import ValidationDatasetsDict, BaseMetricsClass, split_iterables
@@ -68,9 +51,11 @@ class MyTrainingSession(TrainingBaseSession):
68
51
  Here you define and return your training dataset, as well as validation datasets.
69
52
  They all should be instances of the Huggingface's dataset library, i.e., `datasets.Dataset` objects.
70
53
 
71
- 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
72
55
  you to do some extra work, but having multiple validation datasets can be very useful, e.g., to monitor
73
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.
74
59
 
75
60
  You can mark some of the validation datasets as "only for demo". In this case they will not be used for
76
61
  the actual validation process but only logged. This can be useful, e.g., if you are curious how your network
@@ -86,13 +71,17 @@ class MyTrainingSession(TrainingBaseSession):
86
71
  from torchvision.transforms import RandomRotation
87
72
  return RandomRotation(degrees=(-10, 10))(image)
88
73
 
89
- data_train, data_valid = split_iterables([torch.randn((self.config_data["image_size"])) for _ in range(20)],
90
- 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"]),
91
78
  shuffle=True)
92
79
 
93
- dataset_train = Dataset.from_dict({"image": data_train}).map(lambda x: augment(x))
94
- dataset_valid = Dataset.from_dict({"image": data_valid})
95
- 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"])})
96
85
 
97
86
  return dataset_train, ValidationDatasetsDict(datasets=(
98
87
  dataset_train, dataset_valid, dataset_valid_aug), only_for_demo=(True, False, False),
@@ -103,9 +92,10 @@ class MyTrainingSession(TrainingBaseSession):
103
92
  def __init__(self, num_ch, num_layers):
104
93
  super().__init__()
105
94
  layers = []
106
- for _ in range(num_layers):
107
- layers.append(torch.nn.Conv2d(num_ch, num_ch, 3))
108
- 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())
109
99
 
110
100
  self.layers = torch.nn.Sequential(*layers)
111
101
 
@@ -133,7 +123,7 @@ class MyTrainingSession(TrainingBaseSession):
133
123
  output_image = self.network(input_image)
134
124
 
135
125
  return {"output": output_image, "target": target_image,
136
- "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()}
137
127
 
138
128
  def loss_function(self, *, output: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
139
129
  """
@@ -154,7 +144,8 @@ class MyTrainingSession(TrainingBaseSession):
154
144
 
155
145
  Similarly to the `loss_function` above, this function receives all its inputs from the key-value pairs of the
156
146
  `forward_pass`. The `keyword_maps` argument of the `BaseMetricsClass` can translate the keywords between the two,
157
- 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.
158
149
 
159
150
  While you specify the subclasses of `BaseMetricsClass` in this function, which are essentially groups of similar
160
151
  metrics around one particular task, which metrics from every family to log for any particular experiment run is
@@ -217,6 +208,10 @@ config = {
217
208
  - The `"network"` field has only the `"architecture"` subfield as necessary, where you should just specify the name of
218
209
  your network. Here you can specify any hyperparameter your network instantiation would need.
219
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
+
220
215
  Why do we need this separate config dictionary while we can have it all implemented within the abstract methods of the
221
216
  class? The idea is that the part of the implementation that is less likely to change very frequently will go to the
222
217
  methods implementations as python code. You would want to version-control this part using `git` as the main components
@@ -255,20 +250,79 @@ directory of your experiment runs will launch the web-service from where you cou
255
250
  logged parameters, judge whether you are going over- or under-fit, or decide the best set of hyperparameters across
256
251
  experiments.
257
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
+
258
263
  For various reasons, you may sometimes want to suspend the training process before it is finalized. `torchbase` provides
259
- you with the possibility to take-over from a past experiment and recover (almost) exactly what was going on:
264
+ you with the possibility to take over from the latest saved iteration of a past experiment, whether it was training
265
+ or validating:
260
266
 
261
267
  ```python
262
268
  the_recovered_session = MyTrainingSession(same_config_as_before,
263
269
  source_run_dir_tag=the_tag_to_the_suspended_experiment,
264
270
  create_run_dir_afresh=False)
265
271
 
266
- the_recovered_session() # This will continue the suspended session where it stopped without creating a new run dir.
272
+ the_recovered_session() # This will continue after the saved iteration without creating a new run dir.
267
273
  ```
268
274
 
275
+ This recovers not only the network weights and the optimizer, but also the dataloader positions, progress counters and
276
+ logged values for training and each validation dataset, along with the best validation losses and their epochs. Keep
277
+ the experimental setup and its configuration the same, although you may increase `num_epochs` to train for longer.
278
+ This specifies the total number of epochs, not additional ones: if you have finished 10 and now specify 15, another 5
279
+ will be run. Any pending validation and model selection are completed before the experiment is considered finished.
280
+
281
+ The session config's `checkpoint_interval` defaults to 100 and must be a positive integer. It specifies the number of
282
+ completed mini-batches between saves within each training or validation loop. If an epoch has 10,000 iterations and
283
+ the process stops at iteration 9070, an interval of 100 lets you recover at 9000 and continue with 9001, retaining the
284
+ averages accumulated so far. Only work after the last successful save is repeated. You may change the interval when
285
+ recovering a run.
286
+
287
+ Checkpoints are also saved before the first epoch, after training and each validation dataset, and after model
288
+ selection, so recovery skips completed phases. Saves synchronously replace `states/checkpoint.pth` rather than
289
+ accumulating separate files; the interval determines how often serialization and disk I/O interrupt training.
290
+
291
+ The original `states/rng_states.json` reconstructs the initial setup, e.g., the same random split of the data. Afterwards,
292
+ the checkpoint's continuation RNG state takes over. The default dataloaders use TorchData's `StatefulDataLoader`
293
+ (`torchdata>=0.11`, `torch>=2.6`), each with its own random generator, to recover the shuffled order and current position,
294
+ including prefetched worker batches.
295
+
296
+ Recovery is tested on CPU with zero or two workers, keeping the data, code and dependencies unchanged. Worker tests
297
+ use deterministic, indexable datasets, not arbitrary random augmentation. Custom `init_dataloaders` implementations
298
+ must use `StatefulDataLoader` with an explicit `torch.Generator`, `in_order=True` and `persistent_workers=False`.
299
+ Changes to recorded settings, including batch size, dataset sizes, worker counts and validation names/order, raise an
300
+ error on recovery. Dataset contents and custom sampling behavior must also remain unchanged, but are not checked.
301
+
302
+ Custom dataset or worker-transform state needs TorchData's `state_dict()` / `load_state_dict()` hooks, using tensors
303
+ and basic Python types compatible with `torch.load(..., weights_only=True)`. Custom or accelerator-specific randomness
304
+ may require further state handling; these setups are outside the default recovery tests. Worker collation functions
305
+ should be module-level functions or static methods. Do not expect identical results across platforms or PyTorch versions.
306
+
307
+ Checkpoints are written to a temporary file and atomically moved into place, so an interrupted write preserves the
308
+ previous save. Leftover temporary files are ignored. This assumes one writer and a filesystem supporting atomic
309
+ replacement, and does not replace backups against storage failure. TensorBoard event files may still contain entries
310
+ from work repeated after recovery.
311
+
312
+ The checkpoint keeps both the latest training state and the best model. The weights-only `network.pth` under the run
313
+ directory remains available for inference and can be restored from the checkpoint if its export was interrupted.
314
+ Each participating validation dataset keeps its own lowest loss and epoch, but a model is selected only when all
315
+ improve their records in the same epoch; `only_for_demo` datasets do not vote. The selected model's epoch is
316
+ recorded separately as `best_model_epoch` (zero-based, like the loss records). The checkpoint may therefore contain
317
+ two sets of weights when the latest and best models differ.
318
+
319
+ Recovery requires all states expected by the current code; missing or inconsistent states raise an error.
320
+
269
321
  Alternatively, passing the flag `create_run_dir_afresh=True`, but still specifying a `source_run_dir_tag` will create a
270
322
  new experiment starting from scratch but only initializing the weights of the network with the previously-trained ones
271
- from the source run.
323
+ from the source run's latest checkpoint. In this case, you are starting a new experiment rather than continuing
324
+ the old one: the optimizer, progress counters, logged values and best-loss tracking start afresh, and the source run's
325
+ randomness and dataloader states are not restored.
272
326
 
273
327
  As a general note, other than the config parameters which are accessible to all member methods, you may want to pass
274
328
  some new members to the class accessible to all methods. In this case, you can re-implement the `__init__` method with
@@ -285,8 +339,8 @@ class MyTrainingSession(TrainingBaseSession):
285
339
  pass
286
340
  ```
287
341
 
288
- Currently, the `torchbase` project has no documentation other than this readme. The best way to learn about its
289
- different features is to look at the unit-tests, or just looking at the source code.
342
+ For a longer walkthrough, see the [runnable example](https://github.com/sssohrab/torchbase/blob/main/examples/README.md).
343
+ The unit-tests and source code provide further details about the different features.
290
344
 
291
345
  ## The idea behind
292
346
 
@@ -403,11 +457,13 @@ any other library mentioned above.
403
457
 
404
458
  ## Contributing
405
459
 
460
+ See the [contributor guide](https://github.com/sssohrab/torchbase/blob/main/CONTRIBUTING.md)
461
+ for development setup, the [release guide](https://github.com/sssohrab/torchbase/blob/main/RELEASING.md)
462
+ for publishing, and the [changelog](https://github.com/sssohrab/torchbase/blob/main/CHANGELOG.md)
463
+ for release history.
464
+
406
465
  This is an early stage project and welcomes community contributions and improvement proposals. Feel free to:
407
466
 
408
467
  - Open a [GitHub issue](https://github.com/sssohrab/torchbase/issues).
409
468
  - Submit a pull request with your proposed changes.
410
469
  - Reach out directly to the owner of the project via [email](mailto:sohrab.ferdowsi@gmail.com).
411
-
412
-
413
-
@@ -0,0 +1,55 @@
1
+ [project]
2
+ name = "torchbase"
3
+ version = "0.2.0"
4
+ description = "A minimalist base for ML projects in PyTorch"
5
+ authors = [{ name = "Sohrab Ferdowsi", email = "sohrab.ferdowsi@gmail.com" }]
6
+ license = "Apache-2.0"
7
+ readme = "README.md"
8
+ requires-python = ">=3.10"
9
+ dependencies = ["torch>=2.6", "torchdata>=0.11", "datasets", "tensorboard", "numpy", "scikit-learn"]
10
+
11
+ [project.urls]
12
+ Repository = "https://github.com/sssohrab/torchbase"
13
+ Issues = "https://github.com/sssohrab/torchbase/issues"
14
+
15
+ [dependency-groups]
16
+ dev = ["torchvision", "coverage[toml]>=7.6.10,<8"]
17
+ tooling = ["ruff>=0.11,<1", "twine>=6,<7", "packaging>=24"]
18
+
19
+ # Keep the existing package layout and backend during the tooling migration.
20
+ [tool.poetry]
21
+ packages = [{ include = "torchbase" }]
22
+
23
+ [build-system]
24
+ requires = ["poetry-core>=2.2,<3"]
25
+ build-backend = "poetry.core.masonry.api"
26
+
27
+ [tool.uv]
28
+ required-version = ">=0.11.7"
29
+
30
+ # Contributor/CI environments use CPU wheels on Linux. This does not change
31
+ # published requirements or the PyTorch installation chosen by pip users.
32
+ [[tool.uv.index]]
33
+ name = "pytorch-cpu"
34
+ url = "https://download.pytorch.org/whl/cpu"
35
+ explicit = true
36
+
37
+ [tool.uv.sources]
38
+ torch = [{ index = "pytorch-cpu", marker = "sys_platform == 'linux'" }]
39
+ torchvision = [{ index = "pytorch-cpu", marker = "sys_platform == 'linux'" }]
40
+
41
+ [tool.ruff]
42
+ target-version = "py310"
43
+
44
+ [tool.ruff.lint]
45
+ # Catch syntax/undefined-name errors without imposing a formatting rewrite.
46
+ select = ["E9", "F63", "F7", "F82"]
47
+
48
+ [tool.coverage.run]
49
+ source = ["torchbase"]
50
+
51
+ [tool.coverage.report]
52
+ fail_under = 70
53
+
54
+ [tool.coverage.paths]
55
+ source = ["torchbase", "*/site-packages/torchbase"]