시작하기무료로 시작하기

디코더 레이어에 교차-어텐션 추가하기

이전에 정의한 인코더와 디코더 스택을 하나의 인코더-디코더 트랜스포머로 통합하려면, 둘 사이를 이어 주는 교차-어텐션 메커니즘을 만들어야 해요.

이전에 정의한 MultiHeadAttention 클래스는 그대로 사용할 수 있어요.

이 연습은 강의의 일부입니다

PyTorch로 배우는 Transformer 모델

강의 보기

연습 안내

  • __init__ 메서드에서 교차-어텐션 메커니즘(MultiHeadAttention 사용)과 세 번째 레이어 정규화(nn.LayerNorm 사용)를 정의하세요.
  • forward 패스를 완성해 디코더 레이어에 교차-어텐션을 추가하세요.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

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
코드 편집 및 실행