mobilenetv2.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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: MobileNet_V2_QuantizedWeights.IMAGENET1K_QNNPACK_V1
  82. if kwargs.get("quantize", False)
  83. else MobileNet_V2_Weights.IMAGENET1K_V1,
  84. )
  85. )
  86. def mobilenet_v2(
  87. *,
  88. weights: Optional[Union[MobileNet_V2_QuantizedWeights, MobileNet_V2_Weights]] = None,
  89. progress: bool = True,
  90. quantize: bool = False,
  91. **kwargs: Any,
  92. ) -> QuantizableMobileNetV2:
  93. """
  94. Constructs a MobileNetV2 architecture from
  95. `MobileNetV2: Inverted Residuals and Linear Bottlenecks
  96. <https://arxiv.org/abs/1801.04381>`_.
  97. .. note::
  98. Note that ``quantize = True`` returns a quantized model with 8 bit
  99. weights. Quantized models only support inference and run on CPUs.
  100. GPU inference is not yet supported.
  101. Args:
  102. weights (:class:`~torchvision.models.quantization.MobileNet_V2_QuantizedWeights` or :class:`~torchvision.models.MobileNet_V2_Weights`, optional): The
  103. pretrained weights for the model. See
  104. :class:`~torchvision.models.quantization.MobileNet_V2_QuantizedWeights` below for
  105. more details, and possible values. By default, no pre-trained
  106. weights are used.
  107. progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True.
  108. quantize (bool, optional): If True, returns a quantized version of the model. Default is False.
  109. **kwargs: parameters passed to the ``torchvision.models.quantization.QuantizableMobileNetV2``
  110. base class. Please refer to the `source code
  111. <https://github.com/pytorch/vision/blob/main/torchvision/models/quantization/mobilenetv2.py>`_
  112. for more details about this class.
  113. .. autoclass:: torchvision.models.quantization.MobileNet_V2_QuantizedWeights
  114. :members:
  115. .. autoclass:: torchvision.models.MobileNet_V2_Weights
  116. :members:
  117. :noindex:
  118. """
  119. weights = (MobileNet_V2_QuantizedWeights if quantize else MobileNet_V2_Weights).verify(weights)
  120. if weights is not None:
  121. _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"]))
  122. if "backend" in weights.meta:
  123. _ovewrite_named_param(kwargs, "backend", weights.meta["backend"])
  124. backend = kwargs.pop("backend", "qnnpack")
  125. model = QuantizableMobileNetV2(block=QuantizableInvertedResidual, **kwargs)
  126. _replace_relu(model)
  127. if quantize:
  128. quantize_model(model, backend)
  129. if weights is not None:
  130. model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
  131. return model