Attention
Queries, keys and values: a soft lookup across positions
Chapter 6 of 21 · II. The transformer · about 45 minutes. Builds on: 2. Neural networks and the multilayer perceptron, 4. Probability, softmax and next-token prediction, 5. Tokens and embeddings.
The problem attention solves
Section titled “The problem attention solves”After embedding, each token has its own vector, computed with no knowledge of its neighbors. But meaning depends on context: in “the bank of the river” and “the bank approved the loan” the first vector for “bank” is identical. We need a mechanism that lets every position gather information from other positions, in a way that is learned and can be computed efficiently.
A soft dictionary lookup
Section titled “A soft dictionary lookup”Think of a dictionary: you present a query, it is compared to every stored key, and you get back the value of the matching entry. A hash table does a hard match. Attention does a soft match: compare the query to all keys, convert the similarities into weights that sum to one, and return the weighted average of all values.
The first form of attention in neural networks was used for translation, letting a decoder look back at all encoder states with learned weights . The transformer made attention the only mechanism for moving information between positions.
The computation, step by step
Section titled “The computation, step by step”Let be the matrix of token vectors, one row per token ( tokens, width ). Three learned matrices project into queries, keys and values:
Row of asks “what am I looking for?”; row of advertises “what do I contain?”; row of is “what I contribute if selected”. Then:
Here is how well token matches token ‘s query, every row of is non-negative and sums to 1, and .
Every output row is a convex combination of value rows. The weights are the “attention pattern” of token . Work through it with numbers you can verify by hand:
This example is small enough to check on paper. A complete model run, with real trained weights, is in the Model Explorer.
Why divide by the square root of the key size
Section titled “Why divide by the square root of the key size”Suppose the components of a query and a key are independent with mean 0 and variance 1. Then is a sum of independent terms, each with variance 1, so has variance . Without scaling, the typical score grows like , and when scores are large the softmax saturates: one weight is almost 1, the rest almost 0, and the gradient through softmax nearly vanishes. Dividing by restores unit variance, so the softmax stays in a useful range .
The causal mask
Section titled “The causal mask”When training a model to predict the next token, position must not see tokens after ; otherwise it could just copy the answer. The causal mask adds to for , so those weights become exactly 0 after softmax. Because of the mask, one forward pass computes the loss for every position of the sequence at the same time, which is what makes training efficient. Try the masks below; the hatched cells are blocked.
Multi-head attention
Section titled “Multi-head attention”One attention pattern per layer is limiting: a token may need to attend to its subject for grammar, a previous mention for coreference, and a delimiter for structure. Multi-head attention runs independent attentions in parallel, each with its own , , and a smaller width , then concatenates the outputs and mixes them with a final matrix:
The parameter count is unchanged: (, , , each ) whatever is. Chapter 11 shows how modern models share keys and values across heads to shrink the inference cache.
Do heads really learn different jobs? Here are all four heads of the small model from the Model Explorer, trained on a toy grammar. Pick a prompt and compare the patterns: layer 0, head 0 mostly reads the token itself, while the other heads spread their attention across the previous token, the start-of-sequence token and earlier words. Switch to random weights to see how much of this structure comes from training.
Interpretability work has identified specific head behaviors. A well-studied one is the induction head : given a sequence ”… A B … A”, it attends from the second A to the token after the first A and copies B. This simple circuit appears around the time models start to show in-context learning (Chapter 19).
The score matrix has entries. Computing it takes operations and storing it takes memory per head. For short sequences the MLP dominates; at tens of thousands of tokens attention dominates. Chapters 10–13 are about living with this cost.
Check yourself
Section titled “Check yourself”Token i's output is a "convex combination" of value rows. What does this say about what attention can do?
It can only produce vectors inside the convex hull of the (projected) value vectors it can see. It selects and blends; the linear maps , and the surrounding MLPs create everything else.
If all scores in a row are equal, what is the output?
A uniform average of all visible value vectors.
Why does the causal mask allow the loss on all positions in one pass?
The mask makes the output at position independent of tokens after , so using the true tokens as inputs at every position does not leak the targets. This is called teacher forcing.
For d = 4096 and h = 32, what is d_k, and how many parameters does the attention block have?
. Parameters million (with full multi-head attention).
Papers
Section titled “Papers”- The original attention mechanism, for translation.
- The transformer. Read sections 3.1–3.2 first.
- What attention heads learn to do.
- Chapter 12 explains transformers with the same notation used here.