Normalize sequence loss by valid tokens
Padded sequence positions should not train the model, and their count should not dilute the reported loss. Mask them before normalization and divide by the number of valid targets. An all-padding batch needs an explicit finite result with a valid zero-gradient connection.
The exercise uses real log-softmax and gather operations over logits. It checks both forward values and backward gradients. Token masking is separate from attention masking: one controls which targets contribute to the objective, while the other controls which context positions can influence predictions. A correct loss mask cannot repair future-token leakage in attention.
import torch
logits=torch.tensor([[0.,0.],[0.,0.]])
logp=torch.nn.functional.log_softmax(logits,dim=-1)
print(-logp[0,1].item())Review the design
Masking and normalization define the optimization objective. Counting padded tokens in the denominator silently changes the effective learning rate as sequence lengths change between batches.
Your task
Implement masked_ce(logits,targets,pad=-1), logits shape [N,C], targets [N]. Mean negative log probability over non-pad targets only. Return logits.sum()*0 for all padding so backward works. Valid non-pad targets are class indices.
The explanation opens here once every check passes.