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 自注意力与多头注意力
在 10.2 节 的示例中,查询来自一条序列,键与值来自另一条序列。仅解码器语言模型只有一条序列:为了给每个词元注入上下文,查询、键与值都必须从该序列自身派生。
考虑句子“Alice gave Bob the book”。理解 gave 需要识别施事者(Alice)、受事者(Bob)与宾语(book)。在自注意力 (Cheng 等 2016年; Lin 等 2017年; Vaswani 等 2017年) 中,每个词元都将自身表征投影为一个查询、一个键与一个值,使 gave 得以查询句中其余单词并聚合它们的值。
然而,单次注意力查找对每个查询只生成一个概率分布,只返回单个混合向量。一个词元如何在不把多个不同论元塌缩成单一平均的前提下同时检索它们?我们首先在五词例句上追踪单头自注意力,接着证明一个信息论下界,阐明为何单头无法恢复两个独立值,最后构建多头注意力与分组查询注意力(GQA)。
10.3.1 自注意力
在自注意力中,每个词元表征 \(\mathbf{x}_i \in \mathbb{R}^d\)(\(\mathbf{X} \in \mathbb{R}^{n \times d}\) 的第 \(i\) 行)通过学得的线性投影 \(\mathbf{W}_q, \mathbf{W}_k \in \mathbb{R}^{d \times d_h}\) 与 \(\mathbf{W}_v \in \mathbb{R}^{d \times d_v}\) 扮演三种不同角色:查询 \(\mathbf{x}_i\mathbf{W}_q\) 刻画词元寻找什么,键 \(\mathbf{x}_i\mathbf{W}_k\) 刻画它向其他查询提供什么,值 \(\mathbf{x}_i\mathbf{W}_v\) 刻画被选中时返回的内容。施加缩放点积注意力即得宽度为 \(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 单头作用于单句
为了具体追踪 式 10.3.1,将“Alice gave Bob the book”的每个单词表示为 9 维向量,拼接 4 维独热语法角色(人、动作、物或功能词)与 5 维独热词身份。令 \(\mathbf{W}_q\) 与 \(\mathbf{W}_k\) 仅读取 4 维角色并映至 \(d_h = 2\) 维,令 \(\mathbf{W}_v\) 提取 5 维词指示向量:
| 角色 | 查询 | 键 |
|---|---|---|
| 人(Alice、Bob) | \((1, -1)\) | \((1, 1)\) |
| 动作(gave) | \((1, 1)\) | \((1, -1)\) |
| 物(book) | \((1, -1)\) | \((1, 1)\) |
| 功能词(“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)对 gave 而言,查询 \((1, 1)\) 与每个名词的键 \((1, 1)\) 点积为 \(2\),与 gave 和“the”点积为 \(0\)。除以 \(\sqrt{2}\) 后,每个名词得分 \(1.41\),其余得分 \(0\);softmax 将其转化为每个名词 \(e^{1.41}/(3e^{1.41} + 2) \approx 0.29\)、gave 与“the”各 \(0.07\) 的权重(图 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. ]
反之,每个名词的查询 \((1, -1)\) 在 gave 上得分 \(1.41\)(权重 \(0.51\)),其余处得分 \(0\);而“the”的查询为零,均匀关注全部五个词(各 \(0.20\))。施加因果掩码后,gave 被限制在 Alice 与自身,两者的得分 \((1.41, 0)\) 重新规范化为 \((0.80, 0.20)\)。
10.3.1.2 查询与键的独立映射
为何要使用独立的矩阵 \(\mathbf{W}_q\) 与 \(\mathbf{W}_k\)?若单一投影 \(\mathbf{u}_i = \mathbf{x}_i\mathbf{W}\) 同时充当查询与键,得分矩阵 \(s_{ij} = \mathbf{u}_i^\top \mathbf{u}_j / \sqrt{d_h}\) 将是对称半正定的,由柯西–施瓦茨不等式满足 \(s_{ij} \le \sqrt{s_{ii}\, s_{jj}} \le \max(s_{ii}, s_{jj})\)。这将导致两件事不可能成立:由于 \(s_{ij} = s_{ji}\),动词无法比名词寻找动词更强烈地寻找名词;而且两个词元永远无法彼此把对方打分排在自己之上——动词只有在名词范数更大时才能更偏好名词而非自身,而此时名词又会更偏好自身而非动词。独立的查询、键与值投影解耦了谁在看、谁被找到以及传递何种内容。
10.3.2 单头的局限
在五词例句中,gave 把 Alice、Bob 与 book 混合成了单一加权平均。为了量化每个查询仅有一个注意力分布所带来的瓶颈,考虑双复制任务:两个源位置持有独立标准高斯值向量 \(\mathbf{v}_1, \mathbf{v}_2 \in \mathbb{R}^{d_v}\) 以及固定的纯位置键,单个查询必须经由线性读出输出它们的拼接 \(\mathbf{t} = [\mathbf{v}_1; \mathbf{v}_2] \in \mathbb{R}^{2d_v}\)。
由于键仅依赖位置,单头分配固定的 softmax 权重 \((\alpha_1, \alpha_2)\)(\(\alpha_1 + \alpha_2 = 1\)),并向线性读出传入单一混合向量 \(\mathbf{m} = \alpha_1 \mathbf{v}_1 + \alpha_2 \mathbf{v}_2 \in \mathbb{R}^{d_v}\)。
命题:对于单个注意力头、两个固定纯位置键、独立标准高斯值 \(\mathbf{v}_1, \mathbf{v}_2 \in \mathbb{R}^{d_v}\) 以及线性读出,无论 softmax 权重对 \((\alpha_1, \alpha_2)\) 如何取值,双复制任务上可达到的最小相对平方误差均为 \(1/2\)。
证明:给定 \(\mathbf{m} = \alpha_1 \mathbf{v}_1 + \alpha_2 \mathbf{v}_2\),\(\mathbf{v}_1\) 的最小均方误差估计量是条件期望 \(\mathbb{E}[\mathbf{v}_1 \mid \mathbf{m}] = \tfrac{\alpha_1}{\alpha_1^2 + \alpha_2^2}\, \mathbf{m}\),它是 \(\mathbf{m}\) 的线性函数,每个坐标留下的残差方差为 \(1 - \tfrac{\alpha_1^2}{\alpha_1^2 + \alpha_2^2} = \tfrac{\alpha_2^2}{\alpha_1^2 + \alpha_2^2}\)。由对称性,估计 \(\mathbf{v}_2\) 在每个坐标留下的残差方差为 \(\tfrac{\alpha_1^2}{\alpha_1^2 + \alpha_2^2}\)。两者之和在每个坐标上为 \(1\),占目标总方差 \(2\) 的一半,因此无论 \((\alpha_1, \alpha_2)\) 为何,相对平方误差均为 \(1/2\)。\(\blacksquare\)
解决双复制任务需要两个要素:(1) 键上至少两组线性无关的加权分布;(2) 足以容纳全部 \(2d_v\) 个检索坐标的输出维度(空间)(5)。下面验证单头的 \(\sqrt{1/2} \approx 0.707\) 相对均方根误差下界,并展示具有不同权重的双头——哪怕是诸如 \((0.88, 0.12)\) 与 \((0.12, 0.88)\) 的软权重——也能让线性读出将 \(2 \times 2\) 混合矩阵求逆至浮点精度(图 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 多头注意力
10.3.3.1 投影多头
多头注意力 (Vaswani 等 2017年) 并行运行 \(H\) 个独立的注意力头,每个头拥有各自的查询、键与值投影 \(\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}\]
并在施加最终线性投影 \(\mathbf{W}_o \in \mathbb{R}^{H d_h \times d}\) 之前拼接它们的输出(图 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 参数量与浮点运算数
将头宽度设为 \(d_h = d/H\) 可使所有头的总维度保持为 \(H d_h = d\)。并排堆叠起来,\(H\) 个查询投影正好构成单个 \(d \times d\) 矩阵,键、值与输出投影同样如此。将一次乘加计为 \(2\) 次浮点运算,作用于 \(n\) 个词元的多头自注意力层需要
\[ \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}\]
对 GPT-2 small 的单层(\(d = 768\),\(n = 1{,}024\)),投影耗费 \(4.8\) GFLOPs,打分与值混合耗费 \(3.2\) GFLOPs,参数量为 \(2.4 \times 10^6\)。值得注意的是,参数量与主阶浮点运算数均不依赖头数 \(H\):将 \(d\) 拆为 \(H\) 个头使每个头的内积缩小 \(1/H\),同时并行运行 \(H\) 个头(只有 \(O(Hn^2)\) 的 softmax 开销随 \(H\) 增长)。反过来,\(d_h\) 也不能任意小:在 \(d_h = 1\) 时,标量得分 \(q k_j\) 关于 \(k_j\) 单调,查询只能聚焦到极值键上(1)。实践中 \(d_h \in \{64, 128\}\) 是标准配置。
10.3.3.3 与卷积及循环的对比
图 10.3.4 与 表 10.3.1 将一维卷积(第 6 章)、循环(8.4 节)与自注意力作为处理 \(n\) 个宽度为 \(d\) 的词元的序列到序列层进行对比。
| 层类型 | 复杂度 | 顺序操作数 | 最大路径长度 |
|---|---|---|---|
| 卷积(核大小 \(k\)) | \(O(knd^2)\) | \(O(1)\) | \(O(n/k)\) |
| 循环 | \(O(nd^2)\) | \(O(n)\) | \(O(n)\) |
| 自注意力 | \(O(nd^2+n^2d)\) | \(O(1)\) | \(O(1)\) |
自注意力将 \(O(1)\) 顺序步数(完全训练并行)与任意词元对之间 \(O(1)\) 的最大路径长度结合在一起,消除了 \(O(n)\) 步的循环梯度链(8.5 节)。其代价是二次方的 \(4n^2 d\) 打分与混合项,当 \(n > 2d\)(GPT-2 small 上为 \(n > 1{,}536\))时,该项将超过 \(8nd^2\) 的投影开销。
10.3.3.4 实现
在 MultiHeadAttention 中,单个线性层一次性算出全部 \(H\) 个头的投影,split_heads 将 (batch, length, H * d_h) 重塑为 (batch, H, length, d_h),使 DotProductAttention 能在一次批量操作中执行所有头(图 10.3.5)。遵循现代 Transformer 惯例,投影默认不含加性偏置(bias=False)。参数 num_kv_heads 支持键值头共享(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_weights两个重塑与转置辅助函数 split_heads 和 merge_heads(图 10.3.5)在注意力前将末维 \(H d_h\) 折叠进显式头轴 (batch, num_heads, length, width),并在之后重新拼接 \(H\) 个头的输出:
@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 在双复制任务上学习的头
现在我们在双复制任务上测试宽度 \(d = 16\) 的 MultiHeadAttention(\(d_v = 8\),补零至宽度 \(16\);键为 \(\mathbf{e}_1, \mathbf{e}_2\),查询为 \(\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()在每个头数 \(H \in \{1, 2, 4\}\)(均共享相同的总宽度 \(d = 16\) 与参数量 \(1{,}024\))下训练两个种子,比较它们的相对重构误差以及每个头落在第一个值向量 \(\mathbf{v}_1\) 上的注意力权重 \(\alpha_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
所有配置均含 \(4 \times 16^2 = 1{,}024\) 个参数。正如命题所预测,\(H = 1\) 停滞在 \(\sqrt{1/2} \approx 0.71\) 下界,而 \(H \in \{2, 4\}\) 学得不同的头权重,将误差降至 \(\sim 10^{-7}\)。
10.3.3.6 共享键与值
在自回归生成期间,过去的键与值会缓存在显存中,使每个新词元无需重算投影即可关注此前所有位置(11.3 节)。分组查询注意力(GQA)(Ainslie 等 2023年) 让每组 \(H / H_\textrm{kv}\) 个查询头共享一个键值头,将该缓存缩小 \(H / H_\textrm{kv}\) 倍;令 \(H_\textrm{kv} = 1\) 即得多查询注意力(MQA)(Shazeer 2019年)。
在双复制任务上,共享值头对每个值至多张成 \(H_\textrm{kv} d_h\) 个坐标,因此恢复 \(d_v\) 维值需要 \(H_\textrm{kv} d_h \ge d_v\)(6)。在 \(d = 16\)、\(d_v = 8\) 下,布局 \((H, H_\textrm{kv}) = (2, 1)\) 与 \((4, 2)\) 满足 \(H_\textrm{kv} d_h = 8\),可将任务求解至 fp32 精度;而 \((4, 1)\) 的 \(H_\textrm{kv} d_h = 4\),尽管四个查询头学得了不同权重,仍退回到 \(0.71\) 瓶颈:
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 交叉注意力
自注意力将同一序列 \(\mathbf{X}\) 作为查询、键与值传入(attention(X, X, X)),而交叉注意力从目标序列 \(\mathbf{A}\) 取查询、从源序列 \(\mathbf{B}\) 取键与值(attention(A, B, B)),为 \(\mathbf{A}\) 的每个词元产生一行输出。编码器–解码器 Transformer 在翻译时用交叉注意力读取编码后的源句,多模态模型则用它让文本词元查询视觉特征 (Alayrac 等 2022年)。
然而,即便引入多头,自注意力对词序依然视而不见:将“Alice gave Bob the book”中的 Alice 与 Bob 互换,gave 处的输出纹丝不动。注入序列顺序正是 10.4 节 的主题。
10.3.5 小结
自注意力将序列中的每个词元投影为查询、键与值,以 \(O(1)\) 顺序步数、\(O(1)\) 路径长度和 \(O(nd^2 + n^2d)\) 浮点运算连接所有位置对。由于单头对每个查询只形成值的一个凸混合,在同时检索两个独立值的任务上,任何单头的相对平方误差都至少为 \(1/2\)。多头注意力通过并行运行 \(H\) 个宽度 \(d_h = d/H\) 的子空间头并经 \(\mathbf{W}_o\) 组合其输出突破了这一瓶颈,耗费与 \(H\) 无关的 \(4d^2\) 参数与 \(8nd^2 + 4n^2d\) 浮点运算。分组查询注意力与多查询注意力在查询组间共享 \(H_\textrm{kv} < H\) 个键值头,将生成缓存缩小 \(H/H_\textrm{kv}\) 倍,只要共享值宽度 \(H_\textrm{kv} d_h\) 足以容纳待检索特征即可保持检索能力。
10.3.6 练习
- [code] 窄头。当 \(d_h = d/H\) 时,式 10.3.4 中的主阶计数不依赖 \(H\),因此头数似乎可以一直免费增加到 \(H = d\)。考虑单个无掩码头,其在键 \(\mathbf{k}_1, \ldots, \mathbf{k}_m \in \mathbb{R}^{d_h}\) 上的得分为 \(\mathbf{q}^\top \mathbf{k}_j / \sqrt{d_h}\)。若将查询乘以趋于无穷的因子时其权重集中到 \(\mathbf{k}_j\) 上,则称该查询在键 \(j\) 上锐利。
- 对 \(d_h = 1\) 与互异标量键,证明每个查询的权重均关于 \(k_j\) 单调。由此推出,此类头的查询只能在最大或最小的键上锐利。
- 证明当 \(d_h = 2\) 时,总可以选取键与查询,使 \(n\) 个查询中的每一个都各自在任意指定的一个键上锐利(对查询到键的任意指派均成立)。
- 结合这两项结果,说明当 \(H\) 逼近 \(d\) 时,注意力层放弃了哪些注意力模式。
- 在 \(8\) 条序列的小批量上,对暂退率为 0、\(d = 256\)、\(n = 512\) 的
MultiHeadAttention自注意力前向传播就 \(H \in \{1, 2, 4, 8, 16, 32, 64\}\) 计时。先执行一次预热调用,并在停止计时前等待结果就绪。报告最慢与最快配置之比,指出 式 10.3.4 遗漏且随 \(H\) 增长的开销,并检验它是否解释了所测趋势。
- [code] 作为切片的多头。
MultiHeadAttention为查询、键与值各计算一次宽度 \(d\) 的投影,再用split_heads将其切分为多个头。- 头 \(i\) 拥有
W_q、W_k与W_v输出特征的一个切片。确定W_o的哪些输入特征接收该头的输出。编写一个遍历各头、施加切片投影并逐头调用d2l.DotProductAttention的前向传播。在带填充掩码的随机输入上验证其与暂退率为 0 的MultiHeadAttention一致,并将循环扩展至num_kv_heads < num_heads。 - 将
split_heads的函数体替换为X.reshape(X.shape[0], num_heads, X.shape[1], -1),它返回相同形状的张量。描述每个“头”此时存有哪些数,在随机输入上展示输出已改变,并解释为何形状检查抓不到这一错误。若存在,哪些输入长度与宽度会使两个版本一致?
- 头 \(i\) 拥有
- 置换源序列。在交叉注意力中,查询来自 \(\mathbf{A} \in \mathbb{R}^{n \times d}\),键与值来自 \(\mathbf{B} \in \mathbb{R}^{m \times d}\),两者均不含位置信息。设 \(\boldsymbol{\Pi}\) 为 \(m \times m\) 置换矩阵。
- 证明在不施加掩码时,将键与值参数中的 \(\mathbf{B}\) 同时替换为 \(\boldsymbol{\Pi}\mathbf{B}\) 不改变
MultiHeadAttention的输出,而仅替换键参数一般会改变输出。 - 现在设填充掩码仅将 \(\mathbf{B}\) 的前 \(\ell\) 行标为有效。当掩码保持固定时,哪些置换不会改变输出?
- 证明在不施加掩码时,将键与值参数中的 \(\mathbf{B}\) 同时替换为 \(\boldsymbol{\Pi}\mathbf{B}\) 不改变
- [code] 近乎相同的头。● 权重为 \((0.5 + \epsilon, 0.5 - \epsilon)\) 与 \((0.5 - \epsilon, 0.5 + \epsilon)\) 的两个头提供两组不同混合,因此对任意 \(\epsilon > 0\) 线性读出都能精确求逆。
- 写出该 \(2 \times 2\) 混合矩阵,计算其特征值与特征向量,并将其条件数表示为 \(\epsilon\) 的函数。
- 向两个混合向量加入标准差 \(\sigma = 0.01\) 的独立高斯噪声,在 \(\epsilon \in \{0.4, 0.1, 0.03, 0.01, 0.003, 0.001\}\) 上用
readout_error测量误差。在双对数坐标上绘制误差随 \(\epsilon\) 的变化,读出直线段的斜率,并用 (a) 中的条件数加以解释。 - 刚初始化的层中每个头对双复制任务两个位置的权重都接近 \((0.5, 0.5)\)。修改
train_copy_both以每 20 步记录一次相对误差与各头权重,并绘制 \(H = 2\) 的两条曲线。借助混合矩阵的条件数解释前几百步误差曲线的形状。对 \(H = 8\) 重复实验,将最终各头归类为近乎独热、软但互异以及近乎重复另一头三类。
- 下界究竟在数什么。● 10.3.2 节 的命题固定了 softmax 权重,但其误差下界依赖的事实更弱:读出仅接收单个向量 \(\mathbf{m} \in \mathbb{R}^{d_v}\),却要生成目标 \(\mathbf{t} \in \mathbb{R}^{2d_v}\)。
- 设 \(\mathbf{m} \in \mathbb{R}^{d_v}\) 是 \(\mathbf{v}_1\) 与 \(\mathbf{v}_2\) 的任意函数(包括权重依赖值的混合),\(\mathbf{W}_o \in \mathbb{R}^{d_v \times 2d_v}\) 为任意矩阵。证明 \[\mathbb{E}\,\|\mathbf{m}\mathbf{W}_o - \mathbf{t}\|^2 \geq \tfrac{1}{2}\, \mathbb{E}\,\|\mathbf{t}\|^2.\] 由此得出结论:只要读出是线性的且仅接收 \(d_v\) 个数,内容相关的键、更多层或残差连接都无法突破该下界。
- 宽度为 \(d\)、含两个宽度 \(d_h = d/2\) 的头的层接收补零至宽度 \(d\) 的值 \(\mathbf{v}_1, \mathbf{v}_2 \in \mathbb{R}^{d/2}\)。给出能精确求解该任务的各头注意力权重、值投影 \(\mathbf{W}_i^{(v)}\) 与输出投影 \(\mathbf{W}_o\),并将你的权重与 10.3.3.5 节 中打印的结果对比。
- 将该命题推广到 \(k\) 个源位置,持独立标准高斯值 \(\mathbf{v}_1, \ldots, \mathbf{v}_k \in \mathbb{R}^{d_v}\),目标为 \([\mathbf{v}_1; \ldots; \mathbf{v}_k]\)。\(H\) 个头各自对值施加固定权重,头 \(i\) 的权重构成矩阵 \(\mathbf{A} \in \mathbb{R}^{H \times k}\) 的第 \(i\) 行,线性读出接收全部 \(H\) 个混合向量。证明最优相对平方误差为 \[1 - \frac{\operatorname{rank}(\mathbf{A})}{k}, \tag{10.3.5}\] 且元素全正的 softmax 权重能够达到 \(\operatorname{rank}(\mathbf{A}) = \min(H, k)\)。
- [code] 双复制任务上的键值共享。● 设宽度为 \(d\) 的层有 \(H\) 个宽度 \(d_h = d/H\) 的查询头与 \(H_\textrm{kv} < H\) 个键值头。
- 利用 5 中的计数论证证明:该层能求解任务当且仅当 \(H_\textrm{kv} d_h \ge d_v\),且该条件充分。
- 用
train_copy_both(2, 1)训练一个两个查询头共享单个键值头的层。找出两个头之间不同与共享的参数,并结合双复制任务解释为何差异必然出现在你找到的位置。