gfocal_loss.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. # The code is based on:
  15. # https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/losses/gfocal_loss.py
  16. from __future__ import absolute_import
  17. from __future__ import division
  18. from __future__ import print_function
  19. import numpy as np
  20. import paddle
  21. import paddle.nn as nn
  22. import paddle.nn.functional as F
  23. from ppdet.core.workspace import register, serializable
  24. from ppdet.modeling import ops
  25. __all__ = ['QualityFocalLoss', 'DistributionFocalLoss']
  26. def quality_focal_loss(pred, target, beta=2.0, use_sigmoid=True):
  27. """
  28. Quality Focal Loss (QFL) is from `Generalized Focal Loss: Learning
  29. Qualified and Distributed Bounding Boxes for Dense Object Detection
  30. <https://arxiv.org/abs/2006.04388>`_.
  31. Args:
  32. pred (Tensor): Predicted joint representation of classification
  33. and quality (IoU) estimation with shape (N, C), C is the number of
  34. classes.
  35. target (tuple([Tensor])): Target category label with shape (N,)
  36. and target quality label with shape (N,).
  37. beta (float): The beta parameter for calculating the modulating factor.
  38. Defaults to 2.0.
  39. Returns:
  40. Tensor: Loss tensor with shape (N,).
  41. """
  42. assert len(target) == 2, """target for QFL must be a tuple of two elements,
  43. including category label and quality label, respectively"""
  44. # label denotes the category id, score denotes the quality score
  45. label, score = target
  46. if use_sigmoid:
  47. func = F.binary_cross_entropy_with_logits
  48. else:
  49. func = F.binary_cross_entropy
  50. # negatives are supervised by 0 quality score
  51. pred_sigmoid = F.sigmoid(pred) if use_sigmoid else pred
  52. scale_factor = pred_sigmoid
  53. zerolabel = paddle.zeros(pred.shape, dtype='float32')
  54. loss = func(pred, zerolabel, reduction='none') * scale_factor.pow(beta)
  55. # FG cat_id: [0, num_classes -1], BG cat_id: num_classes
  56. bg_class_ind = pred.shape[1]
  57. pos = paddle.logical_and((label >= 0),
  58. (label < bg_class_ind)).nonzero().squeeze(1)
  59. if pos.shape[0] == 0:
  60. return loss.sum(axis=1)
  61. pos_label = paddle.gather(label, pos, axis=0)
  62. pos_mask = np.zeros(pred.shape, dtype=np.int32)
  63. pos_mask[pos.numpy(), pos_label.numpy()] = 1
  64. pos_mask = paddle.to_tensor(pos_mask, dtype='bool')
  65. score = score.unsqueeze(-1).expand([-1, pred.shape[1]]).cast('float32')
  66. # positives are supervised by bbox quality (IoU) score
  67. scale_factor_new = score - pred_sigmoid
  68. loss_pos = func(
  69. pred, score, reduction='none') * scale_factor_new.abs().pow(beta)
  70. loss = loss * paddle.logical_not(pos_mask) + loss_pos * pos_mask
  71. loss = loss.sum(axis=1)
  72. return loss
  73. def distribution_focal_loss(pred, label):
  74. """Distribution Focal Loss (DFL) is from `Generalized Focal Loss: Learning
  75. Qualified and Distributed Bounding Boxes for Dense Object Detection
  76. <https://arxiv.org/abs/2006.04388>`_.
  77. Args:
  78. pred (Tensor): Predicted general distribution of bounding boxes
  79. (before softmax) with shape (N, n+1), n is the max value of the
  80. integral set `{0, ..., n}` in paper.
  81. label (Tensor): Target distance label for bounding boxes with
  82. shape (N,).
  83. Returns:
  84. Tensor: Loss tensor with shape (N,).
  85. """
  86. dis_left = label.cast('int64')
  87. dis_right = dis_left + 1
  88. weight_left = dis_right.cast('float32') - label
  89. weight_right = label - dis_left.cast('float32')
  90. loss = F.cross_entropy(pred, dis_left, reduction='none') * weight_left \
  91. + F.cross_entropy(pred, dis_right, reduction='none') * weight_right
  92. return loss
  93. @register
  94. @serializable
  95. class QualityFocalLoss(nn.Layer):
  96. r"""Quality Focal Loss (QFL) is a variant of `Generalized Focal Loss:
  97. Learning Qualified and Distributed Bounding Boxes for Dense Object
  98. Detection <https://arxiv.org/abs/2006.04388>`_.
  99. Args:
  100. use_sigmoid (bool): Whether sigmoid operation is conducted in QFL.
  101. Defaults to True.
  102. beta (float): The beta parameter for calculating the modulating factor.
  103. Defaults to 2.0.
  104. reduction (str): Options are "none", "mean" and "sum".
  105. loss_weight (float): Loss weight of current loss.
  106. """
  107. def __init__(self,
  108. use_sigmoid=True,
  109. beta=2.0,
  110. reduction='mean',
  111. loss_weight=1.0):
  112. super(QualityFocalLoss, self).__init__()
  113. self.use_sigmoid = use_sigmoid
  114. self.beta = beta
  115. assert reduction in ('none', 'mean', 'sum')
  116. self.reduction = reduction
  117. self.loss_weight = loss_weight
  118. def forward(self, pred, target, weight=None, avg_factor=None):
  119. """Forward function.
  120. Args:
  121. pred (Tensor): Predicted joint representation of
  122. classification and quality (IoU) estimation with shape (N, C),
  123. C is the number of classes.
  124. target (tuple([Tensor])): Target category label with shape
  125. (N,) and target quality label with shape (N,).
  126. weight (Tensor, optional): The weight of loss for each
  127. prediction. Defaults to None.
  128. avg_factor (int, optional): Average factor that is used to average
  129. the loss. Defaults to None.
  130. """
  131. loss = self.loss_weight * quality_focal_loss(
  132. pred, target, beta=self.beta, use_sigmoid=self.use_sigmoid)
  133. if weight is not None:
  134. loss = loss * weight
  135. if avg_factor is None:
  136. if self.reduction == 'none':
  137. return loss
  138. elif self.reduction == 'mean':
  139. return loss.mean()
  140. elif self.reduction == 'sum':
  141. return loss.sum()
  142. else:
  143. # if reduction is mean, then average the loss by avg_factor
  144. if self.reduction == 'mean':
  145. loss = loss.sum() / avg_factor
  146. # if reduction is 'none', then do nothing, otherwise raise an error
  147. elif self.reduction != 'none':
  148. raise ValueError(
  149. 'avg_factor can not be used with reduction="sum"')
  150. return loss
  151. @register
  152. @serializable
  153. class DistributionFocalLoss(nn.Layer):
  154. """Distribution Focal Loss (DFL) is a variant of `Generalized Focal Loss:
  155. Learning Qualified and Distributed Bounding Boxes for Dense Object
  156. Detection <https://arxiv.org/abs/2006.04388>`_.
  157. Args:
  158. reduction (str): Options are `'none'`, `'mean'` and `'sum'`.
  159. loss_weight (float): Loss weight of current loss.
  160. """
  161. def __init__(self, reduction='mean', loss_weight=1.0):
  162. super(DistributionFocalLoss, self).__init__()
  163. assert reduction in ('none', 'mean', 'sum')
  164. self.reduction = reduction
  165. self.loss_weight = loss_weight
  166. def forward(self, pred, target, weight=None, avg_factor=None):
  167. """Forward function.
  168. Args:
  169. pred (Tensor): Predicted general distribution of bounding
  170. boxes (before softmax) with shape (N, n+1), n is the max value
  171. of the integral set `{0, ..., n}` in paper.
  172. target (Tensor): Target distance label for bounding boxes
  173. with shape (N,).
  174. weight (Tensor, optional): The weight of loss for each
  175. prediction. Defaults to None.
  176. avg_factor (int, optional): Average factor that is used to average
  177. the loss. Defaults to None.
  178. """
  179. loss = self.loss_weight * distribution_focal_loss(pred, target)
  180. if weight is not None:
  181. loss = loss * weight
  182. if avg_factor is None:
  183. if self.reduction == 'none':
  184. return loss
  185. elif self.reduction == 'mean':
  186. return loss.mean()
  187. elif self.reduction == 'sum':
  188. return loss.sum()
  189. else:
  190. # if reduction is mean, then average the loss by avg_factor
  191. if self.reduction == 'mean':
  192. loss = loss.sum() / avg_factor
  193. # if reduction is 'none', then do nothing, otherwise raise an error
  194. elif self.reduction != 'none':
  195. raise ValueError(
  196. 'avg_factor can not be used with reduction="sum"')
  197. return loss