Sub topic 5
Self-attention: letting tokens look at each other
This chapter assumes you know matrix multiplication, the softmax function, and that each token is already a vector (from the embeddings chapter). The code uses NumPy.
Why tokens need to look at each other
An embedding gives each token a vector that does not depend on its neighbors. In "The bank raised rates" and "The bank was muddy", the token "bank" starts with the same vector. The model needs a step that mixes information between positions, so the vector for "bank" can change based on the words around it. Self-attention is that step.
Queries, keys, and values
Each token's input vector x is projected three ways by learned weight matrices:
- The query (
q = x @ Wq) describes what this token is looking for. - The key (
k = x @ Wk) describes what this token offers to others. - The value (
v = x @ Wv) is the content that gets passed along if another token pays attention to it.
For every pair of positions, the dot product of one token's query with another token's key gives a score. A high score means the second token is relevant to the first. Softmax turns each row of scores into weights that sum to 1. The output for a token is the weighted sum of all the value vectors.
In matrix form:
output = softmax(Q Kᵀ / sqrt(d_k)) V
Dividing by sqrt(d_k), where d_k is the key dimension, keeps the scores from growing with the vector size. Without it, softmax saturates and the weights become nearly one-hot.
The causal mask
A decoder-only model predicts the next token, so position i must not see positions after i. Otherwise it could copy the answer. The fix is a causal mask: before softmax, set every score above the diagonal to -inf. Softmax turns -inf into a weight of exactly 0.
A working implementation
import numpy as np
def causal_self_attention(x, Wq, Wk, Wv):
q, k, v = x @ Wq, x @ Wk, x @ Wv
scores = q @ k.T / np.sqrt(k.shape[-1])
mask = np.triu(np.ones_like(scores), k=1).astype(bool)
scores = np.where(mask, -np.inf, scores)
scores = scores - scores.max(axis=-1, keepdims=True)
weights = np.exp(scores)
weights = weights / weights.sum(axis=-1, keepdims=True)
return weights @ v, weights
rng = np.random.default_rng(0)
x = rng.normal(size=(4, 8))
Wq, Wk, Wv = (rng.normal(size=(8, 8)) for _ in range(3))
out, weights = causal_self_attention(x, Wq, Wk, Wv)
print(out.shape)
print(np.round(weights, 2))Here x holds 4 tokens with 8 dimensions each. The output shape is (4, 8): one new vector per token, same size as the input.
Reading the result
Print weights and check three things:
- Every row sums to 1.
- Everything above the diagonal is 0.
- The first row is
[1, 0, 0, 0], because token 0 can only attend to itself.
Row i shows how much token i draws from each earlier token. In a trained model, these patterns are meaningful. For example, a pronoun may put high weight on the noun it refers to. Here the weights are random because the matrices are random.
Common errors
- Applying the mask after softmax. The remaining weights then no longer sum to 1, and information has already leaked through the normalization.
- Masking with 0 instead of
-inf. A score of 0 still receives positive weight after softmax. - Normalizing over the wrong axis. Softmax must run across keys (the last axis), so each query's weights sum to 1.
- Omitting the
sqrt(d_k)scaling. The code still runs, but the weights become sharper than intended.
Exercise
In causal_self_attention, what would happen to the weights if you replaced -np.inf with 0.0 in the np.where call, and why is that a bug for a next-token predictor?
Show answer
Masked positions would keep a score of 0 instead of being removed. After softmax, each would get a positive weight, because exp(0) = 1. Each token would then draw information from future tokens, so the model could see the answer it is supposed to predict. The weights above the diagonal would no longer be 0.