File size: 1,362 Bytes
643267a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Fixed memory-efficient PAT training objective."""

import torch
from torch.nn import functional as F

from .config import EOD_ID


def pat_training_loss(hidden, weight, targets):
    """Fuse vocabulary projection and CE with the publication's FP32 sum."""
    from liger_kernel.transformers.functional import liger_fused_linear_cross_entropy

    loss_sum = liger_fused_linear_cross_entropy(
        hidden,
        weight,
        targets.contiguous(),
        bias=None,
        ce_weight=None,
        ignore_index=-100,
        lse_square_scale=0.0,
        label_smoothing=0.0,
        reduction="sum",
        softcap=None,
        return_z_loss=False,
        accum_dtype=torch.float32,
        use_token_scaling=False,
        return_token_accuracy=False,
        return_predicted_tokens=False,
    )
    with torch.no_grad():
        special = targets.eq(EOD_ID)
        if not bool(special.any().item()):
            lexical_sum = loss_sum.detach()
        elif bool(special.all().item()):
            lexical_sum = loss_sum.detach().new_zeros(())
        else:
            special_logits = F.linear(hidden[special], weight)
            special_loss = F.cross_entropy(
                special_logits, targets[special], reduction="sum"
            ).float()
            lexical_sum = loss_sum.detach() - special_loss
    return loss_sum, lexical_sum