Skip to content

Commit dcc8c6c

Browse files
Soohwan KimSoohwan Kim
Soohwan Kim
authored and
Soohwan Kim
committed
init commit
1 parent 446a6ec commit dcc8c6c

13 files changed

+668
-0
lines changed

.gitignore

+10
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,16 @@ __pycache__/
66
# C extensions
77
*.so
88

9+
.DS_Store
10+
*.bin
11+
*.zip
12+
*.idea
13+
venv/*
14+
*.pyc
15+
.idea
16+
.ipynb_checkpoints
17+
.DS_Store/*
18+
919
# Distribution / packaging
1020
.Python
1121
build/

README.md

+187
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,189 @@
11
# pytorch-lr-scheduler
22
PyTorch implementation of some learning rate schedulers for deep learning researcher.
3+
4+
## Usage
5+
6+
### `ReduceLROnPlateauScheduler`
7+
8+
- Example code
9+
10+
```python
11+
import torch
12+
13+
from lr_scheduler.reduce_lr_on_plateau_lr_scheduler import ReduceLROnPlateauScheduler
14+
15+
if __name__ == '__main__':
16+
max_epochs, steps_in_epoch = 10, 10000
17+
18+
model = [torch.nn.Parameter(torch.randn(2, 2, requires_grad=True))]
19+
optimizer = torch.optim.Adam(model, 1e-4)
20+
21+
scheduler = ReduceLROnPlateauScheduler(optimizer, patience=1, factor=0.3)
22+
23+
for epoch in range(max_epochs):
24+
for timestep in range(steps_in_epoch):
25+
...
26+
...
27+
28+
val_loss = validate()
29+
scheduler.step(val_loss)
30+
```
31+
32+
- Visualize
33+
![](images/ReduceLROnPlateauScheduler.png)
34+
35+
### `TransformerLRScheduler`
36+
37+
- Example code
38+
39+
```python
40+
import torch
41+
42+
from lr_scheduler.transformer_lr_scheduler import TransformerLRScheduler
43+
44+
if __name__ == '__main__':
45+
max_epochs, steps_in_epoch = 10, 10000
46+
47+
model = [torch.nn.Parameter(torch.randn(2, 2, requires_grad=True))]
48+
optimizer = torch.optim.Adam(model, 1e-10)
49+
50+
scheduler = TransformerLRScheduler(
51+
optimizer=optimizer,
52+
init_lr=1e-10,
53+
peak_lr=0.1,
54+
final_lr=1e-4,
55+
final_lr_scale=0.05,
56+
warmup_steps=3000,
57+
decay_steps=17000,
58+
)
59+
60+
for epoch in range(max_epochs):
61+
for timestep in range(steps_in_epoch):
62+
...
63+
...
64+
scheduler.step()
65+
```
66+
67+
- Visualize
68+
![](images/TransformerLRScheduler.png)
69+
70+
### `TriStageLRScheduler`
71+
72+
- Example code
73+
74+
```python
75+
import torch
76+
77+
from lr_scheduler.tri_stage_lr_scheduler import TriStageLRScheduler
78+
79+
if __name__ == '__main__':
80+
max_epochs, steps_in_epoch = 10, 10000
81+
82+
model = [torch.nn.Parameter(torch.randn(2, 2, requires_grad=True))]
83+
optimizer = torch.optim.Adam(model, 1e-10)
84+
85+
scheduler = TriStageLRScheduler(
86+
optimizer,
87+
init_lr=1e-10,
88+
peak_lr=1e-4,
89+
final_lr=1e-7,
90+
init_lr_scale=0.01,
91+
final_lr_scale=0.05,
92+
warmup_steps=30000,
93+
hold_steps=70000,
94+
decay_steps=100000,
95+
total_steps=200000,
96+
)
97+
98+
for epoch in range(max_epochs):
99+
for timestep in range(steps_in_epoch):
100+
...
101+
...
102+
scheduler.step()
103+
```
104+
105+
- Visualize
106+
107+
![](images/TriStageLRScheduler.png)
108+
109+
### `WarmupReduceLROnPlateauScheduler`
110+
111+
- Example code
112+
```python
113+
import torch
114+
115+
from lr_scheduler.warmup_reduce_lr_on_plateau_scheduler import WarmupReduceLROnPlateauScheduler
116+
117+
if __name__ == '__main__':
118+
max_epochs, steps_in_epoch = 10, 10000
119+
120+
model = [torch.nn.Parameter(torch.randn(2, 2, requires_grad=True))]
121+
optimizer = torch.optim.Adam(model, 1e-10)
122+
123+
scheduler = WarmupReduceLROnPlateauScheduler(
124+
optimizer,
125+
init_lr=1e-10,
126+
peak_lr=1e-4,
127+
warmup_steps=30000,
128+
patience=1,
129+
factor=0.3,
130+
)
131+
132+
for epoch in range(max_epochs):
133+
for timestep in range(steps_in_epoch):
134+
...
135+
...
136+
if timestep < warmup_steps:
137+
scheduler.step()
138+
139+
val_loss = validate()
140+
scheduler.step(val_loss)
141+
```
142+
143+
- Visualize
144+
145+
![](images/WarmupReduceLROnPlateauScheduler.png)
146+
147+
### `WarmupLRScheduler`
148+
149+
- Example code
150+
151+
```python
152+
import torch
153+
154+
from lr_scheduler.warmup_lr_scheduler import WarmupLRScheduler
155+
156+
if __name__ == '__main__':
157+
max_epochs, steps_in_epoch = 10, 10000
158+
159+
model = [torch.nn.Parameter(torch.randn(2, 2, requires_grad=True))]
160+
optimizer = torch.optim.Adam(model, 1e-10)
161+
162+
scheduler = WarmupLRScheduler(
163+
optimizer,
164+
init_lr=1e-10,
165+
peak_lr=1e-4,
166+
warmup_steps=4000,
167+
)
168+
169+
for epoch in range(max_epochs):
170+
for timestep in range(steps_in_epoch):
171+
...
172+
...
173+
scheduler.step()
174+
```
175+
176+
- Visualize
177+
178+
![](images/WarmupLRScheduler.png)
179+
180+
## Troubleshoots and Contributing
181+
If you have any questions, bug reports, and feature requests, please [open an issue](https://github.com/sooftware/openspeech/issues) on Github.
182+
183+
I appreciate any kind of feedback or contribution. Feel free to proceed with small issues like bug fixes, documentation improvement. For major contributions and new features, please discuss with the collaborators in corresponding issues.
184+
185+
### Code Style
186+
I follow [PEP-8](https://www.python.org/dev/peps/pep-0008/) for code style. Especially the style of docstrings is important to generate documentation.
187+
188+
### License
189+
This project is licensed under the MIT LICENSE - see the [LICENSE.md](https://github.com/sooftware/OpenSpeech/blob/master/LICENSE) file for details

images/ReduceLROnPlateauScheduler.png

18.8 KB
Loading

images/TransformerLRScheduler.png

26.8 KB
Loading

images/TriStageLRScheduler.png

27.8 KB
Loading

images/WarmupLRScheduler.png

22.7 KB
Loading
25.2 KB
Loading

lr_scheduler/lr_scheduler.py

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# MIT License
2+
#
3+
# Copyright (c) 2021 Soohwan Kim
4+
#
5+
# Permission is hereby granted, free of charge, to any person obtaining a copy
6+
# of this software and associated documentation files (the "Software"), to deal
7+
# in the Software without restriction, including without limitation the rights
8+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
# copies of the Software, and to permit persons to whom the Software is
10+
# furnished to do so, subject to the following conditions:
11+
#
12+
# The above copyright notice and this permission notice shall be included in all
13+
# copies or substantial portions of the Software.
14+
#
15+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
# SOFTWARE.
22+
23+
24+
class LearningRateScheduler(object):
25+
r"""
26+
Provides inteface of learning rate scheduler.
27+
28+
Note:
29+
Do not use this class directly, use one of the sub classes.
30+
"""
31+
def __init__(self, optimizer, lr):
32+
self.optimizer = optimizer
33+
self.lr = lr
34+
35+
def step(self, *args, **kwargs):
36+
raise NotImplementedError
37+
38+
@staticmethod
39+
def set_lr(optimizer, lr):
40+
for g in optimizer.param_groups:
41+
g['lr'] = lr
42+
43+
def get_lr(self):
44+
for g in self.optimizer.param_groups:
45+
return g['lr']
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
# MIT License
2+
#
3+
# Copyright (c) 2021 Soohwan Kim
4+
#
5+
# Permission is hereby granted, free of charge, to any person obtaining a copy
6+
# of this software and associated documentation files (the "Software"), to deal
7+
# in the Software without restriction, including without limitation the rights
8+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
# copies of the Software, and to permit persons to whom the Software is
10+
# furnished to do so, subject to the following conditions:
11+
#
12+
# The above copyright notice and this permission notice shall be included in all
13+
# copies or substantial portions of the Software.
14+
#
15+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
# SOFTWARE.
22+
23+
from omegaconf import DictConfig
24+
from torch.optim import Optimizer
25+
26+
from lr_scheduler.lr_scheduler import LearningRateScheduler
27+
28+
29+
class ReduceLROnPlateauScheduler(LearningRateScheduler):
30+
r"""
31+
Reduce learning rate when a metric has stopped improving. Models often benefit from reducing the learning rate by
32+
a factor of 2-10 once learning stagnates. This scheduler reads a metrics quantity and if no improvement is seen
33+
for a ‘patience’ number of epochs, the learning rate is reduced.
34+
35+
Args:
36+
optimizer (Optimizer): Optimizer.
37+
lr (float): Initial learning rate.
38+
patience (int): Number of epochs with no improvement after which learning rate will be reduced.
39+
factor (float): Factor by which the learning rate will be reduced. new_lr = lr * factor.
40+
"""
41+
def __init__(
42+
self,
43+
optimizer: Optimizer,
44+
lr: float,
45+
patience: int = 1,
46+
factor: float = 0.3,
47+
) -> None:
48+
super(ReduceLROnPlateauScheduler, self).__init__(optimizer, lr)
49+
self.lr = lr
50+
self.patience = patience
51+
self.factor = factor
52+
self.val_loss = 100.0
53+
self.count = 0
54+
55+
def step(self, val_loss: float):
56+
if val_loss is not None:
57+
if self.val_loss < val_loss:
58+
self.count += 1
59+
self.val_loss = val_loss
60+
else:
61+
self.count = 0
62+
self.val_loss = val_loss
63+
64+
if self.patience == self.count:
65+
self.count = 0
66+
self.lr *= self.factor
67+
self.set_lr(self.optimizer, self.lr)
68+
69+
return self.lr

0 commit comments

Comments
 (0)