"""Complete-target CE with bounded vocabulary logits and a single tail backward pass.""" import torch from torch.nn import functional as F def target_loss(hidden,head,labels,chunk_size=8,backward=False): if chunk_size<1:raise ValueError('Chunk size must be positive') positions=(labels[0,1:]!=-100).nonzero().flatten() if hidden.shape[0]!=1 or labels.shape[0]!=1 or not len(positions):raise ValueError('Require one example with target tokens') leaf=hidden.detach().requires_grad_(True) if backward else hidden total=0.;count=len(positions) for offset in range(0,count,chunk_size): selected=positions[offset:offset+chunk_size] logits=head(leaf[:,selected,:]).float() loss=F.cross_entropy(logits.reshape(-1,logits.shape[-1]),labels[:,selected+1].reshape(-1),reduction='sum')/count if not torch.isfinite(loss):raise RuntimeError('Nonfinite target loss') total+=loss.detach().item() if backward:loss.backward() if backward:hidden.backward(leaf.grad) return total,count