"""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