Feed-forward sublayers
Feed-forward sublayer ทำหน้าที่แมปผลลัพธ์จาก attention ให้เป็นการแทนค่าแบบนามธรรมและไม่เชิงเส้น เพื่อให้โมเดลสามารถจับความสัมพันธ์ที่ซับซ้อนได้ดียิ่งขึ้น
ในแบบฝึกหัดนี้ คุณจะสร้าง FeedForwardSubLayer สำหรับ encoder-only transformer ของคุณ เลเยอร์นี้ประกอบด้วยเลเยอร์เชิงเส้นสองชั้นโดยมี ReLU activation function คั่นกลาง และรับพารามิเตอร์สองตัว ได้แก่ d_model และ d_ff ซึ่งแทนมิติของ input embeddings และมิติระหว่างเลเยอร์เชิงเส้น ตามลำดับ
d_model และ d_ff พร้อมใช้งานแล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Transformer Models ด้วย PyTorch
คำแนะนำการฝึกหัด
- กำหนดเลเยอร์เชิงเส้นแรกและที่สอง รวมถึง ReLU activation สำหรับคลาส feed-forward sublayer โดยใช้
d_modelและมิติd_ffระหว่างเลเยอร์ - ส่งอินพุตผ่านเลเยอร์และ activation function ในเมธอด
forward() - สร้างอินสแตนซ์ของ
FeedForwardSubLayerโดยใช้d_modelและd_ffที่กำหนดไว้ (ตั้งค่าเป็น512และ2048ตามลำดับ) แล้วนำไปใช้กับ input embeddingsx
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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}")