centernet_head.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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 KaimingUniform
  19. from paddlex.ppdet.core.workspace import register
  20. from paddlex.ppdet.modeling.losses import CTFocalLoss
  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=KaimingUniform())
  36. if bias:
  37. bias_attr = paddle.ParamAttr(
  38. initializer=nn.initializer.Uniform(-bound, bound))
  39. self.conv = nn.Conv2D(
  40. in_channels=ch_in,
  41. out_channels=ch_out,
  42. kernel_size=kernel_size,
  43. stride=stride,
  44. padding=padding,
  45. dilation=dilation,
  46. groups=groups,
  47. weight_attr=param_attr,
  48. bias_attr=bias_attr)
  49. def forward(self, inputs):
  50. out = self.conv(inputs)
  51. return out
  52. @register
  53. class CenterNetHead(nn.Layer):
  54. """
  55. Args:
  56. in_channels (int): the channel number of input to CenterNetHead.
  57. num_classes (int): the number of classes, 80 by default.
  58. head_planes (int): the channel number in all head, 256 by default.
  59. heatmap_weight (float): the weight of heatmap loss, 1 by default.
  60. regress_ltrb (bool): whether to regress left/top/right/bottom or
  61. width/height for a box, true by default
  62. size_weight (float): the weight of box size loss, 0.1 by default.
  63. offset_weight (float): the weight of center offset loss, 1 by default.
  64. """
  65. __shared__ = ['num_classes']
  66. def __init__(self,
  67. in_channels,
  68. num_classes=80,
  69. head_planes=256,
  70. heatmap_weight=1,
  71. regress_ltrb=True,
  72. size_weight=0.1,
  73. offset_weight=1):
  74. super(CenterNetHead, self).__init__()
  75. self.weights = {
  76. 'heatmap': heatmap_weight,
  77. 'size': size_weight,
  78. 'offset': offset_weight
  79. }
  80. self.heatmap = nn.Sequential(
  81. ConvLayer(
  82. in_channels, head_planes, kernel_size=3, padding=1, bias=True),
  83. nn.ReLU(),
  84. ConvLayer(
  85. head_planes,
  86. num_classes,
  87. kernel_size=1,
  88. stride=1,
  89. padding=0,
  90. bias=True))
  91. with paddle.no_grad():
  92. self.heatmap[2].conv.bias[:] = -2.19
  93. self.size = nn.Sequential(
  94. ConvLayer(
  95. in_channels, head_planes, kernel_size=3, padding=1, bias=True),
  96. nn.ReLU(),
  97. ConvLayer(
  98. head_planes,
  99. 4 if regress_ltrb else 2,
  100. kernel_size=1,
  101. stride=1,
  102. padding=0,
  103. bias=True))
  104. self.offset = nn.Sequential(
  105. ConvLayer(
  106. in_channels, head_planes, kernel_size=3, padding=1, bias=True),
  107. nn.ReLU(),
  108. ConvLayer(
  109. head_planes, 2, kernel_size=1, stride=1, padding=0, bias=True))
  110. self.focal_loss = CTFocalLoss()
  111. @classmethod
  112. def from_config(cls, cfg, input_shape):
  113. if isinstance(input_shape, (list, tuple)):
  114. input_shape = input_shape[0]
  115. return {'in_channels': input_shape.channels}
  116. def forward(self, feat, inputs):
  117. heatmap = self.heatmap(feat)
  118. size = self.size(feat)
  119. offset = self.offset(feat)
  120. if self.training:
  121. loss = self.get_loss(heatmap, size, offset, self.weights, inputs)
  122. return loss
  123. else:
  124. heatmap = F.sigmoid(heatmap)
  125. return {'heatmap': heatmap, 'size': size, 'offset': offset}
  126. def get_loss(self, heatmap, size, offset, weights, inputs):
  127. heatmap_target = inputs['heatmap']
  128. size_target = inputs['size']
  129. offset_target = inputs['offset']
  130. index = inputs['index']
  131. mask = inputs['index_mask']
  132. heatmap = paddle.clip(F.sigmoid(heatmap), 1e-4, 1 - 1e-4)
  133. heatmap_loss = self.focal_loss(heatmap, heatmap_target)
  134. size = paddle.transpose(size, perm=[0, 2, 3, 1])
  135. size_n, size_h, size_w, size_c = size.shape
  136. size = paddle.reshape(size, shape=[size_n, -1, size_c])
  137. index = paddle.unsqueeze(index, 2)
  138. batch_inds = list()
  139. for i in range(size_n):
  140. batch_ind = paddle.full(
  141. shape=[1, index.shape[1], 1], fill_value=i, dtype='int64')
  142. batch_inds.append(batch_ind)
  143. batch_inds = paddle.concat(batch_inds, axis=0)
  144. index = paddle.concat(x=[batch_inds, index], axis=2)
  145. pos_size = paddle.gather_nd(size, index=index)
  146. mask = paddle.unsqueeze(mask, axis=2)
  147. size_mask = paddle.expand_as(mask, pos_size)
  148. size_mask = paddle.cast(size_mask, dtype=pos_size.dtype)
  149. pos_num = size_mask.sum()
  150. size_mask.stop_gradient = True
  151. size_target.stop_gradient = True
  152. size_loss = F.l1_loss(
  153. pos_size * size_mask, size_target * size_mask, reduction='sum')
  154. size_loss = size_loss / (pos_num + 1e-4)
  155. offset = paddle.transpose(offset, perm=[0, 2, 3, 1])
  156. offset_n, offset_h, offset_w, offset_c = offset.shape
  157. offset = paddle.reshape(offset, shape=[offset_n, -1, offset_c])
  158. pos_offset = paddle.gather_nd(offset, index=index)
  159. offset_mask = paddle.expand_as(mask, pos_offset)
  160. offset_mask = paddle.cast(offset_mask, dtype=pos_offset.dtype)
  161. pos_num = offset_mask.sum()
  162. offset_mask.stop_gradient = True
  163. offset_target.stop_gradient = True
  164. offset_loss = F.l1_loss(
  165. pos_offset * offset_mask,
  166. offset_target * offset_mask,
  167. reduction='sum')
  168. offset_loss = offset_loss / (pos_num + 1e-4)
  169. det_loss = weights['heatmap'] * heatmap_loss + weights[
  170. 'size'] * size_loss + weights['offset'] * offset_loss
  171. return {
  172. 'det_loss': det_loss,
  173. 'heatmap_loss': heatmap_loss,
  174. 'size_loss': size_loss,
  175. 'offset_loss': offset_loss
  176. }