lt-tensor 0.0.1a0__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.
@@ -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,31 @@
1
+ Metadata-Version: 2.4
2
+ Name: lt-tensor
3
+ Version: 0.0.1a0
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 :: Utilities
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: torch>=2.2.0
15
+ Requires-Dist: torchaudio>=2.2.0
16
+ Requires-Dist: numpy>=1.26.4
17
+ Requires-Dist: tokenizers
18
+ Requires-Dist: pyyaml>=6.0.0
19
+ Requires-Dist: numba>0.60.0
20
+ Requires-Dist: lt-utils==0.0.1a0
21
+ Dynamic: author
22
+ Dynamic: classifier
23
+ Dynamic: description
24
+ Dynamic: description-content-type
25
+ Dynamic: home-page
26
+ Dynamic: license
27
+ Dynamic: license-file
28
+ Dynamic: requires-dist
29
+ Dynamic: summary
30
+
31
+ General utilities for PyTorch and others. Built for general use.
@@ -0,0 +1 @@
1
+ General utilities for PyTorch and others. Built for general use.
@@ -0,0 +1 @@
1
+ __version__ = "0.0.1dev3"
@@ -0,0 +1,270 @@
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
+
10
+ class _ModelDevice(nn.Module):
11
+ """
12
+ This makes it easier to assign a device and retrieves it later
13
+ """
14
+
15
+ _device: torch.device = ROOT_DEVICE
16
+
17
+ @property
18
+ def device(self):
19
+ return self._device
20
+
21
+ @device.setter
22
+ def device(self, device: Union[torch.device, str]):
23
+ assert isinstance(device, (str, torch.device))
24
+ self._device = torch.device(device) if isinstance(device, str) else device
25
+ self.tp_apply_device_to()
26
+
27
+ def tp_apply_device_to(self):
28
+ """Add here components that are needed to have device applied to them,
29
+ that usualy the '.to()' function fails to apply
30
+
31
+ example:
32
+ ```
33
+ def tp_apply_device_to(self):
34
+ self.my_tensor = self.my_tensor.to(device=self.device)
35
+ ```
36
+ """
37
+ pass
38
+
39
+ def to(self, *args, **kwargs):
40
+ device, dtype, non_blocking, convert_to_format = torch._C._nn._parse_to(
41
+ *args, **kwargs
42
+ )
43
+
44
+ if dtype is not None:
45
+ if not (dtype.is_floating_point or dtype.is_complex):
46
+ raise TypeError(
47
+ "nn.Module.to only accepts floating point or complex "
48
+ f"dtypes, but got desired dtype={dtype}"
49
+ )
50
+ if dtype.is_complex:
51
+ warnings.warn(
52
+ "Complex modules are a new feature under active development whose design may change, "
53
+ "and some modules might not work as expected when using complex tensors as parameters or buffers. "
54
+ "Please file an issue at https://github.com/pytorch/pytorch/issues/new?template=bug-report.yml "
55
+ "if a complex module does not work as expected."
56
+ )
57
+
58
+ def convert(t: Tensor):
59
+ try:
60
+ if convert_to_format is not None and t.dim() in (4, 5):
61
+ return t.to(
62
+ device,
63
+ dtype if t.is_floating_point() or t.is_complex() else None,
64
+ non_blocking,
65
+ memory_format=convert_to_format,
66
+ )
67
+ return t.to(
68
+ device,
69
+ dtype if t.is_floating_point() or t.is_complex() else None,
70
+ non_blocking,
71
+ )
72
+ except NotImplementedError as e:
73
+ if str(e) == "Cannot copy out of meta tensor; no data!":
74
+ raise NotImplementedError(
75
+ f"{e} Please use torch.nn.Module.to_empty() instead of torch.nn.Module.to() "
76
+ f"when moving module from meta to a different device."
77
+ ) from None
78
+ else:
79
+ raise
80
+
81
+ self._apply(convert)
82
+ self.device = device
83
+ return self
84
+
85
+ def ipu(self, device: Optional[Union[int, torch.device]] = None) -> T:
86
+ super().ipu(device)
87
+ dvc = "ipu"
88
+ if device is not None:
89
+ dvc += (
90
+ ":" + str(device) if isinstance(device, (int, float)) else device.index
91
+ )
92
+ self.device = dvc
93
+ return self
94
+
95
+ def xpu(self, device: Optional[Union[int, torch.device]] = None) -> T:
96
+ super().xpu(device)
97
+ dvc = "xpu"
98
+ if device is not None:
99
+ dvc += (
100
+ ":" + str(device) if isinstance(device, (int, float)) else device.index
101
+ )
102
+ self.device = dvc
103
+ return self
104
+
105
+ def cuda(self, device: Optional[Union[int, torch.device]] = None) -> T:
106
+ super().cuda(device)
107
+ dvc = "cuda"
108
+ if device is not None:
109
+ dvc += (
110
+ ":" + str(device) if isinstance(device, (int, float)) else device.index
111
+ )
112
+ self.device = dvc
113
+ return self
114
+
115
+ def mtia(self, device: Optional[Union[int, torch.device]] = None) -> T:
116
+ super().mtia(device)
117
+ dvc = "mtia"
118
+ if device is not None:
119
+ dvc += (
120
+ ":" + str(device) if isinstance(device, (int, float)) else device.index
121
+ )
122
+ self.device = dvc
123
+ return self
124
+
125
+ def cpu(self) -> T:
126
+ super().cpu()
127
+ self.device = "cpu"
128
+ return self
129
+
130
+
131
+ class Model(_ModelDevice, ABC):
132
+ _autocast: bool = False
133
+
134
+ @property
135
+ def autocast(self):
136
+ return self._autocast
137
+
138
+ @autocast.setter
139
+ def autocast(self, value: bool):
140
+ self._autocast = value
141
+
142
+ def count_trainable_parameters(self, module_name: Optional[str] = None):
143
+ """Gets the number of trainable parameters from either the entire model or from a specific module."""
144
+ if module_name is not None:
145
+ assert hasattr(self, module_name), f"Module {module_name} does not exits"
146
+ module = getattr(self, module_name)
147
+ return sum(
148
+ [
149
+ x.numel()
150
+ for x in module.parameters()
151
+ if hasattr(x, "requires_grad") and x.requires_grad
152
+ ]
153
+ )
154
+ return sum(
155
+ [
156
+ x.numel()
157
+ for x in self.parameters()
158
+ if hasattr(x, "requires_grad") and x.requires_grad
159
+ ]
160
+ )
161
+
162
+ def count_non_trainable_parameters(self, module_name: Optional[str] = None):
163
+ """Gets the number of non-trainable parameters from either the entire model or from a specific module."""
164
+ if module_name is not None:
165
+ assert hasattr(self, module_name), f"Module {module_name} does not exits"
166
+ module = getattr(self, module_name)
167
+ return sum(
168
+ [
169
+ x.numel()
170
+ for x in module.parameters()
171
+ if not hasattr(x, "requires_grad") or not x.requires_grad
172
+ ]
173
+ )
174
+ return sum(
175
+ [
176
+ x.numel()
177
+ for x in self.parameters()
178
+ if not hasattr(x, "requires_grad") or not x.requires_grad
179
+ ]
180
+ )
181
+
182
+ def get_weights(self, module_name: Optional[str] = None) -> List[Tensor]:
183
+ """Returns the weights of the model entrie model or from a specified module"""
184
+ if module_name is not None:
185
+ assert hasattr(self, module_name), f"Module {module_name} does not exits"
186
+ module = getattr(self, module_name)
187
+ return [x.data.detach() for x in module.parameters()]
188
+ return [x.data.detach() for x in self.parameters()]
189
+
190
+ def print_trainable_parameters(
191
+ self, module_name: Optional[str] = None
192
+ ) -> List[Tensor]:
193
+ params = format(self.count_trainable_parameters(module_name), ",").replace(
194
+ ",", "."
195
+ )
196
+ if module_name:
197
+ print(f'Trainable Parameters from "{module_name}": {params}')
198
+ else:
199
+ print(f"Trainable Parameters: {params}")
200
+
201
+ def print_non_trainable_parameters(
202
+ self, module_name: Optional[str] = None
203
+ ) -> List[Tensor]:
204
+ params = format(self.count_non_trainable_parameters(module_name), ",").replace(
205
+ ",", "."
206
+ )
207
+ if module_name:
208
+ print(f'Non-Trainable Parameters from "{module_name}": {params}')
209
+ else:
210
+ print(f"Non-Trainable Parameters: {params}")
211
+
212
+ def save_weights(self, path: Union[Path, str]):
213
+ path = Path(path)
214
+ if path.exists():
215
+ assert (
216
+ path.is_file()
217
+ ), "The provided path exists but its a directory not a file!"
218
+ path.rmdir()
219
+ path.parent.mkdir(exist_ok=True, parents=True)
220
+ torch.save(obj=self.state_dict(), f=str(path))
221
+
222
+ def load_weights(
223
+ self,
224
+ path: Union[Path, str],
225
+ raise_if_not_exists: bool = False,
226
+ strict: bool = True,
227
+ assign: bool = False,
228
+ weights_only: bool = False,
229
+ mmap: Optional[bool] = None,
230
+ **torch_loader_kwargs,
231
+ ):
232
+ path = Path(path)
233
+ if not path.exists():
234
+ assert not raise_if_not_exists, "Path does not exists!"
235
+ return None
236
+ assert path.is_file(), "The provided path is not a valid file!"
237
+ state_dict = torch.load(
238
+ str(path), weights_only=weights_only, mmap=mmap, **torch_loader_kwargs
239
+ )
240
+ incompatible_keys = self.load_state_dict(
241
+ state_dict,
242
+ strict=strict,
243
+ assign=assign,
244
+ )
245
+ return incompatible_keys
246
+
247
+ @torch.no_grad()
248
+ def inference(self, *args, **kwargs):
249
+ if self.training:
250
+ self.eval()
251
+ if self.autocast:
252
+ with torch.autocast(device_type=self.device.type):
253
+ return self(*args, **kwargs)
254
+ return self(*args, **kwargs)
255
+
256
+ def train_step(
257
+ self,
258
+ *args,
259
+ **kwargs,
260
+ ):
261
+ """Train Step"""
262
+ if not self.training:
263
+ self.train()
264
+ return self(*args, **kwargs)
265
+
266
+ @abstractmethod
267
+ def forward(
268
+ self, *args, **kwargs
269
+ ) -> Union[Tensor, Sequence[Tensor], Dict[Any, Union[Any, Tensor]]]:
270
+ 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,114 @@
1
+ __all__ = [
2
+ "WarmupDecayScheduler",
3
+ "AdaptiveDropScheduler",
4
+ "WaveringLRScheduler",
5
+ ]
6
+
7
+ import math
8
+ from torch.optim import Optimizer
9
+ from torch.optim.lr_scheduler import _LRScheduler
10
+
11
+
12
+ class WarmupDecayScheduler(_LRScheduler):
13
+ def __init__(
14
+ self,
15
+ optimizer: Optimizer,
16
+ warmup_steps: int,
17
+ total_steps: int,
18
+ decay_type: str = "linear", # or "cosine"
19
+ min_lr: float = 0.0,
20
+ last_epoch: int = -1,
21
+ ):
22
+ self.warmup_steps = warmup_steps
23
+ self.total_steps = total_steps
24
+ self.decay_type = decay_type
25
+ self.min_lr = min_lr
26
+ super().__init__(optimizer, last_epoch)
27
+
28
+ def get_lr(self):
29
+ step = self.last_epoch + 1
30
+ warmup = self.warmup_steps
31
+ total = self.total_steps
32
+ lrs = []
33
+
34
+ for base_lr in self.base_lrs:
35
+ if step < warmup:
36
+ lr = base_lr * step / warmup
37
+ else:
38
+ progress = (step - warmup) / max(1, total - warmup)
39
+ if self.decay_type == "linear":
40
+ lr = base_lr * (1.0 - progress)
41
+ elif self.decay_type == "cosine":
42
+ lr = base_lr * 0.5 * (1 + math.cos(math.pi * progress))
43
+ else:
44
+ raise ValueError(f"Unknown decay type: {self.decay_type}")
45
+
46
+ lr = max(self.min_lr, lr)
47
+ lrs.append(lr)
48
+
49
+ return lrs
50
+
51
+
52
+ class AdaptiveDropScheduler(_LRScheduler):
53
+ def __init__(
54
+ self,
55
+ optimizer,
56
+ drop_factor=0.5,
57
+ patience=10,
58
+ min_lr=1e-6,
59
+ cooldown=5,
60
+ last_epoch=-1,
61
+ ):
62
+ self.drop_factor = drop_factor
63
+ self.patience = patience
64
+ self.min_lr = min_lr
65
+ self.cooldown = cooldown
66
+ self.cooldown_counter = 0
67
+ self.best_loss = float("inf")
68
+ self.bad_steps = 0
69
+ super().__init__(optimizer, last_epoch)
70
+
71
+ def step(self, val_loss=None):
72
+ if val_loss is not None:
73
+ if val_loss < self.best_loss:
74
+ self.best_loss = val_loss
75
+ self.bad_steps = 0
76
+ self.cooldown_counter = 0
77
+ else:
78
+ self.bad_steps += 1
79
+ if self.bad_steps >= self.patience and self.cooldown_counter == 0:
80
+ for i, group in enumerate(self.optimizer.param_groups):
81
+ new_lr = max(group["lr"] * self.drop_factor, self.min_lr)
82
+ group["lr"] = new_lr
83
+ self.cooldown_counter = self.cooldown
84
+ self.bad_steps = 0
85
+ if self.cooldown_counter > 0:
86
+ self.cooldown_counter -= 1
87
+
88
+ def get_lr(self):
89
+ return [group["lr"] for group in self.optimizer.param_groups]
90
+
91
+
92
+ class WaveringLRScheduler(_LRScheduler):
93
+ def __init__(
94
+ self, optimizer, base_lr, max_lr, period=1000, decay=0.999, last_epoch=-1
95
+ ):
96
+ """
97
+ Sinusoidal-like oscillating LR. Can escape shallow local minima.
98
+ - base_lr: minimum LR
99
+ - max_lr: maximum LR
100
+ - period: full sine cycle in steps
101
+ - decay: multiplies max_lr each cycle
102
+ """
103
+ self.base_lr = base_lr
104
+ self.max_lr = max_lr
105
+ self.period = period
106
+ self.decay = decay
107
+ super().__init__(optimizer, last_epoch)
108
+
109
+ def get_lr(self):
110
+ cycle = self.last_epoch // self.period
111
+ step_in_cycle = self.last_epoch % self.period
112
+ factor = math.sin(math.pi * step_in_cycle / self.period)
113
+ amplitude = (self.max_lr - self.base_lr) * (self.decay**cycle)
114
+ return [self.base_lr + amplitude * factor for _ in self.optimizer.param_groups]