開始使用免費開始

解碼器層

和編碼器 transformer 一樣,解碼器 transformer 也是由多個使用多頭注意力與前饋子層的層所組成。試著把這些元件組合起來,建立一個 DecoderLayer 類別。

系統已提供 MultiHeadAttentionFeedForwardSubLayer 類別可供使用,另外也會用到你建立的 tgt_mask

本練習屬於課程

Transformer Models with PyTorch

檢視課程

練習說明

完成 forward() 方法,將輸入的嵌入向量(embeddings)依照 __init__ 方法中定義的各層傳遞:

  • 使用提供的 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
編輯並執行程式碼