Bahdanau Attention:加性对齐、乘性变体与早期瓶颈

第 14/62 篇

系列目录 11 「注意力」的直觉:带宽、凸包寻址与短…13 Q/K/V 三件套:把 Bahdan…

目录

在 11|「注意力」的直觉 中,我们立住了注意力的几何与梯度内核:给候选打分、用 Softmax 归一、在 Value 凸包内做可微加权平均。这一篇回到 2014 年秋的蒙特利尔大学实验室,看 Bahdanau、Cho 与 Bengio(ICLR 2015;2014 年 9 月预印本)如何第一次把这套直觉写成端到端可训练的神经网络模块,拆掉 Seq2Seq 的定长上下文高墙。

理解 Bahdanau Attention 不只是翻一段模型考古史:它的打分公式里藏着参数量、显存访存与 GPU 算子形态的权衡,它留下的「解码器串行循环」直接逼出了 Transformer 对编码器与解码器的双重改造,而它的结构简化也正是下一篇 13|Q/K/V 三件套 抽象的直接母体。

学习目标(学完你能独立回答)

  1. 为什么 Bahdanau 加性打分 \(e_{t,i} = \mathbf{v}_a^\top \tanh(W_1 \mathbf{s}_{t-1} + W_2 \mathbf{h}_i)\) 等价于对拼接向量 \([\mathbf{s}_{t-1}; \mathbf{h}_i]\) 过单隐层 MLP,工程上又如何通过预计算 \(W_2 \mathbf{h}_i\) 省掉重复乘法?
  2. Bahdanau 加性注意力与 Luong 乘性注意力(dot / general)在参数量、MACs 计算量与中间 3D 张量显存上如何量化取舍?给定 \(d=2\)、2 个源端词条,你能否手算完整前向步骤?
  3. Bahdanau Attention 已经实现了每步动态寻址源句,为什么它仍然保留着阻碍大规模并行的结构瓶颈?相比标准 Q/K/V,它还隐含了哪两个简化?

一、2014 年现场:定长 context vector 的三道墙

要看清 Bahdanau 的改动为何切中要害,先对齐当时神经机器翻译(NMT)的时间线:

纯 Seq2Seq 把源句全部隐状态压缩进单一终点向量 \(\mathbf{c} = \mathbf{h}_{T_x}\),同时撞上三道结构墙:第一,定长容量上限——无论源句 8 个词还是 60 个词都挤在同一条 \(\mathbb{R}^d\) 向量里;第二,上下文静态不可调——解码器生成第 1 个目标词和第 30 个目标词看到的 \(\mathbf{c}\) 完全一样,无法按当前语法角色切换焦点;第三,梯度长路衰减——末步解码误差必须倒穿全部解码步与编码步才能更新源句开头的词表示。

Bahdanau 论文标题中的「Jointly Learning to Align and Translate」直接点明了破局方式:把统计机器翻译时代用 EM 算法单独学习的离散对齐变量,替换成端到端共享梯度的连续 Softmax 权重分布,一边学对齐一边学翻译。


二、RNNsearch 架构:双向 GRU 编码与动态上下文 \(\mathbf{c}_t\)

在模型细节上,教材常顺口说「Bahdanau 用了双向 LSTM」,但原论文(Bahdanau et al., ICLR 2015, Appendix A)实际采用的是刚提出的 GRU(具体为双向 GRU 编码器 + 单向 GRU 解码器)。这处改动包含三个紧密配合的构件:

  1. 双向编码器给出全句上下文标注(Annotation):单向 RNN 在位置 \(i\) 的隐状态 \(\overrightarrow{\mathbf{h}}_i\) 只见过前文 \(x_1, \ldots, x_i\)。为了让每个源位置 \(i\) 的表示同时携带左右语境(例如根据右侧动词判断左侧多义名词词性),RNNsearch 拼接正向与反向隐状态: \[ \overrightarrow{\mathbf{h}}_i = \operatorname{GRU}_{\text{fwd}}(x_i, \overrightarrow{\mathbf{h}}_{i-1}), \qquad \overleftarrow{\mathbf{h}}_i = \operatorname{GRU}_{\text{bwd}}(x_i, \overleftarrow{\mathbf{h}}_{i+1}), \qquad \mathbf{h}_i = \begin{bmatrix} \overrightarrow{\mathbf{h}}_i \\ \overleftarrow{\mathbf{h}}_i \end{bmatrix} \in \mathbb{R}^{2 d_{\text{enc}}} \] 编码器不再只输出最后一个状态,而是保留整排标注序列 \(H = (\mathbf{h}_1, \ldots, \mathbf{h}_{T_x})\) 供解码器随时检索。
  2. 每步重算动态上下文 \(\mathbf{c}_t\):解码第 \(t\) 个词时,先根据上一时刻解码状态 \(\mathbf{s}_{t-1}\) 与每个源标注 \(\mathbf{h}_i\) 算对齐权重 \(\alpha_{t,i}\),再做凸组合得到本步专属上下文: \[ \mathbf{c}_t = \sum_{i=1}^{T_x} \alpha_{t,i} \mathbf{h}_i \]
  3. 为什么查询向量用 \(\mathbf{s}_{t-1}\) 而不是 \(\mathbf{s}_t\):因为解码器的递归更新 \(\mathbf{s}_t = \operatorname{GRU}(\mathbf{s}_{t-1}, y_{t-1}, \mathbf{c}_t)\) 本身依赖 \(\mathbf{c}_t\) 作为输入!要想先算出 \(\mathbf{c}_t\),查询只能取上一时刻已知的状态 \(\mathbf{s}_{t-1}\)(下图中用 \(s_t\) 简写示意查询向量位置,实际对应 Bahdanau 的 pre-RNN 查询 \(\mathbf{s}_{t-1}\);而下一节的 Luong 则先更新出 \(\mathbf{s}_t\) 再做注意力查询)。
Bahdanau Attention 架构:双向编码器保留全序列标注,解码器在每步按当前状态动态加权生成 c_t

三、Bahdanau 加性注意力的公式拆解与分块矩阵等价性

离开校园多年的程序员第一次看到 Bahdanau 公式时,最容易卡在三个问题上:为什么要同时乘两个矩阵 \(W_1, W_2\) 才能相加?加完之后为什么要再套一层 \(\tanh\) 和 \(\mathbf{v}_a^\top\)?文献里一会写成拼接 \(W_a [\mathbf{s}_{t-1}; \mathbf{h}_i]\)、一会写成加法 \(W_1 \mathbf{s}_{t-1} + W_2 \mathbf{h}_i\),到底是不是同一个东西?

先把整套公式想成一个「慢查询预缓存 + 广播相加 + 门控打分」的三段式服务管线:

  1. 为什么不能直接写 \(\mathbf{s}_{t-1} + \mathbf{h}_i\),而必须先乘 \(W_1\) 和 \(W_2\)? 因为解码器状态 \(\mathbf{s}_{t-1} \in \mathbb{R}^{d_s}\) 与双向编码器标注 \(\mathbf{h}_i \in \mathbb{R}^{d_h}\) 来自两套完全不同的「坐标系」(例如双向 GRU 拼接后 \(d_h = 2 d_{\text{enc}}\),连向量长度都可能跟 \(d_s\) 不一致,代码里直接相加会报 shape mismatch)。\(W_1 \in \mathbb{R}^{d_a \times d_s}\) 和 \(W_2 \in \mathbb{R}^{d_a \times d_h}\) 的作用,就是充当两块坐标适配器,先把两边都投影到同一个维度为 \(d_a\) 的中间匹配空间,对齐之后才能逐维相加。
  2. 为什么加完还要过 \(\tanh\) 和 \(\mathbf{v}_a^\top\)? 两个 \(d_a\) 维向量相加得到的还是一个 \(d_a\) 维向量(特征列表),而不是 Softmax 需要的单个标量分数。\(\tanh(\cdot)\) 逐元素把过大的数值压扁到 \((-1, 1)\) 区间,避免某个通道一枝独秀;随后可学习的读出向量 \(\mathbf{v}_a^\top \in \mathbb{R}^{1 \times d_a}\) 把这 \(d_a\) 个隐藏特征加权求成 \(1\) 个打分标量 \(e_{t,i}\)。合起来,它正是一个「拼接输入 \(\to\) 隐层宽度 \(d_a\)(\(\tanh\) 激活)\(\to\) 单标量输出」的经典单隐层感知机(MLP)。

合在一起,Bahdanau 对齐模型(alignment model)的完整三步为:

\[ e_{t,i} = \mathbf{v}_a^\top \tanh\big(W_1 \mathbf{s}_{t-1} + W_2 \mathbf{h}_i\big), \qquad \alpha_{t,i} = \frac{\exp(e_{t,i})}{\sum_{j=1}^{T_x} \exp(e_{t,j})}, \qquad \mathbf{c}_t = \sum_{i=1}^{T_x} \alpha_{t,i} \mathbf{h}_i \]

其中 \(\mathbf{s}_{t-1} \in \mathbb{R}^{d_s}\),\(\mathbf{h}_i \in \mathbb{R}^{d_h}\)(双向编码时 \(d_h = 2 d_{\text{enc}}\)),可学习参数为 \(W_1 \in \mathbb{R}^{d_a \times d_s}\)、\(W_2 \in \mathbb{R}^{d_a \times d_h}\) 以及打分方向向量 \(\mathbf{v}_a \in \mathbb{R}^{d_a}\)。

分块矩阵乘法视角:为什么相加等价于拼接

很多文献(包括 Luong 的 concat 命名)会把上式写成 \(\mathbf{v}_a^\top \tanh(W_a [\mathbf{s}_{t-1}; \mathbf{h}_i])\),与 Bahdanau 的 \(W_1 \mathbf{s}_{t-1} + W_2 \mathbf{h}_i\) 看起来像两种操作。用具体的 \(2\times 2\) 矩阵切一遍就彻底明白了:假设 \(d_s = d_h = d_a = 2\),把第五节里的 \(W_1, W_2\) 左右拼成 \(2 \times 4\) 大矩阵 \(W_a\),去乘上下拼起来的 \(4\times 1\) 向量 \([\mathbf{s}_{t-1}; \mathbf{h}_1] = [1, 0, 1, 1]^\top\):

\[ W_a \begin{bmatrix} \mathbf{s}_{t-1} \\ \mathbf{h}_1 \end{bmatrix} = \left[\begin{array}{cc|cc} 1.0 & 0.5 & 0.5 & 0.5 \\ 0.0 & 1.0 & -0.5 & 1.0 \end{array}\right] \begin{bmatrix} 1 \\ 0 \\ \hline 1 \\ 1 \end{bmatrix} = \underbrace{\begin{pmatrix} 1.0\times 1 + 0.5\times 0 \\ 0.0\times 1 + 1.0\times 0 \end{pmatrix}}_{W_1 \mathbf{s}_{t-1} = [1.0,\; 0.0]^\top} + \underbrace{\begin{pmatrix} 0.5\times 1 + 0.5\times 1 \\ -0.5\times 1 + 1.0\times 1 \end{pmatrix}}_{W_2 \mathbf{h}_1 = [1.0,\; 0.5]^\top} = \begin{pmatrix} 2.0 \\ 0.5 \end{pmatrix} \]

放到一般任意维度下,这就是标准的分块矩阵乘法:把 \(W_a \in \mathbb{R}^{d_a \times (d_s + d_h)}\) 按列切分为左右两块 \(W_a = [W_1 \mid W_2]\),则:

\[ W_a \begin{bmatrix} \mathbf{s}_{t-1} \\ \mathbf{h}_i \end{bmatrix} = \begin{bmatrix} W_1 & W_2 \end{bmatrix} \begin{bmatrix} \mathbf{s}_{t-1} \\ \mathbf{h}_i \end{bmatrix} = W_1 \mathbf{s}_{t-1} + W_2 \mathbf{h}_i \]

两者在代数上逐比特完全恒等,但拆成相加的工程收益极其巨大——就像把慢查询里不随用户请求变化的静态列提前建好索引缓存:

Bahdanau 加性打分流水线:分块矩阵预缓存与 d=2 数值走查

四、Bahdanau 加性 vs Luong 乘性:参数量与 FLOPs 严格对比

Bahdanau 发表一年后,Luong, Pham & Manning(EMNLP 2015)系统比较了不同的打分函数与计算位置,提出了更加矩阵化的乘性注意力(multiplicative attention),并把解码器查询时机从 Bahdanau 的「pre-RNN」改成「post-RNN」——写成伪代码对比,两者的执行顺序刚好调了个个儿:

Additive(Bahdanau)与 Multiplicative(Luong)注意力打分结构对比
Bahdanau 加性 vs Luong 乘性:算子形态、3D 显存与时序顺序

Luong 给出的三种打分函数(其中 concat 即 Bahdanau 的加性形式):

\[ \operatorname{score}(\mathbf{s}_t, \mathbf{h}_i) = \begin{cases} \mathbf{s}_t^\top \mathbf{h}_i & \text{dot(要求 } d_s = d_h \text{)} \\ \mathbf{s}_t^\top W \mathbf{h}_i & \text{general(双线性,} W \in \mathbb{R}^{d_s \times d_h} \text{)} \\ \mathbf{v}_a^\top \tanh(W_a [\mathbf{s}_t; \mathbf{h}_i]) & \text{concat / additive} \end{cases} \]

为了避免「感觉上谁快谁慢」的模糊评价,我们用程序员最习惯的数组维度 + 乘加次数(MACs)逐项记账法,把表格里每一项公式的来历彻底算清(单条样本:源长 \(T_x\)、目标长 \(T_y\)、维度 \(d_s, d_h\)、加性隐层 \(d_a\)):

机制与变体 打分公式 可学参数量 跨全序列投影 + 打分 MACs(含预计算) 成对中间特征张量显存 GPU Tensor Core 友好度
Bahdanau Additive \(\mathbf{v}_a^\top \tanh(W_1 \mathbf{s} + W_2 \mathbf{h})\) \(d_a(d_s + d_h + 1)\) \(T_x d_a d_h + T_y d_a d_s + T_y T_x d_a\) \(O(T_y T_x d_a)\)(逐元素 \(\tanh\) 需落盘 3D 张量) 低–中(逐对加法与 \(\tanh\) 受内存带宽制约)
Luong General(双线性) \(\mathbf{s}^\top W \mathbf{h}\) \(d_s d_h\) \(T_x d_s d_h + T_y T_x d_s\) \(O(T_y T_x)\)(无 \(d_a\) 维度,直接产出标量矩阵) 高(直接降为 \(S (W H^\top)\) 大矩阵乘)
Luong Dot(纯内积) \(\mathbf{s}^\top \mathbf{h}\) \(0\) \(T_y T_x d_s\)(要求 \(d_s = d_h\)) \(O(T_y T_x)\) 极高(单次 GEMM \(S H^\top\),Transformer 直接继承)

注意表格第四列揭示的工程鸿沟:即使加性注意力提前缓存了 \(W_2 H^\top\)、甚至把 \(d_a\) 设得比 \(d_s\) 小,它依然必须在每一步计算并读写形状为 \((B, T_x, d_a)\)(若全序列并行则为 4D 张量 \((B, T_y, T_x, d_a)\))的中间激活并逐元素求 \(\tanh\),算术强度低且显存带宽吃紧;而乘性注意力跳过隐层激活,把成对交互完全压成一次高度优化的 BLAS/GEMM 矩阵乘法 \(S (W H^\top)\)。

反过来,加性注意力为什么当年依然表现优异?因为自带 \(\tanh\) 非线性且输出被 \(\mathbf{v}_a^\top\) 有界约束在 \((-\|\mathbf{v}_a\|_1, \|\mathbf{v}_a\|_1)\) 内,即使维度 \(d_h\) 较大也不易像未缩放内积那样出现方差随 \(d_k\) 膨胀导致的 Softmax 饱和——直到 Transformer 为点积补上了 \(1/\sqrt{d_k}\) 缩放因子,乘性注意力才同时兼得高维稳定性与极致的矩阵乘吞吐(详见 15|Scaled Dot-Product)。


五、跟着纸笔算一遍:\(d=2\)、2 词条 Bahdanau 前向手算与 NumPy 验证

下面取最小维度 \(d_s = d_h = d_a = 2\)、源序列长度 \(T_x = 2\),亲手算完 Bahdanau 加性注意力的每一步输出,同时验证忘记遮罩 <PAD> 位置时会发生什么灾难。

设定:设上一时刻解码器状态为 \(\mathbf{s}_{t-1} = [1.0,\; 0.0]^\top\),编码器两个源词条为 \(\mathbf{h}_1 = [1.0,\; 1.0]^\top\)、\(\mathbf{h}_2 = [-1.0,\; 0.0]^\top\)。对齐网络参数取:

\[ W_1 = \begin{pmatrix} 1.0 & 0.5 \\ 0.0 & 1.0 \end{pmatrix}, \qquad W_2 = \begin{pmatrix} 0.5 & 0.5 \\ -0.5 & 1.0 \end{pmatrix}, \qquad \mathbf{v}_a = \begin{pmatrix} 1.0 \\ 1.0 \end{pmatrix} \]

第一步:投影查询与源端键值

  1. 查询投影: \[W_1 \mathbf{s}_{t-1} = \begin{pmatrix} 1.0 & 0.5 \\ 0.0 & 1.0 \end{pmatrix} \begin{pmatrix} 1.0 \\ 0.0 \end{pmatrix} = \begin{pmatrix} 1.0 \\ 0.0 \end{pmatrix}\]
  2. 源端键投影(可预计算): \[W_2 \mathbf{h}_1 = \begin{pmatrix} 0.5 & 0.5 \\ -0.5 & 1.0 \end{pmatrix} \begin{pmatrix} 1.0 \\ 1.0 \end{pmatrix} = \begin{pmatrix} 1.0 \\ 0.5 \end{pmatrix}, \qquad W_2 \mathbf{h}_2 = \begin{pmatrix} 0.5 & 0.5 \\ -0.5 & 1.0 \end{pmatrix} \begin{pmatrix} -1.0 \\ 0.0 \end{pmatrix} = \begin{pmatrix} -0.5 \\ 0.5 \end{pmatrix}\]

第二步:逐对相加、过 \(\tanh\) 与标量打分

  1. 词条 1: \[W_1 \mathbf{s}_{t-1} + W_2 \mathbf{h}_1 = \begin{pmatrix} 2.0 \\ 0.5 \end{pmatrix} \implies \tanh\begin{pmatrix} 2.0 \\ 0.5 \end{pmatrix} \approx \begin{pmatrix} 0.964028 \\ 0.462117 \end{pmatrix}\] \[e_{t,1} = \mathbf{v}_a^\top \begin{pmatrix} 0.964028 \\ 0.462117 \end{pmatrix} = 0.964028 + 0.462117 = 1.426145\]
  2. 词条 2: \[W_1 \mathbf{s}_{t-1} + W_2 \mathbf{h}_2 = \begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix} \implies \tanh\begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix} \approx \begin{pmatrix} 0.462117 \\ 0.462117 \end{pmatrix}\] \[e_{t,2} = \mathbf{v}_a^\top \begin{pmatrix} 0.462117 \\ 0.462117 \end{pmatrix} = 0.924234\]

第三步:Softmax 归一化与动态上下文 \(\mathbf{c}_t\)

\[ e_{t,1} - e_{t,2} = 1.426145 - 0.924234 = 0.501911 \implies \alpha_{t,1} = \frac{1}{1 + e^{-0.501911}} \approx 0.622908, \quad \alpha_{t,2} \approx 0.377092 \]

\[ \mathbf{c}_t = 0.622908 \begin{pmatrix} 1.0 \\ 1.0 \end{pmatrix} + 0.377092 \begin{pmatrix} -1.0 \\ 0.0 \end{pmatrix} \approx \begin{pmatrix} 0.245816 \\ 0.622908 \end{pmatrix} \]

第四步:NumPy 复现、<PAD> 污染验证与 PyTorch 参考实现

下面的 NumPy 脚本复现上述手算,并额外演示一个工程经典故障:若在源端末尾追加一个全零 <PAD> 向量 \(\mathbf{h}_3 = [0, 0]^\top\) 但忘了传 mask,即便 \(\mathbf{h}_3\) 本身为零,它的加性分数依然有 \(e_{t,3} = \mathbf{v}_a^\top \tanh(W_1 \mathbf{s}_{t-1} + \mathbf{0}) = \tanh(1.0) \approx 0.761594\),会强行偷走近四分之一的注意力权重!

import numpy as np

s_prev = np.array([1.0, 0.0])
H = np.array([[1.0, 1.0], [-1.0, 0.0]])
W1 = np.array([[1.0, 0.5], [0.0, 1.0]])
W2 = np.array([[0.5, 0.5], [-0.5, 1.0]])
v_a = np.array([1.0, 1.0])

def bahdanau_step(s, enc_H, mask=None):
    s_proj = W1 @ s                  # (d_a,)
    h_proj = enc_H @ W2.T            # (T_x, d_a)
    e = np.tanh(h_proj + s_proj) @ v_a
    if mask is not None:
        e = np.where(mask > 0, e, -1e9)
    e_shift = e - np.max(e)
    alpha = np.exp(e_shift)
    alpha /= np.sum(alpha)
    c = alpha @ enc_H
    return e, alpha, c

e, alpha, c_t = bahdanau_step(s_prev, H)
print("2-token e_t    =", np.round(e, 6))
print("2-token alpha  =", np.round(alpha, 6))
print("2-token c_t    =", np.round(c_t, 6))

# 演示:追加零向量 <PAD> 但忘记 mask
H_pad = np.vstack([H, [0.0, 0.0]])
e_pad, alpha_pad, c_pad = bahdanau_step(s_prev, H_pad, mask=None)
print("Unmasked PAD e =", np.round(e_pad, 6))
print("Unmasked alpha =", np.round(alpha_pad, 6))
print("Unmasked c_t   =", np.round(c_pad, 6))

在本地 python3(NumPy 1.26.4)执行输出如下:

2-token e_t    = [1.426145 0.924234]
2-token alpha  = [0.622908 0.377092]
2-token c_t    = [0.245816 0.622908]
Unmasked PAD e = [1.426145 0.924234 0.761594]
Unmasked alpha = [0.471725 0.28557  0.242705]
Unmasked c_t   = [0.186156 0.471725]

看最后两行:零向量 <PAD> 竟然分走了 \(24.27\%\) 的注意力,直接把输出上下文向量整体缩水了四分之一。对照在 PyTorch 中编写可训练模块时(API 参考写法,带批处理 unsqueeze(1) 广播与半精度安全的 -float("inf") 掩码):

import torch
import torch.nn as nn

class BahdanauAttention(nn.Module):
    def __init__(self, d_s: int, d_h: int, d_a: int = 128):
        super().__init__()
        self.W1 = nn.Linear(d_s, d_a, bias=False)
        self.W2 = nn.Linear(d_h, d_a, bias=False)
        self.v_a = nn.Linear(d_a, 1, bias=False)

    def forward(self, s_prev: torch.Tensor, h: torch.Tensor, mask: torch.Tensor | None = None):
        # s_prev: (B, d_s), h: (B, T_x, d_h), mask: (B, T_x) bool (True=valid)
        s_proj = self.W1(s_prev).unsqueeze(1)                    # (B, 1, d_a)
        h_proj = self.W2(h)                                      # (B, T_x, d_a)
        e = self.v_a(torch.tanh(s_proj + h_proj)).squeeze(-1)    # (B, T_x)
        if mask is not None:
            e = e.masked_fill(~mask, float("-inf"))
        alpha = torch.softmax(e, dim=-1)                         # (B, T_x)
        c = torch.bmm(alpha.unsqueeze(1), h).squeeze(1)          # (B, d_h)
        return c, alpha

工程上写这段代码最常错两处:一是漏掉 s_proj 的 unsqueeze(1) 导致广播维度错位;二是在混合精度 fp16 下把 mask 填成 -1e9 引发下溢或溢出问题(推荐使用 -float("inf") 或 fp16 安全值,且需确保每个样本至少有一个有效非 pad 键以防整行 NaN)。


六、对齐矩阵的发现、后续变种与可解释性边界

Bahdanau 论文(ICLR 2015)在 WMT’14 英法翻译上给出了直观的实证对比:不带注意力的纯循环基线 RNNenc 在句长超过 30 词后 BLEU 迅速下滑,而加上加性注意力的 RNNsearch 在 50 词以上长句仍保持平稳,整体单模型翻译质量反超同期无注意力基线(且仅含已知词表子集对比中也明显领先)。

写代码时怎样读懂一张软对齐热力图?其实热力图的第 \(t\) 行,就是解码第 \(t\) 个词时打在编码器数组 H 上的一个长度为 \(T_x\) 的「软指针概率分布」alpha[t, :](全行加起来严格等于 \(1.00\)):

Bahdanau 论文 Fig 3 风格的英法软对齐矩阵:法语名词后置修饰造成的反序交叉自然涌现
英法软对齐热力图:每一行都是解码器在源句上的动态聚光灯

沿 Bahdanau 的加性形式继续演化出几个重要分支(部分至今仍在垂直领域使用):

在调试和监控时,每步注意力熵 \(H(\boldsymbol{\alpha}_t) = -\sum_i \alpha_{t,i}\ln \alpha_{t,i}\) 与源端覆盖度 \(C_i\) 非常实用,但仍需牢记第 11 篇强调的边界:如图形再漂亮,也不能把 \(\alpha_{t,i}\) 直接等同于因果解释(Jain & Wallace, NAACL 2019;Wiegreffe & Pinter, EMNLP 2019)。


七、为什么 Bahdanau 仍然没摆脱 RNN 的顺序瓶颈

既然 Bahdanau Attention 已经能一步直连源句任意位置,彻底治愈了长句的上下文向量瓶颈,为什么仅仅三年后 Transformer 还是把整套 RNNsearch 淘汰掉了?

答案在计算图的依赖箭头里。虽然在单个解码步 \(t\) 内部,计算所有 \(i \in \{1, \ldots, T_x\}\) 的打分 \(e_{t,i}\) 与加权 \(\mathbf{c}_t\) 可以沿 \(T_x\) 维完全并行;但跨解码时间步 \(t = 1, 2, \ldots, T_y\) 形成了一条死锁环路:

\[ \mathbf{s}_{t-1} \xrightarrow{\text{Attn}(s_{t-1}, H)} \mathbf{c}_t \xrightarrow{\text{GRU}(y_{t-1}, \mathbf{s}_{t-1}, \mathbf{c}_t)} \mathbf{s}_t \xrightarrow{\text{Attn}(s_t, H)} \mathbf{c}_{t+1} \longrightarrow \cdots \]

即便在训练阶段开启 Teacher Forcing(所有真实目标词 \(y_1, \ldots, y_{T_y}\) 事先全部已知),要计算第 \(t\) 步的注意力分数,依然必须苦等第 \(t-1\) 步的解码器 GRU 把 \(\mathbf{s}_{t-1}\) 算出来;而双向编码器自身也必须按顺序走完 \(O(T_x)\) 步正向循环和 \(O(T_x)\) 步反向循环。

flowchart LR
    H["Encoder Annotations H = (h_1 ... h_Tx)"] --> A1["Step t-1 Attn (uses s_t-2)"]
    H --> A2["Step t Attn (uses s_t-1)"]
    H --> A3["Step t+1 Attn (uses s_t)"]
    S0["s_t-2"] --> A1 --> C1["c_t-1"] --> G1["Decoder GRU"] --> S1["s_t-1 (serial wait!)"]
    S1 --> A2 --> C2["c_t"] --> G2["Decoder GRU"] --> S2["s_t (serial wait!)"]
    S2 --> A3 --> C3["c_t+1"] --> G3["Decoder GRU"]

换句话说,Bahdanau 治好了编码端与解码端之间的空间距离瓶颈,却一点也没有动摇编码器内部与解码器内部沿时间轴的\(O(T_x) + O(T_y)\) 串行计算墙。要想让整段训练期目标序列所有 \(T_y\) 个位置一次前向并发算完,必须把 \(\mathbf{s}_t\) 的循环更新也一起拔掉,换成用下三角因果掩码隔绝未来的并行自注意力——这正是 14|Self-Attention 与 17|Causal Mask 完成的最后临门一脚。


八、通向 Q/K/V 抽象:Bahdanau 隐含了哪两个简化

站回现代 Transformer 的视角审视 Bahdanau 公式,它已经具备了「查询—打分—归一—聚合」的完整骨架,距离标准缩放点积注意力 \(\operatorname{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V\) 只差拆掉两个早期简化:

  1. 没有独立的 Value 投影 \(W_V\),且强绑定 \(K = V = \mathbf{h}_i\):在 Bahdanau 中,用来算相似度分数的载体 \(\mathbf{h}_i\),与被加权取出的信息载荷 \(\mathbf{h}_i\) 是同一组双向 RNN 隐状态向量。模型无法做到「按句法位置或词性标签去检索(Key 空间),同时按翻译所需的语义内容去提取载荷(Value 空间)」。
  2. 投影耦合在非线性 MLP 内部,尚未拆成独立可批处理的 \(Q, K\) 空间内积:\(W_1, W_2\) 嵌在 \(\tanh\) 里,无法提前通过一次大矩阵乘算完所有 \((t, i)\) 之间的交互分数。

下表总结从 Bahdanau(ICLR 2015)到 Vaswani Transformer(NeurIPS 2017)的范式跃迁:

架构维度 Bahdanau Attention(2015) Vaswani Transformer(2017)
编码器骨架 双向 GRU 堆叠双向 Self-Attention + FFN
解码器骨架 单向 GRU + 跨序列 Attention Causal Masked Self-Attention + Cross-Attention + FFN
Query / Key / Value \(\mathbf{s}_{t-1}\) 作 Query;\(\mathbf{h}_i\) 同时兼任 Key 与 Value(\(K=V\)) 各自独立线性投影 \(X W_Q, X W_K, X W_V\)(\(K\) 与 \(V\) 解耦)
打分函数 加性 MLP:\(\mathbf{v}_a^\top \tanh(W_1 \mathbf{q} + W_2 \mathbf{k})\) 缩放点积:\(\mathbf{q}^\top \mathbf{k} / \sqrt{d_k}\)
注意力头数 单头(单一对齐分布) 多头 Multi-Head(并行捕捉多种子空间关联)
训练并行度 编码器串行 \(O(T_x)\),解码器串行 \(O(T_y)\) 编码器与解码器均时间维全并行 \(O(1)\) 串行层数
位置表示 由双向 RNN 递推隐式编码 显式注入正弦/可学/旋转位置编码

下一篇 13|Q/K/V 三件套 将正式拆解这三块独立投影矩阵背后的线性代数含义。


课后作业与自测

1. 概念辨析与计算顺序

请辨析以下两对概念并回答一个依赖问题:(1)经常有资料把 soft / hard attention 与 additive / multiplicative attention 混为一谈,它们分别是在哪两个独立维度上做的分类?(2)为什么 Bahdanau 公式的打分必须用 \(\mathbf{s}_{t-1}\) 而非 \(\mathbf{s}_t\),而 Luong 又是如何用 \(\mathbf{s}_t\) 做查询的?

参考解答与评分要点(先独立推导再展开)
  1. 两个正交维度(5 分):
    • soft vs hard 分类依据是权重分布形态与可微性:soft 用 Softmax 在所有候选上生成连续概率分布做加权平均,全程可微;hard 用 argmax 或采样只挑单个或离散子集,需 REINFORCE 等策略梯度方法训练。
    • additive vs multiplicative 分类依据是未归一化打分函数 \(e_{t,i}\) 的形式:additive 用隐层 + \(\tanh\) 加法拼接打分;multiplicative 用双线性内积 \(\mathbf{s}^\top W \mathbf{h}\) 或点积 \(\mathbf{s}^\top \mathbf{h}\) 打分。两对概念完全正交,加性与乘性注意力均属于 soft attention。
  2. 查询状态时序差异(5 分):Bahdanau 把动态上下文 \(\mathbf{c}_t\) 作为输入喂进解码器 GRU 以生成当前状态 \(\mathbf{s}_t = \operatorname{GRU}(y_{t-1}, \mathbf{s}_{t-1}, \mathbf{c}_t)\),因此计算 \(\mathbf{c}_t\) 时 \(\mathbf{s}_t\) 尚未诞生,只能用 \(\mathbf{s}_{t-1}\) 当 query;而 Luong 调换了计算顺序,先执行 \(\mathbf{s}_t = \operatorname{RNN}(y_{t-1}, \mathbf{s}_{t-1})\) 算出临时隐状态 \(\mathbf{s}_t\),再用 \(\mathbf{s}_t\) 去查编码器得到 \(\mathbf{c}_t\),最后拼接 \([\mathbf{s}_t; \mathbf{c}_t]\) 过线性层预测输出词。

2. 参数量、MACs 与显存账本

设单条样本源序列长 \(T_x = 50\)、目标序列长 \(T_y = 50\),隐藏维度 \(d_s = d_h = 512\),加性注意力隐层维度 \(d_a = 256\)。对比 Bahdanau 加性注意力(含预计算 \(W_2 H^\top\) 优化) 与 Luong general 双线性注意力(预计算 \(W H^\top\)): (1)分别计算二者的可学参数量; (2)分别计算解码整条样本所需的打分阶段总 MACs(不包含后续 \(\boldsymbol{\alpha}^\top H\) 加权); (3)假设全序列并行评估,加性注意力比 general 多出多大的 fp32 3D 中间激活张量?如果不做 \(W_2 H^\top\) 预计算而直接逐对拼接 \([\mathbf{s}_{t-1}; \mathbf{h}_i]\),计算量会膨胀到多少?

参考解答与评分要点(先独立推导再展开)
  1. 参数量对比(3 分):
    • Bahdanau:\(P_{\text{add}} = d_a(d_s + d_h + 1) = 256 \times (512 + 512 + 1) = 262,400\)。
    • Luong general:\(P_{\text{gen}} = d_s d_h = 512 \times 512 = 262,144\)。二者总参数量几乎相等。
  2. 总 MACs 对比(4 分):
    • Bahdanau(含预计算):源端预计算 \(T_x d_a d_h = 50 \times 256 \times 512 = 6,553,600\);目标投影 \(T_y d_a d_s = 50 \times 256 \times 512 = 6,553,600\);逐对 \(\mathbf{v}_a^\top \tanh(\cdot)\) 点积 \(T_y T_x d_a = 50 \times 50 \times 256 = 640,000\),合计 \(13,747,200\) MACs(另加 \(640,000\) 次加法与 \(\tanh\))。
    • Luong general(含预计算):源端投影 \(T_x d_s d_h = 50 \times 512 \times 512 = 13,107,200\);矩阵乘打分 \(T_y T_x d_s = 50 \times 50 \times 512 = 1,280,000\),合计 \(14,387,200\) MACs。虽然这里因 \(d_a=256 < d_s\) 使得总 MACs 略接近,但 Luong 全部是高密度 GEMM 而无逐元素 \(\tanh\)。
  3. 3D 中间激活与未预计算代价(3 分):
    • 加性注意力多出的 3D 张量形状为 \((T_y, T_x, d_a) = (50, 50, 256)\),共 \(640,000\) 个元素,fp32(4 字节)下占 \(2,560,000\) 字节(\(2500.0\text{ KiB} \approx 2.44\text{ MiB}\)/样本)(batch 为 64 时达 \(156\text{ MiB}\))。
    • 若不做预计算而对每对 \((t, i)\) 直接算 \(W_a [\mathbf{s}_{t-1}; \mathbf{h}_i]\),仅投影就需 \(T_y T_x d_a (d_s + d_h) = 2500 \times 256 \times 1024 = 655,360,000\) MACs,加上 \(\mathbf{v}_a\) 点积共 \(656,000,000\) MACs,暴涨近 48 倍!

3. 手算与 <PAD> 掩码故障诊断

在第五节的 \(d=2\) 手算例题中,假如由于批处理需要补长,源句在 \(\mathbf{h}_1=(1,1)^\top, \mathbf{h}_2=(-1,0)^\top\) 之后多了一个全零 <PAD> 状态 \(\mathbf{h}_3 = (0, 0)^\top\),而开发者忘记添加 mask。请说明为什么即使 \(\mathbf{h}_3\) 为零向量,在 Bahdanau Attention 中它的分数 \(e_{t,3}\) 依然不会等于 \(0\)(甚至在许多位置还很大)?这种错误对 \(\mathbf{c}_t\) 与训练行为分别造成什么影响,以及与 Luong 点积注意力相比有什么不同?

参考解答与评分要点(先独立推导再展开)
  1. 为何 <PAD> 零向量分数非零(4 分):即使 \(\mathbf{h}_3 = \mathbf{0} \implies W_2 \mathbf{h}_3 = \mathbf{0}\),加性打分仍包含来自查询端的非零偏置项 \(W_1 \mathbf{s}_{t-1}\): \[e_{t,3} = \mathbf{v}_a^\top \tanh(W_1 \mathbf{s}_{t-1} + \mathbf{0}) = \mathbf{v}_a^\top \tanh\begin{pmatrix} 1.0 \\ 0.0 \end{pmatrix} = \tanh(1.0) \approx 0.761594\] 因为对所有有效词 \(e_{t,i}\) 与 <PAD> 位置 \(e_{t,3}\) 经过 \(\exp\) 后均严格为正,在本例中 <PAD> 强行拿到了 \(\alpha_{t,3} \approx 0.242705\) 的概率质量,导致上下文向量 \(\mathbf{c}_t\) 被人为乘以 \(1 - 0.242705 \approx 0.757\) 整体衰减!
  2. 与点积注意力对比(3 分):在无偏置点积注意力中 \(\mathbf{q}^\top \mathbf{0} = 0\),但 \(\exp(0) = 1 \neq 0\),所以只要不做 mask,点积注意力同样会把不可忽略的正权重分给零向量 <PAD>(尤其当其他词与 query 夹角大于 \(90^\circ\) 分数为负时,零向量的 \(0\) 分反而成了最高分!)。
  3. 修复方式(3 分):必须在 Softmax 之前对 <PAD> 位置执行 e = e.masked_fill(~mask, float('-inf'))(或混合精度安全极小值),使 \(\exp(-\infty) = 0\),既保证不占权重分母,也保证反向梯度完全不会流入填充槽位。

参考资料

经典教材与课程

  1. Jurafsky, D., & Martin, J. H. (2024). Speech and Language Processing (3rd ed. draft, Chapter 9/10 RNNs, Sequence-to-Sequence & Attention).

核心论文

  1. Brown, P. F. et al. (1993). The mathematics of statistical machine translation: Parameter estimation. Computational Linguistics, 19(2), 263–311.
  2. Cho, K. et al. (2014). Learning phrase representations using RNN encoder-decoder for statistical machine translation. EMNLP 2014.
  3. Sutskever, I., Vinyals, O., & Le, Q. V. (2014). Sequence to sequence learning with neural networks. NeurIPS 2014.
  4. Bahdanau, D., Cho, K., & Bengio, Y. (2015). Neural machine translation by jointly learning to align and translate. ICLR 2015 (arXiv:1409.0473).
  5. Luong, M.-T., Pham, H., & Manning, C. D. (2015). Effective approaches to attention-based neural machine translation. EMNLP 2015.
  6. Chorowski, J. K., Bahdanau, D., Serdyuk, D., Cho, K., & Bengio, Y. (2015). Attention-based models for speech recognition. NeurIPS 2015.
  7. Vinyals, O., Fortunato, M., & Jaitly, N. (2015). Pointer networks. NeurIPS 2015.
  8. Tu, Z., Lu, Z., Liu, Y., Liu, X., & Li, H. (2016). Modeling coverage for neural machine translation. ACL 2016.
  9. Wang, Y. et al. (2017). Tacotron: Towards end-to-end speech synthesis. Interspeech 2017.
  10. Vaswani, A. et al. (2017). Attention is all you need. NeurIPS 2017.
  11. Shen, J. et al. (2018). Natural TTS synthesis by conditioning WaveNet on mel spectrogram predictions (Tacotron 2). ICASSP 2018.
  12. Veličković, P. et al. (2018). Graph attention networks. ICLR 2018.
  13. Jain, S., & Wallace, B. C. (2019). Attention is not explanation. NAACL 2019.
  14. Wiegreffe, S., & Pinter, Y. (2019). Attention is not not explanation. EMNLP 2019.
  15. Wu, Y. et al. (2016). Google’s neural machine translation system: Bridging the gap between human and machine translation. arXiv:1609.08144(arXiv 预印本,未经 peer review).

开源实现与工具

  1. OpenNMT-py GlobalAttention(mlp / general / dot 三种评分模式参考实现)。
  2. PyTorch torch.nn.functional.scaled_dot_product_attention 与官方 Seq2Seq 文档。

← 上一篇:11|「注意力」的直觉:带宽、凸包寻址与短路径梯度 | 下一篇:13|Q/K/V 三件套:把 Bahdanau 抽象成一个公式 →

返回系列目录

文章导航

分类入口
transformer
标签入口
#transformer#attention#bahdanau#luong#additive-attention#nmt#seq2seq

读完这篇,下一步读什么

优先读同系列或同问题的下一篇,把单篇消费变成主题集群。


By .