L1 Beginner · Module 1: The LLM forward pass, for inference engineers
1.3Attention, step by step
Attention is four small steps, scores, mask, softmax and weighted sum, and the causal mask in the middle is what makes fast generation possible. This chapter walks through each step and ends with the observation that leads to the KV cache.
By the end you will be able to
- ✓Compute single-head causal attention by hand from Q, K and V
- ✓Explain what the causal mask does and why generation depends on it
- ✓Describe multi-head attention and how the heads are split and merged
- ✓State how attention's cost grows with sequence length in prefill and in decode
Attention lets each token pull in information from the tokens before it. For each token, three vectors are projected from the residual stream (1.2):
- a query : what this token is looking for,
- a key : what this token offers to others,
- a value : what it actually hands over when picked.
Four steps
- Scores. is a matrix. Entry says how relevant key is to query . Dividing by keeps the scores from growing with the head size, which would make softmax too peaked.
- Mask. is on and below the diagonal and above it. A token cannot look at tokens that come after it.
- Softmax. Each row becomes a set of weights that sum to 1. The entries become exactly 0.
- Weighted sum. Row of the output is : a blend of the values, weighted by relevance.
| query ↓ key → | The | cat | sat | on | the | mat |
|---|---|---|---|---|---|---|
| 1.00 | −∞ | −∞ | −∞ | −∞ | −∞ | |
| 0.43 | 0.57 | −∞ | −∞ | −∞ | −∞ | |
| 0.10 | 0.67 | 0.22 | −∞ | −∞ | −∞ | |
| 0.06 | 0.16 | 0.57 | 0.21 | −∞ | −∞ | |
| 0.48 | 0.09 | 0.06 | 0.16 | 0.21 | −∞ | |
| 0.07 | 0.28 | 0.14 | 0.21 | 0.13 | 0.17 |
Stage 3: softmax
Softmax turns each row into weights that sum to 1. Masked entries become exactly 0.
To compute this row, the model needs K and V for positions 0–3 only. Rows 0–2 were already computed in earlier steps.
Why the mask matters for inference
The causal mask exists for training: the model learns to predict token from tokens , so it must not see . It has a consequence that inference relies on heavily:
Multi-head attention
Real models run attention heads in parallel, each with its own slice of of width (typically 64 or 128). Each head can learn a different pattern: one tracks the previous token, another tracks the subject of the sentence. The head outputs are concatenated back to width and mixed by .
Implementation-wise, heads are just an extra batch dimension: reshape into , run attention on every head at once, and reshape back. Grouped-query attention (GQA) lets several query heads share one K/V head, which shrinks the cache; chapter 9.2 covers it.
What attention costs
| Prefill ( prompt tokens) | Decode (1 new token, context ) | |
|---|---|---|
| Score matrix | ||
| FLOPs per layer | ||
| Bytes read | , , for tokens | the whole cached and for tokens |
In prefill, attention is quadratic in prompt length, and it is a lot of math on data already loaded: compute-heavy. In decode, a single query row has to read every cached key and value to do very little math with each. That makes decode attention memory-bound, and unlike the weight matmuls, batching more requests does not help it (3.3).
Lab: attention with every intermediate printed 🟢
S = Q @ K.T / np.sqrt(dh) # [T, T]mask = np.triu(np.ones((T, T), dtype=bool), k=1) # True above the diagonal = the futureS_masked = np.where(mask, -np.inf, S)A = softmax(S_masked) # rows sum to 1out = A @ Vpython labs/m01/1.3/attention.pyattention weights A = softmax(rows), each row sums to 1: The attends to 1.00 0.00 0.00 0.00 cat attends to 0.43 0.57 0.00 0.00 sat attends to 0.61 0.09 0.30 0.00 down attends to 0.05 0.03 0.13 0.80Sources
Check your understanding
0 / 4 answered1.Why are attention scores divided by √d_head?
2.What does the causal mask guarantee?
3.A new token is appended to the sequence. Which earlier quantities change?
4.During decode, how do attention FLOPs and bytes grow with the context length n?