rec_cppd_loss.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # copyright (c) 2023 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. import paddle
  15. from paddle import nn
  16. import paddle.nn.functional as F
  17. class CPPDLoss(nn.Layer):
  18. def __init__(
  19. self, smoothing=False, ignore_index=100, sideloss_weight=1.0, **kwargs
  20. ):
  21. super(CPPDLoss, self).__init__()
  22. self.edge_ce = nn.CrossEntropyLoss(reduction="mean", ignore_index=ignore_index)
  23. self.char_node_ce = nn.CrossEntropyLoss(reduction="mean")
  24. self.pos_node_ce = nn.BCEWithLogitsLoss(reduction="mean")
  25. self.smoothing = smoothing
  26. self.ignore_index = ignore_index
  27. self.sideloss_weight = sideloss_weight
  28. def label_smoothing_ce(self, preds, targets):
  29. non_pad_mask = paddle.not_equal(
  30. targets,
  31. paddle.zeros(targets.shape, dtype=targets.dtype) + self.ignore_index,
  32. )
  33. tgts = paddle.where(
  34. targets
  35. == (paddle.zeros(targets.shape, dtype=targets.dtype) + self.ignore_index),
  36. paddle.zeros(targets.shape, dtype=targets.dtype),
  37. targets,
  38. )
  39. eps = 0.1
  40. n_class = preds.shape[1]
  41. one_hot = F.one_hot(tgts, preds.shape[1])
  42. one_hot = one_hot * (1 - eps) + (1 - one_hot) * eps / (n_class - 1)
  43. log_prb = F.log_softmax(preds, axis=1)
  44. loss = -(one_hot * log_prb).sum(axis=1)
  45. loss = loss.masked_select(non_pad_mask).mean()
  46. return loss
  47. def forward(self, pred, batch):
  48. node_feats, edge_feats = pred
  49. node_tgt = batch[2]
  50. char_tgt = batch[1]
  51. loss_char_node = self.char_node_ce(
  52. node_feats[0].flatten(0, 1), node_tgt[:, :-26].flatten(0, 1)
  53. )
  54. loss_pos_node = self.pos_node_ce(
  55. node_feats[1].flatten(0, 1), node_tgt[:, -26:].flatten(0, 1).cast("float32")
  56. )
  57. loss_node = loss_char_node + loss_pos_node
  58. edge_feats = edge_feats.flatten(0, 1)
  59. char_tgt = char_tgt.flatten(0, 1)
  60. if self.smoothing:
  61. loss_edge = self.label_smoothing_ce(edge_feats, char_tgt)
  62. else:
  63. loss_edge = self.edge_ce(edge_feats, char_tgt)
  64. return {
  65. "loss": self.sideloss_weight * loss_node + loss_edge,
  66. "loss_node": self.sideloss_weight * loss_node,
  67. "loss_edge": loss_edge,
  68. }