Attention is born
A differentiable lookup that lets the decoder read the whole source
This is the hinge of the entire path. Bahdanau's 2015 attention mechanism removed the seq2seq bottleneck and, two years later, became the only mechanism in the transformer (7.1 Attention Is All You Need: the big picture). Derive it once as a soft dictionary lookup with queries, keys and values, and every later formula — scaled dot-product attention (7.2 Scaled dot-product and multi-head attention, fully derived), cross-attention in text-to-image models (8.10 Multimodal models), even dense retrieval in RAG (9.2 Embeddings deep dive) — becomes a variation on something you already understand.
You'll be able to
- Write Bahdanau's additive attention equations and explain each term
- Compare additive and multiplicative (Luong) scoring functions and explain why dot products won
- Reformulate attention as a soft dictionary lookup over queries, keys and values and compute a numeric example
- State what attention fixed in seq2seq models and what remained for the transformer to fix
Key ideas
- Attention computes, at each decoder step, a weighted average of all encoder states; the weights are a softmax of learned alignment scores.
- Bahdanau (additive): e_tj = v_aᵀ tanh(W_a s_{t−1} + U_a h_j); α_tj = softmax_j(e_tj); c_t = Σ_j α_tj h_j.
- Luong (multiplicative): dot, general and concat scores; the dot product is one matrix multiply and became the standard.
Show 4 more key ideas
- Attention = soft dictionary lookup: queries compared with keys, weights blend values; differentiable, so backprop learns what to look up.
- Cross-attention (decoder→encoder), self-attention (sequence→itself) and causal self-attention are the same formula with different Q/K/V sources.
- Dividing scores by √d_k keeps the softmax from saturating as dimensions grow — the 'scaled' in scaled dot-product attention.
- Attention removed the bottleneck but RNNs stayed sequential; dropping the recurrence entirely gives the transformer.
Suggested path through this lesson
Look back, softly
A human translator does not memorize the whole sentence and then write; they glance back at the relevant source words while producing each target word. Bahdanau, Cho and Bengio (2015) gave the decoder the same ability: at every output step it computes a weighted average of all encoder states, with weights that depend on what it is currently trying to produce. The weights are computed by a small network and trained end-to-end with the rest of the model — no alignment supervision, just backprop (4.4 Backpropagation, fully derived).
Bahdanau (additive) attention
Let the encoder (bidirectional, so each state sees the whole source) produce states , and let the decoder's previous state be . For output step :
The score function is a one-hidden-layer network, hence "additive": it adds projections of the decoder and encoder states before the . The context vector is now different at every step — a fresh summary of the source focused on what matters right now — so no single vector has to carry everything. Plotting as a matrix of target × source positions gives the famous alignment heatmaps: a near-diagonal for English→French with visible swaps where word order differs ("European Economic Area" ↔ "zone économique européenne"). Attention learned alignments as a by-product of translation.
Luong (multiplicative) attention
Luong, Pham and Manning (2015) simplified the scoring and compared variants using the current decoder state :
The dot-product score is a single matrix multiplication for all positions at once, so it is far cheaper on GPUs, and in practice it works as well as the additive form once dimensions are matched. Luong also distinguished global attention (over all source positions) from local attention (a window around a predicted position) and introduced input feeding (passing the previous attention output into the next decoder step). The transformer chose the dot product and fixed its one weakness — the growth of score variance with dimension — by dividing by (7.2 Scaled dot-product and multi-head attention, fully derived).
Attention as a soft dictionary
Strip away the RNNs and a pattern remains. A query (what I am looking for: the decoder state) is compared with a set of keys (what each item is about: the encoder states); the similarities become weights; the weights blend the corresponding values (what each item contains: also the encoder states, in seq2seq):
A hard dictionary returns the single value whose key matches exactly; attention returns a soft, differentiable mixture weighted by how well each key matches. That differentiability is the whole trick: it lets gradient descent learn what to look up.
Worked example. Three source positions with dot-product scores for the current query. Softmax: , , , sum , so . With values , , the context is — mostly the first item, a little of the third.
Math check (why scaling will matter). If the key dimension is and we divide the scores by before the softmax, the scores become and the weights — flatter. Larger raw scores make the softmax sharper and its gradients smaller; the transformer's keeps the softmax in its well-behaved range as dimensions grow (7.2 Scaled dot-product and multi-head attention, fully derived).
Three kinds of attention follow from the same formula by choosing where queries and keys come from: cross-attention (queries from the decoder, keys/values from the encoder — Bahdanau's case), self-attention (queries, keys and values all from the same sequence, so each position gathers information from the others — proposed for sentence encoding by Cheng et al. and Parikh et al. in 2016) and causal self-attention (self-attention restricted to earlier positions, for generation — 7.6 Decoder-only: GPT and autoregressive generation).
What attention fixed — and what it did not
Fixed: the bottleneck (quality no longer collapses with sentence length), a few BLEU points, and interpretability through alignment plots. Not fixed: the encoder and decoder were still RNNs, so training remained sequential in time (no parallelism across positions) and information between two distant words still travelled through recurrent steps, with the gradient problems of 6.4 Recurrent neural networks and BPTT along the way. The 2017 question was: if attention is doing the work of connecting positions, do we need the recurrence at all? The answer — replace every RNN with self-attention, add positional encodings, stack the blocks — is 7.1 Attention Is All You Need: the big picture.
Where this shows up later
- Scaled dot-product and multi-head attention — 7.2 Scaled dot-product and multi-head attention, fully derived; positional encodings restore the order information RNNs gave for free — 7.3 Positional information: sinusoidal, learned, RoPE, ALiBi; cross-attention in encoder–decoder transformers — 7.7 Encoder–decoder: T5, BART and choosing an architecture.
- Cross-attention conditions image generators on text — 8.10 Multimodal models; attention weights as (unreliable) explanations and as circuits — 8.11 Interpretability: what is happening inside.
- Retrieval is attention over a database: a query embedding scored against stored keys, returning the top values — 9.2 Embeddings deep dive, 9.3 Vector search and indexes; agents' memory retrieval does the same — 10.4 Memory and context engineering.
Common pitfalls (4)
- Confusing attention weights with the context vector: the weights are scalars that sum to 1; the context is the weighted sum of value vectors.
- Reading attention heatmaps as faithful explanations of a model's decision — they show where it looked, not why.
- Thinking attention requires an RNN; the mechanism is independent of the encoder/decoder type.
- Forgetting that the softmax is over source positions (the keys), not over the vocabulary.
Recap: all 7 key points
- Attention computes, at each decoder step, a weighted average of all encoder states; the weights are a softmax of learned alignment scores.
- Bahdanau (additive): e_tj = v_aᵀ tanh(W_a s_{t−1} + U_a h_j); α_tj = softmax_j(e_tj); c_t = Σ_j α_tj h_j.
- Luong (multiplicative): dot, general and concat scores; the dot product is one matrix multiply and became the standard.
- Attention = soft dictionary lookup: queries compared with keys, weights blend values; differentiable, so backprop learns what to look up.
- Cross-attention (decoder→encoder), self-attention (sequence→itself) and causal self-attention are the same formula with different Q/K/V sources.
- Dividing scores by √d_k keeps the softmax from saturating as dimensions grow — the 'scaled' in scaled dot-product attention.
- Attention removed the bottleneck but RNNs stayed sequential; dropping the recurrence entirely gives the transformer.
Watch
Adds attention to the seq2seq model from his previous video with explicit similarity scores and softmax weights.
Read
Exercises
- Attention by hand
A query has dot-product scores against four keys with values , , , . Compute the softmax weights and the context vector; then recompute with the scores divided by . Expected: weights ≈ (0.787, 0.106, 0.039, 0.106) and context ≈ (0.748, 0); the scaled version is flatter with context ≈ (0.56, 0).
- Add attention to your seq2seq
Extend the PyTorch seq2seq tutorial model with Luong dot-product attention over the encoder states. Compare validation BLEU and the quality on the longest 10% of sentences against the no-attention model. Expected: a clear gain concentrated on long sentences.
- Plot the alignments
For 5 translated sentences, plot the matrix as a heatmap (target words on rows, source words on columns). Expected: a roughly diagonal pattern with off-diagonal jumps where word order differs; note the cases where the plot is diffuse and the translation is wrong.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →