开始使用免费开始使用

为解码器层添加交叉注意力

为了把您之前定义的编码器栈和解码器栈整合为一个编码器—解码器 Transformer,您需要创建一个充当两者桥梁的交叉注意力机制

您之前定义的 MultiHeadAttention 类仍可使用。

本练习是课程的一部分

使用 PyTorch 的 Transformer 模型

查看课程

练习说明

  • __init__ 方法中定义一个交叉注意力机制(使用 MultiHeadAttention)以及第三个层归一化(使用 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
编辑并运行代码