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)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 \(\mathbf{x}_i \in \mathbb{R}^d\) (row \(i\) of \(\mathbf{X} \in \mathbb{R}^{n \times d}\)) plays three distinct roles via learned linear projections \(\mathbf{W}_q, \mathbf{W}_k \in \mathbb{R}^{d \times d_h}\) and \(\mathbf{W}_v \in \mathbb{R}^{d \times d_v}\): the query \(\mathbf{x}_i\mathbf{W}_q\) specifies what the token seeks, the key \(\mathbf{x}_i\mathbf{W}_k\) specifies what it offers to other queries, and the value \(\mathbf{x}_i\mathbf{W}_v\) specifies the content returned when selected. Applying scaled dot-product attention yields one attention head of width \(d_h\):
\[ \mathrm{softmax}\left(\frac{(\mathbf{X}\mathbf{W}_q)(\mathbf{X}\mathbf{W}_k)^\top}{\sqrt{d_h}}\right)\mathbf{X}\mathbf{W}_v \in \mathbb{R}^{n \times d_v}. \tag{10.3.1}\]
10.3.1.1 One Head on One Sentence
To trace Equation 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 \(\mathbf{W}_q\) and \(\mathbf{W}_k\) to read only the 4D role into \(d_h = 2\) dimensions, and \(\mathbf{W}_v\) to extract the 5D word indicator:
| role | query | key |
|---|---|---|
| person (Alice, Bob) | \((1, -1)\) | \((1, 1)\) |
| action (gave) | \((1, 1)\) | \((1, -1)\) |
| thing (book) | \((1, -1)\) | \((1, 1)\) |
| function word (“the”) | \((0, 0)\) | \((0, 0)\) |
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 \((1, 1)\) has dot product \(2\) with each noun’s key \((1, 1)\) and \(0\) with gave and “the”. Dividing by \(\sqrt{2}\) gives scaled scores \(1.41\) on each noun and \(0\) elsewhere, which softmax converts into weights \(e^{1.41}/(3e^{1.41} + 2) \approx 0.29\) per noun and \(0.07\) on gave and “the” (Figure 10.3.1).
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. ]
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 \((1, -1)\) scores \(1.41\) on gave (weight \(0.51\)) and \(0\) elsewhere, while “the” has a zero query and attends uniformly (\(0.20\) across all five words). Applying a causal mask restricts gave to Alice and itself, renormalizing their scores \((1.41, 0)\) to \((0.80, 0.20)\).
10.3.1.2 Separate Maps for Queries and Keys
Why use separate matrices \(\mathbf{W}_q\) and \(\mathbf{W}_k\)? If a single projection \(\mathbf{u}_i = \mathbf{x}_i\mathbf{W}\) served as both query and key, the score matrix \(s_{ij} = \mathbf{u}_i^\top \mathbf{u}_j / \sqrt{d_h}\) would be symmetric and positive semidefinite, satisfying \(s_{ij} \le \sqrt{s_{ii}\, s_{jj}} \le \max(s_{ii}, s_{jj})\) by Cauchy–Schwarz. Two things are then impossible. A verb could not seek a noun more strongly than the noun seeks the verb, since \(s_{ij} = s_{ji}\). 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 \(\mathbf{v}_1, \mathbf{v}_2 \in \mathbb{R}^{d_v}\) with fixed position-only keys, and a single query must output their concatenation \(\mathbf{t} = [\mathbf{v}_1; \mathbf{v}_2] \in \mathbb{R}^{2d_v}\) via a linear readout.
Because the keys depend only on position, a single head assigns fixed softmax weights \((\alpha_1, \alpha_2)\) with \(\alpha_1 + \alpha_2 = 1\) and passes a single mixture \(\mathbf{m} = \alpha_1 \mathbf{v}_1 + \alpha_2 \mathbf{v}_2 \in \mathbb{R}^{d_v}\) to the linear readout.
Proposition. For one attention head with two fixed position-only keys, independent standard Gaussian values \(\mathbf{v}_1, \mathbf{v}_2 \in \mathbb{R}^{d_v}\), and a linear readout, the minimum achievable relative squared error on the copy-both task is \(1/2\) for every softmax pair \((\alpha_1, \alpha_2)\).
Proof. Given \(\mathbf{m} = \alpha_1 \mathbf{v}_1 + \alpha_2 \mathbf{v}_2\), the minimum mean-squared error estimator of \(\mathbf{v}_1\) is the conditional expectation \(\mathbb{E}[\mathbf{v}_1 \mid \mathbf{m}] = \tfrac{\alpha_1}{\alpha_1^2 + \alpha_2^2}\, \mathbf{m}\), which is linear in \(\mathbf{m}\) and leaves residual variance \(1 - \tfrac{\alpha_1^2}{\alpha_1^2 + \alpha_2^2} = \tfrac{\alpha_2^2}{\alpha_1^2 + \alpha_2^2}\) per coordinate. By symmetry, estimating \(\mathbf{v}_2\) leaves residual variance \(\tfrac{\alpha_1^2}{\alpha_1^2 + \alpha_2^2}\) per coordinate. Their sum is \(1\) per coordinate out of a total target variance of \(2\) per coordinate, giving a relative squared error of \(1/2\) regardless of \((\alpha_1, \alpha_2)\). \(\blacksquare\)
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 \(2d_v\) retrieved coordinates (Exercise 5). We verify the \(\sqrt{1/2} \approx 0.707\) root-mean-square relative error bound for one head, and show that two heads with distinct weightings—even soft ones such as \((0.88, 0.12)\) and \((0.12, 0.88)\)—allow a linear readout to invert the \(2 \times 2\) 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
N, d_v = 10000, 8
key1, key2 = jax.random.split(d2l.get_key())
V1, V2 = jax.random.normal(key1, (N, d_v)), jax.random.normal(key2, (N, d_v))
target = jnp.concatenate([V1, V2], axis=1)
def readout_error(M, target):
"""Best linear readout of target from M, relative error."""
# Full fp32 products: TF32, the default on recent NVIDIA cards, would
# stop the two-head errors near 1e-4
with jax.default_matmul_precision('highest'):
W = jnp.linalg.lstsq(M, target)[0]
err = jnp.linalg.norm(M @ W - target) / jnp.linalg.norm(target)
return float(err)
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 = jnp.concatenate([a * V1 + (1 - a) * V2, (1 - a) * V1 + a * V2],
axis=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.706; sqrt(1/2) = 0.707
two heads, weights (1.00, 0.00) and (0.00, 1.00): relative error 5.7e-07
two heads, weights (0.88, 0.12) and (0.12, 0.88): relative error 6.2e-07
10.3.3 Multi-Head Attention
10.3.3.1 Projected Heads
Multi-head attention (Vaswani et al. 2017) runs \(H\) independent attention heads in parallel, each with its own query, key, and value projections \(\mathbf{W}_i^{(q)}, \mathbf{W}_i^{(k)}, \mathbf{W}_i^{(v)} \in \mathbb{R}^{d \times d_h}\):
\[ \mathbf{Z}_i = \mathrm{softmax}\left(\frac{(\mathbf{X}\mathbf{W}_i^{(q)})(\mathbf{X}\mathbf{W}_i^{(k)})^\top}{\sqrt{d_h}}\right)\mathbf{X}\mathbf{W}_i^{(v)} \in \mathbb{R}^{n \times d_h}, \qquad i = 1, \ldots, H, \tag{10.3.2}\]
and concatenates their outputs before applying a final linear projection \(\mathbf{W}_o \in \mathbb{R}^{H d_h \times d}\) (Figure 10.3.3):
\[ [\mathbf{Z}_1, \ldots, \mathbf{Z}_H]\, \mathbf{W}_o \in \mathbb{R}^{n \times d}. \tag{10.3.3}\]
10.3.3.2 Parameter and FLOP Counts
Setting the head width to \(d_h = d/H\) keeps the total dimension across all heads equal to \(H d_h = d\). Stacked side by side, the \(H\) query projections form a single \(d \times d\) matrix, as do the key, value, and output projections. Counting one multiply–add as \(2\) FLOPs, a multi-head self-attention layer over \(n\) tokens requires
\[ \underbrace{8nd^2}_{\textrm{projections}} \;+\; \underbrace{4n^2 d}_{\textrm{scores and mixing}} \quad \textrm{FLOPs,} \qquad 4d^2 \ \textrm{parameters.} \tag{10.3.4}\]
For one layer of GPT-2 small (\(d = 768\), \(n = 1{,}024\)), this amounts to \(4.8\) GFLOPs for projections, \(3.2\) GFLOPs for scores and value mixing, and \(2.4 \times 10^6\) parameters. Remarkably, neither the parameter count nor the leading FLOP count depends on the number of heads \(H\): splitting \(d\) into \(H\) heads shrinks each head’s inner product by \(1/H\) while running \(H\) of them (only the \(O(Hn^2)\) softmax overhead scales with \(H\)). Conversely, \(d_h\) cannot be made arbitrarily small: at \(d_h = 1\), scalar scores \(q k_j\) are monotone in \(k_j\), so a query can focus only on the extremal keys (Exercise 1). In practice, \(d_h \in \{64, 128\}\) 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 \(n\) tokens of width \(d\).
| layer type | complexity | sequential operations | maximum path length |
|---|---|---|---|
| convolution (kernel \(k\)) | \(O(knd^2)\) | \(O(1)\) | \(O(n/k)\) |
| recurrence | \(O(nd^2)\) | \(O(n)\) | \(O(n)\) |
| self-attention | \(O(nd^2+n^2d)\) | \(O(1)\) | \(O(1)\) |
Self-attention combines \(O(1)\) sequential steps (full training parallelism) with \(O(1)\) maximum path length between any pair of tokens, eliminating the \(O(n)\)-step recurrent gradient chain (Section 8.5). The price is the quadratic \(4n^2 d\) score-and-mix term, which exceeds the \(8nd^2\) projection cost once \(n > 2d\) (\(n > 1{,}536\) for GPT-2 small).
10.3.3.4 Implementation
In MultiHeadAttention, a single linear layer computes all \(H\) 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 Linear(nnx.Linear):
"""nnx.Linear with weights and biases drawn from U(-a, a), where
a = 1/sqrt(in_features)."""
def __init__(self, in_features, out_features, *, use_bias=True, rngs,
**kwargs):
a = in_features ** -0.5
init = lambda key, shape, dtype=jnp.float32: jax.random.uniform(
key, shape, dtype, -a, a)
super().__init__(in_features, out_features, use_bias=use_bias,
kernel_init=init, bias_init=init, rngs=rngs,
**kwargs)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_weightsclass MultiHeadAttention(nnx.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, *, rngs):
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, rngs=rngs)
self.W_q = Linear(num_hiddens, num_hiddens, use_bias=bias, rngs=rngs)
self.W_k = Linear(num_hiddens, kv_hiddens, use_bias=bias, rngs=rngs)
self.W_v = Linear(num_hiddens, kv_hiddens, use_bias=bias, rngs=rngs)
self.W_o = Linear(num_hiddens, num_hiddens, use_bias=bias, rngs=rngs)
def __call__(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 = jnp.repeat(k, group, axis=1), jnp.repeat(v, group, axis=1)
if mask is not None and mask.ndim == 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_weightsThe two reshape-and-transpose helpers split_heads and merge_heads (Figure 10.3.5) fold the last dimension \(H d_h\) into an explicit head axis (batch, num_heads, length, width) before attention and re-concatenate the \(H\) 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)@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).swapaxes(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.swapaxes(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 \(d = 16\) on the copy-both task (\(d_v = 8\), padded with zeros to width \(16\); keys \(\mathbf{e}_1,
\mathbf{e}_2\) and query \(\mathbf{e}_3\)).
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()def copy_both_data(key, n, d=16, d_v=8):
"""One query, two position-only keys, values of width d_v padded to d."""
V = jax.random.normal(key, (n, 2, d_v))
keys = jnp.broadcast_to(jnp.eye(d)[:2], (n, 2, d)) # e_1, e_2: positions
query = jnp.broadcast_to(jnp.eye(d)[2], (n, 1, d)) # e_3 asks for both
values = jnp.pad(V, ((0, 0), (0, 0), (0, d - d_v)))
return query, keys, values, V.reshape(n, 1, 2 * d_v)
@nnx.jit
def copy_both_step(model, optimizer, key):
query, keys, values, target = copy_both_data(key, 256)
loss = lambda model: ((model(query, keys, values) - target) ** 2).mean()
optimizer.update(model, nnx.grad(loss)(model))
def train_copy_both(num_heads, num_kv_heads=None, num_steps=2000):
model = MultiHeadAttention(16, num_heads, num_kv_heads=num_kv_heads,
rngs=nnx.Rngs(d2l.get_key()))
optimizer = nnx.Optimizer(model, optax.adam(1e-2), wrt=nnx.Param)
# Full fp32 products: TF32, the default on recent NVIDIA cards, would
# stop the error of a solved task near 1e-3 instead of fp32 rounding
with jax.default_matmul_precision('highest'):
for key in jax.random.split(d2l.get_key(), num_steps):
copy_both_step(model, optimizer, key)
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(d2l.get_key(), n)
with jax.default_matmul_precision('highest'):
Y = model(query, keys, values)
err = jnp.linalg.norm(Y - target) / jnp.linalg.norm(target)
return float(err), model.attention_weights[0, :, 0, 0].tolist()Training two seeds at each head count \(H \in \{1, 2, 4\}\) (all sharing the same total width \(d = 16\) and parameter count \(1{,}024\)) compares their relative reconstruction error and the attention weight \(\alpha_1\) that each head places on the first value vector \(\mathbf{v}_1\):
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
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.41
1 2 1024 0.71 0.54
2 1 1024 1.2e-07 0.96 0.08
2 2 1024 1.1e-07 0.02 0.82
4 1 1024 1.9e-07 0.00 0.98 0.23 0.54
4 2 1024 1.2e-07 0.98 0.14 0.05 0.74
All configurations have \(4 \times 16^2 = 1{,}024\) parameters. As predicted by our proposition, \(H = 1\) stalls at the \(\sqrt{1/2} \approx 0.71\) bound, whereas \(H \in \{2, 4\}\) learns distinct head weightings and reduces the error to \(\sim 10^{-7}\).
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 \(H / H_\textrm{kv}\) by sharing each key–value head across a group of \(H / H_\textrm{kv}\) query heads; setting \(H_\textrm{kv} = 1\) gives multi-query attention (MQA) (Shazeer 2019).
On the copy-both task, the shared value heads span at most \(H_\textrm{kv} d_h\) coordinates per value, so recovering a \(d_v\)-dimensional value requires \(H_\textrm{kv} d_h \ge d_v\) (Exercise 6). With \(d = 16\) and \(d_v = 8\), layouts \((H, H_\textrm{kv}) = (2, 1)\) and \((4, 2)\) have \(H_\textrm{kv} d_h = 8\) and solve the task to fp32 precision, whereas \((4, 1)\) has \(H_\textrm{kv} d_h = 4\) and returns to the \(0.71\) 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
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.0e-07 0.94 0.02
2 1 2 768 1.1e-07 0.99 0.09
4 2 1 768 1.2e-07 0.96 0.11 0.85 0.02
4 2 2 768 1.1e-07 0.18 0.98 0.04 0.91
4 1 1 640 0.71 0.11 0.94 0.05 0.96
4 1 2 640 0.71 0.91 0.03 0.94 0.07
10.3.4 Cross-Attention
While self-attention passes the same sequence \(\mathbf{X}\) as queries, keys, and values (attention(X, X, X)), cross-attention draws queries from a target sequence \(\mathbf{A}\) and keys and values from a source sequence \(\mathbf{B}\) (attention(A, B, B)), producing one output row per token of \(\mathbf{A}\). 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 \(O(1)\) sequential steps and \(O(1)\) path length at \(O(nd^2 + n^2d)\) 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 \(1/2\) when tasked with retrieving two independent values simultaneously. Multi-head attention overcomes this bottleneck by running \(H\) subspace heads of width \(d_h = d/H\) in parallel and combining their outputs through \(\mathbf{W}_o\), requiring \(4d^2\) parameters and \(8nd^2 + 4n^2d\) FLOPs independent of \(H\). Grouped-query and multi-query attention share \(H_\textrm{kv} < H\) key–value heads across query groups to shrink generation caches by a factor of \(H/H_\textrm{kv}\), preserving retrieval capacity whenever the shared value width \(H_\textrm{kv} d_h\) can accommodate the retrieved features.
10.3.6 Exercises
- [code] Narrow heads. With \(d_h = d/H\), the leading count of Equation 10.3.4 does not depend on \(H\), so the number of heads looks free up to \(H = d\). Consider one head with scores \(\mathbf{q}^\top \mathbf{k}_j / \sqrt{d_h}\) over keys \(\mathbf{k}_1,
\ldots, \mathbf{k}_m \in \mathbb{R}^{d_h}\) and no mask. Call a query sharp on key \(j\) when its weights concentrate on \(\mathbf{k}_j\) as the query is scaled by a factor that grows without bound.
- For \(d_h = 1\) and distinct scalar keys, show that every query’s weights are monotone in \(k_j\). Conclude that the queries of such a head can be sharp only on the largest or the smallest key.
- Show that for \(d_h = 2\) the keys and queries can be chosen so that each of \(n\) 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 \(H\) approaches \(d\).
- Time the forward pass of
MultiHeadAttentionwith dropout 0 for self-attention with \(d = 256\) and \(n = 512\) on a minibatch of \(8\) sequences for \(H \in \{1, 2, 4, 8, 16, 32, 64\}\). 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 \(H\) and that Equation 10.3.4 leaves out, and check that it accounts for the trend.
- [code] Heads as slices.
MultiHeadAttentioncomputes one projection of width \(d\) for each of the queries, keys, and values and splits it into heads withsplit_heads.- Head \(i\) 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 \(i\) owns a slice of the output features of
- Permuting the source. In cross-attention, the queries come from \(\mathbf{A} \in \mathbb{R}^{n \times d}\) and the keys and values from \(\mathbf{B} \in \mathbb{R}^{m \times d}\), neither carrying positional information. Let \(\boldsymbol{\Pi}\) be an \(m \times m\) permutation matrix.
- Show that replacing \(\mathbf{B}\) by \(\boldsymbol{\Pi}\mathbf{B}\) 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 \(\ell\) rows of \(\mathbf{B}\) as valid. Which permutations leave the output unchanged when the mask stays fixed?
- Show that replacing \(\mathbf{B}\) by \(\boldsymbol{\Pi}\mathbf{B}\) in both the key and the value argument leaves the output of
- [code] Nearly identical heads. ● Two heads with weights \((0.5 + \epsilon, 0.5 - \epsilon)\) and \((0.5 - \epsilon, 0.5 +
\epsilon)\) supply two distinct mixtures, so the linear readout inverts them exactly for every \(\epsilon > 0\).
- Write the \(2 \times 2\) mixing matrix, compute its eigenvalues and eigenvectors, and express its condition number as a function of \(\epsilon\).
- Add independent Gaussian noise of standard deviation \(\sigma = 0.01\) to both mixtures and measure the error with
readout_errorfor \(\epsilon \in \{0.4, 0.1, 0.03, 0.01, 0.003, 0.001\}\). Plot the error against \(\epsilon\) 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 \((0.5, 0.5)\). Modify
train_copy_bothto record the relative error and the weights of each head every 20 steps, and plot both for \(H = 2\). Use the conditioning of the mixing matrix to explain the shape of the error curve in the first few hundred steps. Repeat for \(H = 8\) 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 \(\mathbf{m} \in \mathbb{R}^{d_v}\) and must produce the target \(\mathbf{t} \in \mathbb{R}^{2d_v}\).
- Let \(\mathbf{m} \in \mathbb{R}^{d_v}\) be any function of \(\mathbf{v}_1\) and \(\mathbf{v}_2\), including a mixture whose weights depend on the values, and let \(\mathbf{W}_o \in \mathbb{R}^{d_v \times 2d_v}\) be any matrix. Show that \[\mathbb{E}\,\|\mathbf{m}\mathbf{W}_o - \mathbf{t}\|^2 \geq \tfrac{1}{2}\, \mathbb{E}\,\|\mathbf{t}\|^2.\] 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 \(d_v\) numbers.
- A layer of width \(d\) with two heads of width \(d_h = d/2\) receives the values \(\mathbf{v}_1, \mathbf{v}_2 \in \mathbb{R}^{d/2}\) padded with zeros to width \(d\). Give the attention weights of each head, value projections \(\mathbf{W}_i^{(v)}\), and an output projection \(\mathbf{W}_o\) that solve the task exactly. Compare your weights with those printed in Section 10.3.3.5.
- Generalize the proposition to \(k\) source positions with independent standard Gaussian values \(\mathbf{v}_1, \ldots, \mathbf{v}_k \in \mathbb{R}^{d_v}\) and the target \([\mathbf{v}_1; \ldots; \mathbf{v}_k]\). Each of \(H\) heads applies fixed weights to the values, the weights of head \(i\) form row \(i\) of a matrix \(\mathbf{A} \in \mathbb{R}^{H \times k}\), and a linear readout sees all \(H\) mixtures. Show that the best relative squared error is \[1 - \frac{\operatorname{rank}(\mathbf{A})}{k}, \tag{10.3.5}\] and that softmax weights, whose entries are all positive, can attain \(\operatorname{rank}(\mathbf{A}) = \min(H, k)\).
- [code] Sharing keys and values on the copy-both task. ● Let a layer of width \(d\) have \(H\) query heads of width \(d_h = d/H\) and \(H_\textrm{kv} < H\) key–value heads.
- Use the counting of Exercise 5 to show that it can solve the task only if \(H_\textrm{kv} d_h \ge d_v\), 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.