始める無料で始める

デコーダーレイヤー

エンコーダートランスフォーマーと同様に、デコーダートランスフォーマーもマルチヘッドアテンションとフィードフォワードサブレイヤーを用いた複数のレイヤーで構成されます。これらのコンポーネントを組み合わせて、DecoderLayer クラスを作成してみましょう。

MultiHeadAttentionFeedForwardSubLayer クラス、そして作成済みの 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
コードを編集して実行