Skip to content

Commit efee5a3

Browse files
committed
Initial commit
0 parents  commit efee5a3

File tree

9 files changed

+1171
-0
lines changed

9 files changed

+1171
-0
lines changed

.gitignore

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
# Byte-compiled / optimized / DLL files
2+
__pycache__/
3+
*.py[cod]
4+
*$py.class
5+
6+
# C extensions
7+
*.so
8+
9+
# Distribution / packaging
10+
.Python
11+
build/
12+
develop-eggs/
13+
dist/
14+
downloads/
15+
eggs/
16+
.eggs/
17+
lib/
18+
lib64/
19+
parts/
20+
sdist/
21+
var/
22+
wheels/
23+
share/python-wheels/
24+
*.egg-info/
25+
.installed.cfg
26+
*.egg
27+
MANIFEST
28+
29+
# PyInstaller
30+
# Usually these files are written by a python script from a template
31+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
32+
*.manifest
33+
*.spec
34+
35+
# Installer logs
36+
pip-log.txt
37+
pip-delete-this-directory.txt
38+
39+
# Unit test / coverage reports
40+
htmlcov/
41+
.tox/
42+
.nox/
43+
.coverage
44+
.coverage.*
45+
.cache
46+
nosetests.xml
47+
coverage.xml
48+
*.cover
49+
.hypothesis/
50+
.pytest_cache/
51+
52+
# Translations
53+
*.mo
54+
*.pot
55+
56+
# Django stuff:
57+
*.log
58+
local_settings.py
59+
db.sqlite3
60+
61+
# Flask stuff:
62+
instance/
63+
.webassets-cache
64+
65+
# Scrapy stuff:
66+
.scrapy
67+
68+
# Sphinx documentation
69+
docs/_build/
70+
71+
# PyBuilder
72+
target/
73+
74+
# Jupyter Notebook
75+
.ipynb_checkpoints
76+
77+
# IPython
78+
profile_default/
79+
ipython_config.py
80+
81+
# pyenv
82+
.python-version
83+
84+
# celery beat schedule file
85+
celerybeat-schedule
86+
87+
# SageMath parsed files
88+
*.sage.py
89+
90+
# Environments
91+
.env
92+
.venv
93+
env/
94+
venv/
95+
ENV/
96+
env.bak/
97+
venv.bak/
98+
99+
# Spyder project settings
100+
.spyderproject
101+
.spyproject
102+
103+
# Rope project settings
104+
.ropeproject
105+
106+
# mkdocs documentation
107+
/site
108+
109+
# mypy
110+
.mypy_cache/
111+
.dmypy.json
112+
dmypy.json
113+
114+
# Pyre type checker
115+
.pyre/
116+
117+
# VSCode project
118+
.vscode/

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2018 davidtvs
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.

README.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# PyTorch learning rate finder
2+
3+
A PyTorch implementation of the learning rate range test detailed in [Cyclical Learning Rates for Training Neural Networks](https://arxiv.org/abs/1506.01186) by Leslie N. Smith and the tweaked version used by [fastai](https://github.com/fastai/fastai).
4+
5+
The learning rate range test is a test that provides valuable information about the optimal learning rate. During a pre-training run, the learning rate is increased linearly or exponentially between two boundaries. The low initial learning rate allows the network to start converging and as the learning rate is increased it will eventually be too large and the network will diverge.
6+
7+
Typically, a good static learning rate can be found half-way on the descending loss curve. In the plot below that would be `lr = 0.002`.
8+
9+
For cyclical learning rates (also detailed in Leslie Smith's paper) where the learning rate is cycled between two boundaries `(base_lr, max_lr)`, the author advises the point at which the loss starts descending and the point at which the loss stops descending or becomes ragged for `base_lr` and `max_lr` respectively. In the plot below, `base_lr = 0.0002` and `max_lr=0.2`.
10+
11+
![Learning rate range test](images/lr_finder_cifar10.png.png)
12+
13+
## Requirements
14+
15+
- Python 2.7 and above
16+
- pip
17+
- see `requirements.txt`
18+
19+
## Implementation details and usage
20+
21+
### Tweaked version from fastai
22+
23+
Increases the learning rate in an exponential manner and computes the training loss for each learning rate. `lr_finder.plot()` plots the training loss versus logarithmic learning rate.
24+
25+
```python
26+
model = ...
27+
criterion = nn.CrossEntropyLoss()
28+
optimizer = optim.Adam(net.parameters(), lr=1e-7, weight_decay=1e-2)
29+
lr_finder = LRFinder(net, optimizer, criterion, device="cuda")
30+
lr_finder.range_test(trainloader, end_lr=100, num_iter=100)
31+
lr_finder.plot()
32+
```
33+
34+
### Leslie Smith's approach
35+
36+
Increases the learning rate linearly and computes the evaluation loss for each learning rate. `lr_finder.plot()` plots the evaluation loss versus learning rate.
37+
This approach typically produces more precise curves because the evaluation loss is more susceptible to divergence but it takes significantly longer to perform the test, especially if the evaluation dataset is large.
38+
39+
```python
40+
model = ...
41+
criterion = nn.CrossEntropyLoss()
42+
optimizer = optim.Adam(net.parameters(), lr=0.1, weight_decay=1e-2)
43+
lr_finder = LRFinder(net, optimizer, criterion, device="cuda")
44+
lr_finder.range_test(trainloader, end_lr=1, num_iter=100, step_mode="linear")
45+
lr_finder.plot(log_lr=False)
46+
```
47+
48+
### Notes
49+
50+
- Examples for CIFAR10 and MNIST can be found in the examples folder.
51+
- `LRFinder.range_test()` will change the model weights and the optimizer parameters. If you want to avoid this use: `model = copy.deepcopy(original_model)`
52+
- The learning rate and loss history can be accessed through `lr_finder.history`. This will return a dictionary with `lr` and `loss` keys.
53+
- When using `step_mode="linear"` the learning rate range should be within the same order of magnitude.

examples/cifar10_resnet.py

Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
import torch.nn as nn
2+
3+
4+
__all__ = ["Cifar10ResNet", "resnet20", "resnet32", "resnet44", "resnet56", "resnet101"]
5+
6+
7+
def conv3x3(in_planes, out_planes, stride=1):
8+
"""3x3 convolution with padding"""
9+
return nn.Conv2d(
10+
in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False
11+
)
12+
13+
14+
def conv1x1(in_planes, out_planes, stride=1):
15+
"""1x1 convolution"""
16+
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
17+
18+
19+
class BasicBlock(nn.Module):
20+
expansion = 1
21+
22+
def __init__(self, inplanes, planes, stride=1, downsample=None):
23+
super(BasicBlock, self).__init__()
24+
self.conv1 = conv3x3(inplanes, planes, stride)
25+
self.bn1 = nn.BatchNorm2d(planes)
26+
self.relu = nn.ReLU(inplace=True)
27+
self.conv2 = conv3x3(planes, planes)
28+
self.bn2 = nn.BatchNorm2d(planes)
29+
self.downsample = downsample
30+
self.stride = stride
31+
32+
def forward(self, x):
33+
residual = x
34+
35+
out = self.conv1(x)
36+
out = self.bn1(out)
37+
out = self.relu(out)
38+
39+
out = self.conv2(out)
40+
out = self.bn2(out)
41+
42+
if self.downsample is not None:
43+
residual = self.downsample(x)
44+
45+
out += residual
46+
out = self.relu(out)
47+
48+
return out
49+
50+
51+
class Cifar10ResNet(nn.Module):
52+
def __init__(self, block, layers, num_classes=10, ch_width=2):
53+
super(Cifar10ResNet, self).__init__()
54+
width = [16, 16 * ch_width, 16 * ch_width * ch_width]
55+
self.inplanes = 16
56+
self.conv1 = nn.Conv2d(
57+
3, width[0], kernel_size=3, stride=1, padding=1, bias=False
58+
)
59+
self.bn1 = nn.BatchNorm2d(width[0])
60+
self.relu = nn.ReLU(inplace=True)
61+
self.layer1 = self._make_layer(block, width[0], layers[0])
62+
self.layer2 = self._make_layer(block, width[1], layers[1], stride=2)
63+
self.layer3 = self._make_layer(block, width[2], layers[2], stride=2)
64+
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
65+
self.fc = nn.Linear(width[2] * block.expansion, num_classes)
66+
67+
for m in self.modules():
68+
if isinstance(m, nn.Conv2d):
69+
nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
70+
elif isinstance(m, nn.BatchNorm2d):
71+
nn.init.constant_(m.weight, 1)
72+
nn.init.constant_(m.bias, 0)
73+
74+
def _make_layer(self, block, planes, blocks, stride=1):
75+
downsample = None
76+
if stride != 1 or self.inplanes != planes * block.expansion:
77+
downsample = nn.Sequential(
78+
conv1x1(self.inplanes, planes * block.expansion, stride),
79+
nn.BatchNorm2d(planes * block.expansion),
80+
)
81+
82+
layers = []
83+
layers.append(block(self.inplanes, planes, stride, downsample))
84+
self.inplanes = planes * block.expansion
85+
for _ in range(1, blocks):
86+
layers.append(block(self.inplanes, planes))
87+
88+
return nn.Sequential(*layers)
89+
90+
def forward(self, x):
91+
x = self.conv1(x)
92+
x = self.bn1(x)
93+
x = self.relu(x)
94+
95+
x = self.layer1(x)
96+
x = self.layer2(x)
97+
x = self.layer3(x)
98+
99+
x = self.avgpool(x)
100+
x = x.view(x.size(0), -1)
101+
x = self.fc(x)
102+
103+
return x
104+
105+
106+
def resnet20(num_classes=10, ch_width=2):
107+
"""Constructs a ResNet-20 model.
108+
"""
109+
return Cifar10ResNet(
110+
BasicBlock, [3, 3, 3], num_classes=num_classes, ch_width=ch_width
111+
)
112+
113+
114+
def resnet32(num_classes=10, ch_width=2):
115+
"""Constructs a ResNet-32 model.
116+
"""
117+
return Cifar10ResNet(
118+
BasicBlock, [5, 5, 5], num_classes=num_classes, ch_width=ch_width
119+
)
120+
121+
122+
def resnet44(num_classes=10, ch_width=2):
123+
"""Constructs a ResNet-44 model.
124+
"""
125+
return Cifar10ResNet(
126+
BasicBlock, [7, 7, 7], num_classes=num_classes, ch_width=ch_width
127+
)
128+
129+
130+
def resnet56(num_classes=10, ch_width=2):
131+
"""Constructs a ResNet-56 model.
132+
"""
133+
return Cifar10ResNet(
134+
BasicBlock, [9, 9, 9], num_classes=num_classes, ch_width=ch_width
135+
)
136+
137+
138+
def resnet101(num_classes=10, ch_width=2):
139+
"""Constructs a ResNet-101 model.
140+
"""
141+
return Cifar10ResNet(
142+
BasicBlock, [18, 18, 18], num_classes=num_classes, ch_width=ch_width
143+
)

0 commit comments

Comments
 (0)