smooth_l1_loss.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 paddlex.ppdet.core.workspace import register
  21. __all__ = ['SmoothL1Loss']
  22. @register
  23. class SmoothL1Loss(nn.Layer):
  24. """Smooth L1 Loss.
  25. Args:
  26. beta (float): controls smooth region, it becomes L1 Loss when beta=0.0
  27. loss_weight (float): the final loss will be multiplied by this
  28. """
  29. def __init__(self, beta=1.0, loss_weight=1.0):
  30. super(SmoothL1Loss, self).__init__()
  31. assert beta >= 0
  32. self.beta = beta
  33. self.loss_weight = loss_weight
  34. def forward(self, pred, target, reduction='none'):
  35. """forward function, based on fvcore.
  36. Args:
  37. pred (Tensor): prediction tensor
  38. target (Tensor): target tensor, pred.shape must be the same as target.shape
  39. reduction (str): the way to reduce loss, one of (none, sum, mean)
  40. """
  41. assert reduction in ('none', 'sum', 'mean')
  42. target = target.detach()
  43. if self.beta < 1e-5:
  44. loss = paddle.abs(pred - target)
  45. else:
  46. n = paddle.abs(pred - target)
  47. cond = n < self.beta
  48. loss = paddle.where(cond, 0.5 * n**2 / self.beta,
  49. n - 0.5 * self.beta)
  50. if reduction == 'mean':
  51. loss = loss.mean() if loss.size > 0 else 0.0 * loss.sum()
  52. elif reduction == 'sum':
  53. loss = loss.sum()
  54. return loss * self.loss_weight