1. 从传统翻译模型说起
想象你要把英文句子"I love coding"翻译成中文。传统的循环神经网络(RNN)翻译模型就像一位只能记住前三个单词的翻译官:编码器把整个英文句子压缩成一个固定长度的记忆包(上下文向量),解码器再根据这个记忆包逐词生成中文翻译。
这种方法存在明显缺陷:当翻译到第四个中文词时,模型已经忘记了原始句子的开头部分。就像我们人类翻译时,会根据当前要翻译的部分动态回忆原句的相关位置,传统模型缺乏这种动态关注能力。
2. 注意力机制的灵感来源
2013年Graves在研究手写生成时,发现可以通过学习对齐的方式让生成笔画与文本对应。Bahdanau团队在此基础上改进,于2014年提出双向注意力机制,让模型在每个翻译步骤都能动态关注原文的不同部分。
这个机制就像给翻译模型装上了可调节的聚光灯:翻译每个词时,用光束扫描原文,重点照亮最相关的词语。
3. 模型架构解析
3.1 核心组件
-
编码器:双向RNN,输出每个单词的上下文信息(隐状态)
-
解码器:带有注意力层的RNN,动态组合编码器输出
3.2 注意力计算公式
当翻译第t个目标词时:
3.2.1 计算对齐分数(能量值):
- 参数说明:
- :解码器当前状态(查询向量),形状为
- 相当于问:"我现在需要关注源句子的哪个部分?"
- 示例值:假设,则
- :编码器第i个位置的隐状态(键/值向量),形状
- 存储源句子第i个位置的信息
- 示例:表示源句子第三个词的上下文信息
- :查询变换矩阵
- :键变换矩阵
- :偏置向量
- :能量转换向量
- :解码器当前状态(查询向量),形状为
- 计算过程:
- 将查询向量和键向量投影到相同空间:
- 通过tanh激活函数进行非线性变换
- 与向量v做点积,得到标量能量值
- 物理意义:衡量目标位置t与源位置i的关联强度。就像用探照灯扫描源句子时,能量值越大,该位置越亮。
3.2.2 通过softmax得到注意力权重:
-
参数说明:
- :源句子长度
- :指数函数,确保值为正数
-
计算特点:
- Softmax将能量值转换为概率分布
- 所有满足
-
物理意义:形成"注意力分布图",例如: 源句子:The cat sat on the mat 注意力权重:[0.02, 0.15, 0.7, 0.1, 0.02, 0.01] 表示模型在翻译当前词时,73%的注意力集中在"sat"上
3.2.3 生成上下文向量:
-
参数说明:
- :同步骤1中的编码器隐状态
- :步骤2得到的注意力权重
-
计算特点:
- 加权求和过程
- 结果的维度与相同
-
物理意义:生成动态上下文胶囊,例如:
# 假设源句子编码为: 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 注意力解码器类
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 前向传播过程
import torch
import d2l
encoder = d2l.Seq2SeqEncoder(vocab_size=10, embed_size=8, num_hiddens=16,
num_layers=2)
encoder.eval()
X = torch.zeros((4, 7), dtype=torch.long) # (batch_size, num_steps)
output, state = encoder(X)
print(output.shape) # torch.Size([7, 4, 16]) (num_steps, batch_size, num_hiddens)
print(state.shape) # torch.Size([2, 4, 16]) (num_layers, batch_size, num_hiddens)
decoder = d2l.Seq2SeqAttentionDecoder(vocab_size=10, embed_size=8, num_hiddens=16,
num_layers=2)
decoder.eval()
outputs, hidden_state, enc_valid_lens = decoder.init_state((output, state), None)
print(outputs.shape) # torch.Size([4, 7, 16]) (batch_size, num_steps, num_hiddens)
print(hidden_state.shape) # torch.Size([2, 4, 16]) (num_layers, batch_size, num_hiddens)
print(enc_valid_lens) # None
output, state = decoder(X, (outputs, hidden_state, enc_valid_lens))
print(output.shape, len(state), state[0].shape, len(state[1]), state[1][0].shape)
# output.shape : torch.Size([4, 7, 10]) (batch_size, num_steps, vocab_size)
# len(state) : 3 [enc_outputs, hidden_state, enc_valid_lens]
# state[0]: enc_outputs
# state[0].shape <==> enc_outputs.shape : torch.Size([4, 7, 16]) (batch_size, num_steps, num_hiddens)
# len(state[1]) <==> len(hidden_state) <==> num_layers : 2
# state[1][0].shape <==> hidden_state[0].shape : torch.Size([4, 16]) (batch_size, num_hiddens)
5. 训练与可视化
5.1 训练参数设置
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分数。
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 注意力权重可视化
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. 实际应用示例
# 伪代码
eng = "he's calm."
translation = model.predict(eng)
print(f"{eng} => {translation}")
输出结果:
he's calm. => il est calme.
此时模型的注意力分布为:
| 解码位置 | 关注源位置 | 权重值 |
|---|---|---|
| il | he's | 0.92 |
| est | he's | 0.85 |
| calme | calm | 0.96 |
7. 关键创新点总结
- 动态上下文生成:每个解码步骤生成独立的上下文向量
- 双向注意力:不受单向对齐限制,能捕捉前后文关系
- 可解释性强:通过注意力权重可视化理解模型决策