LLM Kitchen
Explanations

Part IV ยท Context

Ch 9. Attention

A spotlight on the past

A model uses 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 , 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:

Step through

Queries, keys, and values

Made-up example
The 11%trophy 50%suitcase 28%it 11% (itself)

Spotlight: โ€œitโ€ shines a light back on the earlier words (and itself). How brightly each one is lit decides how much of it gets mixed in.

Made-up 2- and 3-number vectors so the arithmetic is readable. GPT-2 small uses 64 numbers per head, 12 heads per layer.

Step 1 of 4 or use โ† โ†’ keys

Spotlight: โ€œitโ€ shines a light back on the earlier words (and itself). How brightly each one is lit decides how much of it gets mixed in.

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

Attentionโก(Q,K,V)=softmaxโก(QKโŠคdk+M)V

Each row of Q, K, and V is one tokenโ€™s query, key, or value. They come from the token vectors X, one row per token, times three learned weight matrices: Q=XWQ, K=XWK, and V=XWV. QKโŠค is the grid of scores, every query times every key. dk is the number of values in each key, and dk is the fixed number the scores are divided by. M 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 dk=768/12=64 numbers, and the scores are divided by 64=8. The 12 headsโ€™ outputs are put side by side, back to 768 numbers, and multiplied by one more learned matrix, WO.[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, n tokens need

n(n+1)2

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 , 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 , 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

xi=eti+pi

where i is the tokenโ€™s place in the text, ti is its token ID, eti is that tokenโ€™s row in the 50,257 ร— 768 table of token vectors, and pi is row i 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 j of the token in place m by the angle mฮธj, with

ฮธj=bโˆ’2j/d

where d is the length of the query and b is a fixed base. When the query in place m meets the key in place n, the two turns partly cancel, and the score depends on the places only through the distance between them, mโˆ’n.[3] The original paper used b=10,000; 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.

Try it

Who looks at whom

Recorded ยท GPT-2 small
WhenยทMaryยทandยทJohnยทwentยทtoยทtheยทstore,ยทJohnยทgaveยทaยทdrinkยทto

Layer 9, head 9: โ€œยทtoโ€ looks most at ยทMary (36%), When (36%), ยทJohn (13%).

Click a word on the right to see what it looks at. A word can only look back at itself and earlier words. Layers and heads are numbered from 0, as in research papers.

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 . 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 . 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.

Try it

One head, step by step

Recorded ยท GPT-2 small
Step
118 of 144
WhenWhenยทMaryยทMaryยทandยทandยทJohnยทJohnยทwentยทwentยทtoยทtoยทtheยทtheยทstoreยทstore,,ยทJohnยทJohnยทgaveยทgaveยทaยทaยทdrinkยทdrinkยทtoยทto

Head 9.9: after softmax, โ€œยทtoโ€ puts 36% on โ€œยทMaryโ€ and 36% on โ€œWhenโ€.

Row โ€œยทtoโ€ in numbers
Each earlier wordโ€™s score, after the mask, and weight
Looked atScoreMaskedWeight
When4.244.2436%
ยทMary4.254.2536%
ยทandโˆ’0.33โˆ’0.330.4%
ยทJohn3.233.2313%
ยทwentโˆ’3.67โˆ’3.67<0.1%
ยทtoโˆ’3.54โˆ’3.54<0.1%
ยทtheโˆ’0.50โˆ’0.500.3%
ยทstoreโˆ’1.87โˆ’1.87<0.1%
,โˆ’0.24โˆ’0.240.4%
ยทJohn3.213.2113%
ยทgaveโˆ’2.61โˆ’2.61<0.1%
ยทaโˆ’0.57โˆ’0.570.3%
ยทdrinkโˆ’1.41โˆ’1.410.1%
ยทtoโˆ’1.10โˆ’1.100.2%

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 es divided by the rowโ€™s total, two scores that differ by ฮ” get weights in the ratio eฮ”, whatever the rest of the row holds: e4.25โˆ’3.23โ‰ˆ2.8, 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 softmaxโก(QKโŠค/dk+M)V. In GPT-2, dk=64.

Next question: attention moves information between tokens. How does it fit into a whole model?

Sources

  1. Ashish Vaswani et al. (2017). Attention Is All You Need. NeurIPS 2017.
  2. Kevin Wang et al. (2022). Interpretability in the Wild: a Circuit for Indirect Object Identification in GPT-2 small. ICLR 2023.
  3. Guangxuan Xiao et al. (2024). Efficient Streaming Language Models with Attention Sinks. ICLR 2024.

Sources

  1. Ashish Vaswani et al. (2017). Attention Is All You Need. NeurIPS 2017.
  2. Jianlin Su et al. (2024). RoFormer: Enhanced Transformer with Rotary Position Embedding. Neurocomputing 568.
  3. Aaron Grattafiori et al. (2024). The Llama 3 Herd of Models. arXiv.
  4. Kevin Wang et al. (2022). Interpretability in the Wild: a Circuit for Indirect Object Identification in GPT-2 small. ICLR 2023.
  5. Alec Radford et al. (2019). Language Models are Unsupervised Multitask Learners. OpenAI.
  6. Guangxuan Xiao et al. (2024). Efficient Streaming Language Models with Attention Sinks. ICLR 2024.

Sources

  1. Ashish Vaswani et al. (2017). Attention Is All You Need. NeurIPS 2017.
  2. Alec Radford et al. (2019). Language Models are Unsupervised Multitask Learners. OpenAI.
  3. Jianlin Su et al. (2024). RoFormer: Enhanced Transformer with Rotary Position Embedding. Neurocomputing 568.
  4. Aaron Grattafiori et al. (2024). The Llama 3 Herd of Models. arXiv.
  5. Kevin Wang et al. (2022). Interpretability in the Wild: a Circuit for Indirect Object Identification in GPT-2 small. ICLR 2023.
  6. Guangxuan Xiao et al. (2024). Efficient Streaming Language Models with Attention Sinks. ICLR 2024.