Part II · Branches & Language
Chapter 7
Transformers
The architecture that reshaped modern AI.
In one sentenceA Transformer lets every token look directly at every other token through attention, stacked in blocks that are fast to train in parallel.
The problem
One word at a time
By 2016, the best language systems — translation above all — were built from recurrent neural networks (Chapter 6). An RNN reads a sentence the way you'd read through a keyhole: one word at a time, carrying a single summary vector forward. Attention had already been bolted on to help the decoder look back at the input, but inside the encoder and decoder, information still crawled from word to word.
That created two problems that grew worse as data and ambitions grew:
- Distance. For the model to connect it to animal six words earlier, that information has to survive six sequential updates of the hidden state — and real dependencies can span hundreds of words.
- Speed. Step 10 can't be computed before step 9. Training can't use the thousands of parallel cores in a GPU across the length of the sequence.
A recurrent network reads left to right, carrying one hidden state. What it knew about animal must survive 6 sequential updates before reaching it — fading a little at each step (shaded). And step 7 can't be computed until step 6 is done, so training can't be parallelized across the sequence.
The idea
Let every word look at every word
The Transformer's authors took the attention mechanism — until then an add-on to RNNs — and made it the whole architecture. Every token directly compares itself with every other token and gathers what it needs, in a single step, with all tokens computed at once.
Remove recurrence entirely. Keep attention. Add small per-token neural networks, and a few engineering tricks that make deep stacks trainable. That is the entire design.
How it works
Attention from first principles
Don't start with matrices. Start with a question.
I have a sentence. For each word, which other words should it pay attention to?
You already have every tool needed. Words are vectors (embeddings). The dot product scores how aligned two vectors are. Softmax turns scores into weights that sum to 1. A weighted sum mixes vectors by those weights. Put them together:
Score
For the word asking the question, compute a similarity score with every word.Normalize
Softmax the scores into attention weights.Mix
The word's new vector is the weighted average of all word vectors.
Try it — and watch what goes wrong in step 1 for the word it:
Try it · toy model
One short sentence, one question: which words should each word pay attention to? Build attention step by step — similarity, softmax, weighted sum, then queries and keys.
Queries, keys and values
Step 1 exposed a flaw: raw similarity asks "who is like me?", but it needs to ask "who could I be referring to?". What a word looks for differs from what it is.
So each token produces three vectors through three learned matrices:
- a query — what I'm looking for,
- a key — what I offer to others,
- a value — the information I pass on if selected.
Scores become query · key; the weighted sum is over values. During training, the model learns , and — it learns what to look for. Two more details complete the mechanism: scores are divided by before the softmax, and in a GPT-style model a causal mask hides every later token.
Self-attention lets every token in a sequence look at every other token, decide how relevant each one is, and update itself with a weighted mix of what it finds.
Open the concept page →
A causal mask stops each position from attending to later positions, so a model trained to predict the next token can't simply look at it.
Open the concept page →
Deep diveWhy divide by √dₖ?Should know
If the entries of and are roughly independent with mean 0 and variance 1, their dot product has variance . With , typical scores would be around ±8, and softmax of scores that spread out puts nearly all the weight on one token — its gradients for the others become tiny and learning stalls. Dividing by brings the variance back to about 1. This is the argument given in the original paper.
Many heads at once
One attention pattern gives each token a single weighted average. Language needs several at once — who did it, to what, what came just before. So the Transformer runs h heads in parallel, each in a smaller subspace with its own , then concatenates their outputs and mixes them with one more matrix, . With 8 heads of 64 dimensions instead of one of 512, the cost is about the same.
Multi-head attention runs several smaller attention operations in parallel, each with its own learned queries, keys and values, so a layer can track several kinds of relationship at once.
Open the concept page →
Where is everything?
There's a catch. Attention compares every token with every other using dot products — nothing in that computation knows where a token is. Shuffle the words and each token gets exactly the same scores, just in a different order. "Dog bites man" and "man bites dog" would look alike.
The fix is to inject position. The original Transformer adds a fixed pattern of sine and cosine waves to each embedding; GPT-2 and BERT learn a vector per position; many recent LLMs rotate queries and keys by position (RoPE).
Positional encodings add information about each token's position, because attention on its own treats a sentence as an unordered set.
Open the concept page →
The Transformer block
Attention alone only averages. Each block therefore pairs it with a feed-forward network applied to every token separately — expand to a wider layer, apply a nonlinearity, project back. Around both sublayers sit two engineering necessities: layer normalization to keep numbers in a stable range, and residual connections so each sublayer adds a correction rather than replacing its input.
The output has the same shape as the input, so blocks stack: 6 in the original encoder and decoder, 12 in GPT-2 small, on the order of a hundred in today's largest models. Step through one below — every number is really computed, just with tiny dimensions and untrained weights.
Try it · toy model
Step through a real forward pass of one GPT-style Transformer block — embeddings, positions, multi-head attention, residuals, the MLP and the output softmax — with the tensor shape at every stage.
A Transformer block is attention followed by a feed-forward network, each wrapped in normalization and a residual connection — and a Transformer is just many identical blocks stacked.
Open the concept page →
Deep diveWhere did the original put layer norm?Should know
The 2017 Transformer applied layer normalization after each residual addition ("post-LN"): . GPT-2 moved it to the input of each sublayer ("pre-LN"), which leaves a clean residual path from bottom to top. Later analysis (Xiong et al., 2020) showed why pre-LN trains more stably without a long learning-rate warm-up. Most modern LLMs use pre-LN, often with RMSNorm.
Three families
The original Transformer was an encoder–decoder for translation: an encoder reads the source sentence with full, bidirectional attention; a decoder generates the translation with causal attention plus cross-attention to the encoder. Within two years the halves were being used on their own.
Trained toNext-token prediction: each position predicts the following token, seeing only the past.
Good forGeneration. One simple objective that scales well; it became the dominant design for LLMs.
Squares show which tokens (columns) each token (rows) may attend to. Cross-attention lets every decoder position look at every encoder position.
The same Transformer block is wired three ways: encoder-only models (BERT) read in both directions to understand text, decoder-only models (GPT) predict the next token to generate it, and encoder–decoder models (T5) map one sequence to another.
Open the concept page →
The math
The math in one place
Everything above, as equations. If the chapter made sense, each line should read as a sentence.
Why it matters
Why it matters
It solved the two problems it set out to solve. Any token reaches any other in one step, and the whole sequence is processed in parallel, which suits GPU hardware.
It scaled. The same uniform block could be made wider and stacked deeper, trained on more data, and kept improving. That property — more than any single benchmark result — is why nearly every large model since descends from it. Chapter 8 tells that story.
It generalized beyond language. The block makes no assumptions about text: images cut into patches (Vision Transformers), audio frames (speech models) and mixtures of modalities all run through essentially the same architecture.
Historical context
Attention Is All You Need
In June 2017, eight researchers, most of them at Google Brain and Google Research, posted Attention Is All You Need. It proposed the Transformer for machine translation and reported 28.4 BLEU on WMT 2014 English-to-German — more than 2 BLEU above the previous best results, including ensembles — and a new single-model state of the art of 41.8 on English-to-French, after training for 3.5 days on eight GPUs: a fraction of the cost of the best earlier models.
The ideas it combined were not all new — attention (2014), residual connections (2015), layer normalization (2016) — but the decision to drop recurrence entirely, and the specific, simple way they were assembled, proved decisive. Within eighteen months, BERT (an encoder) and GPT (a decoder) had shown that pretraining a Transformer on unlabelled text and then adapting it beat task-specific models across NLP.
Concepts in this chapter
Mark each one as you go. Must-know concepts are the core path.
- Causal MaskingA causal mask stops each position from attending to later positions, so a model trained to predict the next token can't simply look at it.Know wellMust know
- Feed-Forward Sublayer (MLP)The feed-forward sublayer is a small two-layer neural network applied to each token separately, transforming the information that attention has gathered.Know wellMust know
- Layer NormalizationLayer normalization rescales each token's vector to zero mean and unit variance (then applies a learned scale and shift), keeping activations in a stable range.UnderstandMust know
- Multi-Head AttentionMulti-head attention runs several smaller attention operations in parallel, each with its own learned queries, keys and values, so a layer can track several kinds of relationship at once.Know wellMust know
- Positional EncodingPositional encodings add information about each token's position, because attention on its own treats a sentence as an unordered set.Know wellMust know
- Residual ConnectionsA residual connection adds a layer's input to its output (x + f(x)), so each layer learns a correction instead of a complete replacement.Know wellMust know
- Self-AttentionSelf-attention lets every token in a sequence look at every other token, decide how relevant each one is, and update itself with a weighted mix of what it finds.ImplementMust know
- The Transformer BlockA Transformer block is attention followed by a feed-forward network, each wrapped in normalization and a residual connection — and a Transformer is just many identical blocks stacked.ImplementMust know
- Encoder, Decoder & Encoder–DecoderThe same Transformer block is wired three ways: encoder-only models (BERT) read in both directions to understand text, decoder-only models (GPT) predict the next token to generate it, and encoder–decoder models (T5) map one sequence to another.Know wellMust know
What do I actually need to remember?
- Transformers drop recurrence: every token attends to every other token directly, and all positions are computed in parallel.
- Self-attention: queries · keys → scale by √d → softmax → weighted sum of values.
- Q, K and V are three learned projections: what I look for, what I offer, what I pass on.
- Multi-head attention runs several smaller attentions in parallel so different heads can track different relationships.
- Attention can't see order, so positional information is added (sinusoids, learned vectors, or RoPE).
- A block = x + Attention(LN(x)), then x + FFN(LN(x)); blocks keep the shape, so they stack.
- Attention communicates between tokens; the feed-forward network computes within each token.
- Causal masking lets decoders train on every position at once without seeing the future.
- Encoder-only (BERT) understands, decoder-only (GPT) generates, encoder–decoder (T5) maps sequence to sequence.
- Attention's cost grows with the square of sequence length — a constraint behind much later engineering.
You do not need to memorize everything else. This list is the revision sheet.
Key papers
Attention Is All You Need
Ashish Vaswani, Noam Shazeer et al. · 2017 · NeurIPS 2017
Introduced the Transformer — the architecture behind BERT, GPT and nearly every modern large language model, and later adapted to vision, audio and more.
- Problem
- Recurrent models process tokens one after another, which limits parallel training and forces distant words to interact through many sequential steps.
- What was new
- Dropped recurrence entirely: stacks of multi-head self-attention and feed-forward layers, with positional encodings, residual connections and layer normalization.
How to read it: Section 3 is the architecture — read it with Figure 1 open. Sections 3.2.1–3.2.2 contain the attention equation. You can skim the training details on a first pass.
Neural Machine Translation by Jointly Learning to Align and Translate
Dzmitry Bahdanau, Kyunghyun Cho, Yoshua Bengio · 2014 · ICLR 2015
Introduced attention in neural networks for language: instead of squeezing a sentence into one vector, the decoder looks back at every input word and decides which ones matter right now.
- Problem
- Encoder–decoder models squeezed the whole source sentence into a single fixed-length vector, and translation quality fell sharply on long sentences.
- What was new
- A learned alignment: at each output step the model scores every encoder state, normalizes the scores with softmax, and uses the weighted average as context.
- Influenced
- Attention Is All You Need
How to read it: Figure 3's alignment heat-maps are the best picture of 'attention' ever drawn — look at them first.
Deep Residual Learning for Image Recognition
Kaiming He, Xiangyu Zhang et al. · 2015 · CVPR 2016
Residual (skip) connections made very deep networks trainable. Every Transformer block relies on the same trick.
- Problem
- Adding more layers to deep networks made training error worse, not better — deeper models were harder to optimize.
- What was new
- Let each block learn a correction added to its input (x + F(x)), giving gradients a direct path through the network.
- Influenced
- Attention Is All You Need
Layer Normalization
Jimmy Lei Ba, Jamie Ryan Kiros, Geoffrey E. Hinton · 2016
The normalization used inside Transformers; it keeps activations at a stable scale regardless of batch size.
- Problem
- Batch normalization depends on batch statistics, which is awkward for recurrent networks and small or variable batches.
- What was new
- Normalize across the features of each individual example instead of across the batch.
- Influenced
- Attention Is All You Need
BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding
Jacob Devlin, Ming-Wei Chang et al. · 2018 · NAACL 2019
Made 'pretrain once, fine-tune everywhere' the default in NLP, using an encoder-only Transformer that reads context in both directions.
- Problem
- Language models read left-to-right, so their representations of a word couldn't use the words that came after it.
- What was new
- Masked language modeling: hide random tokens and train an encoder to fill them in from both sides.
Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer
Colin Raffel, Noam Shazeer et al. · 2019 · JMLR 2020
Framed every NLP task as text in, text out, using an encoder–decoder Transformer — and ran a huge, careful set of ablations that is still a model of empirical method.
- Problem
- Transfer-learning results were hard to compare because every paper changed many things at once.
- What was new
- One text-to-text format for all tasks, plus a systematic study of objectives, architectures and data.
How to read it: Long (67 pages). Read the introduction and Section 3.2's architecture comparison; treat the rest as a reference.
On Layer Normalization in the Transformer Architecture
Ruibin Xiong, Yunchang Yang et al. · 2020 · ICML 2020
Explains why modern Transformers put layer normalization before each sublayer ('pre-LN') rather than after it.
- Problem
- The original post-LN Transformer needed a careful learning-rate warm-up to train stably.
- What was new
- Analysis showing pre-LN keeps gradients well-behaved at initialization, allowing training without warm-up.
Watch
3Blue1Brown
Transformers, the tech behind LLMs | Deep Learning Chapter 5
A visual tour of a GPT from input text to next-token probabilities — ideal before or right after Chapter 7.
Covers: Tokens, embeddings, the flow of data through a GPT, softmax and temperature.
3Blue1Brown
Attention in transformers, step-by-step | Deep Learning Chapter 6
Animates exactly what queries, keys and values do. Watch it alongside the Attention Explorer.
Covers: Queries, keys, values, the attention pattern, masking, multi-head attention.
3Blue1Brown
How might LLMs store facts | Deep Learning Chapter 7
The feed-forward half of a Transformer block gets less attention than attention; this fixes that.
Covers: MLP sublayers, directions in embedding space, superposition (intuition).
Andrej Karpathy
Let's build GPT: from scratch, in code, spelled out.
The best way to reach IMPLEMENT level on Transformers: write one yourself, line by line, in PyTorch.
Covers: Self-attention, multi-head attention, masking, residuals, layer norm — all built from a bigram baseline up.
What came next?
Chapter 8
The Rise of Large Language Models
Task-specific models needed task-specific data. Could one pretrained model do many tasks?
This chapter is being written.