shufflenetv2.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. from functools import partial
  2. from typing import Any, Optional, Union
  3. import torch
  4. import torch.nn as nn
  5. from torch import Tensor
  6. from torchvision.models import shufflenetv2
  7. from ...transforms._presets import ImageClassification
  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. from ..shufflenetv2 import (
  12. ShuffleNet_V2_X0_5_Weights,
  13. ShuffleNet_V2_X1_0_Weights,
  14. ShuffleNet_V2_X1_5_Weights,
  15. ShuffleNet_V2_X2_0_Weights,
  16. )
  17. from .utils import _fuse_modules, _replace_relu, quantize_model
  18. __all__ = [
  19. "QuantizableShuffleNetV2",
  20. "ShuffleNet_V2_X0_5_QuantizedWeights",
  21. "ShuffleNet_V2_X1_0_QuantizedWeights",
  22. "ShuffleNet_V2_X1_5_QuantizedWeights",
  23. "ShuffleNet_V2_X2_0_QuantizedWeights",
  24. "shufflenet_v2_x0_5",
  25. "shufflenet_v2_x1_0",
  26. "shufflenet_v2_x1_5",
  27. "shufflenet_v2_x2_0",
  28. ]
  29. class QuantizableInvertedResidual(shufflenetv2.InvertedResidual):
  30. def __init__(self, *args: Any, **kwargs: Any) -> None:
  31. super().__init__(*args, **kwargs)
  32. self.cat = nn.quantized.FloatFunctional()
  33. def forward(self, x: Tensor) -> Tensor:
  34. if self.stride == 1:
  35. x1, x2 = x.chunk(2, dim=1)
  36. out = self.cat.cat([x1, self.branch2(x2)], dim=1)
  37. else:
  38. out = self.cat.cat([self.branch1(x), self.branch2(x)], dim=1)
  39. out = shufflenetv2.channel_shuffle(out, 2)
  40. return out
  41. class QuantizableShuffleNetV2(shufflenetv2.ShuffleNetV2):
  42. # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659
  43. def __init__(self, *args: Any, **kwargs: Any) -> None:
  44. super().__init__(*args, inverted_residual=QuantizableInvertedResidual, **kwargs) # type: ignore[misc]
  45. self.quant = torch.ao.quantization.QuantStub()
  46. self.dequant = torch.ao.quantization.DeQuantStub()
  47. def forward(self, x: Tensor) -> Tensor:
  48. x = self.quant(x)
  49. x = self._forward_impl(x)
  50. x = self.dequant(x)
  51. return x
  52. def fuse_model(self, is_qat: Optional[bool] = None) -> None:
  53. r"""Fuse conv/bn/relu modules in shufflenetv2 model
  54. Fuse conv+bn+relu/ conv+relu/conv+bn modules to prepare for quantization.
  55. Model is modified in place.
  56. .. note::
  57. Note that this operation does not change numerics
  58. and the model after modification is in floating point
  59. """
  60. for name, m in self._modules.items():
  61. if name in ["conv1", "conv5"] and m is not None:
  62. _fuse_modules(m, [["0", "1", "2"]], is_qat, inplace=True)
  63. for m in self.modules():
  64. if type(m) is QuantizableInvertedResidual:
  65. if len(m.branch1._modules.items()) > 0:
  66. _fuse_modules(m.branch1, [["0", "1"], ["2", "3", "4"]], is_qat, inplace=True)
  67. _fuse_modules(
  68. m.branch2,
  69. [["0", "1", "2"], ["3", "4"], ["5", "6", "7"]],
  70. is_qat,
  71. inplace=True,
  72. )
  73. def _shufflenetv2(
  74. stages_repeats: list[int],
  75. stages_out_channels: list[int],
  76. *,
  77. weights: Optional[WeightsEnum],
  78. progress: bool,
  79. quantize: bool,
  80. **kwargs: Any,
  81. ) -> QuantizableShuffleNetV2:
  82. if weights is not None:
  83. _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"]))
  84. if "backend" in weights.meta:
  85. _ovewrite_named_param(kwargs, "backend", weights.meta["backend"])
  86. backend = kwargs.pop("backend", "fbgemm")
  87. model = QuantizableShuffleNetV2(stages_repeats, stages_out_channels, **kwargs)
  88. _replace_relu(model)
  89. if quantize:
  90. quantize_model(model, backend)
  91. if weights is not None:
  92. model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
  93. return model
  94. _COMMON_META = {
  95. "min_size": (1, 1),
  96. "categories": _IMAGENET_CATEGORIES,
  97. "backend": "fbgemm",
  98. "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#post-training-quantized-models",
  99. "_docs": """
  100. These weights were produced by doing Post Training Quantization (eager mode) on top of the unquantized
  101. weights listed below.
  102. """,
  103. }
  104. class ShuffleNet_V2_X0_5_QuantizedWeights(WeightsEnum):
  105. IMAGENET1K_FBGEMM_V1 = Weights(
  106. url="https://download.pytorch.org/models/quantized/shufflenetv2_x0.5_fbgemm-00845098.pth",
  107. transforms=partial(ImageClassification, crop_size=224),
  108. meta={
  109. **_COMMON_META,
  110. "num_params": 1366792,
  111. "unquantized": ShuffleNet_V2_X0_5_Weights.IMAGENET1K_V1,
  112. "_metrics": {
  113. "ImageNet-1K": {
  114. "acc@1": 57.972,
  115. "acc@5": 79.780,
  116. }
  117. },
  118. "_ops": 0.04,
  119. "_file_size": 1.501,
  120. },
  121. )
  122. DEFAULT = IMAGENET1K_FBGEMM_V1
  123. class ShuffleNet_V2_X1_0_QuantizedWeights(WeightsEnum):
  124. IMAGENET1K_FBGEMM_V1 = Weights(
  125. url="https://download.pytorch.org/models/quantized/shufflenetv2_x1_fbgemm-1e62bb32.pth",
  126. transforms=partial(ImageClassification, crop_size=224),
  127. meta={
  128. **_COMMON_META,
  129. "num_params": 2278604,
  130. "unquantized": ShuffleNet_V2_X1_0_Weights.IMAGENET1K_V1,
  131. "_metrics": {
  132. "ImageNet-1K": {
  133. "acc@1": 68.360,
  134. "acc@5": 87.582,
  135. }
  136. },
  137. "_ops": 0.145,
  138. "_file_size": 2.334,
  139. },
  140. )
  141. DEFAULT = IMAGENET1K_FBGEMM_V1
  142. class ShuffleNet_V2_X1_5_QuantizedWeights(WeightsEnum):
  143. IMAGENET1K_FBGEMM_V1 = Weights(
  144. url="https://download.pytorch.org/models/quantized/shufflenetv2_x1_5_fbgemm-d7401f05.pth",
  145. transforms=partial(ImageClassification, crop_size=224, resize_size=232),
  146. meta={
  147. **_COMMON_META,
  148. "recipe": "https://github.com/pytorch/vision/pull/5906",
  149. "num_params": 3503624,
  150. "unquantized": ShuffleNet_V2_X1_5_Weights.IMAGENET1K_V1,
  151. "_metrics": {
  152. "ImageNet-1K": {
  153. "acc@1": 72.052,
  154. "acc@5": 90.700,
  155. }
  156. },
  157. "_ops": 0.296,
  158. "_file_size": 3.672,
  159. },
  160. )
  161. DEFAULT = IMAGENET1K_FBGEMM_V1
  162. class ShuffleNet_V2_X2_0_QuantizedWeights(WeightsEnum):
  163. IMAGENET1K_FBGEMM_V1 = Weights(
  164. url="https://download.pytorch.org/models/quantized/shufflenetv2_x2_0_fbgemm-5cac526c.pth",
  165. transforms=partial(ImageClassification, crop_size=224, resize_size=232),
  166. meta={
  167. **_COMMON_META,
  168. "recipe": "https://github.com/pytorch/vision/pull/5906",
  169. "num_params": 7393996,
  170. "unquantized": ShuffleNet_V2_X2_0_Weights.IMAGENET1K_V1,
  171. "_metrics": {
  172. "ImageNet-1K": {
  173. "acc@1": 75.354,
  174. "acc@5": 92.488,
  175. }
  176. },
  177. "_ops": 0.583,
  178. "_file_size": 7.467,
  179. },
  180. )
  181. DEFAULT = IMAGENET1K_FBGEMM_V1
  182. @register_model(name="quantized_shufflenet_v2_x0_5")
  183. @handle_legacy_interface(
  184. weights=(
  185. "pretrained",
  186. lambda kwargs: (
  187. ShuffleNet_V2_X0_5_QuantizedWeights.IMAGENET1K_FBGEMM_V1
  188. if kwargs.get("quantize", False)
  189. else ShuffleNet_V2_X0_5_Weights.IMAGENET1K_V1
  190. ),
  191. )
  192. )
  193. def shufflenet_v2_x0_5(
  194. *,
  195. weights: Optional[Union[ShuffleNet_V2_X0_5_QuantizedWeights, ShuffleNet_V2_X0_5_Weights]] = None,
  196. progress: bool = True,
  197. quantize: bool = False,
  198. **kwargs: Any,
  199. ) -> QuantizableShuffleNetV2:
  200. """
  201. Constructs a ShuffleNetV2 with 0.5x output channels, as described in
  202. `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design
  203. <https://arxiv.org/abs/1807.11164>`__.
  204. .. note::
  205. Note that ``quantize = True`` returns a quantized model with 8 bit
  206. weights. Quantized models only support inference and run on CPUs.
  207. GPU inference is not yet supported.
  208. Args:
  209. weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X0_5_Weights`, optional): The
  210. pretrained weights for the model. See
  211. :class:`~torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights` below for
  212. more details, and possible values. By default, no pre-trained
  213. weights are used.
  214. progress (bool, optional): If True, displays a progress bar of the download to stderr.
  215. Default is True.
  216. quantize (bool, optional): If True, return a quantized version of the model.
  217. Default is False.
  218. **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights``
  219. base class. Please refer to the `source code
  220. <https://github.com/pytorch/vision/blob/main/torchvision/models/quantization/shufflenetv2.py>`_
  221. for more details about this class.
  222. .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights
  223. :members:
  224. .. autoclass:: torchvision.models.ShuffleNet_V2_X0_5_Weights
  225. :members:
  226. :noindex:
  227. """
  228. weights = (ShuffleNet_V2_X0_5_QuantizedWeights if quantize else ShuffleNet_V2_X0_5_Weights).verify(weights)
  229. return _shufflenetv2(
  230. [4, 8, 4], [24, 48, 96, 192, 1024], weights=weights, progress=progress, quantize=quantize, **kwargs
  231. )
  232. @register_model(name="quantized_shufflenet_v2_x1_0")
  233. @handle_legacy_interface(
  234. weights=(
  235. "pretrained",
  236. lambda kwargs: (
  237. ShuffleNet_V2_X1_0_QuantizedWeights.IMAGENET1K_FBGEMM_V1
  238. if kwargs.get("quantize", False)
  239. else ShuffleNet_V2_X1_0_Weights.IMAGENET1K_V1
  240. ),
  241. )
  242. )
  243. def shufflenet_v2_x1_0(
  244. *,
  245. weights: Optional[Union[ShuffleNet_V2_X1_0_QuantizedWeights, ShuffleNet_V2_X1_0_Weights]] = None,
  246. progress: bool = True,
  247. quantize: bool = False,
  248. **kwargs: Any,
  249. ) -> QuantizableShuffleNetV2:
  250. """
  251. Constructs a ShuffleNetV2 with 1.0x output channels, as described in
  252. `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design
  253. <https://arxiv.org/abs/1807.11164>`__.
  254. .. note::
  255. Note that ``quantize = True`` returns a quantized model with 8 bit
  256. weights. Quantized models only support inference and run on CPUs.
  257. GPU inference is not yet supported.
  258. Args:
  259. weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X1_0_Weights`, optional): The
  260. pretrained weights for the model. See
  261. :class:`~torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights` below for
  262. more details, and possible values. By default, no pre-trained
  263. weights are used.
  264. progress (bool, optional): If True, displays a progress bar of the download to stderr.
  265. Default is True.
  266. quantize (bool, optional): If True, return a quantized version of the model.
  267. Default is False.
  268. **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights``
  269. base class. Please refer to the `source code
  270. <https://github.com/pytorch/vision/blob/main/torchvision/models/quantization/shufflenetv2.py>`_
  271. for more details about this class.
  272. .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights
  273. :members:
  274. .. autoclass:: torchvision.models.ShuffleNet_V2_X1_0_Weights
  275. :members:
  276. :noindex:
  277. """
  278. weights = (ShuffleNet_V2_X1_0_QuantizedWeights if quantize else ShuffleNet_V2_X1_0_Weights).verify(weights)
  279. return _shufflenetv2(
  280. [4, 8, 4], [24, 116, 232, 464, 1024], weights=weights, progress=progress, quantize=quantize, **kwargs
  281. )
  282. @register_model(name="quantized_shufflenet_v2_x1_5")
  283. @handle_legacy_interface(
  284. weights=(
  285. "pretrained",
  286. lambda kwargs: (
  287. ShuffleNet_V2_X1_5_QuantizedWeights.IMAGENET1K_FBGEMM_V1
  288. if kwargs.get("quantize", False)
  289. else ShuffleNet_V2_X1_5_Weights.IMAGENET1K_V1
  290. ),
  291. )
  292. )
  293. def shufflenet_v2_x1_5(
  294. *,
  295. weights: Optional[Union[ShuffleNet_V2_X1_5_QuantizedWeights, ShuffleNet_V2_X1_5_Weights]] = None,
  296. progress: bool = True,
  297. quantize: bool = False,
  298. **kwargs: Any,
  299. ) -> QuantizableShuffleNetV2:
  300. """
  301. Constructs a ShuffleNetV2 with 1.5x output channels, as described in
  302. `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design
  303. <https://arxiv.org/abs/1807.11164>`__.
  304. .. note::
  305. Note that ``quantize = True`` returns a quantized model with 8 bit
  306. weights. Quantized models only support inference and run on CPUs.
  307. GPU inference is not yet supported.
  308. Args:
  309. weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X1_5_Weights`, optional): The
  310. pretrained weights for the model. See
  311. :class:`~torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights` below for
  312. more details, and possible values. By default, no pre-trained
  313. weights are used.
  314. progress (bool, optional): If True, displays a progress bar of the download to stderr.
  315. Default is True.
  316. quantize (bool, optional): If True, return a quantized version of the model.
  317. Default is False.
  318. **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights``
  319. base class. Please refer to the `source code
  320. <https://github.com/pytorch/vision/blob/main/torchvision/models/quantization/shufflenetv2.py>`_
  321. for more details about this class.
  322. .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights
  323. :members:
  324. .. autoclass:: torchvision.models.ShuffleNet_V2_X1_5_Weights
  325. :members:
  326. :noindex:
  327. """
  328. weights = (ShuffleNet_V2_X1_5_QuantizedWeights if quantize else ShuffleNet_V2_X1_5_Weights).verify(weights)
  329. return _shufflenetv2(
  330. [4, 8, 4], [24, 176, 352, 704, 1024], weights=weights, progress=progress, quantize=quantize, **kwargs
  331. )
  332. @register_model(name="quantized_shufflenet_v2_x2_0")
  333. @handle_legacy_interface(
  334. weights=(
  335. "pretrained",
  336. lambda kwargs: (
  337. ShuffleNet_V2_X2_0_QuantizedWeights.IMAGENET1K_FBGEMM_V1
  338. if kwargs.get("quantize", False)
  339. else ShuffleNet_V2_X2_0_Weights.IMAGENET1K_V1
  340. ),
  341. )
  342. )
  343. def shufflenet_v2_x2_0(
  344. *,
  345. weights: Optional[Union[ShuffleNet_V2_X2_0_QuantizedWeights, ShuffleNet_V2_X2_0_Weights]] = None,
  346. progress: bool = True,
  347. quantize: bool = False,
  348. **kwargs: Any,
  349. ) -> QuantizableShuffleNetV2:
  350. """
  351. Constructs a ShuffleNetV2 with 2.0x output channels, as described in
  352. `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design
  353. <https://arxiv.org/abs/1807.11164>`__.
  354. .. note::
  355. Note that ``quantize = True`` returns a quantized model with 8 bit
  356. weights. Quantized models only support inference and run on CPUs.
  357. GPU inference is not yet supported.
  358. Args:
  359. weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X2_0_Weights`, optional): The
  360. pretrained weights for the model. See
  361. :class:`~torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights` below for
  362. more details, and possible values. By default, no pre-trained
  363. weights are used.
  364. progress (bool, optional): If True, displays a progress bar of the download to stderr.
  365. Default is True.
  366. quantize (bool, optional): If True, return a quantized version of the model.
  367. Default is False.
  368. **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights``
  369. base class. Please refer to the `source code
  370. <https://github.com/pytorch/vision/blob/main/torchvision/models/quantization/shufflenetv2.py>`_
  371. for more details about this class.
  372. .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights
  373. :members:
  374. .. autoclass:: torchvision.models.ShuffleNet_V2_X2_0_Weights
  375. :members:
  376. :noindex:
  377. """
  378. weights = (ShuffleNet_V2_X2_0_QuantizedWeights if quantize else ShuffleNet_V2_X2_0_Weights).verify(weights)
  379. return _shufflenetv2(
  380. [4, 8, 4], [24, 244, 488, 976, 2048], weights=weights, progress=progress, quantize=quantize, **kwargs
  381. )