← All writingLLMs, starting with one token · 02

Compute attention: Q, K, V and the causal mask

Use four tokens to understand scores, normalization and aggregation, and why masking precedes softmax.

阅读中文版 →

Compute attention: Q, K, V and the causal mask

A weighted lookup

A query describes what a position seeks, a key describes how a position can be matched, and a value contains the information to aggregate. This is a role analogy, not a claim that individual dimensions have human-readable meanings. Different learned projections usually produce all three from the input.

With and , first compute with shape [T,T]. Normalize each row into A, then compute with shape [T,d_v]. Weight describes how position i reads value j. It is not a causal explanation of an answer.

Why the square root?

If q and k dimensions are approximately independent, zero-mean and unit-variance, their dot-product variance grows with . Dividing by its square root stabilizes the score scale and reduces early softmax saturation. This is a numerical motivation, not a theorem about every learned distribution.

scores = q @ k.transpose(-2, -1) / q.shape[-1]**0.5
future = torch.ones(T, T, dtype=torch.bool).triu(1)
scores = scores.masked_fill(future, float('-inf'))
weights = scores.softmax(dim=-1)
out = weights @ v

This fragment assumes PyTorch tensors q/k/v and sequence length T; the notebook supplies a runnable version. Zeroing future weights after softmax without renormalizing produces rows summing below one and changes the operation.

Mask and temperature experiment

The experiment fixes four two-dimensional Q/K vectors. Predict the first row under causal masking, then disable the mask. With one legal key, the first row is always [1,0,0,0], regardless of temperature. Increasing temperature makes weights more uniform over legal positions; it must not leak into future positions.

We display a full matrix for teaching. A production implementation should avoid storing all entries per layer and head when possible. FlashAttention reorganizes memory access using tiles while targeting exact attention; it does not simply discard low weights.

Check your understanding

Question: Does adding 100 to every legal score in each row change the result?

AnswerNo, mathematically. Softmax is invariant to a uniform row-wise shift. Implementations usually subtract the maximum to avoid exponential overflow. Different biases for different columns do change the distribution.

Primary sources and further reading

Sources checked on 2026-09-10. Teaching examples are not production benchmarks; confirm APIs and model support against the linked version.

INTERACTIVE LAB · LIVE NUMERICAL COMPUTATION

What does each attention row distribute?

Fixed Q=K=[[1,0],[0,1],[1,1],[-1,0.5]]. Observe softmax(QKᵀ/√2/T). These are teaching vectors, not extracted model attention.

Rows are queries; columns are keys. Each row sums to 1.
Q / Kt0t1t2t3
t01.0000.0000.0000.000
t10.3300.6700.0000.000
t20.2480.2480.5030.000
t30.0980.2830.1390.480

Try removing the mask: the first token can now see the future. Near zero temperature, mass concentrates on the largest scores; ties still share it.

Companion notebook

Inspect tensors, run experiments, and check the stated environment and execution status in the first cell.

Open in Colab ↗Download notebook