shufflenetv2.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. from functools import partial
  2. from typing import Any, Callable, List, Optional
  3. import torch
  4. import torch.nn as nn
  5. from torch import Tensor
  6. from ..transforms._presets import ImageClassification
  7. from ..utils import _log_api_usage_once
  8. from ._api import register_model, Weights, WeightsEnum
  9. from ._meta import _IMAGENET_CATEGORIES
  10. from ._utils import _ovewrite_named_param, handle_legacy_interface
  11. __all__ = [
  12. "ShuffleNetV2",
  13. "ShuffleNet_V2_X0_5_Weights",
  14. "ShuffleNet_V2_X1_0_Weights",
  15. "ShuffleNet_V2_X1_5_Weights",
  16. "ShuffleNet_V2_X2_0_Weights",
  17. "shufflenet_v2_x0_5",
  18. "shufflenet_v2_x1_0",
  19. "shufflenet_v2_x1_5",
  20. "shufflenet_v2_x2_0",
  21. ]
  22. def channel_shuffle(x: Tensor, groups: int) -> Tensor:
  23. batchsize, num_channels, height, width = x.size()
  24. channels_per_group = num_channels // groups
  25. # reshape
  26. x = x.view(batchsize, groups, channels_per_group, height, width)
  27. x = torch.transpose(x, 1, 2).contiguous()
  28. # flatten
  29. x = x.view(batchsize, num_channels, height, width)
  30. return x
  31. class InvertedResidual(nn.Module):
  32. def __init__(self, inp: int, oup: int, stride: int) -> None:
  33. super().__init__()
  34. if not (1 <= stride <= 3):
  35. raise ValueError("illegal stride value")
  36. self.stride = stride
  37. branch_features = oup // 2
  38. if (self.stride == 1) and (inp != branch_features << 1):
  39. raise ValueError(
  40. f"Invalid combination of stride {stride}, inp {inp} and oup {oup} values. If stride == 1 then inp should be equal to oup // 2 << 1."
  41. )
  42. if self.stride > 1:
  43. self.branch1 = nn.Sequential(
  44. self.depthwise_conv(inp, inp, kernel_size=3, stride=self.stride, padding=1),
  45. nn.BatchNorm2d(inp),
  46. nn.Conv2d(inp, branch_features, kernel_size=1, stride=1, padding=0, bias=False),
  47. nn.BatchNorm2d(branch_features),
  48. nn.ReLU(inplace=True),
  49. )
  50. else:
  51. self.branch1 = nn.Sequential()
  52. self.branch2 = nn.Sequential(
  53. nn.Conv2d(
  54. inp if (self.stride > 1) else branch_features,
  55. branch_features,
  56. kernel_size=1,
  57. stride=1,
  58. padding=0,
  59. bias=False,
  60. ),
  61. nn.BatchNorm2d(branch_features),
  62. nn.ReLU(inplace=True),
  63. self.depthwise_conv(branch_features, branch_features, kernel_size=3, stride=self.stride, padding=1),
  64. nn.BatchNorm2d(branch_features),
  65. nn.Conv2d(branch_features, branch_features, kernel_size=1, stride=1, padding=0, bias=False),
  66. nn.BatchNorm2d(branch_features),
  67. nn.ReLU(inplace=True),
  68. )
  69. @staticmethod
  70. def depthwise_conv(
  71. i: int, o: int, kernel_size: int, stride: int = 1, padding: int = 0, bias: bool = False
  72. ) -> nn.Conv2d:
  73. return nn.Conv2d(i, o, kernel_size, stride, padding, bias=bias, groups=i)
  74. def forward(self, x: Tensor) -> Tensor:
  75. if self.stride == 1:
  76. x1, x2 = x.chunk(2, dim=1)
  77. out = torch.cat((x1, self.branch2(x2)), dim=1)
  78. else:
  79. out = torch.cat((self.branch1(x), self.branch2(x)), dim=1)
  80. out = channel_shuffle(out, 2)
  81. return out
  82. class ShuffleNetV2(nn.Module):
  83. def __init__(
  84. self,
  85. stages_repeats: List[int],
  86. stages_out_channels: List[int],
  87. num_classes: int = 1000,
  88. inverted_residual: Callable[..., nn.Module] = InvertedResidual,
  89. ) -> None:
  90. super().__init__()
  91. _log_api_usage_once(self)
  92. if len(stages_repeats) != 3:
  93. raise ValueError("expected stages_repeats as list of 3 positive ints")
  94. if len(stages_out_channels) != 5:
  95. raise ValueError("expected stages_out_channels as list of 5 positive ints")
  96. self._stage_out_channels = stages_out_channels
  97. input_channels = 3
  98. output_channels = self._stage_out_channels[0]
  99. self.conv1 = nn.Sequential(
  100. nn.Conv2d(input_channels, output_channels, 3, 2, 1, bias=False),
  101. nn.BatchNorm2d(output_channels),
  102. nn.ReLU(inplace=True),
  103. )
  104. input_channels = output_channels
  105. self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
  106. # Static annotations for mypy
  107. self.stage2: nn.Sequential
  108. self.stage3: nn.Sequential
  109. self.stage4: nn.Sequential
  110. stage_names = [f"stage{i}" for i in [2, 3, 4]]
  111. for name, repeats, output_channels in zip(stage_names, stages_repeats, self._stage_out_channels[1:]):
  112. seq = [inverted_residual(input_channels, output_channels, 2)]
  113. for i in range(repeats - 1):
  114. seq.append(inverted_residual(output_channels, output_channels, 1))
  115. setattr(self, name, nn.Sequential(*seq))
  116. input_channels = output_channels
  117. output_channels = self._stage_out_channels[-1]
  118. self.conv5 = nn.Sequential(
  119. nn.Conv2d(input_channels, output_channels, 1, 1, 0, bias=False),
  120. nn.BatchNorm2d(output_channels),
  121. nn.ReLU(inplace=True),
  122. )
  123. self.fc = nn.Linear(output_channels, num_classes)
  124. def _forward_impl(self, x: Tensor) -> Tensor:
  125. # See note [TorchScript super()]
  126. x = self.conv1(x)
  127. x = self.maxpool(x)
  128. x = self.stage2(x)
  129. x = self.stage3(x)
  130. x = self.stage4(x)
  131. x = self.conv5(x)
  132. x = x.mean([2, 3]) # globalpool
  133. x = self.fc(x)
  134. return x
  135. def forward(self, x: Tensor) -> Tensor:
  136. return self._forward_impl(x)
  137. def _shufflenetv2(
  138. weights: Optional[WeightsEnum],
  139. progress: bool,
  140. *args: Any,
  141. **kwargs: Any,
  142. ) -> ShuffleNetV2:
  143. if weights is not None:
  144. _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"]))
  145. model = ShuffleNetV2(*args, **kwargs)
  146. if weights is not None:
  147. model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
  148. return model
  149. _COMMON_META = {
  150. "min_size": (1, 1),
  151. "categories": _IMAGENET_CATEGORIES,
  152. "recipe": "https://github.com/ericsun99/Shufflenet-v2-Pytorch",
  153. }
  154. class ShuffleNet_V2_X0_5_Weights(WeightsEnum):
  155. IMAGENET1K_V1 = Weights(
  156. # Weights ported from https://github.com/ericsun99/Shufflenet-v2-Pytorch
  157. url="https://download.pytorch.org/models/shufflenetv2_x0.5-f707e7126e.pth",
  158. transforms=partial(ImageClassification, crop_size=224),
  159. meta={
  160. **_COMMON_META,
  161. "num_params": 1366792,
  162. "_metrics": {
  163. "ImageNet-1K": {
  164. "acc@1": 60.552,
  165. "acc@5": 81.746,
  166. }
  167. },
  168. "_ops": 0.04,
  169. "_file_size": 5.282,
  170. "_docs": """These weights were trained from scratch to reproduce closely the results of the paper.""",
  171. },
  172. )
  173. DEFAULT = IMAGENET1K_V1
  174. class ShuffleNet_V2_X1_0_Weights(WeightsEnum):
  175. IMAGENET1K_V1 = Weights(
  176. # Weights ported from https://github.com/ericsun99/Shufflenet-v2-Pytorch
  177. url="https://download.pytorch.org/models/shufflenetv2_x1-5666bf0f80.pth",
  178. transforms=partial(ImageClassification, crop_size=224),
  179. meta={
  180. **_COMMON_META,
  181. "num_params": 2278604,
  182. "_metrics": {
  183. "ImageNet-1K": {
  184. "acc@1": 69.362,
  185. "acc@5": 88.316,
  186. }
  187. },
  188. "_ops": 0.145,
  189. "_file_size": 8.791,
  190. "_docs": """These weights were trained from scratch to reproduce closely the results of the paper.""",
  191. },
  192. )
  193. DEFAULT = IMAGENET1K_V1
  194. class ShuffleNet_V2_X1_5_Weights(WeightsEnum):
  195. IMAGENET1K_V1 = Weights(
  196. url="https://download.pytorch.org/models/shufflenetv2_x1_5-3c479a10.pth",
  197. transforms=partial(ImageClassification, crop_size=224, resize_size=232),
  198. meta={
  199. **_COMMON_META,
  200. "recipe": "https://github.com/pytorch/vision/pull/5906",
  201. "num_params": 3503624,
  202. "_metrics": {
  203. "ImageNet-1K": {
  204. "acc@1": 72.996,
  205. "acc@5": 91.086,
  206. }
  207. },
  208. "_ops": 0.296,
  209. "_file_size": 13.557,
  210. "_docs": """
  211. These weights were trained from scratch by using TorchVision's `new training recipe
  212. <https://pytorch.org/blog/how-to-train-state-of-the-art-models-using-torchvision-latest-primitives/>`_.
  213. """,
  214. },
  215. )
  216. DEFAULT = IMAGENET1K_V1
  217. class ShuffleNet_V2_X2_0_Weights(WeightsEnum):
  218. IMAGENET1K_V1 = Weights(
  219. url="https://download.pytorch.org/models/shufflenetv2_x2_0-8be3c8ee.pth",
  220. transforms=partial(ImageClassification, crop_size=224, resize_size=232),
  221. meta={
  222. **_COMMON_META,
  223. "recipe": "https://github.com/pytorch/vision/pull/5906",
  224. "num_params": 7393996,
  225. "_metrics": {
  226. "ImageNet-1K": {
  227. "acc@1": 76.230,
  228. "acc@5": 93.006,
  229. }
  230. },
  231. "_ops": 0.583,
  232. "_file_size": 28.433,
  233. "_docs": """
  234. These weights were trained from scratch by using TorchVision's `new training recipe
  235. <https://pytorch.org/blog/how-to-train-state-of-the-art-models-using-torchvision-latest-primitives/>`_.
  236. """,
  237. },
  238. )
  239. DEFAULT = IMAGENET1K_V1
  240. @register_model()
  241. @handle_legacy_interface(weights=("pretrained", ShuffleNet_V2_X0_5_Weights.IMAGENET1K_V1))
  242. def shufflenet_v2_x0_5(
  243. *, weights: Optional[ShuffleNet_V2_X0_5_Weights] = None, progress: bool = True, **kwargs: Any
  244. ) -> ShuffleNetV2:
  245. """
  246. Constructs a ShuffleNetV2 architecture with 0.5x output channels, as described in
  247. `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design
  248. <https://arxiv.org/abs/1807.11164>`__.
  249. Args:
  250. weights (:class:`~torchvision.models.ShuffleNet_V2_X0_5_Weights`, optional): The
  251. pretrained weights to use. See
  252. :class:`~torchvision.models.ShuffleNet_V2_X0_5_Weights` below for
  253. more details, and possible values. By default, no pre-trained
  254. weights are used.
  255. progress (bool, optional): If True, displays a progress bar of the
  256. download to stderr. Default is True.
  257. **kwargs: parameters passed to the ``torchvision.models.shufflenetv2.ShuffleNetV2``
  258. base class. Please refer to the `source code
  259. <https://github.com/pytorch/vision/blob/main/torchvision/models/shufflenetv2.py>`_
  260. for more details about this class.
  261. .. autoclass:: torchvision.models.ShuffleNet_V2_X0_5_Weights
  262. :members:
  263. """
  264. weights = ShuffleNet_V2_X0_5_Weights.verify(weights)
  265. return _shufflenetv2(weights, progress, [4, 8, 4], [24, 48, 96, 192, 1024], **kwargs)
  266. @register_model()
  267. @handle_legacy_interface(weights=("pretrained", ShuffleNet_V2_X1_0_Weights.IMAGENET1K_V1))
  268. def shufflenet_v2_x1_0(
  269. *, weights: Optional[ShuffleNet_V2_X1_0_Weights] = None, progress: bool = True, **kwargs: Any
  270. ) -> ShuffleNetV2:
  271. """
  272. Constructs a ShuffleNetV2 architecture with 1.0x output channels, as described in
  273. `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design
  274. <https://arxiv.org/abs/1807.11164>`__.
  275. Args:
  276. weights (:class:`~torchvision.models.ShuffleNet_V2_X1_0_Weights`, optional): The
  277. pretrained weights to use. See
  278. :class:`~torchvision.models.ShuffleNet_V2_X1_0_Weights` below for
  279. more details, and possible values. By default, no pre-trained
  280. weights are used.
  281. progress (bool, optional): If True, displays a progress bar of the
  282. download to stderr. Default is True.
  283. **kwargs: parameters passed to the ``torchvision.models.shufflenetv2.ShuffleNetV2``
  284. base class. Please refer to the `source code
  285. <https://github.com/pytorch/vision/blob/main/torchvision/models/shufflenetv2.py>`_
  286. for more details about this class.
  287. .. autoclass:: torchvision.models.ShuffleNet_V2_X1_0_Weights
  288. :members:
  289. """
  290. weights = ShuffleNet_V2_X1_0_Weights.verify(weights)
  291. return _shufflenetv2(weights, progress, [4, 8, 4], [24, 116, 232, 464, 1024], **kwargs)
  292. @register_model()
  293. @handle_legacy_interface(weights=("pretrained", ShuffleNet_V2_X1_5_Weights.IMAGENET1K_V1))
  294. def shufflenet_v2_x1_5(
  295. *, weights: Optional[ShuffleNet_V2_X1_5_Weights] = None, progress: bool = True, **kwargs: Any
  296. ) -> ShuffleNetV2:
  297. """
  298. Constructs a ShuffleNetV2 architecture with 1.5x output channels, as described in
  299. `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design
  300. <https://arxiv.org/abs/1807.11164>`__.
  301. Args:
  302. weights (:class:`~torchvision.models.ShuffleNet_V2_X1_5_Weights`, optional): The
  303. pretrained weights to use. See
  304. :class:`~torchvision.models.ShuffleNet_V2_X1_5_Weights` below for
  305. more details, and possible values. By default, no pre-trained
  306. weights are used.
  307. progress (bool, optional): If True, displays a progress bar of the
  308. download to stderr. Default is True.
  309. **kwargs: parameters passed to the ``torchvision.models.shufflenetv2.ShuffleNetV2``
  310. base class. Please refer to the `source code
  311. <https://github.com/pytorch/vision/blob/main/torchvision/models/shufflenetv2.py>`_
  312. for more details about this class.
  313. .. autoclass:: torchvision.models.ShuffleNet_V2_X1_5_Weights
  314. :members:
  315. """
  316. weights = ShuffleNet_V2_X1_5_Weights.verify(weights)
  317. return _shufflenetv2(weights, progress, [4, 8, 4], [24, 176, 352, 704, 1024], **kwargs)
  318. @register_model()
  319. @handle_legacy_interface(weights=("pretrained", ShuffleNet_V2_X2_0_Weights.IMAGENET1K_V1))
  320. def shufflenet_v2_x2_0(
  321. *, weights: Optional[ShuffleNet_V2_X2_0_Weights] = None, progress: bool = True, **kwargs: Any
  322. ) -> ShuffleNetV2:
  323. """
  324. Constructs a ShuffleNetV2 architecture with 2.0x output channels, as described in
  325. `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design
  326. <https://arxiv.org/abs/1807.11164>`__.
  327. Args:
  328. weights (:class:`~torchvision.models.ShuffleNet_V2_X2_0_Weights`, optional): The
  329. pretrained weights to use. See
  330. :class:`~torchvision.models.ShuffleNet_V2_X2_0_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.shufflenetv2.ShuffleNetV2``
  336. base class. Please refer to the `source code
  337. <https://github.com/pytorch/vision/blob/main/torchvision/models/shufflenetv2.py>`_
  338. for more details about this class.
  339. .. autoclass:: torchvision.models.ShuffleNet_V2_X2_0_Weights
  340. :members:
  341. """
  342. weights = ShuffleNet_V2_X2_0_Weights.verify(weights)
  343. return _shufflenetv2(weights, progress, [4, 8, 4], [24, 244, 488, 976, 2048], **kwargs)