10.2  注意力打分与掩码

在 10.1.2 节 中,注意力权重由输入空间欧氏距离上的固定高斯核决定。然而在序列模型中,相似度必须靠学习获得——寻找主语的动词需要的是扮演该句法角色的词,而非原始嵌入最接近的词。将软查找转化为可训练网络层会引出两个问题:该层应计算何种打分函数 \(a(\mathbf{q}, \mathbf{k})\),以及哪些查询–键对应当被排除在查找之外?

由于读取 \(n = 1{,}024\) 个词元的单个头每条序列就要评估 \(n^2 = 1{,}048{,}576\) 个查询–键对,打分必须开销低廉,并能干净地映射到矩阵乘法硬件上。此外,无效对——例如变长小批量中的填充词元,或自回归语言模型中的未来词元——必须在规范化前置零。

本节推导缩放点积注意力(\(\mathbf{q}^\top\mathbf{k}/\sqrt{d}\)),阐明 \(1/\sqrt{d}\) 因子如何在初始化时防止 softmax 饱和,实现布尔掩码与掩码组合,并展示可学习注意力如何仅凭输出监督恢复序列对齐。

10.2.1 点积注意力

展开 10.1.2 节 中单位带宽高斯核的负平方距离,会得到一个内积项加上两个平方范数项:

\[ a(\mathbf{q}, \mathbf{k}_i) = -\frac{1}{2} \|\mathbf{q} - \mathbf{k}_i\|^2 = \mathbf{q}^\top \mathbf{k}_i -\frac{1}{2} \|\mathbf{k}_i\|^2 -\frac{1}{2} \|\mathbf{q}\|^2. \tag{10.2.1}\]

由于 \(-\tfrac{1}{2}\|\mathbf{q}\|^2\) 对所有键 \(i\) 都相同,softmax 规范化会将其消去。若所有键的范数相等,\(-\tfrac{1}{2}\|\mathbf{k}_i\|^2\) 同样相消。即便键范数各不相同,仍舍去两个范数项便得到点积得分 \(\mathbf{q}^\top \mathbf{k}_i\)。与惩罚大 \(\|\mathbf{k}_i\|\) 的高斯核不同,点积允许键的范数充当乘法先验:更长的键会从每个与其对齐的查询那里吸引更大的权重(1c)。

早期的神经机器翻译模型转而采用单隐藏层多层感知机,称为加性注意力 (Bahdanau 等 2015年):

\[a(\mathbf{q}, \mathbf{k}) = \mathbf{w}_v^\top \tanh(\mathbf{W}_q \mathbf{q} + \mathbf{W}_k \mathbf{k}) \in \mathbb{R}, \tag{10.2.2}\]

其中 \(\mathbf{W}_q \in \mathbb{R}^{r \times d_q}\)、\(\mathbf{W}_k \in \mathbb{R}^{r \times d_k}\) 为学得的矩阵,\(\mathbf{w}_v \in \mathbb{R}^{r}\) 为权重向量。尽管加性打分与点积打分的渐近运算量相近(对 \(n\) 个查询与 \(m\) 个键分别为 \(O(nmr)\) 对比 \(O(nmd)\)),但加性注意力必须物化一个 \(n \times m \times r\) 的隐藏激活张量并逐元素施加 \(\tanh\)。点积注意力则用单次矩阵乘法 \(\mathbf{Q}\mathbf{K}^\top\) 即可算出全部 \(n \times m\) 个得分。双线性得分的表达形式不如多层感知机一般,但当查询与键本身由学得的投影 \((\mathbf{W}_q \mathbf{q})^\top (\mathbf{W}_k \mathbf{k})\) 生成时,这一差别在实践中并无实质影响(另见 6)。

还剩一个关键的缩放因子。设 \(\mathbf{q}, \mathbf{k} \in \mathbb{R}^d\) 的各坐标为均值 \(0\)、方差 \(1\) 的独立随机变量,则每一项 \(q_j k_j\) 的均值为 \(0\)、方差为 \(1\),于是总和 \(\mathbf{q}^\top \mathbf{k}\) 的均值为 \(0\)、方差为 \(d\)(\(d = 64\) 时标准差为 \(8\))。为了防止大维度 \(d\) 下的巨大点积把 softmax 推入梯度消失区间,Vaswani 等 (2017年) 将其除以 \(\sqrt{d}\) 以恢复单位方差,得到缩放点积得分:

\[a(\mathbf{q}, \mathbf{k}_i) = \mathbf{q}^\top \mathbf{k}_i / \sqrt{d}. \tag{10.2.3}\]

这里的 \(1/\sqrt{d}\) 扮演了 10.1.2 节 中逆温度 \(1/\sigma^2\) 的角色,并随向量宽度 \(d\) 自动校准。随后经 softmax 规范化得到注意力权重

\[\alpha(\mathbf{q}, \mathbf{k}_i) = \mathrm{softmax}(a(\mathbf{q}, \mathbf{k}_i)) = \frac{\exp(\mathbf{q}^\top \mathbf{k}_i / \sqrt{d})}{\sum_{j=1}^m \exp(\mathbf{q}^\top \mathbf{k}_j / \sqrt{d})}, \tag{10.2.4}\]

以及输出 \(\sum_{i=1}^m \alpha(\mathbf{q}, \mathbf{k}_i)\, \mathbf{v}_i\)。

10.2.1.1 实例演算

设 \(d = 4\)(从而 \(1/\sqrt{d} = 1/2\)),包含两个查询与三个键值对:

\[ \begin{aligned} \mathbf{q}_1 &= (2, 2, 0, 0), & \mathbf{k}_1 &= (1, 1, 0, 0), & \mathbf{v}_1 &= (1, 0),\\ \mathbf{q}_2 &= (0, 0, 2, 0), & \mathbf{k}_2 &= (0, 0, 1, 1), & \mathbf{v}_2 &= (0, 1),\\ & & \mathbf{k}_3 &= (0, 0, 1, -1), & \mathbf{v}_3 &= (1, 1). \end{aligned} \]

  1. 得分:\(\mathbf{q}_1\) 与三个键的原始点积为 \((4, 0, 0)\);\(\mathbf{q}_2\) 为 \((0, 2, 2)\)。
  2. 缩放:除以 \(\sqrt{4} = 2\) 得到 \((2, 0, 0)\) 与 \((0, 1, 1)\)。
  3. Softmax:\(\mathbf{q}_1\) 分配权重 \(\big(e^2/(e^2 + 2),\, 1/(e^2 + 2),\, 1/(e^2 + 2)\big) \approx (0.787, 0.107, 0.107)\);\(\mathbf{q}_2\) 分配权重 \(\big(1/(1 + 2e),\, e/(1 + 2e),\, e/(1 + 2e)\big) \approx (0.155, 0.422, 0.422)\)。
  4. 加权和:\(\mathbf{o}_1 = 0.787\,\mathbf{v}_1 + 0.107\,\mathbf{v}_2 + 0.107\,\mathbf{v}_3 \approx (0.893, 0.213)\),\(\mathbf{o}_2 \approx (0.578, 0.845)\)。

即便是正交键也会分得非零的 softmax 权重(\(0.107\)),而在查询活跃坐标上打平的键(\(\mathbf{q}_2\) 下的 \(\mathbf{k}_2\) 与 \(\mathbf{k}_3\))则平分剩余权重。若省略 \(1/2\) 缩放因子,\(\mathbf{q}_1\) 落在 \(\mathbf{k}_1\) 上的权重会从 \(0.787\) 锐化至 \(e^4/(e^4 + 2) \approx 0.96\)。

10.2.1.2 得分方差与 \(1/\sqrt{d}\) 因子

当某一个得分大幅领先其余所有得分时,权重向量 \(\boldsymbol{\alpha}\) 逼近独热向量,softmax 发生饱和。\(\boldsymbol{\alpha} = \mathrm{softmax}(\mathbf{a})\) 的雅可比矩阵

\[ \frac{\partial \boldsymbol{\alpha}}{\partial \mathbf{a}} = \mathrm{diag}(\boldsymbol{\alpha}) - \boldsymbol{\alpha} \boldsymbol{\alpha}^\top, \tag{10.2.5}\]

在 \(\boldsymbol{\alpha}\) 趋近独热时收敛至零矩阵(2)。在饱和行中,反向传播到得分的梯度趋于消失,使未被选中的键在训练中难以重新获得权重。

我们可以在标准正态随机查询(\(2{,}048\) 个查询,各自关注 \(64\) 个随机键)上跨维度 \(d \in \{4, \ldots, 512\}\) 度量这一效应,比较未缩放得分与按 \(1/\sqrt{d}\) 缩放的得分。\(64\) 个键上的均匀权重熵为 \(\log 64 \approx 4.16\) 奈特,而独热分布的熵为 \(0\)。

def softmax_weights(d, scale, num_keys=64, num_queries=2048):
    """Log-weights of random queries over random keys, scores scaled."""
    q = torch.randn(num_queries, d)
    keys = torch.randn(num_queries, num_keys, d)
    scores = (keys @ q[..., None]).squeeze(-1) * scale
    return F.log_softmax(scores, dim=-1)

def entropy(log_alpha):
    return -(log_alpha.exp() * log_alpha).sum(-1).mean().item()

def largest_weight(log_alpha):
    return log_alpha.exp().max(-1).values.mean().item()

def jacobian_norm(log_alpha):
    """Mean Frobenius norm of the Jacobian diag(alpha) - alpha alpha^T."""
    alpha = log_alpha.exp()
    J = torch.diag_embed(alpha) - alpha[..., :, None] * alpha[..., None, :]
    return torch.linalg.matrix_norm(J).mean().item()
def softmax_weights(d, scale, num_keys=64, num_queries=2048):
    """Log-weights of random queries over random keys, scores scaled."""
    q = jax.random.normal(d2l.get_key(), (num_queries, d))
    keys = jax.random.normal(d2l.get_key(), (num_queries, num_keys, d))
    scores = (keys @ q[..., None]).squeeze(-1) * scale
    return jax.nn.log_softmax(scores, axis=-1)

def entropy(log_alpha):
    return float(-(jnp.exp(log_alpha) * log_alpha).sum(-1).mean())

def largest_weight(log_alpha):
    return float(jnp.exp(log_alpha).max(-1).mean())

def jacobian_norm(log_alpha):
    """Mean Frobenius norm of the Jacobian diag(alpha) - alpha alpha^T."""
    alpha = jnp.exp(log_alpha)
    J = (alpha[..., None] * jnp.eye(alpha.shape[-1])
         - alpha[..., :, None] * alpha[..., None, :])
    return float(jnp.linalg.norm(J, axis=(-2, -1)).mean())

在对数轴上将头宽度 \(d\) 从 \(4\) 扫描至 \(512\) 表明,未缩放点积注意力随 \(d\) 增大迅速发生熵坍缩,而按 \(1/\sqrt{d}\) 缩放在所有宽度上都能使注意力熵保持平直:

ds = [2**k for k in range(2, 10)]
entropies = [[entropy(softmax_weights(d, 1.0)) for d in ds],
             [entropy(softmax_weights(d, 1 / math.sqrt(d))) for d in ds]]
d2l.plot(ds, entropies, 'width d', 'entropy (nats)',
         legend=['unscaled', 'scaled by 1/sqrt(d)'], xscale='log')

ds = [2**k for k in range(2, 10)]
entropies = [[entropy(softmax_weights(d, 1.0)) for d in ds],
             [entropy(softmax_weights(d, 1 / math.sqrt(d))) for d in ds]]
d2l.plot(ds, entropies, 'width d', 'entropy (nats)',
         legend=['unscaled', 'scaled by 1/sqrt(d)'], xscale='log')

下表汇总了五个宽度下的熵、平均最大权重与 softmax 雅可比矩阵的平均 Frobenius 范数。

print('      entropy (nats)    largest weight     Jacobian norm')
print('  d' + '   unscaled scaled' * 3)
for d in (4, 16, 64, 128, 512):
    stats = [(entropy(la), largest_weight(la), jacobian_norm(la))
             for la in (softmax_weights(d, 1.0),
                        softmax_weights(d, 1 / math.sqrt(d)))]
    print(f'{d:3d}' + ''.join(f'   {u:8.3f} {s:6.3f}'
                              for u, s in zip(*stats)))
      entropy (nats)    largest weight     Jacobian norm
  d   unscaled scaled   unscaled scaled   unscaled scaled
  4      2.782  3.701      0.285  0.105      0.256  0.180
 16      1.388  3.691      0.578  0.105      0.295  0.182
 64      0.584  3.682      0.791  0.108      0.209  0.184
128      0.372  3.683      0.862  0.107      0.158  0.184
512      0.182  3.681      0.926  0.108      0.094  0.184
print('      entropy (nats)    largest weight     Jacobian norm')
print('  d' + '   unscaled scaled' * 3)
for d in (4, 16, 64, 128, 512):
    stats = [(entropy(la), largest_weight(la), jacobian_norm(la))
             for la in (softmax_weights(d, 1.0),
                        softmax_weights(d, 1 / math.sqrt(d)))]
    print(f'{d:3d}' + ''.join(f'   {u:8.3f} {s:6.3f}'
                              for u, s in zip(*stats)))
      entropy (nats)    largest weight     Jacobian norm
  d   unscaled scaled   unscaled scaled   unscaled scaled
  4      2.819  3.706      0.273  0.104      0.257  0.180
 16      1.367  3.682      0.583  0.109      0.293  0.183
 64      0.598  3.686      0.786  0.106      0.214  0.183
128      0.383  3.687      0.855  0.106      0.163  0.183
512      0.180  3.685      0.928  0.108      0.091  0.184

采用 \(1/\sqrt{d}\) 缩放后,熵在所有宽度上均稳定在 \(\log 64 - \tfrac{1}{2} \approx 3.66\) 奈特附近(5),最大权重 \(\approx 0.11\),雅可比范数 \(\approx 0.18\)。若不缩放,得分标准差按 \(\sqrt{d}\) 增长:到 \(d = 512\) 时,熵坍缩至 \(\approx 0.2\) 奈特,随机初始化下排第一的键便独揽超过 \(90\%\) 的权重,雅可比范数跌去一半。按 \(1/\sqrt{d}\) 缩放将初始 softmax 锐度与头宽度解耦,同时仍允许学得的投影在训练中自由锐化权重(一旦查询与键对齐,点积按 \(O(d)\) 增长,这正是 9.9 节 中最大更新参数化采用 \(1/d\) 缩放的动因)。许多近期模型甚至不再把温度交给投影控制:它们将查询与键规范化为单位长度,并将得分尺度作为独立参数学习,这种设计称为 QK-norm,我们将在 11.1 节 中遇到它。

这种缩放消除了锐度对宽度 \(d\) 的依赖,却未消除对键数 \(m\) 的依赖。对于单位方差得分,熵约为 \(\log m - \tfrac{1}{2}\),权重分布在约 \(0.6\,m\) 个键上——无论上下文多长,总占固定比例。查找也会以同样方式被稀释:若匹配键领先其余每个键(共 \(m - 1\) 个)的得分差为 \(g\),则它分得的权重为 \(1/(1 + (m-1)e^{-g})\)。得分差 \(g = 9\) 在 \(1{,}000\) 个键中能拿到约 \(0.9\) 的权重,在 \(100{,}000\) 个键中却不足 \(0.1\)。为保持锐度,得分差必须随 \(\log m\) 增长。因此,在某一上下文长度上训练的模型在更长上下文中注意力会更弥散,这也是某些模型随上下文长度增大得分尺度的原因(10.8 节)。

10.2.2 掩码

两种常见条件会将特定查询–键对排除在注意力之外:

  1. 填充:将不等长序列用 <blank> 词元填充成小批量时,任何查询都不应关注填充位置。
  2. 因果性:在自回归语言建模中,位置 \(t\) 的查询只能关注位置 \(j \le t\) 的键。

这两种约束均由布尔掩码张量表示:当允许查询 \(i\) 关注键 \(j\) 时为 True。

10.2.2.1 掩码 Softmax 操作

为了保持稠密张量形状,掩码 softmax 在调用 softmax 之前把被排除的得分(~mask)替换为大负数。填充值的选择需兼顾不同浮点格式:

  • 硬编码常数如 \(-10^6\) 在 float16 中会上溢(其最大有限幅值为 \(65{,}504\))。
  • 每当整行查询都被掩码时,字面 \(-\infty\) 会产生 NaN,因为数值稳定的 softmax 会减去行最大值 \(-\infty\),形成 \(-\infty - (-\infty) = \mathrm{NaN}\)。
  • 采用张量数据类型的最小有限负值(finfo(dtype).min)可在 float16、bfloat16 与 float32 中将被排除的指数精确下溢为零而不产生 NaN。对于所有键都被掩码的查询行(~mask.any(-1)),masked_softmax 显式将所得权重置零。
def masked_softmax(X, mask=None):
    """Softmax over the last axis with zero weight where mask is False."""
    if mask is None:
        return F.softmax(X, dim=-1)
    # Most negative finite value: zero weight at any precision, no NaN
    X = X.masked_fill(~mask, torch.finfo(X.dtype).min)
    weights = F.softmax(X, dim=-1)
    # A query without any valid key gets zero weights, not a uniform row
    return torch.where(mask.any(-1, keepdim=True), weights, 0.0)
def masked_softmax(X, mask=None):
    """Softmax over the last axis with zero weight where mask is False."""
    if mask is None:
        return jax.nn.softmax(X, axis=-1)
    # Most negative finite value: zero weight at any precision, no NaN
    X = jnp.where(mask, X, jnp.finfo(X.dtype).min)
    weights = jax.nn.softmax(X, axis=-1)
    # A query without any valid key gets zero weights, not a uniform row
    return jnp.where(mask.any(-1, keepdims=True), weights, 0.0)

由于 mask 只需与 X 广播对齐,同一序列中所有查询共享的填充掩码可以按形状 (batch, 1, keys) 存储。

def padding_mask(valid_lens, num_keys):
    """Boolean mask that is True for the first valid_lens keys."""
    # valid_lens of shape (batch,) gives (batch, 1, keys); per-query
    # lengths of shape (batch, queries) give (batch, queries, keys)
    if valid_lens.dim() == 1:
        valid_lens = valid_lens[:, None]
    keys = torch.arange(num_keys, device=valid_lens.device)
    return keys < valid_lens[..., None]
def padding_mask(valid_lens, num_keys):
    """Boolean mask that is True for the first valid_lens keys."""
    # valid_lens of shape (batch,) gives (batch, 1, keys); per-query
    # lengths of shape (batch, queries) give (batch, queries, keys)
    if valid_lens.ndim == 1:
        valid_lens = valid_lens[:, None]
    return jnp.arange(num_keys) < valid_lens[..., None]

在包含两条长度为 \(4\)、有效长度分别为 \(2\) 和 \(3\) 的全零得分序列的小批量上,masked_softmax 将权重均匀分配在每行的有效前缀上:

masked_softmax(torch.zeros(2, 2, 4), padding_mask(torch.tensor([2, 3]), 4))
tensor([[[0.5000, 0.5000, 0.0000, 0.0000],
         [0.5000, 0.5000, 0.0000, 0.0000]],

        [[0.3333, 0.3333, 0.3333, 0.0000],
         [0.3333, 0.3333, 0.3333, 0.0000]]])
masked_softmax(jnp.zeros((2, 2, 4)), padding_mask(jnp.array([2, 3]), 4))
Array([[[0.5       , 0.5       , 0.        , 0.        ],
        [0.5       , 0.5       , 0.        , 0.        ]],

       [[0.33333334, 0.33333334, 0.33333334, 0.        ],
        [0.33333334, 0.33333334, 0.33333334, 0.        ]]], dtype=float32)

10.2.2.2 因果掩码

因果掩码仅允许查询 \(i\) 关注满足 \(j \le i\) 的键 \(j\),构成下三角矩阵,排除了 \(n^2\) 对中的 \(n(n-1)/2\) 对(\(n = 1{,}024\) 时为 \(523{,}776\) 对)。当 num_queries < num_keys 时(例如带缓存生成期间),causal_mask 将查询与序列末尾位置对齐。

def causal_mask(num_queries, num_keys=None, device=None):
    """Boolean (queries, keys) mask, True where a query may see a key."""
    # Queries are the last positions, as when new tokens attend to a
    # cache: query i sees key j if j <= i + num_keys - num_queries
    num_keys = num_queries if num_keys is None else num_keys
    i = torch.arange(num_queries, device=device)[:, None]
    j = torch.arange(num_keys, device=device)[None, :]
    return j <= i + (num_keys - num_queries)
def causal_mask(num_queries, num_keys=None):
    """Boolean (queries, keys) mask, True where a query may see a key."""
    # Queries are the last positions, as when new tokens attend to a
    # cache: query i sees key j if j <= i + num_keys - num_queries
    num_keys = num_queries if num_keys is None else num_keys
    i = jnp.arange(num_queries)[:, None]
    j = jnp.arange(num_keys)[None, :]
    return j <= i + (num_keys - num_queries)

10.2.2.3 组合掩码

当多项约束同时生效时,一对查询–键仅在每项约束都允许时才有效,因此布尔掩码在广播下通过逻辑与(&)组合(图 10.2.1)。

图 10.2.1: 掩码通过逻辑与组合。对长度 6、有效长度 3 的序列,填充掩码只存一行键,广播为每个查询重复该行(浅色);因果掩码为下三角;两者的逻辑与仅在二者皆允许时才放行。行为查询,列为键,实心格表示允许。

在等得分上将填充掩码(有效长度 \(6\) 与 \(3\))与因果掩码组合,第一条序列得到完整因果下三角,第二条序列的所有行都在键 \(3\) 处截断:

n = 6
padding = padding_mask(torch.tensor([6, 3]), n)  # (batch, 1, key)
causal = causal_mask(n)                          # (query, key)
mask = padding & causal                          # (batch, query, key)
weights = masked_softmax(torch.zeros(2, n, n), mask)  # Equal scores
d2l.show_heatmaps(weights[None], xlabel='keys', ylabel='queries',
                  titles=['valid length 6', 'valid length 3'],
                  figsize=(5, 2.5))

n = 6
padding = padding_mask(jnp.array([6, 3]), n)  # (batch, 1, key)
causal = causal_mask(n)                       # (query, key)
mask = padding & causal                       # (batch, query, key)
weights = masked_softmax(jnp.zeros((2, n, n)), mask)  # Equal scores
d2l.show_heatmaps(weights[None], xlabel='keys', ylabel='queries',
                  titles=['valid length 6', 'valid length 3'],
                  figsize=(5, 2.5))

在较短序列中,查询 \(4\) 到 \(6\) 本身是填充,但各自仍有有效键,因为因果三角总能回溯到键 \(1\)。这是掩码形状的性质,而非逻辑与的一般性质。若我们将填充掩码与滑动窗口(仅允许每个查询看到最近几个键)组合,窗口完全落入填充区的查询就会不剩任何有效键。单独无害的掩码组合后仍可能产生空行,而这正是 masked_softmax 显式置零的情形。

同一套布尔代数也适用于打包序列——将多篇短文档拼接到同一行中以避免填充开销。把同文档指示矩阵 doc[:, None] == doc[None, :] 与 causal_mask 做逻辑与,即得块对角因果掩码:

doc = torch.tensor([0, 0, 0, 1, 1, 2])  # Document of each position
same_doc = doc[:, None] == doc[None, :]
packed = same_doc & causal_mask(6)
d2l.show_heatmaps(packed.float()[None, None], xlabel='keys',
                  ylabel='queries', cbar=False)

doc = jnp.array([0, 0, 0, 1, 1, 2])  # Document of each position
same_doc = doc[:, None] == doc[None, :]
packed = same_doc & causal_mask(6)
d2l.show_heatmaps(packed.astype(jnp.float32)[None, None], xlabel='keys',
                  ylabel='queries', cbar=False)

10.2.3 小批量注意力

将 \(n\) 个查询堆叠为 \(\mathbf{Q} \in \mathbb{R}^{n \times d}\)、\(m\) 个键堆叠为 \(\mathbf{K} \in \mathbb{R}^{m \times d}\)、\(m\) 个值堆叠为 \(\mathbf{V} \in \mathbb{R}^{m \times d_v}\),即可用两次矩阵乘法与一次逐行 softmax 表示缩放点积注意力(图 10.2.2):

\[\mathrm{softmax}\left(\frac{\mathbf{Q} \mathbf{K}^\top}{\sqrt{d}}\right) \mathbf{V} \in \mathbb{R}^{n \times d_v}. \tag{10.2.6}\]

图 10.2.2: 缩放点积注意力中的张量形状。\(\mathbf{Q}\mathbf{K}^\top/\sqrt{d}\) 存有全部 \(n \times m\) 个查询–键对的得分;经掩码与逐行 softmax 转化为权重 \(\mathbf{A}\)(此处带因果掩码,上三角留空);再乘以 \(\mathbf{V}\) 即得每个查询的值加权和。

对于带前导批量(及头)轴的小批量输入,批量矩阵乘法 @ 作用于最后两维并自动广播前导轴。对 GPT-2 small 的单个头(\(n = m = 1{,}024\),\(d = d_v = 64\)),得分矩阵包含 \(1{,}048{,}576\) 个浮点数(fp32 下占 4 MiB),两次乘法耗费 \(4n^2 d \approx 0.27\) GFLOPs——两者均随 \(n\) 二次方增长。

10.2.3.1 DotProductAttention 类

DotProductAttention 实现了 式 10.2.6,支持可选掩码与注意力权重暂退(默认 \(0.0\)),并将最近一次的注意力权重保存在 attention_weights 中以便检查。

class DotProductAttention(nn.Module):
    """Scaled dot-product attention over the last two axes."""
    def __init__(self, dropout=0.0):
        super().__init__()
        self.dropout = nn.Dropout(dropout)
        self.attention_weights = None

    # Leading axes (batch, and heads if present) are carried along.
    # Shape of queries: (..., no. of queries, d)
    # Shape of keys: (..., no. of key-value pairs, d)
    # Shape of values: (..., no. of key-value pairs, value dimension)
    # mask: boolean, broadcastable to (..., no. of queries, no. of keys),
    # True where a query may attend to a key
    def forward(self, queries, keys, values, mask=None):
        d = queries.shape[-1]
        scores = queries @ keys.transpose(-2, -1) / math.sqrt(d)
        self.attention_weights = masked_softmax(scores, mask)
        return self.dropout(self.attention_weights) @ values
class DotProductAttention(nnx.Module):
    """Scaled dot-product attention over the last two axes."""
    def __init__(self, dropout=0.0, *, rngs=None):
        # rngs is needed only to draw dropout masks (dropout > 0)
        self.dropout = nnx.Dropout(dropout, rngs=rngs)
        # A Variable, so that views of the module (nnx.view) share it
        self.last_weights = nnx.Intermediate(None)

    # Leading axes (batch, and heads if present) are carried along.
    # Shape of queries: (..., no. of queries, d)
    # Shape of keys: (..., no. of key-value pairs, d)
    # Shape of values: (..., no. of key-value pairs, value dimension)
    # mask: boolean, broadcastable to (..., no. of queries, no. of keys),
    # True where a query may attend to a key
    def __call__(self, queries, keys, values, mask=None):
        d = queries.shape[-1]
        scores = queries @ keys.swapaxes(-2, -1) / math.sqrt(d)
        weights = masked_softmax(scores, mask)
        if not isinstance(weights, jax.core.Tracer):
            # Record the weights of eager calls for inspection; inside
            # jit-compiled code skip it, so the module state keeps a
            # fixed structure and the compiled step is reused
            self.last_weights.set_value(weights)
        return self.dropout(weights) @ values

    @property
    def attention_weights(self):
        """Weights of the last eager call: (..., queries, keys)."""
        return self.last_weights.get_value()

在 10.2.1.1 节 的向量上评估 DotProductAttention,精确复现了我们的手算结果:

queries = d2l.tensor([[[2.0, 2, 0, 0], [0, 0, 2, 0]]])           # (1, 2, 4)
keys = d2l.tensor([[[1.0, 1, 0, 0], [0, 0, 1, 1], [0, 0, 1, -1]]])  # (1, 3, 4)
values = d2l.tensor([[[1.0, 0], [0, 1], [1, 1]]])                   # (1, 3, 2)
attention = DotProductAttention()
output = attention(queries, keys, values)
print('weights:', np.asarray(attention.attention_weights[0]).round(3))
print('output: ', np.asarray(output[0]).round(3))
weights: [[0.787 0.107 0.107]
 [0.155 0.422 0.422]]
output:  [[0.893 0.213]
 [0.578 0.845]]
queries = d2l.tensor([[[2.0, 2, 0, 0], [0, 0, 2, 0]]])           # (1, 2, 4)
keys = d2l.tensor([[[1.0, 1, 0, 0], [0, 0, 1, 1], [0, 0, 1, -1]]])  # (1, 3, 4)
values = d2l.tensor([[[1.0, 0], [0, 1], [1, 1]]])                   # (1, 3, 2)
attention = DotProductAttention()
output = attention(queries, keys, values)
print('weights:', np.asarray(attention.attention_weights[0]).round(3))
print('output: ', np.asarray(output[0]).round(3))
weights: [[0.787 0.107 0.107]
 [0.155 0.422 0.422]]
output:  [[0.893 0.213]
 [0.578 0.845]]

10.2.3.2 匹配两个单词的字母

为了观察无投影的内容匹配能区分什么、不能区分什么,我们为 "attention" 与 "translation" 中的每个不同字母分配随机标准正态嵌入 \(\mathbf{e} \in \mathbb{R}^{32}\),并让 "attention" 的字母去查询 "translation" 的字母。相同字母的期望缩放得分为 \(\mathbb{E}[\|\mathbf{e}\|^2]/\sqrt{32} = \sqrt{32} \approx 5.7\),而不同字母的期望得分为 \(0\)、具有单位方差。

words = 'attention', 'translation'
letters = sorted(set(''.join(words)))
emb = torch.randn(len(letters), 32)
queries, keys = (emb[[letters.index(c) for c in w]][None] for w in words)
attention = DotProductAttention()
attention(queries, keys, keys)
d2l.show_heatmaps(attention.attention_weights[None], xlabel='keys',
                  ylabel='queries', figsize=(4, 3.5), cmap='Blues',
                  xticklabels=words[1], yticklabels=words[0])

words = 'attention', 'translation'
letters = sorted(set(''.join(words)))
emb = jax.random.normal(d2l.get_key(), (len(letters), 32))
queries, keys = (emb[jnp.array([letters.index(c) for c in w])][None]
                 for w in words)
attention = DotProductAttention()
attention(queries, keys, keys)
d2l.show_heatmaps(attention.attention_weights[None], xlabel='keys',
                  ylabel='queries', figsize=(4, 3.5), cmap='Blues',
                  xticklabels=words[1], yticklabels=words[0])

三种行为尤为突出:

  1. 唯一匹配(i、o)将几乎全部权重集中到对应字母上。
  2. 重复匹配(a、t、n)将权重均分到该字母在 "translation" 中的每一次出现上,因为纯内容键不含位置身份。
  3. 未匹配查询(e)将概率质量分散到随机键上,因为即便没有相关键存在,softmax 权重之和也必须为一(在训练好的语言模型中,起始词元往往作为注意力汇吸收这些无处安放的质量,(Xiao 等 2024年))。

10.2.4 作为学得对齐的注意力

可学习注意力发源于神经机器翻译 (Bahdanau 等 2015年),旨在缓解序列到序列循环神经网络的定长向量瓶颈(12.2 节)。每一步解码时,解码器查询全部编码器状态,学得的注意力权重会自发恢复源语言与目标语言之间的词对齐——整体呈单调对角线,并在词序不同处出现偏离对角线的交叉(例如英语“black cat”对比法语“chat noir”)。

我们可以在极简模型 ToyAligner 中观察对齐的涌现。源序列由从大小 \(16\) 的词表中抽取的 \(8\) 个词元构成,目标序列施加一个交换位置 \(3\) 与 \(4\) 的固定置换 \(\pi\)。每个输出位置 \(j\) 持有一个学得的查询向量;每个源键是独热词元与独热源位置拼接后的线性投影;值则是独热源词元。

class ToyAligner(nn.Module):
    """One learned query per output position; keys from token and position."""
    def __init__(self, seq_len=8, vocab_size=16, d=16):
        super().__init__()
        self.vocab_size, n_in = vocab_size, vocab_size + seq_len
        self.queries = nn.Parameter(torch.randn(seq_len, d))
        self.W_k = nn.Parameter(torch.randn(n_in, d) / math.sqrt(n_in))
        self.attention = DotProductAttention()

    def forward(self, X):
        # X: (batch, seq_len) token ids; the values are their one-hot vectors
        tokens = F.one_hot(X, self.vocab_size).float()
        eye = torch.eye(X.shape[1], device=X.device)
        positions = eye.expand(len(X), -1, -1)
        keys = torch.cat((tokens, positions), -1) @ self.W_k
        # The queries broadcast over the batch: (batch, seq_len, vocab_size)
        return self.attention(self.queries, keys, tokens)
class ToyAligner(nnx.Module):
    """One learned query per output position; keys from token and position."""
    def __init__(self, seq_len=8, vocab_size=16, d=16, *, rngs):
        self.vocab_size, n_in = vocab_size, vocab_size + seq_len
        self.queries = nnx.Param(
            jax.random.normal(rngs.params(), (seq_len, d)))
        self.W_k = nnx.Param(jax.random.normal(rngs.params(), (n_in, d))
                             / math.sqrt(n_in))
        self.attention = DotProductAttention()

    def __call__(self, X):
        # X: (batch, seq_len) token ids; the values are their one-hot vectors
        tokens = jax.nn.one_hot(X, self.vocab_size)
        n = X.shape[1]
        positions = jnp.broadcast_to(jnp.eye(n), (len(X), n, n))
        keys = jnp.concatenate((tokens, positions), -1) @ self.W_k
        # The queries broadcast over the batch: (batch, seq_len, vocab_size)
        return self.attention(self.queries, keys, tokens)

我们通过最小化置换后目标词元的负对数似然,用 Adam 训练 ToyAligner 共 100 步。

perm = torch.tensor([0, 1, 2, 4, 3, 5, 6, 7])  # Output j copies source perm[j]

def align_data(n, seq_len=8, vocab_size=16):
    X = torch.randint(0, vocab_size, (n, seq_len))
    return X, X[:, perm]

def train_aligner(num_steps=100):
    model = ToyAligner()
    optimizer = torch.optim.Adam(model.parameters(), lr=0.05)
    for _ in range(num_steps):
        X, Y = align_data(128)
        loss = -model(X).gather(-1, Y[..., None]).log().mean()
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    return model
perm = jnp.array([0, 1, 2, 4, 3, 5, 6, 7])  # Output j copies source perm[j]

def align_data(key, n, seq_len=8, vocab_size=16):
    X = jax.random.randint(key, (n, seq_len), 0, vocab_size)
    return X, X[:, perm]

@nnx.jit
def align_step(model, optimizer, key):
    X, Y = align_data(key, 128)
    loss = lambda model: -jnp.log(
        jnp.take_along_axis(model(X), Y[..., None], -1)).mean()
    optimizer.update(model, nnx.grad(loss)(model))

def train_aligner(num_steps=100):
    model = ToyAligner(rngs=nnx.Rngs(d2l.get_key()))
    optimizer = nnx.Optimizer(model, optax.adam(0.05), wrt=nnx.Param)
    for key in jax.random.split(d2l.get_key(), num_steps):
        align_step(model, optimizer, key)
    return model

在 \(1{,}000\) 条测试序列上将未训练模型与三次独立训练运行对比,可见梯度下降可靠收敛至 \(100\%\) 准确率,且在输出位置平均下把超过 \(99\%\) 的权重落在 \(\pi(j)\) 上:

X, Y = align_data(1000)

def evaluate_aligner(model, X, Y, name):
    with torch.inference_mode():
        accuracy = (model(X).argmax(-1) == Y).float().mean()
    weights = model.attention.attention_weights  # (1000, 8, 8)
    largest = (weights.argmax(-1) == perm).float().mean()
    on_perm = weights[:, torch.arange(8), perm].mean()
    print(f'{name:>9}: accuracy {accuracy:.3f}, largest weight on pi(j) '
          f'{largest:.3f}, mean weight on pi(j) {on_perm:.3f}')

untrained = ToyAligner()
evaluate_aligner(untrained, X, Y, 'untrained')
for run in range(1, 4):
    model = train_aligner()
    evaluate_aligner(model, X, Y, f'run {run}')
untrained: accuracy 0.272, largest weight on pi(j) 0.161, mean weight on pi(j) 0.132
    run 1: accuracy 1.000, largest weight on pi(j) 1.000, mean weight on pi(j) 1.000
    run 2: accuracy 1.000, largest weight on pi(j) 1.000, mean weight on pi(j) 0.999
    run 3: accuracy 1.000, largest weight on pi(j) 1.000, mean weight on pi(j) 1.000
X, Y = align_data(d2l.get_key(), 1000)

def evaluate_aligner(model, X, Y, name):
    accuracy = (model(X).argmax(-1) == Y).mean()
    weights = model.attention.attention_weights  # (1000, 8, 8)
    largest = (weights.argmax(-1) == perm).mean()
    on_perm = weights[:, jnp.arange(8), perm].mean()
    print(f'{name:>9}: accuracy {accuracy:.3f}, largest weight on pi(j) '
          f'{largest:.3f}, mean weight on pi(j) {on_perm:.3f}')

untrained = ToyAligner(rngs=nnx.Rngs(d2l.get_key()))
evaluate_aligner(untrained, X, Y, 'untrained')
for run in range(1, 4):
    model = train_aligner()
    evaluate_aligner(model, X, Y, f'run {run}')
untrained: accuracy 0.214, largest weight on pi(j) 0.053, mean weight on pi(j) 0.120
    run 1: accuracy 1.000, largest weight on pi(j) 1.000, mean weight on pi(j) 0.999
    run 2: accuracy 1.000, largest weight on pi(j) 1.000, mean weight on pi(j) 1.000
    run 3: accuracy 1.000, largest weight on pi(j) 1.000, mean weight on pi(j) 1.000

在第一条测试序列上可视化训练前后的注意力权重矩阵,证实 ToyAligner 将无结构的初始分布转化为 \(\pi\) 的精确置换矩阵(位置 \(3\) 与 \(4\) 处呈非对角交换):

letters = 'abcdefghijklmnop'  # One letter per token id
maps = d2l.stack([untrained.attention.attention_weights[0],
                  model.attention.attention_weights[0]])
d2l.show_heatmaps(maps[None], xlabel='source', ylabel='target',
                  titles=['untrained', 'trained'], figsize=(5.5, 3),
                  cmap='Blues', xticklabels=[letters[int(i)] for i in X[0]],
                  yticklabels=[letters[int(i)] for i in Y[0]])

letters = 'abcdefghijklmnop'  # One letter per token id
maps = d2l.stack([untrained.attention.attention_weights[0],
                  model.attention.attention_weights[0]])
d2l.show_heatmaps(maps[None], xlabel='source', ylabel='target',
                  titles=['untrained', 'trained'], figsize=(5.5, 3),
                  cmap='Blues', xticklabels=[letters[int(i)] for i in X[0]],
                  yticklabels=[letters[int(i)] for i in Y[0]])

即便源序列中存在重复词元,训练后的注意力热力图依然精确恢复了 \(\pi\) 的置换矩阵,因为键在词元身份之外同时编码了位置。不过在通用序列建模中,查询必须源自序列本身,单个位置可能需要同时检索多个不同的值(10.3 节),而位置编码也必须能泛化到不同序列长度(10.4 节)。

10.2.5 小结

缩放点积打分 \(a(\mathbf{q}, \mathbf{k}) = \mathbf{q}^\top \mathbf{k} / \sqrt{d}\) 舍去了高斯核的二次范数惩罚,用单次矩阵乘法 \(\mathbf{Q}\mathbf{K}^\top\) 即可评估所有成对得分。除以 \(\sqrt{d}\) 为单位方差输入保持单位得分方差,防止 softmax 随头宽度 \(d\) 增大而饱和并导致得分梯度消失。序列填充与因果解码等结构约束通过布尔掩码施加并在逻辑与下组合,采用 finfo(dtype).min 配合显式空行置零以避免 float16 上溢与 NaN 传播。最后,纯内容键会在重复词元间均分注意力,而位置感知键则支持端到端学习序列对齐。

10.2.6 练习

  1. 得分的不变性。高斯得分 式 10.2.1 与缩放点积 式 10.2.3 都通过 softmax 式 10.2.4 定义注意力权重。
    1. 针对这两种得分,分别判断以下哪些变换使权重保持不变:给每个键加上同一向量 \(\mathbf{c}\);给查询与每个键同时加上 \(\mathbf{c}\);将查询与每个键同乘一个正交矩阵。
    2. 查询与键通常由输入经仿射映射得到:\(\mathbf{q} = \mathbf{W}_q \mathbf{x} + \mathbf{b}_q\),\(\mathbf{k}_i = \mathbf{W}_k \mathbf{y}_i + \mathbf{b}_k\)。将 \(\mathbf{q}^\top \mathbf{k}_i\) 展开为四项,证明权重不依赖 \(\mathbf{b}_k\)。损失关于 \(\mathbf{b}_k\) 的梯度是多少?
    3. \(\mathbf{b}_q\) 通过四项中的哪一项影响权重?它能表达无偏置得分所不能表达的何种键偏好?
  2. [code] Softmax 雅可比矩阵。jacobian_norm 度量雅可比矩阵 式 10.2.5 的 Frobenius 范数。
    1. 由 式 10.2.4 推导 式 10.2.5,证明对有限得分其零空间由全一向量张成,并在随机得分向量上用自动微分检验该公式。
    2. 计算权重均匀分布在 \(m\) 个键中的 \(k\) 个键上时的范数,找出使其最大化的 \(k\),并通过采样随机权重向量确认无一超过该最大值。据此解释为何前文表格中未缩放范数从 \(d = 4\) 升至 \(d = 16\) 后又下降。
  3. 全掩码行。masked_softmax 用该数据类型的最小有限负值覆盖被排除得分,随后将没有有效键的查询行置零。
    1. 构造一行四个全被排除的得分。分别在 float16 中填入 \(-10^6\)、在 float32 中填入 \(-\infty\) 以及在 float32 中填入 finfo(dtype).min,不经 masked_softmax 末尾的置零步骤而直接施加框架的 softmax。报告各自结果,并顺着减去行最大值的过程追踪成因。
    2. 在查询、键与值均来自同一序列的自注意力层中,设某个填充位置的查询没有有效键(正如 10.2.2.3 节 的复合掩码可能造成的那样),且被排除得分被覆盖为 \(-\infty\),从而该位置输出为 NaN。即便该输出被丢弃,且下一层注意力中每个有效查询都排除了该填充位置作为键,解释为何该 NaN 仍会污染该序列下一层所有有效位置的输出。
  4. 复合掩码。10.2.2.3 节 用逻辑与组合掩码,并提醒单独无害的掩码组合后可能使某些查询不剩有效键。宽度为 \(w\) 的因果滑动窗口允许位置 \(t\) 的查询关注位置 \(t - w + 1, \ldots, t\) 的键。
    1. 对长度 \(6\)、有效长度 \(3\) 的序列,将填充掩码与宽度 \(2\) 的因果滑动窗口写成 \(6 \times 6\) 布尔矩阵。验证两者各自都为每个查询保留至少一个键,并找出逻辑与之后行为空的查询。
    2. 证明只要每个掩码都允许每个查询关注自身位置,它们的逻辑与就不会出现空行。填充、因果、滑动窗口与打包序列掩码中哪些满足该条件?这如何解释你找到的空行?
    3. 某些实现会加上一个偏置矩阵(允许对为 \(0\),排除对为 \(c < 0\)),并通过将偏置相加来组合掩码。取 \(c\) 为单精度最小有限负值(约 \(-3.4 \times 10^{38}\))。计算两个此类偏置在单精度下的和,并确定 softmax 在以下两类行上的返回值:所有键都被两个掩码同时排除的行,以及所有键都被排除但部分键仅被一个掩码排除的行。
  5. 随机得分的熵。● 前文缩放后的熵曲线停留在 \(3.7\) 奈特附近,低于均匀值 \(\log 64 \approx 4.16\)。固定一个查询 \(\mathbf{q} \in \mathbb{R}^d\),并如 softmax_weights 那样抽取 \(m\) 个各坐标独立服从标准正态分布的键。
    1. 证明缩放得分 \(a_i = \mathbf{q}^\top \mathbf{k}_i / \sqrt{d}\) 是均值 \(0\)、方差 \(s^2 = \|\mathbf{q}\|^2 / d\) 的独立正态变量,并计算按 softmax_weights 抽取 \(\mathbf{q}\) 时 \(s^2\) 的期望值。
    2. 权重的熵为 \(H = \log Z - \sum_i \alpha_i a_i\),其中 \(Z = \sum_j \exp(a_j)\)。对大 \(m\),用期望值替换 \(Z/m\) 与 \(\sum_i \exp(a_i)\, a_i / m\),推导 \[H \approx \log m - \frac{s^2}{2}.\] 计算 \(m = 64\)、\(s = 1\) 时的近似值。
    3. 该近似要求 \(Z\) 集中在其均值附近。计算 \(Z\) 的相对标准差关于 \(s\) 与 \(m\) 的表达式,并据此导出该近似成立的 \(s^2\) 条件。未缩放得分满足 \(s^2 = \|\mathbf{q}\|^2\),期望为 \(d\)。计算 \(m = 64\) 在 \(s^2 = 4\) 与 \(s^2 = 8\) 处的相对标准差,并将近似值与前文绘制的 \(d = 4\) 和 \(d = 8\) 处的未缩放熵对比。
  6. [code] 零附近的加性得分。● 加性得分 式 10.2.2 在 \(\tanh\) 内部将投影后的查询与投影后的键相加。
    1. 将 \(\tanh\) 替换为恒等映射,证明此时注意力权重不依赖查询。
    2. 在零附近将 \(\tanh\) 展开至三阶,找出权重借以依赖查询的最低阶项,并说明当 \(\mathbf{W}_q\) 与 \(\mathbf{W}_k\) 同时乘以小因子 \(\epsilon\) 时该依赖如何缩放。
    3. 为 \(\mathbb{R}^8\) 中 \(3\) 个查询与 \(6\) 个键(元素独立服从标准正态分布)实现隐藏宽度 \(r = 16\) 的加性得分,按标准正态除以输入宽度平方根初始化 \(\mathbf{W}_q\)、\(\mathbf{W}_k\) 与 \(\mathbf{w}_v\)。将 \(\mathbf{W}_q\) 与 \(\mathbf{W}_k\) 乘以 \(\epsilon \in \{1, 0.3, 0.1, 0.03\}\),测量三个查询权重行之间的最大差值(跨多次抽样取平均),检验你推导的缩放律。在哪些尺度下权重才显著依赖查询?
  7. [code] 对齐变体。● 10.2.4 节 中的 ToyAligner 依靠每个输出位置一个学得查询以及同时携带词元与位置的键来学习置换 \(\pi\)。
    1. 从键中移除独热位置,使其仅依赖词元。训练前预测输出位置 \(j\) 是否仍能将权重落在 \(\pi(j)\) 上,以及模型大致能达到多少准确率;随后训练并对比。将结果与 10.2.3.2 节 中的字母示例联系起来。
    2. 将得分替换为加性规则 式 10.2.2,比较两种模型达到 \(99\%\) 准确率所需的步数。训练前,利用 6 预测加性模型在投影初始化较小时的起步表现,并加以检验。
    3. 令查询与键的宽度 \(d \in \{16, 256, 1024\}\) 且采用标准正态初始化,分别在有无 \(1/\sqrt{d}\) 因子下训练。将训练曲线与初始化时的权重熵联系起来。
    4. 证明 ToyAligner 无法学习依赖词元的重排,例如仅当首词元属于指定词表子集时才交换相邻两词元。(提示:其得分是所有位置共享的词元项加上位置项;比较相邻两者的得分。)说明查询或键需要依赖什么才能实现此类重排。

讨论