ace_loss.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
  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. # This code is refer from: https://github.com/viig99/LS-ACELoss
  15. from __future__ import absolute_import
  16. from __future__ import division
  17. from __future__ import print_function
  18. import paddle
  19. import paddle.nn as nn
  20. class ACELoss(nn.Layer):
  21. def __init__(self, **kwargs):
  22. super().__init__()
  23. self.loss_func = nn.CrossEntropyLoss(
  24. weight=None,
  25. ignore_index=0,
  26. reduction='none',
  27. soft_label=True,
  28. axis=-1)
  29. def __call__(self, predicts, batch):
  30. if isinstance(predicts, (list, tuple)):
  31. predicts = predicts[-1]
  32. B, N = predicts.shape[:2]
  33. div = paddle.to_tensor([N]).astype('float32')
  34. predicts = nn.functional.softmax(predicts, axis=-1)
  35. aggregation_preds = paddle.sum(predicts, axis=1)
  36. aggregation_preds = paddle.divide(aggregation_preds, div)
  37. length = batch[2].astype("float32")
  38. batch = batch[3].astype("float32")
  39. batch[:, 0] = paddle.subtract(div, length)
  40. batch = paddle.divide(batch, div)
  41. loss = self.loss_func(aggregation_preds, batch)
  42. return {"loss_ace": loss}