開始使用免費開始

在解碼器層加入交叉注意力

為了把你先前定義的編碼器與解碼器堆疊整合成一個編碼器—解碼器 transformer,你需要建立一個「交叉注意力機制」作為兩者之間的橋樑。

你先前定義的 MultiHeadAttention 類別仍可使用。

本練習屬於課程

Transformer Models with PyTorch

檢視課程

練習說明

  • __init__ 方法中定義交叉注意力機制(使用 MultiHeadAttention)以及第三個層正規化(使用 nn.LayerNorm)。
  • 完成 forward pass,將交叉注意力加入解碼器層。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

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
編輯並執行程式碼