bbox_head.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import numpy as np
  15. import paddle
  16. import paddle.nn as nn
  17. import paddle.nn.functional as F
  18. from paddle.nn.initializer import Normal, XavierUniform, KaimingNormal
  19. from paddle.regularizer import L2Decay
  20. from ppdet.core.workspace import register, create
  21. from .roi_extractor import RoIAlign
  22. from ..shape_spec import ShapeSpec
  23. from ..bbox_utils import bbox2delta
  24. from ppdet.modeling.layers import ConvNormLayer
  25. __all__ = ['TwoFCHead', 'XConvNormHead', 'BBoxHead']
  26. @register
  27. class TwoFCHead(nn.Layer):
  28. """
  29. RCNN bbox head with Two fc layers to extract feature
  30. Args:
  31. in_channel (int): Input channel which can be derived by from_config
  32. out_channel (int): Output channel
  33. resolution (int): Resolution of input feature map, default 7
  34. """
  35. def __init__(self, in_channel=256, out_channel=1024, resolution=7):
  36. super(TwoFCHead, self).__init__()
  37. self.in_channel = in_channel
  38. self.out_channel = out_channel
  39. fan = in_channel * resolution * resolution
  40. self.fc6 = nn.Linear(
  41. in_channel * resolution * resolution,
  42. out_channel,
  43. weight_attr=paddle.ParamAttr(
  44. initializer=XavierUniform(fan_out=fan)))
  45. self.fc6.skip_quant = True
  46. self.fc7 = nn.Linear(
  47. out_channel,
  48. out_channel,
  49. weight_attr=paddle.ParamAttr(initializer=XavierUniform()))
  50. self.fc7.skip_quant = True
  51. @classmethod
  52. def from_config(cls, cfg, input_shape):
  53. s = input_shape
  54. s = s[0] if isinstance(s, (list, tuple)) else s
  55. return {'in_channel': s.channels}
  56. @property
  57. def out_shape(self):
  58. return [ShapeSpec(channels=self.out_channel, )]
  59. def forward(self, rois_feat):
  60. rois_feat = paddle.flatten(rois_feat, start_axis=1, stop_axis=-1)
  61. fc6 = self.fc6(rois_feat)
  62. fc6 = F.relu(fc6)
  63. fc7 = self.fc7(fc6)
  64. fc7 = F.relu(fc7)
  65. return fc7
  66. @register
  67. class XConvNormHead(nn.Layer):
  68. __shared__ = ['norm_type', 'freeze_norm']
  69. """
  70. RCNN bbox head with serveral convolution layers
  71. Args:
  72. in_channel (int): Input channels which can be derived by from_config
  73. num_convs (int): The number of conv layers
  74. conv_dim (int): The number of channels for the conv layers
  75. out_channel (int): Output channels
  76. resolution (int): Resolution of input feature map
  77. norm_type (string): Norm type, bn, gn, sync_bn are available,
  78. default `gn`
  79. freeze_norm (bool): Whether to freeze the norm
  80. stage_name (string): Prefix name for conv layer, '' by default
  81. """
  82. def __init__(self,
  83. in_channel=256,
  84. num_convs=4,
  85. conv_dim=256,
  86. out_channel=1024,
  87. resolution=7,
  88. norm_type='gn',
  89. freeze_norm=False,
  90. stage_name=''):
  91. super(XConvNormHead, self).__init__()
  92. self.in_channel = in_channel
  93. self.num_convs = num_convs
  94. self.conv_dim = conv_dim
  95. self.out_channel = out_channel
  96. self.norm_type = norm_type
  97. self.freeze_norm = freeze_norm
  98. self.bbox_head_convs = []
  99. fan = conv_dim * 3 * 3
  100. initializer = KaimingNormal(fan_in=fan)
  101. for i in range(self.num_convs):
  102. in_c = in_channel if i == 0 else conv_dim
  103. head_conv_name = stage_name + 'bbox_head_conv{}'.format(i)
  104. head_conv = self.add_sublayer(
  105. head_conv_name,
  106. ConvNormLayer(
  107. ch_in=in_c,
  108. ch_out=conv_dim,
  109. filter_size=3,
  110. stride=1,
  111. norm_type=self.norm_type,
  112. freeze_norm=self.freeze_norm,
  113. initializer=initializer))
  114. self.bbox_head_convs.append(head_conv)
  115. fan = conv_dim * resolution * resolution
  116. self.fc6 = nn.Linear(
  117. conv_dim * resolution * resolution,
  118. out_channel,
  119. weight_attr=paddle.ParamAttr(
  120. initializer=XavierUniform(fan_out=fan)),
  121. bias_attr=paddle.ParamAttr(
  122. learning_rate=2., regularizer=L2Decay(0.)))
  123. @classmethod
  124. def from_config(cls, cfg, input_shape):
  125. s = input_shape
  126. s = s[0] if isinstance(s, (list, tuple)) else s
  127. return {'in_channel': s.channels}
  128. @property
  129. def out_shape(self):
  130. return [ShapeSpec(channels=self.out_channel, )]
  131. def forward(self, rois_feat):
  132. for i in range(self.num_convs):
  133. rois_feat = F.relu(self.bbox_head_convs[i](rois_feat))
  134. rois_feat = paddle.flatten(rois_feat, start_axis=1, stop_axis=-1)
  135. fc6 = F.relu(self.fc6(rois_feat))
  136. return fc6
  137. @register
  138. class BBoxHead(nn.Layer):
  139. __shared__ = ['num_classes']
  140. __inject__ = ['bbox_assigner', 'bbox_loss']
  141. """
  142. RCNN bbox head
  143. Args:
  144. head (nn.Layer): Extract feature in bbox head
  145. in_channel (int): Input channel after RoI extractor
  146. roi_extractor (object): The module of RoI Extractor
  147. bbox_assigner (object): The module of Box Assigner, label and sample the
  148. box.
  149. with_pool (bool): Whether to use pooling for the RoI feature.
  150. num_classes (int): The number of classes
  151. bbox_weight (List[float]): The weight to get the decode box
  152. """
  153. def __init__(self,
  154. head,
  155. in_channel,
  156. roi_extractor=RoIAlign().__dict__,
  157. bbox_assigner='BboxAssigner',
  158. with_pool=False,
  159. num_classes=80,
  160. bbox_weight=[10., 10., 5., 5.],
  161. bbox_loss=None):
  162. super(BBoxHead, self).__init__()
  163. self.head = head
  164. self.roi_extractor = roi_extractor
  165. if isinstance(roi_extractor, dict):
  166. self.roi_extractor = RoIAlign(**roi_extractor)
  167. self.bbox_assigner = bbox_assigner
  168. self.with_pool = with_pool
  169. self.num_classes = num_classes
  170. self.bbox_weight = bbox_weight
  171. self.bbox_loss = bbox_loss
  172. self.bbox_score = nn.Linear(
  173. in_channel,
  174. self.num_classes + 1,
  175. weight_attr=paddle.ParamAttr(initializer=Normal(
  176. mean=0.0, std=0.01)))
  177. self.bbox_score.skip_quant = True
  178. self.bbox_delta = nn.Linear(
  179. in_channel,
  180. 4 * self.num_classes,
  181. weight_attr=paddle.ParamAttr(initializer=Normal(
  182. mean=0.0, std=0.001)))
  183. self.bbox_delta.skip_quant = True
  184. self.assigned_label = None
  185. self.assigned_rois = None
  186. @classmethod
  187. def from_config(cls, cfg, input_shape):
  188. roi_pooler = cfg['roi_extractor']
  189. assert isinstance(roi_pooler, dict)
  190. kwargs = RoIAlign.from_config(cfg, input_shape)
  191. roi_pooler.update(kwargs)
  192. kwargs = {'input_shape': input_shape}
  193. head = create(cfg['head'], **kwargs)
  194. return {
  195. 'roi_extractor': roi_pooler,
  196. 'head': head,
  197. 'in_channel': head.out_shape[0].channels
  198. }
  199. def forward(self, body_feats=None, rois=None, rois_num=None, inputs=None):
  200. """
  201. body_feats (list[Tensor]): Feature maps from backbone
  202. rois (list[Tensor]): RoIs generated from RPN module
  203. rois_num (Tensor): The number of RoIs in each image
  204. inputs (dict{Tensor}): The ground-truth of image
  205. """
  206. if self.training:
  207. rois, rois_num, targets = self.bbox_assigner(rois, rois_num, inputs)
  208. self.assigned_rois = (rois, rois_num)
  209. self.assigned_targets = targets
  210. rois_feat = self.roi_extractor(body_feats, rois, rois_num)
  211. bbox_feat = self.head(rois_feat)
  212. if self.with_pool:
  213. feat = F.adaptive_avg_pool2d(bbox_feat, output_size=1)
  214. feat = paddle.squeeze(feat, axis=[2, 3])
  215. else:
  216. feat = bbox_feat
  217. scores = self.bbox_score(feat)
  218. deltas = self.bbox_delta(feat)
  219. if self.training:
  220. loss = self.get_loss(scores, deltas, targets, rois,
  221. self.bbox_weight)
  222. return loss, bbox_feat
  223. else:
  224. pred = self.get_prediction(scores, deltas)
  225. return pred, self.head
  226. def get_loss(self, scores, deltas, targets, rois, bbox_weight):
  227. """
  228. scores (Tensor): scores from bbox head outputs
  229. deltas (Tensor): deltas from bbox head outputs
  230. targets (list[List[Tensor]]): bbox targets containing tgt_labels, tgt_bboxes and tgt_gt_inds
  231. rois (List[Tensor]): RoIs generated in each batch
  232. """
  233. cls_name = 'loss_bbox_cls'
  234. reg_name = 'loss_bbox_reg'
  235. loss_bbox = {}
  236. # TODO: better pass args
  237. tgt_labels, tgt_bboxes, tgt_gt_inds = targets
  238. # bbox cls
  239. tgt_labels = paddle.concat(tgt_labels) if len(
  240. tgt_labels) > 1 else tgt_labels[0]
  241. valid_inds = paddle.nonzero(tgt_labels >= 0).flatten()
  242. if valid_inds.shape[0] == 0:
  243. loss_bbox[cls_name] = paddle.zeros([1], dtype='float32')
  244. else:
  245. tgt_labels = tgt_labels.cast('int64')
  246. tgt_labels.stop_gradient = True
  247. loss_bbox_cls = F.cross_entropy(
  248. input=scores, label=tgt_labels, reduction='mean')
  249. loss_bbox[cls_name] = loss_bbox_cls
  250. # bbox reg
  251. cls_agnostic_bbox_reg = deltas.shape[1] == 4
  252. fg_inds = paddle.nonzero(
  253. paddle.logical_and(tgt_labels >= 0, tgt_labels <
  254. self.num_classes)).flatten()
  255. if fg_inds.numel() == 0:
  256. loss_bbox[reg_name] = paddle.zeros([1], dtype='float32')
  257. return loss_bbox
  258. if cls_agnostic_bbox_reg:
  259. reg_delta = paddle.gather(deltas, fg_inds)
  260. else:
  261. fg_gt_classes = paddle.gather(tgt_labels, fg_inds)
  262. reg_row_inds = paddle.arange(fg_gt_classes.shape[0]).unsqueeze(1)
  263. reg_row_inds = paddle.tile(reg_row_inds, [1, 4]).reshape([-1, 1])
  264. reg_col_inds = 4 * fg_gt_classes.unsqueeze(1) + paddle.arange(4)
  265. reg_col_inds = reg_col_inds.reshape([-1, 1])
  266. reg_inds = paddle.concat([reg_row_inds, reg_col_inds], axis=1)
  267. reg_delta = paddle.gather(deltas, fg_inds)
  268. reg_delta = paddle.gather_nd(reg_delta, reg_inds).reshape([-1, 4])
  269. rois = paddle.concat(rois) if len(rois) > 1 else rois[0]
  270. tgt_bboxes = paddle.concat(tgt_bboxes) if len(
  271. tgt_bboxes) > 1 else tgt_bboxes[0]
  272. reg_target = bbox2delta(rois, tgt_bboxes, bbox_weight)
  273. reg_target = paddle.gather(reg_target, fg_inds)
  274. reg_target.stop_gradient = True
  275. if self.bbox_loss is not None:
  276. reg_delta = self.bbox_transform(reg_delta)
  277. reg_target = self.bbox_transform(reg_target)
  278. loss_bbox_reg = self.bbox_loss(
  279. reg_delta, reg_target).sum() / tgt_labels.shape[0]
  280. loss_bbox_reg *= self.num_classes
  281. else:
  282. loss_bbox_reg = paddle.abs(reg_delta - reg_target).sum(
  283. ) / tgt_labels.shape[0]
  284. loss_bbox[reg_name] = loss_bbox_reg
  285. return loss_bbox
  286. def bbox_transform(self, deltas, weights=[0.1, 0.1, 0.2, 0.2]):
  287. wx, wy, ww, wh = weights
  288. deltas = paddle.reshape(deltas, shape=(0, -1, 4))
  289. dx = paddle.slice(deltas, axes=[2], starts=[0], ends=[1]) * wx
  290. dy = paddle.slice(deltas, axes=[2], starts=[1], ends=[2]) * wy
  291. dw = paddle.slice(deltas, axes=[2], starts=[2], ends=[3]) * ww
  292. dh = paddle.slice(deltas, axes=[2], starts=[3], ends=[4]) * wh
  293. dw = paddle.clip(dw, -1.e10, np.log(1000. / 16))
  294. dh = paddle.clip(dh, -1.e10, np.log(1000. / 16))
  295. pred_ctr_x = dx
  296. pred_ctr_y = dy
  297. pred_w = paddle.exp(dw)
  298. pred_h = paddle.exp(dh)
  299. x1 = pred_ctr_x - 0.5 * pred_w
  300. y1 = pred_ctr_y - 0.5 * pred_h
  301. x2 = pred_ctr_x + 0.5 * pred_w
  302. y2 = pred_ctr_y + 0.5 * pred_h
  303. x1 = paddle.reshape(x1, shape=(-1, ))
  304. y1 = paddle.reshape(y1, shape=(-1, ))
  305. x2 = paddle.reshape(x2, shape=(-1, ))
  306. y2 = paddle.reshape(y2, shape=(-1, ))
  307. return paddle.concat([x1, y1, x2, y2])
  308. def get_prediction(self, score, delta):
  309. bbox_prob = F.softmax(score)
  310. return delta, bbox_prob
  311. def get_head(self, ):
  312. return self.head
  313. def get_assigned_targets(self, ):
  314. return self.assigned_targets
  315. def get_assigned_rois(self, ):
  316. return self.assigned_rois