Attention, step by step
One sentence, one word, one real attention head. A walk through the arithmetic at the heart of a language model, using actual numbers from GPT-2.
The first essay on this site drew arcs over a sentence: “The cat sat on the mat because it was tired.” The thickest arc ran from “it” to “cat.” Those weights were made up.
This essay does it for real. The numbers below come from the smallest version of GPT-2,1 a model OpenAI released in 2019 that is small enough to take apart on a laptop. We will follow one word, “it,” through one small piece of the model, and then ask what the result does and does not show.
What goes in
GPT-2 reads this sentence as ten tokens, one per word. Each starts as an embedding, a list of 768 numbers, with its position in the sentence mixed in. Those lists then pass through twelve layers, each of which revises them.
Every layer contains twelve attention heads working side by side, for 144 in all. Each head is its own small version of attention, with its own learned parameters. We will look at the fourth head in the fifth layer. By the time a word reaches it, four layers have already been at work, so “it” is no longer just a dictionary entry. It carries some information about the words before it.
Queries, keys and values
The head turns each word’s 768 numbers into three shorter lists of 64 numbers, using matrices learned in training. They are called the query, the key and the value, and it helps to think of them as three roles:
- The query is what this word is looking for.
- The key is what this word offers to be found by.
- The value is what this word hands over if it is found.
The descriptions are an aid to memory, not something written into the model. Each one is only a list of numbers that training found useful.
Four steps
Start with “it” selected in the figure and press the steps in order.
Score. The query for “it” is compared with the key of every word by a dot product: multiply the two lists number by number and add up the results. “Cat” scores 4.6. Nothing else comes close; “because,” for example, scores −29.0.
Scale. Every score is divided by 8, the square root of 64. Adding up 64 products can produce large numbers, and large gaps make the last step too decisive. Applied to the unscaled scores here, softmax would give “cat” more than 99.99 percent.
Mask. GPT-2 is trained to predict the next word, so it must not peek ahead. The mask rules out “was” and “tired,” which come after “it.” Not every Transformer has this step: BERT, for one, reads in both directions.
Softmax. Softmax turns the scores that are left into weights adding up to 100 percent. “Cat” gets about 84. The runner-up, “The,” gets less than 6.
One thing remains. The head adds up the values of all the words, each multiplied by its weight, so what “it” receives is mostly the value of “cat.” The results from all twelve heads are combined and added to the list of numbers for “it,” which moves on through the layer a little changed.
Go deeper: the whole head in code
This is one head, with the mask. X holds one row of 768 numbers per word, after GPT-2’s layer normalization. The three matrices are 768 by 64. GPT-2 also adds a learned bias to each product, left out here.
import numpy as np
def head(X, W_q, W_k, W_v):
Q, K, V = X @ W_q, X @ W_k, X @ W_v
scores = Q @ K.T / np.sqrt(K.shape[-1])
future = np.triu(np.ones(scores.shape, dtype=bool), k=1)
scores[future] = -np.inf
weights = np.exp(scores - scores.max(axis=-1, keepdims=True))
weights /= weights.sum(axis=-1, keepdims=True)
return weights @ V
The twelve outputs, 64 numbers each, are joined into one list of 768 and multiplied by one more learned matrix.
Does it understand the sentence?
It is tempting to say the model has worked out that “it” means the cat. The mask shows why that is too generous. When this head processes “it,” the word “tired” is still hidden. Change the ending to “because it was soft,” which points to the mat, and the weights for “it” are exactly the same. They have to be.
Running the same head on other sentences is humbling. In “Yesterday the old car hit the wall because it was raining,” it sends 52 percent of the weight for “it” to “car,” though nothing there refers to the car. In “The dog chased the ball because it was fast,” it splits almost evenly, 45 percent to “dog” and 44 to “ball.” In “The trophy did not fit in the suitcase because it was too big,” its favorite is “The.”
Nor is it reserved for pronouns. Select “sat” in the figure: 96 percent goes to “cat.” A fairer description, from these few examples, is that the head often finds an earlier noun that the current word might have to do with. That is useful, and it is a long way from understanding.
The other 143
That head was also hand-picked. Of the 144, it gives “cat” the most weight from “it,” by a wide margin: the next highest gives 41 percent. Only five heads give “cat” the most weight of any word.
Some heads do something much simpler. The last head in the same layer looks, almost without exception, at the word just before:
The most common habit is stranger. For “it,” 108 of the 144 heads give the most weight to “The,” the first word of the sentence. This is not because “The” is informative. Researchers have found that language models often send large amounts of attention to the first few tokens, whatever they are, and call them attention sinks.2 One explanation is that weights have to add up to 100 percent, so a head with nothing useful to add still has to put them somewhere.
What the arcs can tell you
Attention weights are appealing because they look like an explanation. Whether they are one has been argued over for years, in papers titled “Attention is not Explanation”3 and, in reply, “Attention is not not Explanation.”4 The weights show how much of each value is passed along at one point. They do not show what the values contain, what the other heads did, or what later layers made of it all.
So the arcs are real, and the arithmetic behind them is simple enough to fit in four buttons. What they mean is harder. A single head is one small calculation among many, and the model’s behavior comes from all of them together.
- Radford et al., “Language Models are Unsupervised Multitask Learners” (2019). The weights are from the published GPT-2 small model, which has about 124 million parameters. ↩
- Xiao et al., “Efficient Streaming Language Models with Attention Sinks” (2023). ↩
- Jain and Wallace, “Attention is not Explanation” (2019). ↩
- Wiegreffe and Pinter, “Attention is not not Explanation” (2019). ↩