A hand-written transformer language model trains, but its validation loss is suspiciously low and its generations are poor. Which bugs do you look for first?
Answer
Model answer, written in a candidate's voice
In short
- Check causal leakage first: logits at position t must not change when future tokens change.
- Verify targets are shifted by one and padding is masked out of the loss.
- Check position indexing/positional embeddings/rotary offsets against attention and cache.
- Check attention scaling by sqrt(d_k) and softmax axes: keys for attention, vocabulary for output.
- Compare train and inference paths: eval mode, dropout, masks, cache positions, sampling.
- Use teacher-forced vs cached generation and future-token perturbation as the decisive test.
In full
The first thing I would check is leakage: in a causal LM the logits at position t must be invariant to tokens after t, so I would perturb future tokens and confirm the loss/logits do not move; a missing or wrong causal mask is the classic cause of suspiciously low validation loss. Then I would verify the objective: targets are shifted by one so the model predicts x_{t+1} from x_{<=t}, padding is masked out of the loss rather than counted as easy labels, and position indices/positional embeddings/rotary offsets are aligned with the same indexing used for attention and cache. I would also check the attention maths: logits scaled by sqrt(d_k), attention softmax over keys, final softmax over vocabulary, and no accidental softmax over batch or sequence. Finally I would compare train and inference paths: eval mode, dropout off, same mask, same position indexing, and KV-cache positions/length so cached decoding matches teacher forcing; if teacher-forced loss is low but sampled generations are bad, I would inspect logits, top-k/temperature, and whether the cache is reusing stale positions.
What a strong answer covers
- A missing or wrong causal mask leaks future tokens, which explains the too-low loss.
- Targets not shifted by one position; padding tokens counted in the loss.
- Misindexed positions.
- Wrong scaling or softmax axis.
- Train/inference mismatch, e.g. cache positions.
- Test: check whether logits change when future tokens are changed.
Common mistakes
- Blaming hyperparameters.
- Missing the leakage hypothesis.