Skip to content
nonconvexcard

Implement multi-head attention from scratch

CodingIntermediate⏱ 3 hoursDeep Learningattentionimplementationcausal masknumerical stability

Problem

Implement multi-head self-attention with a causal mask, and verify the mathematics.

  1. Check that the attention matrix rows sum to one and that the causal mask is respected.
  2. Verify permutation equivariance numerically when the positional encoding is removed.
  3. Demonstrate softmax saturation by removing the 1/dk1/\sqrt{d_k} scaling.
  4. Verify that rotary embeddings make the logits depend only on the position difference.

Implement it, then check the implementation against something you can verify independently.

Write it

Solve it here5 tests · Python runs in your browser
⌘/Ctrl + ↵ to run · limit 30s · draft saved in this browser
5 tests will run against your code. The first run downloads the Python runtime — several megabytes, once per browser.

Solution

Opening this before you have a real attempt on paper is the fastest way to feel like you understand something you cannot reproduce.

Related problems

All problems
SolvedProblemFieldTypeDifficultyTime
When does attention dominate the MLP?Deep LearningNumericalBeginner30 min
Attention is permutation equivariantDeep LearningProofIntermediate30 min
Implement backpropagation from scratch runDeep LearningCodingIntermediate3 hours
Implement kernel ridge regression runClassical MLCodingIntermediate1 hour
Implement power iteration and verify the convergence rate runFoundationsCodingIntermediate1 hour