mobilenetv3.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. import warnings
  2. from functools import partial
  3. from typing import Any, Callable, List, Optional, Sequence
  4. import torch
  5. from torch import nn, Tensor
  6. from ..ops.misc import Conv2dNormActivation, SqueezeExcitation as SElayer
  7. from ..transforms._presets import ImageClassification
  8. from ..utils import _log_api_usage_once
  9. from ._api import WeightsEnum, Weights
  10. from ._meta import _IMAGENET_CATEGORIES
  11. from ._utils import handle_legacy_interface, _ovewrite_named_param, _make_divisible
  12. __all__ = [
  13. "MobileNetV3",
  14. "MobileNet_V3_Large_Weights",
  15. "MobileNet_V3_Small_Weights",
  16. "mobilenet_v3_large",
  17. "mobilenet_v3_small",
  18. ]
  19. class SqueezeExcitation(SElayer):
  20. """DEPRECATED"""
  21. def __init__(self, input_channels: int, squeeze_factor: int = 4):
  22. squeeze_channels = _make_divisible(input_channels // squeeze_factor, 8)
  23. super().__init__(input_channels, squeeze_channels, scale_activation=nn.Hardsigmoid)
  24. self.relu = self.activation
  25. delattr(self, "activation")
  26. warnings.warn(
  27. "This SqueezeExcitation class is deprecated since 0.12 and will be removed in 0.14. "
  28. "Use torchvision.ops.SqueezeExcitation instead.",
  29. FutureWarning,
  30. )
  31. class InvertedResidualConfig:
  32. # Stores information listed at Tables 1 and 2 of the MobileNetV3 paper
  33. def __init__(
  34. self,
  35. input_channels: int,
  36. kernel: int,
  37. expanded_channels: int,
  38. out_channels: int,
  39. use_se: bool,
  40. activation: str,
  41. stride: int,
  42. dilation: int,
  43. width_mult: float,
  44. ):
  45. self.input_channels = self.adjust_channels(input_channels, width_mult)
  46. self.kernel = kernel
  47. self.expanded_channels = self.adjust_channels(expanded_channels, width_mult)
  48. self.out_channels = self.adjust_channels(out_channels, width_mult)
  49. self.use_se = use_se
  50. self.use_hs = activation == "HS"
  51. self.stride = stride
  52. self.dilation = dilation
  53. @staticmethod
  54. def adjust_channels(channels: int, width_mult: float):
  55. return _make_divisible(channels * width_mult, 8)
  56. class InvertedResidual(nn.Module):
  57. # Implemented as described at section 5 of MobileNetV3 paper
  58. def __init__(
  59. self,
  60. cnf: InvertedResidualConfig,
  61. norm_layer: Callable[..., nn.Module],
  62. se_layer: Callable[..., nn.Module] = partial(SElayer, scale_activation=nn.Hardsigmoid),
  63. ):
  64. super().__init__()
  65. if not (1 <= cnf.stride <= 2):
  66. raise ValueError("illegal stride value")
  67. self.use_res_connect = cnf.stride == 1 and cnf.input_channels == cnf.out_channels
  68. layers: List[nn.Module] = []
  69. activation_layer = nn.Hardswish if cnf.use_hs else nn.ReLU
  70. # expand
  71. if cnf.expanded_channels != cnf.input_channels:
  72. layers.append(
  73. Conv2dNormActivation(
  74. cnf.input_channels,
  75. cnf.expanded_channels,
  76. kernel_size=1,
  77. norm_layer=norm_layer,
  78. activation_layer=activation_layer,
  79. )
  80. )
  81. # depthwise
  82. stride = 1 if cnf.dilation > 1 else cnf.stride
  83. layers.append(
  84. Conv2dNormActivation(
  85. cnf.expanded_channels,
  86. cnf.expanded_channels,
  87. kernel_size=cnf.kernel,
  88. stride=stride,
  89. dilation=cnf.dilation,
  90. groups=cnf.expanded_channels,
  91. norm_layer=norm_layer,
  92. activation_layer=activation_layer,
  93. )
  94. )
  95. if cnf.use_se:
  96. squeeze_channels = _make_divisible(cnf.expanded_channels // 4, 8)
  97. layers.append(se_layer(cnf.expanded_channels, squeeze_channels))
  98. # project
  99. layers.append(
  100. Conv2dNormActivation(
  101. cnf.expanded_channels, cnf.out_channels, kernel_size=1, norm_layer=norm_layer, activation_layer=None
  102. )
  103. )
  104. self.block = nn.Sequential(*layers)
  105. self.out_channels = cnf.out_channels
  106. self._is_cn = cnf.stride > 1
  107. def forward(self, input: Tensor) -> Tensor:
  108. result = self.block(input)
  109. if self.use_res_connect:
  110. result += input
  111. return result
  112. class MobileNetV3(nn.Module):
  113. def __init__(
  114. self,
  115. inverted_residual_setting: List[InvertedResidualConfig],
  116. last_channel: int,
  117. num_classes: int = 1000,
  118. block: Optional[Callable[..., nn.Module]] = None,
  119. norm_layer: Optional[Callable[..., nn.Module]] = None,
  120. dropout: float = 0.2,
  121. **kwargs: Any,
  122. ) -> None:
  123. """
  124. MobileNet V3 main class
  125. Args:
  126. inverted_residual_setting (List[InvertedResidualConfig]): Network structure
  127. last_channel (int): The number of channels on the penultimate layer
  128. num_classes (int): Number of classes
  129. block (Optional[Callable[..., nn.Module]]): Module specifying inverted residual building block for mobilenet
  130. norm_layer (Optional[Callable[..., nn.Module]]): Module specifying the normalization layer to use
  131. dropout (float): The droupout probability
  132. """
  133. super().__init__()
  134. _log_api_usage_once(self)
  135. if not inverted_residual_setting:
  136. raise ValueError("The inverted_residual_setting should not be empty")
  137. elif not (
  138. isinstance(inverted_residual_setting, Sequence)
  139. and all([isinstance(s, InvertedResidualConfig) for s in inverted_residual_setting])
  140. ):
  141. raise TypeError("The inverted_residual_setting should be List[InvertedResidualConfig]")
  142. if block is None:
  143. block = InvertedResidual
  144. if norm_layer is None:
  145. norm_layer = partial(nn.BatchNorm2d, eps=0.001, momentum=0.01)
  146. layers: List[nn.Module] = []
  147. # building first layer
  148. firstconv_output_channels = inverted_residual_setting[0].input_channels
  149. layers.append(
  150. Conv2dNormActivation(
  151. 3,
  152. firstconv_output_channels,
  153. kernel_size=3,
  154. stride=2,
  155. norm_layer=norm_layer,
  156. activation_layer=nn.Hardswish,
  157. )
  158. )
  159. # building inverted residual blocks
  160. for cnf in inverted_residual_setting:
  161. layers.append(block(cnf, norm_layer))
  162. # building last several layers
  163. lastconv_input_channels = inverted_residual_setting[-1].out_channels
  164. lastconv_output_channels = 6 * lastconv_input_channels
  165. layers.append(
  166. Conv2dNormActivation(
  167. lastconv_input_channels,
  168. lastconv_output_channels,
  169. kernel_size=1,
  170. norm_layer=norm_layer,
  171. activation_layer=nn.Hardswish,
  172. )
  173. )
  174. self.features = nn.Sequential(*layers)
  175. self.avgpool = nn.AdaptiveAvgPool2d(1)
  176. self.classifier = nn.Sequential(
  177. nn.Linear(lastconv_output_channels, last_channel),
  178. nn.Hardswish(inplace=True),
  179. nn.Dropout(p=dropout, inplace=True),
  180. nn.Linear(last_channel, num_classes),
  181. )
  182. for m in self.modules():
  183. if isinstance(m, nn.Conv2d):
  184. nn.init.kaiming_normal_(m.weight, mode="fan_out")
  185. if m.bias is not None:
  186. nn.init.zeros_(m.bias)
  187. elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
  188. nn.init.ones_(m.weight)
  189. nn.init.zeros_(m.bias)
  190. elif isinstance(m, nn.Linear):
  191. nn.init.normal_(m.weight, 0, 0.01)
  192. nn.init.zeros_(m.bias)
  193. def _forward_impl(self, x: Tensor) -> Tensor:
  194. x = self.features(x)
  195. x = self.avgpool(x)
  196. x = torch.flatten(x, 1)
  197. x = self.classifier(x)
  198. return x
  199. def forward(self, x: Tensor) -> Tensor:
  200. return self._forward_impl(x)
  201. def _mobilenet_v3_conf(
  202. arch: str, width_mult: float = 1.0, reduced_tail: bool = False, dilated: bool = False, **kwargs: Any
  203. ):
  204. reduce_divider = 2 if reduced_tail else 1
  205. dilation = 2 if dilated else 1
  206. bneck_conf = partial(InvertedResidualConfig, width_mult=width_mult)
  207. adjust_channels = partial(InvertedResidualConfig.adjust_channels, width_mult=width_mult)
  208. if arch == "mobilenet_v3_large":
  209. inverted_residual_setting = [
  210. bneck_conf(16, 3, 16, 16, False, "RE", 1, 1),
  211. bneck_conf(16, 3, 64, 24, False, "RE", 2, 1), # C1
  212. bneck_conf(24, 3, 72, 24, False, "RE", 1, 1),
  213. bneck_conf(24, 5, 72, 40, True, "RE", 2, 1), # C2
  214. bneck_conf(40, 5, 120, 40, True, "RE", 1, 1),
  215. bneck_conf(40, 5, 120, 40, True, "RE", 1, 1),
  216. bneck_conf(40, 3, 240, 80, False, "HS", 2, 1), # C3
  217. bneck_conf(80, 3, 200, 80, False, "HS", 1, 1),
  218. bneck_conf(80, 3, 184, 80, False, "HS", 1, 1),
  219. bneck_conf(80, 3, 184, 80, False, "HS", 1, 1),
  220. bneck_conf(80, 3, 480, 112, True, "HS", 1, 1),
  221. bneck_conf(112, 3, 672, 112, True, "HS", 1, 1),
  222. bneck_conf(112, 5, 672, 160 // reduce_divider, True, "HS", 2, dilation), # C4
  223. bneck_conf(160 // reduce_divider, 5, 960 // reduce_divider, 160 // reduce_divider, True, "HS", 1, dilation),
  224. bneck_conf(160 // reduce_divider, 5, 960 // reduce_divider, 160 // reduce_divider, True, "HS", 1, dilation),
  225. ]
  226. last_channel = adjust_channels(1280 // reduce_divider) # C5
  227. elif arch == "mobilenet_v3_small":
  228. inverted_residual_setting = [
  229. bneck_conf(16, 3, 16, 16, True, "RE", 2, 1), # C1
  230. bneck_conf(16, 3, 72, 24, False, "RE", 2, 1), # C2
  231. bneck_conf(24, 3, 88, 24, False, "RE", 1, 1),
  232. bneck_conf(24, 5, 96, 40, True, "HS", 2, 1), # C3
  233. bneck_conf(40, 5, 240, 40, True, "HS", 1, 1),
  234. bneck_conf(40, 5, 240, 40, True, "HS", 1, 1),
  235. bneck_conf(40, 5, 120, 48, True, "HS", 1, 1),
  236. bneck_conf(48, 5, 144, 48, True, "HS", 1, 1),
  237. bneck_conf(48, 5, 288, 96 // reduce_divider, True, "HS", 2, dilation), # C4
  238. bneck_conf(96 // reduce_divider, 5, 576 // reduce_divider, 96 // reduce_divider, True, "HS", 1, dilation),
  239. bneck_conf(96 // reduce_divider, 5, 576 // reduce_divider, 96 // reduce_divider, True, "HS", 1, dilation),
  240. ]
  241. last_channel = adjust_channels(1024 // reduce_divider) # C5
  242. else:
  243. raise ValueError(f"Unsupported model type {arch}")
  244. return inverted_residual_setting, last_channel
  245. def _mobilenet_v3(
  246. inverted_residual_setting: List[InvertedResidualConfig],
  247. last_channel: int,
  248. weights: Optional[WeightsEnum],
  249. progress: bool,
  250. **kwargs: Any,
  251. ) -> MobileNetV3:
  252. if weights is not None:
  253. _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"]))
  254. model = MobileNetV3(inverted_residual_setting, last_channel, **kwargs)
  255. if weights is not None:
  256. model.load_state_dict(weights.get_state_dict(progress=progress))
  257. return model
  258. _COMMON_META = {
  259. "min_size": (1, 1),
  260. "categories": _IMAGENET_CATEGORIES,
  261. }
  262. class MobileNet_V3_Large_Weights(WeightsEnum):
  263. IMAGENET1K_V1 = Weights(
  264. url="https://download.pytorch.org/models/mobilenet_v3_large-8738ca79.pth",
  265. transforms=partial(ImageClassification, crop_size=224),
  266. meta={
  267. **_COMMON_META,
  268. "num_params": 5483032,
  269. "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#mobilenetv3-large--small",
  270. "_metrics": {
  271. "ImageNet-1K": {
  272. "acc@1": 74.042,
  273. "acc@5": 91.340,
  274. }
  275. },
  276. "_docs": """These weights were trained from scratch by using a simple training recipe.""",
  277. },
  278. )
  279. IMAGENET1K_V2 = Weights(
  280. url="https://download.pytorch.org/models/mobilenet_v3_large-5c1a4163.pth",
  281. transforms=partial(ImageClassification, crop_size=224, resize_size=232),
  282. meta={
  283. **_COMMON_META,
  284. "num_params": 5483032,
  285. "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe-with-reg-tuning",
  286. "_metrics": {
  287. "ImageNet-1K": {
  288. "acc@1": 75.274,
  289. "acc@5": 92.566,
  290. }
  291. },
  292. "_docs": """
  293. These weights improve marginally upon the results of the original paper by using a modified version of
  294. TorchVision's `new training recipe
  295. <https://pytorch.org/blog/how-to-train-state-of-the-art-models-using-torchvision-latest-primitives/>`_.
  296. """,
  297. },
  298. )
  299. DEFAULT = IMAGENET1K_V2
  300. class MobileNet_V3_Small_Weights(WeightsEnum):
  301. IMAGENET1K_V1 = Weights(
  302. url="https://download.pytorch.org/models/mobilenet_v3_small-047dcff4.pth",
  303. transforms=partial(ImageClassification, crop_size=224),
  304. meta={
  305. **_COMMON_META,
  306. "num_params": 2542856,
  307. "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#mobilenetv3-large--small",
  308. "_metrics": {
  309. "ImageNet-1K": {
  310. "acc@1": 67.668,
  311. "acc@5": 87.402,
  312. }
  313. },
  314. "_docs": """
  315. These weights improve upon the results of the original paper by using a simple training recipe.
  316. """,
  317. },
  318. )
  319. DEFAULT = IMAGENET1K_V1
  320. @handle_legacy_interface(weights=("pretrained", MobileNet_V3_Large_Weights.IMAGENET1K_V1))
  321. def mobilenet_v3_large(
  322. *, weights: Optional[MobileNet_V3_Large_Weights] = None, progress: bool = True, **kwargs: Any
  323. ) -> MobileNetV3:
  324. """
  325. Constructs a large MobileNetV3 architecture from
  326. `Searching for MobileNetV3 <https://arxiv.org/abs/1905.02244>`__.
  327. Args:
  328. weights (:class:`~torchvision.models.MobileNet_V3_Large_Weights`, optional): The
  329. pretrained weights to use. See
  330. :class:`~torchvision.models.MobileNet_V3_Large_Weights` below for
  331. more details, and possible values. By default, no pre-trained
  332. weights are used.
  333. progress (bool, optional): If True, displays a progress bar of the
  334. download to stderr. Default is True.
  335. **kwargs: parameters passed to the ``torchvision.models.resnet.MobileNetV3``
  336. base class. Please refer to the `source code
  337. <https://github.com/pytorch/vision/blob/main/torchvision/models/mobilenetv3.py>`_
  338. for more details about this class.
  339. .. autoclass:: torchvision.models.MobileNet_V3_Large_Weights
  340. :members:
  341. """
  342. weights = MobileNet_V3_Large_Weights.verify(weights)
  343. inverted_residual_setting, last_channel = _mobilenet_v3_conf("mobilenet_v3_large", **kwargs)
  344. return _mobilenet_v3(inverted_residual_setting, last_channel, weights, progress, **kwargs)
  345. @handle_legacy_interface(weights=("pretrained", MobileNet_V3_Small_Weights.IMAGENET1K_V1))
  346. def mobilenet_v3_small(
  347. *, weights: Optional[MobileNet_V3_Small_Weights] = None, progress: bool = True, **kwargs: Any
  348. ) -> MobileNetV3:
  349. """
  350. Constructs a small MobileNetV3 architecture from
  351. `Searching for MobileNetV3 <https://arxiv.org/abs/1905.02244>`__.
  352. Args:
  353. weights (:class:`~torchvision.models.MobileNet_V3_Small_Weights`, optional): The
  354. pretrained weights to use. See
  355. :class:`~torchvision.models.MobileNet_V3_Small_Weights` below for
  356. more details, and possible values. By default, no pre-trained
  357. weights are used.
  358. progress (bool, optional): If True, displays a progress bar of the
  359. download to stderr. Default is True.
  360. **kwargs: parameters passed to the ``torchvision.models.resnet.MobileNetV3``
  361. base class. Please refer to the `source code
  362. <https://github.com/pytorch/vision/blob/main/torchvision/models/mobilenetv3.py>`_
  363. for more details about this class.
  364. .. autoclass:: torchvision.models.MobileNet_V3_Small_Weights
  365. :members:
  366. """
  367. weights = MobileNet_V3_Small_Weights.verify(weights)
  368. inverted_residual_setting, last_channel = _mobilenet_v3_conf("mobilenet_v3_small", **kwargs)
  369. return _mobilenet_v3(inverted_residual_setting, last_channel, weights, progress, **kwargs)
  370. # The dictionary below is internal implementation detail and will be removed in v0.15
  371. from ._utils import _ModelURLs
  372. model_urls = _ModelURLs(
  373. {
  374. "mobilenet_v3_large": MobileNet_V3_Large_Weights.IMAGENET1K_V1.url,
  375. "mobilenet_v3_small": MobileNet_V3_Small_Weights.IMAGENET1K_V1.url,
  376. }
  377. )