Attention Mechanisms
Every position reads a weighted average of the others. The dot products, the softmax, the square-root scaling and what attention costs.
Jump to a section
Each position reads a weighted average of the others
To continue "Small models can", a decoder needs the vector at "can" to carry information from "Small" and "models". Attention is the operation that moves it there. The new vector at each position is a weighted average of vectors computed at other positions, and the weights are computed on the fly from the content.
Every position produces three vectors from its current representation, through three learned linear maps. The query describes what the position is looking for. The key describes what it offers. The value is what it hands over when another position attends to it. A position's output is the sum of the allowed values, each weighted by how well its key matches the query.
That makes attention a soft dictionary lookup. A hash map returns the one value whose key matches exactly. Attention returns a blend of all of them, weighted by match strength, and because the blend is differentiable, the projections that produce queries, keys and values train by gradient descent like any other layer.
In self-attention the queries, keys and values all come from the same sequence. In cross-attention, as in the decoder of the original encoder-decoder Transformer, the queries come from one sequence and the keys and values from another. A mask decides which keys each query may read: a causal decoder lets position see positions to and nothing later.
One attention row by hand
Take the four tokens "Small models can reason" with two-dimensional vectors, small enough to work by hand. The query for "can" is . The four keys are , , and . The four values are , , and .
The dot products with the keys are 1, 1, 1 and 0. Dividing by gives three scores of and one of 0. The causal mask removes "reason", which comes after "can". Softmax over three equal scores gives a weight of each, so the output is .
See what one attention row computes
Choose a query token. Follow its scores through the causal mask and into a weighted sum of values.
Reduced motion is on. Use Previous and Next to inspect each state.
weights = softmax(qKᵀ / √2 + causal mask)
Compare the query with each key
For “can”, q = [1, 1]. Scores compare positions. The values carry the information that will be mixed.
Explore the inputs and calculations
Values received by can
Inspect this row’s arithmetic
q = [1, 1]. Each score is q · k / √2. Masking happens before softmax.
| Key token | Key k | Score | Weight | Value v | Weight × v |
|---|---|---|---|---|---|
| Small | [1, 0] | 0.707 | 0.333 | [1, 0] | [0.333, 0] |
| models | [0, 1] | 0.707 | 0.333 | [0, 2] | [0, 0.667] |
| can | [0.5, 0.5] | 0.707 | 0.333 | [1, 1] | [0.333, 0.333] |
| reason | [-1, 1] | −∞ | 0 | [-1, 0.5] | [0, 0] |
The output sums the final column. Attention weights choose how much to mix; they are not themselves the mixed representation.
Can a token with a negative score still contribute to the output?
Yes. A finite negative score gets a positive softmax weight. Only a masked score of negative infinity receives exactly zero weight in this mathematical example.
Turn the mask off and "reason" joins the row. Its score of 0 is the lowest, but it still takes a weight of about 0.14, and the other three drop to about 0.29 each. The output moves to roughly . Any finite score, even a negative one, gets a positive weight. Only a score of gets exactly zero.
That is why the mask goes before the softmax. Adding to a score makes its exponential zero, and the remaining weights still sum to one. Zeroing a probability after the softmax without renormalizing is a different calculation, and the row no longer sums to one.
The formula and its square-root scaling
For queries and keys, with , and :
is an score matrix with one row per query. The softmax runs along each row, so each query's weights sum to 1, and multiplying by gives output vectors of width . In self-attention .
The divisor exists because dot products grow with dimension. If the components of and are independent with mean 0 and variance 1, then is a sum of terms of variance 1, so its variance is . The original Transformer used , which puts the standard deviation of unscaled scores at 8.
Softmax at that scale is close to one-hot. A one-standard-deviation gap between two scores, 8, makes one weight times the other. Near one-hot, the softmax Jacobian is close to zero in every entry, so almost no gradient reaches the scores. Dividing by brings the standard deviation back to 1 under the same assumptions.
The scale acts as a fixed softmax temperature. It cancels the growth that comes from dimension alone. It does not guarantee unit variance once and are learned, and it does not stop a trained model from producing sharp attention when sharp attention helps.
Eight heads for the price of one
A single softmax gives one weighting per query, and every dimension of the value vector is mixed with those same weights. Multi-head attention runs attention operations in parallel, each on its own learned projections, then concatenates the results:
The Transformer base model has and , with . Each head projects the 512-wide input to 64 dimensions for its queries, keys and values. The eight 64-wide outputs concatenate back to 512, and mixes them.
Splitting the width this way adds no parameters. Viewed as one head or eight, the query, key, value and output projections are each , so a layer holds projection weights, excluding biases. The FLOPs are close to those of one full-width head too. What the split buys is eight independent softmaxes, so a query can weight different positions in different subspaces at once. Heads sometimes learn roles a person can name, but nothing in the objective forces that.
Later models changed the number of key and value heads, not the idea. Llama 3 8B has 32 query heads sharing 8 key-value heads (grouped-query attention), which makes its KV cache a quarter of the size full multi-head attention would need.
In code
The worked row from above, in plain Python, makes the masking rule checkable:
1import math
2
3
4def attention_row(q, keys, values, allowed):
5 d = len(q)
6 scores = [sum(a * b for a, b in zip(q, k)) / math.sqrt(d) for k in keys]
7 scores = [s if ok else -math.inf for s, ok in zip(scores, allowed)]
8 top = max(scores)
9 exps = [math.exp(s - top) for s in scores] # exp(-inf) == 0.0
10 weights = [e / sum(exps) for e in exps]
11 return weights, [sum(w * v[i] for w, v in zip(weights, values)) for i in range(len(values[0]))]
12
13
14keys = [(1, 0), (0, 1), (0.5, 0.5), (-1, 1)]
15values = [(1, 0), (0, 2), (1, 1), (-1, 0.5)]
16weights, out = attention_row((1, 1), keys, values, [True, True, True, False])
17assert weights[3] == 0.0 and all(abs(w - 1 / 3) < 1e-12 for w in weights[:3])
18assert abs(out[0] - 2 / 3) < 1e-12 and abs(out[1] - 1) < 1e-12
19
20weights, out = attention_row((1, 1), keys, values, [True] * 4)
21assert 0.14 < weights[3] < 0.15 and abs(sum(weights) - 1) < 1e-12A batched multi-head version in PyTorch. The fused projection produces Q, K and V in one matrix multiply, and the reshape splits the model width into heads:
1import torch
2import torch.nn.functional as F
3from torch import Tensor, nn
4
5
6def scaled_dot_product_attention(
7 q: Tensor, k: Tensor, v: Tensor, mask: Tensor | None = None
8) -> Tensor:
9 # q,k,v: (batch, heads, seq, d_k); each mask row must allow at least one key
10 d_k = q.size(-1)
11 scores = (q @ k.transpose(-2, -1)) / d_k**0.5 # (b, h, seq, seq)
12 if mask is not None:
13 scores = scores.masked_fill(mask == 0, float("-inf")) # causal / padding
14 weights = F.softmax(scores, dim=-1)
15 return weights @ v # (b, h, seq, d_k)
16
17
18class MultiHeadAttention(nn.Module):
19 def __init__(self, d_model: int, n_heads: int) -> None:
20 super().__init__()
21 assert d_model % n_heads == 0, "d_model must be divisible by n_heads"
22 self.n_heads, self.d_k = n_heads, d_model // n_heads
23 self.qkv = nn.Linear(d_model, 3 * d_model) # fused Q,K,V projection
24 self.out = nn.Linear(d_model, d_model)
25
26 def forward(self, x: Tensor, mask: Tensor | None = None) -> Tensor:
27 b, seq, _ = x.shape
28 qkv = self.qkv(x).view(b, seq, 3, self.n_heads, self.d_k)
29 q, k, v = qkv.permute(2, 0, 3, 1, 4) # each: (b, heads, seq, d_k)
30 out = scaled_dot_product_attention(q, k, v, mask)
31 out = out.transpose(1, 2).reshape(b, seq, -1) # recombine heads
32 return self.out(out)
33
34
35# quick shape test
36mha = MultiHeadAttention(d_model=512, n_heads=8)
37x = torch.randn(2, 10, 512)
38assert mha(x).shape == (2, 10, 512)What it costs, and where it goes wrong
The score matrix is for a sequence of tokens, in every head of every layer. Dense attention therefore does arithmetic on top of for the projections. A naive implementation also stores the scores: at 8,192 tokens that is 67 million entries, 128 MiB in bf16, for one head of one layer of one sequence.
FlashAttention computes the same result in tiles and never writes the full matrix to GPU main memory. It is exact, not an approximation, and its arithmetic is still quadratic. Sparse and linear attention are different: they change what is computed. At decode time, a KV cache keeps past keys and values, so a new token costs per layer for its projections and to attend over a prefix of tokens.
Rows with nothing to attend to. If padding and causal masks combine to disallow every key for some query, its row is all and the softmax returns , which is NaN. The NaN then spreads through every later layer. Every mask row needs at least one allowed key.
Masking in the wrong place. Masks belong on the scores, before the softmax. Multiplying the weights by a 0/1 mask afterward leaves rows that no longer sum to one.
Reading heatmaps as explanations. An attention map shows mixing coefficients. It does not show what the value vectors carry or how transforms the mixture, and two heads with identical weights return different outputs when their value projections differ.
Sources and further reading
- Vaswani et al., Attention Is All You Need, §3.2: attention equations, head dimensions, and projection shapes.
- Dao et al., FlashAttention: exact attention with reduced memory traffic.
- Ainslie et al., GQA (2023): sharing key and value heads across groups of query heads.
- Llama Team, The Llama 3 Herd of Models (2024): the 8B configuration with 32 query heads and 8 key-value heads.
Keep going
Ask your own question about Attention Mechanisms, or start a guided session on it: six short pages, from the big picture to code you can run.