ace_loss.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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, ignore_index=0, reduction="none", soft_label=True, axis=-1
  25. )
  26. def __call__(self, predicts, batch):
  27. if isinstance(predicts, (list, tuple)):
  28. predicts = predicts[-1]
  29. B, N = predicts.shape[:2]
  30. div = paddle.to_tensor([N]).astype("float32")
  31. predicts = nn.functional.softmax(predicts, axis=-1)
  32. aggregation_preds = paddle.sum(predicts, axis=1)
  33. aggregation_preds = paddle.divide(aggregation_preds, div)
  34. length = batch[2].astype("float32")
  35. batch = batch[3].astype("float32")
  36. batch[:, 0] = paddle.subtract(div, length)
  37. batch = paddle.divide(batch, div)
  38. loss = self.loss_func(aggregation_preds, batch)
  39. return {"loss_ace": loss}