Chapter 3 · Model Architecture 3.2
Attention Basics: How a Transformer Reads Context
Understand Q/K/V, scaled dot-product attention and multi-head attention through intuition, a worked numeric example and a minimal code sample.
After this page you will be able to
- Explain why a Transformer can process sequences without relying on an RNN.
- Say what
Q,KandVeach represent. - Explain why the attention formula divides the scores by √d_k.
- Explain why one head is not enough and what multi-head attention adds.
On this page
- Why attention is needed
- Q, K and V in one sentence each
- A minimal numeric example with one head
- Step 1: compute similarity scores
- Step 2: scale
- Step 3: softmax
- Step 4: take the weighted sum of the values
- Try it yourself
- Why the scores are scaled
- From one head to matrix form
- What multi-head attention adds
- Self-attention versus cross-attention
- A minimal PyTorch implementation
- Points that are easy to confuse
- 1. A high weight does not mean a large value
- 2. Attention is not a database lookup
- 3. Multiple heads are not repeated computation
- 4. Strong attention is not a causal explanation
- A suggested study order
- Exercises
- Quick self-check
- Further reading
- FAQ
If this topic is new to you, follow the numeric examples and change the parameters yourself as you read. That is the fastest way to build intuition.
Why attention is needed
In a traditional RNN, information has to be passed along step by step. The longer the sentence, the harder it is for early information to reach the end intact (you can measure this in the gradient and copy experiments of From RNNs to Attention). The Transformer takes a more direct approach:
Don’t make information crawl along the time axis. Let the current token look straight at the whole context and find out who is most relevant to it.
That is the core intuition of attention. Picture a meeting:
Querymeans “what information am I looking for right now?”Keymeans “the label each token holds up, telling others who should pay attention to it”.Valuemeans “the content you actually take away if you do pay attention to me”.
So attention is: “take my query, score everyone in the context, then collect information back according to the scores.”
Drawn as a diagram, Q / K / V stop being three easily confused abbreviations:
Q, K and V in one sentence each
From the formula alone, many people memorize Q/K/V as three abstract letters. A more useful view is that they are representations from three different perspectives:
Q: the question the current token is asking.K: whether each token can answer that question.V: the information a token contributes once it is attended to.
Why project the same input vector into three representations? Because “who gets matched” and “what content is output” are different things. When the pronoun “it” looks for its antecedent, for example, the rule for attending and the information finally retrieved are not the same.
A minimal numeric example with one head
Start with a simplified two-dimensional example. Suppose the current query is , and the context has three positions with the following keys and values:
| Position | key | value |
|---|---|---|
| 1 | ||
| 2 | ||
| 3 |
Step 1: compute similarity scores
Use the dot product to measure the relevance of to each :
So the raw scores are .
Step 2: scale
Here , so we divide by and get .
Step 3: softmax
This means the current token puts about 40% of its attention on position 1, 20% on position 2 and 40% on position 3.
Step 4: take the weighted sum of the values
That is one attention output. Notice that the model does not simply copy the value of one position; it mixes the information of several positions into one new representation by weight.
Try it yourself
Drag the two components of the query, or turn scaling off, and watch how the scores, weights and output change. The default matches the hand calculation above.
Why the scores are scaled
This is a detail beginners often skip, but it matters a lot. Suppose every component of the query and key is independent with mean 0 and variance 1. Then the dot product
has mean 0 and variance . The larger the dimension, the larger the absolute scores tend to be. Without scaling, the input to softmax can become extreme, which leads to:
- One position getting a weight of almost 1 and the others almost 0 (softmax saturation).
- Very small gradients in the saturated region, which makes training unstable.
After dividing by , the variance of the scores returns to about 1, and the attention distribution stays smooth at every dimension size. The demo below generates 8 random keys and compares the weights before and after scaling:
Once the dimension reaches a few hundred, the largest weight approaches 100% without scaling, and attention becomes “pick one position”. With scaling it barely changes with dimension.
From one head to matrix form
Real models do not compute token by token by hand; they pack the whole sequence into matrices. Let the input be , where is the sequence length. First apply three learnable linear projections:
Then compute everything at once:
Here is the score matrix of “every position against every position”, and each row is the attention distribution of one query over the whole context.
This is what lets a Transformer parallelize efficiently: the relations between all tokens come out of one large matrix operation instead of a step-by-step recurrence like an RNN. The price is that both the size of the score matrix and the computation grow quadratically with the sequence length , which is the root of the high cost of long contexts; see KV Cache and Inference Performance.
What multi-head attention adds
With a single attention head, every relation has to be handled in the same representation space. The idea of multi-head attention is to:
- Project the input into several subspaces.
- Run one attention in each subspace.
- Concatenate the results of all heads and map them back to the output space.
As a formula:
Usually each head has dimension , so the total computation is similar to a single head; it is just split across subspaces.
The benefit is not that “more heads is magic”, but that the model gets a chance to learn different kinds of relations at once, for example:
- One head leans toward local syntactic relations.
- One head leans toward long-range reference.
- One head leans toward special separators or structural tokens.
From an interpretability point of view, not every head has a clear meaning, but multiple heads do give the model more parallel modeling perspectives. Much later model analysis work studies “which heads do what”.
Putting single-head and multi-head side by side makes it clearer that multi-head attention is not the same attention formula mechanically repeated many times, but different relations assigned to different subspaces and processed in parallel:
Self-attention versus cross-attention
Two kinds of attention are common in a Transformer:
- Self-attention:
Q/K/Vall come from the same sequence. In an encoder, for example, the tokens of the input sentence attend to one another. - Cross-attention:
Qcomes from the current decoder state, andK/Vcome from the encoder output. In other words, “the generating side reads the encoded result of the input side”.
This distinction matters because it lets you see the Transformer as a single set of building blocks: different modules only differ in where Q/K/V come from, and the underlying computation stays the same.
A minimal PyTorch implementation
The code below leaves out the fiddly details of batching but keeps the core of attention:
import math
import torch
def scaled_dot_product_attention(q, k, v, mask=None):
scores = q @ k.transpose(-2, -1) / math.sqrt(q.size(-1))
if mask is not None:
scores = scores.masked_fill(mask == 0, float("-inf"))
weights = torch.softmax(scores, dim=-1)
output = weights @ v
return output, weights
batch = 2
tokens = 4
d_model = 8
x = torch.randn(batch, tokens, d_model)
Wq = torch.randn(d_model, d_model)
Wk = torch.randn(d_model, d_model)
Wv = torch.randn(d_model, d_model)
q = x @ Wq
k = x @ Wk
v = x @ Wv
output, attn = scaled_dot_product_attention(q, k, v)
print(output.shape) # [2, 4, 8]
print(attn.shape) # [2, 4, 4]
If you can read this code, you have a basic understanding of single-head attention. What remains is “how multiple heads split the dimension and concatenate”, and “why a decoder needs a causal mask”.
Points that are easy to confuse
1. A high weight does not mean a large value
Attention weights come from the match between Q and K, while the output content comes from V. So “who is attended to” and “what information is output” are two separate layers of logic.
2. Attention is not a database lookup
It behaves more like a differentiable soft retrieval. The model does not find one exact answer; it mixes several relevant positions into a new representation.
3. Multiple heads are not repeated computation
Each head works in a subspace after its own linear projection, so it sees a different slice of the features rather than a copy.
4. Strong attention is not a causal explanation
Attention heat maps are helpful, but they cannot be taken as a full explanation of what the model is “really thinking”. They are better at building intuition than at replacing theoretical analysis.
A suggested study order
To keep going from here, you can proceed in this order:
- Make sure you can work out a single-head attention example by hand.
- Then understand how multi-head attention splits and concatenates dimensions.
- Next learn positional encoding, to see how the model perceives order.
- Finally return to the complete Transformer block and see how residuals, LayerNorm and the FFN fit together.
Where to go next:
- Positional Encoding Explained: Absolute, Relative and RoPE
- Transformer Block Explained: Attention, FFN, Residuals and LayerNorm
- Modern LLM Architecture: From GPT-2 to Llama, Qwen and DeepSeek
- Attention Is All You Need, Explained
Exercises
- If you change in the numeric example above to , what happens to the attention weights? Work it out by hand first, then check it with the calculator above.
- Why is softmax more likely to saturate when is large and no scaling is applied?
- If two heads learn exactly the same pattern, does multi-head attention still give any extra benefit?
- Why must a decoder use a mask, while an encoder usually does not?
Reference answers
- The raw scores become , scaled , and softmax gives the weights , so the output is . The keys and values in this example are symmetric in their two components, so the result is the mirror image of for : the query now resembles and , and attention moves from position 1 to position 2.
- Without scaling, the standard deviation of the dot product is : 8 for , so the largest of 8 scores typically sits about 10 above the median, a weight ratio of , and the softmax output is nearly one-hot. I simulated it once in Python (seed 0, standard normal query and 8 keys, averaged over 2,000 draws): the largest weight is 0.53, 0.87 and 0.96 without scaling for , 64 and 512, and 0.35 to 0.36 with scaling, almost independent of . The gradient of softmax is ; when the output is nearly one-hot every term is close to 0, the gradient vanishes and training stalls.
- No extra benefit, only waste: the two heads give the same weights and outputs, the same information appears twice after concatenation, and a share of the parameters and compute is spent for nothing. Trained heads are often redundant: Michel et al. (2019) found that a large share of the heads of a trained multi-head model can be removed at test time with little loss in performance. MQA and GQA, which let several heads share K and V (see Efficient Attention), also show that the heads’ K and V need not be fully independent.
- In training the decoder is fed the whole target sequence at once and predicts the next token at every position in parallel. Without a causal mask, position could see the token at position , which is exactly the answer it is asked to predict; the loss would fall by copying the answer without learning to predict, and at inference the future tokens do not exist, so training and inference would no longer match. The encoder reads a complete given input (a source sentence or a whole document) and does not predict the next token of its own input, so letting every position see both sides helps (this is what BERT does). Do not confuse this with the padding mask, which hides the placeholder tokens used for padding and is needed by both encoder and decoder.
Quick self-check
1. Why are attention scores divided by rather than by ?
- To turn the scores into integers
- If the components of and are independent with mean 0 and variance 1, the dot product has variance ; dividing by brings it back to 1
- To reduce the number of parameters
- So that the softmax output no longer sums to 1
The dot product is a sum of independent terms, so its variance grows linearly with and its standard deviation is . Dividing by restores unit variance; dividing by would squash the scores so much that the attention becomes nearly uniform.
2. In the cross-attention of an encoder-decoder Transformer, where do , and come from?
- All three come from the decoder
- comes from the decoder; and come from the encoder output
- comes from the encoder; and come from the decoder
- All three come from the encoder
Cross-attention means “the current decoder position queries the source sequence”: the asker () is the decoder and the content being queried (, ) is the encoder’s representation of the source. When all three share one source it is self-attention.
3. Which of these statements are true? (select all that apply)
- A high attention weight does not by itself mean a large contribution: the contribution also depends on the value
- A causal mask lets position see only positions
- Multi-head attention is the same head computed several times and averaged
- An attention heatmap is a complete explanation of the model’s “reasoning”
The output is : the weight decides whom to look at, and decides what to take. Each head has its own and works in a different subspace, so it is not repeated computation. Heatmaps help build intuition; they are not causal explanations.
4. For a sequence of length , how large is the score matrix of one attention head?
Every token scores every (visible) token, so the score matrix is , and both time and memory grow with . This is the root of the cost of long contexts and the starting point of optimizations such as FlashAttention.
Further reading
- To understand the complete architecture from the paper itself, read Attention Is All You Need.
FAQ
- What is the core formula of attention?
- Scaled dot-product attention is softmax(QKᵀ/√d_k)·V. The dot product of Q and K gives a relevance score for every pair of positions, dividing by √d_k keeps the numbers stable, softmax turns the scores into weights, and the weights are used to average V, so each position gets a new representation that blends in the context.
- Why does attention divide by √d_k?
- When the components of the query and key are independent with mean 0 and variance 1, their dot product has variance d_k. The larger the dimension, the larger the absolute scores, and the easier it is for softmax to saturate into "pick almost one position", which also shrinks the gradients. Dividing by √d_k brings the variance back to about 1, which keeps the attention distribution smooth and training stable.
- Why is multi-head attention better than a single head?
- Multi-head attention projects the representation into several lower-dimensional subspaces, lets each head compute attention independently, then concatenates the results and maps them back with a linear layer. One layer can then learn different kinds of relations at once (local collocations, long-range reference, structural boundaries), whereas a single head has to squeeze every relation into one representation space. More heads are not always better, and a head does not always have a clear meaning.
- What is the difference between self-attention and cross-attention?
- In self-attention, Q, K and V all come from the same sequence. In cross-attention, Q comes from one sequence (for example the current decoder state) while K and V come from another (for example the encoder output). The computation is identical; only the source of the inputs differs.