理解Bahdanau注意力机制:让机器翻译更智能

329 阅读6分钟

1. 从传统翻译模型说起

想象你要把英文句子"I love coding"翻译成中文。传统的循环神经网络(RNN)翻译模型就像一位只能记住前三个单词的翻译官:编码器把整个英文句子压缩成一个固定长度的记忆包(上下文向量),解码器再根据这个记忆包逐词生成中文翻译。

这种方法存在明显缺陷:当翻译到第四个中文词时,模型已经忘记了原始句子的开头部分。就像我们人类翻译时,会根据当前要翻译的部分动态回忆原句的相关位置,传统模型缺乏这种动态关注能力。

2. 注意力机制的灵感来源

2013年Graves在研究手写生成时,发现可以通过学习对齐的方式让生成笔画与文本对应。Bahdanau团队在此基础上改进,于2014年提出双向注意力机制,让模型在每个翻译步骤都能动态关注原文的不同部分。

这个机制就像给翻译模型装上了可调节的聚光灯:翻译每个词时,用光束扫描原文,重点照亮最相关的词语。

3. 模型架构解析

3.1 核心组件

  • 编码器:双向RNN,输出每个单词的上下文信息(隐状态)

    hi=[hi;hi]\boxed{h_i = [\overrightarrow{h_i}; \overleftarrow{h_i}]}

  • 解码器:带有注意力层的RNN,动态组合编码器输出

3.2 注意力计算公式

当翻译第t个目标词时:

3.2.1 计算对齐分数(能量值):

eti=vTtanh(Wqqt+Wkhi+b)\boxed{e_{ti} = v^T \tanh(W_q q_t + W_k h_i + b)}

  • 参数说明
    • qtq_t:解码器当前状态(查询向量),形状为dqd_q
      • 相当于问:"我现在需要关注源句子的哪个部分?"
      • 示例值:假设dq=256d_q=256,则qtR256q_t \in \mathbb{R}^{256}
    • hih_i:编码器第i个位置的隐状态(键/值向量),形状dhd_h
      • 存储源句子第i个位置的信息
      • 示例:hi=3h_{i=3}表示源句子第三个词的上下文信息
    • WqRda×dqW_q \in \mathbb{R}^{d_a \times d_q}:查询变换矩阵
    • WkRda×dhW_k \in \mathbb{R}^{d_a \times d_h}:键变换矩阵
    • bRdab \in \mathbb{R}^{d_a}:偏置向量
    • vRdav \in \mathbb{R}^{d_a}:能量转换向量
  • 计算过程
    1. 将查询向量和键向量投影到相同空间: 投影后=Wqqt+Wkhi+b\text{投影后} = W_q q_t + W_k h_i + b
    2. 通过tanh激活函数进行非线性变换
    3. 与向量v做点积,得到标量能量值
  • 物理意义:衡量目标位置t与源位置i的关联强度。就像用探照灯扫描源句子时,能量值越大,该位置越亮。

3.2.2 通过softmax得到注意力权重:

αti=exp(eti)j=1Texp(etj)\boxed{\alpha_{ti} = \frac{\exp(e_{ti})}{\sum_{j=1}^T \exp(e_{tj})}}

  • 参数说明

    • TT:源句子长度
    • exp\exp:指数函数,确保值为正数
  • 计算特点

    • Softmax将能量值转换为概率分布
    • 所有αti\alpha_{ti}满足i=1Tαti=1\sum_{i=1}^T \alpha_{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 生成上下文向量:

ct=i=1Tαtihi\boxed{c_t = \sum_{i=1}^T \alpha_{ti} h_i}

  • 参数说明

    • hih_i:同步骤1中的编码器隐状态
    • αti\alpha_{ti}:步骤2得到的注意力权重
  • 计算特点

    • 加权求和过程
    • 结果ctc_t的维度与hih_i相同
  • 物理意义:生成动态上下文胶囊,例如:

    # 假设源句子编码为:
    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"为"你好世界"为例:

解码步骤注意力焦点生成词语
1hello
2hello
3world世界

一个带有Bahdanau注意力的循环神经网络编码器-解码器模型:

seq2seq-attention-details.svg

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)

屏幕截图 2025-03-20 160852.png

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)

屏幕截图 2025-03-20 161200.png

模型训练后,我们用它将几个英语句子翻译成法语并计算它们的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}')

屏幕截图 2025-03-20 161411.png

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')

屏幕截图 2025-03-20 161612.png

6. 实际应用示例

# 伪代码
eng = "he's calm."
translation = model.predict(eng)
print(f"{eng} => {translation}")

输出结果:

he's calm. => il est calme.

此时模型的注意力分布为:

解码位置关注源位置权重值
ilhe's0.92
esthe's0.85
calmecalm0.96

7. 关键创新点总结

  1. 动态上下文生成:每个解码步骤生成独立的上下文向量
  2. 双向注意力:不受单向对齐限制,能捕捉前后文关系
  3. 可解释性强:通过注意力权重可视化理解模型决策