Seq2Seq & Attention 架构对比图解

包含单时间步单节点融合、精准数据流向与高清晰度双色调对比

Standard Model

1. 普通 Seq2Seq 全景架构 (Encoder-Decoder)

固定 Context Vector $c = h_{T_x}$

编码器按时序处理全部输入文本后,将整个序列的信息压缩并仅保留最后一个隐藏状态 $h_3$,作为固定的 Context Vector $c$ 传递给解码器作为初始隐藏状态。

Encoder (编码器) Input x₁ Input x₂ Input x₃ RNN (h₁) RNN (h₂) RNN (h₃) Context (c) c = h₃ (固定) Decoder (解码器) RNN (s₁) RNN (s₂) RNN (s₃) <BOS> Target y₁ Target y₂ Out y₁ Out y₂ Out y₃
Bahdanau Model

2. Bahdanau Attention (单时间步视角 Step $t$)

输入融合节点 $x_t = W_x [c_t ; y_{t-1}] + b_x$

数据流机制: 先由上一时刻解码器隐藏状态 $s_{t-1}$ 与编码器全部隐藏状态 $H$ 计算注意力得出 $c_t$。将 $c_t$ 与上一目标词 $y_{t-1}$ 输入统一的输入融合节点 (Linear Projection) 映射为 $x_t$,送入 Decoder RNN 更新得到当前状态 $s_t$,再由 $s_t$ 直连 Linear+Softmax 预测目标词 $y_t$。

Encoder Hidden States H = [h₁, h₂, h₃] h₁ h₂ h₃ 上一解码状态 s_{t-1} Attention Calculation e_{t,i} = v_aᵀ tanh(W_a s_{t-1} + U_a h_i) α_{t,i} = softmax(e_{t,i}) c_t = Σ α_{t,i} h_i s_{t-1} Context Vector c_t Target Input y_{t-1} 输入融合节点 (Fusion Node) x_t = W_x · [ c_t ; y_{t-1} ] + b_x Decoder RNN Cell s_t = RNN(s_{t-1}, x_t) 隐藏状态 s_{t-1} 传入 Output Prediction y_t Softmax(W_o · s_t + b_o)
Luong Model

3. Luong Attention (单时间步视角 Step $t$)

输出融合节点 $\tilde{s}_t = \tanh(W_c [c_t ; s_t] + b_c)$

数据流机制: 上一隐藏状态 $s_{t-1}$ 与上一目标词 Embedding $y_{t-1}$ 独立并行输入 Decoder RNN 产生当前状态 $s_t$。利用 $s_t$ 与编码器状态 $H$ 计算注意力得出 $c_t$。最后在 RNN 外部的输出注意力融合节点拼接 $c_t$ 与 $s_t$ 映射为 Attentional Hidden State $\tilde{s}_t$,并输入 Linear + Softmax 产生目标词 $y_t$。

Encoder Hidden States H = [h₁, h₂, h₃] h₁ h₂ h₃ State s_{t-1} Input y_{t-1} Decoder RNN Cell 生成当前隐藏状态 s_t Attention Calculation score(s_t, h_i) = s_tᵀ W_a h_i a_{t,i} = softmax(score) c_t = Σ a_{t,i} h_i s_t Context Vector c_t Current State s_t 输出融合节点 (Attentional State) s̃_t = tanh( W_c [ c_t ; s_t ] + b_c ) Output Prediction y_t Softmax( W_o · s̃_t + b_o )

3大 Seq2Seq 机制深度对比表

从编码器输出、解码步输入、Context 生成机制与最终输出映射彻底对比

数学级完整对齐
模型 编码器输出 解码器每一步的输入 上下文向量 Context ($c_t$) 解码器输出 (Decoder Output)
普通 Seq2Seq 所有隐藏状态,但通常只用最后一个状态传递语义 ($h_{T_x}$)。 上一时刻的目标词 Embedding ($y_{t-1}$) + 上一时刻隐藏状态 ($s_{t-1}$)。 编码结束后得到的固定语义表示,通常由编码器最终状态提供 ($c = h_{T_x}$)。 直接由当前隐藏状态映射输出:
$P(y_t) = \text{softmax}(W_o s_t + b_o)$
Bahdanau Attention 加法注意力 (Additive) 保留所有时间步的隐藏状态 $H = [h_1, h_2, \dots, h_{T_x}]$。 在 输入融合节点中拼接并线性变换 $y_{t-1}$ 与 $c_t$:
$x_t = W_x [c_t ; y_{t-1}] + b_x$
与上一时刻隐藏状态 $s_{t-1}$ 共同输入 RNN。
先使用上一时刻解码器状态 $s_{t-1}$ 与编码器全部隐藏状态计算注意力,加权求和得到 $c_t$。 由融入了 $c_t$ 信息的新隐藏状态 $s_t$ 直接映射输出:
$P(y_t) = \text{softmax}(W_o s_t + b_o)$
Luong Attention 乘法注意力 (Multiplicative) 保留所有时间步的隐藏状态 $H = [h_1, h_2, \dots, h_{T_x}]$。 目标词 Embedding ($y_{t-1}$) 与上一时刻隐藏状态 ($s_{t-1}$) 分开独立输入 RNN 计算出 $s_t$;随后再进行注意力融合。 先计算当前时刻解码器隐藏状态 $s_t$,再与编码器各状态计算注意力权重和 $c_t$。 在 输出融合节点 拼接 $c_t$ 与 $s_t$ 生成 Attentional State:
$\tilde{s}_t = \tanh(W_c [c_t ; s_t] + b_c)$
再过 Linear+Softmax 输出:
$P(y_t) = \text{softmax}(W_o \tilde{s}_t + b_o)$

关键区别总结: