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 xi∈Rd\mathbf{x}_i \in \mathbb{R}^d (row ii of X∈Rn×d\mathbf{X} \in \mathbb{R}^{n \times d}) plays three distinct roles via learned linear projections Wq,Wk∈Rd×dh\mathbf{W}_q, \mathbf{W}_k \in \mathbb{R}^{d \times d_h} and Wv∈Rd×dv\mathbf{W}_v \in \mathbb{R}^{d \times d_v}: the query xiWq\mathbf{x}_i\mathbf{W}_q specifies what the token seeks, the key xiWk\mathbf{x}_i\mathbf{W}_k specifies what it offers to other queries, and the value xiWv\mathbf{x}_i\mathbf{W}_v specifies the content returned when selected. Applying scaled dot-product attention yields one attention head of width dhd_h:

softmax((XWq)(XWk)⊤dh)XWv∈Rn×dv.(10.3.1)\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 (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 Wq\mathbf{W}_q and Wk\mathbf{W}_k to read only the 4D role into dh=2d_h = 2 dimensions, and Wv\mathbf{W}_v to extract the 5D word indicator:

rolequerykey
person (Alice, Bob)(1,−1)(1, -1)(1,1)(1, 1)
action (gave)(1,1)(1, 1)(1,−1)(1, -1)
thing (book)(1,−1)(1, -1)(1,1)(1, 1)
function word ("the")(0,0)(0, 0)(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)(1, 1) has dot product 22 with each noun's key (1,1)(1, 1) and 00 with gave and "the". Dividing by 2\sqrt{2} gives scaled scores 1.411.41 on each noun and 00 elsewhere, which softmax converts into weights e1.41/(3e1.41+2)≈0.29e^{1.41}/(3e^{1.41} + 2) \approx 0.29 per noun and 0.070.07 on gave and "the" (Figure 10.3.1).

Figure 10.3.1:

One head of self-attention on "Alice gave Bob the book", with the hand-set maps of the code above (dh=2d_h = 2). Every token emits a query, a key, and a value. The query of gave, (1,1)(1, 1), is scored against every key by q⋅k/2\mathbf{q} \cdot \mathbf{k}/\sqrt{2}; the softmax turns the scores 1.411.41 and 00 into weights 0.290.29 and 0.070.07; 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 (1,−1)(1, -1) scores 1.411.41 on gave (weight 0.510.51) and 00 elsewhere, while "the" has a zero query and attends uniformly (0.200.20 across all five words). Applying a causal mask restricts gave to Alice and itself, renormalizing their scores (1.41,0)(1.41, 0) to (0.80,0.20)(0.80, 0.20).

10.3.1.2 Separate Maps for Queries and Keys#

Why use separate matrices Wq\mathbf{W}_q and Wk\mathbf{W}_k? If a single projection ui=xiW\mathbf{u}_i = \mathbf{x}_i\mathbf{W} served as both query and key, the score matrix sij=ui⊤uj/dhs_{ij} = \mathbf{u}_i^\top \mathbf{u}_j / \sqrt{d_h} would be symmetric and positive semidefinite, satisfying sij≤sii sjj≤max⁡(sii,sjj)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 sij=sjis_{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 v1,v2∈Rdv\mathbf{v}_1, \mathbf{v}_2 \in \mathbb{R}^{d_v} with fixed position-only keys, and a single query must output their concatenation t=[v1;v2]∈R2dv\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 (α1,α2)(\alpha_1, \alpha_2) with α1+α2=1\alpha_1 + \alpha_2 = 1 and passes a single mixture m=α1v1+α2v2∈Rdv\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 v1,v2∈Rdv\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/21/2 for every softmax pair (α1,α2)(\alpha_1, \alpha_2).

Proof. Given m=α1v1+α2v2\mathbf{m} = \alpha_1 \mathbf{v}_1 + \alpha_2 \mathbf{v}_2, the minimum mean-squared error estimator of v1\mathbf{v}_1 is the conditional expectation E[v1∣m]=α1α12+α22 m\mathbb{E}[\mathbf{v}_1 \mid \mathbf{m}] = \tfrac{\alpha_1}{\alpha_1^2 + \alpha_2^2}\, \mathbf{m}, which is linear in m\mathbf{m} and leaves residual variance 1−α12α12+α22=α22α12+α221 - \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 v2\mathbf{v}_2 leaves residual variance α12α12+α22\tfrac{\alpha_1^2}{\alpha_1^2 + \alpha_2^2} per coordinate. Their sum is 11 per coordinate out of a total target variance of 22 per coordinate, giving a relative squared error of 1/21/2 regardless of (α1,α2)(\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 2dv2d_v retrieved coordinates (Exercise 5). We verify the 1/2≈0.707\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)(0.88, 0.12) and (0.12,0.88)(0.12, 0.88)—allow a linear readout to invert the 2×22 \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
Figure 10.3.2:

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 HH independent attention heads in parallel, each with its own query, key, and value projections Wi(q),Wi(k),Wi(v)∈Rd×dh\mathbf{W}_i^{(q)}, \mathbf{W}_i^{(k)}, \mathbf{W}_i^{(v)} \in \mathbb{R}^{d \times d_h}:

Zi=softmax((XWi(q))(XWi(k))⊤dh)XWi(v)∈Rn×dh,i=1,…,H,(10.3.2)\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 Wo∈RHdh×d\mathbf{W}_o \in \mathbb{R}^{H d_h \times d} (Figure 10.3.3):

[Z1,…,ZH] Wo∈Rn×d.(10.3.3)[\mathbf{Z}_1, \ldots, \mathbf{Z}_H]\, \mathbf{W}_o \in \mathbb{R}^{n \times d}. \tag{10.3.3}
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 dh=d/Hd_h = d/H keeps the total dimension across all heads equal to Hdh=dH d_h = d. Stacked side by side, the HH query projections form a single d×dd \times d matrix, as do the key, value, and output projections. Counting one multiply--add as 22 FLOPs, a multi-head self-attention layer over nn tokens requires

8nd2⏟projections  +  4n2d⏟scores and mixingFLOPs,4d2 parameters.(10.3.4)\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=768d = 768, n=1,024n = 1{,}024), this amounts to 4.84.8 GFLOPs for projections, 3.23.2 GFLOPs for scores and value mixing, and 2.4×1062.4 \times 10^6 parameters. Remarkably, neither the parameter count nor the leading FLOP count depends on the number of heads HH: splitting dd into HH heads shrinks each head's inner product by 1/H1/H while running HH of them (only the O(Hn2)O(Hn^2) softmax overhead scales with HH). Conversely, dhd_h cannot be made arbitrarily small: at dh=1d_h = 1, scalar scores qkjq k_j are monotone in kjk_j, so a query can focus only on the extremal keys (Exercise 1). In practice, dh∈{64,128}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 nn tokens of width dd.

Figure 10.3.4:

Sequence-layer connectivity for five tokens. Highlighted edges show how the inputs reach the third output in one layer: a convolution with kernel size k=3k = 3 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.

Table 10.3.1. Per-layer cost of mapping nn tokens of dimension dd to nn tokens of dimension dd.
layer typecomplexitysequential operationsmaximum path length
convolution (kernel kk)O(knd2)O(knd^2)O(1)O(1)O(n/k)O(n/k)
recurrenceO(nd2)O(nd^2)O(n)O(n)O(n)O(n)
self-attentionO(nd2+n2d)O(nd^2+n^2d)O(1)O(1)O(1)O(1)

Self-attention combines O(1)O(1) sequential steps (full training parallelism) with O(1)O(1) maximum path length between any pair of tokens, eliminating the O(n)O(n)-step recurrent gradient chain (Section 8.5). The price is the quadratic 4n2d4n^2 d score-and-mix term, which exceeds the 8nd28nd^2 projection cost once n>2dn > 2d (n>1,536n > 1{,}536 for GPT-2 small).

10.3.3.4 Implementation#

In MultiHeadAttention, a single linear layer computes all HH 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_weights
Figure 10.3.5:

Heads as slices of one projection. The projected queries of nn tokens are cut into HH column slices of width dh=d/Hd_h = d/H, 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 Wo\mathbf{W}_o. 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 HdhH d_h into an explicit head axis (batch, num_heads, length, width) before attention and re-concatenate the HH 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 d=16d = 16 on the copy-both task (dv=8d_v = 8, padded with zeros to width 1616; keys e1,e2\mathbf{e}_1, \mathbf{e}_2 and query e3\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()

Training two seeds at each head count H∈{1,2,4}H \in \{1, 2, 4\} (all sharing the same total width d=16d = 16 and parameter count 1,0241{,}024) compares their relative reconstruction error and the attention weight α1\alpha_1 that each head places on the first value vector v1\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

All configurations have 4×162=1,0244 \times 16^2 = 1{,}024 parameters. As predicted by our proposition, H=1H = 1 stalls at the 1/2≈0.71\sqrt{1/2} \approx 0.71 bound, whereas H∈{2,4}H \in \{2, 4\} learns distinct head weightings and reduces the error to ∼10−7\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/HkvH / H_\textrm{kv} by sharing each key--value head across a group of H/HkvH / H_\textrm{kv} query heads; setting Hkv=1H_\textrm{kv} = 1 gives multi-query attention (MQA) (Shazeer, 2019).

On the copy-both task, the shared value heads span at most HkvdhH_\textrm{kv} d_h coordinates per value, so recovering a dvd_v-dimensional value requires Hkvdh≥dvH_\textrm{kv} d_h \ge d_v (Exercise 6). With d=16d = 16 and dv=8d_v = 8, layouts (H,Hkv)=(2,1)(H, H_\textrm{kv}) = (2, 1) and (4,2)(4, 2) have Hkvdh=8H_\textrm{kv} d_h = 8 and solve the task to fp32 precision, whereas (4,1)(4, 1) has Hkvdh=4H_\textrm{kv} d_h = 4 and returns to the 0.710.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

10.3.4 Cross-Attention#

While self-attention passes the same sequence X\mathbf{X} as queries, keys, and values (attention(X, X, X)), cross-attention draws queries from a target sequence A\mathbf{A} and keys and values from a source sequence B\mathbf{B} (attention(A, B, B)), producing one output row per token of A\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)O(1) sequential steps and O(1)O(1) path length at O(nd2+n2d)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/21/2 when tasked with retrieving two independent values simultaneously. Multi-head attention overcomes this bottleneck by running HH subspace heads of width dh=d/Hd_h = d/H in parallel and combining their outputs through Wo\mathbf{W}_o, requiring 4d24d^2 parameters and 8nd2+4n2d8nd^2 + 4n^2d FLOPs independent of HH. Grouped-query and multi-query attention share Hkv<HH_\textrm{kv} \lt H key–value heads across query groups to shrink generation caches by a factor of H/HkvH/H_\textrm{kv}, preserving retrieval capacity whenever the shared value width HkvdhH_\textrm{kv} d_h can accommodate the retrieved features.

10.3.6 Exercises#

  1. [code] Narrow heads. With dh=d/Hd_h = d/H, the leading count of (10.3.4) does not depend on HH, so the number of heads looks free up to H=dH = d. Consider one head with scores q⊤kj/dh\mathbf{q}^\top \mathbf{k}_j / \sqrt{d_h} over keys k1,…,km∈Rdh\mathbf{k}_1, \ldots, \mathbf{k}_m \in \mathbb{R}^{d_h} and no mask. Call a query sharp on key jj when its weights concentrate on kj\mathbf{k}_j as the query is scaled by a factor that grows without bound.

    1. For dh=1d_h = 1 and distinct scalar keys, show that every query's weights are monotone in kjk_j. Conclude that the queries of such a head can be sharp only on the largest or the smallest key.
    2. Show that for dh=2d_h = 2 the keys and queries can be chosen so that each of nn queries is sharp on a key of its own choosing, for every assignment of queries to keys.
    3. Use these two results to state which attention patterns a layer gives up as HH approaches dd.
    4. Time the forward pass of MultiHeadAttention with dropout 0 for self-attention with d=256d = 256 and n=512n = 512 on a minibatch of 88 sequences for H∈{1,2,4,8,16,32,64}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 HH and that (10.3.4) leaves out, and check that it accounts for the trend.
  2. [code] Heads as slices. MultiHeadAttention computes one projection of width dd for each of the queries, keys, and values and splits it into heads with split_heads.

    1. Head ii owns a slice of the output features of W_q, W_k, and W_v. Determine which input features of W_o receive that head's output. Write a forward pass that loops over the heads, applies the sliced projections, and calls d2l.DotProductAttention once per head. Verify on random inputs with a padding mask that it matches MultiHeadAttention with dropout 0, and extend your loop to num_kv_heads < num_heads.
    2. Replace the body of split_heads by X.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?
  3. Permuting the source. In cross-attention, the queries come from A∈Rn×d\mathbf{A} \in \mathbb{R}^{n \times d} and the keys and values from B∈Rm×d\mathbf{B} \in \mathbb{R}^{m \times d}, neither carrying positional information. Let Π\boldsymbol{\Pi} be an m×mm \times m permutation matrix.

    1. Show that replacing B\mathbf{B} by ΠB\boldsymbol{\Pi}\mathbf{B} in both the key and the value argument leaves the output of MultiHeadAttention unchanged when no mask is applied, and that replacing it in the key argument alone changes the output in general.
    2. Now let a padding mask mark only the first ℓ\ell rows of B\mathbf{B} as valid. Which permutations leave the output unchanged when the mask stays fixed?
  4. [code] Nearly identical heads. ● Two heads with weights (0.5+ϵ,0.5−ϵ)(0.5 + \epsilon, 0.5 - \epsilon) and (0.5−ϵ,0.5+ϵ)(0.5 - \epsilon, 0.5 + \epsilon) supply two distinct mixtures, so the linear readout inverts them exactly for every ϵ>0\epsilon > 0.

    1. Write the 2×22 \times 2 mixing matrix, compute its eigenvalues and eigenvectors, and express its condition number as a function of ϵ\epsilon.
    2. Add independent Gaussian noise of standard deviation σ=0.01\sigma = 0.01 to both mixtures and measure the error with readout_error for ϵ∈{0.4,0.1,0.03,0.01,0.003,0.001}\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).
    3. Every head of a freshly initialized layer weights the two positions of the copy-both task close to (0.5,0.5)(0.5, 0.5). Modify train_copy_both to record the relative error and the weights of each head every 20 steps, and plot both for H=2H = 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=8H = 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.
  5. 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 m∈Rdv\mathbf{m} \in \mathbb{R}^{d_v} and must produce the target t∈R2dv\mathbf{t} \in \mathbb{R}^{2d_v}.

    1. Let m∈Rdv\mathbf{m} \in \mathbb{R}^{d_v} be any function of v1\mathbf{v}_1 and v2\mathbf{v}_2, including a mixture whose weights depend on the values, and let Wo∈Rdv×2dv\mathbf{W}_o \in \mathbb{R}^{d_v \times 2d_v} be any matrix. Show that
E ∥mWo−t∥2≥12 E ∥t∥2.\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 dvd_v numbers.

  1. A layer of width dd with two heads of width dh=d/2d_h = d/2 receives the values v1,v2∈Rd/2\mathbf{v}_1, \mathbf{v}_2 \in \mathbb{R}^{d/2} padded with zeros to width dd. Give the attention weights of each head, value projections Wi(v)\mathbf{W}_i^{(v)}, and an output projection Wo\mathbf{W}_o that solve the task exactly. Compare your weights with those printed in Section 10.3.3.5.
  2. Generalize the proposition to kk source positions with independent standard Gaussian values v1,…,vk∈Rdv\mathbf{v}_1, \ldots, \mathbf{v}_k \in \mathbb{R}^{d_v} and the target [v1;…;vk][\mathbf{v}_1; \ldots; \mathbf{v}_k]. Each of HH heads applies fixed weights to the values, the weights of head ii form row ii of a matrix A∈RH×k\mathbf{A} \in \mathbb{R}^{H \times k}, and a linear readout sees all HH mixtures. Show that the best relative squared error is
1−rank⁡(A)k,(10.3.5)1 - \frac{\operatorname{rank}(\mathbf{A})}{k}, \tag{10.3.5}

and that softmax weights, whose entries are all positive, can attain rank⁡(A)=min⁡(H,k)\operatorname{rank}(\mathbf{A}) = \min(H, k).

  1. [code] Sharing keys and values on the copy-both task. ● Let a layer of width dd have HH query heads of width dh=d/Hd_h = d/H and Hkv<HH_\textrm{kv} \lt H key--value heads.
    1. Use the counting of Exercise 5 to show that it can solve the task only if Hkvdh≥dvH_\textrm{kv} d_h \ge d_v, and that this condition suffices.
    2. 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.

Discussions