Attention: how words look at each other

“Mina bought cups. They soon broke.” What does “They” mean here? You look back and know it means the cups. Attention is how a model does this with numbers. Pick a word and see where it looks.

Short answer. Attention is a calculation where each word (token) in a sentence decides how much to look at every other word, then mixes their information by those shares to build a new meaning for itself. The shares come from the dot product of “what I am looking for” (the query) and “what the other word offers” (the key). The bigger the dot product, the more it looks.

A small toy model. The vectors have only 2 numbers, and a person picked the numbers to explain the idea. Real models use hundreds or thousands of numbers per vector, learn them in training, and run many of these calculations side by side (heads) and stacked (layers).

Sentence: “Mina bought cups. They soon broke.” (We left out the period.) Pick the word that looks.

Where the chosen word looks. Thicker line, more attention
All words. Row = looking, column = looked at

Each number in the grid is “how much the word in that row looks at the word in that column”. Each row adds up to 100%. “off” marks a blocked cell. Here one word is one token. Real models often cut text into smaller pieces.

Definitions

The text below explains with pictures and labs. These are the textbook definitions. X is the matrix with one token vector in each row, and d is the number of dimensions of the queries and keys (also written dk).

query, key, value
Three vectors you get by multiplying a token's vector by three different learned matrices WQ, WK, WV. Each token gets one of each. Stacked one per row, they form the matrices Q, K, V. Queries and keys have the same number of dimensions, d.

Q=XWQ,K=XWK,V=XWV

scaled dot-product attention
Take the dot products of queries and keys and divide them by √d to get scores. Apply softmax to each row to turn the scores into attention weights that add up to 1. Then use those weights to take a weighted sum of the values. Row i of the result is the new vector of token i.

Attention(Q,K,V)=softmax(QK𝖳d)V

self-attention, cross-attention
Self-attention makes Q, K and V all from the same sequence. Cross-attention makes Q from one sequence and K and V from another sequence. If the two sequences have lengths n and m, the matrix of attention weights is n × m.
causal mask
A way to let token i see only itself and the tokens before it (j ≤ i): before softmax, the score in every cell with j > i is set to −∞, so its attention weight becomes 0. This is the same as adding the matrix M below to the scores.

Mij={0j≤i−∞j>i

multi-head attention
Keep h sets of WQ, WK, WV, compute attention separately for each set (head), join the h results side by side, and multiply by an output matrix WO. For self-attention:

headi=Attention(XWQ(i),XWK(i),XWV(i))

MultiHead(X)=Concat(head1,…,headh)WO

1. Why we need it

The same word can mean different things. The “bank” in “river bank” is land. The “bank” in “bank account” is a business. You only know what “They” means by looking at what came before. One word on its own is often not enough.

Embeddings give each word one vector. But that vector does not know the context. “bank” gets the same vector in every sentence. Attention mixes in information from the words around it and builds a new vector that fits the context.

It can look at far away words directly. Older recurrent neural networks (RNNs) read words one at a time and passed a memory along. Information from a far away word could fade as it was passed many times. Attention compares every pair of words at once. Even the first and the last word are one step apart.

Try this. ① At the start, “They” is chosen. It looks at “cups” 68%, at itself 16% and at “Mina” 8%. The numbers found that “They” means the cups. ② Pick “broke”. It looks at “cups” 54% and “They” 22%. It is finding what broke. ③ “bought” looks at “Mina” and “cups” 33% each. Who bought, and what.

A person chose these numbers so that this happens. In a real model, training finds relations like these. Nobody tells the model which relations to look for.

2. Query, key and value: a library

Think of looking for a book in a library. You hold what you are searching for (the query). You compare it with the label on each book (the key). Then you read the contents (the value) of the books that match. Attention works the same way, with two differences. It does not pick one book. It reads every book a little, by share. And the way it compares is the dot product.

NameIn the libraryWhat it doesIn the lab
Query qWhat you search forWhat the chosen word is looking forGreen arrow
Key kThe label on a bookWhat each word shows to say “this is the kind of word I am”Blue arrows
Value vThe contents of a bookThe information a word actually hands over when it is looked atThe v column in the step table

Every word has its own q, k and v. All three come from the same word's vector. The model multiplies that vector by three different matrices (matrix multiplication). The numbers in the matrices are learned in training. So what a word looks for, what it shows, and what it hands over can all be different.

Pick a word. The same three matrices turn that word's vector x into q, k and v.

WQ WK WV
One x splits three ways and goes through three matrices. On each branch, matrix × x gives q, k or v.

q = WQ x, k = WK x, v = WV x

A person chose this lab's x's and matrices so that the q, k and v of “cups” and “They” are the same numbers as in the lab of section 3. With only 2 numbers in x and 2×2 matrices, all six words cannot match the numbers of section 3, so only these two are shown.

In this toy, the two numbers of v mean (how much like a person, how much like a thing). “Mina” is (1, 0). “cups” is (0, 1). “They” is (0.5, 0.5): on its own, it cannot tell a person from a thing. The verbs and “soon” are (0, 0). With only two numbers, v cannot hold any other meaning.

3. The calculation, one step at a time

The new vector of one chosen word comes out in four steps.

  1. Dot product. Take the chosen word's q and the k of every word, and find the dot product of each pair. It is bigger when they point the same way and are longer. This is the score.
  2. Divide by √d. d is how many numbers q and k have. Here d = 2, so we divide by √2 ≈ 1.41. Section 4 explains why.
  3. Softmax. Turn the scores into shares that add up to 1. Raise e (≈ 2.718) to the power of each score, then divide each result by their total. Every share is positive, and big scores pull further ahead. The sampling page covers softmax in more detail.
  4. Mix. Mix the v of every word by those shares (a weighted average). Add up share × v for every word. That sum is the chosen word's new vector.

q() = ( , )

Green arrows: from q to each word (①② number at the tip = score, ③ thickness = share). Black arrows: share × v flows into the new vector (④). Dashed grey: blocked.

Drag an arrow tip or type a number and the shares change right away. You can also change a key in the k column of the table. The causal mask and the multiplier from the lab above apply here too.

Try this. ① With “They” chosen, press “Next step” four times. ① The dot products are 3 for “cups”, 1 for “They”, 0 for “Mina”, −1 for “broke”, and −2 for “bought” and “soon”. ② Divided by √2, “cups” has 2.12. ③ The share of “cups” is 0.68. ④ The new vector is (0.16, 0.76). Before mixing, “They” was (0.5, 0.5). Now it leans toward “thing”. ② Move the green q to (0, 2). Now it points the same way as the key of “Mina”. “Mina” gets 50%, and the new vector is (0.62, 0.24), on the person side. If the word were “She” instead, this is how it would need to look. ③ Turn q around to (−2, 0). It now points away from the key of “cups”, and “cups” drops to 1%.

4. All at once: softmax(Q Kᵀ ÷ √d) V

Section 3 does one word. Doing every word at once gives a single formula. Stack the q of every word, one per row, into a table called Q. Do the same with the keys to get K, and with the values to get V.

Attention(Q, K, V) = softmax(Q Kᵀ ÷ √d) V

To see this formula built one piece at a time, with pictures, go to 5. How the formula is built.

PartIn plain words
Q KᵀThe dot product of every pair of words in one table. Row i, column j is “q of word i · k of word j”. Kᵀ is K turned on its side (rows and columns swapped), and one matrix multiplication does it all
÷ √dDivide every cell by √d
softmax(…)Turn each row, on its own, into shares that add up to 1. The grid in the lab is exactly this table
(…) VShare table × V. Each row mixes the v's by that row's shares. Every word gets one new vector

Why divide by √d. When d is large, a dot product adds up many terms, so the scores spread out a lot. Softmax then piles almost everything onto one word, and training works poorly. If the numbers in q and k are independent, with mean 0 and variance 1, the dot product has variance d. Dividing by √d brings the variance back to 1.

5. How the formula is built

We build the formula from section 4 one piece at a time. The words are the same three as in the hand example in section 6 (Mina · cups · They), and q, k and v are the same numbers as in the lab. In the picture, rows are the words that look (green q) and columns are the words looked at (blue k). The bar and number in each cell are the value for that pair.

Press “Next” to go one step at a time. A piece is added to the formula at the top (the orange background is the new piece), the picture changes by that step, and the reason appears below. An orange frame in the picture marks what is new in this step. The bars for scores (① and ②) and for shares (from ③ on) use different scales. This picture does not use what you changed in the labs above. It always starts from the original numbers.

  1. The score of one pair: q · k. The q of “They” is (2, 0) and the k of “cups” is (1.5, 1). Their dot product is 2×1.5 + 0×1 = 3. Why: as in section 3, the more two vectors point the same way, the bigger their dot product, so one number can say “how well do these match”.
  2. Every pair at once: Q Kᵀ. Stack the three q's as rows to get Q, a 3×2 table. Stand the three k's up as columns to get Kᵀ, a 2×3 table. In matrix multiplication, row i, column j is “row i of Q · column j of Kᵀ”, which is “q of word i · k of word j”. So one multiplication gives all 3×3 = 9 dot products. The row of “They” is 0, 3, 1. Why: you get every score at once instead of word by word. The rows of “Mina” and “cups” are all negative. Their q's were chosen to match the k's of the verbs (“bought”, “broke”) in the six word sentence, and these three words have no verbs, so nothing matches them well.
  3. Turn scores into shares: softmax(Q Kᵀ). In each row, raise e to the power of each score and divide by the row's total. For the row of “They”, divide 1, 20.09, 2.72 by their total 23.8 to get 0.04, 0.84, 0.11 (they add up to 0.99 because of rounding). Why: to mix the v's in the next steps, the shares must be above 0 and add up to 1. Scores can be negative and each row has a different total, so they cannot be used as they are.
  4. Less piling up: softmax(Q Kᵀ ÷ √d). Before softmax, divide the scores by √d. Here d = 2, so divide by √2 ≈ 1.41. The scores of the row of “They” become 0, 2.12, 0.71, and the shares change from 0.04, 0.84, 0.11 to 0.09, 0.73, 0.18. The big share shrank and the small ones grew. Why: the more numbers d a vector has, the further apart the scores spread. Assume the numbers in q and k are independent, with mean 0 and variance 1. Then one term qiki has mean 0 and variance 1, and the dot product q₁k₁ + q₂k₂ + … is a sum of d such terms, so its variance is d and its standard deviation is √d. With d = 64 the standard deviation is 8. If three scores sit one standard deviation apart, as in (−8, 0, 8), softmax gives about (0.0000, 0.0003, 0.9997): almost everything goes to one word. Divided by 8 they become (−1, 0, 1), which gives (0.09, 0.24, 0.67). Under the same assumption, dividing by √d brings the variance back to 1, so the scores stay at a similar size whatever d is. The original paper says that when softmax piles onto one word its gradients become very small, which makes training hard. We do not prove that here.
  5. Mix: Attention(Q, K, V) = softmax(Q Kᵀ ÷ √d) V. Multiply the share table (3×3) by V (3×2). Row i of the result is the v's mixed by the shares in row i, which is the new vector of word i. “They” = 0.09×(1, 0) + 0.73×(0, 1) + 0.18×(0.5, 0.5) = (0.18, 0.82). Why: the shares only say how much to look. The information a word actually receives is in the v's. Before mixing, “They” was (0.5, 0.5). Now it leans toward “thing”.

In the textbook formula, ÷√d sits inside softmax. Here we showed softmax first so you can compare the shares before and after dividing. The numbers in this toy were picked by a person, not drawn under the assumption above. Dividing by √2 just follows the rule.

6. Work it out by hand: three tokens

Shorten the sentence to three words: “Mina · cups · They”. The numbers are the same as in the lab. We find the new vector of “They” all the way through. The query of “They” is q = (2, 0).

WordKey kValue v
Mina(0, 2)(1, 0)
cups(1.5, 1)(0, 1)
They(0.5, 1.5)(0.5, 0.5)
  1. Dot products. q · k(Mina) = 2×0 + 0×2 = 0, q · k(cups) = 2×1.5 + 0×1 = 3, q · k(They) = 2×0.5 + 0×1.5 = 1.
  2. Divide by √2. 0 ÷ 1.41 = 0, 3 ÷ 1.41 ≈ 2.12, 1 ÷ 1.41 ≈ 0.71.
  3. Softmax. Powers of e: e⁰ = 1, e²·¹² ≈ 8.34, e⁰·⁷¹ ≈ 2.03. The total is ≈ 11.37. Divide each by the total and the shares are 0.09, 0.73, 0.18. They add up to 1.
  4. Mix. 0.09 × (1, 0) + 0.73 × (0, 1) + 0.18 × (0.5, 0.5) = (0.09, 0) + (0, 0.73) + (0.09, 0.09) = (0.18, 0.82).
  5. Read it. Before mixing, “They” was (0.5, 0.5). After mixing, it is (0.18, 0.82): much more like a thing. With all six words you get the lab's value, (0.16, 0.76). The verbs take a little of the share, and their v is (0, 0), so the numbers get a bit smaller.

7. Key properties

PropertyIn plain words
Each row of shares adds up to 1The new vector is a weighted average of the v's. It never goes outside the range the v's cover
Shares are above 0 (only blocked cells are 0)Softmax never gives exactly 0. However low the score, a word still gets a tiny bit
The more q and k point the same way, and the longer they are, the bigger the shareBecause their dot product is bigger. If they point opposite ways, the word is almost ignored
It does not know the orderA word's position is not part of the calculation. Shuffle the words, and each word still gets the same shares (section 11)
The work grows with the square of the number of tokensn words give n × n shares (section 12)

8. Things to switch: causal mask and multiplier

Causal mask. Models that write text one token at a time learn by “guess the next token”. If a word could see the words after it during training, it would be looking at the answer. So each word is only allowed to see itself and the words before it. The trick is simple. Set the score of each blocked cell to −∞. e to the power of −∞ is 0, so after softmax the share of that cell is 0. In the grid, the triangle at the top right gets blocked.

Multiplier (sharper or flatter). A number multiplied into the scores before softmax. Make it bigger and big scores pull further ahead, so the shares pile onto one word. Make it 0 and every score becomes 0, so every share is the same. This is the same as dividing the scores by a temperature T (multiplier = 1 ÷ T). Normal attention has no such slider. Dividing by √d plays the role of a fixed multiplier. We added it so you can see how sensitive softmax is to the size of the scores. Temperature for choosing words is on the sampling page.

Try this. ① Turn on “Can't see later words”. The top right of the grid changes to “off”. “Mina” has no word before it, so it can only look at itself (100%). “They” can no longer see “soon” and “broke”, so the other four share the total. “cups” goes up from 68% to 72%. “broke” is last, so every word is already before it, and its row does not change. ② Turn the mask off and set the multiplier to 0. Every cell becomes 17% (= 1 ÷ 6). ③ Set the multiplier to 3. “They” looks at “cups” 98%. Set it to 0.5 and the share spreads out to 41%.

9. Self-attention and cross-attention

The lab on this page is self-attention. q, k and v all come from the same sentence. The sentence looks at itself.

Cross-attention works between two sentences. q comes from one sentence, and k and v come from the other. Translation is a good example. While writing the translation one word at a time, the q at the current spot is compared with the k of each word in the original, and the v's of the original are mixed in. The method of Bahdanau and others (2014), which let a translation model find the relevant parts of the original by itself, has this shape. They computed the score with a small neural network instead of a dot product.

Self-attentionCross-attention
Where q comes fromThis sentenceThis sentence (for example, the translation being written)
Where k and v come fromThis sentenceAnother sentence (for example, the original)
Shape of the gridn × nLength of this sentence × length of the other

10. Many heads: different relations

The lab has one table of shares. A real model keeps several sets of matrices that make q, k and v, and runs them side by side. One set is called a head. The base model in the original paper (Vaswani and others, 2017) has 8 heads.

Each head gets its own table of shares, so each can look at a different relation. One head might look at what a pronoun points to, another at a verb and its object. The figures at the end of the original paper show heads that seem to find what a pronoun refers to. The new vectors from all heads are joined end to end, then multiplied by one more matrix to bring them back to the original size.

The same sentence as section 3, with two heads. Head 1 uses the numbers of the lab in section 3. Head 2 has different q, k and v. In each table a row is the word looking, a column is the word looked at, and each row adds up to 100%.

Head 1: “They” → “cups”, what it points to
Head 2: “They” → “broke”, a word and its verb

Green arrows: share × v of each word flows into that head's new vector (thicker = bigger share). Black arrows: joining (③) and multiplying by the output matrix (④). Training decides what each head ends up looking at. Here a person set it by hand to show the idea. The same goes for the numbers in the output matrix.

These attention layers are stacked. The output of one layer is the input of the next, so higher layers hold vectors with more context mixed in. How they are stacked is on the Transformer page.

A warning. An attention picture only shows how much of each word's information was mixed in during the calculation. It is not an explanation of why the model gave its answer (Jain and Wallace, 2019).

11. The order has to be added separately

A word's position is not part of the attention calculation. Shuffle the words, and each word's shares and new vector stay the same. Only their places move. You can see this in the lab too. The Korean version of this page puts the same numbers in a different word order, and its pronoun row is the same as the “They” row here: 68%, 16%, 8%.

But in text, order matters. a − b and b − a use the same three tokens and mean different things. “Dog bites man” is not “man bites dog”. So the Transformer adds a vector that says “this is position number such and such” to each word's vector. This is called position information. The Transformer page has more.

12. The work grows with the square: the context window

With n tokens there are n × n shares. Double the tokens and the share table and the work grow 4 times. 1,000 tokens give 1 million cells. 10,000 tokens give 100 million cells. Every head in every layer has one of these tables.

So each model has a limit on how many tokens it can take at once. This is the context window. There are several reasons for the limit, and this square cost is one of them. Text longer than the context window has to be cut or split into parts.

Where it is used

Frequently asked questions

What is attention?

It is a calculation where each word (token) in a sentence decides how much to look at every other word, then mixes their information by those shares to build a new meaning for itself. The shares come from the dot product of “what I am looking for” (the query) and “what the other word offers” (the key).

Where do the query, key and value come from?

All three come from the same word's vector. The model multiplies that vector by three different matrices. The numbers in those matrices are learned in training.

Why divide by √d?

When the number of entries d is large, dot products spread out a lot. Softmax then piles almost everything onto one word, and training works poorly. Dividing by √d keeps the scores at a similar size no matter how many entries there are.

How is self-attention different from cross-attention?

In self-attention, the queries, keys and values all come from the same sentence. In cross-attention, the queries come from one sentence (for example, the translation being written) and the keys and values come from another (for example, the original text).

Does an attention picture tell me why the model gave its answer?

No. An attention picture only shows how much of each word's information was mixed in during the calculation. There are many heads and layers, and other parts of the model also do work, so the picture alone cannot explain why the model answered the way it did.

Words

Word used hereName in textbooks
Word, piece of a wordToken
Share, how much it looksAttention weight
What I am looking forQuery
The label a word showsKey
What a word hands overValue
Score before softmaxAttention score, logit
Dot product attention divided by √dScaled dot-product attention
Turning scores into shares that add up to 1Softmax
Mixing by shareWeighted average, weighted sum
Can't see later wordsCausal mask, masked self-attention
Looking within the same sentenceSelf-attention
Looking at another sentenceCross-attention, encoder-decoder attention
Several side by sideMulti-head attention, head
The grid pictureAttention map, heatmap
Multiplier1 ÷ temperature
Position informationPositional encoding
How many tokens fit at onceContext window, context length
How many numbers a vector hasDimension, d or dk
K turned on its sideTranspose, Kᵀ

Sources

← EmbeddingsTransformers and LLMs →