Attention as Matrix Products
The attention mechanism at the heart of every transformer and LLM is three matrix multiplications and a softmax: . This lesson builds it by hand in NumPy, adds the causal mask used by GPT-style models, and shows how multi-head attention is just a reshape.
Queries, keys and values
Take a sequence of tokens, each already turned into a -dimensional vector (an embedding), stacked as the rows of (). Three learned matrices, applied like dense layers, give three views of every token:
Scaled dot-product attention
is a dot product: how well token 's query matches token 's key. The row softmax, , turns scores into weights, and output row is the convex combination : a matrix product . So each token's output lies in the span of the value vectors, mixed according to similarity.
Why divide by ? If the entries of and are independent with mean 0 and variance 1, then is a sum of such products and has variance . Dividing by brings the scores back to variance 1. Without it, for large the softmax saturates: one weight near 1, the rest near 0, and the gradients vanish.
import numpy as np
def softmax(S):
S = S - S.max(axis=-1, keepdims=True) # subtract row max: same result, no overflow
E = np.exp(S)
return E / E.sum(axis=-1, keepdims=True)
rng = np.random.default_rng(0)
T, d_model, d = 4, 8, 4
X = rng.normal(size=(T, d_model))
W_Q, W_K, W_V = (rng.normal(size=(d_model, d)) / np.sqrt(d_model) for _ in range(3))
Q, K, V = X @ W_Q, X @ W_K, X @ W_V
S = Q @ K.T / np.sqrt(d)
A = softmax(S)
out = A @ V
print("shapes Q, S, out:", Q.shape, S.shape, out.shape)
print("attention weights:\n", np.round(A, 3))
print("rows sum to 1:", np.allclose(A.sum(axis=1), 1))
print("row 0 of out = sum_j A[0,j] v_j:", np.allclose(out[0], sum(A[0, j] * V[j] for j in range(T))))shapes Q, S, out: (4, 4) (4, 4) (4, 4)
attention weights:
[[0.276 0.242 0.283 0.2 ]
[0.212 0.137 0.287 0.364]
[0.398 0.133 0.296 0.173]
[0.19 0.27 0.236 0.305]]
rows sum to 1: True
row 0 of out = sum_j A[0,j] v_j: True
The scaling argument is easy to check numerically:
import numpy as np
rng = np.random.default_rng(1)
for d in (4, 64, 1024):
q, k = rng.normal(size=(20000, d)), rng.normal(size=(20000, d))
dots = np.sum(q * k, axis=1)
print(f"d={d:5d} var(q.k) = {dots.var():8.1f} var(q.k/sqrt d) = {(dots / np.sqrt(d)).var():.3f}")d= 4 var(q.k) = 4.0 var(q.k/sqrt d) = 1.005
d= 64 var(q.k) = 63.5 var(q.k/sqrt d) = 0.992
d= 1024 var(q.k) = 994.5 var(q.k/sqrt d) = 0.971
The causal mask
A language model predicts the next token, so token must not look at tokens . Before the softmax, set above the diagonal; , so those weights vanish and each row still sums to 1. The result is lower triangular.
import numpy as np
def softmax(S):
S = S - S.max(axis=-1, keepdims=True); E = np.exp(S)
return E / E.sum(axis=-1, keepdims=True)
rng = np.random.default_rng(0)
T, d = 5, 4
Q, K, V = rng.normal(size=(T, d)), rng.normal(size=(T, d)), rng.normal(size=(T, d))
mask = np.triu(np.ones((T, T), dtype=bool), k=1) # True above the diagonal
S = np.where(mask, -np.inf, Q @ K.T / np.sqrt(d))
A = softmax(S)
print(np.round(A, 3))
out = A @ V
# Changing a future token must not change earlier outputs:
V2 = V.copy(); V2[4] += 100
print("outputs 0-3 unchanged:", np.allclose((A @ V2)[:4], out[:4]))[[1. 0. 0. 0. 0. ]
[0.761 0.239 0. 0. 0. ]
[0.196 0.304 0.5 0. 0. ]
[0.21 0.122 0.531 0.137 0. ]
[0.136 0.064 0.124 0.188 0.487]]
outputs 0-3 unchanged: True
Token 0 can only attend to itself; token 4 sees everything.
Multi-head attention is a reshape
One attention pattern per layer is limiting, so transformers run heads in parallel, each with dimension . Instead of separate matrix sets, compute one big (), then reshape it to : the columns are split into blocks. Batched matrix multiplication (@ on 3D arrays) then does all heads at once, and the outputs are reshaped back and mixed by an output matrix .
import numpy as np
def softmax(S):
S = S - S.max(axis=-1, keepdims=True); E = np.exp(S)
return E / E.sum(axis=-1, keepdims=True)
rng = np.random.default_rng(2)
T, d_model, h = 6, 8, 2
dh = d_model // h
X = rng.normal(size=(T, d_model))
W_Q, W_K, W_V, W_O = (rng.normal(size=(d_model, d_model)) / np.sqrt(d_model) for _ in range(4))
def split(M): # (T, d_model) -> (h, T, dh)
return M.reshape(T, h, dh).transpose(1, 0, 2)
Q, K, V = split(X @ W_Q), split(X @ W_K), split(X @ W_V)
A = softmax(Q @ K.transpose(0, 2, 1) / np.sqrt(dh)) # (h, T, T)
heads = A @ V # (h, T, dh)
out = heads.transpose(1, 0, 2).reshape(T, d_model) @ W_O # concat heads, mix
print("Q per head:", Q.shape, " A:", A.shape, " out:", out.shape)
# Same as running head 1 on its own column block:
q1, k1, v1 = (X @ W_Q)[:, dh:], (X @ W_K)[:, dh:], (X @ W_V)[:, dh:]
print("head 1 matches its column block:", np.allclose(heads[1], softmax(q1 @ k1.T / np.sqrt(dh)) @ v1))
print("attention parameters:", 4 * d_model * d_model)Q per head: (2, 6, 4) A: (2, 6, 6) out: (6, 8)
head 1 matches its column block: True
attention parameters: 256
Cost and what it means
The score matrix is , so attention costs about operations and memory per head: doubling the context length quadruples the work. That is the linear-algebra reason for context-window limits and for techniques such as FlashAttention (computing in tiles without storing ), KV caches (keeping and of earlier tokens during generation, since with the causal mask they never change) and sparse or low-rank attention approximations.
Note: Attention by itself is permutation-equivariant: shuffling the rows of just shuffles the output rows. Word order enters only through positional encodings added to (or rotations applied to and , as in RoPE).
In software
- Transformers.
torch.nn.functional.scaled_dot_product_attention(Q, K, V, is_causal=True)is the code above, fused into one fast kernel (Attention, Transformers). - Context windows. The cost is why long contexts are expensive (Context Windows).
- Retrieval. Attention is a "soft" nearest-neighbour lookup: compare a query with keys, return a similarity-weighted mix of values, the differentiable cousin of vector search.
Exercises
Exercise 1: A softmax by hand
Compute .
Answer
.
Solution
The exponentials are 1, 2, 5 with sum 8.
Exercise 2: Two tokens by hand
With , , , , , , find token 1's output (no mask).
Answer
About .
Solution
Exercise 3: Shapes of multi-head attention
, , . Give the shapes of after the reshape, of , and the number of entries of over all heads.
Answer
: ; : ; 80,000 entries.
Solution
. Each head has a attention matrix; .
Exercise 4: Masked row (code)
For the scores with a causal mask, compute .
Answer
Row 0: ; row 1: ; row 2: .
Solution
Row 1 keeps : weights and 0.8808. Row 2 keeps all three equal zeros, giving a uniform average.
import numpy as np
S = np.array([[2.0, 1, 0], [1, 3, 0], [0, 0, 0]])
S = np.where(np.triu(np.ones((3, 3), bool), 1), -np.inf, S)
E = np.exp(S - S.max(1, keepdims=True))
print(np.round(E / E.sum(1, keepdims=True), 4))[[1. 0. 0. ]
[0.1192 0.8808 0. ]
[0.3333 0.3333 0.3333]]
Test yourself
In , what does row of the result represent?
- The query of token
- A weighted average of value vectors, weighted by how well query matches each key
- The -th key
- A probability distribution over tokens
Why are attention scores divided by ?
- To make them integers
- The dot product of random -dimensional vectors has variance about ; scaling keeps the softmax from saturating
- To make the matrix symmetric
- To normalize
How is the causal mask applied?
- Multiply by a lower-triangular matrix after the softmax
- Set the scores above the diagonal to before the softmax
- Zero out the values
- Transpose