Self-attention and multi-head attention
Self-attention trained live in your browser: every Q, K, V, scaled score, causal mask, softmax and weighted sum, multi-head split and concat, and the patterns each head learns.
Updated
- Queries, keys and values
- Scaled dot-product attention
- The causal mask
- Multiple heads, split and concatenated
- Position-based vs content-based attention
Intuition
A soft table lookup
To write 8 digits backwards, output position 1 needs the last input, position 2 the second-to-last, and so on: everything each position needs is somewhere else. Attention is a "soft" table lookup: the query is compared with every key, the more alike the larger the weight, and the result is the weighted average of the values. When all the weight lands on one position, it becomes an exact lookup.
The three small labs below really train the same model in your browser (one attention layer, 2 heads, width 16). Each picture is the attention matrix for the first evaluation sample: rows are query positions, columns the positions looked at, and darker means more weight. Below, x is the input and ŷ the model's output at each position (green right, red wrong).
At first every position looks at all positions about equally, and per-position accuracy is 10.2% (guessing gives 10%). At 40 steps per-position accuracy is 77.3%, but only 7.4% of sequences are entirely right. After 100 steps the attention is a clear anti-diagonal — position looks at position — and everything is right.
Math
Queries, keys and values
The input is position vectors (token embedding plus position embedding), each -dimensional, stacked into a matrix . Three learned linear maps give
The score of position for position is ; a softmax over each row gives the weights , and the output is .
Why divide by : if the components of and have variance 1, their dot product has variance . Without scaling, scores grow with the dimension, the softmax becomes almost one-hot, and the gradients become tiny and hard to train.
Multiple heads and the causal mask
Split the dimensions into parts; each head computes attention in its own dimensions, and the outputs are concatenated and multiplied by . Different heads can attend to different positions or different features at the same time.
Causal mask: when generating text, position must not peek ahead, so scores with are set to before the softmax and their weights are 0. The upper-right triangle of the attention map is therefore empty.
Where position comes from: attention by itself only looks at content; shuffle the input order and each position's result simply moves with it. Position information therefore has to be added to the input; this page uses learned position embeddings.
Three tasks, three patterns
Average weight that the head best at looking in the right place puts on "where it should look", over 64 evaluation samples:
| Task | Rule | Where to look | Random weights | Trained |
|---|---|---|---|---|
| Reverse | Mirror position | 0.126 | 0.986 (100 steps) | |
| Previous | Previous position | — | 0.974 (100 steps) | |
| Running maximum | Where the maximum is | — | 0.911 (200 steps) |
The first two tasks look at a fixed relative position, so the attention map is a diagonal line; the running maximum looks by content, and every sample's map is different. With 4 heads on the reverse task the best head reaches 0.992 and the other three lie between 0.669 and 0.869: the task needs only one head, and the others merely "help".
How fast it trains
Reverse task (per position / whole sequence right):
| Steps | 0 | 20 | 40 | 60 | 80 |
|---|---|---|---|---|---|
| Per position | 10.2% | 23.8% | 77.3% | 99.9% | 100% |
| Whole sequence | 0 | 0 | 7.4% | 99.2% | 100% |
Lowering the learning rate from 0.01 to 0.001 gives only 54.6% at 200 steps; it takes 400 steps to get everything right. With sequences of length 12 it is still fully right at 100 steps.
How it is computed, with real numbers
Once the lab above has loaded, this panel works through the same formulas with its current numbers.
Experiment
Follow the lesson
Course
Lesson 1: attention learns where to look
5 steps · each one: set up and run → look → answer
1. Getting started
The default reverse task, 20 training steps. Open "Heads".
2. The anti-diagonal
Train to 60 steps.
3. Looking at the previous one
Switch the task to "Previous".
4. Looking by content
Switch to "Running maximum".
5. Four heads
Back to reverse with 4 heads; open "Heads".
Try these settings
Exercises
Exercises
Exercise 1: learning too slowly
At learning rate 0.001, 200 steps give only 54.6%. Change the settings to get at least 99% of whole sequences right within 100 steps.
Hint
Set the learning rate back to 0.01: everything is right after 80 steps.
- Whole sequence ≥ 99.0%
- at most 100 steps
Exercise 2: running maximum
Looking by content is a little harder than looking at a fixed position. Within 200 steps, get at least 99% of whole sequences right on the running-maximum task.
Hint
Learning rate 0.01: fully right at 200 steps.
- Whole sequence ≥ 99.0%
- at most 200 steps
Quiz
Further reading
Frequently asked questions
What is self-attention?
Each position in a sequence compares its query with every position's key, turns the similarities into weights with softmax, and takes the weighted sum of the values. "Self" means the queries, keys and values all come from the same sequence.
What are queries, keys and values?
All three come from the input vectors through different linear maps. The query says "what I am looking for", the key "how I can be found", and the value "what I provide once found". Separate maps let "matching" and "what to take" be learned as different things.
What is the benefit of multi-head attention?
Several smaller attentions run in parallel, each free to focus on different positions or features, and their outputs are concatenated. The total cost is about the same as one large head. On this page's reverse task only one of 4 heads actually does the reversing: multiple heads give the model room, but not every head has to be useful.
Can attention weights be used as an explanation of the model?
With care. The weights show where a layer took information from, but how the values taken affect the output after later transformations needs separate analysis, and in multi-layer models information gets mixed layer after layer. Only in a model like this page's, with one layer and a clear task, do the weights line up with the rule.
How much computation does self-attention take?
A sequence of length T needs T × T scores, so computation and memory grow as T², the main bottleneck for long texts; FlashAttention, sparse attention and linear attention all address it.
Further reading
- Bahdanau, Cho, Bengio, Neural Machine Translation by Jointly Learning to Align and Translate, 2014: where attention began.
- Vaswani et al., Attention Is All You Need, 2017: scaled dot-product and multi-head attention.
- Clark et al., What Does BERT Look At?, 2019: how attention heads divide the work in large models.
- Jain, Wallace, Attention is not Explanation, 2019.
- Olsson et al., In-context Learning and Induction Heads, 2022: how two attention layers learn to "copy from earlier text".