centernet_head.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. # Copyright (c) 2021 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 math
  15. import paddle
  16. import paddle.nn as nn
  17. import paddle.nn.functional as F
  18. from paddle.nn.initializer import Constant, Uniform
  19. from ppdet.core.workspace import register
  20. from ppdet.modeling.losses import CTFocalLoss, GIoULoss
  21. class ConvLayer(nn.Layer):
  22. def __init__(self,
  23. ch_in,
  24. ch_out,
  25. kernel_size,
  26. stride=1,
  27. padding=0,
  28. dilation=1,
  29. groups=1,
  30. bias=False):
  31. super(ConvLayer, self).__init__()
  32. bias_attr = False
  33. fan_in = ch_in * kernel_size**2
  34. bound = 1 / math.sqrt(fan_in)
  35. param_attr = paddle.ParamAttr(initializer=Uniform(-bound, bound))
  36. if bias:
  37. bias_attr = paddle.ParamAttr(initializer=Constant(0.))
  38. self.conv = nn.Conv2D(
  39. in_channels=ch_in,
  40. out_channels=ch_out,
  41. kernel_size=kernel_size,
  42. stride=stride,
  43. padding=padding,
  44. dilation=dilation,
  45. groups=groups,
  46. weight_attr=param_attr,
  47. bias_attr=bias_attr)
  48. def forward(self, inputs):
  49. out = self.conv(inputs)
  50. return out
  51. @register
  52. class CenterNetHead(nn.Layer):
  53. """
  54. Args:
  55. in_channels (int): the channel number of input to CenterNetHead.
  56. num_classes (int): the number of classes, 80 (COCO dataset) by default.
  57. head_planes (int): the channel number in all head, 256 by default.
  58. heatmap_weight (float): the weight of heatmap loss, 1 by default.
  59. regress_ltrb (bool): whether to regress left/top/right/bottom or
  60. width/height for a box, true by default
  61. size_weight (float): the weight of box size loss, 0.1 by default.
  62. size_loss (): the type of size regression loss, 'L1 loss' by default.
  63. offset_weight (float): the weight of center offset loss, 1 by default.
  64. iou_weight (float): the weight of iou head loss, 0 by default.
  65. """
  66. __shared__ = ['num_classes']
  67. def __init__(self,
  68. in_channels,
  69. num_classes=80,
  70. head_planes=256,
  71. heatmap_weight=1,
  72. regress_ltrb=True,
  73. size_weight=0.1,
  74. size_loss='L1',
  75. offset_weight=1,
  76. iou_weight=0):
  77. super(CenterNetHead, self).__init__()
  78. self.regress_ltrb = regress_ltrb
  79. self.weights = {
  80. 'heatmap': heatmap_weight,
  81. 'size': size_weight,
  82. 'offset': offset_weight,
  83. 'iou': iou_weight
  84. }
  85. # heatmap head
  86. self.heatmap = nn.Sequential(
  87. ConvLayer(
  88. in_channels, head_planes, kernel_size=3, padding=1, bias=True),
  89. nn.ReLU(),
  90. ConvLayer(
  91. head_planes,
  92. num_classes,
  93. kernel_size=1,
  94. stride=1,
  95. padding=0,
  96. bias=True))
  97. with paddle.no_grad():
  98. self.heatmap[2].conv.bias[:] = -2.19
  99. # size(ltrb or wh) head
  100. self.size = nn.Sequential(
  101. ConvLayer(
  102. in_channels, head_planes, kernel_size=3, padding=1, bias=True),
  103. nn.ReLU(),
  104. ConvLayer(
  105. head_planes,
  106. 4 if regress_ltrb else 2,
  107. kernel_size=1,
  108. stride=1,
  109. padding=0,
  110. bias=True))
  111. self.size_loss = size_loss
  112. # offset head
  113. self.offset = nn.Sequential(
  114. ConvLayer(
  115. in_channels, head_planes, kernel_size=3, padding=1, bias=True),
  116. nn.ReLU(),
  117. ConvLayer(
  118. head_planes, 2, kernel_size=1, stride=1, padding=0, bias=True))
  119. # iou head (optinal)
  120. if iou_weight > 0:
  121. self.iou = nn.Sequential(
  122. ConvLayer(
  123. in_channels,
  124. head_planes,
  125. kernel_size=3,
  126. padding=1,
  127. bias=True),
  128. nn.ReLU(),
  129. ConvLayer(
  130. head_planes,
  131. 4 if regress_ltrb else 2,
  132. kernel_size=1,
  133. stride=1,
  134. padding=0,
  135. bias=True))
  136. @classmethod
  137. def from_config(cls, cfg, input_shape):
  138. if isinstance(input_shape, (list, tuple)):
  139. input_shape = input_shape[0]
  140. return {'in_channels': input_shape.channels}
  141. def forward(self, feat, inputs):
  142. heatmap = self.heatmap(feat)
  143. size = self.size(feat)
  144. offset = self.offset(feat)
  145. iou = self.iou(feat) if hasattr(self, 'iou_weight') else None
  146. if self.training:
  147. loss = self.get_loss(
  148. inputs, self.weights, heatmap, size, offset, iou=iou)
  149. return loss
  150. else:
  151. heatmap = F.sigmoid(heatmap)
  152. head_outs = {'heatmap': heatmap, 'size': size, 'offset': offset}
  153. if iou is not None:
  154. head_outs.update({'iou': iou})
  155. return head_outs
  156. def get_loss(self, inputs, weights, heatmap, size, offset, iou=None):
  157. # heatmap head loss: CTFocalLoss
  158. heatmap_target = inputs['heatmap']
  159. heatmap = paddle.clip(F.sigmoid(heatmap), 1e-4, 1 - 1e-4)
  160. ctfocal_loss = CTFocalLoss()
  161. heatmap_loss = ctfocal_loss(heatmap, heatmap_target)
  162. # size head loss: L1 loss or GIoU loss
  163. index = inputs['index']
  164. mask = inputs['index_mask']
  165. size = paddle.transpose(size, perm=[0, 2, 3, 1])
  166. size_n, size_h, size_w, size_c = size.shape
  167. size = paddle.reshape(size, shape=[size_n, -1, size_c])
  168. index = paddle.unsqueeze(index, 2)
  169. batch_inds = list()
  170. for i in range(size_n):
  171. batch_ind = paddle.full(
  172. shape=[1, index.shape[1], 1], fill_value=i, dtype='int64')
  173. batch_inds.append(batch_ind)
  174. batch_inds = paddle.concat(batch_inds, axis=0)
  175. index = paddle.concat(x=[batch_inds, index], axis=2)
  176. pos_size = paddle.gather_nd(size, index=index)
  177. mask = paddle.unsqueeze(mask, axis=2)
  178. size_mask = paddle.expand_as(mask, pos_size)
  179. size_mask = paddle.cast(size_mask, dtype=pos_size.dtype)
  180. pos_num = size_mask.sum()
  181. size_mask.stop_gradient = True
  182. if self.size_loss == 'L1':
  183. if self.regress_ltrb:
  184. size_target = inputs['size']
  185. # shape: [bs, max_per_img, 4]
  186. else:
  187. if inputs['size'].shape[-1] == 2:
  188. # inputs['size'] is wh, and regress as wh
  189. # shape: [bs, max_per_img, 2]
  190. size_target = inputs['size']
  191. else:
  192. # inputs['size'] is ltrb, but regress as wh
  193. # shape: [bs, max_per_img, 4]
  194. size_target = inputs['size'][:, :, 0:2] + inputs['size'][:, :, 2:]
  195. size_target.stop_gradient = True
  196. size_loss = F.l1_loss(
  197. pos_size * size_mask, size_target * size_mask, reduction='sum')
  198. size_loss = size_loss / (pos_num + 1e-4)
  199. elif self.size_loss == 'giou':
  200. size_target = inputs['bbox_xys']
  201. size_target.stop_gradient = True
  202. centers_x = (size_target[:, :, 0:1] + size_target[:, :, 2:3]) / 2.0
  203. centers_y = (size_target[:, :, 1:2] + size_target[:, :, 3:4]) / 2.0
  204. x1 = centers_x - pos_size[:, :, 0:1]
  205. y1 = centers_y - pos_size[:, :, 1:2]
  206. x2 = centers_x + pos_size[:, :, 2:3]
  207. y2 = centers_y + pos_size[:, :, 3:4]
  208. pred_boxes = paddle.concat([x1, y1, x2, y2], axis=-1)
  209. giou_loss = GIoULoss(reduction='sum')
  210. size_loss = giou_loss(
  211. pred_boxes * size_mask,
  212. size_target * size_mask,
  213. iou_weight=size_mask,
  214. loc_reweight=None)
  215. size_loss = size_loss / (pos_num + 1e-4)
  216. # offset head loss: L1 loss
  217. offset_target = inputs['offset']
  218. offset = paddle.transpose(offset, perm=[0, 2, 3, 1])
  219. offset_n, offset_h, offset_w, offset_c = offset.shape
  220. offset = paddle.reshape(offset, shape=[offset_n, -1, offset_c])
  221. pos_offset = paddle.gather_nd(offset, index=index)
  222. offset_mask = paddle.expand_as(mask, pos_offset)
  223. offset_mask = paddle.cast(offset_mask, dtype=pos_offset.dtype)
  224. pos_num = offset_mask.sum()
  225. offset_mask.stop_gradient = True
  226. offset_target.stop_gradient = True
  227. offset_loss = F.l1_loss(
  228. pos_offset * offset_mask,
  229. offset_target * offset_mask,
  230. reduction='sum')
  231. offset_loss = offset_loss / (pos_num + 1e-4)
  232. # iou head loss: GIoU loss
  233. if iou is not None:
  234. iou = paddle.transpose(iou, perm=[0, 2, 3, 1])
  235. iou_n, iou_h, iou_w, iou_c = iou.shape
  236. iou = paddle.reshape(iou, shape=[iou_n, -1, iou_c])
  237. pos_iou = paddle.gather_nd(iou, index=index)
  238. iou_mask = paddle.expand_as(mask, pos_iou)
  239. iou_mask = paddle.cast(iou_mask, dtype=pos_iou.dtype)
  240. pos_num = iou_mask.sum()
  241. iou_mask.stop_gradient = True
  242. gt_bbox_xys = inputs['bbox_xys']
  243. gt_bbox_xys.stop_gradient = True
  244. centers_x = (gt_bbox_xys[:, :, 0:1] + gt_bbox_xys[:, :, 2:3]) / 2.0
  245. centers_y = (gt_bbox_xys[:, :, 1:2] + gt_bbox_xys[:, :, 3:4]) / 2.0
  246. x1 = centers_x - pos_size[:, :, 0:1]
  247. y1 = centers_y - pos_size[:, :, 1:2]
  248. x2 = centers_x + pos_size[:, :, 2:3]
  249. y2 = centers_y + pos_size[:, :, 3:4]
  250. pred_boxes = paddle.concat([x1, y1, x2, y2], axis=-1)
  251. giou_loss = GIoULoss(reduction='sum')
  252. iou_loss = giou_loss(
  253. pred_boxes * iou_mask,
  254. gt_bbox_xys * iou_mask,
  255. iou_weight=iou_mask,
  256. loc_reweight=None)
  257. iou_loss = iou_loss / (pos_num + 1e-4)
  258. losses = {
  259. 'heatmap_loss': heatmap_loss,
  260. 'size_loss': size_loss,
  261. 'offset_loss': offset_loss,
  262. }
  263. det_loss = weights['heatmap'] * heatmap_loss + weights[
  264. 'size'] * size_loss + weights['offset'] * offset_loss
  265. if iou is not None:
  266. losses.update({'iou_loss': iou_loss})
  267. det_loss = det_loss + weights['iou'] * iou_loss
  268. losses.update({'det_loss': det_loss})
  269. return losses