You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

mobilenet_v2.py 7.6 kB

2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import warnings
  3. import torch.nn as nn
  4. from mmcv.cnn import ConvModule
  5. from mmcv.runner import BaseModule
  6. from torch.nn.modules.batchnorm import _BatchNorm
  7. from ..builder import BACKBONES
  8. from ..utils import InvertedResidual, make_divisible
  9. @BACKBONES.register_module()
  10. class MobileNetV2(BaseModule):
  11. """MobileNetV2 backbone.
  12. Args:
  13. widen_factor (float): Width multiplier, multiply number of
  14. channels in each layer by this amount. Default: 1.0.
  15. out_indices (Sequence[int], optional): Output from which stages.
  16. Default: (1, 2, 4, 7).
  17. frozen_stages (int): Stages to be frozen (all param fixed).
  18. Default: -1, which means not freezing any parameters.
  19. conv_cfg (dict, optional): Config dict for convolution layer.
  20. Default: None, which means using conv2d.
  21. norm_cfg (dict): Config dict for normalization layer.
  22. Default: dict(type='BN').
  23. act_cfg (dict): Config dict for activation layer.
  24. Default: dict(type='ReLU6').
  25. norm_eval (bool): Whether to set norm layers to eval mode, namely,
  26. freeze running stats (mean and var). Note: Effect on Batch Norm
  27. and its variants only. Default: False.
  28. with_cp (bool): Use checkpoint or not. Using checkpoint will save some
  29. memory while slowing down the training speed. Default: False.
  30. pretrained (str, optional): model pretrained path. Default: None
  31. init_cfg (dict or list[dict], optional): Initialization config dict.
  32. Default: None
  33. """
  34. # Parameters to build layers. 4 parameters are needed to construct a
  35. # layer, from left to right: expand_ratio, channel, num_blocks, stride.
  36. arch_settings = [[1, 16, 1, 1], [6, 24, 2, 2], [6, 32, 3, 2],
  37. [6, 64, 4, 2], [6, 96, 3, 1], [6, 160, 3, 2],
  38. [6, 320, 1, 1]]
  39. def __init__(self,
  40. widen_factor=1.,
  41. out_indices=(1, 2, 4, 7),
  42. frozen_stages=-1,
  43. conv_cfg=None,
  44. norm_cfg=dict(type='BN'),
  45. act_cfg=dict(type='ReLU6'),
  46. norm_eval=False,
  47. with_cp=False,
  48. pretrained=None,
  49. init_cfg=None):
  50. super(MobileNetV2, self).__init__(init_cfg)
  51. self.pretrained = pretrained
  52. assert not (init_cfg and pretrained), \
  53. 'init_cfg and pretrained cannot be specified at the same time'
  54. if isinstance(pretrained, str):
  55. warnings.warn('DeprecationWarning: pretrained is deprecated, '
  56. 'please use "init_cfg" instead')
  57. self.init_cfg = dict(type='Pretrained', checkpoint=pretrained)
  58. elif pretrained is None:
  59. if init_cfg is None:
  60. self.init_cfg = [
  61. dict(type='Kaiming', layer='Conv2d'),
  62. dict(
  63. type='Constant',
  64. val=1,
  65. layer=['_BatchNorm', 'GroupNorm'])
  66. ]
  67. else:
  68. raise TypeError('pretrained must be a str or None')
  69. self.widen_factor = widen_factor
  70. self.out_indices = out_indices
  71. if not set(out_indices).issubset(set(range(0, 8))):
  72. raise ValueError('out_indices must be a subset of range'
  73. f'(0, 8). But received {out_indices}')
  74. if frozen_stages not in range(-1, 8):
  75. raise ValueError('frozen_stages must be in range(-1, 8). '
  76. f'But received {frozen_stages}')
  77. self.out_indices = out_indices
  78. self.frozen_stages = frozen_stages
  79. self.conv_cfg = conv_cfg
  80. self.norm_cfg = norm_cfg
  81. self.act_cfg = act_cfg
  82. self.norm_eval = norm_eval
  83. self.with_cp = with_cp
  84. self.in_channels = make_divisible(32 * widen_factor, 8)
  85. self.conv1 = ConvModule(
  86. in_channels=3,
  87. out_channels=self.in_channels,
  88. kernel_size=3,
  89. stride=2,
  90. padding=1,
  91. conv_cfg=self.conv_cfg,
  92. norm_cfg=self.norm_cfg,
  93. act_cfg=self.act_cfg)
  94. self.layers = []
  95. for i, layer_cfg in enumerate(self.arch_settings):
  96. expand_ratio, channel, num_blocks, stride = layer_cfg
  97. out_channels = make_divisible(channel * widen_factor, 8)
  98. inverted_res_layer = self.make_layer(
  99. out_channels=out_channels,
  100. num_blocks=num_blocks,
  101. stride=stride,
  102. expand_ratio=expand_ratio)
  103. layer_name = f'layer{i + 1}'
  104. self.add_module(layer_name, inverted_res_layer)
  105. self.layers.append(layer_name)
  106. if widen_factor > 1.0:
  107. self.out_channel = int(1280 * widen_factor)
  108. else:
  109. self.out_channel = 1280
  110. layer = ConvModule(
  111. in_channels=self.in_channels,
  112. out_channels=self.out_channel,
  113. kernel_size=1,
  114. stride=1,
  115. padding=0,
  116. conv_cfg=self.conv_cfg,
  117. norm_cfg=self.norm_cfg,
  118. act_cfg=self.act_cfg)
  119. self.add_module('conv2', layer)
  120. self.layers.append('conv2')
  121. def make_layer(self, out_channels, num_blocks, stride, expand_ratio):
  122. """Stack InvertedResidual blocks to build a layer for MobileNetV2.
  123. Args:
  124. out_channels (int): out_channels of block.
  125. num_blocks (int): number of blocks.
  126. stride (int): stride of the first block. Default: 1
  127. expand_ratio (int): Expand the number of channels of the
  128. hidden layer in InvertedResidual by this ratio. Default: 6.
  129. """
  130. layers = []
  131. for i in range(num_blocks):
  132. if i >= 1:
  133. stride = 1
  134. layers.append(
  135. InvertedResidual(
  136. self.in_channels,
  137. out_channels,
  138. mid_channels=int(round(self.in_channels * expand_ratio)),
  139. stride=stride,
  140. with_expand_conv=expand_ratio != 1,
  141. conv_cfg=self.conv_cfg,
  142. norm_cfg=self.norm_cfg,
  143. act_cfg=self.act_cfg,
  144. with_cp=self.with_cp))
  145. self.in_channels = out_channels
  146. return nn.Sequential(*layers)
  147. def _freeze_stages(self):
  148. if self.frozen_stages >= 0:
  149. for param in self.conv1.parameters():
  150. param.requires_grad = False
  151. for i in range(1, self.frozen_stages + 1):
  152. layer = getattr(self, f'layer{i}')
  153. layer.eval()
  154. for param in layer.parameters():
  155. param.requires_grad = False
  156. def forward(self, x):
  157. """Forward function."""
  158. x = self.conv1(x)
  159. outs = []
  160. for i, layer_name in enumerate(self.layers):
  161. layer = getattr(self, layer_name)
  162. x = layer(x)
  163. if i in self.out_indices:
  164. outs.append(x)
  165. return tuple(outs)
  166. def train(self, mode=True):
  167. """Convert the model into training mode while keep normalization layer
  168. frozen."""
  169. super(MobileNetV2, self).train(mode)
  170. self._freeze_stages()
  171. if mode and self.norm_eval:
  172. for m in self.modules():
  173. # trick: eval have effect on BatchNorm only
  174. if isinstance(m, _BatchNorm):
  175. m.eval()

No Description

Contributors (2)