解码器层
与编码器 Transformer 一样,解码器 Transformer 也由多个层构成,这些层会使用多头注意力和前馈子层。请尝试将这些组件组合起来,构建一个 DecoderLayer 类。
MultiHeadAttention 和 FeedForwardSubLayer 类已为您准备好可直接使用,同时还可以使用您创建的 tgt_mask。
本练习是课程的一部分
使用 PyTorch 的 Transformer 模型
练习说明
完成 forward() 方法,将输入嵌入向量依次通过 __init__ 方法中定义的各层:
- 使用给定的
tgt_mask和输入嵌入向量x作为查询、键、值矩阵进行注意力计算。 - 应用
dropout和第一个层归一化norm1。 - 通过前馈子层
ff_sublayer进行传递。 - 应用
dropout和第二个层归一化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