เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

Decoder layer

เช่นเดียวกับ encoder transformer decoder transformer ก็ประกอบด้วยหลายเลเยอร์ที่ใช้ multi-head attention และ feed-forward sublayer ลองนำคอมโพเนนต์เหล่านี้มารวมกันเพื่อสร้างคลาส DecoderLayer

คลาส MultiHeadAttention และ FeedForwardSubLayer พร้อมใช้งานแล้ว รวมถึง tgt_mask ที่สร้างไว้ก่อนหน้านี้

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Transformer Models ด้วย PyTorch

ดูคอร์ส

คำแนะนำการฝึกหัด

เติมโค้ดใน method forward() เพื่อส่ง input embedding ผ่านเลเยอร์ต่างๆ ที่กำหนดไว้ใน method __init__:

  • คำนวณ attention โดยใช้ tgt_mask ที่กำหนดให้ และ input embedding x สำหรับ query, key และ value matrix
  • ใช้ dropout และ layer normalization ชั้นแรก norm1
  • ส่งข้อมูลผ่าน feed-forward sublayer ff_sublayer
  • ใช้ dropout และ layer normalization ชั้นที่สอง 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
แก้ไขและรันโค้ด