anchor_free_head.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. from abc import abstractmethod
  3. from typing import Any, List, Sequence, Tuple, Union
  4. import torch.nn as nn
  5. from mmcv.cnn import ConvModule
  6. from numpy import ndarray
  7. from torch import Tensor
  8. from mmdet.registry import MODELS, TASK_UTILS
  9. from mmdet.utils import (ConfigType, InstanceList, MultiConfig, OptConfigType,
  10. OptInstanceList)
  11. from ..task_modules.prior_generators import MlvlPointGenerator
  12. from ..utils import multi_apply
  13. from .base_dense_head import BaseDenseHead
  14. StrideType = Union[Sequence[int], Sequence[Tuple[int, int]]]
  15. @MODELS.register_module()
  16. class AnchorFreeHead(BaseDenseHead):
  17. """Anchor-free head (FCOS, Fovea, RepPoints, etc.).
  18. Args:
  19. num_classes (int): Number of categories excluding the background
  20. category.
  21. in_channels (int): Number of channels in the input feature map.
  22. feat_channels (int): Number of hidden channels. Used in child classes.
  23. stacked_convs (int): Number of stacking convs of the head.
  24. strides (Sequence[int] or Sequence[Tuple[int, int]]): Downsample
  25. factor of each feature map.
  26. dcn_on_last_conv (bool): If true, use dcn in the last layer of
  27. towers. Defaults to False.
  28. conv_bias (bool or str): If specified as `auto`, it will be decided by
  29. the norm_cfg. Bias of conv will be set as True if `norm_cfg` is
  30. None, otherwise False. Default: "auto".
  31. loss_cls (:obj:`ConfigDict` or dict): Config of classification loss.
  32. loss_bbox (:obj:`ConfigDict` or dict): Config of localization loss.
  33. bbox_coder (:obj:`ConfigDict` or dict): Config of bbox coder. Defaults
  34. 'DistancePointBBoxCoder'.
  35. conv_cfg (:obj:`ConfigDict` or dict, Optional): Config dict for
  36. convolution layer. Defaults to None.
  37. norm_cfg (:obj:`ConfigDict` or dict, Optional): Config dict for
  38. normalization layer. Defaults to None.
  39. train_cfg (:obj:`ConfigDict` or dict, Optional): Training config of
  40. anchor-free head.
  41. test_cfg (:obj:`ConfigDict` or dict, Optional): Testing config of
  42. anchor-free head.
  43. init_cfg (:obj:`ConfigDict` or dict or list[:obj:`ConfigDict` or \
  44. dict]): Initialization config dict.
  45. """ # noqa: W605
  46. _version = 1
  47. def __init__(
  48. self,
  49. num_classes: int,
  50. in_channels: int,
  51. feat_channels: int = 256,
  52. stacked_convs: int = 4,
  53. strides: StrideType = (4, 8, 16, 32, 64),
  54. dcn_on_last_conv: bool = False,
  55. conv_bias: Union[bool, str] = 'auto',
  56. loss_cls: ConfigType = dict(
  57. type='FocalLoss',
  58. use_sigmoid=True,
  59. gamma=2.0,
  60. alpha=0.25,
  61. loss_weight=1.0),
  62. loss_bbox: ConfigType = dict(type='IoULoss', loss_weight=1.0),
  63. bbox_coder: ConfigType = dict(type='DistancePointBBoxCoder'),
  64. conv_cfg: OptConfigType = None,
  65. norm_cfg: OptConfigType = None,
  66. train_cfg: OptConfigType = None,
  67. test_cfg: OptConfigType = None,
  68. init_cfg: MultiConfig = dict(
  69. type='Normal',
  70. layer='Conv2d',
  71. std=0.01,
  72. override=dict(
  73. type='Normal', name='conv_cls', std=0.01, bias_prob=0.01))
  74. ) -> None:
  75. super().__init__(init_cfg=init_cfg)
  76. self.num_classes = num_classes
  77. self.use_sigmoid_cls = loss_cls.get('use_sigmoid', False)
  78. if self.use_sigmoid_cls:
  79. self.cls_out_channels = num_classes
  80. else:
  81. self.cls_out_channels = num_classes + 1
  82. self.in_channels = in_channels
  83. self.feat_channels = feat_channels
  84. self.stacked_convs = stacked_convs
  85. self.strides = strides
  86. self.dcn_on_last_conv = dcn_on_last_conv
  87. assert conv_bias == 'auto' or isinstance(conv_bias, bool)
  88. self.conv_bias = conv_bias
  89. self.loss_cls = MODELS.build(loss_cls)
  90. self.loss_bbox = MODELS.build(loss_bbox)
  91. self.bbox_coder = TASK_UTILS.build(bbox_coder)
  92. self.prior_generator = MlvlPointGenerator(strides)
  93. # In order to keep a more general interface and be consistent with
  94. # anchor_head. We can think of point like one anchor
  95. self.num_base_priors = self.prior_generator.num_base_priors[0]
  96. self.train_cfg = train_cfg
  97. self.test_cfg = test_cfg
  98. self.conv_cfg = conv_cfg
  99. self.norm_cfg = norm_cfg
  100. self.fp16_enabled = False
  101. self._init_layers()
  102. def _init_layers(self) -> None:
  103. """Initialize layers of the head."""
  104. self._init_cls_convs()
  105. self._init_reg_convs()
  106. self._init_predictor()
  107. def _init_cls_convs(self) -> None:
  108. """Initialize classification conv layers of the head."""
  109. self.cls_convs = nn.ModuleList()
  110. for i in range(self.stacked_convs):
  111. chn = self.in_channels if i == 0 else self.feat_channels
  112. if self.dcn_on_last_conv and i == self.stacked_convs - 1:
  113. conv_cfg = dict(type='DCNv2')
  114. else:
  115. conv_cfg = self.conv_cfg
  116. self.cls_convs.append(
  117. ConvModule(
  118. chn,
  119. self.feat_channels,
  120. 3,
  121. stride=1,
  122. padding=1,
  123. conv_cfg=conv_cfg,
  124. norm_cfg=self.norm_cfg,
  125. bias=self.conv_bias))
  126. def _init_reg_convs(self) -> None:
  127. """Initialize bbox regression conv layers of the head."""
  128. self.reg_convs = nn.ModuleList()
  129. for i in range(self.stacked_convs):
  130. chn = self.in_channels if i == 0 else self.feat_channels
  131. if self.dcn_on_last_conv and i == self.stacked_convs - 1:
  132. conv_cfg = dict(type='DCNv2')
  133. else:
  134. conv_cfg = self.conv_cfg
  135. self.reg_convs.append(
  136. ConvModule(
  137. chn,
  138. self.feat_channels,
  139. 3,
  140. stride=1,
  141. padding=1,
  142. conv_cfg=conv_cfg,
  143. norm_cfg=self.norm_cfg,
  144. bias=self.conv_bias))
  145. def _init_predictor(self) -> None:
  146. """Initialize predictor layers of the head."""
  147. self.conv_cls = nn.Conv2d(
  148. self.feat_channels, self.cls_out_channels, 3, padding=1)
  149. self.conv_reg = nn.Conv2d(self.feat_channels, 4, 3, padding=1)
  150. def _load_from_state_dict(self, state_dict: dict, prefix: str,
  151. local_metadata: dict, strict: bool,
  152. missing_keys: Union[List[str], str],
  153. unexpected_keys: Union[List[str], str],
  154. error_msgs: Union[List[str], str]) -> None:
  155. """Hack some keys of the model state dict so that can load checkpoints
  156. of previous version."""
  157. version = local_metadata.get('version', None)
  158. if version is None:
  159. # the key is different in early versions
  160. # for example, 'fcos_cls' become 'conv_cls' now
  161. bbox_head_keys = [
  162. k for k in state_dict.keys() if k.startswith(prefix)
  163. ]
  164. ori_predictor_keys = []
  165. new_predictor_keys = []
  166. # e.g. 'fcos_cls' or 'fcos_reg'
  167. for key in bbox_head_keys:
  168. ori_predictor_keys.append(key)
  169. key = key.split('.')
  170. if len(key) < 2:
  171. conv_name = None
  172. elif key[1].endswith('cls'):
  173. conv_name = 'conv_cls'
  174. elif key[1].endswith('reg'):
  175. conv_name = 'conv_reg'
  176. elif key[1].endswith('centerness'):
  177. conv_name = 'conv_centerness'
  178. else:
  179. conv_name = None
  180. if conv_name is not None:
  181. key[1] = conv_name
  182. new_predictor_keys.append('.'.join(key))
  183. else:
  184. ori_predictor_keys.pop(-1)
  185. for i in range(len(new_predictor_keys)):
  186. state_dict[new_predictor_keys[i]] = state_dict.pop(
  187. ori_predictor_keys[i])
  188. super()._load_from_state_dict(state_dict, prefix, local_metadata,
  189. strict, missing_keys, unexpected_keys,
  190. error_msgs)
  191. def forward(self, x: Tuple[Tensor]) -> Tuple[List[Tensor], List[Tensor]]:
  192. """Forward features from the upstream network.
  193. Args:
  194. feats (tuple[Tensor]): Features from the upstream network, each is
  195. a 4D-tensor.
  196. Returns:
  197. tuple: Usually contain classification scores and bbox predictions.
  198. - cls_scores (list[Tensor]): Box scores for each scale level, \
  199. each is a 4D-tensor, the channel number is \
  200. num_points * num_classes.
  201. - bbox_preds (list[Tensor]): Box energies / deltas for each scale \
  202. level, each is a 4D-tensor, the channel number is num_points * 4.
  203. """
  204. return multi_apply(self.forward_single, x)[:2]
  205. def forward_single(self, x: Tensor) -> Tuple[Tensor, ...]:
  206. """Forward features of a single scale level.
  207. Args:
  208. x (Tensor): FPN feature maps of the specified stride.
  209. Returns:
  210. tuple: Scores for each class, bbox predictions, features
  211. after classification and regression conv layers, some
  212. models needs these features like FCOS.
  213. """
  214. cls_feat = x
  215. reg_feat = x
  216. for cls_layer in self.cls_convs:
  217. cls_feat = cls_layer(cls_feat)
  218. cls_score = self.conv_cls(cls_feat)
  219. for reg_layer in self.reg_convs:
  220. reg_feat = reg_layer(reg_feat)
  221. bbox_pred = self.conv_reg(reg_feat)
  222. return cls_score, bbox_pred, cls_feat, reg_feat
  223. @abstractmethod
  224. def loss_by_feat(
  225. self,
  226. cls_scores: List[Tensor],
  227. bbox_preds: List[Tensor],
  228. batch_gt_instances: InstanceList,
  229. batch_img_metas: List[dict],
  230. batch_gt_instances_ignore: OptInstanceList = None) -> dict:
  231. """Calculate the loss based on the features extracted by the detection
  232. head.
  233. Args:
  234. cls_scores (list[Tensor]): Box scores for each scale level,
  235. each is a 4D-tensor, the channel number is
  236. num_points * num_classes.
  237. bbox_preds (list[Tensor]): Box energies / deltas for each scale
  238. level, each is a 4D-tensor, the channel number is
  239. num_points * 4.
  240. batch_gt_instances (list[:obj:`InstanceData`]): Batch of
  241. gt_instance. It usually includes ``bboxes`` and ``labels``
  242. attributes.
  243. batch_img_metas (list[dict]): Meta information of each image, e.g.,
  244. image size, scaling factor, etc.
  245. batch_gt_instances_ignore (list[:obj:`InstanceData`], Optional):
  246. Batch of gt_instances_ignore. It includes ``bboxes`` attribute
  247. data that is ignored during training and testing.
  248. Defaults to None.
  249. """
  250. raise NotImplementedError
  251. @abstractmethod
  252. def get_targets(self, points: List[Tensor],
  253. batch_gt_instances: InstanceList) -> Any:
  254. """Compute regression, classification and centerness targets for points
  255. in multiple images.
  256. Args:
  257. points (list[Tensor]): Points of each fpn level, each has shape
  258. (num_points, 2).
  259. batch_gt_instances (list[:obj:`InstanceData`]): Batch of
  260. gt_instance. It usually includes ``bboxes`` and ``labels``
  261. attributes.
  262. """
  263. raise NotImplementedError
  264. # TODO refactor aug_test
  265. def aug_test(self,
  266. aug_batch_feats: List[Tensor],
  267. aug_batch_img_metas: List[List[Tensor]],
  268. rescale: bool = False) -> List[ndarray]:
  269. """Test function with test time augmentation.
  270. Args:
  271. aug_batch_feats (list[Tensor]): the outer list indicates test-time
  272. augmentations and inner Tensor should have a shape NxCxHxW,
  273. which contains features for all images in the batch.
  274. aug_batch_img_metas (list[list[dict]]): the outer list indicates
  275. test-time augs (multiscale, flip, etc.) and the inner list
  276. indicates images in a batch. each dict has image information.
  277. rescale (bool, optional): Whether to rescale the results.
  278. Defaults to False.
  279. Returns:
  280. list[ndarray]: bbox results of each class
  281. """
  282. return self.aug_test_bboxes(
  283. aug_batch_feats, aug_batch_img_metas, rescale=rescale)