Sub topic 5
Self-attention: letting tokens look at each other
This chapter assumes you can read Python and NumPy, multiply matrices, and know what a softmax does. It also assumes you have seen token embeddings from the previous chapter: each token ID maps to a vector, so a sequence of n tokens becomes a matrix of shape (n, d_model).
Why embeddings alone are not enough
An embedding lookup treats every token in isolation. The vector for "bank" is the same whether the sentence is about a river or a loan. The vector for "it" does not say which noun it refers to.
To predict the next token well, the model needs each position to build a representation that depends on its context. Self-attention does this. Each position reads from other positions and mixes what it finds into a new vector. "Self" means the tokens attend to other tokens in the same sequence, not to a separate input.
Queries, keys, and values
Self-attention gives each token three roles. The model learns three weight matrices, Wq, Wk, and Wv, and applies each to the input x:
- The query
q = x @ Wqdescribes what this position is looking for. - The key
k = x @ Wkdescribes what this position offers to others. - The value
v = x @ Wvis the information this position passes along if someone attends to it.
A position's query is compared against every key. A high match means that position's value contributes a lot to the output. Keeping keys and values separate lets the model decide how to find information independently of what information to move.
The table shows the shapes for a sequence of n tokens, with key dimension d_k and value dimension d_v.
| Quantity | Shape | Meaning |
|---|---|---|
| `x` | `(n, d_model)` | Input vectors, one row per token |
| `Wq`, `Wk` | `(d_model, d_k)` | Learned projections |
| `Wv` | `(d_model, d_v)` | Learned projection |
| `q`, `k` | `(n, d_k)` | Queries and keys |
| `v` | `(n, d_v)` | Values |
| `scores` | `(n, n)` | Query-key similarity for every pair |
| `weights` | `(n, n)` | Scores after softmax; each row sums to 1 |
| `out` | `(n, d_v)` | Weighted mix of values per position |
The computation, step by step
- Project. Compute
q,k, andvfromx. - Score.
q @ k.Tis an(n, n)matrix. Entry[i, j]is the dot product of the query at positioniwith the key at positionj. A larger value means a stronger match. - Scale. Divide by
sqrt(d_k). - Mask. Block positions the query must not see.
- Normalize. Apply softmax along each row so the weights are non-negative and sum to 1.
- Mix.
weights @ vgives each position a weighted average of all value vectors.
Why divide by sqrt(d_k)
A dot product of two d_k-dimensional vectors with independent unit-variance entries has variance d_k. As d_k grows, raw scores get large in magnitude. Softmax on large inputs saturates: one entry gets nearly all the weight, and the gradients for the others nearly vanish. Dividing by sqrt(d_k) brings the score variance back to about 1, which keeps softmax in a range where it still learns.
The causal mask
A decoder-only model is trained to predict the next token at every position at once. If position 2 could see position 3, it could copy the answer, and the loss would teach nothing. The causal mask prevents this. Position i may attend only to positions 0 through i.
In the score matrix, that means every entry above the diagonal (where j > i) must get zero weight. The standard way is to set those scores to negative infinity before softmax, because exp(-inf) is 0.
A complete 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))Walk through the pieces:
np.triu(..., k=1)keeps the entries strictly above the diagonal. Converting to bool givesTruewhere attention is forbidden.np.where(mask, -np.inf, scores)replaces those scores.- Subtracting the row maximum is the standard stability trick. Softmax is unchanged by a constant shift, but
expno longer overflows. The maximum is always finite because the diagonal is never masked. - The final
weights @ vproduces one output row per input row.
The output shape is (4, 8). In the printed weights, check three properties:
- The upper triangle is all zeros.
- Each row sums to 1.
- Row 0 is
[1, 0, 0, 0], because the first token can only attend to itself.
Later rows spread their weight across more positions, and the exact numbers depend on the random seed.
What the output means
Each output row is a weighted average of value vectors, so it lives in the same space as the values. Position 3's output blends information from positions 0 to 3 in proportions set by how well its query matched their keys. The model does not receive this as a lookup it programmed. It learns Wq, Wk, and Wv during pretraining so that useful mixing emerges. Trained models show patterns such as attending to the previous token, to a matching earlier word, or to the start of the sequence.
Attention by itself has no sense of order. If you shuffle the rows of x (without a mask), the output rows shuffle the same way. Order enters through the positional information covered in the next chapter, and in this chapter's code through the causal mask.
Multiple heads
One attention head produces one weighting pattern per position. Real models run several heads in parallel, each with its own smaller Wq, Wk, Wv. For example, 8 heads with d_model = 512 would use d_k = 64 per head. The head outputs are concatenated along the feature axis and passed through one more learned matrix, Wo, which maps back to d_model. Different heads can specialize in different relationships, such as syntax in one and coreference in another, without sharing a single softmax. The code above is one head. A multi-head version repeats it with different weights and concatenates the results.
Common errors
- Masking after softmax. Zeroing the weights after softmax leaves rows that no longer sum to 1, so the output is wrong. Mask the scores with
-infbefore softmax, or renormalize afterward. - Masking with 0 instead of
-inf. A score of 0 still produces a positive weight, so future tokens leak through. - Forgetting the scale. The code still runs, but training becomes unstable at larger
d_k. - Mixing up axes. Softmax must run over the key axis (
axis=-1), so that each query's weights sum to 1. Normalizing over the query axis gives columns that sum to 1, which is wrong. - Fully masked rows. In causal attention this cannot happen, because the diagonal is open. With padding masks, a row that is entirely
-infgivesnanfrom0 / 0. Libraries handle this with special cases or by keeping one position visible. - Transposing the wrong matrix. Scores need
q @ k.T, an(n, d_k)times(d_k, n)product. Usingq @ kfails on shape, or silently computes something else when the matrix is square.
Cost
The score matrix has n * n entries. Doubling the sequence length quadruples the memory and compute for this step. This quadratic growth is the main reason context windows are limited, and it motivates the key-value cache covered in a later chapter. During generation, the keys and values of earlier tokens do not change, so they can be stored and reused instead of recomputed.
Summary of the idea
Self-attention turns a sequence of independent vectors into a sequence of context-aware vectors. Each position asks a question (query), compares it with what every visible position advertises (keys), and takes a weighted blend of their contents (values). The causal mask restricts "visible" to the past, which is what makes next-token training valid.
Exercise
In the code above, suppose you delete the line scores = np.where(mask, -np.inf, scores) but keep everything else. What happens to the first row of weights, and why is this a problem for training a next-token predictor?
Show answer
Row 0 would no longer be [1, 0, 0, 0]. Its query is compared against all four keys, so softmax gives positive weight to positions 1, 2, and 3. The output at position 0 would then contain information from future tokens. During training the model could read the token it is supposed to predict, so the loss would fall without the model learning to predict. At generation time those future tokens do not exist, so the model would perform much worse than its training loss suggested.
Exercise
A head has d_k = 64. Roughly what variance do raw dot-product scores have if query and key entries are independent with mean 0 and variance 1, and what does the scaling step change it to?
Show answer
The raw dot product sums 64 independent products, each with variance 1, so the variance is about 64 (standard deviation 8). Dividing by sqrt(64) = 8 divides the standard deviation by 8, giving variance of about 1. This keeps softmax from saturating on a single position.