Part IV ยท Context
Ch 9. Attention
A spotlight on the past
A model uses attentionattention: The step where each token gathers information from the earlier tokens it finds relevant. Ch 9 to let each token look back over everything before it and pull in whatโs useful. Picture each token holding a spotlight. It shines on the earlier tokens, brightly on the relevant ones and dimly on the rest, and takes in a blend of whatever it lights up. Attention is the core idea of the transformertransformer: The model design used by modern LLMs: a stack of repeated blocks built around attention. Ch 10, the design introduced in 2017 that almost every modern LLM uses, GPT-2 included.[1][1][1]
Queries, keys, and values
How does a token decide where to shine? Each token makes three things from its numbers, using weights learned in training: a query (what itโs looking for), a key (what it has to offer), and a value (what it passes on). Where one tokenโs query matches another tokenโs key well, the spotlight shines brighter. Each token then takes in a blend of the values, mostly from the tokens it lights up most.
How does a token decide where to shine? Each tokenโs vector is turned into three new vectors, using weights learned in training:
- a query: what this token is looking for,
- a key: what this token has to offer, to anyone looking,
- a value: what this token passes on if it gets picked.
To score how relevant one token is to another, multiply the first tokenโs query with the second tokenโs key, number by number, and add up the results. When the two vectors point in similar directions (think of the nearby words in Ch 5), the score is high. The scores are divided by a fixed number to keep them from getting too large, then softmax (Ch 2) turns them into percentages. Finally each token takes a weighted blend of the values.
Step through it with made-up numbers:
Notice the blank cells: a token canโt look at tokens that come after it. When the model is predicting the next word, those words donโt exist yet.
The formula
Written out for every token at once, one attention head computes
Each row of , , and is one tokenโs query, key, or value. They come from the token vectors , one row per token, times three learned weight matrices: , , and . is the grid of scores, every query times every key. is the number of values in each key, and is the fixed number the scores are divided by. is the mask: 0 where a token may look, and where it would look ahead, which softmax turns into a weight of exactly 0. Softmax runs along each row, so each tokenโs weights add up to 1.[1]
In GPT-2, each token vector has 768 numbers and each layer has 12 heads, so each head works with numbers, and the scores are divided by . The 12 headsโ outputs are put side by side, back to 768 numbers, and multiplied by one more learned matrix, .[1] Unlike the toy, GPT-2 also normalizes the token vectors before they go in (more in the next chapter).[2]
The grid has a cell for every pair of tokens, so it grows with the square of the textโs length. With the mask, tokens need
scores in each head: 524,800 for a full window of 1,024 tokens, in each of GPT-2โs 144 heads.
Which word came first?
Attention on its own has a blind spot: nothing in a score says where a token sits. โThe dog chased the cat.โ and โThe cat chased the dog.โ contain the same words, so attention would blend them the same way, and who chased whom would be lost. So GPT-2 adds a second list of numbers to each token, a position vectorposition vector: A learned vector for each place in the text, added to the tokenโs vector so the model knows word order. Ch 9, that says where it is: first, second, third, and so on, up to 1,024 places.
Look again at how a score is made: one tokenโs query times another tokenโs key. Nothing in that says where either token sits in the text. Take โthe dog chased the cat.โ and โthe cat chased the dog.โ At the final โ.โ, one attention step would see the same six tokens in both, just in another order, and blend them in exactly the same way. Who chased whom would be lost.
So before the first layer, GPT-2 adds a second vector to each tokenโs vector: a position vectorposition vector: A learned vector for each place in the text, added to the tokenโs vector so the model knows word order. Ch 9, one for each place in the text, learned in training like the token vectors. (This is position in the text, not the position in meaning from Ch 5.) Now โdogโ second and โdogโ fifth start out as different vectors, and attention can tell the sentences apart. GPT-2 has 1,024 position vectors, one for each place in its context window (Ch 8). There is no vector for place 1,025, which is one reason the window stops there.
Newer models such as Llama 3 add no position vectors. Instead they turn each query and key by an angle that grows with its place in the text, so the score between two tokens also depends on how far apart they are.[2][3][3][4]
In symbols, GPT-2โs first layer starts each token from
where is the tokenโs place in the text, is its token ID, is that tokenโs row in the 50,257 ร 768 table of token vectors, and is row of the 1,024 ร 768 table of position vectors.
Rotary position embedding, the method Llama 3 uses, works on the queries and keys instead. It splits each one into pairs of numbers and turns pair of the token in place by the angle , with
where is the length of the query and is a fixed base. When the query in place meets the key in place , the two turns partly cancel, and the score depends on the places only through the distance between them, .[3] The original paper used ; Llama 3 raised it to 500,000 to handle longer texts.[4]
Real attention in GPT-2
Here are attention patterns recorded from GPT-2. Each line runs from the word doing the looking (right) to an earlier word (left); thicker lines mean more attention.
Some patterns are surprisingly readable:
- Who gets the drink? In โWhen Mary and John went to the store, John gave a drink toโ, GPT-2 predicts โ Maryโ next. Layer 9, head 9 looks from the last word back at โMaryโ far more than at either โJohnโ (the pull toward โWhenโ is explained below). Researchers who took this behavior apart found a small set of heads, including 9.6 and 9.9, that find the right name and copy it forward.[2][4][5]
- Whose fleece? In the nursery rhyme, layer 9, head 0 looks from โitsโ back to โlambโ.
- What was too big? The same head looks from โitโ mostly to โsuitcaseโ, in both versions of the trophy sentence. That isnโt a mistake in the viewer: โbigโ and โsmallโ come after โitโ, and a word can only look back. The model has to sort out โitโ later, at the words after the clue.
GPT-2 isnโt very good at that last kind of puzzle. The patterns you can read are a few bright spots in a mostly murky picture.
GPT-2 isnโt very good at that last kind of puzzle. Even the largest GPT-2 answered 70.70% of Winograd questions correctly, where guessing gets 50%.[5][2] The patterns you can read are a few bright spots in a mostly murky picture.
Many heads, many layers
One set of queries, keys, and values is called an attention headattention head: One attention pattern with its own weights. Each layer runs several side by side; GPT-2 small has 12 per layer. Ch 9. GPT-2 runs 12 heads side by side in each of its 12 layers, each free to look for something different. Switch heads in the viewer: many donโt have a job you can name, and many put most of their attention on the very first word, a resting spot for when thereโs nothing useful to find.[3]
One set of queries, keys, and values is called an attention headattention head: One attention pattern with its own weights. Each layer runs several side by side; GPT-2 small has 12 per layer. Ch 9. Each layer of GPT-2 runs 12 heads side by side, each with its own weights, so each can look for something different. With 12 layers, thatโs 144 heads. Layers and heads are numbered from 0, as in research papers.
Switch to other heads in the viewer and youโll see that many donโt have a job you can name. Youโll also see lots of heads putting most of their attention on the very first word. In these sentences, from the fourth word on, that happens more than half the time. Researchers think itโs a resting spot: softmax always has to share out 100%, so a head with nothing useful to find parks its attention there.[6][6]
Here is one head in full, for the sentence about Mary and John. Each row is a word looking back, each column a word it could look at. Step through what the head works out: a score for every pair, then the mask that hides every later word, then softmax, which turns each row into percentages. The buttons page through all 144 heads.
Here is one head in full, for the sentence about Mary and John: every row is a word doing the looking, every column a word it could look at. Step through the formula from the queries and keys above: first the score for every pair, then the mask, then softmax along each row. Page through all 144 heads with the buttons.
The head works out a score for every pair, even for words that come later; the mask then throws those away, 91 of the 196 squares. For head 9.9, the last wordโs scores for โMaryโ and โJohnโ are close, 4.25 and 3.23, yet after softmax โMaryโ gets 36% and โJohnโ 13%. Softmax turns a small lead in score into a big lead in weight.
The scores exist for every pair, later words included: the head computes them all at once, and the mask throws away the 91 of 196 that look ahead before softmax sees them. For head 9.9, the last wordโs scores for โMaryโ and the first โJohnโ differ by about 1 (4.25 against 3.23), yet after softmax โMaryโ gets 36% and that โJohnโ 13%. Softmax turns small gaps in score into large gaps in weight. โWhenโ scores 4.24 and also gets 36%: the resting spot described above.
Since a weight is divided by the rowโs total, two scores that differ by get weights in the ratio , whatever the rest of the row holds: , and 36% is about 2.8 times 13%.
Recipe card
Recap
- Attention lets each token pull in information from any earlier token, weighted by relevance.
- Each token makes a query, a key, and a value. Query times key gives a score; softmax turns scores into weights; the weights blend the values.
- A token can only look back, never ahead.
- Attention alone ignores word order, so GPT-2 adds a learned position vector to each tokenโs vector.
- GPT-2 has 12 heads in each of its 12 layers. A few have clear jobs, like finding the name that comes next; most are harder to read.
- One head computes . In GPT-2, .
Next question: attention moves information between tokens. How does it fit into a whole model?
Sources
- Ashish Vaswani et al. (2017). Attention Is All You Need. NeurIPS 2017.
- Kevin Wang et al. (2022). Interpretability in the Wild: a Circuit for Indirect Object Identification in GPT-2 small. ICLR 2023.
- Guangxuan Xiao et al. (2024). Efficient Streaming Language Models with Attention Sinks. ICLR 2024.
Sources
- Ashish Vaswani et al. (2017). Attention Is All You Need. NeurIPS 2017.
- Jianlin Su et al. (2024). RoFormer: Enhanced Transformer with Rotary Position Embedding. Neurocomputing 568.
- Aaron Grattafiori et al. (2024). The Llama 3 Herd of Models. arXiv.
- Kevin Wang et al. (2022). Interpretability in the Wild: a Circuit for Indirect Object Identification in GPT-2 small. ICLR 2023.
- Alec Radford et al. (2019). Language Models are Unsupervised Multitask Learners. OpenAI.
- Guangxuan Xiao et al. (2024). Efficient Streaming Language Models with Attention Sinks. ICLR 2024.
Sources
- Ashish Vaswani et al. (2017). Attention Is All You Need. NeurIPS 2017.
- Alec Radford et al. (2019). Language Models are Unsupervised Multitask Learners. OpenAI.
- Jianlin Su et al. (2024). RoFormer: Enhanced Transformer with Rotary Position Embedding. Neurocomputing 568.
- Aaron Grattafiori et al. (2024). The Llama 3 Herd of Models. arXiv.
- Kevin Wang et al. (2022). Interpretability in the Wild: a Circuit for Indirect Object Identification in GPT-2 small. ICLR 2023.
- Guangxuan Xiao et al. (2024). Efficient Streaming Language Models with Attention Sinks. ICLR 2024.