Attention, worked through with three tokens
Attention lets each token in a sequence build its representation from the others, weighting each by how relevant it is. It is the core operation of the transformer. This page works through it with three tokens and two-dimensional vectors, small enough to check every number by hand.
On this page
The idea
In the sentence “the cat sat”, what “sat” means depends on who sat. Attention gives every token a way to look up information from the other tokens. Each token produces three vectors:
- a query : what this token is looking for;
- a key : what this token offers to be found by;
- a value : the information it hands over when found.
A token compares its query with every key using a dot product, turns the scores into weights with softmax, and takes the weighted average of the values. It is a soft, differentiable version of a dictionary lookup: instead of returning the one value whose key matches, it returns a blend, weighted by how well each key matches.
The formula
Stack the token embeddings as the rows of a matrix . Three learned weight matrices produce the queries, keys and values for all tokens at once:
Then scaled dot-product attention is
where softmax is applied to each row separately and is the length of the key vectors. Entry of is , the score of token attending to token .
Why divide by ?
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 such spread-out numbers is almost one-hot: one weight near 1, the rest near 0, with gradients near zero. Dividing by brings the variance back to 1 and keeps the softmax in a range where it can learn.
Worked example
Step 1: queries, keys and values
The tokens “the”, “cat” and “sat” have embeddings , and . With the weight matrices
we get, multiplying row by row,
For example, the query for “sat” is .
Step 2: scores
Every query dotted with every key gives ; then divide by :
Row 3 is “sat”: , , .
Step 3: softmax each row
For “sat”: , which sum to about 90.6, giving weights 0.187, 0.045, 0.768. “sat” attends mostly to itself and somewhat to “the”. Each row sums to 1.
Step 4: weighted sum of values
For “sat”: . That vector, a blend of the three tokens’ values, is the new representation of “sat”.
Try it
The widget starts from the same numbers. Edit any embedding or weight and every matrix updates. Click a row of the heatmap to see that token’s calculation written out.
Causal masking
A model that generates text one token at a time must not let a token look at tokens that come after it, or training would let it cheat by reading the answer. The fix is a causal mask: before the softmax, set every score with to , so its weight becomes exactly 0. In the example, “the” can then only attend to itself (weight 1), “cat” splits its attention between “the” and itself (0.500 and 0.500), and “sat” is unchanged because it was already last. Tick the checkbox in the widget to see it.
From one head to a transformer
- Multi-head attention. Instead of one set of , a layer runs several in parallel (often 8 to 128 heads), each with smaller vectors, and concatenates the results. Different heads can specialise: one may track which noun a pronoun refers to, another the previous token.
- Position. Attention by itself ignores order: shuffle the tokens and the outputs shuffle the same way. Transformers add positional information to the embeddings, or build it into the scores, so that order can matter.
- Cost. The score matrix has an entry for every pair of tokens, so attention over a sequence of length takes time and memory. That quadratic cost is why long context windows are expensive, and the target of a great deal of research.
References
- A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser and I. Polosukhin, “Attention is all you need”, NeurIPS 2017. arXiv:1706.03762
- D. Bahdanau, K. Cho and Y. Bengio, “Neural machine translation by jointly learning to align and translate”, ICLR 2015. arXiv:1409.0473
- 3Blue1Brown, Neural networks, whose later chapters explain transformers and attention visually.