mobilenetv2.py 5.9 KB

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