시작하기무료로 시작하기

디코더 트랜스포머 완성하기

이제 디코더 트랜스포머의 본체를 만들어 볼 차례예요! 앞에서 만든 InputEmbeddings, PositionalEncoding, DecoderLayer 클래스를 결합해 구현합니다.

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

PyTorch로 배우는 Transformer 모델

강의 보기

연습 안내

  • 리스트 컴프리헨션과 DecoderLayer 클래스를 사용해 num_layers 개의 디코더 레이어 리스트를 정의하세요.
  • 은닉 상태를 단어 확률로 투영할 선형 레이어를 정의하세요.
  • __init__에 정의한 레이어들을 따라 순전파를 완성하세요.
  • 디코더 트랜스포머를 인스턴스화하고 input_tokenstgt_mask에 적용하세요.

실습형 인터랙티브 연습

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

class TransformerDecoder(nn.Module):
    def __init__(self, vocab_size, d_model, num_layers, num_heads, d_ff, dropout, max_seq_length):
        super(TransformerDecoder, self).__init__()
        self.embedding = InputEmbeddings(vocab_size, d_model)
        self.positional_encoding = PositionalEncoding(d_model, max_seq_length)
        # Define the list of decoder layers and linear layer
        self.layers = nn.____([____(d_model, num_heads, d_ff, dropout) for _ in range(num_layers)])
        # Define a linear layer to project hidden states to likelihoods
        self.fc = ____
  
    def forward(self, x, tgt_mask):
        # Complete the forward pass
        x = self.____(x)
        x = self.____(x)
        for layer in self.layers:
            x = ____
        x = self.____(x)
        return F.log_softmax(x, dim=-1)

# Instantiate a decoder transformer and apply it to input_tokens and tgt_mask
transformer_decoder = ____(vocab_size, d_model, num_layers, num_heads, d_ff, dropout, max_seq_length)   
output = ____
print(output)
print(output.shape)
코드 편집 및 실행