开始使用免费开始使用

前馈子层

前馈子层会将注意力的输出映射为更抽象的非线性表示,从而更好地捕捉复杂关系。

在本练习中,您将为仅编码器的 Transformer 创建一个 FeedForwardSubLayer。该层由两个线性层组成,中间使用 ReLU 激活函数。它还接收两个参数 d_modeld_ff,分别表示输入嵌入的维度,以及两个线性层之间的中间维度。

d_modeld_ff 已为您提供,可直接使用。

本练习是课程的一部分

使用 PyTorch 的 Transformer 模型

查看课程

练习说明

  • 为前馈子层类定义第一个与第二个线性层,以及 ReLU 激活;层的输入输出使用 d_model,两层之间使用维度 d_ff
  • forward() 方法中,按顺序将输入依次通过这些线性层和激活函数。
  • 使用给定的 d_modeld_ff(分别为 5122048)实例化 FeedForwardSubLayer,并将其应用于输入嵌入 x

交互式实操练习

通过完成这段示例代码来试试这个练习。

class FeedForwardSubLayer(nn.Module):
    def __init__(self, d_model, d_ff):
        super().__init__()
        # Define the layers and activation
        self.fc1 = ____
        self.fc2 = ____
        self.relu = ____

    def forward(self, x):
        # Pass the input through the layers and activation
        return self.____(self.____(self.____(x)))
    
# Instantiate the FeedForwardSubLayer and apply it to x
feed_forward = ____
output = ____
print(f"Input shape: {x.shape}")
print(f"Output shape: {output.shape}")
编辑并运行代码