cross_entropy.py 2.36 KB
Newer Older
1
2
# Copyright (c) 2023, Tri Dao.

3
4
5
import torch
import torch.nn as nn

6
from flash_attn.ops.triton.cross_entropy import cross_entropy_loss
7
8
9


class CrossEntropyLoss(nn.Module):
Tri Dao's avatar
Tri Dao committed
10
11
12
13
14
    def __init__(
        self,
        ignore_index=-100,
        reduction="mean",
        label_smoothing=0.0,
15
        logit_scale=1.0,
16
        lse_square_scale=0.0,
Tri Dao's avatar
Tri Dao committed
17
18
19
        inplace_backward=False,
        process_group=None,
    ):
20
21
22
23
24
25
26
27
28
29
30
        """
        Arguments:
            ignored_index: int. If labels == ignored_index, the loss is set to 0.0.
            label_smoothing: float
            lse_square_scale: float. If > 0, we add lse_square_scale * lse(logits) ^ 2 to the loss.
                This is also referred to as "z-loss".
            inplace_backward: bool. If True, we do the backward pass in-place by modifying the logits.
                This saves memory.
            process_group: if not None, we're doing Tensor Parallel: each process is responsible for
            one part of the vocab. The loss will be aggregated across processes.
        """
31
        super().__init__()
32
33
        if reduction not in ["mean", "none", "sum"]:
            raise NotImplementedError("Only support reduction = 'mean' or 'none' or 'sum'")
34
35
36
        self.ignore_index = ignore_index
        self.reduction = reduction
        self.label_smoothing = label_smoothing
37
        self.logit_scale = logit_scale
38
        self.lse_square_scale = lse_square_scale
39
        self.inplace_backward = inplace_backward
40
        self.process_group = process_group
41

42
    def forward(self, input, target):
43
44
45
46
47
48
49
50
51
        """
        Arguments:
            input: (batch, vocab_size)
            target: (batch,)
        Returns:
            losses: (batch,) if reduction is 'none', else (1,), dtype float
        """
        assert input.is_cuda and target.is_cuda, "Only support CUDA tensors"
        loss = cross_entropy_loss(
Tri Dao's avatar
Tri Dao committed
52
53
            input,
            target,
54
            label_smoothing=self.label_smoothing,
55
            logit_scale=self.logit_scale,
56
57
58
59
            lse_square_scale=self.lse_square_scale,
            ignored_index=self.ignore_index,
            inplace_backward=self.inplace_backward,
            process_group=self.process_group,
60
        )
Tri Dao's avatar
Tri Dao committed
61
        if self.reduction == "mean":
62
            return loss.sum() / (target != self.ignore_index).sum()
63
64
        elif self.reduction == "sum":
            return loss.sum()
65
66
        else:
            return loss