Code scaled dot-product self-attention in NumPy

8 steps · about 3 h 20 min · Intermediate

  1. Separate queries, keys and values conceptually (reference, Wikipedia, 20 min)

    Defines how soft dictionary lookup weights value vectors by query-key compatibility.

  2. 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.

  3. 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.

  4. 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.

  5. Express batched head projections cleanly with einsum (reference, NumPy, 15 min)

    Makes multi-head dot products readable without error-prone manual transposes and reshapes.

  6. 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.

  7. Compare your NumPy output with PyTorch's reference (reference, PyTorch, 15 min)

    Provides the exact mathematical contract for validating shapes, masks and numerical agreement.

  8. 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.