-
Notifications
You must be signed in to change notification settings - Fork 122
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit efee5a3
Showing
9 changed files
with
1,171 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,118 @@ | ||
# Byte-compiled / optimized / DLL files | ||
__pycache__/ | ||
*.py[cod] | ||
*$py.class | ||
|
||
# C extensions | ||
*.so | ||
|
||
# Distribution / packaging | ||
.Python | ||
build/ | ||
develop-eggs/ | ||
dist/ | ||
downloads/ | ||
eggs/ | ||
.eggs/ | ||
lib/ | ||
lib64/ | ||
parts/ | ||
sdist/ | ||
var/ | ||
wheels/ | ||
share/python-wheels/ | ||
*.egg-info/ | ||
.installed.cfg | ||
*.egg | ||
MANIFEST | ||
|
||
# PyInstaller | ||
# Usually these files are written by a python script from a template | ||
# before PyInstaller builds the exe, so as to inject date/other infos into it. | ||
*.manifest | ||
*.spec | ||
|
||
# Installer logs | ||
pip-log.txt | ||
pip-delete-this-directory.txt | ||
|
||
# Unit test / coverage reports | ||
htmlcov/ | ||
.tox/ | ||
.nox/ | ||
.coverage | ||
.coverage.* | ||
.cache | ||
nosetests.xml | ||
coverage.xml | ||
*.cover | ||
.hypothesis/ | ||
.pytest_cache/ | ||
|
||
# Translations | ||
*.mo | ||
*.pot | ||
|
||
# Django stuff: | ||
*.log | ||
local_settings.py | ||
db.sqlite3 | ||
|
||
# Flask stuff: | ||
instance/ | ||
.webassets-cache | ||
|
||
# Scrapy stuff: | ||
.scrapy | ||
|
||
# Sphinx documentation | ||
docs/_build/ | ||
|
||
# PyBuilder | ||
target/ | ||
|
||
# Jupyter Notebook | ||
.ipynb_checkpoints | ||
|
||
# IPython | ||
profile_default/ | ||
ipython_config.py | ||
|
||
# pyenv | ||
.python-version | ||
|
||
# celery beat schedule file | ||
celerybeat-schedule | ||
|
||
# SageMath parsed files | ||
*.sage.py | ||
|
||
# Environments | ||
.env | ||
.venv | ||
env/ | ||
venv/ | ||
ENV/ | ||
env.bak/ | ||
venv.bak/ | ||
|
||
# Spyder project settings | ||
.spyderproject | ||
.spyproject | ||
|
||
# Rope project settings | ||
.ropeproject | ||
|
||
# mkdocs documentation | ||
/site | ||
|
||
# mypy | ||
.mypy_cache/ | ||
.dmypy.json | ||
dmypy.json | ||
|
||
# Pyre type checker | ||
.pyre/ | ||
|
||
# VSCode project | ||
.vscode/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2018 davidtvs | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
# PyTorch learning rate finder | ||
|
||
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). | ||
|
||
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. | ||
|
||
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`. | ||
|
||
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`. | ||
|
||
 | ||
|
||
## Requirements | ||
|
||
- Python 2.7 and above | ||
- pip | ||
- see `requirements.txt` | ||
|
||
## Implementation details and usage | ||
|
||
### Tweaked version from fastai | ||
|
||
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. | ||
|
||
```python | ||
model = ... | ||
criterion = nn.CrossEntropyLoss() | ||
optimizer = optim.Adam(net.parameters(), lr=1e-7, weight_decay=1e-2) | ||
lr_finder = LRFinder(net, optimizer, criterion, device="cuda") | ||
lr_finder.range_test(trainloader, end_lr=100, num_iter=100) | ||
lr_finder.plot() | ||
``` | ||
|
||
### Leslie Smith's approach | ||
|
||
Increases the learning rate linearly and computes the evaluation loss for each learning rate. `lr_finder.plot()` plots the evaluation loss versus learning rate. | ||
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. | ||
|
||
```python | ||
model = ... | ||
criterion = nn.CrossEntropyLoss() | ||
optimizer = optim.Adam(net.parameters(), lr=0.1, weight_decay=1e-2) | ||
lr_finder = LRFinder(net, optimizer, criterion, device="cuda") | ||
lr_finder.range_test(trainloader, end_lr=1, num_iter=100, step_mode="linear") | ||
lr_finder.plot(log_lr=False) | ||
``` | ||
|
||
### Notes | ||
|
||
- Examples for CIFAR10 and MNIST can be found in the examples folder. | ||
- `LRFinder.range_test()` will change the model weights and the optimizer parameters. If you want to avoid this use: `model = copy.deepcopy(original_model)` | ||
- The learning rate and loss history can be accessed through `lr_finder.history`. This will return a dictionary with `lr` and `loss` keys. | ||
- When using `step_mode="linear"` the learning rate range should be within the same order of magnitude. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,143 @@ | ||
import torch.nn as nn | ||
|
||
|
||
__all__ = ["Cifar10ResNet", "resnet20", "resnet32", "resnet44", "resnet56", "resnet101"] | ||
|
||
|
||
def conv3x3(in_planes, out_planes, stride=1): | ||
"""3x3 convolution with padding""" | ||
return nn.Conv2d( | ||
in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False | ||
) | ||
|
||
|
||
def conv1x1(in_planes, out_planes, stride=1): | ||
"""1x1 convolution""" | ||
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) | ||
|
||
|
||
class BasicBlock(nn.Module): | ||
expansion = 1 | ||
|
||
def __init__(self, inplanes, planes, stride=1, downsample=None): | ||
super(BasicBlock, self).__init__() | ||
self.conv1 = conv3x3(inplanes, planes, stride) | ||
self.bn1 = nn.BatchNorm2d(planes) | ||
self.relu = nn.ReLU(inplace=True) | ||
self.conv2 = conv3x3(planes, planes) | ||
self.bn2 = nn.BatchNorm2d(planes) | ||
self.downsample = downsample | ||
self.stride = stride | ||
|
||
def forward(self, x): | ||
residual = x | ||
|
||
out = self.conv1(x) | ||
out = self.bn1(out) | ||
out = self.relu(out) | ||
|
||
out = self.conv2(out) | ||
out = self.bn2(out) | ||
|
||
if self.downsample is not None: | ||
residual = self.downsample(x) | ||
|
||
out += residual | ||
out = self.relu(out) | ||
|
||
return out | ||
|
||
|
||
class Cifar10ResNet(nn.Module): | ||
def __init__(self, block, layers, num_classes=10, ch_width=2): | ||
super(Cifar10ResNet, self).__init__() | ||
width = [16, 16 * ch_width, 16 * ch_width * ch_width] | ||
self.inplanes = 16 | ||
self.conv1 = nn.Conv2d( | ||
3, width[0], kernel_size=3, stride=1, padding=1, bias=False | ||
) | ||
self.bn1 = nn.BatchNorm2d(width[0]) | ||
self.relu = nn.ReLU(inplace=True) | ||
self.layer1 = self._make_layer(block, width[0], layers[0]) | ||
self.layer2 = self._make_layer(block, width[1], layers[1], stride=2) | ||
self.layer3 = self._make_layer(block, width[2], layers[2], stride=2) | ||
self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) | ||
self.fc = nn.Linear(width[2] * block.expansion, num_classes) | ||
|
||
for m in self.modules(): | ||
if isinstance(m, nn.Conv2d): | ||
nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") | ||
elif isinstance(m, nn.BatchNorm2d): | ||
nn.init.constant_(m.weight, 1) | ||
nn.init.constant_(m.bias, 0) | ||
|
||
def _make_layer(self, block, planes, blocks, stride=1): | ||
downsample = None | ||
if stride != 1 or self.inplanes != planes * block.expansion: | ||
downsample = nn.Sequential( | ||
conv1x1(self.inplanes, planes * block.expansion, stride), | ||
nn.BatchNorm2d(planes * block.expansion), | ||
) | ||
|
||
layers = [] | ||
layers.append(block(self.inplanes, planes, stride, downsample)) | ||
self.inplanes = planes * block.expansion | ||
for _ in range(1, blocks): | ||
layers.append(block(self.inplanes, planes)) | ||
|
||
return nn.Sequential(*layers) | ||
|
||
def forward(self, x): | ||
x = self.conv1(x) | ||
x = self.bn1(x) | ||
x = self.relu(x) | ||
|
||
x = self.layer1(x) | ||
x = self.layer2(x) | ||
x = self.layer3(x) | ||
|
||
x = self.avgpool(x) | ||
x = x.view(x.size(0), -1) | ||
x = self.fc(x) | ||
|
||
return x | ||
|
||
|
||
def resnet20(num_classes=10, ch_width=2): | ||
"""Constructs a ResNet-20 model. | ||
""" | ||
return Cifar10ResNet( | ||
BasicBlock, [3, 3, 3], num_classes=num_classes, ch_width=ch_width | ||
) | ||
|
||
|
||
def resnet32(num_classes=10, ch_width=2): | ||
"""Constructs a ResNet-32 model. | ||
""" | ||
return Cifar10ResNet( | ||
BasicBlock, [5, 5, 5], num_classes=num_classes, ch_width=ch_width | ||
) | ||
|
||
|
||
def resnet44(num_classes=10, ch_width=2): | ||
"""Constructs a ResNet-44 model. | ||
""" | ||
return Cifar10ResNet( | ||
BasicBlock, [7, 7, 7], num_classes=num_classes, ch_width=ch_width | ||
) | ||
|
||
|
||
def resnet56(num_classes=10, ch_width=2): | ||
"""Constructs a ResNet-56 model. | ||
""" | ||
return Cifar10ResNet( | ||
BasicBlock, [9, 9, 9], num_classes=num_classes, ch_width=ch_width | ||
) | ||
|
||
|
||
def resnet101(num_classes=10, ch_width=2): | ||
"""Constructs a ResNet-101 model. | ||
""" | ||
return Cifar10ResNet( | ||
BasicBlock, [18, 18, 18], num_classes=num_classes, ch_width=ch_width | ||
) |
Oops, something went wrong.