The question each token asks
Read this sentence: “The animal didn’t cross the street because it was too tired.” What does “it” mean? You know at once: the animal, because streets do not get tired. To understand “it”, you looked back at the other words and picked the one that mattered.
Attention gives a model the same ability. For every token, it computes how much to look at each earlier token, and then mixes their information into its own vector. After attention, the vector for “it” carries information about “animal”.
The bars show how much attention a word pays to the words up to and including itself (illustrative numbers, in the spirit of what real models do). “it” looks mostly at “animal”. Tap other words; notice that no word can look at words after it.
This interactive part needs JavaScript.
Queries, keys and values
Each token’s vector is multiplied by three different learned matrices, giving three new vectors:
- Query (q): what this token is looking for. Made by the
q_projmatrix you counted in the matrices lesson. - Key (k): what this token offers to others, as a label to be matched. Made by
k_proj. - Value (v): the information this token passes on if someone attends to it. Made by
v_proj.
The match between a query and a key is their dot product: large when they point the same way. This is why the vectors lesson called the dot product the most important operation in AI.
Attention by hand
Three tokens, “the cat sat”, with tiny 2-number vectors. We work out what the last token, “sat”, takes from the others.
| Token | Key | Value |
|---|---|---|
| the | [0, 1] | [1, 0] |
| cat | [2, 1] | [0, 3] |
| sat | [1, 0] | [2, 2] |
The query of “sat” is [1, 2].
1. scores = q · k = [2, 4, 1][1, 2]·[0, 1] = 2 for “the”, [1, 2]·[2, 1] = 4 for “cat”, [1, 2]·[1, 0] = 1 for “sat” itself.
2. scaled = scores ÷ √2 = [1.41, 2.83, 0.71]Divide by the square root of the vector length (here 2). This keeps scores from growing too large in long vectors, which would make the softmax all-or-nothing.
3. weights = softmax(scaled) = [0.18, 0.73, 0.09]“sat” pays 73 % of its attention to “cat”: the one doing the sitting.
4. output = 0.18×[1, 0] + 0.73×[0, 3] + 0.09×[2, 2] = [0.35, 2.38]A weighted average of the values. This is what gets added to the vector of “sat”.
Attention(Q, K, V) = softmax(Q·Kᵀ ÷ √d) · VEquation 1 of “Attention Is All You Need” (2017). Q, K and V are matrices with one row per token, so all tokens are computed at once. Kᵀ means K turned on its side, so that every query meets every key.
Quick check
No peeking: the causal mask
In a language model, a token may only look at itself and the tokens before it. Before the softmax, every score for a later token is set to minus infinity, which softmax turns into exactly 0. This is the causal mask, and the demo above shows it as the greyed-out words.
Why? Because of how training works. A model learns by predicting every next token in a text. If position 5 could see position 6, it could simply copy the answer. With the mask, one pass over a text of 4,096 tokens gives 4,096 honest predictions at once, all in parallel. That parallelism is the transformer’s great advantage over the old recurrent networks.
Many heads, and how they share
A single attention can only look for one kind of thing at a time. So each layer runs several in parallel, each with its own smaller queries, keys and values. These are attention heads. Llama 3.1 8B has 32 heads per layer, each working with vectors of 128 numbers (32 × 128 = 4,096). Their outputs are joined and mixed by the o_proj matrix.
Heads specialise during training. Researchers have found heads that look at the previous token, heads that link a pronoun to its noun, and induction heads, which spot that the current text repeats an earlier pattern and predict that it will continue the same way. Induction heads are a big part of how models learn from examples placed in their prompt.
Keys and values have to be kept in memory for every earlier token (the KV cache, which has its own lesson). Giving every head its own keys and values is expensive, so newer models share them:
| Design | Idea | Example |
|---|---|---|
| Multi-head attention (MHA) | Every query head has its own key and value head | The original 2017 transformer |
| Multi-query attention (MQA, 2019) | All query heads share one key and value head | Fastest, with some loss of quality |
| Grouped-query attention (GQA, 2023) | Groups of query heads share a key and value head | Llama 3.1 8B: 32 query heads, 8 key-value heads. Qwen3.8-27B: 24 and 4 |
| Multi-head latent attention (MLA, 2024) | Keys and values are compressed into one small vector per token, and expanded when needed | DeepSeek-V2 and later: 93 % less cache than its earlier 67B model |
Query, key or value?
-
What this token is looking for
Answer: Query
-
The label other tokens match against
Answer: Key
-
The information passed on to whoever attends
Answer: Value
-
Made by k_proj
Answer: Key
-
Averaged together, using the attention weights
Answer: Value
-
Dotted with every earlier key
Answer: Query
The cost of looking at everything
Attention compares each token with every earlier token. For a text of n tokens that is about n² ÷ 2 pairs, in every head of every layer. The cost grows with the square of the length:
| Text length | Pairs |
|---|---|
| 1,000 tokens | about 500,000 |
| 128,000 tokens | about 8 billion |
| 1,000,000 tokens | about 500 billion |
Ten times longer text means a hundred times more attention work.
And all those keys and values must stay in memory while the model writes. For Llama 3.1 8B that is 128 KiB per token, or 16 GiB for a 128,000-token conversation: as much as the model’s weights. This is why long context is one of the hottest research areas, with three main lines of attack you will meet in the long-context lesson:
- Better kernels such as FlashAttention: the same exact maths, with far fewer trips to memory.
- Sparse attention: each token looks only at the earlier tokens most likely to matter, as in DeepSeek’s sparse attention and GLM-5.3.
- Linear attention layers with a fixed-size memory, mixed with a few full attention layers, as in Qwen3.8 and Kimi K3.
Remember
- Attention lets each token gather information from earlier tokens, weighted by how relevant they are.
- Each token makes a query (what it wants), a key (its label) and a value (what it passes on). Scores are query·key dot products.
- softmax(Q·Kᵀ ÷ √d)·V: score, scale, softmax, weighted average of values.
- The causal mask stops tokens seeing the future, so training makes every prediction in parallel.
- Many heads run at once. GQA and MLA shrink the key-value memory. Cost grows with the square of the length.
Words to know
- Attention
- A way for each token to gather information from others, weighted by relevance.
- Query
- The vector that says what a token is looking for.
- Key
- The vector that labels what a token offers, to be matched against queries.
- Value
- The vector of information a token passes on when attended to.
- Causal mask
- The rule that a token cannot attend to tokens after it.
- Attention head
- One of several attentions running side by side in a layer, each learning its own job.
- Induction head
- A head that spots a repeated pattern and predicts it will continue.
- GQA
- Grouped-query attention: several query heads share one key and value head, to save memory.
- MLA
- Multi-head latent attention: DeepSeek’s method of compressing keys and values into a small vector.
- Encoder and decoder
- Models that see the whole text both ways, and models that write and only look back.
Go to the source
This lesson is built on these papers and documents. Paper links open arxiv.org, a separate site.
-
Attention Is All You Need
Read section 3.2 now: you know every symbol in it.
-
The Illustrated Transformer (J. Alammar)
The most famous picture-by-picture walk through queries, keys and values.
-
Attention in transformers, step by step (3Blue1Brown)
A beautifully animated version of this lesson.
-
In-context Learning and Induction Heads (Anthropic)
How a simple two-head circuit lets models learn from examples in their prompt.
-
GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints
Why sharing keys and values between heads costs so little quality.
-
DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model
Section 2.1 introduces multi-head latent attention. Your first real DeepSeek paper section.
Check yourself
5 questions. Tap the answer you think is right.
0 of 5 answered
Lesson complete
Answer every question above to complete this lesson.
Your progress is saved on this device only.
Next lessonThe transformer: putting it all together