fcos_loss.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import paddle
  18. import paddle.nn as nn
  19. import paddle.nn.functional as F
  20. from ppdet.core.workspace import register
  21. from ppdet.modeling import ops
  22. __all__ = ['FCOSLoss']
  23. def flatten_tensor(inputs, channel_first=False):
  24. """
  25. Flatten a Tensor
  26. Args:
  27. inputs (Tensor): 4-D Tensor with shape [N, C, H, W] or [N, H, W, C]
  28. channel_first (bool): If true the dimension order of Tensor is
  29. [N, C, H, W], otherwise is [N, H, W, C]
  30. Return:
  31. output_channel_last (Tensor): The flattened Tensor in channel_last style
  32. """
  33. if channel_first:
  34. input_channel_last = paddle.transpose(inputs, perm=[0, 2, 3, 1])
  35. else:
  36. input_channel_last = inputs
  37. output_channel_last = paddle.flatten(
  38. input_channel_last, start_axis=0, stop_axis=2)
  39. return output_channel_last
  40. @register
  41. class FCOSLoss(nn.Layer):
  42. """
  43. FCOSLoss
  44. Args:
  45. loss_alpha (float): alpha in focal loss
  46. loss_gamma (float): gamma in focal loss
  47. iou_loss_type (str): location loss type, IoU/GIoU/LINEAR_IoU
  48. reg_weights (float): weight for location loss
  49. """
  50. def __init__(self,
  51. loss_alpha=0.25,
  52. loss_gamma=2.0,
  53. iou_loss_type="giou",
  54. reg_weights=1.0):
  55. super(FCOSLoss, self).__init__()
  56. self.loss_alpha = loss_alpha
  57. self.loss_gamma = loss_gamma
  58. self.iou_loss_type = iou_loss_type
  59. self.reg_weights = reg_weights
  60. def __iou_loss(self, pred, targets, positive_mask, weights=None):
  61. """
  62. Calculate the loss for location prediction
  63. Args:
  64. pred (Tensor): bounding boxes prediction
  65. targets (Tensor): targets for positive samples
  66. positive_mask (Tensor): mask of positive samples
  67. weights (Tensor): weights for each positive samples
  68. Return:
  69. loss (Tensor): location loss
  70. """
  71. plw = pred[:, 0] * positive_mask
  72. pth = pred[:, 1] * positive_mask
  73. prw = pred[:, 2] * positive_mask
  74. pbh = pred[:, 3] * positive_mask
  75. tlw = targets[:, 0] * positive_mask
  76. tth = targets[:, 1] * positive_mask
  77. trw = targets[:, 2] * positive_mask
  78. tbh = targets[:, 3] * positive_mask
  79. tlw.stop_gradient = True
  80. trw.stop_gradient = True
  81. tth.stop_gradient = True
  82. tbh.stop_gradient = True
  83. ilw = paddle.minimum(plw, tlw)
  84. irw = paddle.minimum(prw, trw)
  85. ith = paddle.minimum(pth, tth)
  86. ibh = paddle.minimum(pbh, tbh)
  87. clw = paddle.maximum(plw, tlw)
  88. crw = paddle.maximum(prw, trw)
  89. cth = paddle.maximum(pth, tth)
  90. cbh = paddle.maximum(pbh, tbh)
  91. area_predict = (plw + prw) * (pth + pbh)
  92. area_target = (tlw + trw) * (tth + tbh)
  93. area_inter = (ilw + irw) * (ith + ibh)
  94. ious = (area_inter + 1.0) / (
  95. area_predict + area_target - area_inter + 1.0)
  96. ious = ious * positive_mask
  97. if self.iou_loss_type.lower() == "linear_iou":
  98. loss = 1.0 - ious
  99. elif self.iou_loss_type.lower() == "giou":
  100. area_uniou = area_predict + area_target - area_inter
  101. area_circum = (clw + crw) * (cth + cbh) + 1e-7
  102. giou = ious - (area_circum - area_uniou) / area_circum
  103. loss = 1.0 - giou
  104. elif self.iou_loss_type.lower() == "iou":
  105. loss = 0.0 - paddle.log(ious)
  106. else:
  107. raise KeyError
  108. if weights is not None:
  109. loss = loss * weights
  110. return loss
  111. def forward(self, cls_logits, bboxes_reg, centerness, tag_labels,
  112. tag_bboxes, tag_center):
  113. """
  114. Calculate the loss for classification, location and centerness
  115. Args:
  116. cls_logits (list): list of Tensor, which is predicted
  117. score for all anchor points with shape [N, M, C]
  118. bboxes_reg (list): list of Tensor, which is predicted
  119. offsets for all anchor points with shape [N, M, 4]
  120. centerness (list): list of Tensor, which is predicted
  121. centerness for all anchor points with shape [N, M, 1]
  122. tag_labels (list): list of Tensor, which is category
  123. targets for each anchor point
  124. tag_bboxes (list): list of Tensor, which is bounding
  125. boxes targets for positive samples
  126. tag_center (list): list of Tensor, which is centerness
  127. targets for positive samples
  128. Return:
  129. loss (dict): loss composed by classification loss, bounding box
  130. """
  131. cls_logits_flatten_list = []
  132. bboxes_reg_flatten_list = []
  133. centerness_flatten_list = []
  134. tag_labels_flatten_list = []
  135. tag_bboxes_flatten_list = []
  136. tag_center_flatten_list = []
  137. num_lvl = len(cls_logits)
  138. for lvl in range(num_lvl):
  139. cls_logits_flatten_list.append(
  140. flatten_tensor(cls_logits[lvl], True))
  141. bboxes_reg_flatten_list.append(
  142. flatten_tensor(bboxes_reg[lvl], True))
  143. centerness_flatten_list.append(
  144. flatten_tensor(centerness[lvl], True))
  145. tag_labels_flatten_list.append(
  146. flatten_tensor(tag_labels[lvl], False))
  147. tag_bboxes_flatten_list.append(
  148. flatten_tensor(tag_bboxes[lvl], False))
  149. tag_center_flatten_list.append(
  150. flatten_tensor(tag_center[lvl], False))
  151. cls_logits_flatten = paddle.concat(cls_logits_flatten_list, axis=0)
  152. bboxes_reg_flatten = paddle.concat(bboxes_reg_flatten_list, axis=0)
  153. centerness_flatten = paddle.concat(centerness_flatten_list, axis=0)
  154. tag_labels_flatten = paddle.concat(tag_labels_flatten_list, axis=0)
  155. tag_bboxes_flatten = paddle.concat(tag_bboxes_flatten_list, axis=0)
  156. tag_center_flatten = paddle.concat(tag_center_flatten_list, axis=0)
  157. tag_labels_flatten.stop_gradient = True
  158. tag_bboxes_flatten.stop_gradient = True
  159. tag_center_flatten.stop_gradient = True
  160. mask_positive_bool = tag_labels_flatten > 0
  161. mask_positive_bool.stop_gradient = True
  162. mask_positive_float = paddle.cast(mask_positive_bool, dtype="float32")
  163. mask_positive_float.stop_gradient = True
  164. num_positive_fp32 = paddle.sum(mask_positive_float)
  165. num_positive_fp32.stop_gradient = True
  166. num_positive_int32 = paddle.cast(num_positive_fp32, dtype="int32")
  167. num_positive_int32 = num_positive_int32 * 0 + 1
  168. num_positive_int32.stop_gradient = True
  169. normalize_sum = paddle.sum(tag_center_flatten * mask_positive_float)
  170. normalize_sum.stop_gradient = True
  171. # 1. cls_logits: sigmoid_focal_loss
  172. # expand onehot labels
  173. num_classes = cls_logits_flatten.shape[-1]
  174. tag_labels_flatten = paddle.squeeze(tag_labels_flatten, axis=-1)
  175. tag_labels_flatten_bin = F.one_hot(
  176. tag_labels_flatten, num_classes=1 + num_classes)
  177. tag_labels_flatten_bin = tag_labels_flatten_bin[:, 1:]
  178. # sigmoid_focal_loss
  179. cls_loss = F.sigmoid_focal_loss(
  180. cls_logits_flatten, tag_labels_flatten_bin) / num_positive_fp32
  181. # 2. bboxes_reg: giou_loss
  182. mask_positive_float = paddle.squeeze(mask_positive_float, axis=-1)
  183. tag_center_flatten = paddle.squeeze(tag_center_flatten, axis=-1)
  184. reg_loss = self.__iou_loss(
  185. bboxes_reg_flatten,
  186. tag_bboxes_flatten,
  187. mask_positive_float,
  188. weights=tag_center_flatten)
  189. reg_loss = reg_loss * mask_positive_float / normalize_sum
  190. # 3. centerness: sigmoid_cross_entropy_with_logits_loss
  191. centerness_flatten = paddle.squeeze(centerness_flatten, axis=-1)
  192. ctn_loss = ops.sigmoid_cross_entropy_with_logits(centerness_flatten,
  193. tag_center_flatten)
  194. ctn_loss = ctn_loss * mask_positive_float / num_positive_fp32
  195. loss_all = {
  196. "loss_centerness": paddle.sum(ctn_loss),
  197. "loss_cls": paddle.sum(cls_loss),
  198. "loss_box": paddle.sum(reg_loss)
  199. }
  200. return loss_all