lt-tensor 0.0.1.dev0__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.
- lt_tensor-0.0.1.dev0/LICENSE +201 -0
- lt_tensor-0.0.1.dev0/PKG-INFO +33 -0
- lt_tensor-0.0.1.dev0/README.md +1 -0
- lt_tensor-0.0.1.dev0/lt_tensor/__init__.py +0 -0
- lt_tensor-0.0.1.dev0/lt_tensor/_basics.py +244 -0
- lt_tensor-0.0.1.dev0/lt_tensor/_torch_commons.py +12 -0
- lt_tensor-0.0.1.dev0/lt_tensor/lr_schedulers.py +108 -0
- lt_tensor-0.0.1.dev0/lt_tensor/math_ops.py +120 -0
- lt_tensor-0.0.1.dev0/lt_tensor/misc_utils.py +596 -0
- lt_tensor-0.0.1.dev0/lt_tensor/model_zoo/__init__.py +2 -0
- lt_tensor-0.0.1.dev0/lt_tensor/model_zoo/basic.py +65 -0
- lt_tensor-0.0.1.dev0/lt_tensor/model_zoo/diffusion/__init__.py +6 -0
- lt_tensor-0.0.1.dev0/lt_tensor/model_zoo/diffusion/models.py +114 -0
- lt_tensor-0.0.1.dev0/lt_tensor/model_zoo/residual.py +236 -0
- lt_tensor-0.0.1.dev0/lt_tensor/model_zoo/transformer_models/__init__.py +6 -0
- lt_tensor-0.0.1.dev0/lt_tensor/model_zoo/transformer_models/models.py +132 -0
- lt_tensor-0.0.1.dev0/lt_tensor/model_zoo/transformer_models/positional_encoders.py +95 -0
- lt_tensor-0.0.1.dev0/lt_tensor/monotonic_align.py +70 -0
- lt_tensor-0.0.1.dev0/lt_tensor/transform.py +113 -0
- lt_tensor-0.0.1.dev0/lt_tensor.egg-info/PKG-INFO +33 -0
- lt_tensor-0.0.1.dev0/lt_tensor.egg-info/SOURCES.txt +24 -0
- lt_tensor-0.0.1.dev0/lt_tensor.egg-info/dependency_links.txt +1 -0
- lt_tensor-0.0.1.dev0/lt_tensor.egg-info/requires.txt +7 -0
- lt_tensor-0.0.1.dev0/lt_tensor.egg-info/top_level.txt +1 -0
- lt_tensor-0.0.1.dev0/setup.cfg +4 -0
- lt_tensor-0.0.1.dev0/setup.py +32 -0
@@ -0,0 +1,201 @@
|
|
1
|
+
Apache License
|
2
|
+
Version 2.0, January 2004
|
3
|
+
http://www.apache.org/licenses/
|
4
|
+
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6
|
+
|
7
|
+
1. Definitions.
|
8
|
+
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
11
|
+
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13
|
+
the copyright owner that is granting the License.
|
14
|
+
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
16
|
+
other entities that control, are controlled by, or are under common
|
17
|
+
control with that entity. For the purposes of this definition,
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
19
|
+
direction or management of such entity, whether by contract or
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22
|
+
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24
|
+
exercising permissions granted by this License.
|
25
|
+
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
27
|
+
including but not limited to software source code, documentation
|
28
|
+
source, and configuration files.
|
29
|
+
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
31
|
+
transformation or translation of a Source form, including but
|
32
|
+
not limited to compiled object code, generated documentation,
|
33
|
+
and conversions to other media types.
|
34
|
+
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
36
|
+
Object form, made available under the License, as indicated by a
|
37
|
+
copyright notice that is included in or attached to the work
|
38
|
+
(an example is provided in the Appendix below).
|
39
|
+
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46
|
+
the Work and Derivative Works thereof.
|
47
|
+
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
49
|
+
the original version of the Work and any modifications or additions
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
61
|
+
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
64
|
+
subsequently incorporated within the Work.
|
65
|
+
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
72
|
+
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78
|
+
where such license applies only to those patent claims licensable
|
79
|
+
by such Contributor that are necessarily infringed by their
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
82
|
+
institute patent litigation against any entity (including a
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
85
|
+
or contributory patent infringement, then any patent licenses
|
86
|
+
granted to You under this License for that Work shall terminate
|
87
|
+
as of the date such litigation is filed.
|
88
|
+
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
91
|
+
modifications, and in Source or Object form, provided that You
|
92
|
+
meet the following conditions:
|
93
|
+
|
94
|
+
(a) You must give any other recipients of the Work or
|
95
|
+
Derivative Works a copy of this License; and
|
96
|
+
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
98
|
+
stating that You changed the files; and
|
99
|
+
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
102
|
+
attribution notices from the Source form of the Work,
|
103
|
+
excluding those notices that do not pertain to any part of
|
104
|
+
the Derivative Works; and
|
105
|
+
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
108
|
+
include a readable copy of the attribution notices contained
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
111
|
+
of the following places: within a NOTICE text file distributed
|
112
|
+
as part of the Derivative Works; within the Source form or
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
114
|
+
within a display generated by the Derivative Works, if and
|
115
|
+
wherever such third-party notices normally appear. The contents
|
116
|
+
of the NOTICE file are for informational purposes only and
|
117
|
+
do not modify the License. You may add Your own attribution
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
120
|
+
that such additional attribution notices cannot be construed
|
121
|
+
as modifying the License.
|
122
|
+
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
124
|
+
may provide additional or different license terms and conditions
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
128
|
+
the conditions stated in this License.
|
129
|
+
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
133
|
+
this License, without any additional terms or conditions.
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135
|
+
the terms of any separate license agreement you may have executed
|
136
|
+
with Licensor regarding such Contributions.
|
137
|
+
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
140
|
+
except as required for reasonable and customary use in describing the
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
142
|
+
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
152
|
+
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
158
|
+
incidental, or consequential damages of any character arising as a
|
159
|
+
result of this License or out of the use or inability to use the
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
162
|
+
other commercial damages or losses), even if such Contributor
|
163
|
+
has been advised of the possibility of such damages.
|
164
|
+
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168
|
+
or other liability obligations and/or rights consistent with this
|
169
|
+
License. However, in accepting such obligations, You may act only
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
174
|
+
of your accepting any such warranty or additional liability.
|
175
|
+
|
176
|
+
END OF TERMS AND CONDITIONS
|
177
|
+
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
179
|
+
|
180
|
+
To apply the Apache License to your work, attach the following
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182
|
+
replaced with your own identifying information. (Don't include
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
184
|
+
comment syntax for the file format. We also recommend that a
|
185
|
+
file or class name and description of purpose be included on the
|
186
|
+
same "printed page" as the copyright notice for easier
|
187
|
+
identification within third-party archives.
|
188
|
+
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
190
|
+
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192
|
+
you may not use this file except in compliance with the License.
|
193
|
+
You may obtain a copy of the License at
|
194
|
+
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
196
|
+
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200
|
+
See the License for the specific language governing permissions and
|
201
|
+
limitations under the License.
|
@@ -0,0 +1,33 @@
|
|
1
|
+
Metadata-Version: 2.4
|
2
|
+
Name: lt-tensor
|
3
|
+
Version: 0.0.1.dev0
|
4
|
+
Summary: General utilities for PyTorch and others. Built for general use.
|
5
|
+
Home-page: https://github.com/gr1336/lt-tensor/
|
6
|
+
Author: gr1336
|
7
|
+
License: Apache Software License (Apache-2.0)
|
8
|
+
Classifier: Development Status :: 1 - Planning
|
9
|
+
Classifier: Topic :: Software Development
|
10
|
+
Classifier: Topic :: Software Development :: Libraries
|
11
|
+
Classifier: Topic :: Software Development :: Testing
|
12
|
+
Classifier: Topic :: Software Development :: Pre-processors
|
13
|
+
Classifier: Topic :: Utilities
|
14
|
+
Description-Content-Type: text/markdown
|
15
|
+
License-File: LICENSE
|
16
|
+
Requires-Dist: torch>=2.2.0
|
17
|
+
Requires-Dist: torchaudio>=2.2.0
|
18
|
+
Requires-Dist: numpy>=1.26.4
|
19
|
+
Requires-Dist: tokenizers
|
20
|
+
Requires-Dist: pyyaml>=6.0.0
|
21
|
+
Requires-Dist: numba>0.60.0
|
22
|
+
Requires-Dist: lt-utils==0.0.1.dev0
|
23
|
+
Dynamic: author
|
24
|
+
Dynamic: classifier
|
25
|
+
Dynamic: description
|
26
|
+
Dynamic: description-content-type
|
27
|
+
Dynamic: home-page
|
28
|
+
Dynamic: license
|
29
|
+
Dynamic: license-file
|
30
|
+
Dynamic: requires-dist
|
31
|
+
Dynamic: summary
|
32
|
+
|
33
|
+
General utilities for PyTorch and others. Built for general use.
|
@@ -0,0 +1 @@
|
|
1
|
+
General utilities for PyTorch and others. Built for general use.
|
File without changes
|
@@ -0,0 +1,244 @@
|
|
1
|
+
__all__ = ["Model"]
|
2
|
+
|
3
|
+
|
4
|
+
import warnings
|
5
|
+
from ._torch_commons import *
|
6
|
+
|
7
|
+
ROOT_DEVICE = torch.device(torch.zeros(1).device)
|
8
|
+
|
9
|
+
class _ModelDevice(nn.Module):
|
10
|
+
"""
|
11
|
+
This makes it easier to assign a device and retrieves it later
|
12
|
+
"""
|
13
|
+
|
14
|
+
_device: torch.device = ROOT_DEVICE
|
15
|
+
|
16
|
+
@property
|
17
|
+
def device(self):
|
18
|
+
return self._device
|
19
|
+
|
20
|
+
@device.setter
|
21
|
+
def device(self, device: Union[torch.device, str]):
|
22
|
+
assert isinstance(device, (str, torch.device))
|
23
|
+
self._device = torch.device(device) if isinstance(device, str) else device
|
24
|
+
self.tp_apply_device_to()
|
25
|
+
|
26
|
+
def __init__(self, *args, **kwargs):
|
27
|
+
super().__init__(*args, **kwargs)
|
28
|
+
|
29
|
+
def tp_apply_device_to(self):
|
30
|
+
"""Add here components that are needed to have device applied to them,
|
31
|
+
that usualy the '.to()' function fails to apply
|
32
|
+
|
33
|
+
example:
|
34
|
+
```
|
35
|
+
def tp_apply_device_to(self):
|
36
|
+
self.my_tensor = self.my_tensor.to(device=self.device)
|
37
|
+
```
|
38
|
+
"""
|
39
|
+
pass
|
40
|
+
|
41
|
+
def to(self, *args, **kwargs):
|
42
|
+
device, dtype, non_blocking, convert_to_format = torch._C._nn._parse_to(
|
43
|
+
*args, **kwargs
|
44
|
+
)
|
45
|
+
|
46
|
+
if dtype is not None:
|
47
|
+
if not (dtype.is_floating_point or dtype.is_complex):
|
48
|
+
raise TypeError(
|
49
|
+
"nn.Module.to only accepts floating point or complex "
|
50
|
+
f"dtypes, but got desired dtype={dtype}"
|
51
|
+
)
|
52
|
+
if dtype.is_complex:
|
53
|
+
warnings.warn(
|
54
|
+
"Complex modules are a new feature under active development whose design may change, "
|
55
|
+
"and some modules might not work as expected when using complex tensors as parameters or buffers. "
|
56
|
+
"Please file an issue at https://github.com/pytorch/pytorch/issues/new?template=bug-report.yml "
|
57
|
+
"if a complex module does not work as expected."
|
58
|
+
)
|
59
|
+
|
60
|
+
def convert(t: Tensor):
|
61
|
+
try:
|
62
|
+
if convert_to_format is not None and t.dim() in (4, 5):
|
63
|
+
return t.to(
|
64
|
+
device,
|
65
|
+
dtype if t.is_floating_point() or t.is_complex() else None,
|
66
|
+
non_blocking,
|
67
|
+
memory_format=convert_to_format,
|
68
|
+
)
|
69
|
+
return t.to(
|
70
|
+
device,
|
71
|
+
dtype if t.is_floating_point() or t.is_complex() else None,
|
72
|
+
non_blocking,
|
73
|
+
)
|
74
|
+
except NotImplementedError as e:
|
75
|
+
if str(e) == "Cannot copy out of meta tensor; no data!":
|
76
|
+
raise NotImplementedError(
|
77
|
+
f"{e} Please use torch.nn.Module.to_empty() instead of torch.nn.Module.to() "
|
78
|
+
f"when moving module from meta to a different device."
|
79
|
+
) from None
|
80
|
+
else:
|
81
|
+
raise
|
82
|
+
|
83
|
+
self._apply(convert)
|
84
|
+
self.device = device
|
85
|
+
return self
|
86
|
+
|
87
|
+
def ipu(self, device: Optional[Union[int, torch.device]] = None) -> T:
|
88
|
+
super().ipu(device)
|
89
|
+
dvc = "ipu"
|
90
|
+
if device is not None:
|
91
|
+
dvc += (
|
92
|
+
":" + str(device) if isinstance(device, (int, float)) else device.index
|
93
|
+
)
|
94
|
+
self.device = dvc
|
95
|
+
return self
|
96
|
+
|
97
|
+
def xpu(self, device: Optional[Union[int, torch.device]] = None) -> T:
|
98
|
+
super().xpu(device)
|
99
|
+
dvc = "xpu"
|
100
|
+
if device is not None:
|
101
|
+
dvc += (
|
102
|
+
":" + str(device) if isinstance(device, (int, float)) else device.index
|
103
|
+
)
|
104
|
+
self.device = dvc
|
105
|
+
return self
|
106
|
+
|
107
|
+
def cuda(self, device: Optional[Union[int, torch.device]] = None) -> T:
|
108
|
+
super().cuda(device)
|
109
|
+
dvc = "cuda"
|
110
|
+
if device is not None:
|
111
|
+
dvc += (
|
112
|
+
":" + str(device) if isinstance(device, (int, float)) else device.index
|
113
|
+
)
|
114
|
+
self.device = dvc
|
115
|
+
return self
|
116
|
+
|
117
|
+
def mtia(self, device: Optional[Union[int, torch.device]] = None) -> T:
|
118
|
+
super().mtia(device)
|
119
|
+
dvc = "mtia"
|
120
|
+
if device is not None:
|
121
|
+
dvc += (
|
122
|
+
":" + str(device) if isinstance(device, (int, float)) else device.index
|
123
|
+
)
|
124
|
+
self.device = dvc
|
125
|
+
return self
|
126
|
+
|
127
|
+
def cpu(self) -> T:
|
128
|
+
super().cpu()
|
129
|
+
self.device = "cpu"
|
130
|
+
return self
|
131
|
+
|
132
|
+
|
133
|
+
class Model(_ModelDevice, ABC):
|
134
|
+
"""
|
135
|
+
For easier access of items in a model
|
136
|
+
This applies to all except to "forward", "save_weights", "load_weights",
|
137
|
+
"train_step", and "inference".
|
138
|
+
"""
|
139
|
+
|
140
|
+
_autocast: bool = False
|
141
|
+
|
142
|
+
@property
|
143
|
+
def autocast(self):
|
144
|
+
return self._autocast
|
145
|
+
|
146
|
+
@autocast.setter
|
147
|
+
def autocast(self, value: bool):
|
148
|
+
self._autocast = value
|
149
|
+
|
150
|
+
def __init__(
|
151
|
+
self,
|
152
|
+
*args,
|
153
|
+
**kwargs,
|
154
|
+
):
|
155
|
+
super().__init__(*args, **kwargs)
|
156
|
+
device = kwargs.get("device", None)
|
157
|
+
if isinstance(device, (torch.device, str)):
|
158
|
+
self.to(device)
|
159
|
+
self.autocast = kwargs.get("autocast", self.autocast)
|
160
|
+
|
161
|
+
def tp_count_parameters(self, module_name: Optional[str] = None):
|
162
|
+
"""Gets the numer of parameters from either the entire model or from a specific module"""
|
163
|
+
if module_name is not None:
|
164
|
+
assert hasattr(self, module_name), f"Module {module_name} does not exits"
|
165
|
+
module = getattr(self, module_name)
|
166
|
+
return sum([x.numel() for x in module.parameters()])
|
167
|
+
else:
|
168
|
+
return sum([x.numel() for x in self.parameters()])
|
169
|
+
|
170
|
+
def tp_get_weights(self, module_name: Optional[str] = None) -> List[Tensor]:
|
171
|
+
"""Returns the weights of the model entrie model or from a specified module"""
|
172
|
+
if module_name is not None:
|
173
|
+
assert hasattr(self, module_name), f"Module {module_name} does not exits"
|
174
|
+
module = getattr(self, module_name)
|
175
|
+
return [x.data.detach() for x in module.parameters()]
|
176
|
+
return [x.data.detach() for x in self.parameters()]
|
177
|
+
|
178
|
+
def tp_print_num_params(self, module_name: Optional[str] = None) -> List[Tensor]:
|
179
|
+
params = format(self.tp_count_parameters(module_name), ",").replace(",", ".")
|
180
|
+
|
181
|
+
if module_name:
|
182
|
+
print(f'Parameters from "{module_name}": {params}')
|
183
|
+
else:
|
184
|
+
print(f"Parameters: {params}")
|
185
|
+
|
186
|
+
def save_weights(self, path: Union[Path, str]):
|
187
|
+
path = Path(path)
|
188
|
+
if path.exists():
|
189
|
+
assert (
|
190
|
+
path.is_file()
|
191
|
+
), "The provided path exists but its a directory not a file!"
|
192
|
+
path.rmdir()
|
193
|
+
path.parent.mkdir(exist_ok=True, parents=True)
|
194
|
+
torch.save(obj=self.state_dict(), f=str(path))
|
195
|
+
|
196
|
+
def load_weights(
|
197
|
+
self,
|
198
|
+
path: Union[Path, str],
|
199
|
+
raise_if_not_exists: bool = False,
|
200
|
+
strict: bool = True,
|
201
|
+
assign: bool = False,
|
202
|
+
weights_only: bool = False,
|
203
|
+
mmap: Optional[bool] = None,
|
204
|
+
**torch_loader_kwargs,
|
205
|
+
):
|
206
|
+
path = Path(path)
|
207
|
+
if not path.exists():
|
208
|
+
assert not raise_if_not_exists, "Path does not exists!"
|
209
|
+
return None
|
210
|
+
assert path.is_file(), "The provided path is not a valid file!"
|
211
|
+
state_dict = torch.load(
|
212
|
+
str(path), weights_only=weights_only, mmap=mmap, **torch_loader_kwargs
|
213
|
+
)
|
214
|
+
incompatible_keys = self.load_state_dict(
|
215
|
+
state_dict,
|
216
|
+
strict=strict,
|
217
|
+
assign=assign,
|
218
|
+
)
|
219
|
+
return incompatible_keys
|
220
|
+
|
221
|
+
@torch.no_grad()
|
222
|
+
def inference(self, *args, **kwargs):
|
223
|
+
if self.training:
|
224
|
+
self.eval()
|
225
|
+
if self.autocast:
|
226
|
+
with torch.autocast(device_type=self.device.type):
|
227
|
+
return self(*args, **kwargs)
|
228
|
+
return self(*args, **kwargs)
|
229
|
+
|
230
|
+
def train_step(
|
231
|
+
self,
|
232
|
+
*args,
|
233
|
+
**kwargs,
|
234
|
+
):
|
235
|
+
"""Train Step"""
|
236
|
+
if not self.training:
|
237
|
+
self.train()
|
238
|
+
return self(*args, **kwargs)
|
239
|
+
|
240
|
+
@abstractmethod
|
241
|
+
def forward(
|
242
|
+
self, *args, **kwargs
|
243
|
+
) -> Union[Tensor, Sequence[Tensor], Dict[Any, Union[Any, Tensor]]]:
|
244
|
+
pass
|
@@ -0,0 +1,12 @@
|
|
1
|
+
import torch
|
2
|
+
from torch import nn, optim
|
3
|
+
import torch.nn.functional as F
|
4
|
+
from torch.optim import Optimizer
|
5
|
+
from torch.nn import Module, L1Loss, MSELoss
|
6
|
+
from torch.nn.utils import remove_weight_norm
|
7
|
+
from torch import Tensor, FloatTensor, device, LongTensor
|
8
|
+
from torch.nn.utils.parametrizations import weight_norm, spectral_norm
|
9
|
+
|
10
|
+
from lt_utils.common import *
|
11
|
+
|
12
|
+
DeviceType: TypeAlias = Union[device, str]
|
@@ -0,0 +1,108 @@
|
|
1
|
+
import math
|
2
|
+
from torch.optim import Optimizer
|
3
|
+
from torch.optim.lr_scheduler import _LRScheduler
|
4
|
+
|
5
|
+
|
6
|
+
class WarmupDecayScheduler(_LRScheduler):
|
7
|
+
def __init__(
|
8
|
+
self,
|
9
|
+
optimizer: Optimizer,
|
10
|
+
warmup_steps: int,
|
11
|
+
total_steps: int,
|
12
|
+
decay_type: str = "linear", # or "cosine"
|
13
|
+
min_lr: float = 0.0,
|
14
|
+
last_epoch: int = -1,
|
15
|
+
):
|
16
|
+
self.warmup_steps = warmup_steps
|
17
|
+
self.total_steps = total_steps
|
18
|
+
self.decay_type = decay_type
|
19
|
+
self.min_lr = min_lr
|
20
|
+
super().__init__(optimizer, last_epoch)
|
21
|
+
|
22
|
+
def get_lr(self):
|
23
|
+
step = self.last_epoch + 1
|
24
|
+
warmup = self.warmup_steps
|
25
|
+
total = self.total_steps
|
26
|
+
lrs = []
|
27
|
+
|
28
|
+
for base_lr in self.base_lrs:
|
29
|
+
if step < warmup:
|
30
|
+
lr = base_lr * step / warmup
|
31
|
+
else:
|
32
|
+
progress = (step - warmup) / max(1, total - warmup)
|
33
|
+
if self.decay_type == "linear":
|
34
|
+
lr = base_lr * (1.0 - progress)
|
35
|
+
elif self.decay_type == "cosine":
|
36
|
+
lr = base_lr * 0.5 * (1 + math.cos(math.pi * progress))
|
37
|
+
else:
|
38
|
+
raise ValueError(f"Unknown decay type: {self.decay_type}")
|
39
|
+
|
40
|
+
lr = max(self.min_lr, lr)
|
41
|
+
lrs.append(lr)
|
42
|
+
|
43
|
+
return lrs
|
44
|
+
|
45
|
+
|
46
|
+
class AdaptiveDropScheduler(_LRScheduler):
|
47
|
+
def __init__(
|
48
|
+
self,
|
49
|
+
optimizer,
|
50
|
+
drop_factor=0.5,
|
51
|
+
patience=10,
|
52
|
+
min_lr=1e-6,
|
53
|
+
cooldown=5,
|
54
|
+
last_epoch=-1,
|
55
|
+
):
|
56
|
+
self.drop_factor = drop_factor
|
57
|
+
self.patience = patience
|
58
|
+
self.min_lr = min_lr
|
59
|
+
self.cooldown = cooldown
|
60
|
+
self.cooldown_counter = 0
|
61
|
+
self.best_loss = float("inf")
|
62
|
+
self.bad_steps = 0
|
63
|
+
super().__init__(optimizer, last_epoch)
|
64
|
+
|
65
|
+
def step(self, val_loss=None):
|
66
|
+
if val_loss is not None:
|
67
|
+
if val_loss < self.best_loss:
|
68
|
+
self.best_loss = val_loss
|
69
|
+
self.bad_steps = 0
|
70
|
+
self.cooldown_counter = 0
|
71
|
+
else:
|
72
|
+
self.bad_steps += 1
|
73
|
+
if self.bad_steps >= self.patience and self.cooldown_counter == 0:
|
74
|
+
for i, group in enumerate(self.optimizer.param_groups):
|
75
|
+
new_lr = max(group["lr"] * self.drop_factor, self.min_lr)
|
76
|
+
group["lr"] = new_lr
|
77
|
+
self.cooldown_counter = self.cooldown
|
78
|
+
self.bad_steps = 0
|
79
|
+
if self.cooldown_counter > 0:
|
80
|
+
self.cooldown_counter -= 1
|
81
|
+
|
82
|
+
def get_lr(self):
|
83
|
+
return [group["lr"] for group in self.optimizer.param_groups]
|
84
|
+
|
85
|
+
|
86
|
+
class WaveringLRScheduler(_LRScheduler):
|
87
|
+
def __init__(
|
88
|
+
self, optimizer, base_lr, max_lr, period=1000, decay=0.999, last_epoch=-1
|
89
|
+
):
|
90
|
+
"""
|
91
|
+
Sinusoidal-like oscillating LR. Can escape shallow local minima.
|
92
|
+
- base_lr: minimum LR
|
93
|
+
- max_lr: maximum LR
|
94
|
+
- period: full sine cycle in steps
|
95
|
+
- decay: multiplies max_lr each cycle
|
96
|
+
"""
|
97
|
+
self.base_lr = base_lr
|
98
|
+
self.max_lr = max_lr
|
99
|
+
self.period = period
|
100
|
+
self.decay = decay
|
101
|
+
super().__init__(optimizer, last_epoch)
|
102
|
+
|
103
|
+
def get_lr(self):
|
104
|
+
cycle = self.last_epoch // self.period
|
105
|
+
step_in_cycle = self.last_epoch % self.period
|
106
|
+
factor = math.sin(math.pi * step_in_cycle / self.period)
|
107
|
+
amplitude = (self.max_lr - self.base_lr) * (self.decay**cycle)
|
108
|
+
return [self.base_lr + amplitude * factor for _ in self.optimizer.param_groups]
|