3 Model Architecture 2 / 9
  1. In this chapter
  2. From RNNs to Attention
  3. Attention Basics
  4. Positional Encoding Explained
  5. Transformer Block Explained
  6. Modern LLM Architecture
  7. Efficient Attention
  8. Mixture of Experts (MoE)
  9. Long Context
  10. State Space Models and Hybrids
All chapters →

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.

Beginner 14 min read Updated Companion code ↓

After this page you will be able to

  • Explain why a Transformer can process sequences without relying on an RNN.
  • Say what Q, K and V each 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
  1. Why attention is needed
  2. Q, K and V in one sentence each
  3. A minimal numeric example with one head
  4. Step 1: compute similarity scores
  5. Step 2: scale
  6. Step 3: softmax
  7. Step 4: take the weighted sum of the values
  8. Try it yourself
  9. Why the scores are scaled
  10. From one head to matrix form
  11. What multi-head attention adds
  12. Self-attention versus cross-attention
  13. A minimal PyTorch implementation
  14. Points that are easy to confuse
  15. 1. A high weight does not mean a large value
  16. 2. Attention is not a database lookup
  17. 3. Multiple heads are not repeated computation
  18. 4. Strong attention is not a causal explanation
  19. A suggested study order
  20. Exercises
  21. Quick self-check
  22. Further reading
  23. 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:

  • Query means “what information am I looking for right now?”
  • Key means “the label each token holds up, telling others who should pay attention to it”.
  • Value means “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:

Minimal flow of scaled dot-product attention The current token produces a query, every context token produces a key and a value; the query is matched against each key to give scores, softmax turns the scores into weights, and the values are summed with those weights into a new context-aware representation. Attention first matches, then gathers information by weight Current token “What do I need?” Q query view current need Context tokens K1 K2 K3 Do I match the query? Softmax Q matched with K gives the weights Sum of V V1 V2 V3 weighted by attention Context-aware output a blend of positions, not a copy
Q decides "what I am looking for", K decides "who is worth looking at", and V decides "what content is contributed once looked at". Keeping the three separate is what lets attention both match relations and output information.

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 q=[1,0]q = [1, 0], and the context has three positions with the following keys and values:

Positionkeyvalue
1k1=[1,0]k_1 = [1, 0]v1=[10,0]v_1 = [10, 0]
2k2=[0,1]k_2 = [0, 1]v2=[0,10]v_2 = [0, 10]
3k3=[1,1]k_3 = [1, 1]v3=[6,6]v_3 = [6, 6]

Step 1: compute similarity scores

Use the dot product to measure the relevance of qq to each kik_i:

q⋅k1=1,q⋅k2=0,q⋅k3=1q \cdot k_1 = 1,\qquad q \cdot k_2 = 0,\qquad q \cdot k_3 = 1

So the raw scores are [1,0,1][1, 0, 1].

Step 2: scale

Here dk=2d_k = 2, so we divide by 2≈1.41\sqrt{2} \approx 1.41 and get [0.71,0,0.71][0.71, 0, 0.71].

Step 3: softmax

softmax([0.71, 0, 0.71])≈[0.40, 0.20, 0.40]\mathrm{softmax}([0.71,\ 0,\ 0.71]) \approx [0.40,\ 0.20,\ 0.40]

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

output=0.40 v1+0.20 v2+0.40 v3≈[6.4, 4.4]\text{output} = 0.40\,v_1 + 0.20\,v_2 + 0.40\,v_3 \approx [6.4,\ 4.4]

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 q=[1,0]q = [1, 0] 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

q⋅k=∑i=1dkqikiq \cdot k = \sum_{i=1}^{d_k} q_i k_i

has mean 0 and variance dkd_k. 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 dk\sqrt{d_k}, 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 X∈Rn×dmodelX \in \mathbb{R}^{n \times d_{\text{model}}}, where nn is the sequence length. First apply three learnable linear projections:

Q=XWQ,K=XWK,V=XWVQ = XW_Q,\qquad K = XW_K,\qquad V = XW_V

Then compute everything at once:

Attention(Q,K,V)=softmax ⁣(QK⊤dk)V\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}}\right)V

Here QK⊤∈Rn×nQK^{\top} \in \mathbb{R}^{n \times n} 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 nn, 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:

  1. Project the input into several subspaces.
  2. Run one attention in each subspace.
  3. Concatenate the results of all heads and map them back to the output space.

As a formula:

MultiHead(X)=Concat(head1,…,headh) WO,headi=Attention(XWQ(i), XWK(i), XWV(i))\mathrm{MultiHead}(X) = \mathrm{Concat}(\mathrm{head}_1, \dots, \mathrm{head}_h)\,W_O,\qquad \mathrm{head}_i = \mathrm{Attention}(XW_Q^{(i)},\, XW_K^{(i)},\, XW_V^{(i)})

Usually each head has dimension dk=dmodel/hd_k = d_{\text{model}} / h, 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:

Single-head versus multi-head attention: how the work is divided On the left, a single head has to handle local syntax, coreference and structural boundaries in one subspace. On the right, multi-head attention assigns these relations to different heads that model them in parallel, and the results are concatenated and fused. Multiple heads split different relations across subspaces Single-head attention local, long-range and structural cues share one subspace Local syntax Coreference Boundaries One head all relations compete in the same space Easily interfere Multi-head attention heads specialize in different subspaces, then concatenate A · Local syntax B · Coreference C · Boundaries Concat W project One layer, many relations
The point of multiple heads is not to run the same attention formula many times, but to spread different kinds of relations over different subspaces, process them in parallel, and fuse the results at the end.

Self-attention versus cross-attention

Two kinds of attention are common in a Transformer:

  • Self-attention: Q/K/V all come from the same sequence. In an encoder, for example, the tokens of the input sentence attend to one another.
  • Cross-attention: Q comes from the current decoder state, and K/V come 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:

  1. Make sure you can work out a single-head attention example by hand.
  2. Then understand how multi-head attention splits and concatenates dimensions.
  3. Next learn positional encoding, to see how the model perceives order.
  4. Finally return to the complete Transformer block and see how residuals, LayerNorm and the FFN fit together.

Where to go next:

Exercises

  1. If you change qq in the numeric example above to [0,1][0, 1], what happens to the attention weights? Work it out by hand first, then check it with the calculator above.
  2. Why is softmax more likely to saturate when dkd_k is large and no scaling is applied?
  3. If two heads learn exactly the same pattern, does multi-head attention still give any extra benefit?
  4. Why must a decoder use a mask, while an encoder usually does not?
Reference answers
  1. The raw scores become [0,1,1][0, 1, 1], scaled [0,0.71,0.71][0, 0.71, 0.71], and softmax gives the weights [0.20,0.40,0.40][0.20, 0.40, 0.40], so the output is 0.20 v1+0.40 v2+0.40 v3≈[4.4,6.4]0.20\,v_1 + 0.40\,v_2 + 0.40\,v_3 \approx [4.4, 6.4]. The keys and values in this example are symmetric in their two components, so the result is the mirror image of [6.4,4.4][6.4, 4.4] for q=[1,0]q=[1,0]: the query now resembles k2k_2 and k3k_3, and attention moves from position 1 to position 2.
  2. Without scaling, the standard deviation of the dot product is dk\sqrt{d_k}: 8 for dk=64d_k=64, so the largest of 8 scores typically sits about 10 above the median, a weight ratio of e10≈2.2×104e^{10}\approx 2.2\times10^4, 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 dk=4d_k=4, 64 and 512, and 0.35 to 0.36 with scaling, almost independent of dkd_k. The gradient of softmax is ∂pi/∂sj=pi(δij−pj)\partial p_i/\partial s_j = p_i(\delta_{ij} - p_j); when the output is nearly one-hot every term is close to 0, the gradient vanishes and training stalls.
  3. 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.
  4. 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 ii could see the token at position i+1i+1, 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 dk\sqrt{d_k} rather than by dkd_k?

  • To turn the scores into integers
  • If the components of qq and kk are independent with mean 0 and variance 1, the dot product has variance dkd_k; dividing by dk\sqrt{d_k} brings it back to 1
  • To reduce the number of parameters
  • So that the softmax output no longer sums to 1

The dot product q⋅kq \cdot k is a sum of dkd_k independent terms, so its variance grows linearly with dkd_k and its standard deviation is dk\sqrt{d_k}. Dividing by dk\sqrt{d_k} restores unit variance; dividing by dkd_k would squash the scores so much that the attention becomes nearly uniform.

2. In the cross-attention of an encoder-decoder Transformer, where do QQ, KK and VV come from?

  • All three come from the decoder
  • QQ comes from the decoder; KK and VV come from the encoder output
  • QQ comes from the encoder; KK and VV come from the decoder
  • All three come from the encoder

Cross-attention means “the current decoder position queries the source sequence”: the asker (QQ) is the decoder and the content being queried (KK, VV) 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 VV
  • A causal mask lets position ii see only positions ≤i\le i
  • 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 ∑jajVj\sum_j a_j V_j: the weight aja_j decides whom to look at, and VjV_j decides what to take. Each head has its own WQ,WK,WVW^Q, W^K, W^V 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 nn, how large is the score matrix of one attention head?

  • n×dn \times d
  • n×nn \times n
  • d×dd \times d
  • n×1n \times 1

Every token scores every (visible) token, so the score matrix is n×nn \times n, and both time and memory grow with n2n^2. This is the root of the cost of long contexts and the starting point of optimizations such as FlashAttention.

Further reading

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.