shufflenetv2.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. from functools import partial
  2. from typing import Any, List, 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 WeightsEnum, Weights
  9. from .._meta import _IMAGENET_CATEGORIES
  10. from .._utils import handle_legacy_interface, _ovewrite_named_param
  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))
  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. },
  119. )
  120. DEFAULT = IMAGENET1K_FBGEMM_V1
  121. class ShuffleNet_V2_X1_0_QuantizedWeights(WeightsEnum):
  122. IMAGENET1K_FBGEMM_V1 = Weights(
  123. url="https://download.pytorch.org/models/quantized/shufflenetv2_x1_fbgemm-db332c57.pth",
  124. transforms=partial(ImageClassification, crop_size=224),
  125. meta={
  126. **_COMMON_META,
  127. "num_params": 2278604,
  128. "unquantized": ShuffleNet_V2_X1_0_Weights.IMAGENET1K_V1,
  129. "_metrics": {
  130. "ImageNet-1K": {
  131. "acc@1": 68.360,
  132. "acc@5": 87.582,
  133. }
  134. },
  135. },
  136. )
  137. DEFAULT = IMAGENET1K_FBGEMM_V1
  138. class ShuffleNet_V2_X1_5_QuantizedWeights(WeightsEnum):
  139. IMAGENET1K_FBGEMM_V1 = Weights(
  140. url="https://download.pytorch.org/models/quantized/shufflenetv2_x1_5_fbgemm-d7401f05.pth",
  141. transforms=partial(ImageClassification, crop_size=224, resize_size=232),
  142. meta={
  143. **_COMMON_META,
  144. "recipe": "https://github.com/pytorch/vision/pull/5906",
  145. "num_params": 3503624,
  146. "unquantized": ShuffleNet_V2_X1_5_Weights.IMAGENET1K_V1,
  147. "_metrics": {
  148. "ImageNet-1K": {
  149. "acc@1": 72.052,
  150. "acc@5": 90.700,
  151. }
  152. },
  153. },
  154. )
  155. DEFAULT = IMAGENET1K_FBGEMM_V1
  156. class ShuffleNet_V2_X2_0_QuantizedWeights(WeightsEnum):
  157. IMAGENET1K_FBGEMM_V1 = Weights(
  158. url="https://download.pytorch.org/models/quantized/shufflenetv2_x2_0_fbgemm-5cac526c.pth",
  159. transforms=partial(ImageClassification, crop_size=224, resize_size=232),
  160. meta={
  161. **_COMMON_META,
  162. "recipe": "https://github.com/pytorch/vision/pull/5906",
  163. "num_params": 7393996,
  164. "unquantized": ShuffleNet_V2_X2_0_Weights.IMAGENET1K_V1,
  165. "_metrics": {
  166. "ImageNet-1K": {
  167. "acc@1": 75.354,
  168. "acc@5": 92.488,
  169. }
  170. },
  171. },
  172. )
  173. DEFAULT = IMAGENET1K_FBGEMM_V1
  174. @handle_legacy_interface(
  175. weights=(
  176. "pretrained",
  177. lambda kwargs: ShuffleNet_V2_X0_5_QuantizedWeights.IMAGENET1K_FBGEMM_V1
  178. if kwargs.get("quantize", False)
  179. else ShuffleNet_V2_X0_5_Weights.IMAGENET1K_V1,
  180. )
  181. )
  182. def shufflenet_v2_x0_5(
  183. *,
  184. weights: Optional[Union[ShuffleNet_V2_X0_5_QuantizedWeights, ShuffleNet_V2_X0_5_Weights]] = None,
  185. progress: bool = True,
  186. quantize: bool = False,
  187. **kwargs: Any,
  188. ) -> QuantizableShuffleNetV2:
  189. """
  190. Constructs a ShuffleNetV2 with 0.5x output channels, as described in
  191. `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design
  192. <https://arxiv.org/abs/1807.11164>`__.
  193. .. note::
  194. Note that ``quantize = True`` returns a quantized model with 8 bit
  195. weights. Quantized models only support inference and run on CPUs.
  196. GPU inference is not yet supported.
  197. Args:
  198. weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X0_5_Weights`, optional): The
  199. pretrained weights for the model. See
  200. :class:`~torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights` below for
  201. more details, and possible values. By default, no pre-trained
  202. weights are used.
  203. progress (bool, optional): If True, displays a progress bar of the download to stderr.
  204. Default is True.
  205. quantize (bool, optional): If True, return a quantized version of the model.
  206. Default is False.
  207. **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights``
  208. base class. Please refer to the `source code
  209. <https://github.com/pytorch/vision/blob/main/torchvision/models/quantization/shufflenetv2.py>`_
  210. for more details about this class.
  211. .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights
  212. :members:
  213. .. autoclass:: torchvision.models.ShuffleNet_V2_X0_5_Weights
  214. :members:
  215. :noindex:
  216. """
  217. weights = (ShuffleNet_V2_X0_5_QuantizedWeights if quantize else ShuffleNet_V2_X0_5_Weights).verify(weights)
  218. return _shufflenetv2(
  219. [4, 8, 4], [24, 48, 96, 192, 1024], weights=weights, progress=progress, quantize=quantize, **kwargs
  220. )
  221. @handle_legacy_interface(
  222. weights=(
  223. "pretrained",
  224. lambda kwargs: ShuffleNet_V2_X1_0_QuantizedWeights.IMAGENET1K_FBGEMM_V1
  225. if kwargs.get("quantize", False)
  226. else ShuffleNet_V2_X1_0_Weights.IMAGENET1K_V1,
  227. )
  228. )
  229. def shufflenet_v2_x1_0(
  230. *,
  231. weights: Optional[Union[ShuffleNet_V2_X1_0_QuantizedWeights, ShuffleNet_V2_X1_0_Weights]] = None,
  232. progress: bool = True,
  233. quantize: bool = False,
  234. **kwargs: Any,
  235. ) -> QuantizableShuffleNetV2:
  236. """
  237. Constructs a ShuffleNetV2 with 1.0x output channels, as described in
  238. `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design
  239. <https://arxiv.org/abs/1807.11164>`__.
  240. .. note::
  241. Note that ``quantize = True`` returns a quantized model with 8 bit
  242. weights. Quantized models only support inference and run on CPUs.
  243. GPU inference is not yet supported.
  244. Args:
  245. weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X1_0_Weights`, optional): The
  246. pretrained weights for the model. See
  247. :class:`~torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights` below for
  248. more details, and possible values. By default, no pre-trained
  249. weights are used.
  250. progress (bool, optional): If True, displays a progress bar of the download to stderr.
  251. Default is True.
  252. quantize (bool, optional): If True, return a quantized version of the model.
  253. Default is False.
  254. **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights``
  255. base class. Please refer to the `source code
  256. <https://github.com/pytorch/vision/blob/main/torchvision/models/quantization/shufflenetv2.py>`_
  257. for more details about this class.
  258. .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights
  259. :members:
  260. .. autoclass:: torchvision.models.ShuffleNet_V2_X1_0_Weights
  261. :members:
  262. :noindex:
  263. """
  264. weights = (ShuffleNet_V2_X1_0_QuantizedWeights if quantize else ShuffleNet_V2_X1_0_Weights).verify(weights)
  265. return _shufflenetv2(
  266. [4, 8, 4], [24, 116, 232, 464, 1024], weights=weights, progress=progress, quantize=quantize, **kwargs
  267. )
  268. def shufflenet_v2_x1_5(
  269. *,
  270. weights: Optional[Union[ShuffleNet_V2_X1_5_QuantizedWeights, ShuffleNet_V2_X1_5_Weights]] = None,
  271. progress: bool = True,
  272. quantize: bool = False,
  273. **kwargs: Any,
  274. ) -> QuantizableShuffleNetV2:
  275. """
  276. Constructs a ShuffleNetV2 with 1.5x output channels, as described in
  277. `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design
  278. <https://arxiv.org/abs/1807.11164>`__.
  279. .. note::
  280. Note that ``quantize = True`` returns a quantized model with 8 bit
  281. weights. Quantized models only support inference and run on CPUs.
  282. GPU inference is not yet supported.
  283. Args:
  284. weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X1_5_Weights`, optional): The
  285. pretrained weights for the model. See
  286. :class:`~torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights` below for
  287. more details, and possible values. By default, no pre-trained
  288. weights are used.
  289. progress (bool, optional): If True, displays a progress bar of the download to stderr.
  290. Default is True.
  291. quantize (bool, optional): If True, return a quantized version of the model.
  292. Default is False.
  293. **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights``
  294. base class. Please refer to the `source code
  295. <https://github.com/pytorch/vision/blob/main/torchvision/models/quantization/shufflenetv2.py>`_
  296. for more details about this class.
  297. .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights
  298. :members:
  299. .. autoclass:: torchvision.models.ShuffleNet_V2_X1_5_Weights
  300. :members:
  301. :noindex:
  302. """
  303. weights = (ShuffleNet_V2_X1_5_QuantizedWeights if quantize else ShuffleNet_V2_X1_5_Weights).verify(weights)
  304. return _shufflenetv2(
  305. [4, 8, 4], [24, 176, 352, 704, 1024], weights=weights, progress=progress, quantize=quantize, **kwargs
  306. )
  307. def shufflenet_v2_x2_0(
  308. *,
  309. weights: Optional[Union[ShuffleNet_V2_X2_0_QuantizedWeights, ShuffleNet_V2_X2_0_Weights]] = None,
  310. progress: bool = True,
  311. quantize: bool = False,
  312. **kwargs: Any,
  313. ) -> QuantizableShuffleNetV2:
  314. """
  315. Constructs a ShuffleNetV2 with 2.0x output channels, as described in
  316. `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design
  317. <https://arxiv.org/abs/1807.11164>`__.
  318. .. note::
  319. Note that ``quantize = True`` returns a quantized model with 8 bit
  320. weights. Quantized models only support inference and run on CPUs.
  321. GPU inference is not yet supported.
  322. Args:
  323. weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X2_0_Weights`, optional): The
  324. pretrained weights for the model. See
  325. :class:`~torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights` below for
  326. more details, and possible values. By default, no pre-trained
  327. weights are used.
  328. progress (bool, optional): If True, displays a progress bar of the download to stderr.
  329. Default is True.
  330. quantize (bool, optional): If True, return a quantized version of the model.
  331. Default is False.
  332. **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights``
  333. base class. Please refer to the `source code
  334. <https://github.com/pytorch/vision/blob/main/torchvision/models/quantization/shufflenetv2.py>`_
  335. for more details about this class.
  336. .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights
  337. :members:
  338. .. autoclass:: torchvision.models.ShuffleNet_V2_X2_0_Weights
  339. :members:
  340. :noindex:
  341. """
  342. weights = (ShuffleNet_V2_X2_0_QuantizedWeights if quantize else ShuffleNet_V2_X2_0_Weights).verify(weights)
  343. return _shufflenetv2(
  344. [4, 8, 4], [24, 244, 488, 976, 2048], weights=weights, progress=progress, quantize=quantize, **kwargs
  345. )
  346. # The dictionary below is internal implementation detail and will be removed in v0.15
  347. from .._utils import _ModelURLs
  348. from ..shufflenetv2 import model_urls # noqa: F401
  349. quant_model_urls = _ModelURLs(
  350. {
  351. "shufflenetv2_x0.5_fbgemm": ShuffleNet_V2_X0_5_QuantizedWeights.IMAGENET1K_FBGEMM_V1.url,
  352. "shufflenetv2_x1.0_fbgemm": ShuffleNet_V2_X1_0_QuantizedWeights.IMAGENET1K_FBGEMM_V1.url,
  353. }
  354. )