1. Tokens need to talk to each other
In "Lily gave the dog a ball. She smiled", the word She is only useful if the model can find Lily earlier in the text. Looking up an embedding cannot do that, because each row of the table knows nothing about its neighbours. Attention is the mechanism that lets every token look at the tokens before it and blend in what it finds.
The key word is before. The model is trained to guess the next token, so a token may never look at the tokens after it, or it could just copy the answer. This rule is called a causal mask, and you will see it as the empty triangle in the picture below.
2. Query, key, value
Each token gets three short vectors, made from its embedding by three learned tables of numbers:
- a query: "what am I looking for?"
- a key: "what do I contain, for anyone who is looking?"
- a value: "what I will hand over if you pick me."
To decide where token i looks, take its query and compare it with the key of every earlier token (including itself) using a dot product. A big score means a good match. The scores are divided by the square root of the vector length to keep them moderate, then a softmax turns them into weights that are positive and add up to exactly 1. Finally the token takes a weighted average of the values. That average is what attention gives back.
Below, the real numbers from a real model. First train one; an untrained model attends almost evenly.
7. What to take from this, and what not to
Several heads, several habits. Each layer runs a few attention heads side by side, each with its own query, key and value tables, and then combines them. Training is free to let different heads specialise: one may mostly look one step back, another may spread out. Compare the rows of the table above before and after training.
Layers stack. The second layer looks at tokens that the first layer has already mixed, so it can combine information in ways one layer cannot.
A weight is not an explanation. A high weight shows where information can flow, not why the model answered as it did. And this model is tiny: it has 2 layers and 2 heads, trained for a minute on children's stories, so don't expect it to resolve "She" to "Lily". The mechanism is identical in far bigger models; only the scale differs.
Next chapter: how the model learns, meaning loss, gradients and the small steps that make all of this work.