How would you verify that a from-scratch multi-head attention implementation is correct?
Last updated
Strongest test: copy your weights into
torch.nn.MultiheadAttention(or useF.scaled_dot_product_attention) and asserttorch.allcloseacross 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
gradcheckin float64 for custom kernels, and compare fp16/bf16 against fp32 with a looser tolerance.