Bắt đầu ngayBắt đầu miễn phí

Thêm cross-attention vào tầng decoder

Để tích hợp các khối encoder và decoder mà bạn đã định nghĩa trước đó thành một transformer encoder–decoder, bạn cần tạo một cơ chế cross-attention đóng vai trò cầu nối giữa hai phần.

Lớp MultiHeadAttention bạn đã định nghĩa trước đó vẫn có sẵn.

Bài tập này là một phần của khóa học

Các mô hình Transformer với PyTorch

Xem khóa học

Hướng dẫn bài tập

  • Định nghĩa một cơ chế cross-attention (dùng MultiHeadAttention) và một lớp chuẩn hóa thứ ba (dùng nn.LayerNorm) trong phương thức __init__.
  • Hoàn thiện forward pass để thêm cross-attention vào tầng decoder.

Bài tập tương tác thực hành trực tiếp

Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.

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
Chỉnh sửa và Chạy Mã