import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy
from olympus.utils import info
[docs]class Block(nn.Module):
"""expand + depthwise + pointwise
See :class`.MobileNetV2` for license and references`
"""
def __init__(self, in_planes, out_planes, expansion, stride):
super(Block, self).__init__()
self.stride = stride
planes = expansion * in_planes
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, stride=1, padding=0, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, groups=planes, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
self.conv3 = nn.Conv2d(planes, out_planes, kernel_size=1, stride=1, padding=0, bias=False)
self.bn3 = nn.BatchNorm2d(out_planes)
self.shortcut = nn.Sequential()
if stride == 1 and in_planes != out_planes:
self.shortcut = nn.Sequential(
nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=1, padding=0, bias=False),
nn.BatchNorm2d(out_planes),
)
[docs] def forward(self, x):
out = F.relu(self.bn1(self.conv1(x)))
out = F.relu(self.bn2(self.conv2(out)))
out = self.bn3(self.conv3(out))
out = out + self.shortcut(x) if self.stride == 1 else out
return out
[docs]class MobileNetV2(nn.Module):
"""Details on `arxiv <https://arxiv.org/abs/1801.04381>`_.
Original source `github <https://github.com/kuangliu/pytorch-cifar/blob/master/models/mobilenetv2.py>`_.
Attributes
----------
input_size: (1, 28, 28), (3, 32, 32), (3, 64, 64)
References
----------
.. [1] Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen.
"MobileNetV2: Inverted Residuals and Linear Bottlenecks" Mar 2019
Notes
-----
MIT License
Copyright (c) 2017 liukuang
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.
"""
# (expansion, out_planes, num_blocks, stride)
def __init__(self, cfg, input_size, conv, avgpool, num_classes=(10,)):
super(MobileNetV2, self).__init__()
self.cfg = cfg
if not isinstance(num_classes, int):
num_classes = numpy.product(num_classes)
self.conv1 = nn.Conv2d(input_size[0], 32, **conv, bias=False)
self.bn1 = nn.BatchNorm2d(32)
self.layers = self._make_layers(in_planes=32)
self.conv2 = nn.Conv2d(320, 1280, kernel_size=1, stride=1, padding=0, bias=False)
self.bn2 = nn.BatchNorm2d(1280)
self.avgpool = nn.AvgPool2d(**avgpool)
self.linear = nn.Linear(1280, num_classes)
def _make_layers(self, in_planes):
layers = []
for expansion, out_planes, num_blocks, stride in self.cfg:
strides = [stride] + [1]*(num_blocks-1)
for stride in strides:
layers.append(Block(in_planes, out_planes, expansion, stride))
in_planes = out_planes
return nn.Sequential(*layers)
[docs] def forward(self, x):
out = F.relu(self.bn1(self.conv1(x)))
out = self.layers(out)
out = F.relu(self.bn2(self.conv2(out)))
out = self.avgpool(out)
out = out.view(out.size(0), -1)
out = self.linear(out)
return out
[docs]def build(input_size, output_size):
cfg = [[1, 16, 1, 1],
[6, 24, 2, 1],
[6, 32, 3, 2],
[6, 64, 4, 2],
[6, 96, 3, 1],
[6, 160, 3, 2],
[6, 320, 1, 1]]
if input_size == (1, 28, 28):
info('Using MobileNetV2 architecture for MNIST')
conv = {'kernel_size': 3, 'stride': 1, 'padding': 1}
avgpool = {'kernel_size': 4}
elif input_size == (3, 32, 32):
info('Using MobileNetV2 architecture for CIFAR10/100')
conv = {'kernel_size': 3, 'stride': 1, 'padding': 1}
avgpool = {'kernel_size': 4}
elif input_size == (3, 64, 64):
info('Using MobileNetV2 architecture for TinyImageNet')
conv = {'kernel_size': 3, 'stride': 2, 'padding': 1}
avgpool = {'kernel_size': 2}
cfg[1][-1] = 2
# TODO: Add support for ImageNet
return MobileNetV2(cfg, input_size, num_classes=output_size, conv=conv, avgpool=avgpool)
builders = {
'mobilenetv2': build}