Batch LM cross-entropy with ignore index, perplexity and gradient
Why it matters Every LM training step and every perplexity number comes from this computation, and the ignore index is how padding and prompts are excluded.
Training and evaluating a language model both start from the same quantity: the mean cross-entropy over all real target tokens in a (B, T, V) batch, skipping ignored positions.
Write lm_cross_entropy(logits, targets, ignore=-100). logits is (B, T, V); targets is (B, T) with ignore at positions that do not count (at least one position counts). Let N be the number of counted positions. Return (loss, ppl, dlogits):
- loss = mean over counted positions of -log_softmax(logits)[target] (stable)
- ppl = exp(loss)
- dlogits (B, T, V) = (softmax - onehot(target)) / N at counted positions and 0 at ignored positions.
def lm_cross_entropy(logits, targets, ignore=-100)Example
lm_cross_entropy(np.zeros((1, 2, 2)), [[0, -100]]) is (0.6931, 2.0, [[[-0.5, 0.5], [0, 0]]]).
Understand the idea
Cross-entropy measures how surprised the model is by the true next token: -log of the probability it gave that token. Averaging over many tokens gives the loss, and exp(loss) is perplexity, roughly "how many tokens the model is choosing between".
Example: two positions, vocabulary of 2, all logits 0, so each token has probability 0.5. Position 0 has target 0; position 1 is padding (-100). Only one position counts, so the loss is -ln 0.5 = 0.693 and the perplexity is 2. The gradient at position 0 is softmax minus one-hot: [0.5 - 1, 0.5] = [-0.5, 0.5], divided by N = 1. Position 1 gets zero gradient.
Rule: loss = (1 / N) sum over counted (b, t) of -log softmax(z_bt)[y_bt]; dz = (softmax - onehot) / N on counted positions.
Dividing by N, not B*T, keeps the loss scale the same no matter how much padding a batch has. Deep learning libraries implement exactly this with an ignore_index argument.
Shapes and data flow
logits (B, T, V) -> (B*T, V); targets (B*T,); valid mask (B*T,); dlogits (B, T, V)