rec_nrtr_loss.py 1.06 KB
Newer Older
Topdu's avatar
Topdu committed
1
2
3
4
5
6
import paddle
from paddle import nn
import paddle.nn.functional as F


class NRTRLoss(nn.Layer):
Topdu's avatar
Topdu committed
7
    def __init__(self, smoothing=True, **kwargs):
Topdu's avatar
Topdu committed
8
        super(NRTRLoss, self).__init__()
Topdu's avatar
Topdu committed
9
        self.loss_func = nn.CrossEntropyLoss(reduction='mean', ignore_index=0)
Topdu's avatar
Topdu committed
10
11
12
13
14
        self.smoothing = smoothing

    def forward(self, pred, batch):
        pred = pred.reshape([-1, pred.shape[2]])
        max_len = batch[2].max()
Topdu's avatar
Topdu committed
15
16
        tgt = batch[1][:, 1:2 + max_len]
        tgt = tgt.reshape([-1])
Topdu's avatar
Topdu committed
17
18
19
20
21
22
        if self.smoothing:
            eps = 0.1
            n_class = pred.shape[1]
            one_hot = F.one_hot(tgt, pred.shape[1])
            one_hot = one_hot * (1 - eps) + (1 - one_hot) * eps / (n_class - 1)
            log_prb = F.log_softmax(pred, axis=1)
Topdu's avatar
Topdu committed
23
24
            non_pad_mask = paddle.not_equal(
                tgt, paddle.zeros(
topduke's avatar
topduke committed
25
                    tgt.shape, dtype=tgt.dtype))
Topdu's avatar
Topdu committed
26
27
28
29
30
            loss = -(one_hot * log_prb).sum(axis=1)
            loss = loss.masked_select(non_pad_mask).mean()
        else:
            loss = self.loss_func(pred, tgt)
        return {'loss': loss}