第11章注意機構とTransformer
11.7.6. Training11.7.6 訓練
Let’s instantiate an encoder–decoder model by following the Transformer architecture. Here we specify that both the Transformer encoder and the Transformer decoder have two layers using 4-head attention. As in Section 10.7.6, we train the Transformer model for sequence-to-sequence learning on the English–French machine translation dataset.
英語のヒント
Transformerの構造に従って、エンコーダ・デコーダのモデルをインスタンス化しよう。ここでは、Transformerのエンコーダとデコーダのどちらも、4ヘッドの注意を使う2層とする。10.7.6節と同じように、英語・フランス語の機械翻訳のデータセットで、Transformerのモデルを系列から系列への学習のために訓練する。
data = d2l.MTFraEng(batch_size=128)
num_hiddens, num_blks, dropout = 256, 2, 0.2
ffn_num_hiddens, num_heads = 64, 4
encoder = TransformerEncoder(
len(data.src_vocab), num_hiddens, ffn_num_hiddens, num_heads,
num_blks, dropout)
decoder = TransformerDecoder(
len(data.tgt_vocab), num_hiddens, ffn_num_hiddens, num_heads,
num_blks, dropout)
model = d2l.Seq2Seq(encoder, decoder, tgt_pad=data.tgt_vocab['<pad>'],
lr=0.001)
trainer = d2l.Trainer(max_epochs=30, gradient_clip_val=1, num_gpus=1)
trainer.fit(model, data)After training, we use the Transformer model to translate a few English sentences into French and compute their BLEU scores.
英語のヒント
訓練の後、Transformerのモデルを使っていくつかの英語の文をフランス語に翻訳し、それらのBLEUスコアを計算する。
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)
for en, fr, p in zip(engs, fras, preds):
translation = []
for token in data.tgt_vocab.to_tokens(p):
if token == '<eos>':
break
translation.append(token)
print(f'{en} => {translation}, bleu,'
f'{d2l.bleu(" ".join(translation), fr, k=2):.3f}')go . => ['va', '!'], bleu,1.000
i lost . => ['je', 'perdu', '.'], bleu,0.687
he's calm . => ['il', 'est', 'mouillé', '.'], bleu,0.658
i'm home . => ['je', 'suis', 'chez', 'moi', '.'], bleu,1.000Let’s visualize the Transformer attention weights when translating the final English sentence into French. The shape of the encoder self-attention weights is (number of encoder layers, number of attention heads,
num_steps or number of queries, num_steps or number of key-value pairs).英語のヒント
最後の英語の文をフランス語に翻訳するときの、Transformerの注意の重みを可視化しよう。エンコーダの自己注意の重みの形状は、(エンコーダの層の数、注意ヘッドの数、
num_stepsつまりクエリの数、num_stepsつまりキーとバリューの組の数)である。_, dec_attention_weights = model.predict_step(
data.build([engs[-1]], [fras[-1]]), d2l.try_gpu(), data.num_steps, True)
enc_attention_weights = torch.cat(model.encoder.attention_weights, 0)
shape = (num_blks, num_heads, -1, data.num_steps)
enc_attention_weights = enc_attention_weights.reshape(shape)
d2l.check_shape(enc_attention_weights,
(num_blks, num_heads, data.num_steps, data.num_steps))In the encoder self-attention, both queries and keys come from the same input sequence. Since padding tokens do not carry meaning, with specified valid length of the input sequence no query attends to positions of padding tokens. In the following, two layers of multi-head attention weights are presented row by row. Each head independently attends based on a separate representation subspace of queries, keys, and values.
英語のヒント
エンコーダの自己注意では、クエリとキーはどちらも同じ入力系列から来る。詰め物のトークンは意味を担わないので、入力系列の有効な長さを指定すれば、どのクエリも詰め物のトークンの位置には注意を向けない。以下では、マルチヘッド注意の重みの二つの層を行ごとに示す。各ヘッドは、クエリ、キー、バリューの別々の表現部分空間にもとづいて独立に注意を向ける。
d2l.show_heatmaps(
enc_attention_weights.cpu(), xlabel='Key positions',
ylabel='Query positions', titles=['Head %d' % i for i in range(1, 5)],
figsize=(7, 3.5))To visualize the decoder self-attention weights and the encoder–decoder attention weights, we need more data manipulations. For example, we fill the masked attention weights with zero. Note that the decoder self-attention weights and the encoder–decoder attention weights both have the same queries: the beginning-of-sequence token followed by the output tokens and possibly end-of-sequence tokens.
英語のヒント
デコーダの自己注意の重みとエンコーダ・デコーダ注意の重みを可視化するには、もっとデータの操作が必要になる。たとえば、マスクされた注意の重みを0で埋める。デコーダの自己注意の重みとエンコーダ・デコーダ注意の重みは、どちらも同じクエリをもつことに注意してほしい。系列の始まりを表すトークンの後に出力トークン、場合によっては系列の終わりを表すトークンが続くものである。
dec_attention_weights_2d = [head[0].tolist()
for step in dec_attention_weights
for attn in step for blk in attn for head in blk]
dec_attention_weights_filled = torch.tensor(
pd.DataFrame(dec_attention_weights_2d).fillna(0.0).values)
shape = (-1, 2, num_blks, num_heads, data.num_steps)
dec_attention_weights = dec_attention_weights_filled.reshape(shape)
dec_self_attention_weights, dec_inter_attention_weights = \
dec_attention_weights.permute(1, 2, 3, 0, 4)
d2l.check_shape(dec_self_attention_weights,
(num_blks, num_heads, data.num_steps, data.num_steps))
d2l.check_shape(dec_inter_attention_weights,
(num_blks, num_heads, data.num_steps, data.num_steps))Because of the autoregressive property of the decoder self-attention, no query attends to key–value pairs after the query position.
英語のヒント
デコーダの自己注意の自己回帰性のため、どのクエリも、クエリの位置より後のキーとバリューの組には注意を向けない。
d2l.show_heatmaps(
dec_self_attention_weights[:, :, :, :],
xlabel='Key positions', ylabel='Query positions',
titles=['Head %d' % i for i in range(1, 5)], figsize=(7, 3.5))Similar to the case in the encoder self-attention, via the specified valid length of the input sequence, no query from the output sequence attends to those padding tokens from the input sequence.
英語のヒント
エンコーダの自己注意の場合と同じように、入力系列の有効な長さを指定したことで、出力系列のどのクエリも、入力系列の詰め物のトークンには注意を向けない。
d2l.show_heatmaps(
dec_inter_attention_weights, xlabel='Key positions',
ylabel='Query positions', titles=['Head %d' % i for i in range(1, 5)],
figsize=(7, 3.5))Although the Transformer architecture was originally proposed for sequence-to-sequence learning, as we will discover later in the book, either the Transformer encoder or the Transformer decoder is often individually used for different deep learning tasks.
英語のヒント
Transformerの構造はもともと系列から系列への学習のために提案されたが、この本の後で見るように、Transformerのエンコーダかデコーダのどちらかが、さまざまな深層学習の課題に単独で使われることが多い。