-
Notifications
You must be signed in to change notification settings - Fork 200
Expand file tree
/
Copy pathmasked_ce.py
More file actions
86 lines (75 loc) · 3.47 KB
/
Copy pathmasked_ce.py
File metadata and controls
86 lines (75 loc) · 3.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributed.tensor import DTensor
class MaskedCrossEntropy(nn.Module):
def __init__(self, fp32_upcast: bool = True, ignore_index: int = -100, reduction: str = "sum"):
"""
Masked cross-entropy loss.
Args:
fp32_upcast (bool): if True it will cast logits to float32 before computing
cross entropy. Default: True.
ignore_index (int): label to ignore in CE calculation. Defaults to -100.
reduction (str): type of reduction. Defaults to "sum".
"""
super().__init__()
self.fp32_upcast = fp32_upcast
self.ignore_index = ignore_index
self.reduction = reduction
def forward(
self,
logits: torch.Tensor,
labels: torch.Tensor,
mask: Optional[torch.Tensor] = None,
num_label_tokens: Optional[int] = None,
) -> torch.Tensor:
"""
Compute the masked cross-entropy loss between logits and targets.
If a mask is provided, the loss is computed per element, multiplied by the mask,
and then averaged. If no mask is provided, the standard cross-entropy loss is used.
Args:
logits (torch.Tensor): The predicted logits with shape [batch_size, seq_len, vocab_size] where C is the number of classes.
labels (torch.Tensor): The ground truth class indices with shape [batch_size, seq_len].
mask (torch.Tensor, optional): A tensor that masks the loss computation. Items marked with
1 will be used to calculate loss, otherwise ignored. Must be broadcastable to the shape
of the loss. Defaults to None.
Returns:
torch.Tensor: The computed loss as a scalar tensor.
"""
# this may happen with CPUOffloadPolicy
if labels.device != logits.device:
labels = labels.to(logits.device) # pragma: no cover
# reshape to (N, C) and (N,) respectively
logits = logits.view(-1, logits.size(-1))
labels = labels.view(-1)
if mask is not None:
with torch.no_grad():
if mask.device != labels.device:
mask = mask.to(labels.device) # pragma: no cover
labels.masked_fill_(mask.view(-1) == 0, self.ignore_index)
del mask
if self.fp32_upcast:
logits = logits.float()
if isinstance(logits, DTensor):
logits = logits.full_tensor()
if isinstance(labels, DTensor):
labels = labels.full_tensor()
loss = F.cross_entropy(logits, labels, reduction=self.reduction)
if num_label_tokens is not None:
assert self.reduction == "sum", "num_label_tokens is only supported when reduction is 'sum'"
loss = loss / num_label_tokens
return loss