Module 18

Transformers

How does a transformer use differentiable algebra and attention to process relationships among elements in a sequence?

lessons
22
duration
38 h 15 min
concepts
115
available in English
22 / 22
completed by you
0 of 22

Where it fits

Overview

Build the transformer from attention as differentiable lookup. Work through self-attention, masks, multi-head attention, absolute and relative positions such as RoPE and ALiBi, residual flow, and the three main architecture families. Build a GPT in NumPy with a manual backward pass and a PyTorch version for the local GPU. Modernize the GPT with RMSNorm, SwiGLU, QK-norm, the KV cache, GQA, MLA, and mixture of experts. Study attention costs through FlashAttention, sparse attention, and linear attention. Finish with state space models and Mamba, their duality with attention, hybrid architectures, long context, and the theory of what a transformer can compute.

Why it matters

Transformers underpin LLMs, vision-language models, many robotic policies, and modern diffusion models. The GPT from scratch project builds directly on this module's code. Deriving the attention backward pass, budgeting a KV cache for 8 GB, reading specifications that include RoPE, GQA, SwiGLU, MoE, or Mamba, and explaining why FlashAttention is exact prepares you to debug training, read architecture papers, and propose your own variants.

Lessons 22

  1. 01Review: from seq2seq attention to differentiable lookupReview additive and multiplicative attention in recurrent encoder-decoder models, then express attention as differentiable key-value lookup and Nadaraya-Watson kernel smoothing. Compare recurrent, convolutional, and attention layers, and establish the tensor shapes and einsum notation used throughout this module.Review70 min
  2. 02Self-attention and scaled dot-product attentionDerive self-attention from query, key, and value projections of the same sequence. Study dot-product scaling, softmax invariance and saturation, and permutation equivariance. Implement the forward pass in NumPy and compare it with PyTorch. GPUCore100 min
  3. 03Masks: causality, padding and additive biasesBuild causal, padding, and document masks as additive biases before softmax. Study parallel autoregressive training, packed sequences, empty rows, numerical safety, ALiBi, and FlexAttention. GPUCore80 min
  4. 04Deriving the attention backward pass by handDerive the row-wise softmax vector-Jacobian product and chain it through matrix products to obtain attention gradients. Implement and check the backward pass, study saturation, and analyze activation memory. GPUCore100 min
  5. 05Multi-head attentionImplement multi-head attention with split and merged heads, derive the output as a sum of head contributions, and study QK and OV circuits, head redundancy, and ablations. GPUCore95 min
  6. 06Embeddings and absolute positional encodingsTurn tokens into vectors with embedding tables, study weight tying and the softmax bottleneck, and derive sinusoidal and learned positional encodings. Compare their behavior beyond training lengths. GPUCore90 min
  7. 07Relative position: relative biases, ALiBi and RoPEStudy relative position representations, T5 bucket biases, ALiBi, and RoPE. Derive RoPE with complex numbers, analyze its frequency spectrum, and implement and compare positional methods. GPUAdvanced110 min
  8. 08The transformer block: residual stream, normalization and feed-forward networkAssemble a transformer block from attention, position-wise feed-forward networks, residual connections, and normalization. Study gradients, rank collapse, parameter counts, and compute costs. GPUCore105 min
  9. 09Cross-attention and the original encoder-decoder transformerReconstruct an encoder-decoder transformer, implement cross-attention and its masks, train a synthetic sequence-to-sequence task, and compare it with recurrent attention and greedy decoding. GPUCore100 min
  10. 10Encoder-only, decoder-only and prefix LM: architecture familiesCompare encoder-only, decoder-only, encoder-decoder, and prefix language models by attention pattern, outputs, tasks, training, inference, and cache costs. GPUCore85 min
  11. 11GPT from scratch in NumPyBuild a complete character-level GPT in NumPy with manual forward and backward passes, verify its modules, train with AdamW, and generate text.Core120 min
  12. 12GPT in PyTorch: training on the local GPUCompare the NumPy GPT with PyTorch, then train a larger model locally while measuring memory, gradients, and controlled recipe ablations. GPUCore120 min
  13. 13The modern block: RMSNorm, SwiGLU, QK-norm and the anatomy of LlamaStudy RMSNorm, gated feed-forward networks, QK normalization, logit soft-capping, and transformer block arrangements with parameter-matched examples and measured ablations. GPUAdvanced110 min
  14. 14KV cache, MQA, GQA and latent attentionDerive KV-cache memory and incremental decoding, compare MHA, MQA, GQA, and latent attention, and test grouped conversion and rotary cache behavior. GPUAdvanced110 min
  15. 15Attention complexity and FlashAttentionDerive stable online softmax and tiled exact attention, analyze backward recomputation and memory traffic, and compare GPU attention backends. GPUAdvanced115 min
  16. 16Sparse, local and linear attentionCompare sparse and sliding-window attention with linear recurrent attention, positive random features, and associative recall. GPUAdvanced110 min
  17. 17Mixture of ExpertsStudy top-k mixture-of-experts routing, capacity, balancing, active and total parameters, and controlled experiments on specialization. GPUAdvanced120 min
  18. 18State space models: from linear recurrences to S4Discretize state-space models, derive recurrent and convolutional forms, study HiPPO and diagonal SSM stability, and compare small models on CIFAR-10. GPUResearch110 min
  19. 19Mamba: selective state space models and parallel scanStudy selective state-space dynamics, affine associative scans, hardware-aware implementations, and a small Mamba-style language model. GPUResearch115 min
  20. 20Attention-SSM duality and hybrid architecturesDerive structured state-space duality, chunkwise computation, delta-rule memory updates, and the quality and memory trade-offs of hybrid stacks. GPUResearch115 min
  21. 21Long context: extending RoPE and length generalizationExplore long-context extrapolation, RoPE scaling, attention sinks and measured retrieval. GPUResearch105 min
  22. 22What a transformer can computeExamine transformer expressivity, resource bounds and in-context learning through theory and experiments. GPUResearch110 min

Module capstone

A modern GPT from scratch, from NumPy to a configurable mini Llama

Start from the verified NumPy GPT and build a configurable decoder-only language model in PyTorch. Choose between layer norm and RMSNorm, GELU and SwiGLU, learned positions and RoPE, MHA and GQA, dense MLPs and MoE, and full attention or a hybrid with Mamba layers. Add a KV cache and incremental generation. Train up to about 30 million parameters on the RTX 4060 using a character corpus or an existing tokenizer as a black box. Module 20 covers BPE. Deliver a reproducible report with three-seed ablations measuring validation loss, training and generation tokens per second, peak memory, cache memory, and associative recall. Include automated tests of generation equivalence with and without the cache. The result forms the basis of the GPT from scratch project.

Check what you already know

  • Write batched attention with einsum and interpret it as soft lookup in a dictionary
  • Derive the 1/√d_k scale from dot-product variance and prove permutation equivariance
  • Combine causal, padding, and document masks without producing NaNs
  • Derive dQ, dK and dV for scaled attention, including the row-wise softmax VJP
  • Implement multi-head attention with the correct reshapes and transposes and interpret each head through its QK and OV circuits
  • Prove that with RoPE the dot product of a query and key depends only on relative position
  • Count parameters and FLOPs per token and explain pre-norm and post-norm
  • Explain the three attention operations in an encoder-decoder model and the mask on each
  • Implement a full GPT with manual forward and backward passes and verify it through gradient checks
  • Configure residual-scaled initialization and parameter groups for AdamW
  • Implement RMSNorm and SwiGLU and explain when to use QK-norm
  • Calculate GQA KV cache memory and explain why decoding is memory-bound
  • Derive online softmax and the tiled FlashAttention forward pass
  • Derive the recurrent form of causal linear attention
  • Implement a top-k router with a load-balancing loss and per-expert capacity
  • Discretize an SSM with a zero-order hold and calculate its convolution kernel
  • Express a selective SSM recurrence as an associative scan

References