ssdlite.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. import warnings
  2. from collections import OrderedDict
  3. from functools import partial
  4. from typing import Any, Callable, Dict, List, Optional, Union
  5. import torch
  6. from torch import nn, Tensor
  7. from ...ops.misc import Conv2dNormActivation
  8. from ...transforms._presets import ObjectDetection
  9. from ...utils import _log_api_usage_once
  10. from .. import mobilenet
  11. from .._api import register_model, Weights, WeightsEnum
  12. from .._meta import _COCO_CATEGORIES
  13. from .._utils import _ovewrite_value_param, handle_legacy_interface
  14. from ..mobilenetv3 import mobilenet_v3_large, MobileNet_V3_Large_Weights
  15. from . import _utils as det_utils
  16. from .anchor_utils import DefaultBoxGenerator
  17. from .backbone_utils import _validate_trainable_layers
  18. from .ssd import SSD, SSDScoringHead
  19. __all__ = [
  20. "SSDLite320_MobileNet_V3_Large_Weights",
  21. "ssdlite320_mobilenet_v3_large",
  22. ]
  23. # Building blocks of SSDlite as described in section 6.2 of MobileNetV2 paper
  24. def _prediction_block(
  25. in_channels: int, out_channels: int, kernel_size: int, norm_layer: Callable[..., nn.Module]
  26. ) -> nn.Sequential:
  27. return nn.Sequential(
  28. # 3x3 depthwise with stride 1 and padding 1
  29. Conv2dNormActivation(
  30. in_channels,
  31. in_channels,
  32. kernel_size=kernel_size,
  33. groups=in_channels,
  34. norm_layer=norm_layer,
  35. activation_layer=nn.ReLU6,
  36. ),
  37. # 1x1 projetion to output channels
  38. nn.Conv2d(in_channels, out_channels, 1),
  39. )
  40. def _extra_block(in_channels: int, out_channels: int, norm_layer: Callable[..., nn.Module]) -> nn.Sequential:
  41. activation = nn.ReLU6
  42. intermediate_channels = out_channels // 2
  43. return nn.Sequential(
  44. # 1x1 projection to half output channels
  45. Conv2dNormActivation(
  46. in_channels, intermediate_channels, kernel_size=1, norm_layer=norm_layer, activation_layer=activation
  47. ),
  48. # 3x3 depthwise with stride 2 and padding 1
  49. Conv2dNormActivation(
  50. intermediate_channels,
  51. intermediate_channels,
  52. kernel_size=3,
  53. stride=2,
  54. groups=intermediate_channels,
  55. norm_layer=norm_layer,
  56. activation_layer=activation,
  57. ),
  58. # 1x1 projetion to output channels
  59. Conv2dNormActivation(
  60. intermediate_channels, out_channels, kernel_size=1, norm_layer=norm_layer, activation_layer=activation
  61. ),
  62. )
  63. def _normal_init(conv: nn.Module):
  64. for layer in conv.modules():
  65. if isinstance(layer, nn.Conv2d):
  66. torch.nn.init.normal_(layer.weight, mean=0.0, std=0.03)
  67. if layer.bias is not None:
  68. torch.nn.init.constant_(layer.bias, 0.0)
  69. class SSDLiteHead(nn.Module):
  70. def __init__(
  71. self, in_channels: List[int], num_anchors: List[int], num_classes: int, norm_layer: Callable[..., nn.Module]
  72. ):
  73. super().__init__()
  74. self.classification_head = SSDLiteClassificationHead(in_channels, num_anchors, num_classes, norm_layer)
  75. self.regression_head = SSDLiteRegressionHead(in_channels, num_anchors, norm_layer)
  76. def forward(self, x: List[Tensor]) -> Dict[str, Tensor]:
  77. return {
  78. "bbox_regression": self.regression_head(x),
  79. "cls_logits": self.classification_head(x),
  80. }
  81. class SSDLiteClassificationHead(SSDScoringHead):
  82. def __init__(
  83. self, in_channels: List[int], num_anchors: List[int], num_classes: int, norm_layer: Callable[..., nn.Module]
  84. ):
  85. cls_logits = nn.ModuleList()
  86. for channels, anchors in zip(in_channels, num_anchors):
  87. cls_logits.append(_prediction_block(channels, num_classes * anchors, 3, norm_layer))
  88. _normal_init(cls_logits)
  89. super().__init__(cls_logits, num_classes)
  90. class SSDLiteRegressionHead(SSDScoringHead):
  91. def __init__(self, in_channels: List[int], num_anchors: List[int], norm_layer: Callable[..., nn.Module]):
  92. bbox_reg = nn.ModuleList()
  93. for channels, anchors in zip(in_channels, num_anchors):
  94. bbox_reg.append(_prediction_block(channels, 4 * anchors, 3, norm_layer))
  95. _normal_init(bbox_reg)
  96. super().__init__(bbox_reg, 4)
  97. class SSDLiteFeatureExtractorMobileNet(nn.Module):
  98. def __init__(
  99. self,
  100. backbone: nn.Module,
  101. c4_pos: int,
  102. norm_layer: Callable[..., nn.Module],
  103. width_mult: float = 1.0,
  104. min_depth: int = 16,
  105. ):
  106. super().__init__()
  107. _log_api_usage_once(self)
  108. if backbone[c4_pos].use_res_connect:
  109. raise ValueError("backbone[c4_pos].use_res_connect should be False")
  110. self.features = nn.Sequential(
  111. # As described in section 6.3 of MobileNetV3 paper
  112. nn.Sequential(*backbone[:c4_pos], backbone[c4_pos].block[0]), # from start until C4 expansion layer
  113. nn.Sequential(backbone[c4_pos].block[1:], *backbone[c4_pos + 1 :]), # from C4 depthwise until end
  114. )
  115. get_depth = lambda d: max(min_depth, int(d * width_mult)) # noqa: E731
  116. extra = nn.ModuleList(
  117. [
  118. _extra_block(backbone[-1].out_channels, get_depth(512), norm_layer),
  119. _extra_block(get_depth(512), get_depth(256), norm_layer),
  120. _extra_block(get_depth(256), get_depth(256), norm_layer),
  121. _extra_block(get_depth(256), get_depth(128), norm_layer),
  122. ]
  123. )
  124. _normal_init(extra)
  125. self.extra = extra
  126. def forward(self, x: Tensor) -> Dict[str, Tensor]:
  127. # Get feature maps from backbone and extra. Can't be refactored due to JIT limitations.
  128. output = []
  129. for block in self.features:
  130. x = block(x)
  131. output.append(x)
  132. for block in self.extra:
  133. x = block(x)
  134. output.append(x)
  135. return OrderedDict([(str(i), v) for i, v in enumerate(output)])
  136. def _mobilenet_extractor(
  137. backbone: Union[mobilenet.MobileNetV2, mobilenet.MobileNetV3],
  138. trainable_layers: int,
  139. norm_layer: Callable[..., nn.Module],
  140. ):
  141. backbone = backbone.features
  142. # Gather the indices of blocks which are strided. These are the locations of C1, ..., Cn-1 blocks.
  143. # The first and last blocks are always included because they are the C0 (conv1) and Cn.
  144. stage_indices = [0] + [i for i, b in enumerate(backbone) if getattr(b, "_is_cn", False)] + [len(backbone) - 1]
  145. num_stages = len(stage_indices)
  146. # find the index of the layer from which we won't freeze
  147. if not 0 <= trainable_layers <= num_stages:
  148. raise ValueError("trainable_layers should be in the range [0, {num_stages}], instead got {trainable_layers}")
  149. freeze_before = len(backbone) if trainable_layers == 0 else stage_indices[num_stages - trainable_layers]
  150. for b in backbone[:freeze_before]:
  151. for parameter in b.parameters():
  152. parameter.requires_grad_(False)
  153. return SSDLiteFeatureExtractorMobileNet(backbone, stage_indices[-2], norm_layer)
  154. class SSDLite320_MobileNet_V3_Large_Weights(WeightsEnum):
  155. COCO_V1 = Weights(
  156. url="https://download.pytorch.org/models/ssdlite320_mobilenet_v3_large_coco-a79551df.pth",
  157. transforms=ObjectDetection,
  158. meta={
  159. "num_params": 3440060,
  160. "categories": _COCO_CATEGORIES,
  161. "min_size": (1, 1),
  162. "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#ssdlite320-mobilenetv3-large",
  163. "_metrics": {
  164. "COCO-val2017": {
  165. "box_map": 21.3,
  166. }
  167. },
  168. "_ops": 0.583,
  169. "_file_size": 13.418,
  170. "_docs": """These weights were produced by following a similar training recipe as on the paper.""",
  171. },
  172. )
  173. DEFAULT = COCO_V1
  174. @register_model()
  175. @handle_legacy_interface(
  176. weights=("pretrained", SSDLite320_MobileNet_V3_Large_Weights.COCO_V1),
  177. weights_backbone=("pretrained_backbone", MobileNet_V3_Large_Weights.IMAGENET1K_V1),
  178. )
  179. def ssdlite320_mobilenet_v3_large(
  180. *,
  181. weights: Optional[SSDLite320_MobileNet_V3_Large_Weights] = None,
  182. progress: bool = True,
  183. num_classes: Optional[int] = None,
  184. weights_backbone: Optional[MobileNet_V3_Large_Weights] = MobileNet_V3_Large_Weights.IMAGENET1K_V1,
  185. trainable_backbone_layers: Optional[int] = None,
  186. norm_layer: Optional[Callable[..., nn.Module]] = None,
  187. **kwargs: Any,
  188. ) -> SSD:
  189. """SSDlite model architecture with input size 320x320 and a MobileNetV3 Large backbone, as
  190. described at `Searching for MobileNetV3 <https://arxiv.org/abs/1905.02244>`__ and
  191. `MobileNetV2: Inverted Residuals and Linear Bottlenecks <https://arxiv.org/abs/1801.04381>`__.
  192. .. betastatus:: detection module
  193. See :func:`~torchvision.models.detection.ssd300_vgg16` for more details.
  194. Example:
  195. >>> model = torchvision.models.detection.ssdlite320_mobilenet_v3_large(weights=SSDLite320_MobileNet_V3_Large_Weights.DEFAULT)
  196. >>> model.eval()
  197. >>> x = [torch.rand(3, 320, 320), torch.rand(3, 500, 400)]
  198. >>> predictions = model(x)
  199. Args:
  200. weights (:class:`~torchvision.models.detection.SSDLite320_MobileNet_V3_Large_Weights`, optional): The
  201. pretrained weights to use. See
  202. :class:`~torchvision.models.detection.SSDLite320_MobileNet_V3_Large_Weights` below for
  203. more details, and possible values. By default, no pre-trained
  204. weights are used.
  205. progress (bool, optional): If True, displays a progress bar of the
  206. download to stderr. Default is True.
  207. num_classes (int, optional): number of output classes of the model
  208. (including the background).
  209. weights_backbone (:class:`~torchvision.models.MobileNet_V3_Large_Weights`, optional): The pretrained
  210. weights for the backbone.
  211. trainable_backbone_layers (int, optional): number of trainable (not frozen) layers
  212. starting from final block. Valid values are between 0 and 6, with 6 meaning all
  213. backbone layers are trainable. If ``None`` is passed (the default) this value is
  214. set to 6.
  215. norm_layer (callable, optional): Module specifying the normalization layer to use.
  216. **kwargs: parameters passed to the ``torchvision.models.detection.ssd.SSD``
  217. base class. Please refer to the `source code
  218. <https://github.com/pytorch/vision/blob/main/torchvision/models/detection/ssd.py>`_
  219. for more details about this class.
  220. .. autoclass:: torchvision.models.detection.SSDLite320_MobileNet_V3_Large_Weights
  221. :members:
  222. """
  223. weights = SSDLite320_MobileNet_V3_Large_Weights.verify(weights)
  224. weights_backbone = MobileNet_V3_Large_Weights.verify(weights_backbone)
  225. if "size" in kwargs:
  226. warnings.warn("The size of the model is already fixed; ignoring the parameter.")
  227. if weights is not None:
  228. weights_backbone = None
  229. num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"]))
  230. elif num_classes is None:
  231. num_classes = 91
  232. trainable_backbone_layers = _validate_trainable_layers(
  233. weights is not None or weights_backbone is not None, trainable_backbone_layers, 6, 6
  234. )
  235. # Enable reduced tail if no pretrained backbone is selected. See Table 6 of MobileNetV3 paper.
  236. reduce_tail = weights_backbone is None
  237. if norm_layer is None:
  238. norm_layer = partial(nn.BatchNorm2d, eps=0.001, momentum=0.03)
  239. backbone = mobilenet_v3_large(
  240. weights=weights_backbone, progress=progress, norm_layer=norm_layer, reduced_tail=reduce_tail, **kwargs
  241. )
  242. if weights_backbone is None:
  243. # Change the default initialization scheme if not pretrained
  244. _normal_init(backbone)
  245. backbone = _mobilenet_extractor(
  246. backbone,
  247. trainable_backbone_layers,
  248. norm_layer,
  249. )
  250. size = (320, 320)
  251. anchor_generator = DefaultBoxGenerator([[2, 3] for _ in range(6)], min_ratio=0.2, max_ratio=0.95)
  252. out_channels = det_utils.retrieve_out_channels(backbone, size)
  253. num_anchors = anchor_generator.num_anchors_per_location()
  254. if len(out_channels) != len(anchor_generator.aspect_ratios):
  255. raise ValueError(
  256. f"The length of the output channels from the backbone {len(out_channels)} do not match the length of the anchor generator aspect ratios {len(anchor_generator.aspect_ratios)}"
  257. )
  258. defaults = {
  259. "score_thresh": 0.001,
  260. "nms_thresh": 0.55,
  261. "detections_per_img": 300,
  262. "topk_candidates": 300,
  263. # Rescale the input in a way compatible to the backbone:
  264. # The following mean/std rescale the data from [0, 1] to [-1, 1]
  265. "image_mean": [0.5, 0.5, 0.5],
  266. "image_std": [0.5, 0.5, 0.5],
  267. }
  268. kwargs: Any = {**defaults, **kwargs}
  269. model = SSD(
  270. backbone,
  271. anchor_generator,
  272. size,
  273. num_classes,
  274. head=SSDLiteHead(out_channels, num_anchors, num_classes, norm_layer),
  275. **kwargs,
  276. )
  277. if weights is not None:
  278. model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True))
  279. return model