centernet_head.py 7.0 KB

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