Code scaled dot-product self-attention in NumPy
8 steps · about 3 h 20 min · Intermediate
- Separate queries, keys and values conceptually (reference, Wikipedia, 20 min)
Defines how soft dictionary lookup weights value vectors by query-key compatibility.
- Trace how attention evolved from seq2seq to self-attention (article, Lilian Weng, 30 min)
Places additive, multiplicative and self-attention side by side so the motivation is unmistakable.
- Derive the self-attention matrix step by step (article, Peter Bloem, 35 min)
Explains why scaling by the square root of head dimension keeps softmax gradients well behaved.
- Build single-head and multi-head attention from scratch (tutorial, Sebastian Raschka, 30 min)
Walks through projection matrices, attention weights and context vectors with explicit dimensions.
- Express batched head projections cleanly with einsum (reference, NumPy, 15 min)
Makes multi-head dot products readable without error-prone manual transposes and reshapes.
- Mask future tokens for autoregressive decoding (reference, NumPy, 15 min)
Shows how a lower-triangular mask sets upper-triangle logits to negative infinity before softmax.
- Compare your NumPy output with PyTorch's reference (reference, PyTorch, 15 min)
Provides the exact mathematical contract for validating shapes, masks and numerical agreement.
- See how self-attention fits into a full transformer block (tutorial, Harvard NLP, 40 min)
Connects multi-head attention to residual connections, layer normalization and feed-forward layers.