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
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 15Attention complexity and FlashAttentionDerive stable online softmax and tiled exact attention, analyze backward recomputation and memory traffic, and compare GPU attention backends.
- 16Sparse, local and linear attentionCompare sparse and sliding-window attention with linear recurrent attention, positive random features, and associative recall.
- 17Mixture of ExpertsStudy top-k mixture-of-experts routing, capacity, balancing, active and total parameters, and controlled experiments on specialization.
- 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.
- 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.
- 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.
- 21Long context: extending RoPE and length generalizationExplore long-context extrapolation, RoPE scaling, attention sinks and measured retrieval.
- 22What a transformer can computeExamine transformer expressivity, resource bounds and in-context learning through theory and experiments.
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
- Attention Is All You Need
- Formal Algorithms for Transformers
- Understanding Deep Learning
- Deep Learning: Foundations and Concepts
- Dive into Deep Learning: Attention Mechanisms and Transformers
- Speech and Language Processing
- Neural Networks: Zero to Hero
- CS336: Language Modeling from Scratch
- The Transformer Family Version 2.0
- How to Scale Your Model