1. 从传统翻译模型说起
想象你要把英文句子"I love coding"翻译成中文。传统的循环神经网络(RNN)翻译模型就像一位只能记住前三个单词的翻译官:编码器把整个英文句子压缩成一个固定长度的记忆包(上下文向量),解码器再根据这个记忆包逐词生成中文翻译。
这种方法存在明显缺陷:当翻译到第四个中文词时,模型已经忘记了原始句子的开头部分。就像我们人类翻译时,会根据当前要翻译的部分动态回忆原句的相关位置,传统模型缺乏这种动态关注能力。
2. 注意力机制的灵感来源
2013年Graves在研究手写生成时,发现可以通过学习对齐 的方式让生成笔画与文本对应。Bahdanau团队在此基础上改进,于2014年提出双向注意力机制,让模型在每个翻译步骤都能动态关注原文的不同部分。
这个机制就像给翻译模型装上了可调节的聚光灯:翻译每个词时,用光束扫描原文,重点照亮最相关的词语。
3. 模型架构解析
3.1 核心组件
-
编码器:双向RNN,输出每个单词的上下文信息(隐状态)
<math xmlns="http://www.w3.org/1998/Math/MathML"> h i = [ h i → ; h i ← ] \boxed{h_i = [\overrightarrow{h_i}; \overleftarrow{h_i}]} </math>hi=[hi ;hi ]
-
解码器:带有注意力层的RNN,动态组合编码器输出
3.2 注意力计算公式
当翻译第t个目标词时:
3.2.1 计算对齐分数(能量值):
<math xmlns="http://www.w3.org/1998/Math/MathML"> e t i = v T tanh ( W q q t + W k h i + b ) \boxed{e_{ti} = v^T \tanh(W_q q_t + W_k h_i + b)} </math>eti=vTtanh(Wqqt+Wkhi+b)
- 参数说明 :
- <math xmlns="http://www.w3.org/1998/Math/MathML"> q t q_t </math>qt:解码器当前状态(查询向量),形状为 <math xmlns="http://www.w3.org/1998/Math/MathML"> d q d_q </math>dq
- 相当于问:"我现在需要关注源句子的哪个部分?"
- 示例值:假设 <math xmlns="http://www.w3.org/1998/Math/MathML"> d q = 256 d_q=256 </math>dq=256,则 <math xmlns="http://www.w3.org/1998/Math/MathML"> q t ∈ R 256 q_t \in \mathbb{R}^{256} </math>qt∈R256
- <math xmlns="http://www.w3.org/1998/Math/MathML"> h i h_i </math>hi:编码器第i个位置的隐状态(键/值向量),形状 <math xmlns="http://www.w3.org/1998/Math/MathML"> d h d_h </math>dh
- 存储源句子第i个位置的信息
- 示例: <math xmlns="http://www.w3.org/1998/Math/MathML"> h i = 3 h_{i=3} </math>hi=3表示源句子第三个词的上下文信息
- <math xmlns="http://www.w3.org/1998/Math/MathML"> W q ∈ R d a × d q W_q \in \mathbb{R}^{d_a \times d_q} </math>Wq∈Rda×dq:查询变换矩阵
- <math xmlns="http://www.w3.org/1998/Math/MathML"> W k ∈ R d a × d h W_k \in \mathbb{R}^{d_a \times d_h} </math>Wk∈Rda×dh:键变换矩阵
- <math xmlns="http://www.w3.org/1998/Math/MathML"> b ∈ R d a b \in \mathbb{R}^{d_a} </math>b∈Rda:偏置向量
- <math xmlns="http://www.w3.org/1998/Math/MathML"> v ∈ R d a v \in \mathbb{R}^{d_a} </math>v∈Rda:能量转换向量
- <math xmlns="http://www.w3.org/1998/Math/MathML"> q t q_t </math>qt:解码器当前状态(查询向量),形状为 <math xmlns="http://www.w3.org/1998/Math/MathML"> d q d_q </math>dq
- 计算过程 :
- 将查询向量和键向量投影到相同空间: <math xmlns="http://www.w3.org/1998/Math/MathML"> 投影后 = W q q t + W k h i + b \text{投影后} = W_q q_t + W_k h_i + b </math>投影后=Wqqt+Wkhi+b
- 通过tanh激活函数进行非线性变换
- 与向量v做点积,得到标量能量值
- 物理意义:衡量目标位置t与源位置i的关联强度。就像用探照灯扫描源句子时,能量值越大,该位置越亮。
3.2.2 通过softmax得到注意力权重:
<math xmlns="http://www.w3.org/1998/Math/MathML"> α t i = exp ( e t i ) ∑ j = 1 T exp ( e t j ) \boxed{\alpha_{ti} = \frac{\exp(e_{ti})}{\sum_{j=1}^T \exp(e_{tj})}} </math>αti=∑j=1Texp(etj)exp(eti)
-
参数说明:
- <math xmlns="http://www.w3.org/1998/Math/MathML"> T T </math>T:源句子长度
- <math xmlns="http://www.w3.org/1998/Math/MathML"> exp \exp </math>exp:指数函数,确保值为正数
-
计算特点:
- Softmax将能量值转换为概率分布
- 所有 <math xmlns="http://www.w3.org/1998/Math/MathML"> α t i \alpha_{ti} </math>αti满足 <math xmlns="http://www.w3.org/1998/Math/MathML"> ∑ i = 1 T α t i = 1 \sum_{i=1}^T \alpha_{ti} = 1 </math>∑i=1Tαti=1
-
物理意义:形成"注意力分布图",例如: 源句子:The cat sat on the mat 注意力权重:[0.02, 0.15, 0.7, 0.1, 0.02, 0.01] 表示模型在翻译当前词时,73%的注意力集中在"sat"上
3.2.3 生成上下文向量:
<math xmlns="http://www.w3.org/1998/Math/MathML"> c t = ∑ i = 1 T α t i h i \boxed{c_t = \sum_{i=1}^T \alpha_{ti} h_i} </math>ct=i=1∑Tαtihi
-
参数说明:
- <math xmlns="http://www.w3.org/1998/Math/MathML"> h i h_i </math>hi:同步骤1中的编码器隐状态
- <math xmlns="http://www.w3.org/1998/Math/MathML"> α t i \alpha_{ti} </math>αti:步骤2得到的注意力权重
-
计算特点:
- 加权求和过程
- 结果 <math xmlns="http://www.w3.org/1998/Math/MathML"> c t c_t </math>ct的维度与 <math xmlns="http://www.w3.org/1998/Math/MathML"> h i h_i </math>hi相同
-
物理意义:生成动态上下文胶囊,例如:
python# 假设源句子编码为: h = [0.2, 0.5, 0.9, 0.3] # 四个词的编码 alpha = [0.1, 0.1, 0.7, 0.1] c_t = 0.1*0.2 + 0.1*0.5 + 0.7*0.9 + 0.1*0.3 = 0.73
3.3 动态工作流程
以翻译"hello world"为"你好世界"为例:
解码步骤 | 注意力焦点 | 生成词语 |
---|---|---|
1 | hello | 你 |
2 | hello | 好 |
3 | world | 世界 |
一个带有Bahdanau注意力的循环神经网络编码器-解码器模型:
4. 代码实现解析
4.1 注意力解码器类
python
class AttentionDecoder(Decoder):
"""带有注意力机制解码器的基本接口"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
@property
def attention_weights(self):
raise NotImplementedError
class Seq2SeqAttentionDecoder(AttentionDecoder):
def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,
dropout=0, **kwargs):
super().__init__(**kwargs)
self.attention = AdditiveAttention(
num_hiddens, num_hiddens, num_hiddens, dropout)
self.embedding = nn.Embedding(vocab_size, embed_size)
self.rnn = nn.GRU(embed_size + num_hiddens, num_hiddens,
num_layers, dropout=dropout)
self.dense = nn.Linear(num_hiddens, vocab_size)
def init_state(self, enc_outputs, enc_valid_lens, *args):
# outputs的形状为(batch_size,num_steps,num_hiddens).
# hidden_state的形状为(num_layers,batch_size,num_hiddens)
outputs, hidden_state = enc_outputs
return outputs.permute(1, 0, 2), hidden_state, enc_valid_lens
def forward(self, X, state):
# enc_outputs的形状为(batch_size,num_steps,num_hiddens).
# hidden_state的形状为(num_layers,batch_size,
# num_hiddens)
enc_outputs, hidden_state, enc_valid_lens = state
# 输出X的形状为(num_steps,batch_size,embed_size)
X = self.embedding(X).permute(1, 0, 2)
outputs, self._attention_weights = [], []
for x in X:
# query的形状为(batch_size,1,num_hiddens)
query = torch.unsqueeze(hidden_state[-1], dim=1)
# context的形状为(batch_size,1,num_hiddens)
context = self.attention(
query, enc_outputs, enc_outputs, enc_valid_lens)
# 在特征维度上连结
x = torch.cat((context, torch.unsqueeze(x, dim=1)), dim=-1)
# 将x变形为(1,batch_size,embed_size+num_hiddens)
out, hidden_state = self.rnn(x.permute(1, 0, 2), hidden_state)
outputs.append(out)
self._attention_weights.append(self.attention.attention_weights)
# 全连接层变换后,outputs的形状为
# (num_steps,batch_size,vocab_size)
outputs = self.dense(torch.cat(outputs, dim=0))
return outputs.permute(1, 0, 2), [enc_outputs, hidden_state,
enc_valid_lens]
@property
def attention_weights(self):
return self._attention_weights
4.2 前向传播过程
python
import torch
import d2l
encoder = d2l.Seq2SeqEncoder(vocab_size=10, embed_size=8, num_hiddens=16,
num_layers=2)
encoder.eval()
decoder = d2l.Seq2SeqAttentionDecoder(vocab_size=10, embed_size=8, num_hiddens=16,
num_layers=2)
decoder.eval()
X = torch.zeros((4, 7), dtype=torch.long) # (batch_size,num_steps)
state = decoder.init_state(encoder(X), None)
output, state = decoder(X, state)
print(output.shape, len(state), state[0].shape, len(state[1]), state[1][0].shape)
5. 训练与可视化
5.1 训练参数设置
python
embed_size, num_hiddens, num_layers, dropout = 32, 32, 2, 0.1
batch_size, num_steps = 64, 10
lr, num_epochs, device = 0.005, 250, d2l.try_gpu()
train_iter, src_vocab, tgt_vocab = d2l.load_data_nmt(batch_size, num_steps)
encoder = d2l.Seq2SeqEncoder(
len(src_vocab), embed_size, num_hiddens, num_layers, dropout)
decoder = d2l.Seq2SeqAttentionDecoder(
len(tgt_vocab), embed_size, num_hiddens, num_layers, dropout)
net = d2l.EncoderDecoder(encoder, decoder)
d2l.train_seq2seq(net, train_iter, lr, num_epochs, tgt_vocab, device)
模型训练后,我们用它将几个英语句子翻译成法语并计算它们的BLEU分数。
python
engs = ['go .', "i lost .", 'he\'s calm .', 'i\'m home .']
fras = ['va !', 'j\'ai perdu .', 'il est calme .', 'je suis chez moi .']
for eng, fra in zip(engs, fras):
translation, dec_attention_weight_seq = d2l.predict_seq2seq(
net, eng, src_vocab, tgt_vocab, num_steps, device, True)
print(f'{eng} => {translation}, ',
f'bleu {d2l.bleu(translation, fra, k=2):.3f}')
5.2 注意力权重可视化
python
attention_weights = torch.cat([step[0][0][0] for step in dec_attention_weight_seq], 0).reshape((
1, 1, -1, num_steps))
# 加上一个包含序列结束词元
d2l.show_heatmaps(
attention_weights[:, :, :, :len(engs[-1].split()) + 1].cpu(),
xlabel='Key positions', ylabel='Query positions')
6. 实际应用示例
python
# 伪代码
eng = "he's calm."
translation = model.predict(eng)
print(f"{eng} => {translation}")
输出结果:
rust
he's calm. => il est calme.
此时模型的注意力分布为:
解码位置 | 关注源位置 | 权重值 |
---|---|---|
il | he's | 0.92 |
est | he's | 0.85 |
calme | calm | 0.96 |
7. 关键创新点总结
- 动态上下文生成:每个解码步骤生成独立的上下文向量
- 双向注意力:不受单向对齐限制,能捕捉前后文关系
- 可解释性强:通过注意力权重可视化理解模型决策