Practice track

Transformers from scratch

Attention, heads, positions and normalization: the parts of a transformer block. 9 problems, about 235 minutes. Do them in order: each problem uses ideas from the problems before it.

0 / 9 solved

  1. 01
    LayerNorm and RMSNorm

    LayerNorm with gamma and beta and RMSNorm with a weight, both over the last axis, with eps inside the square root.

    From The Full Transformer — Encoder + Decoder

    ImplementEasy15 min
  2. 02
    Sinusoidal positional encoding

    Build the sin and cos position table with interleaved columns and base 10000, and add it to a batch of token embeddings.

    From Positional Encoding — Sinusoidal, RoPE, ALiBi

    ImplementEasy15 min
  3. 03
    Fixed-capacity KV cache

    Append keys and values to a preallocated cache, attend one query over the valid prefix, and reject an append past the capacity.

    From KV Cache, Flash Attention & Inference Optimization

    ImplementMedium25 min
  4. 04
    Rotary position embedding

    Rotate adjacent coordinate pairs of queries and keys by position times base^(-2i/d), so attention scores depend only on the position gap.

    From Positional Encoding — Sinusoidal, RoPE, ALiBi

    ImplementMedium25 min
  5. 05
    Scaled dot-product attention with a mask

    Batched softmax(QK^T / sqrt(d_k)) V with an optional boolean mask, plus the causal mask that a decoder uses.

    From Self-Attention from Scratch

    ImplementMedium25 min
  6. 06
    Grouped-query attention

    GQA forward with H query heads and G shared key and value groups, plus mean pooling of a multi-head checkpoint into groups.

    From Multi-Head Attention

    ResearchMedium30 min
  7. 07
    Top-k MoE gating and the Switch load-balancing loss

    Route tokens to the top k experts with renormalized softmax gates, and compute the Switch Transformer auxiliary loss E times sum f_i P_i.

    From Mixture of Experts (MoE)

    ResearchMedium30 min
  8. 08
    Split heads, merge heads, multi-head attention

    Reshape (B, T, D) into H heads and back, then run batched multi-head self-attention with given projection matrices.

    From Multi-Head Attention

    ImplementMedium30 min
  9. 09
    Tiled attention with an online softmax

    FlashAttention in numpy: a running max and a running sum over key blocks give exact attention for any block size.

    From KV Cache, Flash Attention & Inference Optimization

    ResearchHard40 min