第11章注意機構とTransformer
11.7.5. Decoder11.7.5 デコーダ
As shown in Fig. 11.7.1, the Transformer decoder is composed of multiple identical layers. Each layer is implemented in the following
TransformerDecoderBlock class, which contains three sublayers: decoder self-attention, encoder–decoder attention, and positionwise feed-forward networks. These sublayers employ a residual connection around them followed by layer normalization.英語のヒント
図11.7.1に示すように、Transformerのデコーダは同一の層を複数積み重ねたものである。各層は以下の
TransformerDecoderBlockクラスで実装され、三つの副層、デコーダの自己注意、エンコーダ・デコーダ注意、位置ごとのフィードフォワードネットワークを含む。これらの副層は、まわりに残差接続を使い、その後に層正規化を続ける。As we described earlier in this section, in the masked multi-head decoder self-attention (the first sublayer), queries, keys, and values all come from the outputs of the previous decoder layer. When training sequence-to-sequence models, tokens at all the positions (time steps) of the output sequence are known. However, during prediction the output sequence is generated token by token; thus, at any decoder time step only the generated tokens can be used in the decoder self-attention. To preserve autoregression in the decoder, its masked self-attention specifies
dec_valid_lens so that any query only attends to all positions in the decoder up to the query position.英語のヒント
この節の前のほうで説明したように、マスクつきのマルチヘッドのデコーダの自己注意(1番目の副層)では、クエリ、キー、バリューはすべて前のデコーダ層の出力から来る。系列から系列へのモデルを訓練するとき、出力系列のすべての位置(時間ステップ)のトークンはわかっている。しかし、予測のときには出力系列はトークンごとに生成される。そのため、デコーダのどの時間ステップでも、デコーダの自己注意で使えるのは生成済みのトークンだけである。デコーダで自己回帰を保つため、そのマスクつきの自己注意は
dec_valid_lensを指定し、どのクエリもデコーダのクエリの位置までのすべての位置にだけ注意を向けるようにする。class TransformerDecoderBlock(nn.Module):
# The i-th block in the Transformer decoder
def __init__(self, num_hiddens, ffn_num_hiddens, num_heads, dropout, i):
super().__init__()
self.i = i
self.attention1 = d2l.MultiHeadAttention(num_hiddens, num_heads,
dropout)
self.addnorm1 = AddNorm(num_hiddens, dropout)
self.attention2 = d2l.MultiHeadAttention(num_hiddens, num_heads,
dropout)
self.addnorm2 = AddNorm(num_hiddens, dropout)
self.ffn = PositionWiseFFN(ffn_num_hiddens, num_hiddens)
self.addnorm3 = AddNorm(num_hiddens, dropout)
def forward(self, X, state):
enc_outputs, enc_valid_lens = state[0], state[1]
# During training, all the tokens of any output sequence are processed
# at the same time, so state[2][self.i] is None as initialized. When
# decoding any output sequence token by token during prediction,
# state[2][self.i] contains representations of the decoded output at
# the i-th block up to the current time step
if state[2][self.i] is None:
key_values = X
else:
key_values = torch.cat((state[2][self.i], X), dim=1)
state[2][self.i] = key_values
if self.training:
batch_size, num_steps, _ = X.shape
# Shape of dec_valid_lens: (batch_size, num_steps), where every
# row is [1, 2, ..., num_steps]
dec_valid_lens = torch.arange(
1, num_steps + 1, device=X.device).repeat(batch_size, 1)
else:
dec_valid_lens = None
# Self-attention
X2 = self.attention1(X, key_values, key_values, dec_valid_lens)
Y = self.addnorm1(X, X2)
# Encoder-decoder attention. Shape of enc_outputs:
# (batch_size, num_steps, num_hiddens)
Y2 = self.attention2(Y, enc_outputs, enc_outputs, enc_valid_lens)
Z = self.addnorm2(Y, Y2)
return self.addnorm3(Z, self.ffn(Z)), stateTo facilitate scaled dot product operations in the encoder–decoder attention and addition operations in the residual connections, the feature dimension (
num_hiddens) of the decoder is the same as that of the encoder.英語のヒント
エンコーダ・デコーダ注意でのスケール化内積の演算と、残差接続での加算の演算をしやすくするため、デコーダの特徴量の次元(
num_hiddens)は、エンコーダのものと同じにする。decoder_blk = TransformerDecoderBlock(24, 48, 8, 0.5, 0)
X = torch.ones((2, 100, 24))
state = [encoder_blk(X, valid_lens), valid_lens, [None]]
d2l.check_shape(decoder_blk(X, state)[0], X.shape)Now we construct the entire Transformer decoder composed of
num_blks instances of TransformerDecoderBlock. In the end, a fully connected layer computes the prediction for all the vocab_size possible output tokens. Both of the decoder self-attention weights and the encoder–decoder attention weights are stored for later visualization.英語のヒント
では、
TransformerDecoderBlockのインスタンスnum_blks個からなる、Transformerのデコーダ全体を組み立てる。最後に、全結合層が、vocab_size個のありうる出力トークンすべてについての予測を計算する。デコーダの自己注意の重みとエンコーダ・デコーダ注意の重みは、どちらも後で可視化するために保存される。class TransformerDecoder(d2l.AttentionDecoder):
def __init__(self, vocab_size, num_hiddens, ffn_num_hiddens, num_heads,
num_blks, dropout):
super().__init__()
self.num_hiddens = num_hiddens
self.num_blks = num_blks
self.embedding = nn.Embedding(vocab_size, num_hiddens)
self.pos_encoding = d2l.PositionalEncoding(num_hiddens, dropout)
self.blks = nn.Sequential()
for i in range(num_blks):
self.blks.add_module("block"+str(i), TransformerDecoderBlock(
num_hiddens, ffn_num_hiddens, num_heads, dropout, i))
self.dense = nn.LazyLinear(vocab_size)
def init_state(self, enc_outputs, enc_valid_lens):
return [enc_outputs, enc_valid_lens, [None] * self.num_blks]
def forward(self, X, state):
X = self.pos_encoding(self.embedding(X) * math.sqrt(self.num_hiddens))
self._attention_weights = [[None] * len(self.blks) for _ in range (2)]
for i, blk in enumerate(self.blks):
X, state = blk(X, state)
# Decoder self-attention weights
self._attention_weights[0][
i] = blk.attention1.attention.attention_weights
# Encoder-decoder attention weights
self._attention_weights[1][
i] = blk.attention2.attention.attention_weights
return self.dense(X), state
@property
def attention_weights(self):
return self._attention_weights