9. Scaled dot-product attention
The heart of the transformer in four steps: dot the query with every key, divide by √d_k, take the softmax, and mix the values by the weights.
Pick a sentence, the word that asks, and a head. The query of that word meets the key of every word in turn; the scores are divided by the square root of d_k, the softmax turns them into weights that add up to 1, and the values are mixed in those proportions. The last frame is the head's output for that word, exactly as the engine and PyTorch compute it.
The idea
Charles's post gives the recipe in three steps, after the queries, keys and values of chapter 8. Attention scores: “the relevance between tokens is measured by calculating the dot product between Query and Key vectors.” Scaling and normalization: “the scores are divided by the square root of the Key dimension (\(d_k\)) and passed through a softmax function, converting them into probabilities.” Weighted sum: “the Value vectors are combined using these probabilities, creating context-aware outputs.”
That is scaled dot-product attention, and you just watched it: one word's query meets each key (chapter 3's dot product), the scores shrink by √d_k, the softmax (chapter 6) turns them into weights, and the word's new vector is the values mixed in those proportions. The weights are the arrows of chapter 7.
Every word does this at the same time, in every head of every layer. The output for a word is no longer just that word: it carries some of every word it attended to, which is what “context-aware” means.
A worked example: “She eats apples”, complete
The post compares the query of She with the key of apples: [1, 0] · [1, 1] = 1. Its score weights the value of apples when the model builds the new vector for She. To finish the example, take all three keys. With the matrices of chapter 8 the keys are She [0, 1], eats [1, 0] and apples [1, 1], and She's three scores are 0, 1, 1.
d_k is 2 here, so the scores are divided by √2. She gives 20 % of her attention to herself, 40 % to eats and 40 % to apples. The values are She [1, 0], eats [−1, 1] and apples [0, 1], so She's new vector is the mix:
On the real model, in the clip's first sentence, head 3 of the second layer gives “it” 87.9 % of its attention to “dog”, with d_k = 16, so its scores are divided by 4.
The formula
The post and the paper write the four steps as one line, for every word at once:
- \(Q,\ K,\ V\)
- the queries, keys and values of all the words, one row per word (chapter 8)
- \(QK^{\top}\)
- every query dotted with every key: a grid of scores, one row per asking word
- \(\sqrt{d_k}\)
- the square root of the key length: 8 in the paper (d_k = 64), 4 in our model (d_k = 16)
- \(\operatorname{softmax}\)
- applied to each row: the scores of one word become weights that add up to 1
- \(\cdot\, V\)
- each row of weights mixes the values: the word's output
Why divide by √d_k?
A dot product adds up d_k products. The more numbers in each vector, the larger those sums can swing. Large scores push the softmax to give one word almost everything, and a softmax that is nearly all-or-nothing barely changes when the model adjusts its weights, so training slows. Dividing by √d_k keeps the scores' spread the same at every size. Try it:
- unscaled q · k
- q · k / √d_k
Spread of q · k: 22.79 (√d_k = 22.63). Divided by √d_k: 1.01.
One key takes more than 90 % of the weight in 87.1 % of trials unscaled, in 0.0 % scaled.
Random queries and keys whose numbers have mean 0 and spread 1, of the size d_k you choose. The chart shows, over 2,000 trials with eight keys each, how much weight the softmax gives the strongest key, without scaling and with it. Below it, the spread of the dot products against √d_k, and how often one key takes more than 90 % of the weight.
Why this is true: the spread of a dot product grows like √d_k (the paper's footnote 4)
Suppose every number in q and k is random, with mean 0 and variance 1, and independent of the others. Each product q_i k_i then has mean 0 and variance 1.
The dot product adds d_k such products. Variances of independent terms add up, so the sum has variance d_k, and spread (standard deviation) √d_k.
Dividing by √d_k divides the spread by √d_k: the scaled scores have spread 1 whatever d_k is. The paper puts it in one line: q · k has “mean 0 and variance d_k”.
Why it matters
This one line is where most of a long prompt's attention cost goes: the grid QKᵀ has one score for every pair of tokens, in every head of every layer. A prompt twice as long makes the grid four times as large. That is why providers limit context windows, why very long prompts are slower, and why so much engineering goes into making this step cheaper.
It is also the step behind “the model lost track of something in the middle of my prompt”: every word's weights must add up to 1, so in a very long context each of thousands of tokens gets a sliver, and the softmax has to pick a few.
Where it fails
- The weights must go somewhere. The softmax always adds up to 1, so a head with nothing useful to do still has to look somewhere; in our model such heads rest on the full stops, <s> and the end marker (the head gallery shows them).
- Quadratic in length. n words make an n × n grid; the paper's Table 1 counts it (chapter 21).
- One mix per head. A single head gives each word one blend of the values. To track several relations at once, the paper runs several heads side by side (chapter 11).
Exercises
Try each one before you open a hint. The lab's engine checks your answer against the same models the chapter uses.
A weight by hand
A query's scores against three keys are [2, 0, 1], and d_k = 4. What weight does the first key get after scaling and the softmax? Three decimals.
She's weight on eats
She's scaled scores are [0.00, 0.71, 0.71] (for She, eats and apples). What weight does the softmax give eats? Two decimals.
The paper's divisor
The paper's keys have d_k = 64 numbers. By what number are its scores divided?
She's new vector
Mixing the values with She's weights gives She's output. What is its second number? Two decimals.
What scaling prevents
In the experiment, set d_k to 512. What does the chart show?
In the paper
Section 3.2.1 names it “Scaled Dot-Product Attention” and writes the formula above as its equation (1); Figure 2 (left) draws the same steps as boxes: MatMul, Scale, Mask (opt.), SoftMax, MatMul. Its reason for √d_k: “We suspect that for large values of \(d_k\), the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients”, with footnote 4's variance argument.
In the paper: section 3.2.1