デコーダーレイヤー
エンコーダートランスフォーマーと同様に、デコーダートランスフォーマーもマルチヘッドアテンションとフィードフォワードサブレイヤーを用いた複数のレイヤーで構成されます。これらのコンポーネントを組み合わせて、DecoderLayer クラスを作成してみましょう。
MultiHeadAttention と FeedForwardSubLayer クラス、そして作成済みの tgt_mask を利用できます。
この演習はコースの一部です
PyTorchで学ぶTransformerモデル
演習の手順
__init__ メソッドで定義したレイヤーを通して入力埋め込みを処理するように、forward() メソッドを完成させてください。
- 提供された
tgt_maskを用い、入力埋め込みxを query・key・value 行列として、アテンション計算を実行します。 dropoutと1つ目のレイヤー正規化norm1を適用します。- フィードフォワードサブレイヤー
ff_sublayerを通過させます。 dropoutと2つ目のレイヤー正規化norm2を適用します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
class DecoderLayer(nn.Module):
def __init__(self, d_model, num_heads, d_ff, dropout):
super().__init__()
self.self_attn = MultiHeadAttention(d_model, num_heads)
self.ff_sublayer = FeedForwardSubLayer(d_model, d_ff)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
self.dropout = nn.Dropout(dropout)
def forward(self, x, tgt_mask):
# Perform the attention calculation
attn_output = self.____
# Apply dropout and the first layer normalization
x = self.____(x + self.____(attn_output))
# Pass through the feed-forward sublayer
ff_output = self.____(x)
# Apply dropout and the second layer normalization
x = self.____(x + self.____(ff_output))
return x