Topic 2 of 5 · 4 min read
Queries, keys and values as lookup
Goal: Work out by hand on a toy example which token receives the most attention weight from query-key scores and a softmax.
Attention is a soft lookup: each token makes a query, compares it with a key from every earlier token, turns the scores into weights with a softmax, and takes a weighted mix of their values.
Check yourself · 1 of 3
In attention, what is compared with a token's query to produce a score?
Why it matters
Once you can do this on paper for three tokens, the big diagrams stop being magic. You also see why the same code runs at any context length, and what a "weight" in an attention visualizer actually is.
The three vectors
Each token's embedding is multiplied by three learned matrices to give three vectors:
- Query (Q): what this token is looking for.
- Key (K): what this token advertises about itself.
- Value (V): the information it hands over if someone attends to it.
Think of a dictionary lookup, but soft. A normal lookup finds one key that matches and returns one value. Attention scores every key, then returns a blend, mostly of the best matches.
The four steps
- Score. For the current token, take the dot product of its query with every key. A bigger number means a better match.
- Scale. Divide by the square root of the key size. This keeps scores from growing with vector length and making the softmax too sharp.
- Softmax. Turn the scores into weights that are positive and sum to 1.
- Mix. Multiply each value by its weight and add them up. That sum is the token's new vector.
A toy example
The current token is "it" and the key size is 4, so we divide by 2. Raw dot products with three earlier tokens:
import math
scores = {"server": 4.0, "job": 2.0, "the": 0.0}
scaled = {k: v / math.sqrt(4) for k, v in scores.items()} # 2.0, 1.0, 0.0
exps = {k: math.exp(v) for k, v in scaled.items()} # 7.39, 2.72, 1.00
total = sum(exps.values()) # 11.11
weights = {k: round(v / total, 2) for k, v in exps.items()}
print(weights) # {'server': 0.67, 'job': 0.24, 'the': 0.09}
"it" takes about two thirds of its new vector from "server", a quarter from "job", and a little from "the". Nothing is thrown away; it is a blend.
Before and after
Weak: "Attention picks the most important word." Better: "Attention gives every visible word a weight between 0 and 1, the weights sum to 1, and the output is the weighted average of their values." No token is selected; the weights are soft.
What goes wrong
- Reading weights as explanations. A heavy weight shows where information flowed, not why the model answered as it did.
- Forgetting the scale. Without dividing by the square root of the key size, large vectors push the softmax toward a single winner and training gets unstable.
- Mixing up K and V. Keys decide how much to read; values decide what is read. They are separate vectors for a reason.
Examples
Reading a weight table
A visualizer shows the token "it" attending to earlier tokens with weights server 0.67, job 0.24, the 0.09. The three numbers add up to 1.00. The new vector for "it" is 0.67 * V_server + 0.24 * V_job + 0.09 * V_the. Raising one weight always lowers the others.
What the scale does
With key size 64, raw dot products can easily reach values like 40. A softmax over 40, 20, 0 gives almost all weight to one token. Dividing by 8 (the square root of 64) gives 5, 2.5, 0, a much smoother spread, so the model can still learn from the other tokens.
Key points
- Each token produces a query (what it seeks), a key (what it advertises) and a value (what it gives).
- Scores are dot products of a query with each key; larger means a better match.
- Scores are divided by the square root of the key size so the softmax does not become too sharp.
- Softmax turns scores into weights that are positive and sum to 1; the output is the weighted sum of values.
- Attention is soft: no token is picked alone, every visible token contributes in proportion to its weight.
Common mistakes
- Saying attention "selects" one word; it computes a weighted blend of all visible values.
- Treating a high attention weight as a full explanation of why the model produced an answer.
- Mixing up keys and values: keys are used to score, values are what actually gets copied into the output.
- Skipping the scale step and expecting softmax scores to stay well behaved at large vector sizes.
Check yourself · 2 of 3
After the softmax, three tokens have weights 0.5, 0.3 and 0.2. What do the weights add up to, and what happens next?
Check yourself · 3 of 3
Why are query-key scores divided by the square root of the key size?
Practice items, not counted towards your mastery.
Start here
- The Illustrated Transformer (Jay Alammar) (opens in a new tab)ArticleFree
Step-by-step pictures of queries, keys, values, multi-head attention and the encoder-decoder stack.
- Transformer Explainer (Georgia Tech Polo Club) (opens in a new tab)ToolFree
Runs a small GPT-2 in your browser so you can watch attention weights change as you edit the prompt.
- 3Blue1Brown: Attention in transformers, step-by-step (opens in a new tab)VideoFree
A visual video lesson, with a written version, on queries, keys, values, masking and multi-head attention.
More for this topic
- Attention Is All You Need (Vaswani et al., 2017) (opens in a new tab)PaperFree
Defines scaled dot-product attention: softmax of query-key scores divided by the square root of the key size, applied to the values.