ssd_loss.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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 ..bbox_utils import iou_similarity, bbox2delta
  22. __all__ = ['SSDLoss']
  23. @register
  24. class SSDLoss(nn.Layer):
  25. """
  26. SSDLoss
  27. Args:
  28. overlap_threshold (float32, optional): IoU threshold for negative bboxes
  29. and positive bboxes, 0.5 by default.
  30. neg_pos_ratio (float): The ratio of negative samples / positive samples.
  31. loc_loss_weight (float): The weight of loc_loss.
  32. conf_loss_weight (float): The weight of conf_loss.
  33. prior_box_var (list): Variances corresponding to prior box coord, [0.1,
  34. 0.1, 0.2, 0.2] by default.
  35. """
  36. def __init__(self,
  37. overlap_threshold=0.5,
  38. neg_pos_ratio=3.0,
  39. loc_loss_weight=1.0,
  40. conf_loss_weight=1.0,
  41. prior_box_var=[0.1, 0.1, 0.2, 0.2]):
  42. super(SSDLoss, self).__init__()
  43. self.overlap_threshold = overlap_threshold
  44. self.neg_pos_ratio = neg_pos_ratio
  45. self.loc_loss_weight = loc_loss_weight
  46. self.conf_loss_weight = conf_loss_weight
  47. self.prior_box_var = [1. / a for a in prior_box_var]
  48. def _bipartite_match_for_batch(self, gt_bbox, gt_label, prior_boxes,
  49. bg_index):
  50. """
  51. Args:
  52. gt_bbox (Tensor): [B, N, 4]
  53. gt_label (Tensor): [B, N, 1]
  54. prior_boxes (Tensor): [A, 4]
  55. bg_index (int): Background class index
  56. """
  57. batch_size, num_priors = gt_bbox.shape[0], prior_boxes.shape[0]
  58. ious = iou_similarity(gt_bbox.reshape((-1, 4)), prior_boxes).reshape(
  59. (batch_size, -1, num_priors))
  60. # For each prior box, get the max IoU of all GTs.
  61. prior_max_iou, prior_argmax_iou = ious.max(axis=1), ious.argmax(axis=1)
  62. # For each GT, get the max IoU of all prior boxes.
  63. gt_max_iou, gt_argmax_iou = ious.max(axis=2), ious.argmax(axis=2)
  64. # Gather target bbox and label according to 'prior_argmax_iou' index.
  65. batch_ind = paddle.arange(end=batch_size, dtype='int64').unsqueeze(-1)
  66. prior_argmax_iou = paddle.stack(
  67. [batch_ind.tile([1, num_priors]), prior_argmax_iou], axis=-1)
  68. targets_bbox = paddle.gather_nd(gt_bbox, prior_argmax_iou)
  69. targets_label = paddle.gather_nd(gt_label, prior_argmax_iou)
  70. # Assign negative
  71. bg_index_tensor = paddle.full([batch_size, num_priors, 1], bg_index,
  72. 'int64')
  73. targets_label = paddle.where(
  74. prior_max_iou.unsqueeze(-1) < self.overlap_threshold,
  75. bg_index_tensor, targets_label)
  76. # Ensure each GT can match the max IoU prior box.
  77. batch_ind = (batch_ind * num_priors + gt_argmax_iou).flatten()
  78. targets_bbox = paddle.scatter(
  79. targets_bbox.reshape([-1, 4]), batch_ind,
  80. gt_bbox.reshape([-1, 4])).reshape([batch_size, -1, 4])
  81. targets_label = paddle.scatter(
  82. targets_label.reshape([-1, 1]), batch_ind,
  83. gt_label.reshape([-1, 1])).reshape([batch_size, -1, 1])
  84. targets_label[:, :1] = bg_index
  85. # Encode box
  86. prior_boxes = prior_boxes.unsqueeze(0).tile([batch_size, 1, 1])
  87. targets_bbox = bbox2delta(
  88. prior_boxes.reshape([-1, 4]),
  89. targets_bbox.reshape([-1, 4]), self.prior_box_var)
  90. targets_bbox = targets_bbox.reshape([batch_size, -1, 4])
  91. return targets_bbox, targets_label
  92. def _mine_hard_example(self,
  93. conf_loss,
  94. targets_label,
  95. bg_index,
  96. mine_neg_ratio=0.01):
  97. pos = (targets_label != bg_index).astype(conf_loss.dtype)
  98. num_pos = pos.sum(axis=1, keepdim=True)
  99. neg = (targets_label == bg_index).astype(conf_loss.dtype)
  100. conf_loss = conf_loss.detach() * neg
  101. loss_idx = conf_loss.argsort(axis=1, descending=True)
  102. idx_rank = loss_idx.argsort(axis=1)
  103. num_negs = []
  104. for i in range(conf_loss.shape[0]):
  105. cur_num_pos = num_pos[i]
  106. num_neg = paddle.clip(
  107. cur_num_pos * self.neg_pos_ratio, max=pos.shape[1])
  108. num_neg = num_neg if num_neg > 0 else paddle.to_tensor(
  109. [pos.shape[1] * mine_neg_ratio])
  110. num_negs.append(num_neg)
  111. num_negs = paddle.stack(num_negs).expand_as(idx_rank)
  112. neg_mask = (idx_rank < num_negs).astype(conf_loss.dtype)
  113. return (neg_mask + pos).astype('bool')
  114. def forward(self, boxes, scores, gt_bbox, gt_label, prior_boxes):
  115. boxes = paddle.concat(boxes, axis=1)
  116. scores = paddle.concat(scores, axis=1)
  117. gt_label = gt_label.unsqueeze(-1).astype('int64')
  118. prior_boxes = paddle.concat(prior_boxes, axis=0)
  119. bg_index = scores.shape[-1] - 1
  120. # Match bbox and get targets.
  121. targets_bbox, targets_label = \
  122. self._bipartite_match_for_batch(gt_bbox, gt_label, prior_boxes, bg_index)
  123. targets_bbox.stop_gradient = True
  124. targets_label.stop_gradient = True
  125. # Compute regression loss.
  126. # Select positive samples.
  127. bbox_mask = paddle.tile(targets_label != bg_index, [1, 1, 4])
  128. if bbox_mask.astype(boxes.dtype).sum() > 0:
  129. location = paddle.masked_select(boxes, bbox_mask)
  130. targets_bbox = paddle.masked_select(targets_bbox, bbox_mask)
  131. loc_loss = F.smooth_l1_loss(location, targets_bbox, reduction='sum')
  132. loc_loss = loc_loss * self.loc_loss_weight
  133. else:
  134. loc_loss = paddle.zeros([1])
  135. # Compute confidence loss.
  136. conf_loss = F.cross_entropy(scores, targets_label, reduction="none")
  137. # Mining hard examples.
  138. label_mask = self._mine_hard_example(
  139. conf_loss.squeeze(-1), targets_label.squeeze(-1), bg_index)
  140. conf_loss = paddle.masked_select(conf_loss, label_mask.unsqueeze(-1))
  141. conf_loss = conf_loss.sum() * self.conf_loss_weight
  142. # Compute overall weighted loss.
  143. normalizer = (targets_label != bg_index).astype('float32').sum().clip(
  144. min=1)
  145. loss = (conf_loss + loc_loss) / normalizer
  146. return loss