inception.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. import warnings
  2. from functools import partial
  3. from typing import Any, List, 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 InceptionOutputs, Inception_V3_Weights
  10. from ...transforms._presets import ImageClassification
  11. from .._api import WeightsEnum, Weights
  12. from .._meta import _IMAGENET_CATEGORIES
  13. from .._utils import handle_legacy_interface, _ovewrite_named_param
  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__(conv_block=QuantizableBasicConv2d, *args, **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__(conv_block=QuantizableBasicConv2d, *args, **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__(conv_block=QuantizableBasicConv2d, *args, **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__(conv_block=QuantizableBasicConv2d, *args, **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__(conv_block=QuantizableBasicConv2d, *args, **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__(conv_block=QuantizableBasicConv2d, *args, **kwargs) # type: ignore[misc]
  93. class QuantizableInception3(inception_module.Inception3):
  94. def __init__(
  95. self,
  96. num_classes: int = 1000,
  97. aux_logits: bool = True,
  98. transform_input: bool = False,
  99. ) -> None:
  100. super().__init__(
  101. num_classes=num_classes,
  102. aux_logits=aux_logits,
  103. transform_input=transform_input,
  104. inception_blocks=[
  105. QuantizableBasicConv2d,
  106. QuantizableInceptionA,
  107. QuantizableInceptionB,
  108. QuantizableInceptionC,
  109. QuantizableInceptionD,
  110. QuantizableInceptionE,
  111. QuantizableInceptionAux,
  112. ],
  113. )
  114. self.quant = torch.ao.quantization.QuantStub()
  115. self.dequant = torch.ao.quantization.DeQuantStub()
  116. def forward(self, x: Tensor) -> InceptionOutputs:
  117. x = self._transform_input(x)
  118. x = self.quant(x)
  119. x, aux = self._forward(x)
  120. x = self.dequant(x)
  121. aux_defined = self.training and self.aux_logits
  122. if torch.jit.is_scripting():
  123. if not aux_defined:
  124. warnings.warn("Scripted QuantizableInception3 always returns QuantizableInception3 Tuple")
  125. return InceptionOutputs(x, aux)
  126. else:
  127. return self.eager_outputs(x, aux)
  128. def fuse_model(self, is_qat: Optional[bool] = None) -> None:
  129. r"""Fuse conv/bn/relu modules in inception model
  130. Fuse conv+bn+relu/ conv+relu/conv+bn modules to prepare for quantization.
  131. Model is modified in place. Note that this operation does not change numerics
  132. and the model after modification is in floating point
  133. """
  134. for m in self.modules():
  135. if type(m) is QuantizableBasicConv2d:
  136. m.fuse_model(is_qat)
  137. class Inception_V3_QuantizedWeights(WeightsEnum):
  138. IMAGENET1K_FBGEMM_V1 = Weights(
  139. url="https://download.pytorch.org/models/quantized/inception_v3_google_fbgemm-71447a44.pth",
  140. transforms=partial(ImageClassification, crop_size=299, resize_size=342),
  141. meta={
  142. "num_params": 27161264,
  143. "min_size": (75, 75),
  144. "categories": _IMAGENET_CATEGORIES,
  145. "backend": "fbgemm",
  146. "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#post-training-quantized-models",
  147. "unquantized": Inception_V3_Weights.IMAGENET1K_V1,
  148. "_metrics": {
  149. "ImageNet-1K": {
  150. "acc@1": 77.176,
  151. "acc@5": 93.354,
  152. }
  153. },
  154. "_docs": """
  155. These weights were produced by doing Post Training Quantization (eager mode) on top of the unquantized
  156. weights listed below.
  157. """,
  158. },
  159. )
  160. DEFAULT = IMAGENET1K_FBGEMM_V1
  161. @handle_legacy_interface(
  162. weights=(
  163. "pretrained",
  164. lambda kwargs: Inception_V3_QuantizedWeights.IMAGENET1K_FBGEMM_V1
  165. if kwargs.get("quantize", False)
  166. else Inception_V3_Weights.IMAGENET1K_V1,
  167. )
  168. )
  169. def inception_v3(
  170. *,
  171. weights: Optional[Union[Inception_V3_QuantizedWeights, Inception_V3_Weights]] = None,
  172. progress: bool = True,
  173. quantize: bool = False,
  174. **kwargs: Any,
  175. ) -> QuantizableInception3:
  176. r"""Inception v3 model architecture from
  177. `Rethinking the Inception Architecture for Computer Vision <http://arxiv.org/abs/1512.00567>`__.
  178. .. note::
  179. **Important**: In contrast to the other models the inception_v3 expects tensors with a size of
  180. N x 3 x 299 x 299, so ensure your images are sized accordingly.
  181. .. note::
  182. Note that ``quantize = True`` returns a quantized model with 8 bit
  183. weights. Quantized models only support inference and run on CPUs.
  184. GPU inference is not yet supported.
  185. Args:
  186. weights (:class:`~torchvision.models.quantization.Inception_V3_QuantizedWeights` or :class:`~torchvision.models.Inception_V3_Weights`, optional): The pretrained
  187. weights for the model. See
  188. :class:`~torchvision.models.quantization.Inception_V3_QuantizedWeights` below for
  189. more details, and possible values. By default, no pre-trained
  190. weights are used.
  191. progress (bool, optional): If True, displays a progress bar of the download to stderr.
  192. Default is True.
  193. quantize (bool, optional): If True, return a quantized version of the model.
  194. Default is False.
  195. **kwargs: parameters passed to the ``torchvision.models.quantization.QuantizableInception3``
  196. base class. Please refer to the `source code
  197. <https://github.com/pytorch/vision/blob/main/torchvision/models/quantization/inception.py>`_
  198. for more details about this class.
  199. .. autoclass:: torchvision.models.quantization.Inception_V3_QuantizedWeights
  200. :members:
  201. .. autoclass:: torchvision.models.Inception_V3_Weights
  202. :members:
  203. :noindex:
  204. """
  205. weights = (Inception_V3_QuantizedWeights if quantize else Inception_V3_Weights).verify(weights)
  206. original_aux_logits = kwargs.get("aux_logits", False)
  207. if weights is not None:
  208. if "transform_input" not in kwargs:
  209. _ovewrite_named_param(kwargs, "transform_input", True)
  210. _ovewrite_named_param(kwargs, "aux_logits", True)
  211. _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"]))
  212. if "backend" in weights.meta:
  213. _ovewrite_named_param(kwargs, "backend", weights.meta["backend"])
  214. backend = kwargs.pop("backend", "fbgemm")
  215. model = QuantizableInception3(**kwargs)
  216. _replace_relu(model)
  217. if quantize:
  218. quantize_model(model, backend)
  219. if weights is not None:
  220. if quantize and not original_aux_logits:
  221. model.aux_logits = False
  222. model.AuxLogits = None
  223. model.load_state_dict(weights.get_state_dict(progress=progress))
  224. if not quantize and not original_aux_logits:
  225. model.aux_logits = False
  226. model.AuxLogits = None
  227. return model
  228. # The dictionary below is internal implementation detail and will be removed in v0.15
  229. from .._utils import _ModelURLs
  230. from ..inception import model_urls # noqa: F401
  231. quant_model_urls = _ModelURLs(
  232. {
  233. # fp32 weights ported from TensorFlow, quantized in PyTorch
  234. "inception_v3_google_fbgemm": Inception_V3_QuantizedWeights.IMAGENET1K_FBGEMM_V1.url,
  235. }
  236. )