시작하기무료로 시작하기

Positional encoding 만들기

토큰을 임베딩하는 것은 좋은 출발이지만, 아직 각 토큰의 시퀀스 내 위치 정보가 없습니다. 이를 보완하기 위해 transformer 아키텍처는 positional encoding을 사용해요. 각 토큰의 위치 정보를 임베딩에 인코딩하는 방식입니다.

다음 매개변수를 갖는 PositionalEncoding 클래스를 만들어 보세요:

  • d_model: 입력 임베딩의 차원 수
  • max_seq_length: 최대 시퀀스 길이(모든 시퀀스 길이가 같다면 해당 시퀀스 길이)

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

PyTorch로 배우는 Transformer 모델

강의 보기

연습 안내

  • max_seq_length × d_model 크기의 0으로 채운 행렬을 만드세요.
  • 짝수와 홀수 위치 임베딩 값을 만들기 위해 position * div_term에 대해 sine과 cosine 계산을 수행하세요.
  • 학습 중 pe가 학습 가능한 파라미터가 되지 않도록 하세요.
  • 변환된 positional embedding을 입력 토큰 임베딩 x에 더하세요.

실습형 인터랙티브 연습

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

class PositionalEncoding(nn.Module):
    def __init__(self, d_model, max_seq_length):
        super().__init__()
        # Create a matrix of zeros of dimensions max_seq_length by d_model
        pe = ____
        position = torch.arange(0, max_seq_length, dtype=torch.float).unsqueeze(1)
        div_term = torch.exp(torch.arange(0, d_model, 2).float() * -(math.log(10000.0) / d_model))
        
        # Perform the sine and cosine calculations
        pe[:, 0::2] = torch.____(position * div_term)
        pe[:, 1::2] = torch.____(position * div_term)
        # Ensure pe isn't a learnable parameter during training
        self.____('____', pe.unsqueeze(0))
        
    def forward(self, x):
        # Add the positional embeddings to the token embeddings
        return ____ + ____[:, :x.size(1)]

pos_encoding_layer = PositionalEncoding(d_model=512, max_seq_length=4)
output = pos_encoding_layer(token_embeddings)
print(output.shape)
print(output[0][0][:10])
코드 편집 및 실행