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.
- 01LayerNorm and RMSNorm
LayerNorm with gamma and beta and RMSNorm with a weight, both over the last axis, with eps inside the square root.
ImplementEasy15 min - 02Sinusoidal positional encoding
Build the sin and cos position table with interleaved columns and base 10000, and add it to a batch of token embeddings.
ImplementEasy15 min - 03Fixed-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.
ImplementMedium25 min - 04Rotary 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.
ImplementMedium25 min - 05Scaled 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.
ImplementMedium25 min - 06Grouped-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 - 07Top-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.
ResearchMedium30 min - 08Split 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 - 09Tiled 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.
ResearchHard40 min