torchbase 0.1.4__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.
- {torchbase-0.1.4 → torchbase-0.2.0}/PKG-INFO +94 -18
- {torchbase-0.1.4 → torchbase-0.2.0}/README.md +91 -16
- {torchbase-0.1.4 → torchbase-0.2.0}/pyproject.toml +3 -3
- {torchbase-0.1.4 → torchbase-0.2.0}/torchbase/session.py +273 -146
- {torchbase-0.1.4 → torchbase-0.2.0}/torchbase/utils/__init__.py +1 -1
- torchbase-0.2.0/torchbase/utils/checkpoint.py +22 -0
- {torchbase-0.1.4 → torchbase-0.2.0}/torchbase/utils/data.py +28 -9
- {torchbase-0.1.4 → torchbase-0.2.0}/torchbase/utils/logger.py +59 -16
- torchbase-0.2.0/torchbase/utils/metrics.py +142 -0
- {torchbase-0.1.4 → torchbase-0.2.0}/torchbase/utils/metrics_instances.py +62 -1
- {torchbase-0.1.4 → torchbase-0.2.0}/torchbase/utils/session.py +68 -43
- torchbase-0.1.4/torchbase/utils/metrics.py +0 -61
- {torchbase-0.1.4 → torchbase-0.2.0}/LICENSE +0 -0
- {torchbase-0.1.4 → torchbase-0.2.0}/torchbase/__init__.py +0 -0
- {torchbase-0.1.4 → torchbase-0.2.0}/torchbase/utils/networks.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: torchbase
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: A minimalist base for ML projects in PyTorch
|
|
5
5
|
License-Expression: Apache-2.0
|
|
6
6
|
License-File: LICENSE
|
|
@@ -17,7 +17,8 @@ Requires-Dist: datasets
|
|
|
17
17
|
Requires-Dist: numpy
|
|
18
18
|
Requires-Dist: scikit-learn
|
|
19
19
|
Requires-Dist: tensorboard
|
|
20
|
-
Requires-Dist: torch
|
|
20
|
+
Requires-Dist: torch (>=2.6)
|
|
21
|
+
Requires-Dist: torchdata (>=0.11)
|
|
21
22
|
Project-URL: Issues, https://github.com/sssohrab/torchbase/issues
|
|
22
23
|
Project-URL: Repository, https://github.com/sssohrab/torchbase
|
|
23
24
|
Description-Content-Type: text/markdown
|
|
@@ -53,6 +54,10 @@ which arguments it requires and whether or not you would like to log certain val
|
|
|
53
54
|
|
|
54
55
|
This may look something like:
|
|
55
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
|
+
|
|
56
61
|
```python
|
|
57
62
|
from torchbase import TrainingBaseSession
|
|
58
63
|
from torchbase.utils import ValidationDatasetsDict, BaseMetricsClass, split_iterables
|
|
@@ -71,9 +76,11 @@ class MyTrainingSession(TrainingBaseSession):
|
|
|
71
76
|
Here you define and return your training dataset, as well as validation datasets.
|
|
72
77
|
They all should be instances of the Huggingface's dataset library, i.e., `datasets.Dataset` objects.
|
|
73
78
|
|
|
74
|
-
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
|
|
75
80
|
you to do some extra work, but having multiple validation datasets can be very useful, e.g., to monitor
|
|
76
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.
|
|
77
84
|
|
|
78
85
|
You can mark some of the validation datasets as "only for demo". In this case they will not be used for
|
|
79
86
|
the actual validation process but only logged. This can be useful, e.g., if you are curious how your network
|
|
@@ -89,13 +96,17 @@ class MyTrainingSession(TrainingBaseSession):
|
|
|
89
96
|
from torchvision.transforms import RandomRotation
|
|
90
97
|
return RandomRotation(degrees=(-10, 10))(image)
|
|
91
98
|
|
|
92
|
-
data_train, data_valid = split_iterables([torch.
|
|
93
|
-
|
|
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"]),
|
|
94
103
|
shuffle=True)
|
|
95
104
|
|
|
96
|
-
dataset_train = Dataset.from_dict({"image": data_train}).map(
|
|
97
|
-
|
|
98
|
-
|
|
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"])})
|
|
99
110
|
|
|
100
111
|
return dataset_train, ValidationDatasetsDict(datasets=(
|
|
101
112
|
dataset_train, dataset_valid, dataset_valid_aug), only_for_demo=(True, False, False),
|
|
@@ -106,9 +117,10 @@ class MyTrainingSession(TrainingBaseSession):
|
|
|
106
117
|
def __init__(self, num_ch, num_layers):
|
|
107
118
|
super().__init__()
|
|
108
119
|
layers = []
|
|
109
|
-
for
|
|
110
|
-
layers.append(torch.nn.Conv2d(num_ch, num_ch, 3))
|
|
111
|
-
|
|
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())
|
|
112
124
|
|
|
113
125
|
self.layers = torch.nn.Sequential(*layers)
|
|
114
126
|
|
|
@@ -136,7 +148,7 @@ class MyTrainingSession(TrainingBaseSession):
|
|
|
136
148
|
output_image = self.network(input_image)
|
|
137
149
|
|
|
138
150
|
return {"output": output_image, "target": target_image,
|
|
139
|
-
"gt_for_metrics": target_image
|
|
151
|
+
"gt_for_metrics": target_image, "predictions_for_metrics": output_image.sigmoid()}
|
|
140
152
|
|
|
141
153
|
def loss_function(self, *, output: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
|
|
142
154
|
"""
|
|
@@ -157,7 +169,8 @@ class MyTrainingSession(TrainingBaseSession):
|
|
|
157
169
|
|
|
158
170
|
Similarly to the `loss_function` above, this function receives all its inputs from the key-value pairs of the
|
|
159
171
|
`forward_pass`. The `keyword_maps` argument of the `BaseMetricsClass` can translate the keywords between the two,
|
|
160
|
-
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.
|
|
161
174
|
|
|
162
175
|
While you specify the subclasses of `BaseMetricsClass` in this function, which are essentially groups of similar
|
|
163
176
|
metrics around one particular task, which metrics from every family to log for any particular experiment run is
|
|
@@ -220,6 +233,10 @@ config = {
|
|
|
220
233
|
- The `"network"` field has only the `"architecture"` subfield as necessary, where you should just specify the name of
|
|
221
234
|
your network. Here you can specify any hyperparameter your network instantiation would need.
|
|
222
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
|
+
|
|
223
240
|
Why do we need this separate config dictionary while we can have it all implemented within the abstract methods of the
|
|
224
241
|
class? The idea is that the part of the implementation that is less likely to change very frequently will go to the
|
|
225
242
|
methods implementations as python code. You would want to version-control this part using `git` as the main components
|
|
@@ -258,20 +275,79 @@ directory of your experiment runs will launch the web-service from where you cou
|
|
|
258
275
|
logged parameters, judge whether you are going over- or under-fit, or decide the best set of hyperparameters across
|
|
259
276
|
experiments.
|
|
260
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
|
+
|
|
261
288
|
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
|
|
289
|
+
you with the possibility to take over from the latest saved iteration of a past experiment, whether it was training
|
|
290
|
+
or validating:
|
|
263
291
|
|
|
264
292
|
```python
|
|
265
293
|
the_recovered_session = MyTrainingSession(same_config_as_before,
|
|
266
294
|
source_run_dir_tag=the_tag_to_the_suspended_experiment,
|
|
267
295
|
create_run_dir_afresh=False)
|
|
268
296
|
|
|
269
|
-
the_recovered_session() # This will continue the
|
|
297
|
+
the_recovered_session() # This will continue after the saved iteration without creating a new run dir.
|
|
270
298
|
```
|
|
271
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
|
+
|
|
272
346
|
Alternatively, passing the flag `create_run_dir_afresh=True`, but still specifying a `source_run_dir_tag` will create a
|
|
273
347
|
new experiment starting from scratch but only initializing the weights of the network with the previously-trained ones
|
|
274
|
-
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.
|
|
275
351
|
|
|
276
352
|
As a general note, other than the config parameters which are accessible to all member methods, you may want to pass
|
|
277
353
|
some new members to the class accessible to all methods. In this case, you can re-implement the `__init__` method with
|
|
@@ -288,8 +364,8 @@ class MyTrainingSession(TrainingBaseSession):
|
|
|
288
364
|
pass
|
|
289
365
|
```
|
|
290
366
|
|
|
291
|
-
|
|
292
|
-
|
|
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.
|
|
293
369
|
|
|
294
370
|
## The idea behind
|
|
295
371
|
|
|
@@ -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.
|
|
69
|
-
|
|
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(
|
|
73
|
-
|
|
74
|
-
|
|
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
|
|
86
|
-
layers.append(torch.nn.Conv2d(num_ch, num_ch, 3))
|
|
87
|
-
|
|
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
|
|
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,79 @@ 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
|
+
|
|
237
263
|
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
|
|
264
|
+
you with the possibility to take over from the latest saved iteration of a past experiment, whether it was training
|
|
265
|
+
or validating:
|
|
239
266
|
|
|
240
267
|
```python
|
|
241
268
|
the_recovered_session = MyTrainingSession(same_config_as_before,
|
|
242
269
|
source_run_dir_tag=the_tag_to_the_suspended_experiment,
|
|
243
270
|
create_run_dir_afresh=False)
|
|
244
271
|
|
|
245
|
-
the_recovered_session() # This will continue the
|
|
272
|
+
the_recovered_session() # This will continue after the saved iteration without creating a new run dir.
|
|
246
273
|
```
|
|
247
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
|
+
|
|
248
321
|
Alternatively, passing the flag `create_run_dir_afresh=True`, but still specifying a `source_run_dir_tag` will create a
|
|
249
322
|
new experiment starting from scratch but only initializing the weights of the network with the previously-trained ones
|
|
250
|
-
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.
|
|
251
326
|
|
|
252
327
|
As a general note, other than the config parameters which are accessible to all member methods, you may want to pass
|
|
253
328
|
some new members to the class accessible to all methods. In this case, you can re-implement the `__init__` method with
|
|
@@ -264,8 +339,8 @@ class MyTrainingSession(TrainingBaseSession):
|
|
|
264
339
|
pass
|
|
265
340
|
```
|
|
266
341
|
|
|
267
|
-
|
|
268
|
-
|
|
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.
|
|
269
344
|
|
|
270
345
|
## The idea behind
|
|
271
346
|
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "torchbase"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.2.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]
|