inception.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. import warnings
  2. from functools import partial
  3. from typing import Any, Optional, Union
  4. import torch
  5. import torch.nn as nn
  6. import torch.nn.functional as F
  7. from torch import Tensor
  8. from torchvision.models import inception as inception_module
  9. from torchvision.models.inception import Inception_V3_Weights, InceptionOutputs
  10. from ...transforms._presets import ImageClassification
  11. from .._api import register_model, Weights, WeightsEnum
  12. from .._meta import _IMAGENET_CATEGORIES
  13. from .._utils import _ovewrite_named_param, handle_legacy_interface
  14. from .utils import _fuse_modules, _replace_relu, quantize_model
  15. __all__ = [
  16. "QuantizableInception3",
  17. "Inception_V3_QuantizedWeights",
  18. "inception_v3",
  19. ]
  20. class QuantizableBasicConv2d(inception_module.BasicConv2d):
  21. def __init__(self, *args: Any, **kwargs: Any) -> None:
  22. super().__init__(*args, **kwargs)
  23. self.relu = nn.ReLU()
  24. def forward(self, x: Tensor) -> Tensor:
  25. x = self.conv(x)
  26. x = self.bn(x)
  27. x = self.relu(x)
  28. return x
  29. def fuse_model(self, is_qat: Optional[bool] = None) -> None:
  30. _fuse_modules(self, ["conv", "bn", "relu"], is_qat, inplace=True)
  31. class QuantizableInceptionA(inception_module.InceptionA):
  32. # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659
  33. def __init__(self, *args: Any, **kwargs: Any) -> None:
  34. super().__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) # type: ignore[misc]
  35. self.myop = nn.quantized.FloatFunctional()
  36. def forward(self, x: Tensor) -> Tensor:
  37. outputs = self._forward(x)
  38. return self.myop.cat(outputs, 1)
  39. class QuantizableInceptionB(inception_module.InceptionB):
  40. # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659
  41. def __init__(self, *args: Any, **kwargs: Any) -> None:
  42. super().__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) # type: ignore[misc]
  43. self.myop = nn.quantized.FloatFunctional()
  44. def forward(self, x: Tensor) -> Tensor:
  45. outputs = self._forward(x)
  46. return self.myop.cat(outputs, 1)
  47. class QuantizableInceptionC(inception_module.InceptionC):
  48. # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659
  49. def __init__(self, *args: Any, **kwargs: Any) -> None:
  50. super().__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) # type: ignore[misc]
  51. self.myop = nn.quantized.FloatFunctional()
  52. def forward(self, x: Tensor) -> Tensor:
  53. outputs = self._forward(x)
  54. return self.myop.cat(outputs, 1)
  55. class QuantizableInceptionD(inception_module.InceptionD):
  56. # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659
  57. def __init__(self, *args: Any, **kwargs: Any) -> None:
  58. super().__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) # type: ignore[misc]
  59. self.myop = nn.quantized.FloatFunctional()
  60. def forward(self, x: Tensor) -> Tensor:
  61. outputs = self._forward(x)
  62. return self.myop.cat(outputs, 1)
  63. class QuantizableInceptionE(inception_module.InceptionE):
  64. # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659
  65. def __init__(self, *args: Any, **kwargs: Any) -> None:
  66. super().__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) # type: ignore[misc]
  67. self.myop1 = nn.quantized.FloatFunctional()
  68. self.myop2 = nn.quantized.FloatFunctional()
  69. self.myop3 = nn.quantized.FloatFunctional()
  70. def _forward(self, x: Tensor) -> list[Tensor]:
  71. branch1x1 = self.branch1x1(x)
  72. branch3x3 = self.branch3x3_1(x)
  73. branch3x3 = [self.branch3x3_2a(branch3x3), self.branch3x3_2b(branch3x3)]
  74. branch3x3 = self.myop1.cat(branch3x3, 1)
  75. branch3x3dbl = self.branch3x3dbl_1(x)
  76. branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
  77. branch3x3dbl = [
  78. self.branch3x3dbl_3a(branch3x3dbl),
  79. self.branch3x3dbl_3b(branch3x3dbl),
  80. ]
  81. branch3x3dbl = self.myop2.cat(branch3x3dbl, 1)
  82. branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1)
  83. branch_pool = self.branch_pool(branch_pool)
  84. outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool]
  85. return outputs
  86. def forward(self, x: Tensor) -> Tensor:
  87. outputs = self._forward(x)
  88. return self.myop3.cat(outputs, 1)
  89. class QuantizableInceptionAux(inception_module.InceptionAux):
  90. # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659
  91. def __init__(self, *args: Any, **kwargs: Any) -> None:
  92. super().__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) # type: ignore[misc]
  93. class QuantizableInception3(inception_module.Inception3):
  94. def __init__(self, *args: Any, **kwargs: Any) -> None:
  95. super().__init__( # type: ignore[misc]
  96. *args,
  97. inception_blocks=[
  98. QuantizableBasicConv2d,
  99. QuantizableInceptionA,
  100. QuantizableInceptionB,
  101. QuantizableInceptionC,
  102. QuantizableInceptionD,
  103. QuantizableInceptionE,
  104. QuantizableInceptionAux,
  105. ],
  106. **kwargs,
  107. )
  108. self.quant = torch.ao.quantization.QuantStub()
  109. self.dequant = torch.ao.quantization.DeQuantStub()
  110. def forward(self, x: Tensor) -> InceptionOutputs:
  111. x = self._transform_input(x)
  112. x = self.quant(x)
  113. x, aux = self._forward(x)
  114. x = self.dequant(x)
  115. aux_defined = self.training and self.aux_logits
  116. if torch.jit.is_scripting():
  117. if not aux_defined:
  118. warnings.warn("Scripted QuantizableInception3 always returns QuantizableInception3 Tuple")
  119. return InceptionOutputs(x, aux)
  120. else:
  121. return self.eager_outputs(x, aux)
  122. def fuse_model(self, is_qat: Optional[bool] = None) -> None:
  123. r"""Fuse conv/bn/relu modules in inception model
  124. Fuse conv+bn+relu/ conv+relu/conv+bn modules to prepare for quantization.
  125. Model is modified in place. Note that this operation does not change numerics
  126. and the model after modification is in floating point
  127. """
  128. for m in self.modules():
  129. if type(m) is QuantizableBasicConv2d:
  130. m.fuse_model(is_qat)
  131. class Inception_V3_QuantizedWeights(WeightsEnum):
  132. IMAGENET1K_FBGEMM_V1 = Weights(
  133. url="https://download.pytorch.org/models/quantized/inception_v3_google_fbgemm-a2837893.pth",
  134. transforms=partial(ImageClassification, crop_size=299, resize_size=342),
  135. meta={
  136. "num_params": 27161264,
  137. "min_size": (75, 75),
  138. "categories": _IMAGENET_CATEGORIES,
  139. "backend": "fbgemm",
  140. "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#post-training-quantized-models",
  141. "unquantized": Inception_V3_Weights.IMAGENET1K_V1,
  142. "_metrics": {
  143. "ImageNet-1K": {
  144. "acc@1": 77.176,
  145. "acc@5": 93.354,
  146. }
  147. },
  148. "_ops": 5.713,
  149. "_file_size": 23.146,
  150. "_docs": """
  151. These weights were produced by doing Post Training Quantization (eager mode) on top of the unquantized
  152. weights listed below.
  153. """,
  154. },
  155. )
  156. DEFAULT = IMAGENET1K_FBGEMM_V1
  157. @register_model(name="quantized_inception_v3")
  158. @handle_legacy_interface(
  159. weights=(
  160. "pretrained",
  161. lambda kwargs: (
  162. Inception_V3_QuantizedWeights.IMAGENET1K_FBGEMM_V1
  163. if kwargs.get("quantize", False)
  164. else Inception_V3_Weights.IMAGENET1K_V1
  165. ),
  166. )
  167. )
  168. def inception_v3(
  169. *,
  170. weights: Optional[Union[Inception_V3_QuantizedWeights, Inception_V3_Weights]] = None,
  171. progress: bool = True,
  172. quantize: bool = False,
  173. **kwargs: Any,
  174. ) -> QuantizableInception3:
  175. r"""Inception v3 model architecture from
  176. `Rethinking the Inception Architecture for Computer Vision <http://arxiv.org/abs/1512.00567>`__.
  177. .. note::
  178. **Important**: In contrast to the other models the inception_v3 expects tensors with a size of
  179. N x 3 x 299 x 299, so ensure your images are sized accordingly.
  180. .. note::
  181. Note that ``quantize = True`` returns a quantized model with 8 bit
  182. weights. Quantized models only support inference and run on CPUs.
  183. GPU inference is not yet supported.
  184. Args:
  185. weights (:class:`~torchvision.models.quantization.Inception_V3_QuantizedWeights` or :class:`~torchvision.models.Inception_V3_Weights`, optional): The pretrained
  186. weights for the model. See
  187. :class:`~torchvision.models.quantization.Inception_V3_QuantizedWeights` below for
  188. more details, and possible values. By default, no pre-trained
  189. weights are used.
  190. progress (bool, optional): If True, displays a progress bar of the download to stderr.
  191. Default is True.
  192. quantize (bool, optional): If True, return a quantized version of the model.
  193. Default is False.
  194. **kwargs: parameters passed to the ``torchvision.models.quantization.QuantizableInception3``
  195. base class. Please refer to the `source code
  196. <https://github.com/pytorch/vision/blob/main/torchvision/models/quantization/inception.py>`_
  197. for more details about this class.
  198. .. autoclass:: torchvision.models.quantization.Inception_V3_QuantizedWeights
  199. :members:
  200. .. autoclass:: torchvision.models.Inception_V3_Weights
  201. :members:
  202. :noindex:
  203. """
  204. weights = (Inception_V3_QuantizedWeights if quantize else Inception_V3_Weights).verify(weights)
  205. original_aux_logits = kwargs.get("aux_logits", False)
  206. if weights is not None:
  207. if "transform_input" not in kwargs:
  208. _ovewrite_named_param(kwargs, "transform_input", True)
  209. _ovewrite_named_param(kwargs, "aux_logits", True)
  210. _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"]))
  211. if "backend" in weights.meta:
  212. _ovewrite_named_param(kwargs, "backend", weights.meta["backend"])
  213. backend = kwargs.pop("backend", "fbgemm")
  214. model = QuantizableInception3(**kwargs)
  215. _replace_relu(model)
  216. if quantize:
  217. quantize_model(model, backend)
  218. if weights is not None:
  219. if quantize and not original_aux_logits:
  220. model.aux_logits = False
  221. model.AuxLogits = None
  222. model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
  223. if not quantize and not original_aux_logits:
  224. model.aux_logits = False
  225. model.AuxLogits = None
  226. return model