rec_aster_loss.py 3.6 KB

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