.. _sec_seq2seq_attention: Bahdanau 注意力 =============== :numref:`sec_seq2seq`\ 中探讨了机器翻译问题: 通过设计一个基于两个循环神经网络的编码器-解码器架构, 用于序列到序列学习。 具体来说,循环神经网络编码器将长度可变的序列转换为固定形状的上下文变量, 然后循环神经网络解码器根据生成的词元和上下文变量 按词元生成输出(目标)序列词元。 然而,即使并非所有输入(源)词元都对解码某个词元都有用, 在每个解码步骤中仍使用编码\ *相同*\ 的上下文变量。 有什么方法能改变上下文变量呢? 我们试着从 :cite:`Graves.2013`\ 中找到灵感: 在为给定文本序列生成手写的挑战中, Graves设计了一种可微注意力模型, 将文本字符与更长的笔迹对齐, 其中对齐方式仅向一个方向移动。 受学习对齐想法的启发,Bahdanau等人提出了一个没有严格单向对齐限制的 可微注意力模型 :cite:`Bahdanau.Cho.Bengio.2014`\ 。 在预测词元时,如果不是所有输入词元都相关,模型将仅对齐(或参与)输入序列中与当前预测相关的部分。这是通过将上下文变量视为注意力集中的输出来实现的。 模型 ---- 下面描述的Bahdanau注意力模型 将遵循 :numref:`sec_seq2seq`\ 中的相同符号表达。 这个新的基于注意力的模型与 :numref:`sec_seq2seq`\ 中的模型相同, 只不过 :eq:`eq_seq2seq_s_t`\ 中的上下文变量\ :math:`\mathbf{c}` 在任何解码时间步\ :math:`t'`\ 都会被\ :math:`\mathbf{c}_{t'}`\ 替换。 假设输入序列中有\ :math:`T`\ 个词元, 解码时间步\ :math:`t'`\ 的上下文变量是注意力集中的输出: .. math:: \mathbf{c}_{t'} = \sum_{t=1}^T \alpha(\mathbf{s}_{t' - 1}, \mathbf{h}_t) \mathbf{h}_t, 其中,时间步\ :math:`t' - 1`\ 时的解码器隐状态\ :math:`\mathbf{s}_{t' - 1}`\ 是查询, 编码器隐状态\ :math:`\mathbf{h}_t`\ 既是键,也是值, 注意力权重\ :math:`\alpha`\ 是使用 :eq:`eq_attn-scoring-alpha` 所定义的加性注意力打分函数计算的。 与 :numref:`fig_seq2seq_details`\ 中的循环神经网络编码器-解码器架构略有不同, :numref:`fig_s2s_attention_details`\ 描述了Bahdanau注意力的架构。 .. _fig_s2s_attention_details: .. figure:: ../img/seq2seq-attention-details.svg 一个带有Bahdanau注意力的循环神经网络编码器-解码器模型 .. raw:: latex \diilbookstyleinputcell .. code:: python import mlx import mlx.core as mx import mlx.nn as nn from d2l import mlx as d2l 定义注意力解码器 ---------------- 下面看看如何定义Bahdanau注意力,实现循环神经网络编码器-解码器。 其实,我们只需重新定义解码器即可。 为了更方便地显示学习的注意力权重, 以下\ ``AttentionDecoder``\ 类定义了带有注意力机制解码器的基本接口。 .. raw:: latex \diilbookstyleinputcell .. code:: python #@save class AttentionDecoder(d2l.Decoder): """带有注意力机制解码器的基本接口""" def __init__(self, **kwargs): super(AttentionDecoder, self).__init__(**kwargs) @property def attention_weights(self): raise NotImplementedError 接下来,让我们在接下来的\ ``Seq2SeqAttentionDecoder``\ 类中 实现带有Bahdanau注意力的循环神经网络解码器。 首先,初始化解码器的状态,需要下面的输入: 1. 编码器在所有时间步的最终层隐状态,将作为注意力的键和值; 2. 上一时间步的编码器全层隐状态,将作为初始化解码器的隐状态; 3. 编码器有效长度(排除在注意力池中填充词元)。 在每个解码时间步骤中,解码器上一个时间步的最终层隐状态将用作查询。 因此,注意力输出和输入嵌入都连结为循环神经网络解码器的输入。 .. raw:: latex \diilbookstyleinputcell .. code:: python #@save class Seq2SeqAttentionDecoder(AttentionDecoder): def __init__(self, num_inputs, vocab_size, embed_size, num_hiddens, num_layers, k_inputs, q_inputs, dropout=0): super().__init__() self.attention = d2l.AdditiveAttention(k_inputs, q_inputs, num_hiddens, dropout) self.embedding = nn.Embedding(vocab_size, embed_size) self.rnn = d2l.GRU( embed_size + num_hiddens, num_hiddens, num_layers, dropout=dropout) self.dense = nn.Linear(num_inputs, vocab_size) for module in self.modules(): if isinstance(module, nn.Linear) or isinstance(module, d2l.GRU): module.update(mlx.utils.tree_map(lambda x: d2l.init_seq2seq(x), module.parameters())) def init_state(self, enc_outputs, enc_valid_lens): # Shape of outputs: (num_steps, batch_size, num_hiddens). # Shape of hidden_state: (num_layers, batch_size, num_hiddens) outputs, hidden_state = enc_outputs return (outputs.transpose(1, 0, 2), hidden_state, enc_valid_lens) def __call__(self, X, state): # Shape of enc_outputs: (batch_size, num_steps, num_hiddens). # Shape of hidden_state: (num_layers, batch_size, num_hiddens) enc_outputs, hidden_state, enc_valid_lens = state # Shape of the output X: (num_steps, batch_size, embed_size) X = self.embedding(X).transpose(1, 0, 2) outputs, self._attention_weights = [], [] for x in X: # Shape of query: (batch_size, 1, num_hiddens) query = mx.expand_dims(hidden_state[-1], axis=1) # Shape of context: (batch_size, 1, num_hiddens) context = self.attention( query, enc_outputs, enc_outputs, enc_valid_lens) # Concatenate on the feature dimension x = mx.concatenate((context, mx.expand_dims(x, axis=1)), axis=-1) # Reshape x as (1, batch_size, embed_size + num_hiddens) out, hidden_state = self.rnn(x.transpose(1, 0, 2), hidden_state) outputs.append(out) self._attention_weights.append(self.attention.attention_weights) # After fully connected layer transformation, shape of outputs: # (num_steps, batch_size, vocab_size) outputs = self.dense(mx.concatenate(outputs, axis=0)) return outputs.transpose(1, 0, 2), [enc_outputs, hidden_state, enc_valid_lens] @property def attention_weights(self): return self._attention_weights 接下来,使用包含7个时间步的4个序列输入的小批量测试Bahdanau注意力解码器。 .. raw:: latex \diilbookstyleinputcell .. code:: python vocab_size, embed_size, num_hiddens, num_layers = 10, 8, 16, 2 batch_size, num_steps = 4, 7 num_inputs, k_inputs, q_inputs = 16, 16, 16 encoder = d2l.Seq2SeqEncoder(vocab_size, embed_size, num_hiddens, num_layers) decoder = Seq2SeqAttentionDecoder(num_inputs, vocab_size, embed_size, num_hiddens, num_layers, k_inputs, q_inputs) X = mx.zeros((batch_size, num_steps), dtype=mx.int64) state = decoder.init_state(encoder(X), None) output, state = decoder(X, state) d2l.check_shape(output, (batch_size, num_steps, vocab_size)) d2l.check_shape(state[0], (batch_size, num_steps, num_hiddens)) d2l.check_shape(state[1][0], (batch_size, num_hiddens)) 训练 ---- 与 :numref:`sec_seq2seq_training`\ 类似, 我们在这里指定超参数,实例化一个带有Bahdanau注意力的编码器和解码器, 并对这个模型进行机器翻译训练。 由于新增的注意力机制,训练要比没有注意力机制的 :numref:`sec_seq2seq_training`\ 慢得多。 .. raw:: latex \diilbookstyleinputcell .. code:: python data = d2l.MTFraEng(batch_size=128) embed_size, num_hiddens, num_layers, dropout = 256, 256, 2, 0.2 num_inputs, k_inputs, q_inputs = 256, 256, 256 encoder = d2l.Seq2SeqEncoder( len(data.src_vocab), embed_size, num_hiddens, num_layers, dropout) decoder = Seq2SeqAttentionDecoder( num_inputs, len(data.tgt_vocab), embed_size, num_hiddens, num_layers, k_inputs, q_inputs, dropout) model = d2l.Seq2Seq(encoder, decoder, tgt_pad=data.tgt_vocab[''], lr=0.001) trainer = d2l.Trainer(max_epochs=30, gradient_clip_val=1, num_gpus=1) trainer.fit(model, data) .. figure:: output_bahdanau-attention_b0c34d_9_0.svg 模型训练后,我们用它将几个英语句子翻译成法语并计算它们的BLEU分数。 .. raw:: latex \diilbookstyleinputcell .. code:: python engs = ['go .', 'i lost .', 'he\'s calm .', 'i\'m home .'] fras = ['va !', 'j\'ai perdu .', 'il est calme .', 'je suis chez moi .'] preds, _ = model.predict_step( data.build(engs, fras), d2l.try_gpu(), data.num_steps) preds = preds.tolist() for en, fr, p in zip(engs, fras, preds): translation = [] for token in data.tgt_vocab.to_tokens(p): if token == '': break translation.append(token) print(f'{en} => {translation}, bleu,' f'{d2l.bleu(" ".join(translation), fr, k=2):.3f}') .. raw:: latex \diilbookstyleoutputcell .. parsed-literal:: :class: output go . => ['va', '!'], bleu,1.000 i lost . => ["j'ai", 'perdu', '.'], bleu,1.000 he's calm . => ['elle', 'court', '.'], bleu,0.000 i'm home . => ['je', 'suis', 'chez', 'moi', '.'], bleu,1.000 .. raw:: latex \diilbookstyleinputcell .. code:: python _, dec_attention_weights = model.predict_step( data.build([engs[-1]], [fras[-1]]), d2l.try_gpu(), data.num_steps, True) attention_weights = mx.concatenate( [step[0][0][0] for step in dec_attention_weights], 0) attention_weights = attention_weights.reshape((1, 1, -1, data.num_steps)) 训练结束后,下面通过可视化注意力权重 会发现,每个查询都会在键值对上分配不同的权重,这说明 在每个解码步中,输入序列的不同部分被选择性地聚集在注意力池中。 .. raw:: latex \diilbookstyleinputcell .. code:: python # 加上一个包含序列结束词元 d2l.show_heatmaps( attention_weights[:, :, :, :len(engs[-1].split()) + 1], xlabel='Key positions', ylabel='Query positions') .. figure:: output_bahdanau-attention_b0c34d_14_0.svg 小结 ---- - 在预测词元时,如果不是所有输入词元都是相关的,那么具有Bahdanau注意力的循环神经网络编码器-解码器会有选择地统计输入序列的不同部分。这是通过将上下文变量视为加性注意力池化的输出来实现的。 - 在循环神经网络编码器-解码器中,Bahdanau注意力将上一时间步的解码器隐状态视为查询,在所有时间步的编码器隐状态同时视为键和值。 练习 ---- 1. 在实验中用LSTM替换GRU。 2. 修改实验以将加性注意力打分函数替换为缩放点积注意力,它如何影响训练效率?