ar_loss.py 675 B

1234567891011121314151617181920212223
  1. import torch.nn.functional as F
  2. from torch import nn
  3. class ARLoss(nn.Module):
  4. def __init__(self, label_smoothing=0.1, ignore_index=0, **kwargs):
  5. super(ARLoss, self).__init__()
  6. self.label_smoothing = label_smoothing
  7. def forward(self, pred, batch):
  8. max_len = batch[2].max()
  9. tgt = batch[1][:, 1:2 + max_len]
  10. pred = pred.flatten(0, 1)
  11. tgt = tgt.reshape([-1])
  12. loss = F.cross_entropy(
  13. pred,
  14. tgt,
  15. reduction='mean',
  16. label_smoothing=self.label_smoothing,
  17. ignore_index=pred.shape[1] + 1,
  18. ) # self.loss_func(pred, tgt)
  19. return {'loss': loss}