shufflenetv2.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. from functools import partial
  2. from typing import Callable, Any, 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 WeightsEnum, Weights
  9. from ._meta import _IMAGENET_CATEGORIES
  10. from ._utils import handle_legacy_interface, _ovewrite_named_param
  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, -1, 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))
  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. "_docs": """These weights were trained from scratch to reproduce closely the results of the paper.""",
  169. },
  170. )
  171. DEFAULT = IMAGENET1K_V1
  172. class ShuffleNet_V2_X1_0_Weights(WeightsEnum):
  173. IMAGENET1K_V1 = Weights(
  174. # Weights ported from https://github.com/ericsun99/Shufflenet-v2-Pytorch
  175. url="https://download.pytorch.org/models/shufflenetv2_x1-5666bf0f80.pth",
  176. transforms=partial(ImageClassification, crop_size=224),
  177. meta={
  178. **_COMMON_META,
  179. "num_params": 2278604,
  180. "_metrics": {
  181. "ImageNet-1K": {
  182. "acc@1": 69.362,
  183. "acc@5": 88.316,
  184. }
  185. },
  186. "_docs": """These weights were trained from scratch to reproduce closely the results of the paper.""",
  187. },
  188. )
  189. DEFAULT = IMAGENET1K_V1
  190. class ShuffleNet_V2_X1_5_Weights(WeightsEnum):
  191. IMAGENET1K_V1 = Weights(
  192. url="https://download.pytorch.org/models/shufflenetv2_x1_5-3c479a10.pth",
  193. transforms=partial(ImageClassification, crop_size=224, resize_size=232),
  194. meta={
  195. **_COMMON_META,
  196. "recipe": "https://github.com/pytorch/vision/pull/5906",
  197. "num_params": 3503624,
  198. "_metrics": {
  199. "ImageNet-1K": {
  200. "acc@1": 72.996,
  201. "acc@5": 91.086,
  202. }
  203. },
  204. "_docs": """
  205. These weights were trained from scratch by using TorchVision's `new training recipe
  206. <https://pytorch.org/blog/how-to-train-state-of-the-art-models-using-torchvision-latest-primitives/>`_.
  207. """,
  208. },
  209. )
  210. DEFAULT = IMAGENET1K_V1
  211. class ShuffleNet_V2_X2_0_Weights(WeightsEnum):
  212. IMAGENET1K_V1 = Weights(
  213. url="https://download.pytorch.org/models/shufflenetv2_x2_0-8be3c8ee.pth",
  214. transforms=partial(ImageClassification, crop_size=224, resize_size=232),
  215. meta={
  216. **_COMMON_META,
  217. "recipe": "https://github.com/pytorch/vision/pull/5906",
  218. "num_params": 7393996,
  219. "_metrics": {
  220. "ImageNet-1K": {
  221. "acc@1": 76.230,
  222. "acc@5": 93.006,
  223. }
  224. },
  225. "_docs": """
  226. These weights were trained from scratch by using TorchVision's `new training recipe
  227. <https://pytorch.org/blog/how-to-train-state-of-the-art-models-using-torchvision-latest-primitives/>`_.
  228. """,
  229. },
  230. )
  231. DEFAULT = IMAGENET1K_V1
  232. @handle_legacy_interface(weights=("pretrained", ShuffleNet_V2_X0_5_Weights.IMAGENET1K_V1))
  233. def shufflenet_v2_x0_5(
  234. *, weights: Optional[ShuffleNet_V2_X0_5_Weights] = None, progress: bool = True, **kwargs: Any
  235. ) -> ShuffleNetV2:
  236. """
  237. Constructs a ShuffleNetV2 architecture with 0.5x output channels, as described in
  238. `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design
  239. <https://arxiv.org/abs/1807.11164>`__.
  240. Args:
  241. weights (:class:`~torchvision.models.ShuffleNet_V2_X0_5_Weights`, optional): The
  242. pretrained weights to use. See
  243. :class:`~torchvision.models.ShuffleNet_V2_X0_5_Weights` below for
  244. more details, and possible values. By default, no pre-trained
  245. weights are used.
  246. progress (bool, optional): If True, displays a progress bar of the
  247. download to stderr. Default is True.
  248. **kwargs: parameters passed to the ``torchvision.models.shufflenetv2.ShuffleNetV2``
  249. base class. Please refer to the `source code
  250. <https://github.com/pytorch/vision/blob/main/torchvision/models/shufflenetv2.py>`_
  251. for more details about this class.
  252. .. autoclass:: torchvision.models.ShuffleNet_V2_X0_5_Weights
  253. :members:
  254. """
  255. weights = ShuffleNet_V2_X0_5_Weights.verify(weights)
  256. return _shufflenetv2(weights, progress, [4, 8, 4], [24, 48, 96, 192, 1024], **kwargs)
  257. @handle_legacy_interface(weights=("pretrained", ShuffleNet_V2_X1_0_Weights.IMAGENET1K_V1))
  258. def shufflenet_v2_x1_0(
  259. *, weights: Optional[ShuffleNet_V2_X1_0_Weights] = None, progress: bool = True, **kwargs: Any
  260. ) -> ShuffleNetV2:
  261. """
  262. Constructs a ShuffleNetV2 architecture with 1.0x output channels, as described in
  263. `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design
  264. <https://arxiv.org/abs/1807.11164>`__.
  265. Args:
  266. weights (:class:`~torchvision.models.ShuffleNet_V2_X1_0_Weights`, optional): The
  267. pretrained weights to use. See
  268. :class:`~torchvision.models.ShuffleNet_V2_X1_0_Weights` below for
  269. more details, and possible values. By default, no pre-trained
  270. weights are used.
  271. progress (bool, optional): If True, displays a progress bar of the
  272. download to stderr. Default is True.
  273. **kwargs: parameters passed to the ``torchvision.models.shufflenetv2.ShuffleNetV2``
  274. base class. Please refer to the `source code
  275. <https://github.com/pytorch/vision/blob/main/torchvision/models/shufflenetv2.py>`_
  276. for more details about this class.
  277. .. autoclass:: torchvision.models.ShuffleNet_V2_X1_0_Weights
  278. :members:
  279. """
  280. weights = ShuffleNet_V2_X1_0_Weights.verify(weights)
  281. return _shufflenetv2(weights, progress, [4, 8, 4], [24, 116, 232, 464, 1024], **kwargs)
  282. @handle_legacy_interface(weights=("pretrained", ShuffleNet_V2_X1_5_Weights.IMAGENET1K_V1))
  283. def shufflenet_v2_x1_5(
  284. *, weights: Optional[ShuffleNet_V2_X1_5_Weights] = None, progress: bool = True, **kwargs: Any
  285. ) -> ShuffleNetV2:
  286. """
  287. Constructs a ShuffleNetV2 architecture with 1.5x output channels, as described in
  288. `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design
  289. <https://arxiv.org/abs/1807.11164>`__.
  290. Args:
  291. weights (:class:`~torchvision.models.ShuffleNet_V2_X1_5_Weights`, optional): The
  292. pretrained weights to use. See
  293. :class:`~torchvision.models.ShuffleNet_V2_X1_5_Weights` below for
  294. more details, and possible values. By default, no pre-trained
  295. weights are used.
  296. progress (bool, optional): If True, displays a progress bar of the
  297. download to stderr. Default is True.
  298. **kwargs: parameters passed to the ``torchvision.models.shufflenetv2.ShuffleNetV2``
  299. base class. Please refer to the `source code
  300. <https://github.com/pytorch/vision/blob/main/torchvision/models/shufflenetv2.py>`_
  301. for more details about this class.
  302. .. autoclass:: torchvision.models.ShuffleNet_V2_X1_5_Weights
  303. :members:
  304. """
  305. weights = ShuffleNet_V2_X1_5_Weights.verify(weights)
  306. return _shufflenetv2(weights, progress, [4, 8, 4], [24, 176, 352, 704, 1024], **kwargs)
  307. @handle_legacy_interface(weights=("pretrained", ShuffleNet_V2_X2_0_Weights.IMAGENET1K_V1))
  308. def shufflenet_v2_x2_0(
  309. *, weights: Optional[ShuffleNet_V2_X2_0_Weights] = None, progress: bool = True, **kwargs: Any
  310. ) -> ShuffleNetV2:
  311. """
  312. Constructs a ShuffleNetV2 architecture with 2.0x output channels, as described in
  313. `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design
  314. <https://arxiv.org/abs/1807.11164>`__.
  315. Args:
  316. weights (:class:`~torchvision.models.ShuffleNet_V2_X2_0_Weights`, optional): The
  317. pretrained weights to use. See
  318. :class:`~torchvision.models.ShuffleNet_V2_X2_0_Weights` below for
  319. more details, and possible values. By default, no pre-trained
  320. weights are used.
  321. progress (bool, optional): If True, displays a progress bar of the
  322. download to stderr. Default is True.
  323. **kwargs: parameters passed to the ``torchvision.models.shufflenetv2.ShuffleNetV2``
  324. base class. Please refer to the `source code
  325. <https://github.com/pytorch/vision/blob/main/torchvision/models/shufflenetv2.py>`_
  326. for more details about this class.
  327. .. autoclass:: torchvision.models.ShuffleNet_V2_X2_0_Weights
  328. :members:
  329. """
  330. weights = ShuffleNet_V2_X2_0_Weights.verify(weights)
  331. return _shufflenetv2(weights, progress, [4, 8, 4], [24, 244, 488, 976, 2048], **kwargs)
  332. # The dictionary below is internal implementation detail and will be removed in v0.15
  333. from ._utils import _ModelURLs
  334. model_urls = _ModelURLs(
  335. {
  336. "shufflenetv2_x0.5": ShuffleNet_V2_X0_5_Weights.IMAGENET1K_V1.url,
  337. "shufflenetv2_x1.0": ShuffleNet_V2_X1_0_Weights.IMAGENET1K_V1.url,
  338. "shufflenetv2_x1.5": None,
  339. "shufflenetv2_x2.0": None,
  340. }
  341. )