rec_aster_loss.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import paddle
  18. from paddle import nn
  19. class CosineEmbeddingLoss(nn.Layer):
  20. def __init__(self, margin=0.0):
  21. super(CosineEmbeddingLoss, self).__init__()
  22. self.margin = margin
  23. self.epsilon = 1e-12
  24. def forward(self, x1, x2, target):
  25. similarity = paddle.sum(x1 * x2, axis=-1) / (
  26. paddle.norm(x1, axis=-1) * paddle.norm(x2, axis=-1) + self.epsilon
  27. )
  28. one_list = paddle.full_like(target, fill_value=1)
  29. out = paddle.mean(
  30. paddle.where(
  31. paddle.equal(target, one_list),
  32. 1.0 - similarity,
  33. paddle.maximum(paddle.zeros_like(similarity), similarity - self.margin),
  34. )
  35. )
  36. return out
  37. class AsterLoss(nn.Layer):
  38. def __init__(
  39. self,
  40. weight=None,
  41. size_average=True,
  42. ignore_index=-100,
  43. sequence_normalize=False,
  44. sample_normalize=True,
  45. **kwargs,
  46. ):
  47. super(AsterLoss, self).__init__()
  48. self.weight = weight
  49. self.size_average = size_average
  50. self.ignore_index = ignore_index
  51. self.sequence_normalize = sequence_normalize
  52. self.sample_normalize = sample_normalize
  53. self.loss_sem = CosineEmbeddingLoss()
  54. self.is_cosin_loss = True
  55. self.loss_func_rec = nn.CrossEntropyLoss(weight=None, reduction="none")
  56. def forward(self, predicts, batch):
  57. targets = batch[1].astype("int64")
  58. label_lengths = batch[2].astype("int64")
  59. sem_target = batch[3].astype("float32")
  60. embedding_vectors = predicts["embedding_vectors"]
  61. rec_pred = predicts["rec_pred"]
  62. if not self.is_cosin_loss:
  63. sem_loss = paddle.sum(self.loss_sem(embedding_vectors, sem_target))
  64. else:
  65. label_target = paddle.ones([embedding_vectors.shape[0]])
  66. sem_loss = paddle.sum(
  67. self.loss_sem(embedding_vectors, sem_target, label_target)
  68. )
  69. # rec loss
  70. batch_size, def_max_length = targets.shape[0], targets.shape[1]
  71. mask = paddle.zeros([batch_size, def_max_length])
  72. for i in range(batch_size):
  73. mask[i, : label_lengths[i]] = 1
  74. mask = paddle.cast(mask, "float32")
  75. max_length = max(label_lengths)
  76. assert max_length == rec_pred.shape[1]
  77. targets = targets[:, :max_length]
  78. mask = mask[:, :max_length]
  79. rec_pred = paddle.reshape(rec_pred, [-1, rec_pred.shape[2]])
  80. input = nn.functional.log_softmax(rec_pred, axis=1)
  81. targets = paddle.reshape(targets, [-1, 1])
  82. mask = paddle.reshape(mask, [-1, 1])
  83. output = -paddle.index_sample(input, index=targets) * mask
  84. output = paddle.sum(output)
  85. if self.sequence_normalize:
  86. output = output / paddle.sum(mask)
  87. if self.sample_normalize:
  88. output = output / batch_size
  89. loss = output + sem_loss * 0.1
  90. return {"loss": loss}