前饋子層
前饋子層會把注意力的輸出映射為抽象的非線性表示,以更好地捕捉複雜關係。
在這個練習中,你將為僅含編碼器的 transformer 建立一個 FeedForwardSubLayer。此層由兩個線性層組成,中間夾一個 ReLU 活化函式。它同時接收兩個參數 d_model 與 d_ff,分別代表輸入嵌入向量的維度,以及兩個線性層之間的維度。
d_model 與 d_ff 已經為你準備好可以使用。
本練習屬於課程
Transformer Models with PyTorch
練習說明
- 在前饋子層類別中,使用
d_model與層間維度d_ff,定義第一個與第二個線性層,以及 ReLU 活化函式。 - 在
forward()方法中,依序將輸入傳入各層與活化函式。 - 使用提供的
d_model與d_ff(分別為512與2048)實例化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}")