เพิ่ม cross-attention ใน decoder layer
เพื่อรวม encoder stack และ decoder stack ที่กำหนดไว้ก่อนหน้านี้เข้าเป็น encoder-decoder transformer จำเป็นต้องสร้าง กลไก cross-attention เพื่อทำหน้าที่เป็นสะพานเชื่อมระหว่างทั้งสองส่วน
คลาส MultiHeadAttention ที่กำหนดไว้ก่อนหน้านี้ยังคงพร้อมใช้งาน
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Transformer Models ด้วย PyTorch
คำแนะนำการฝึกหัด
- กำหนดกลไก cross-attention (โดยใช้
MultiHeadAttention) และ layer normalization ชั้นที่สาม (โดยใช้nn.LayerNorm) ใน method__init__ - เติม forward pass ให้ครบเพื่อเพิ่ม cross-attention เข้าใน decoder layer
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
class DecoderLayer(nn.Module):
def __init__(self, d_model, num_heads, d_ff, dropout):
super().__init__()
self.self_attn = MultiHeadAttention(d_model, num_heads)
# Define cross-attention and a third layer normalization
self.cross_attn = ____
self.ff_sublayer = FeedForwardSubLayer(d_model, d_ff)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
self.norm3 = ____
self.dropout = nn.Dropout(dropout)
def forward(self, x, y, tgt_mask, cross_mask):
self_attn_output = self.self_attn(x, x, x, tgt_mask)
x = self.norm1(x + self.dropout(self_attn_output))
# Complete the forward pass
cross_attn_output = self.____(____)
x = self.norm2(x + self.dropout(____))
ff_output = self.ff_sublayer(x)
x = self.norm3(x + self.dropout(ff_output))
return x