mobilenetv2.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. from functools import partial
  2. from typing import Any, Optional, Union
  3. from torch import nn, Tensor
  4. from torch.ao.quantization import DeQuantStub, QuantStub
  5. from torchvision.models.mobilenetv2 import InvertedResidual, MobileNet_V2_Weights, MobileNetV2
  6. from ...ops.misc import Conv2dNormActivation
  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 .utils import _fuse_modules, _replace_relu, quantize_model
  12. __all__ = [
  13. "QuantizableMobileNetV2",
  14. "MobileNet_V2_QuantizedWeights",
  15. "mobilenet_v2",
  16. ]
  17. class QuantizableInvertedResidual(InvertedResidual):
  18. def __init__(self, *args: Any, **kwargs: Any) -> None:
  19. super().__init__(*args, **kwargs)
  20. self.skip_add = nn.quantized.FloatFunctional()
  21. def forward(self, x: Tensor) -> Tensor:
  22. if self.use_res_connect:
  23. return self.skip_add.add(x, self.conv(x))
  24. else:
  25. return self.conv(x)
  26. def fuse_model(self, is_qat: Optional[bool] = None) -> None:
  27. for idx in range(len(self.conv)):
  28. if type(self.conv[idx]) is nn.Conv2d:
  29. _fuse_modules(self.conv, [str(idx), str(idx + 1)], is_qat, inplace=True)
  30. class QuantizableMobileNetV2(MobileNetV2):
  31. def __init__(self, *args: Any, **kwargs: Any) -> None:
  32. """
  33. MobileNet V2 main class
  34. Args:
  35. Inherits args from floating point MobileNetV2
  36. """
  37. super().__init__(*args, **kwargs)
  38. self.quant = QuantStub()
  39. self.dequant = DeQuantStub()
  40. def forward(self, x: Tensor) -> Tensor:
  41. x = self.quant(x)
  42. x = self._forward_impl(x)
  43. x = self.dequant(x)
  44. return x
  45. def fuse_model(self, is_qat: Optional[bool] = None) -> None:
  46. for m in self.modules():
  47. if type(m) is Conv2dNormActivation:
  48. _fuse_modules(m, ["0", "1", "2"], is_qat, inplace=True)
  49. if type(m) is QuantizableInvertedResidual:
  50. m.fuse_model(is_qat)
  51. class MobileNet_V2_QuantizedWeights(WeightsEnum):
  52. IMAGENET1K_QNNPACK_V1 = Weights(
  53. url="https://download.pytorch.org/models/quantized/mobilenet_v2_qnnpack_37f702c5.pth",
  54. transforms=partial(ImageClassification, crop_size=224),
  55. meta={
  56. "num_params": 3504872,
  57. "min_size": (1, 1),
  58. "categories": _IMAGENET_CATEGORIES,
  59. "backend": "qnnpack",
  60. "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#qat-mobilenetv2",
  61. "unquantized": MobileNet_V2_Weights.IMAGENET1K_V1,
  62. "_metrics": {
  63. "ImageNet-1K": {
  64. "acc@1": 71.658,
  65. "acc@5": 90.150,
  66. }
  67. },
  68. "_ops": 0.301,
  69. "_file_size": 3.423,
  70. "_docs": """
  71. These weights were produced by doing Quantization Aware Training (eager mode) on top of the unquantized
  72. weights listed below.
  73. """,
  74. },
  75. )
  76. DEFAULT = IMAGENET1K_QNNPACK_V1
  77. @register_model(name="quantized_mobilenet_v2")
  78. @handle_legacy_interface(
  79. weights=(
  80. "pretrained",
  81. lambda kwargs: (
  82. MobileNet_V2_QuantizedWeights.IMAGENET1K_QNNPACK_V1
  83. if kwargs.get("quantize", False)
  84. else MobileNet_V2_Weights.IMAGENET1K_V1
  85. ),
  86. )
  87. )
  88. def mobilenet_v2(
  89. *,
  90. weights: Optional[Union[MobileNet_V2_QuantizedWeights, MobileNet_V2_Weights]] = None,
  91. progress: bool = True,
  92. quantize: bool = False,
  93. **kwargs: Any,
  94. ) -> QuantizableMobileNetV2:
  95. """
  96. Constructs a MobileNetV2 architecture from
  97. `MobileNetV2: Inverted Residuals and Linear Bottlenecks
  98. <https://arxiv.org/abs/1801.04381>`_.
  99. .. note::
  100. Note that ``quantize = True`` returns a quantized model with 8 bit
  101. weights. Quantized models only support inference and run on CPUs.
  102. GPU inference is not yet supported.
  103. Args:
  104. weights (:class:`~torchvision.models.quantization.MobileNet_V2_QuantizedWeights` or :class:`~torchvision.models.MobileNet_V2_Weights`, optional): The
  105. pretrained weights for the model. See
  106. :class:`~torchvision.models.quantization.MobileNet_V2_QuantizedWeights` below for
  107. more details, and possible values. By default, no pre-trained
  108. weights are used.
  109. progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True.
  110. quantize (bool, optional): If True, returns a quantized version of the model. Default is False.
  111. **kwargs: parameters passed to the ``torchvision.models.quantization.QuantizableMobileNetV2``
  112. base class. Please refer to the `source code
  113. <https://github.com/pytorch/vision/blob/main/torchvision/models/quantization/mobilenetv2.py>`_
  114. for more details about this class.
  115. .. autoclass:: torchvision.models.quantization.MobileNet_V2_QuantizedWeights
  116. :members:
  117. .. autoclass:: torchvision.models.MobileNet_V2_Weights
  118. :members:
  119. :noindex:
  120. """
  121. weights = (MobileNet_V2_QuantizedWeights if quantize else MobileNet_V2_Weights).verify(weights)
  122. if weights is not None:
  123. _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"]))
  124. if "backend" in weights.meta:
  125. _ovewrite_named_param(kwargs, "backend", weights.meta["backend"])
  126. backend = kwargs.pop("backend", "qnnpack")
  127. model = QuantizableMobileNetV2(block=QuantizableInvertedResidual, **kwargs)
  128. _replace_relu(model)
  129. if quantize:
  130. quantize_model(model, backend)
  131. if weights is not None:
  132. model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
  133. return model