torch-einops-kit 0.1.8__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- torch_einops_kit/__init__.py +172 -0
- torch_einops_kit/_cat_and_stack.py +197 -0
- torch_einops_kit/_dimensions.py +523 -0
- torch_einops_kit/_helpers.py +441 -0
- torch_einops_kit/_masking.py +318 -0
- torch_einops_kit/_padding.py +654 -0
- torch_einops_kit/_slicing.py +300 -0
- torch_einops_kit/_theTypes.py +434 -0
- torch_einops_kit/device.py +326 -0
- torch_einops_kit/einops.py +234 -0
- torch_einops_kit/nn.py +189 -0
- torch_einops_kit/py.typed +0 -0
- torch_einops_kit/save_load.py +554 -0
- torch_einops_kit/scaleValues.py +391 -0
- torch_einops_kit/utils.py +170 -0
- torch_einops_kit-0.1.8.dist-info/METADATA +482 -0
- torch_einops_kit-0.1.8.dist-info/RECORD +20 -0
- torch_einops_kit-0.1.8.dist-info/WHEEL +4 -0
- torch_einops_kit-0.1.8.dist-info/licenses/LICENSE +407 -0
- torch_einops_kit-0.1.8.dist-info/licenses/LICENSE-WANG +23 -0
|
@@ -0,0 +1,554 @@
|
|
|
1
|
+
"""Decorate `torch.nn.Module` subclasses with checkpoint save, load, and reconstruct methods.
|
|
2
|
+
|
|
3
|
+
You can use this module to equip any `torch.nn.Module` subclass with methods that persist a
|
|
4
|
+
checkpoint to disk, restore parameter values into an existing instance, and reconstruct a new
|
|
5
|
+
instance from a checkpoint without hand-written reconstruction code. The module also exposes the
|
|
6
|
+
companion functions that serialize nested decorated modules into checkpoint-safe records and
|
|
7
|
+
deserialize those records back to live instances.
|
|
8
|
+
|
|
9
|
+
Contents
|
|
10
|
+
--------
|
|
11
|
+
Functions
|
|
12
|
+
dehydrate_config
|
|
13
|
+
Convert nested decorated modules in a configuration value into reconstruction records.
|
|
14
|
+
rehydrate_config
|
|
15
|
+
Reconstruct nested decorated modules from checkpoint configuration records.
|
|
16
|
+
save_load
|
|
17
|
+
Decorate a `torch.nn.Module` subclass with checkpoint save, load, and reconstruct helpers.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from functools import wraps
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from torch.nn import Module
|
|
25
|
+
from torch_einops_kit import (
|
|
26
|
+
ConfigArgsKwargs, DehydratedCheckpoint, DehydratedTorchNNModule, exists, map_values, StrPath, TorchNNModule, TVar)
|
|
27
|
+
from typing import Any, cast, overload, TYPE_CHECKING
|
|
28
|
+
import pickle
|
|
29
|
+
import torch
|
|
30
|
+
import warnings
|
|
31
|
+
|
|
32
|
+
if TYPE_CHECKING:
|
|
33
|
+
from collections.abc import Callable
|
|
34
|
+
|
|
35
|
+
def dehydrate_config(config: TVar, config_instance_var_name: str) -> TVar:
|
|
36
|
+
"""Convert nested decorated modules in `config` into reconstruction records.
|
|
37
|
+
|
|
38
|
+
You can use `dehydrate_config` to replace each nested `torch.nn.Module` [1] in `config` that
|
|
39
|
+
carries `config_instance_var_name` with a dictionary containing the module `class` and recorded
|
|
40
|
+
constructor configuration. `dehydrate_config` preserves the surrounding `tuple`, `list`, and
|
|
41
|
+
`dict` structure by delegating traversal to `map_values` [2]. The `save_load` decorator [3] uses
|
|
42
|
+
`dehydrate_config` before serializing checkpoint configuration payloads.
|
|
43
|
+
|
|
44
|
+
Parameters
|
|
45
|
+
----------
|
|
46
|
+
config : TVar
|
|
47
|
+
The constructor configuration to transform. `config` may contain plain Python values, nested
|
|
48
|
+
containers, and decorated module instances.
|
|
49
|
+
config_instance_var_name : str
|
|
50
|
+
The attribute name that stores constructor arguments on each decorated module instance.
|
|
51
|
+
|
|
52
|
+
Returns
|
|
53
|
+
-------
|
|
54
|
+
dehydrated_config : TVar
|
|
55
|
+
A value with the same container structure as `config`, where each decorated module instance
|
|
56
|
+
has been replaced by a reconstruction record.
|
|
57
|
+
|
|
58
|
+
See Also
|
|
59
|
+
--------
|
|
60
|
+
rehydrate_config : Reconstruct module instances from dehydrated configuration records.
|
|
61
|
+
save_load : Decorate a module class so constructor configuration can be dehydrated and restored.
|
|
62
|
+
|
|
63
|
+
torch
|
|
64
|
+
-----
|
|
65
|
+
Only module instances that have an attribute named `config_instance_var_name` are converted.
|
|
66
|
+
`save_load` [3] writes that attribute when the decorated `torch.nn.Module` [1] subclass records
|
|
67
|
+
its constructor arguments. Undecorated module instances remain unchanged.
|
|
68
|
+
|
|
69
|
+
Examples
|
|
70
|
+
--------
|
|
71
|
+
From `tests.test_save_load_extended.test_dehydrate_config_respects_config_instance_var_name` [4]:
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
from torch_einops_kit.save_load import dehydrate_config
|
|
75
|
+
from tests.test_save_load_extended import SaveLoadExtendedCustomNamedModel
|
|
76
|
+
|
|
77
|
+
custom_model = SaveLoadExtendedCustomNamedModel(13)
|
|
78
|
+
config_args_kwargs = ((custom_model,), {})
|
|
79
|
+
dehydrated_config = dehydrate_config(config_args_kwargs, 'stored_config')
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
References
|
|
83
|
+
----------
|
|
84
|
+
[1] torch.nn.Module - PyTorch documentation
|
|
85
|
+
https://pytorch.org/docs/stable/generated/torch.nn.Module.html
|
|
86
|
+
[2] torch_einops_kit.save_load.map_values
|
|
87
|
+
|
|
88
|
+
[3] torch_einops_kit.save_load.save_load
|
|
89
|
+
|
|
90
|
+
[4] tests.test_save_load_extended.test_dehydrate_config_respects_config_instance_var_name
|
|
91
|
+
"""
|
|
92
|
+
|
|
93
|
+
@overload
|
|
94
|
+
def dehydrate(v: Module) -> DehydratedTorchNNModule: ...
|
|
95
|
+
@overload
|
|
96
|
+
def dehydrate(v: TVar) -> TVar: ...
|
|
97
|
+
def dehydrate(v: Module | TVar) -> DehydratedTorchNNModule | TVar:
|
|
98
|
+
"""Convert a candidate value to a reconstruction record when it is a decorated module instance.
|
|
99
|
+
|
|
100
|
+
The function converts `v` to a `DehydratedTorchNNModule` [1] when `v` is a `torch.nn.Module`
|
|
101
|
+
[2] that carries the `config_instance_var_name` attribute written by `save_load` [3]. All
|
|
102
|
+
other values pass through unchanged.
|
|
103
|
+
|
|
104
|
+
Parameters
|
|
105
|
+
----------
|
|
106
|
+
v : Module | TVar
|
|
107
|
+
The value to inspect and potentially convert.
|
|
108
|
+
|
|
109
|
+
Returns
|
|
110
|
+
-------
|
|
111
|
+
converted_value : DehydratedTorchNNModule | TVar
|
|
112
|
+
A reconstruction record when `v` is a decorated module instance, or `v` unchanged for all
|
|
113
|
+
other values.
|
|
114
|
+
|
|
115
|
+
References
|
|
116
|
+
----------
|
|
117
|
+
[1] torch_einops_kit.DehydratedTorchNNModule
|
|
118
|
+
|
|
119
|
+
[2] torch.nn.Module - PyTorch documentation
|
|
120
|
+
https://pytorch.org/docs/stable/generated/torch.nn.Module.html
|
|
121
|
+
|
|
122
|
+
[3] torch_einops_kit.save_load.save_load
|
|
123
|
+
"""
|
|
124
|
+
if isinstance(v, Module) and hasattr(v, config_instance_var_name):
|
|
125
|
+
return DehydratedTorchNNModule(
|
|
126
|
+
__save_load_module__=True,
|
|
127
|
+
klass=v.__class__,
|
|
128
|
+
config=dehydrate_config(getattr(v, config_instance_var_name), config_instance_var_name),
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
return cast('TVar', v)
|
|
132
|
+
|
|
133
|
+
return map_values(dehydrate, config)
|
|
134
|
+
|
|
135
|
+
def rehydrate_config(config: ConfigArgsKwargs) -> ConfigArgsKwargs:
|
|
136
|
+
"""Reconstruct nested decorated modules from checkpoint configuration records.
|
|
137
|
+
|
|
138
|
+
You can use `rehydrate_config` to replace each dictionary emitted by `dehydrate_config` [1] with
|
|
139
|
+
a fresh `torch.nn.Module` [2] instance. `rehydrate_config` preserves the surrounding `tuple`,
|
|
140
|
+
`list`, and `dict` structure by delegating traversal to `map_values` [3]. The classmethod
|
|
141
|
+
generated by `save_load` [4] uses `rehydrate_config` to rebuild constructor arguments before it
|
|
142
|
+
restores parameter values from the checkpoint.
|
|
143
|
+
|
|
144
|
+
Parameters
|
|
145
|
+
----------
|
|
146
|
+
config : ConfigArgsKwargs
|
|
147
|
+
The dehydrated constructor configuration to transform.
|
|
148
|
+
|
|
149
|
+
Returns
|
|
150
|
+
-------
|
|
151
|
+
rehydrated_config : ConfigArgsKwargs
|
|
152
|
+
A configuration tuple whose module reconstruction records have been replaced by newly
|
|
153
|
+
instantiated module objects.
|
|
154
|
+
|
|
155
|
+
See Also
|
|
156
|
+
--------
|
|
157
|
+
dehydrate_config : Convert decorated module instances into reconstruction records.
|
|
158
|
+
save_load : Decorate a module class so constructor configuration can be rehydrated during load.
|
|
159
|
+
|
|
160
|
+
torch
|
|
161
|
+
-----
|
|
162
|
+
Each reconstruction record stores `klass` together with nested `(args, kwargs)` data.
|
|
163
|
+
`rehydrate_config` calls `klass(*args, **kwargs)` to rebuild the module graph. `rehydrate_config`
|
|
164
|
+
does not restore parameter tensors. The generated load method added by `save_load` [4] performs
|
|
165
|
+
that state restoration after construction.
|
|
166
|
+
|
|
167
|
+
Examples
|
|
168
|
+
--------
|
|
169
|
+
From `tests.test_save_load_extended` [5]:
|
|
170
|
+
|
|
171
|
+
```python
|
|
172
|
+
from torch_einops_kit.save_load import rehydrate_config
|
|
173
|
+
from tests.test_save_load_extended import SaveLoadExtendedLinearModel
|
|
174
|
+
|
|
175
|
+
config_args_kwargs = (
|
|
176
|
+
({'__save_load_module__': True, 'klass': SaveLoadExtendedLinearModel, 'config': ((7, 11), {})},),
|
|
177
|
+
{'tag': 'manual-dehydrated-config'},
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
rehydrated_config = rehydrate_config(config_args_kwargs)
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
References
|
|
184
|
+
----------
|
|
185
|
+
[1] torch_einops_kit.save_load.dehydrate_config
|
|
186
|
+
|
|
187
|
+
[2] torch.nn.Module - PyTorch documentation
|
|
188
|
+
https://pytorch.org/docs/stable/generated/torch.nn.Module.html
|
|
189
|
+
[3] torch_einops_kit.save_load.map_values
|
|
190
|
+
|
|
191
|
+
[4] torch_einops_kit.save_load.save_load
|
|
192
|
+
|
|
193
|
+
[5] tests.test_save_load_extended.test_rehydrate_config_instantiates_manual_dehydrated_modules
|
|
194
|
+
"""
|
|
195
|
+
|
|
196
|
+
@overload
|
|
197
|
+
def rehydrate(v: ConfigArgsKwargs) -> ConfigArgsKwargs: ...
|
|
198
|
+
@overload
|
|
199
|
+
def rehydrate(v: DehydratedTorchNNModule) -> Module: ...
|
|
200
|
+
def rehydrate(v: DehydratedTorchNNModule | ConfigArgsKwargs) -> Module | ConfigArgsKwargs:
|
|
201
|
+
"""Instantiate a module from its reconstruction record when the value carries the `__save_load_module__` marker.
|
|
202
|
+
|
|
203
|
+
The function calls `klass(*args, **kwargs)` to rebuild the module when `v` is a
|
|
204
|
+
`DehydratedTorchNNModule` [1] dictionary. All other values pass through unchanged.
|
|
205
|
+
|
|
206
|
+
Parameters
|
|
207
|
+
----------
|
|
208
|
+
v : DehydratedTorchNNModule | ConfigArgsKwargs
|
|
209
|
+
The value to inspect and potentially reconstruct as a module.
|
|
210
|
+
|
|
211
|
+
Returns
|
|
212
|
+
-------
|
|
213
|
+
reconstructed : Module | ConfigArgsKwargs
|
|
214
|
+
A newly instantiated `torch.nn.Module` [2] when `v` is a reconstruction record, or `v`
|
|
215
|
+
unchanged for all other values.
|
|
216
|
+
|
|
217
|
+
References
|
|
218
|
+
----------
|
|
219
|
+
[1] torch_einops_kit.DehydratedTorchNNModule
|
|
220
|
+
|
|
221
|
+
[2] torch.nn.Module - PyTorch documentation
|
|
222
|
+
https://pytorch.org/docs/stable/generated/torch.nn.Module.html
|
|
223
|
+
"""
|
|
224
|
+
if isinstance(v, dict) and v.get('__save_load_module__', False):
|
|
225
|
+
klass = v['klass']
|
|
226
|
+
args, kwargs = v['config']
|
|
227
|
+
return klass(*args, **kwargs)
|
|
228
|
+
|
|
229
|
+
return cast('ConfigArgsKwargs', v)
|
|
230
|
+
|
|
231
|
+
return map_values(rehydrate, config)
|
|
232
|
+
|
|
233
|
+
def save_load(
|
|
234
|
+
save_method_name: str = 'save',
|
|
235
|
+
load_method_name: str = 'load',
|
|
236
|
+
config_instance_var_name: str = '_config',
|
|
237
|
+
init_and_load_classmethod_name: str = 'init_and_load',
|
|
238
|
+
version: str | None = None,
|
|
239
|
+
) -> Callable[[type[TorchNNModule]], type[TorchNNModule]]:
|
|
240
|
+
"""Decorate a `torch.nn.Module` subclass with checkpoint save and restore helpers.
|
|
241
|
+
|
|
242
|
+
You can use `save_load` to wrap a `torch.nn.Module` [1] subclass so each instance records its
|
|
243
|
+
constructor arguments and gains instance methods for checkpoint save and checkpoint load plus a
|
|
244
|
+
classmethod that reconstructs a new instance from a checkpoint. The generated checkpoint payload
|
|
245
|
+
stores model state, serialized constructor configuration, and an optional version string.
|
|
246
|
+
`save_load` also uses `dehydrate_config` [2] and `rehydrate_config` [3] so constructor graphs
|
|
247
|
+
that contain other decorated modules can round-trip through a checkpoint [4].
|
|
248
|
+
|
|
249
|
+
Parameters
|
|
250
|
+
----------
|
|
251
|
+
save_method_name : str = 'save'
|
|
252
|
+
The name assigned to the generated instance method that writes a checkpoint.
|
|
253
|
+
load_method_name : str = 'load'
|
|
254
|
+
The name assigned to the generated instance method that reads model state from a checkpoint.
|
|
255
|
+
config_instance_var_name : str = '_config'
|
|
256
|
+
The attribute name used to store constructor arguments on each decorated instance.
|
|
257
|
+
init_and_load_classmethod_name : str = 'init_and_load'
|
|
258
|
+
The name assigned to the generated classmethod that instantiates a model from checkpoint
|
|
259
|
+
configuration and then loads model state.
|
|
260
|
+
version : str | None = None
|
|
261
|
+
An optional version string written into each checkpoint and compared during load.
|
|
262
|
+
|
|
263
|
+
Returns
|
|
264
|
+
-------
|
|
265
|
+
decorator : Callable[[type[TorchNNModule]], type[TorchNNModule]]
|
|
266
|
+
A class decorator that mutates a `torch.nn.Module` subclass in place and returns the same
|
|
267
|
+
class object.
|
|
268
|
+
|
|
269
|
+
Raises
|
|
270
|
+
------
|
|
271
|
+
TypeError
|
|
272
|
+
Raised when the returned decorator is applied to a class that is not a subclass of
|
|
273
|
+
`torch.nn.Module` [1].
|
|
274
|
+
|
|
275
|
+
See Also
|
|
276
|
+
--------
|
|
277
|
+
dehydrate_config : Convert decorated module instances into checkpoint-safe configuration records.
|
|
278
|
+
rehydrate_config : Reconstruct decorated module instances from stored configuration records.
|
|
279
|
+
|
|
280
|
+
Generated Methods
|
|
281
|
+
-----------------
|
|
282
|
+
`save_method_name` : instance method
|
|
283
|
+
Added to each instance. The generated method serializes the current model state, the
|
|
284
|
+
dehydrated constructor configuration, and `version` to `path`. The generated method raises
|
|
285
|
+
`FileExistsError` when `overwrite` is `False` and `path` already exists.
|
|
286
|
+
`load_method_name` : instance method
|
|
287
|
+
Added to each instance. The generated method reads the checkpoint at `path`, optionally
|
|
288
|
+
prints a version-mismatch notice, and restores model state. The generated method raises
|
|
289
|
+
`FileNotFoundError` when `path` does not exist.
|
|
290
|
+
`init_and_load_classmethod_name` : classmethod
|
|
291
|
+
Added to the decorated class. The generated classmethod reads constructor configuration from
|
|
292
|
+
the checkpoint, rebuilds the module with `rehydrate_config` [3], and then restores model
|
|
293
|
+
state. The generated classmethod raises `KeyError` when the checkpoint does not contain a
|
|
294
|
+
`config` entry.
|
|
295
|
+
|
|
296
|
+
torch
|
|
297
|
+
-----
|
|
298
|
+
The generated save method writes a dictionary that is compatible with `torch.save` [5], and the
|
|
299
|
+
generated load paths read the dictionary with `torch.load` [6] on CPU before restoring state.
|
|
300
|
+
When `version` and the stored checkpoint version are different, the generated load method prints
|
|
301
|
+
a notice but still restores the stored model state.
|
|
302
|
+
|
|
303
|
+
Examples
|
|
304
|
+
--------
|
|
305
|
+
From `tests.test_save_load.test_init_and_load` [7]:
|
|
306
|
+
|
|
307
|
+
```python
|
|
308
|
+
from pathlib import Path
|
|
309
|
+
|
|
310
|
+
from torch import nn
|
|
311
|
+
from torch_einops_kit.save_load import save_load
|
|
312
|
+
|
|
313
|
+
@save_load()
|
|
314
|
+
class SimpleNet(nn.Module):
|
|
315
|
+
def __init__(self, dim, hidden_dim):
|
|
316
|
+
super().__init__()
|
|
317
|
+
self.dim = dim
|
|
318
|
+
self.hidden_dim = hidden_dim
|
|
319
|
+
self.net = nn.Linear(dim, hidden_dim)
|
|
320
|
+
|
|
321
|
+
path = Path('test_model_init.pt')
|
|
322
|
+
model = SimpleNet(10, 20)
|
|
323
|
+
model.save(str(path))
|
|
324
|
+
restored_model = SimpleNet.init_and_load(str(path))
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
From `tests.test_save_load_extended` [8]:
|
|
328
|
+
|
|
329
|
+
```python
|
|
330
|
+
import torch
|
|
331
|
+
from torch import nn
|
|
332
|
+
from torch_einops_kit.save_load import save_load
|
|
333
|
+
|
|
334
|
+
@save_load(
|
|
335
|
+
save_method_name='store',
|
|
336
|
+
load_method_name='restore',
|
|
337
|
+
config_instance_var_name='stored_config',
|
|
338
|
+
init_and_load_classmethod_name='create_and_restore',
|
|
339
|
+
)
|
|
340
|
+
class SaveLoadExtendedCustomNamedModel(nn.Module):
|
|
341
|
+
def __init__(self, width):
|
|
342
|
+
super().__init__()
|
|
343
|
+
self.width = width
|
|
344
|
+
self.weight = nn.Parameter(torch.randn(width))
|
|
345
|
+
|
|
346
|
+
model = SaveLoadExtendedCustomNamedModel(13)
|
|
347
|
+
model.store('save-load-custom-methods.pt')
|
|
348
|
+
restored_model = SaveLoadExtendedCustomNamedModel.create_and_restore('save-load-custom-methods.pt')
|
|
349
|
+
```
|
|
350
|
+
|
|
351
|
+
References
|
|
352
|
+
----------
|
|
353
|
+
[1] torch.nn.Module - PyTorch documentation
|
|
354
|
+
https://pytorch.org/docs/stable/generated/torch.nn.Module.html
|
|
355
|
+
[2] torch_einops_kit.save_load.dehydrate_config
|
|
356
|
+
|
|
357
|
+
[3] torch_einops_kit.save_load.rehydrate_config
|
|
358
|
+
|
|
359
|
+
[4] tests.test_save_load_extended.test_save_load_init_and_load_rehydrates_nested_modules
|
|
360
|
+
|
|
361
|
+
[5] torch.save - PyTorch documentation
|
|
362
|
+
https://pytorch.org/docs/stable/generated/torch.save.html
|
|
363
|
+
[6] torch.load - PyTorch documentation
|
|
364
|
+
https://pytorch.org/docs/stable/generated/torch.load.html
|
|
365
|
+
[7] tests.test_save_load.test_init_and_load
|
|
366
|
+
|
|
367
|
+
[8] tests.test_save_load_extended.test_save_load_supports_custom_method_names_and_config_storage
|
|
368
|
+
""" # noqa: DOC502
|
|
369
|
+
|
|
370
|
+
def _save_load(klass: type[TorchNNModule]) -> type[TorchNNModule]:
|
|
371
|
+
if not issubclass(klass, Module):
|
|
372
|
+
message: str = 'save_load should decorate a subclass of torch.nn.Module'
|
|
373
|
+
raise TypeError(message)
|
|
374
|
+
|
|
375
|
+
original_init: Callable[..., None] = klass.__init__
|
|
376
|
+
|
|
377
|
+
@wraps(original_init)
|
|
378
|
+
def __init__(self: TorchNNModule, *args: Any, **kwargs: Any) -> None:
|
|
379
|
+
setattr(self, config_instance_var_name, (args, kwargs))
|
|
380
|
+
original_init(self, *args, **kwargs)
|
|
381
|
+
|
|
382
|
+
def _save(self: TorchNNModule, path: StrPath, *, overwrite: bool = True) -> None:
|
|
383
|
+
"""Save the current model state and constructor configuration to a checkpoint file.
|
|
384
|
+
|
|
385
|
+
You can use this method to persist a decorated module instance. The method dehydrates
|
|
386
|
+
constructor configuration via `dehydrate_config` [1], packs it with the current state
|
|
387
|
+
dict and the version string captured at decoration time, and writes the bundle via
|
|
388
|
+
`torch.save` [2].
|
|
389
|
+
|
|
390
|
+
Parameters
|
|
391
|
+
----------
|
|
392
|
+
path : StrPath
|
|
393
|
+
The filesystem path to write the checkpoint to.
|
|
394
|
+
overwrite : bool = True
|
|
395
|
+
When `False`, raise `FileExistsError` if a file already exists at `path`. When
|
|
396
|
+
`True`, an existing file at `path` is silently replaced.
|
|
397
|
+
|
|
398
|
+
Raises
|
|
399
|
+
------
|
|
400
|
+
FileExistsError
|
|
401
|
+
Raised when `overwrite` is `False` and a file already exists at `path`.
|
|
402
|
+
|
|
403
|
+
References
|
|
404
|
+
----------
|
|
405
|
+
[1] torch_einops_kit.save_load.dehydrate_config
|
|
406
|
+
|
|
407
|
+
[2] torch.save - PyTorch documentation
|
|
408
|
+
https://pytorch.org/docs/stable/generated/torch.save.html
|
|
409
|
+
"""
|
|
410
|
+
path = Path(path)
|
|
411
|
+
if not overwrite and path.exists():
|
|
412
|
+
message: str = f'I received `{path = }`, but the file already exists and `overwrite` is `False`.'
|
|
413
|
+
raise FileExistsError(message)
|
|
414
|
+
|
|
415
|
+
config = getattr(self, config_instance_var_name)
|
|
416
|
+
pkg = DehydratedCheckpoint(
|
|
417
|
+
model=self.state_dict(), config=pickle.dumps(dehydrate_config(config, config_instance_var_name)), version=version
|
|
418
|
+
)
|
|
419
|
+
|
|
420
|
+
torch.save(pkg, str(path))
|
|
421
|
+
|
|
422
|
+
def _load(self: TorchNNModule, path: StrPath | Path, *, strict: bool = True) -> None:
|
|
423
|
+
"""Restore model state from a checkpoint file.
|
|
424
|
+
|
|
425
|
+
You can use this method to load parameter values into an already-constructed decorated
|
|
426
|
+
module instance. The method reads the checkpoint via `torch.load` [1] on CPU, then
|
|
427
|
+
restores parameter values via `load_state_dict`.
|
|
428
|
+
|
|
429
|
+
Parameters
|
|
430
|
+
----------
|
|
431
|
+
path : StrPath | Path
|
|
432
|
+
The filesystem path to read the checkpoint from.
|
|
433
|
+
strict : bool = True
|
|
434
|
+
Forwarded to `load_state_dict`. When `True`, the key sets of the checkpoint and the
|
|
435
|
+
current model must match exactly.
|
|
436
|
+
|
|
437
|
+
Raises
|
|
438
|
+
------
|
|
439
|
+
FileNotFoundError
|
|
440
|
+
Raised when no file exists at `path`.
|
|
441
|
+
|
|
442
|
+
Warns
|
|
443
|
+
-----
|
|
444
|
+
UserWarning
|
|
445
|
+
Emitted when the checkpoint's stored version and the decoration-time version are
|
|
446
|
+
different [2].
|
|
447
|
+
|
|
448
|
+
References
|
|
449
|
+
----------
|
|
450
|
+
[1] torch.load - PyTorch documentation
|
|
451
|
+
https://pytorch.org/docs/stable/generated/torch.load.html
|
|
452
|
+
"""
|
|
453
|
+
path = Path(path)
|
|
454
|
+
if not path.exists():
|
|
455
|
+
message: str = f'I received `{path = }`, but no file exists at that path.'
|
|
456
|
+
raise FileNotFoundError(message)
|
|
457
|
+
|
|
458
|
+
pkg: DehydratedCheckpoint = torch.load(str(path), map_location='cpu')
|
|
459
|
+
|
|
460
|
+
if exists(version) and exists(pkg['version']) and (version != pkg['version']):
|
|
461
|
+
message: str = (
|
|
462
|
+
f'I received a checkpoint saved at version `{pkg["version"]}`, but the current package version is `{version}`.'
|
|
463
|
+
)
|
|
464
|
+
warnings.warn(message, UserWarning, stacklevel=2)
|
|
465
|
+
|
|
466
|
+
self.load_state_dict(pkg['model'], strict=strict)
|
|
467
|
+
|
|
468
|
+
@classmethod
|
|
469
|
+
def _init_and_load_from(cls: type[TorchNNModule], path: StrPath | Path, *, strict: bool = True) -> TorchNNModule:
|
|
470
|
+
"""Construct a new instance of the decorated class and restore its state from a checkpoint file.
|
|
471
|
+
|
|
472
|
+
You can use this classmethod to reconstruct a model that was previously saved with the
|
|
473
|
+
corresponding save method. The classmethod reads the checkpoint, unpickles the `config`
|
|
474
|
+
entry, rebuilds the module graph via `rehydrate_config` [1], and then restores parameter
|
|
475
|
+
values from the same checkpoint.
|
|
476
|
+
|
|
477
|
+
Parameters
|
|
478
|
+
----------
|
|
479
|
+
path : StrPath | Path
|
|
480
|
+
The filesystem path to read the checkpoint from.
|
|
481
|
+
strict : bool = True
|
|
482
|
+
Forwarded to `load_state_dict`. When `True`, the key sets of the checkpoint and the
|
|
483
|
+
reconstructed model must match exactly.
|
|
484
|
+
|
|
485
|
+
Returns
|
|
486
|
+
-------
|
|
487
|
+
model : TorchNNModule
|
|
488
|
+
A newly instantiated and state-restored instance of the decorated class.
|
|
489
|
+
|
|
490
|
+
Raises
|
|
491
|
+
------
|
|
492
|
+
FileNotFoundError
|
|
493
|
+
Raised when no file exists at `path`.
|
|
494
|
+
KeyError
|
|
495
|
+
Raised when the checkpoint does not contain a `config` entry.
|
|
496
|
+
|
|
497
|
+
References
|
|
498
|
+
----------
|
|
499
|
+
[1] torch_einops_kit.save_load.rehydrate_config
|
|
500
|
+
"""
|
|
501
|
+
path = Path(path)
|
|
502
|
+
if not path.exists():
|
|
503
|
+
message: str = f'I received `{path = }`, but no file exists at that path.'
|
|
504
|
+
raise FileNotFoundError(message)
|
|
505
|
+
pkg: DehydratedCheckpoint = torch.load(str(path), map_location='cpu')
|
|
506
|
+
|
|
507
|
+
if 'config' not in pkg:
|
|
508
|
+
message: str = 'model configs were not found in this saved checkpoint'
|
|
509
|
+
raise KeyError(message)
|
|
510
|
+
|
|
511
|
+
config: ConfigArgsKwargs = pickle.loads(pkg['config']) # noqa: S301
|
|
512
|
+
args, kwargs = rehydrate_config(config)
|
|
513
|
+
model: TorchNNModule = cls(*args, **kwargs)
|
|
514
|
+
|
|
515
|
+
_load(model, path, strict=strict)
|
|
516
|
+
return model
|
|
517
|
+
|
|
518
|
+
# set decorated init as well as save, load, and init_and_load
|
|
519
|
+
|
|
520
|
+
klass.__init__ = __init__ # ty:ignore[invalid-assignment]
|
|
521
|
+
# TODO figure out how to use something like `wraps` so the signature and docstring are public.
|
|
522
|
+
setattr(klass, save_method_name, _save)
|
|
523
|
+
setattr(klass, load_method_name, _load)
|
|
524
|
+
setattr(klass, init_and_load_classmethod_name, _init_and_load_from)
|
|
525
|
+
|
|
526
|
+
return klass
|
|
527
|
+
|
|
528
|
+
return _save_load
|
|
529
|
+
|
|
530
|
+
"""
|
|
531
|
+
Some or all of the logic in this module may be protected by the following.
|
|
532
|
+
|
|
533
|
+
MIT License
|
|
534
|
+
|
|
535
|
+
Copyright (c) 2026 Phil Wang
|
|
536
|
+
|
|
537
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
538
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
539
|
+
in the Software without restriction, including without limitation the rights
|
|
540
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
541
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
542
|
+
furnished to do so, subject to the following conditions:
|
|
543
|
+
|
|
544
|
+
The above copyright notice and this permission notice shall be included in all
|
|
545
|
+
copies or substantial portions of the Software.
|
|
546
|
+
|
|
547
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
548
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
549
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
550
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
551
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
552
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
553
|
+
SOFTWARE.
|
|
554
|
+
"""
|