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.

✦ Interactive~20 min

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 qq: what this token is looking for,
  • a key kk: what this token offers to others,
  • a value vv: what it actually hands over when picked.
Q=hWQK=hWKV=hWVQ,K,V∈RT×dhQ = hW_Q \qquad K = hW_K \qquad V = hW_V \qquad\qquad Q, K, V \in \mathbb{R}^{T \times d_h}

Four steps

Attention⁡(Q,K,V)=softmax⁡ ⁣(QK⊤dh+M)V\operatorname{Attention}(Q, K, V) = \operatorname{softmax}\!\left(\frac{QK^\top}{\sqrt{d_h}} + M\right) V
  1. Scores. S=QK⊤/dhS = QK^\top / \sqrt{d_h} is a T×TT \times T matrix. Entry (i,j)(i, j) says how relevant key jj is to query ii. Dividing by dh\sqrt{d_h} keeps the scores from growing with the head size, which would make softmax too peaked.
  2. Mask. MM is 00 on and below the diagonal and −∞-\infty above it. A token cannot look at tokens that come after it.
  3. Softmax. Each row becomes a set of weights that sum to 1. The −∞-\infty entries become exactly 0.
  4. Weighted sum. Row ii of the output is ∑jAij vj\sum_j A_{ij}\, v_j: a blend of the values, weighted by relevance.
Stage
query ↓ key →Thecatsatonthemat
1.00−∞−∞−∞−∞−∞
0.430.57−∞−∞−∞−∞
0.100.670.22−∞−∞−∞
0.060.160.570.21−∞−∞
0.480.090.060.160.21−∞
0.070.280.140.210.130.17
query = “on” (position 3)

Stage 3: softmax

Softmax turns each row into weights that sum to 1. Masked entries become exactly 0.

The
0.06K,V cached
cat
0.16K,V cached
sat
0.57K,V cached
on
0.21K,V new
the
0.00future
mat
0.00future

To compute this row, the model needs K and V for positions 0–3 only. Rows 0–2 were already computed in earlier steps.

fig. 1.3Single-head causal attention over six tokens. Pick a stage, click a query row, and turn the causal mask off to see what the model would be allowed to peek at.

Why the mask matters for inference

The causal mask exists for training: the model learns to predict token t+1t+1 from tokens 0…t0 \dots t, so it must not see t+1t+1. It has a consequence that inference relies on heavily:

Multi-head attention

Real models run nhn_h attention heads in parallel, each with its own slice of WQ,WK,WVW_Q, W_K, W_V of width dh=d/nhd_h = d / n_h (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 dd and mixed by WOW_O.

Implementation-wise, heads are just an extra batch dimension: reshape [T,d][T, d] into [nh,T,dh][n_h, T, d_h], 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 (TT prompt tokens)Decode (1 new token, context nn)
Score matrixT×TT \times T1×n1 \times n
FLOPs per layer≈4T2d\approx 4T^2 d≈4nd\approx 4nd
Bytes readQQ, KK, VV for TT tokensthe whole cached KK and VV for nn 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 🟢

labs/m01/1.3/attention.py
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 future
S_masked = np.where(mask, -np.inf, S)
A = softmax(S_masked) # rows sum to 1
out = A @ V
Terminal window
python labs/m01/1.3/attention.py
output (excerpt)
attention 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.80

Sources

Check your understanding

0 / 4 answered
  1. 1.Why are attention scores divided by √d_head?

  2. 2.What does the causal mask guarantee?

  3. 3.A new token is appended to the sequence. Which earlier quantities change?

  4. 4.During decode, how do attention FLOPs and bytes grow with the context length n?