Attention and the Transformer Architecture
Self-attention, multi-head attention, positional information and the encoder, decoder and encoder-decoder transformer families.
Advanced · about 12 hours · difficulty 4/5
Learn first: Text Preprocessing and Representations, Regularization, Initialization and Normalization
The transformer is the architecture behind modern language models, and increasingly vision, audio and multimodal models too. Its core idea is attention: every token looks at every other token and decides how much each one matters, all in parallel.
Self-attention step by step
- Each token vector is projected into a query, a key and a value.
- Scores are the dot products of queries with keys, scaled by the square root of the dimension, then passed through softmax.
- The output for each token is a weighted sum of values:
softmax(QK^T / sqrt(d)) V. - Multi-head attention runs several of these in parallel so different heads can track different relationships.
The rest of a block
Residual connections, layer normalization and a position-wise feed-forward network wrap each attention layer. Because attention ignores order, positional encodings (sinusoidal, learned, or rotary RoPE) inject position information.
Three families
- Encoder-only (BERT style): bidirectional, great for classification, tagging and embeddings.
- Decoder-only (GPT style): causal masking so each token sees only the past; trained to predict the next token. This is what large language models are.
- Encoder-decoder (T5, BART): for translation and summarization.
Cost
Attention is quadratic in sequence length, which drives research on efficient attention, KV caching and long-context tricks.
Good enough to move on when you can implement single-head self-attention in NumPy or PyTorch, explain causal masking, and say which family suits a given task.
Key concepts
- Queries, keys and values
- Scaled dot-product attention
- Multi-head attention
- Positional encodings and RoPE
- Causal masking
- Encoder vs decoder vs encoder-decoder
- KV caching
- Efficient attention variants
Mini project
Implement a tiny decoder-only transformer from scratch (a few layers, character-level) and train it on a small text corpus until it generates plausible text. Visualize the attention weights for one sample.
Check yourself
Why is the dot product divided by sqrt(d) before softmax, and what would go wrong in a language model without a causal mask?
Free resources
- Dive into Deep Learning: attention mechanisms and transformers (d2l.ai)
- Hugging Face Learn (Hugging Face)
- The Illustrated Transformer (Jay Alammar)