10.3 Self-Attention and Multiple Heads
In the examples of Section 10.2, queries came from one sequence and keys and values from another. A decoder-only language model has only a single sequence: to contextualize each token, queries, keys, and values must all be derived from that sequence itself.
Consider the sentence "Alice gave Bob the book". Interpreting gave requires identifying the giver (Alice), the recipient (Bob), and the object (book). In self-attention (Cheng et al., 2016; Lin et al., 2017; Vaswani et al., 2017), every token projects its representation into a query, a key, and a value, allowing gave to query the other words in the sentence and aggregate their values.
However, a single attention lookup produces only one probability distribution per query and returns a single blended vector. How can a token retrieve several distinct arguments without collapsing them into one average? We first trace a single head of self-attention on our five-word sentence, then prove an information-theoretic lower bound showing why one head cannot recover two independent values, and finally construct multi-head attention and grouped-query attention (GQA).
10.3.1 Self-Attention#
In self-attention, each token representation (row of ) plays three distinct roles via learned linear projections and : the query specifies what the token seeks, the key specifies what it offers to other queries, and the value specifies the content returned when selected. Applying scaled dot-product attention yields one attention head of width :
10.3.1.1 One Head on One Sentence#
To trace (10.3.1) concretely, represent each word of "Alice gave Bob the book" by a 9-dimensional vector concatenating a 4D one-hot grammatical role (person, action, thing, or function word) and a 5D one-hot word identity. Set and to read only the 4D role into dimensions, and to extract the 5D word indicator:
| role | query | key |
|---|---|---|
| person (Alice, Bob) | ||
| action (gave) | ||
| thing (book) | ||
| function word ("the") |
tokens = ['Alice', 'gave', 'Bob', 'the', 'book']
# Role of each token: person, action, thing, function word
roles = d2l.tensor([[1.0, 0, 0, 0], [0, 1, 0, 0], [1, 0, 0, 0],
[0, 0, 0, 1], [0, 0, 1, 0]])
X = d2l.concat((roles, d2l.eye(5)), 1) # (5, 9): the role, then the word
# Queries and keys read the role part (rows: person, action, thing,
# function word), values the word part
W_q = d2l.concat((d2l.tensor([[1.0, -1], [1, 1], [1, -1], [0, 0]]),
d2l.zeros((5, 2))))
W_k = d2l.concat((d2l.tensor([[1.0, 1], [1, -1], [1, 1], [0, 0]]),
d2l.zeros((5, 2))))
W_v = d2l.concat((d2l.zeros((4, 5)), d2l.eye(5)))
Q, K, V = X @ W_q, X @ W_k, X @ W_v # (5, 2), (5, 2), (5, 5)For gave, the query has dot product with each noun's key and with gave and "the". Dividing by gives scaled scores on each noun and elsewhere, which softmax converts into weights per noun and on gave and "the" (Figure 10.3.1).
One head of self-attention on "Alice gave Bob the book", with the hand-set maps of the code above (). Every token emits a query, a key, and a value. The query of gave, , is scored against every key by ; the softmax turns the scores and into weights and ; the output of gave is the weighted sum of the values, which mark the five words.
attention = d2l.DotProductAttention()
Y = attention(Q[None], K[None], V[None]) # A minibatch of one sentence
weights = attention.attention_weights[0]
scores = Q[1] @ K.T / math.sqrt(Q.shape[-1]) # Scaled by sqrt(d_h)
print('scores of gave: ', np.asarray(scores).round(2))
print('weights of gave:', np.asarray(weights[1]).round(2))
print('weights of the: ', np.asarray(weights[3]).round(2))
print('output of gave: ', np.asarray(Y[0, 1]).round(2))
attention(Q[None], K[None], V[None], d2l.causal_mask(5))
print('causal weights of gave:',
np.asarray(attention.attention_weights[0, 1]).round(2))
d2l.show_heatmaps(weights[None, None], xlabel='keys', ylabel='queries',
figsize=(3.2, 3.2), cmap='Blues',
xticklabels=tokens, yticklabels=tokens)scores of gave: [1.41 0. 1.41 0. 1.41]
weights of gave: [0.29 0.07 0.29 0.07 0.29]
weights of the: [0.2 0.2 0.2 0.2 0.2]
output of gave: [0.29 0.07 0.29 0.07 0.29]
causal weights of gave: [0.8 0.2 0. 0. 0. ]
Conversely, each noun's query scores on gave (weight ) and elsewhere, while "the" has a zero query and attends uniformly ( across all five words). Applying a causal mask restricts gave to Alice and itself, renormalizing their scores to .
10.3.1.2 Separate Maps for Queries and Keys#
Why use separate matrices and ? If a single projection served as both query and key, the score matrix would be symmetric and positive semidefinite, satisfying by Cauchy--Schwarz. Two things are then impossible. A verb could not seek a noun more strongly than the noun seeks the verb, since . And two tokens could never each score the other above themselves: a verb can prefer nouns to itself only if nouns have the larger norm, and then nouns prefer themselves to the verb. Separate query, key, and value projections decouple who looks, who is found, and what content is passed on.
10.3.2 Limits of a Single Head#
In our five-word sentence, gave blended Alice, Bob, and book into a single weighted average. To quantify the bottleneck of having only one attention distribution per query, consider the copy-both task: two source positions hold independent standard Gaussian value vectors with fixed position-only keys, and a single query must output their concatenation via a linear readout.
Because the keys depend only on position, a single head assigns fixed softmax weights with and passes a single mixture to the linear readout.
Proposition. For one attention head with two fixed position-only keys, independent standard Gaussian values , and a linear readout, the minimum achievable relative squared error on the copy-both task is for every softmax pair .
Proof. Given , the minimum mean-squared error estimator of is the conditional expectation , which is linear in and leaves residual variance per coordinate. By symmetry, estimating leaves residual variance per coordinate. Their sum is per coordinate out of a total target variance of per coordinate, giving a relative squared error of regardless of .
Solving the copy-both task requires two ingredients: (1) at least two linearly independent weightings over the keys, and (2) sufficient output dimension (room) to hold all retrieved coordinates (Exercise 5). We verify the root-mean-square relative error bound for one head, and show that two heads with distinct weightings—even soft ones such as and —allow a linear readout to invert the mixing matrix up to floating-point precision (Figure 10.3.2).
N, d_v = 10000, 8
V1, V2 = torch.randn(N, d_v), torch.randn(N, d_v)
target = torch.cat([V1, V2], dim=1)
def readout_error(M, target):
"""Best linear readout of target from M, relative error."""
W = torch.linalg.lstsq(M, target).solution
return ((M @ W - target).norm() / target.norm()).item()
M = 0.7 * V1 + 0.3 * V2
print(f'one head, weights (0.70, 0.30): relative error '
f'{readout_error(M, target):.3f}; sqrt(1/2) = {0.5 ** 0.5:.3f}')
for a in (1.0, 0.88):
M2 = torch.cat([a * V1 + (1 - a) * V2, (1 - a) * V1 + a * V2], dim=1)
print(f'two heads, weights ({a:.2f}, {1 - a:.2f}) and '
f'({1 - a:.2f}, {a:.2f}): '
f'relative error {readout_error(M2, target):.1e}')one head, weights (0.70, 0.30): relative error 0.709; sqrt(1/2) = 0.707
two heads, weights (1.00, 0.00) and (0.00, 1.00): relative error 1.5e-06
two heads, weights (0.88, 0.12) and (0.12, 0.88): relative error 7.0e-07
One weighting per query against two. A single head serves the copy-both task with one softmax weighting, so its output blends the two requested values. Two heads with different weightings supply two mixtures, from which a linear readout recovers both values.
10.3.3 Multi-Head Attention#
10.3.3.1 Projected Heads#
Multi-head attention (Vaswani et al., 2017) runs independent attention heads in parallel, each with its own query, key, and value projections :
and concatenates their outputs before applying a final linear projection (Figure 10.3.3):
Multi-head attention. Every head reads the same queries, keys, and values, projects them into its own subspace, and attends there; the head outputs are concatenated and recombined by one output projection.
10.3.3.2 Parameter and FLOP Counts#
Setting the head width to keeps the total dimension across all heads equal to . Stacked side by side, the query projections form a single matrix, as do the key, value, and output projections. Counting one multiply--add as FLOPs, a multi-head self-attention layer over tokens requires
For one layer of GPT-2 small (, ), this amounts to GFLOPs for projections, GFLOPs for scores and value mixing, and parameters. Remarkably, neither the parameter count nor the leading FLOP count depends on the number of heads : splitting into heads shrinks each head's inner product by while running of them (only the softmax overhead scales with ). Conversely, cannot be made arbitrarily small: at , scalar scores are monotone in , so a query can focus only on the extremal keys (Exercise 1). In practice, is standard.
10.3.3.3 Comparison with Convolution and Recurrence#
Figure 10.3.4 and Table 10.3.1 compare 1D convolution (Chapter 6), recurrence (Section 8.4), and self-attention as sequence-to-sequence layers over tokens of width .
Sequence-layer connectivity for five tokens. Highlighted edges show how the inputs reach the third output in one layer: a convolution with kernel size sees its neighbors, a recurrence passes information step by step along the chain, and self-attention connects every position directly. Below each panel are the path length between distant tokens and whether the outputs are computed in parallel.
| layer type | complexity | sequential operations | maximum path length |
|---|---|---|---|
| convolution (kernel ) | |||
| recurrence | |||
| self-attention |
Self-attention combines sequential steps (full training parallelism) with maximum path length between any pair of tokens, eliminating the -step recurrent gradient chain (Section 8.5). The price is the quadratic score-and-mix term, which exceeds the projection cost once ( for GPT-2 small).
10.3.3.4 Implementation#
In MultiHeadAttention, a single linear layer computes all head
projections at once, and split_heads reshapes (batch, length, H * d_h)
into (batch, H, length, d_h) so that DotProductAttention executes all
heads in one batched operation (Figure 10.3.5). Projections omit
additive biases by default (bias=False), following modern transformer
conventions. The parameter num_kv_heads supports key--value head sharing
(Section 10.3.3.6).
class MultiHeadAttention(nn.Module):
"""Multi-head attention with heads as an explicit axis; num_kv_heads <
num_heads shares each key-value head across a group of query heads."""
def __init__(self, num_hiddens, num_heads, dropout=0.0, bias=False,
num_kv_heads=None):
super().__init__()
assert num_hiddens % num_heads == 0, 'heads must divide num_hiddens'
self.num_heads = num_heads
self.num_kv_heads = num_kv_heads or num_heads
assert num_heads % self.num_kv_heads == 0
kv_hiddens = self.num_kv_heads * (num_hiddens // num_heads)
self.attention = d2l.DotProductAttention(dropout)
self.W_q = nn.Linear(num_hiddens, num_hiddens, bias=bias)
self.W_k = nn.Linear(num_hiddens, kv_hiddens, bias=bias)
self.W_v = nn.Linear(num_hiddens, kv_hiddens, bias=bias)
self.W_o = nn.Linear(num_hiddens, num_hiddens, bias=bias)
def forward(self, queries, keys, values, mask=None):
# queries: (batch, no. of queries, num_hiddens); keys and values:
# (batch, no. of key-value pairs, num_hiddens). mask: boolean,
# broadcastable to (batch, no. of queries, no. of keys), shared by
# all heads, or to (batch, num_heads, no. of queries, no. of keys)
q = self.split_heads(self.W_q(queries), self.num_heads)
k = self.split_heads(self.W_k(keys), self.num_kv_heads)
v = self.split_heads(self.W_v(values), self.num_kv_heads)
group = self.num_heads // self.num_kv_heads
k, v = k.repeat_interleave(group, 1), v.repeat_interleave(group, 1)
if mask is not None and mask.dim() == 3:
mask = mask[:, None] # The same mask for every head
# Shape of Y: (batch, num_heads, no. of queries, head width)
Y = self.attention(q, k, v, mask)
return self.W_o(self.merge_heads(Y))
@property
def attention_weights(self):
"""Weights of the last call: (batch, num_heads, queries, keys)."""
return self.attention.attention_weightsHeads as slices of one projection. The projected queries of tokens are cut into column slices of width , which become a separate head axis; each head attends on its own, and the head outputs are placed side by side again before the output projection . Keys and values are split in the same way.
The two reshape-and-transpose helpers split_heads and merge_heads (Figure 10.3.5) fold the last dimension into an explicit head axis (batch, num_heads, length, width) before attention and re-concatenate the head outputs afterward:
@d2l.add_to_class(MultiHeadAttention)
def split_heads(self, X, num_heads):
"""(batch, length, num_heads * width) -> (batch, num_heads, length,
width)."""
return X.reshape(X.shape[0], X.shape[1], num_heads, -1).transpose(1, 2)
@d2l.add_to_class(MultiHeadAttention)
def merge_heads(self, X):
"""Reverse split_heads: (batch, num_heads, length, width) -> (batch,
length, num_heads * width)."""
return X.transpose(1, 2).reshape(X.shape[0], X.shape[2], -1)10.3.3.5 Learned Heads on the Copy-Both Task#
We now test MultiHeadAttention of width on the copy-both task
(, padded with zeros to width ; keys and query ).
def copy_both_data(n, d=16, d_v=8):
"""One query, two position-only keys, values of width d_v padded to d."""
V = torch.randn(n, 2, d_v)
keys = torch.eye(d)[:2].expand(n, 2, d) # e_1, e_2 mark the positions
query = torch.eye(d)[2].expand(n, 1, d) # e_3 asks for both values
values = F.pad(V, (0, d - d_v))
return query, keys, values, V.reshape(n, 1, 2 * d_v)
def train_copy_both(num_heads, num_kv_heads=None, num_steps=2000):
model = MultiHeadAttention(16, num_heads, num_kv_heads=num_kv_heads)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)
for _ in range(num_steps):
query, keys, values, target = copy_both_data(256)
loss = ((model(query, keys, values) - target) ** 2).mean()
optimizer.zero_grad()
loss.backward()
optimizer.step()
return model
def evaluate_copy_both(model, n=10000):
"""Relative error on fresh examples; each head's weight on v_1."""
query, keys, values, target = copy_both_data(n)
with torch.inference_mode():
err = (model(query, keys, values) - target).norm() / target.norm()
return err.item(), model.attention_weights[0, :, 0, 0].tolist()Training two seeds at each head count (all sharing the same total width and parameter count ) compares their relative reconstruction error and the attention weight that each head places on the first value vector :
print('H run parameters error weight on v_1, per head')
for num_heads in (1, 2, 4):
for run in (1, 2):
model = train_copy_both(num_heads)
err, alpha_1 = evaluate_copy_both(model)
print(f'{num_heads} {run:3d} {d2l.num_params(model):10d} '
f'{err:<#8.2g} ' + ' '.join(f'{a:.2f}' for a in alpha_1))H run parameters error weight on v_1, per head
1 1 1024 0.71 0.51
1 2 1024 0.71 0.52
2 1 1024 1.1e-07 0.98 0.12
2 2 1024 1.1e-07 0.93 0.03
4 1 1024 1.1e-07 0.96 0.94 0.16 0.12
4 2 1024 1.2e-07 0.04 0.26 0.88 0.95
All configurations have parameters. As predicted by our proposition, stalls at the bound, whereas learns distinct head weightings and reduces the error to .
10.3.3.6 Shared Keys and Values#
During autoregressive generation, past keys and values are cached in memory, so that each new token can attend to all previous positions without recomputing their projections (Section 11.3). Grouped-query attention (GQA) (Ainslie et al., 2023) reduces this cache by a factor of by sharing each key--value head across a group of query heads; setting gives multi-query attention (MQA) (Shazeer, 2019).
On the copy-both task, the shared value heads span at most coordinates per value, so recovering a -dimensional value requires (Exercise 6). With and , layouts and have and solve the task to fp32 precision, whereas has and returns to the bottleneck despite learning distinct weightings across its four query heads:
print('H H_kv run parameters error weight on v_1, per head')
for num_heads, num_kv_heads in ((2, 1), (4, 2), (4, 1)):
for run in (1, 2):
model = train_copy_both(num_heads, num_kv_heads)
err, alpha_1 = evaluate_copy_both(model)
print(f'{num_heads} {num_kv_heads:4d} {run:3d} '
f'{d2l.num_params(model):10d} {err:<#8.2g} '
+ ' '.join(f'{a:.2f}' for a in alpha_1))H H_kv run parameters error weight on v_1, per head
2 1 1 768 1.1e-07 0.93 0.03
2 1 2 768 1.1e-07 0.03 0.96
4 2 1 768 1.1e-07 0.08 0.95 0.98 0.08
4 2 2 768 1.1e-07 0.03 0.88 0.02 0.88
4 1 1 640 0.71 0.97 0.04 0.13 0.89
4 1 2 640 0.71 0.03 0.04 0.72 0.98
10.3.4 Cross-Attention#
While self-attention passes the same sequence as queries, keys,
and values (attention(X, X, X)), cross-attention draws queries from a
target sequence and keys and values from a source sequence
(attention(A, B, B)), producing one output row per token of
. Encoder--decoder transformers use cross-attention to read an
encoded source sentence during translation, and multimodal models use it to
let text tokens query visual features (Alayrac et al., 2022).
Even with multiple heads, however, self-attention remains blind to word order: swapping Alice and Bob in "Alice gave Bob the book" leaves the output at gave unchanged. Injecting sequence order is the subject of Section 10.4.
10.3.5 Summary#
Self-attention projects each token of a sequence into a query, a key, and a value, connecting all pairs of positions in sequential steps and path length at FLOPs. Because a single head forms only one convex mixture of values per query, any single head incurs a relative squared error of at least when tasked with retrieving two independent values simultaneously. Multi-head attention overcomes this bottleneck by running subspace heads of width in parallel and combining their outputs through , requiring parameters and FLOPs independent of . Grouped-query and multi-query attention share key–value heads across query groups to shrink generation caches by a factor of , preserving retrieval capacity whenever the shared value width can accommodate the retrieved features.
10.3.6 Exercises#
-
[code] Narrow heads. With , the leading count of (10.3.4) does not depend on , so the number of heads looks free up to . Consider one head with scores over keys and no mask. Call a query sharp on key when its weights concentrate on as the query is scaled by a factor that grows without bound.
- For and distinct scalar keys, show that every query's weights are monotone in . Conclude that the queries of such a head can be sharp only on the largest or the smallest key.
- Show that for the keys and queries can be chosen so that each of queries is sharp on a key of its own choosing, for every assignment of queries to keys.
- Use these two results to state which attention patterns a layer gives up as approaches .
- Time the forward pass of
MultiHeadAttentionwith dropout 0 for self-attention with and on a minibatch of sequences for . Make a warm-up call first and wait for the result before stopping the clock. Report the ratio of the slowest to the fastest configuration. Identify the cost that grows with and that (10.3.4) leaves out, and check that it accounts for the trend.
-
[code] Heads as slices.
MultiHeadAttentioncomputes one projection of width for each of the queries, keys, and values and splits it into heads withsplit_heads.- Head owns a slice of the output features of
W_q,W_k, andW_v. Determine which input features ofW_oreceive that head's output. Write a forward pass that loops over the heads, applies the sliced projections, and callsd2l.DotProductAttentiononce per head. Verify on random inputs with a padding mask that it matchesMultiHeadAttentionwith dropout 0, and extend your loop tonum_kv_heads < num_heads. - Replace the body of
split_headsbyX.reshape(X.shape[0], num_heads, X.shape[1], -1), which returns a tensor of the same shape. Describe which numbers each "head" now holds, show on random inputs that the output changes, and explain why no shape check can detect the mistake. Which input lengths and widths, if any, make the two versions agree?
- Head owns a slice of the output features of
-
Permuting the source. In cross-attention, the queries come from and the keys and values from , neither carrying positional information. Let be an permutation matrix.
- Show that replacing by in
both the key and the value argument leaves the output of
MultiHeadAttentionunchanged when no mask is applied, and that replacing it in the key argument alone changes the output in general. - Now let a padding mask mark only the first rows of as valid. Which permutations leave the output unchanged when the mask stays fixed?
- Show that replacing by in
both the key and the value argument leaves the output of
-
[code] Nearly identical heads. ● Two heads with weights and supply two distinct mixtures, so the linear readout inverts them exactly for every .
- Write the mixing matrix, compute its eigenvalues and eigenvectors, and express its condition number as a function of .
- Add independent Gaussian noise of standard deviation
to both mixtures and measure the error with
readout_errorfor . Plot the error against on logarithmic axes, read off the slope where the curve is straight, and explain it with the condition number from (a). - Every head of a freshly initialized layer weights the two positions
of the copy-both task close to . Modify
train_copy_bothto record the relative error and the weights of each head every 20 steps, and plot both for . Use the conditioning of the mixing matrix to explain the shape of the error curve in the first few hundred steps. Repeat for and sort the final heads into those that are nearly one-hot, those that are soft but distinct, and those that nearly duplicate another head.
-
What the bound counts. ● The proposition of Section 10.3.2 fixes the softmax weights, but its error bound rests on a weaker fact: the readout receives a single vector and must produce the target .
- Let be any function of and , including a mixture whose weights depend on the values, and let be any matrix. Show that
Conclude that content-dependent keys, more layers, or a residual connection leave the bound in place as long as the readout is linear and receives numbers.
- A layer of width with two heads of width receives the values padded with zeros to width . Give the attention weights of each head, value projections , and an output projection that solve the task exactly. Compare your weights with those printed in Section 10.3.3.5.
- Generalize the proposition to source positions with independent standard Gaussian values and the target . Each of heads applies fixed weights to the values, the weights of head form row of a matrix , and a linear readout sees all mixtures. Show that the best relative squared error is
and that softmax weights, whose entries are all positive, can attain .
- [code] Sharing keys and values on the copy-both task. ● Let a layer
of width have query heads of width and
key--value heads.
- Use the counting of Exercise 5 to show that it can solve the task only if , and that this condition suffices.
- Train a layer with
train_copy_both(2, 1), in which two query heads share one key--value head. Find the parameters that differ between the two heads and those they share, and explain from the copy-both task why the difference must lie where you found it.