Self-Attention & Multi-Head Attention
Queries, keys and values, scaled dot products and many heads in parallel.
Self-attention fits on one line, , and most of a transformer's design decisions hide inside it: why the scores are scaled, how the future is hidden from each token, why many heads cost no more than one, and where the bill for long contexts comes from. Here you derive each one and implement the layer.
What you’ll learn
- Compute scaled dot-product attention in matrix form with causal and padding masks, and derive the scaling from the variance of a dot product.
- Prove that self-attention without positional information is permutation-equivariant, and say what breaks the symmetry.
- Assemble multi-head attention and show that it has weights (plus biases) whatever the number of heads.
- Count the FLOPs of an attention layer, , and find the length at which the quadratic term dominates.
- Distinguish self-attention from cross-attention, and describe the kinds of heads found in trained models.
Attention in matrix form
Stack the token vectors of a sequence as the rows of . Each token is mapped to a query, a key and a value by three learned matrices: and in , and . Every query is compared with every key in one matrix product, and each row of scores becomes a probability distribution over positions. This is scaled dot-product attention:
Assume the coordinates of and are independent with mean and variance , roughly the situation at initialization when inputs are normalized and weights are scaled to preserve variance. The score is a sum of products, with mean
Each product has variance :
The products involve disjoint pairs of independent coordinates, so they are independent and their variances add:
Dividing by the standard deviation gives scores of variance for every head size. Without it, a head with starts with scores of standard deviation :
Why does the spread matter? Draw 512 random scores and apply the softmax. With standard deviation the largest weight is typically under 3%, so every key contributes and gradients reach all of them. With standard deviation the largest weight is about three-quarters on average: the row is nearly one-hot from the first step. The softmax's Jacobian, , vanishes as approaches a one-hot vector, so almost no gradient would reach and . The scaling keeps the initial attention soft regardless of head size.
Masks, and the symmetry they break
Two masks appear in practice, and both act before the softmax, by adding to forbidden scores. Their weights become exactly , and each row still sums to over the allowed positions.
- The causal mask sets for , so position sees only positions . One forward pass then yields a prediction at every position, each conditioned only on its own prefix.
- The padding mask handles batches of sequences of different lengths. Shorter sequences are padded to a common length , and every key column that belongs to padding is set to , so no real token attends to filler. Outputs at padded query positions are simply ignored by the loss.
import torch
import torch.nn.functional as F
B, H, T, dk = 2, 4, 5, 16
q, k, v = (torch.randn(B, H, T, dk) for _ in range(3))
lengths = torch.tensor([5, 3]) # the second sequence ends in 2 padding tokens
real_key = torch.arange(T)[None, :] < lengths[:, None] # (B, T): True for real tokens
causal = torch.ones(T, T, dtype=torch.bool).tril() # (T, T): True where j <= t
allowed = causal[None, None] & real_key[:, None, None, :] # (B, 1, T, T), broadcast over heads
z = F.scaled_dot_product_attention(q, k, v, attn_mask=allowed) # (B, H, T, dk)
# with no padding, attn_mask=causal or is_causal=True gives the same resultPyTorch's boolean attn_mask marks the pairs that may attend (True) and is broadcast over batch and heads; a float mask is added to the scores instead. The default scale is , from the last dimension of the query.
Permuting the rows of permutes the rows of , and alike, so the score matrix is permuted in its rows and its columns:
A row-wise softmax commutes with both operations: permuting the rows permutes the outputs' rows, and permuting the entries within a row permutes that row's outputs.
Multiply by the permuted values and use :
Which change makes a self-attention layer's output for a given token depend on where the other tokens stand in the sequence?
- Using more heads
- Dividing the scores by
- Using a larger value dimension
- A causal mask, or position vectors added to the inputs
Show the answer
D. A causal mask, or position vectors added to the inputs
The proof needs the mask to be invariant under , and is. A causal mask is not: what token sees depends on which tokens precede it. Adding a positional encoding makes the input rows themselves differ by position. Heads, scaling and widths all leave the symmetry intact.
Multi-head attention
One head produces one distribution per query. Multi-head attention runs heads in parallel, each in its own subspace of size with its own projections , then concatenates the outputs and mixes them with :
The query projections, each , sit side by side in one matrix. The same holds for keys and values:
Add the output projection and one bias vector of length per matrix:
does not appear: more heads means more, narrower attention patterns at the same cost in weights. Vaswani et al. (2017) split into heads of dimensions each; heads of 64 to 128 dimensions remain common.
import torch.nn as nn
import torch.nn.functional as F
class MultiHeadAttention(nn.Module):
def __init__(self, d, n_heads):
super().__init__()
assert d % n_heads == 0
self.h, self.dk = n_heads, d // n_heads
self.qkv = nn.Linear(d, 3 * d) # W_Q, W_K, W_V side by side: 3d^2 + 3d
self.out = nn.Linear(d, d) # W_O: d^2 + d
def forward(self, x, causal=True): # x: (B, T, d)
B, T, d = x.shape
q, k, v = self.qkv(x).split(d, dim=-1)
q, k, v = (t.view(B, T, self.h, self.dk).transpose(1, 2) for t in (q, k, v))
z = F.scaled_dot_product_attention(q, k, v, is_causal=causal) # (B, h, T, dk)
z = z.transpose(1, 2).reshape(B, T, d) # concatenate the heads
return self.out(z)Splitting one projection into heads is exactly the block structure of the derivation: the heads are just a reshaping of the same matrices. Fused kernels behind scaled_dot_product_attention compute all heads at once.
GPT-2's smallest model has width and 12 heads. How many parameters, in millions, does one of its attention sublayers have, biases included?
Show the answer
2.36 M
million, independent of the 12 heads. Twelve layers of attention hold about 28 million of the model's roughly 124 million parameters; the feed-forward layers hold twice as many.
What a layer costs
Count a multiply–add as 2 FLOPs, so multiplying an matrix by an one costs . The four projections each multiply by :
Each head forms , a times product, and then multiplies the weights by , of size . Over heads, with :
The softmax and scaling add only operations. In total, and the length at which the two terms are equal:
With the feed-forward network (, next lesson) the whole layer costs , and the quadratic term takes over only at . A causal mask makes half the scores useless; kernels that skip the masked blocks save nearly half of the .
| Width | Length | Projections | Scores and mixing |
|---|---|---|---|
| 768 | 1,024 | ||
| 4,096 | 4,096 | ||
| 4,096 | 32,768 |
A layer of width processes tokens. How many times larger is the attention core () than the projections ()?
Show the answer
4 ×
The ratio is . Long contexts shift the cost from the weights, which do not depend on , to the token-to-token interactions.
Memory. A naive implementation stores the weights of every head for the backward pass. At in 16-bit numbers that is bytes MiB per head per layer, which quickly exceeds a GPU's memory at long contexts. Exact kernels such as FlashAttention never store the full matrix: they compute it in tiles in fast on-chip memory and recompute it during the backward pass (Efficient Transformers, and FlashAttention in Depth for the algorithm).
Cross-attention, and the heads models learn
In an encoder–decoder model the decoder also needs to read the input. Cross-attention takes its queries from the decoder states and its keys and values from the encoder's output :
What trained heads do. Studies of trained models find recurring head types. In BERT-base, Clark et al. (2019) found heads that put most of their weight on the previous or the next token, heads whose attention tracks syntactic relations such as verbs to their direct objects with over 75% accuracy, and a large share of attention parked on the separator token [SEP], which they read as a "no-op" (Attention Sinks & Massive Activations takes that up). In translation models, Voita et al. (2019) identified positional, syntactic and rare-word heads, and pruned 38 of 48 encoder heads at a cost of only 0.15 BLEU. In decoders, an induction head finds an earlier occurrence of the current token and copies the token that followed it, so "… A B … A" predicts "B" (Elhage et al., 2021; Olsson et al., 2022): a mechanism behind in-context learning.
Key takeaways
- Attention computes : each output is a convex combination of values, with weights from query–key dot products; masks add before the softmax.
- A dot product of two -dimensional vectors with independent unit-variance coordinates has variance ; dividing by keeps the initial softmax away from saturation for every head size.
- Without masks or positions, self-attention is permutation-equivariant, ; causal masks and positional encodings break the symmetry.
- Multi-head attention splits width into heads of size for parameters whatever , and a layer costs about FLOPs, so the quadratic part dominates beyond .
- Cross-attention takes queries from the decoder and keys and values from the encoder. Trained models show recurring head types: positional, syntactic, delimiter and induction heads.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Suppose every coordinate of a query and a key is an independent draw with mean and variance , and , roughly the situation at initialization. How spread out is the raw dot product , and which factor does scaled dot-product attention apply to it?
- About ; it multiplies by
- ; it multiplies by
- ; no scaling is needed
- About ; it multiplies by
Show the answer
A. About ; it multiplies by
The variance is the sum of unit variances, so the standard deviation is . Multiplying by restores unit variance, keeping the softmax away from one-hot rows at the start of training.
A batch holds a 10-token sentence padded to . In an encoder (no causal mask), which scores receive ?
- The rows of the 6 padding positions, so padding tokens attend to nothing
- The columns of the 6 padding keys, so no query attends to padding
- The diagonal, so no token attends to itself
- Every score above the diagonal
Show the answer
B. The columns of the 6 padding keys, so no query attends to padding
Masking the key columns of the padding removes the filler from every real token's weighted average. The outputs at padding positions are meaningless but harmless: the loss ignores them. A fully masked row would even be dangerous, since a softmax of all is undefined.
For a single attention sublayer of width , at what sequence length do the score and mixing FLOPs equal the projection FLOPs?
Show the answer
C.
gives . Including the feed-forward network's moves the crossover for the whole layer to .
In the cross-attention of an encoder–decoder translator, where do the queries, keys and values come from?
- All three from the encoder output
- All three from the decoder states, with a causal mask
- Queries from the encoder output; keys and values from the decoder states
- Queries from the decoder states; keys and values from the encoder output
Show the answer
D. Queries from the decoder states; keys and values from the encoder output
Each output position asks a question (query) of the source sentence (keys) and reads what it finds (values). The score matrix is , and the encoder's keys and values are computed once per input.
Go deeper
- Attention as Associative Memory · Hopfield networks, key–value storage and how much one layer can hold.
- Attention Sinks & Massive Activations · Why models park attention on the first token, and the outliers this creates.
- What Transformers Can Compute · Circuit complexity, formal languages and the extra power of chain of thought.
Further reading
- A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser & I. Polosukhin, "Attention is all you need," NeurIPS (2017).
- K. Clark, U. Khandelwal, O. Levy & C. D. Manning, "What does BERT look at? An analysis of BERT's attention," BlackboxNLP (2019).
- E. Voita, D. Talbot, F. Moiseev, R. Sennrich & I. Titov, "Analyzing multi-head self-attention: Specialized heads do the heavy lifting, the rest can be pruned," ACL (2019).
- C. Olsson et al., "In-context learning and induction heads," Transformer Circuits Thread (2022).
- S. J. D. Prince, Understanding Deep Learning, ch. 12 "Transformers" (MIT Press, 2023).