The problem: a word alone knows too little
In the embeddings chapter you saw that “bank” has exactly one row in the table and therefore ends up somewhere between the furniture corner and the money corner. In “I sit on the bank by the river” and in “I get money from the bank” it starts with exactly the same list of numbers. The word alone doesn't know what it means in this sentence.
It is similar with references across many words: “The cat, which spent the whole day in the garden, is now tired.” To predict “tired” after “is now”, the model has to know who is tired: the cat, ten words earlier. The bigram model only saw the last token. That doesn't get you far here.
The idea: copying from the neighbors
The solution is surprisingly plain: every word may look at the other words in the sentence and take over information from them into its own list of numbers. In the first sentence “bank” takes over something from “river” and becomes a riverbank. In the second sentence it takes over something from “money” and becomes a financial institution.
At its core, that is all attention does: every word refreshes itself with context from the other words. This idea was the big breakthrough in 2017; the famous paper about it was called “Attention Is All You Need”.
Only one question remains: from whom should a word take how much? A lot from “river”, little from “the”. But how does the word know that?
Who listens to whom, and how much?
Picture a meeting where every word brings three things:
- A question (query): what is the word looking for right now? “Bank” asks roughly: “Is there anything here that tells me which bank I am?”
- A name tag (key): what does the word have to offer? “River” wears something like “I am a place outdoors”, “money” wears “I am finance stuff”, “the” wears hardly anything interesting.
- A content (value): what does the word tell you when you listen to it?
“Bank” holds its question against every name tag. If it fits well, “bank” listens to that word a lot; if it fits badly, hardly at all. That turns into shares that add up to 100 percent: for example 45 percent for “river”, 24 percent for “sit” and almost nothing for “the”. The new list of numbers for “bank” is then a mix of what the others tell: 45 percent “river”, 24 percent “sit” and so on.
Where do question, tag and content come from?
Every word computes them from its own list of numbers, that is, from its embedding, using three weight tables that are the same for all words. That is why the two are closely linked: because “river” has an embedding from the outdoors corner, it gets a name tag that fits the question of “bank”.
And the three weight tables? They start out random, like all weights. Then comes the training from the chapter on cross-entropy: the model is supposed to predict the next word, and the answer is simply the word that comes next in the real text. If “bank” listens to the wrong thing, say “the”, it doesn't know afterwards which bank is meant. It guesses worse, and the loss is high. The gradient nudges the weight tables a little so that next time “bank” listens more to “river” or “money”. After millions of sentences, useful questions and name tags have emerged by themselves. That is exactly what the “training progress” slider above acts out.
Nobody programs “bank looks for a place” or “pronoun looks for noun”. Patterns like these emerge because they help with predicting.
The same thing once more with the cat sentence from above. The “is” asks something like “Who is the subject here?”, and the tag of “cat” fits best. Try it: tap a word and see whom it listens to.
Now with numbers: a weighted mix
Now let's calculate it. Imagine three values: 10, 20 and 30. A value is the content that can be passed along. To keep it simple, each one is a single number here; in a real model it is a list of numbers.
With the weights 0.5, 0.25 and 0.25 the mix is: 0.5×10+0.25×20+0.25×30=17.5. More weight means: more from this source. The weights add up to one, like ingredients in a recipe that make up 100 percent together.
You know a weighted sum like this from the neuron. The big difference: in a neuron the weights are fixed and get trained. In attention the weights are computed fresh for every text. In a different sentence, the same position looks somewhere else.
Three roles for every position
From each position's list of numbers, three learned layers compute three new lists:
| Name | Translation and role |
|---|---|
| Query, Q for short | “Search request”: which pattern does the reading position compare the sources with? |
| Key, K for short | “Comparison feature”: which list of numbers does a source offer for comparison? |
| Value, V for short | “Content”: which list of numbers gets taken over in the mix? |
So every position plays all three roles at once: it asks (query), it can be found (key) and it has something to offer (value). How exactly to ask and to be found, the model learns during training. A learned conversion into a new list of numbers like this is called a projection, by the way.
Comparing query and key
Our query is [1,0]. The three keys are [1,0], [0,1] and [1,1]. We compare using the dot product from chapter 9: multiply matching numbers, add up.
| Source | Calculation | Comparison score |
|---|---|---|
| Key 1 = [1,0] | 1×1 + 0×0 | 1 |
| Key 2 = [0,1] | 1×0 + 0×1 | 0 |
| Key 3 = [1,1] | 1×1 + 0×1 | 1 |
Sources 1 and 3 fit equally well, source 2 not at all. The higher the score, the better question and label fit.
Scores become mixing weights
First a small intermediate step: we divide the scores by the square root of the length of the lists (here 2, so by about 1.414). [1,0,1] becomes about [0.707;0;0.707]. This is just a fixed size adjustment so the numbers don't explode with long lists. Nothing is learned here.
Then our old friend softmax turns them into percentages: about [0.401;0.198;0.401]. Positive, adding up to one. So our position takes about 40 percent from value 1, 20 percent from value 2 and 40 percent from value 3.
Computing the new output
With the values 10, 20 and 30:
0.401×10 + 0.198×20 + 0.401×30 = 20.
That exactly 20 comes out is due to the symmetric example. Try it in the experiment: if you only change value 3, the weights stay the same but the result changes. If you change the query, the weights shift. That way you can see the two parts cleanly separated: query and key decide where to look. The value decides what gets taken along.
You can go through the whole path from the lists of numbers to the new output step by step here:
All positions at once
For a whole text, every position gets its own query and therefore its own row of scores. Together they form a table, the score matrix: the row means “who is reading”, the column “who is being read”. Softmax is applied to each row separately; each position hands out its own 100 percent.
And because all of this is matrix multiplication, a graphics card can compute it for thousands of positions at the same time. That is why transformers scale so well.
One thing stands out: the calculation compares contents but knows nothing about order. Swap two sources and nothing changes. “Dog bites man” would be the same as “man bites dog”! That is why every position also gets position information. How that works is shown in the chapter on the transformer block.
The familiar calculation in short form
| Symbol | Meaning in the calculation just explained |
|---|---|
| Q | Table of all query vectors |
| K | Table of all key vectors |
| The same key table with rows and columns swapped | |
| All query–key dot products as one table | |
| d | Number of components per query or key |
| A | Table of mixing weights after row-wise softmax |
| V | Table of contents to mix, i.e. the values |
| Y | Table of new outputs, one per reading position |
Read the formula: compare queries with keys, scale, softmax per row, mix the values with that. Exactly the steps from above.
Watch out for a name clash: here V is the value table. In shapes like [B,T,V], V instead stands for the vocabulary size. Common, unfortunately, and confusing.
What is learned and what is computed fresh each time
The layers that produce Q, K and V have weights, and those get trained. The attention weights themselves (the percentages), on the other hand, are intermediate values computed fresh for every text. There is no fixed table saying “word 5 always looks at word 2”.
One more problem
So far every position could read all sources, including later ones. In training that would be cheating: the position could simply look at the next word it is supposed to predict. We have to cover up the future. That is called a mask, and it is what the next chapter is about.
Build it yourself: in step 4 of part VII you program this attention yourself, and check it against PyTorch's built-in version.
Key points
- An embedding only knows its own word. Attention lets every word copy from the other words in the sentence; that is how “bank” becomes a riverbank or a financial institution.
- How much it takes from whom is decided by comparing query (question) and key (name tag). Softmax turns that into shares, which are used to mix the values (contents).
- The shares are computed fresh for every text. What gets trained are the tables that produce Q, K and V, through the perfectly normal loss of predicting the next word.