How would you verify that a from-scratch multi-head attention implementation is correct?

Last updated 22 November 2026

  • Strongest test: copy your weights into torch.nn.MultiheadAttention (or use F.scaled_dot_product_attention) and assert torch.allclose across masks, batch sizes, lengths and head counts.

  • Test invariants: output shape (B, T, d_model), attention rows ≥ 0 and summing to 1, no causal leakage (perturbing future tokens leaves earlier outputs unchanged), pad contents not affecting real tokens, and no NaN on fully masked rows.

  • Sanity-check training: overfit a tiny batch (loss near 0), use gradcheck in float64 for custom kernels, and compare fp16/bf16 against fp32 with a looser tolerance.

  • https://sanjayasubedi.com.np/deeplearning/multihead-attention-from-scratch/
  • https://discuss.pytorch.org/t/which-multihead-attention-implementation-is-correct/198996
  • https://github.com/lowoncuties/VSB-FEI-Machine-Learning-Exercises/blob/main/ML_08_Attention_Mechanisms_PyTorch.ipynb
All Transformers interview questions