デコーダ層にクロスアテンションを追加する
これまでに定義したエンコーダとデコーダのスタックをエンコーダ-デコーダ型トランスフォーマーに統合するには、両者を橋渡しする クロスアテンション機構 を作成する必要があります。
以前に定義した MultiHeadAttention クラスは引き続き使用できます。
この演習はコースの一部です
PyTorchで学ぶTransformerモデル
演習の手順
__init__メソッドで、クロスアテンション機構(MultiHeadAttentionの使用)と3つ目のレイヤー正規化(nn.LayerNormの使用)を定義します。- フォワードパスを完成させ、デコーダ層にクロスアテンションを追加します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
class DecoderLayer(nn.Module):
def __init__(self, d_model, num_heads, d_ff, dropout):
super().__init__()
self.self_attn = MultiHeadAttention(d_model, num_heads)
# Define cross-attention and a third layer normalization
self.cross_attn = ____
self.ff_sublayer = FeedForwardSubLayer(d_model, d_ff)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
self.norm3 = ____
self.dropout = nn.Dropout(dropout)
def forward(self, x, y, tgt_mask, cross_mask):
self_attn_output = self.self_attn(x, x, x, tgt_mask)
x = self.norm1(x + self.dropout(self_attn_output))
# Complete the forward pass
cross_attn_output = self.____(____)
x = self.norm2(x + self.dropout(____))
ff_output = self.ff_sublayer(x)
x = self.norm3(x + self.dropout(ff_output))
return x