Attention, from scratch
Self-attention lets the same token gather different clues from its context. How does a model tell a living rabbit from a chocolate one?
Which rabbit?
The embedding table gives “rabbit” the same starting vector in every sentence. But a living rabbit and a chocolate rabbit are very different things.
We can read the surrounding words and work out which rabbit is meant. The embedding lookup cannot: it returns the same starting vector either way.
What would let that vector pick up something from the sentence?
An old rabbit
We have found the animal. Now take “the old rabbit sleeps”. There is something else to learn about this rabbit: it is old.
Imagine “rabbit” asking the other tokens: “Is there an adjective?”
“Old” could reply: “I’m an adjective.”
But who decides what to ask? Writing a rule for “old” and “rabbit” would only solve this one example.
We need the questions themselves to be learned.
Let a question grow from the token
The rabbit’s vector is what the network has to work with. A table of learned weights can turn it into another vector, representing the question the token is asking.
A question needs an answer. “Old” could answer “I’m an adjective.”
A second table of learned weights turns each token’s vector into a vector representing its answer. We can then compare the question with each answer.
The asking vector is a query. The vector it matches against is a key.
These are calculated in parallel. “Old” does not wait to hear “rabbit”’s question: each token makes its query and key from its own vector.
All four tokens use those same two tables.
The two tables are trained together. When a prediction goes wrong, training adjusts both, so the questions and answers learn to match in useful ways—without us writing the language rules.
How well do they match?
Now we have two lists. Does the question from “rabbit” match what “old” is offering?
An array of numbers can be viewed as a vector. With just two numbers, we can draw it: one coordinate goes across, the other goes up or down. Together they give us an arrow.
The same calculation works with longer vectors.
The dot product measures how much the vectors point together. With lengths fixed, alignment gives a positive score; perpendicular arrows give zero; opposing arrows give a negative score.
Put the matches on a map
“Rabbit” has a question. How well does each token answer it?
Take the dot product of “rabbit”’s query with each token’s key. The four scores form a row: one score for each possible answer.
Now do that for every token’s question. Stack the rows and we get an attention map: questions down the side, answers across the top.
Each cell tells us how well that column’s token answers that row’s question.
“Old” is the strongest match for “rabbit”’s question. We want it to contribute more information—but how much more?
Multiplying the query and key matrices gives us the dot products for every question–answer pair.
Then we apply softmax so each row’s scores become attention weights that add up to one.
Read each row as one token’s attention to the others.
In the rabbit row, old gets about 69% of the attention—the brightest cell. The remaining attention is shared between the, rabbit and sleeps.
These weights decide how much information to take from each token. What information can they send?
We know where to look. What do we take?
“Old” needs something to send. Another learned set of weights produces its value vector, the information attention can collect from that position.
In our attention map, rabbit gives old about 69% of its attention.
Multiplying the attention map by the value matrix collects information for every token at once.
No peeking
You may have noticed that every token gets to answer every question. Even sleeps can answer rabbit, although it comes later in the sentence.
But in the previous article, we saw why later tokens must not affect earlier ones. They should not be allowed to answer those earlier questions.
How do we stop them? Mask the attention map. Set the scores for later tokens to −∞ before applying softmax. Softmax turns those scores into zero attention.
In the rabbit row, sleeps goes from a score to −∞, then to 0 after softmax. Its value cannot contribute to rabbit.
Add what we learned to “rabbit”
We now have information collected from the other tokens. How do we add it to “rabbit”’s vector?
There is a size mismatch: the collected vector is shorter than “rabbit”’s original vector. We cannot add them coordinate by coordinate yet.
A learned matrix, Wₒ, converts the collected information into a vector the same size as “rabbit”’s. This is the output projection.
Now we can add the two vectors. “Rabbit” keeps its existing representation and gains information from the tokens it attended to—the residual addition we saw earlier.
Zoom out: the original token vectors travel along the residual stream. Attention branches off, gathers information, and adds its update back to that stream.
One question is not enough
We can run attention several times with different learned projections. Each version is an attention head.
One head may focus on “old”; another on “the”. The heads can learn different, overlapping patterns without being assigned neat jobs.
This is called multi-head attention.
Explore a small trained model
This small trained model has its own vocabulary.
Pick “rabbit” in “the old rabbit sleeps”, then press Next step. Follow its query through to the weighted sum of values.
The small transformer learned from training examples. Its token vectors have 64 numbers; each head uses 16.
Try two changes:
- Switch heads. Do they look at the same tokens?
- Turn the mask off. Which extra matches become available?
The second experiment changes the calculation, not the training. This model was never trained to look ahead.
What happens to a longer sentence?
Every extra token adds a row and a column. Double the context, and the map grows fourfold. Each head needs its own map.
At long contexts, attention becomes one of the model’s biggest bottlenecks. Other articles explore ways to make it faster and use less memory.
Sources and assumptions
- Vaswani and colleagues: Attention Is All You Need (2017), for scaled dot-product attention and multiple heads.
- Dao: FlashAttention-2 (2023), for attention as a bottleneck at long context lengths.
- Bahdanau, Cho and Bengio (2014), for earlier attention in recurrent translation.
- Released plain-MHA examples: GPT-2 config and the original LLaMA report.
The matrix animations use six-coordinate queries and keys, chosen to reproduce the score map exactly. The query rows start from seeded random values and are orthonormalized, with all six coordinates populated; the key table is calculated from those rows so division by √6 restores the displayed scores. The value animation uses the same six coordinates as the gathering diagram and the same row-wise softmax weights.
The small interactive model has trained weights; rounded softmax scores and the question/key metaphors are teaching aids. Positions, normalisation and the feed-forward sublayer are omitted from this attention-only diagram.
The stacked-head diagram shows each head’s slice of Wₒ inside its box, then sums the projected updates. This is equivalent to concatenating the head outputs and multiplying by the full Wₒ.
The compact formula. With tokens written as rows, a head computes
Here supplies the causal mask. The diagrams draw tokens as columns instead, so their projections multiply on the left: , and likewise for keys and values.
Attention predates the Transformer: Bahdanau, Cho and Bengio used it in recurrent translation in 2014. Vaswani and colleagues introduced the Transformer in 2017. The tiny experiment also adds learned position information; this article isolates attention rather than the whole layer.