Bahdanau 注意力

:label:sec_seq2seq_attention

我们在 :numref:sec_seq2seq中探讨了机器翻译问题: 通过设计一个基于两个循环神经网络的编码器-解码器架构, 用于序列到序列学习。 具体来说,循环神经网络编码器将长度可变的序列转换为固定形状的上下文变量, 然后循环神经网络解码器根据生成的词元和上下文变量 按词元生成输出(目标)序列词元。 然而,即使并非所有输入(源)词元都对解码某个词元都有用, 在每个解码步骤中仍使用编码相同的上下文变量。 有什么方法能改变上下文变量呢?

我们试着从 :cite:Graves.2013中找到灵感: 在为给定文本序列生成手写的挑战中, Graves设计了一种可微注意力模型, 将文本字符与更长的笔迹对齐, 其中对齐方式仅向一个方向移动。 受学习对齐想法的启发,Bahdanau等人提出了一个没有严格单向对齐限制的 可微注意力模型 :cite:Bahdanau.Cho.Bengio.2014。 在预测词元时,如果不是所有输入词元都相关,模型将仅对齐(或参与)输入序列中与当前预测相关的部分。这是通过将上下文变量视为注意力集中的输出来实现的。

模型

下面描述的Bahdanau注意力模型 将遵循 :numref:sec_seq2seq中的相同符号表达。 这个新的基于注意力的模型与 :numref:sec_seq2seq中的模型相同, 只不过 :eqref:eq_seq2seq_s_t中的上下文变量$\mathbf{c}$ 在任何解码时间步$t’$都会被$\mathbf{c}_{t’}$替换。 假设输入序列中有$T$个词元, 解码时间步$t’$的上下文变量是注意力集中的输出:

\mathbf{c}{t’} = \sum{t=1}^T \alpha(\mathbf{s}_{t’ - 1}, \mathbf{h}_t) \mathbf{h}_t,

其中,时间步$t’ - 1$时的解码器隐状态$\mathbf{s}_{t’ - 1}$是查询, 编码器隐状态$\mathbf{h}_t$既是键,也是值, 注意力权重$\alpha$是使用 :eqref:eq_attn-scoring-alpha 所定义的加性注意力打分函数计算的。

与 :numref:fig_seq2seq_details中的循环神经网络编码器-解码器架构略有不同, :numref:fig_s2s_attention_details描述了Bahdanau注意力的架构。

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

```{.python .input} from d2l import mxnet as d2l from mxnet import np, npx from mxnet.gluon import rnn, nn npx.set_np()

  1. ```{.python .input}
  2. #@tab pytorch
  3. from d2l import torch as d2l
  4. import torch
  5. from torch import nn

```{.python .input}

@tab tensorflow

from d2l import tensorflow as d2l import tensorflow as tf

  1. ## 定义注意力解码器
  2. 下面我们看看如何定义Bahdanau注意力,实现循环神经网络编码器-解码器。
  3. 其实,我们只需重新定义解码器即可。
  4. 为了更方便地显示学习的注意力权重,
  5. 以下`AttentionDecoder`类定义了[**带有注意力机制解码器的基本接口**]。
  6. ```{.python .input}
  7. #@tab all
  8. #@save
  9. class AttentionDecoder(d2l.Decoder):
  10. """带有注意力机制解码器的基本接口"""
  11. def __init__(self, **kwargs):
  12. super(AttentionDecoder, self).__init__(**kwargs)
  13. @property
  14. def attention_weights(self):
  15. raise NotImplementedError

接下来,让我们在接下来的Seq2SeqAttentionDecoder类中 [实现带有Bahdanau注意力的循环神经网络解码器]。 首先,我们初始化解码器的状态,需要下面的输入:

  1. 编码器在所有时间步的最终层隐状态,将作为注意力的键和值;
  2. 上一时间步的编码器全层隐状态,将作为初始化解码器的隐状态;
  3. 编码器有效长度(排除在注意力池中填充词元)。

在每个解码时间步骤中,解码器上一个时间步的最终层隐状态将用作查询。 因此,注意力输出和输入嵌入都连结为循环神经网络解码器的输入。

```{.python .input} class Seq2SeqAttentionDecoder(AttentionDecoder): def init(self, vocabsize, embedsize, num_hiddens, num_layers, dropout=0, **kwargs): super(Seq2SeqAttentionDecoder, self).__init(**kwargs) self.attention = d2l.AdditiveAttention(num_hiddens, dropout) self.embedding = nn.Embedding(vocab_size, embed_size) self.rnn = rnn.GRU(num_hiddens, num_layers, dropout=dropout) self.dense = nn.Dense(vocab_size, flatten=False)

  1. def init_state(self, enc_outputs, enc_valid_lens, *args):
  2. # outputs的形状为(num_steps,batch_size,num_hiddens)
  3. # hidden_state[0]的形状为(num_layers,batch_size,num_hiddens)
  4. outputs, hidden_state = enc_outputs
  5. return (outputs.swapaxes(0, 1), hidden_state, enc_valid_lens)
  6. def forward(self, X, state):
  7. # enc_outputs的形状为(batch_size,num_steps,num_hiddens).
  8. # hidden_state[0]的形状为(num_layers,batch_size,
  9. # num_hiddens)
  10. enc_outputs, hidden_state, enc_valid_lens = state
  11. # 输出X的形状为(num_steps,batch_size,embed_size)
  12. X = self.embedding(X).swapaxes(0, 1)
  13. outputs, self._attention_weights = [], []
  14. for x in X:
  15. # query的形状为(batch_size,1,num_hiddens)
  16. query = np.expand_dims(hidden_state[0][-1], axis=1)
  17. # context的形状为(batch_size,1,num_hiddens)
  18. context = self.attention(
  19. query, enc_outputs, enc_outputs, enc_valid_lens)
  20. # 在特征维度上连结
  21. x = np.concatenate((context, np.expand_dims(x, axis=1)), axis=-1)
  22. # 将x变形为(1,batch_size,embed_size+num_hiddens)
  23. out, hidden_state = self.rnn(x.swapaxes(0, 1), hidden_state)
  24. outputs.append(out)
  25. self._attention_weights.append(self.attention.attention_weights)
  26. # 全连接层变换后,outputs的形状为
  27. # (num_steps,batch_size,vocab_size)
  28. outputs = self.dense(np.concatenate(outputs, axis=0))
  29. return outputs.swapaxes(0, 1), [enc_outputs, hidden_state,
  30. enc_valid_lens]
  31. @property
  32. def attention_weights(self):
  33. return self._attention_weights
  1. ```{.python .input}
  2. #@tab pytorch
  3. class Seq2SeqAttentionDecoder(AttentionDecoder):
  4. def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,
  5. dropout=0, **kwargs):
  6. super(Seq2SeqAttentionDecoder, self).__init__(**kwargs)
  7. self.attention = d2l.AdditiveAttention(
  8. num_hiddens, num_hiddens, num_hiddens, dropout)
  9. self.embedding = nn.Embedding(vocab_size, embed_size)
  10. self.rnn = nn.GRU(
  11. embed_size + num_hiddens, num_hiddens, num_layers,
  12. dropout=dropout)
  13. self.dense = nn.Linear(num_hiddens, vocab_size)
  14. def init_state(self, enc_outputs, enc_valid_lens, *args):
  15. # outputs的形状为(batch_size,num_steps,num_hiddens).
  16. # hidden_state的形状为(num_layers,batch_size,num_hiddens)
  17. outputs, hidden_state = enc_outputs
  18. return (outputs.permute(1, 0, 2), hidden_state, enc_valid_lens)
  19. def forward(self, X, state):
  20. # enc_outputs的形状为(batch_size,num_steps,num_hiddens).
  21. # hidden_state的形状为(num_layers,batch_size,
  22. # num_hiddens)
  23. enc_outputs, hidden_state, enc_valid_lens = state
  24. # 输出X的形状为(num_steps,batch_size,embed_size)
  25. X = self.embedding(X).permute(1, 0, 2)
  26. outputs, self._attention_weights = [], []
  27. for x in X:
  28. # query的形状为(batch_size,1,num_hiddens)
  29. query = torch.unsqueeze(hidden_state[-1], dim=1)
  30. # context的形状为(batch_size,1,num_hiddens)
  31. context = self.attention(
  32. query, enc_outputs, enc_outputs, enc_valid_lens)
  33. # 在特征维度上连结
  34. x = torch.cat((context, torch.unsqueeze(x, dim=1)), dim=-1)
  35. # 将x变形为(1,batch_size,embed_size+num_hiddens)
  36. out, hidden_state = self.rnn(x.permute(1, 0, 2), hidden_state)
  37. outputs.append(out)
  38. self._attention_weights.append(self.attention.attention_weights)
  39. # 全连接层变换后,outputs的形状为
  40. # (num_steps,batch_size,vocab_size)
  41. outputs = self.dense(torch.cat(outputs, dim=0))
  42. return outputs.permute(1, 0, 2), [enc_outputs, hidden_state,
  43. enc_valid_lens]
  44. @property
  45. def attention_weights(self):
  46. return self._attention_weights

```{.python .input}

@tab tensorflow

class Seq2SeqAttentionDecoder(AttentionDecoder): def init(self, vocabsize, embedsize, numhiddens, num_layers, dropout=0, **kwargs): super().__init(**kwargs) self.attention = d2l.AdditiveAttention(num_hiddens, num_hiddens, num_hiddens, dropout) self.embedding = tf.keras.layers.Embedding(vocab_size, embed_size) self.rnn = tf.keras.layers.RNN(tf.keras.layers.StackedRNNCells( [tf.keras.layers.GRUCell(num_hiddens, dropout=dropout) for in range(num_layers)]), return_sequences=True, return_state=True) self.dense = tf.keras.layers.Dense(vocab_size)

  1. def init_state(self, enc_outputs, enc_valid_lens, *args):
  2. # outputs的形状为(num_steps,batch_size,num_hiddens)
  3. # hidden_state[0]的形状为(num_layers,batch_size,num_hiddens)
  4. outputs, hidden_state = enc_outputs
  5. return (outputs, hidden_state, enc_valid_lens)
  6. def call(self, X, state, **kwargs):
  7. # enc_outputs的形状为(batch_size,num_steps,num_hiddens)
  8. # hidden_state[0]的形状为(num_layers,batch_size, num_hiddens)
  9. enc_outputs, hidden_state, enc_valid_lens = state
  10. # 输出X的形状为(num_steps,batch_size,embed_size)
  11. X = self.embedding(X) # 输入X的形状为(batch_size,num_steps)
  12. X = tf.transpose(X, perm=(1, 0, 2))
  13. outputs, self._attention_weights = [], []
  14. for x in X:
  15. # query的形状为(batch_size,1,num_hiddens)
  16. query = tf.expand_dims(hidden_state[-1], axis=1)
  17. # context的形状为(batch_size,1,num_hiddens)
  18. context = self.attention(query, enc_outputs, enc_outputs,
  19. enc_valid_lens, **kwargs)
  20. # 在特征维度上连结
  21. x = tf.concat((context, tf.expand_dims(x, axis=1)), axis=-1)
  22. out = self.rnn(x, hidden_state, **kwargs)
  23. hidden_state = out[1:]
  24. outputs.append(out[0])
  25. self._attention_weights.append(self.attention.attention_weights)
  26. # 全连接层变换后,outputs的形状为(num_steps,batch_size,vocab_size)
  27. outputs = self.dense(tf.concat(outputs, axis=1))
  28. return outputs, [enc_outputs, hidden_state, enc_valid_lens]
  29. @property
  30. def attention_weights(self):
  31. return self._attention_weights
  1. 接下来,我们使用包含7个时间步的4个序列输入的小批量[**测试Bahdanau注意力解码器**]。
  2. ```{.python .input}
  3. encoder = d2l.Seq2SeqEncoder(vocab_size=10, embed_size=8, num_hiddens=16,
  4. num_layers=2)
  5. encoder.initialize()
  6. decoder = Seq2SeqAttentionDecoder(vocab_size=10, embed_size=8, num_hiddens=16,
  7. num_layers=2)
  8. decoder.initialize()
  9. X = d2l.zeros((4, 7)) # (batch_size,num_steps)
  10. state = decoder.init_state(encoder(X), None)
  11. output, state = decoder(X, state)
  12. output.shape, len(state), state[0].shape, len(state[1]), state[1][0].shape

```{.python .input}

@tab pytorch

encoder = d2l.Seq2SeqEncoder(vocab_size=10, embed_size=8, num_hiddens=16, num_layers=2) encoder.eval() decoder = Seq2SeqAttentionDecoder(vocab_size=10, embed_size=8, num_hiddens=16, num_layers=2) decoder.eval() X = d2l.zeros((4, 7), dtype=torch.long) # (batch_size,num_steps) state = decoder.init_state(encoder(X), None) output, state = decoder(X, state) output.shape, len(state), state[0].shape, len(state[1]), state[1][0].shape

  1. ```{.python .input}
  2. #@tab tensorflow
  3. encoder = d2l.Seq2SeqEncoder(vocab_size=10, embed_size=8, num_hiddens=16,
  4. num_layers=2)
  5. decoder = Seq2SeqAttentionDecoder(vocab_size=10, embed_size=8, num_hiddens=16,
  6. num_layers=2)
  7. X = tf.zeros((4, 7))
  8. state = decoder.init_state(encoder(X, training=False), None)
  9. output, state = decoder(X, state, training=False)
  10. output.shape, len(state), state[0].shape, len(state[1]), state[1][0].shape

[训练]

与 :numref:sec_seq2seq_training类似, 我们在这里指定超参数,实例化一个带有Bahdanau注意力的编码器和解码器, 并对这个模型进行机器翻译训练。 由于新增的注意力机制,训练要比没有注意力机制的 :numref:sec_seq2seq_training慢得多。

```{.python .input}

@tab all

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

  1. 模型训练后,我们用它[**将几个英语句子翻译成法语**]并计算它们的BLEU分数。
  2. ```{.python .input}
  3. #@tab mxnet, pytorch
  4. engs = ['go .', "i lost .", 'he\'s calm .', 'i\'m home .']
  5. fras = ['va !', 'j\'ai perdu .', 'il est calme .', 'je suis chez moi .']
  6. for eng, fra in zip(engs, fras):
  7. translation, dec_attention_weight_seq = d2l.predict_seq2seq(
  8. net, eng, src_vocab, tgt_vocab, num_steps, device, True)
  9. print(f'{eng} => {translation}, ',
  10. f'bleu {d2l.bleu(translation, fra, k=2):.3f}')

```{.python .input}

@tab tensorflow

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, True) print(f’{eng} => {translation}, ‘, f’bleu {d2l.bleu(translation, fra, k=2):.3f}’)

  1. ```{.python .input}
  2. #@tab all
  3. attention_weights = d2l.reshape(
  4. d2l.concat([step[0][0][0] for step in dec_attention_weight_seq], 0),
  5. (1, 1, -1, num_steps))

训练结束后,下面我们通过[可视化注意力权重] 你会发现,每个查询都会在键值对上分配不同的权重,这说明 在每个解码步中,输入序列的不同部分被选择性地聚集在注意力池中。

```{.python .input}

加上一个包含序列结束词元

d2l.show_heatmaps( attention_weights[:, :, :, :len(engs[-1].split()) + 1], xlabel=’Key positions’, ylabel=’Query positions’)

  1. ```{.python .input}
  2. #@tab pytorch
  3. # 加上一个包含序列结束词元
  4. d2l.show_heatmaps(
  5. attention_weights[:, :, :, :len(engs[-1].split()) + 1].cpu(),
  6. xlabel='Key positions', ylabel='Query positions')

```{.python .input}

@tab tensorflow

加上一个包含序列结束词元

d2l.show_heatmaps(attention_weights[:, :, :, :len(engs[-1].split()) + 1], xlabel=’Key posistions’, ylabel=’Query posistions’) ```

小结

  • 在预测词元时,如果不是所有输入词元都是相关的,那么具有Bahdanau注意力的循环神经网络编码器-解码器会有选择地统计输入序列的不同部分。这是通过将上下文变量视为加性注意力池化的输出来实现的。
  • 在循环神经网络编码器-解码器中,Bahdanau注意力将上一时间步的解码器隐状态视为查询,在所有时间步的编码器隐状态同时视为键和值。

练习

  1. 在实验中用LSTM替换GRU。
  2. 修改实验以将加性注意力打分函数替换为缩放点积注意力,它如何影响训练效率?

:begin_tab:mxnet Discussions :end_tab:

:begin_tab:pytorch Discussions :end_tab: