mmpretrain/mmcls/models/backbones/shufflenet_v2.py

292 lines
9.9 KiB
Python
Raw Normal View History

2020-05-28 11:48:14 +08:00
import torch
import torch.nn as nn
import torch.utils.checkpoint as cp
from mmcv.cnn import ConvModule, constant_init, normal_init
2020-06-14 00:46:22 +08:00
from torch.nn.modules.batchnorm import _BatchNorm
2020-05-28 11:48:14 +08:00
2020-06-15 20:46:30 +08:00
from mmcls.models.utils import channel_shuffle
2020-06-16 14:37:03 +08:00
from ..builder import BACKBONES
2020-05-28 11:48:14 +08:00
from .base_backbone import BaseBackbone
class InvertedResidual(nn.Module):
2020-06-14 00:46:22 +08:00
"""InvertedResidual block for ShuffleNetV2 backbone.
2020-06-07 23:33:47 +08:00
2020-06-14 00:46:22 +08:00
Args:
2020-07-03 19:21:18 +08:00
in_channels (int): The input channels of the block.
out_channels (int): The output channels of the block.
2020-06-15 15:15:19 +08:00
stride (int): Stride of the 3x3 convolution layer. Default: 1
conv_cfg (dict, optional): Config dict for convolution layer.
2020-06-14 03:51:42 +08:00
Default: None, which means using conv2d.
norm_cfg (dict): Config dict for normalization layer.
Default: dict(type='BN').
2020-06-14 00:46:22 +08:00
act_cfg (dict): Config dict for activation layer.
Default: dict(type='ReLU').
2020-06-14 03:51:42 +08:00
with_cp (bool): Use checkpoint or not. Using checkpoint will save some
memory while slowing down the training speed. Default: False.
2020-06-14 00:46:22 +08:00
Returns:
Tensor: The output tensor.
"""
2020-05-28 11:48:14 +08:00
2020-06-14 00:46:22 +08:00
def __init__(self,
2020-07-03 19:21:18 +08:00
in_channels,
out_channels,
2020-06-14 00:46:22 +08:00
stride=1,
conv_cfg=None,
norm_cfg=dict(type='BN'),
act_cfg=dict(type='ReLU'),
with_cp=False):
super(InvertedResidual, self).__init__()
2020-05-28 11:48:14 +08:00
self.stride = stride
self.with_cp = with_cp
2020-07-03 19:21:18 +08:00
branch_features = out_channels // 2
2020-06-15 15:15:19 +08:00
if self.stride == 1:
2020-07-03 19:21:18 +08:00
assert in_channels == branch_features * 2, (
f'in_channels ({in_channels}) should equal to '
f'branch_features * 2 ({branch_features * 2}) '
'when stride is 1')
2020-06-15 15:15:19 +08:00
2020-07-03 19:21:18 +08:00
if in_channels != branch_features * 2:
2020-06-15 20:42:04 +08:00
assert self.stride != 1, (
f'stride ({self.stride}) should not equal 1 when '
2020-07-03 19:21:18 +08:00
f'in_channels != branch_features * 2')
2020-05-28 11:48:14 +08:00
if self.stride > 1:
self.branch1 = nn.Sequential(
2020-06-14 00:46:22 +08:00
ConvModule(
2020-07-03 19:21:18 +08:00
in_channels,
in_channels,
2020-06-14 00:46:22 +08:00
kernel_size=3,
stride=self.stride,
padding=1,
2020-07-03 19:21:18 +08:00
groups=in_channels,
2020-06-14 00:46:22 +08:00
conv_cfg=conv_cfg,
norm_cfg=norm_cfg,
act_cfg=None),
ConvModule(
2020-07-03 19:21:18 +08:00
in_channels,
2020-06-07 23:33:47 +08:00
branch_features,
kernel_size=1,
stride=1,
padding=0,
2020-06-14 00:46:22 +08:00
conv_cfg=conv_cfg,
norm_cfg=norm_cfg,
act_cfg=act_cfg),
2020-05-28 11:48:14 +08:00
)
self.branch2 = nn.Sequential(
2020-06-14 00:46:22 +08:00
ConvModule(
2020-07-03 19:21:18 +08:00
in_channels if (self.stride > 1) else branch_features,
2020-06-07 23:33:47 +08:00
branch_features,
kernel_size=1,
stride=1,
padding=0,
2020-06-14 00:46:22 +08:00
conv_cfg=conv_cfg,
norm_cfg=norm_cfg,
act_cfg=act_cfg),
ConvModule(
2020-06-07 23:33:47 +08:00
branch_features,
branch_features,
kernel_size=3,
stride=self.stride,
2020-06-14 00:46:22 +08:00
padding=1,
groups=branch_features,
conv_cfg=conv_cfg,
norm_cfg=norm_cfg,
act_cfg=None),
ConvModule(
2020-06-07 23:33:47 +08:00
branch_features,
branch_features,
kernel_size=1,
stride=1,
padding=0,
2020-06-14 00:46:22 +08:00
conv_cfg=conv_cfg,
norm_cfg=norm_cfg,
act_cfg=act_cfg))
2020-05-28 11:48:14 +08:00
def forward(self, x):
2020-06-07 23:33:47 +08:00
2020-05-28 11:48:14 +08:00
def _inner_forward(x):
2020-06-15 15:15:19 +08:00
if self.stride > 1:
out = torch.cat((self.branch1(x), self.branch2(x)), dim=1)
else:
2020-05-28 11:48:14 +08:00
x1, x2 = x.chunk(2, dim=1)
out = torch.cat((x1, self.branch2(x2)), dim=1)
out = channel_shuffle(out, 2)
return out
if self.with_cp and x.requires_grad:
out = cp.checkpoint(_inner_forward, x)
else:
out = _inner_forward(x)
return out
2020-06-16 14:37:03 +08:00
@BACKBONES.register_module()
class ShuffleNetV2(BaseBackbone):
"""ShuffleNetV2 backbone.
2020-05-28 11:48:14 +08:00
Args:
2020-06-15 16:16:27 +08:00
widen_factor (float): Width multiplier - adjusts the number of
2020-06-14 00:46:22 +08:00
channels in each layer by this amount. Default: 1.0.
2020-05-28 11:48:14 +08:00
out_indices (Sequence[int]): Output from which stages.
2020-06-14 00:46:22 +08:00
Default: (0, 1, 2, 3).
frozen_stages (int): Stages to be frozen (all param fixed).
Default: -1, which means not freezing any parameters.
conv_cfg (dict, optional): Config dict for convolution layer.
2020-06-14 00:46:22 +08:00
Default: None, which means using conv2d.
norm_cfg (dict): Config dict for normalization layer.
Default: dict(type='BN').
act_cfg (dict): Config dict for activation layer.
Default: dict(type='ReLU').
norm_eval (bool): Whether to set norm layers to eval mode, namely,
freeze running stats (mean and var). Note: Effect on Batch Norm
2020-06-15 02:16:13 +08:00
and its variants only. Default: False.
2020-05-28 11:48:14 +08:00
with_cp (bool): Use checkpoint or not. Using checkpoint will save some
2020-06-14 00:46:22 +08:00
memory while slowing down the training speed. Default: False.
2020-05-28 11:48:14 +08:00
"""
def __init__(self,
widen_factor=1.0,
2020-07-08 15:22:18 +08:00
out_indices=(3, ),
2020-05-28 11:48:14 +08:00
frozen_stages=-1,
2020-06-14 00:46:22 +08:00
conv_cfg=None,
norm_cfg=dict(type='BN'),
act_cfg=dict(type='ReLU'),
2020-06-15 02:16:13 +08:00
norm_eval=False,
with_cp=False,
init_cfg=None):
super(ShuffleNetV2, self).__init__(init_cfg)
2020-06-14 00:46:22 +08:00
self.stage_blocks = [4, 8, 4]
2020-07-08 15:22:18 +08:00
for index in out_indices:
if index not in range(0, 4):
raise ValueError('the item in out_indices must in '
f'range(0, 4). But received {index}')
if frozen_stages not in range(-1, 4):
raise ValueError('frozen_stages must be in range(-1, 4). '
f'But received {frozen_stages}')
2020-05-28 11:48:14 +08:00
self.out_indices = out_indices
self.frozen_stages = frozen_stages
2020-06-14 00:46:22 +08:00
self.conv_cfg = conv_cfg
self.norm_cfg = norm_cfg
self.act_cfg = act_cfg
self.norm_eval = norm_eval
2020-05-28 11:48:14 +08:00
self.with_cp = with_cp
if widen_factor == 0.5:
channels = [48, 96, 192, 1024]
elif widen_factor == 1.0:
channels = [116, 232, 464, 1024]
elif widen_factor == 1.5:
channels = [176, 352, 704, 1024]
elif widen_factor == 2.0:
channels = [244, 488, 976, 2048]
else:
2020-06-15 15:15:19 +08:00
raise ValueError('widen_factor must be in [0.5, 1.0, 1.5, 2.0]. '
f'But received {widen_factor}')
2020-06-14 00:46:22 +08:00
2020-07-03 19:21:18 +08:00
self.in_channels = 24
2020-06-14 00:46:22 +08:00
self.conv1 = ConvModule(
in_channels=3,
2020-07-03 19:21:18 +08:00
out_channels=self.in_channels,
2020-06-14 00:46:22 +08:00
kernel_size=3,
stride=2,
padding=1,
conv_cfg=conv_cfg,
norm_cfg=norm_cfg,
act_cfg=act_cfg)
2020-05-28 11:48:14 +08:00
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
2020-06-15 20:42:04 +08:00
self.layers = nn.ModuleList()
2020-06-14 00:46:22 +08:00
for i, num_blocks in enumerate(self.stage_blocks):
layer = self._make_layer(channels[i], num_blocks)
2020-06-15 20:42:04 +08:00
self.layers.append(layer)
2020-06-14 00:46:22 +08:00
output_channels = channels[-1]
2020-07-08 15:22:18 +08:00
self.layers.append(
ConvModule(
in_channels=self.in_channels,
out_channels=output_channels,
kernel_size=1,
conv_cfg=conv_cfg,
norm_cfg=norm_cfg,
act_cfg=act_cfg))
2020-06-14 00:46:22 +08:00
2020-07-03 19:21:18 +08:00
def _make_layer(self, out_channels, num_blocks):
"""Stack blocks to make a layer.
2020-06-14 00:46:22 +08:00
Args:
2020-07-03 19:21:18 +08:00
out_channels (int): out_channels of the block.
2020-06-14 00:46:22 +08:00
num_blocks (int): number of blocks.
"""
layers = []
for i in range(num_blocks):
stride = 2 if i == 0 else 1
layers.append(
InvertedResidual(
2020-07-03 19:21:18 +08:00
in_channels=self.in_channels,
out_channels=out_channels,
2020-06-14 00:46:22 +08:00
stride=stride,
conv_cfg=self.conv_cfg,
norm_cfg=self.norm_cfg,
act_cfg=self.act_cfg,
with_cp=self.with_cp))
2020-07-03 19:21:18 +08:00
self.in_channels = out_channels
2020-06-14 00:46:22 +08:00
return nn.Sequential(*layers)
def _freeze_stages(self):
if self.frozen_stages >= 0:
2020-06-15 15:15:19 +08:00
for param in self.conv1.parameters():
param.requires_grad = False
2020-05-28 11:48:14 +08:00
2020-06-15 20:42:04 +08:00
for i in range(self.frozen_stages):
m = self.layers[i]
2020-06-14 00:46:22 +08:00
m.eval()
for param in m.parameters():
param.requires_grad = False
2020-05-28 11:48:14 +08:00
def init_weighs(self):
super(ShuffleNetV2, self).init_weights()
for name, m in self.named_modules():
if isinstance(m, nn.Conv2d):
if 'conv1' in name:
normal_init(m, mean=0, std=0.01)
else:
normal_init(m, mean=0, std=1.0 / m.weight.shape[1])
elif isinstance(m, (_BatchNorm, nn.GroupNorm)):
constant_init(m.weight, val=1, bias=0.0001)
if isinstance(m, _BatchNorm):
if m.running_mean is not None:
nn.init.constant_(m.running_mean, 0)
2020-05-28 11:48:14 +08:00
def forward(self, x):
x = self.conv1(x)
x = self.maxpool(x)
outs = []
2020-06-15 20:42:04 +08:00
for i, layer in enumerate(self.layers):
2020-06-14 00:46:22 +08:00
x = layer(x)
if i in self.out_indices:
outs.append(x)
2020-05-28 11:48:14 +08:00
if len(outs) == 1:
return outs[0]
else:
return tuple(outs)
def train(self, mode=True):
2020-06-16 14:37:03 +08:00
super(ShuffleNetV2, self).train(mode)
2020-06-14 00:46:22 +08:00
self._freeze_stages()
if mode and self.norm_eval:
2020-05-28 11:48:14 +08:00
for m in self.modules():
if isinstance(m, nn.BatchNorm2d):
m.eval()