翻篇收录说明
翻篇网页快照

10.3 Self-Attention and Multiple Heads – Dive into Deep Learning

https://d2l.ai/chapter_attention/multihead-attention.html

最近抓取:2026-12-04 15:07:14(北京时间)

最近内容变化:2026-12-02 01:01:54(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

正文摘录

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)\) PyTorchJAX 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) 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). Figure 10.3.1: One head of self-attention on “Alice gave Bob the book”, with the hand-set maps of the code above (\(d_h = 2\)). Every token emits a query, a key, and a value. The query of gave, \((1, 1)\), is scored against every key by \(\mathbf{q} \cdot \mathbf{k}/\sqrt{2}\); the softmax turns the scores \(1.41\) and \(0\) into weights \(0.29\) and \(0.07\); the output of gave is the weighted sum of the values, which mark the five words. PyTorchJAX 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.1