임베딩과 위치 인코딩

PyTorch로 배우는 Transformer 모델

James Chapman

Curriculum Manager, DataCamp

트랜스포머의 임베딩과 위치 인코딩

 

  • 임베딩: 토큰 → 임베딩 벡터
  • 위치 인코딩: 토큰 위치 + 임베딩 벡터 → 위치 인코딩

트랜스포머에서 토큰 임베딩과 위치 인코딩 구성 요소가 강조 표시됨.

PyTorch로 배우는 Transformer 모델

시퀀스 임베딩

세 토큰: Hello, world, 느낌표.

PyTorch로 배우는 Transformer 모델

시퀀스 임베딩

세 토큰이 모델의 vocabulary에 따라 토큰 ID로 변환됩니다.

PyTorch로 배우는 Transformer 모델

시퀀스 임베딩

토큰 ID가 지정 차원의 벡터로 임베딩됩니다.

PyTorch로 배우는 Transformer 모델
import torch
import math
import torch.nn as nn

class InputEmbeddings(nn.Module):

def __init__(self, vocab_size: int, d_model: int) -> None: super().__init__() self.d_model = d_model self.vocab_size = vocab_size self.embedding = nn.Embedding(vocab_size, d_model)
def forward(self, x): return self.embedding(x) * math.sqrt(self.d_model)
  • 표준 관례: $\sqrt{d_{model}}$로 스케일링
PyTorch로 배우는 Transformer 모델

임베딩 생성하기

embedding_layer = InputEmbeddings(vocab_size=10_000, d_model=512)

embedded_output = embedding_layer(torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]))
print(embedded_output.shape)
torch.Size([2, 4, 512])
PyTorch로 배우는 Transformer 모델

위치 인코딩

토큰 임베딩과 위치 임베딩을 더해 입력 임베딩에 위치 정보를 추가합니다.

PyTorch로 배우는 Transformer 모델

위치 인코딩

홀수 인덱스는 sin, 짝수 인덱스는 cosine으로 위치 임베딩 값을 계산합니다.

PyTorch로 배우는 Transformer 모델

sin(x)

sin 함수.

 

$$ PE_{(pos, 2i)}=\sin(\frac{pos}{10000^{2i/d_{model}}}) $$

cos(x)

cosine 함수.

 

$$ PE_{(pos, 2i+1)}=\cos(\frac{pos}{10000^{2i/d_{model}}}) $$

PyTorch로 배우는 Transformer 모델

위치 인코더 구축하기

class PositionalEncoding(nn.Module):
    def __init__(self, d_model, max_seq_length):
        super().__init__()

        pe = torch.zeros(max_seq_length, d_model)

position = torch.arange(0, max_seq_length, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2, dtype=torch.float) * -(math.log(10000.0) / d_model)) pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position * div_term)
self.register_buffer('pe', pe.unsqueeze(0))
def forward(self, x): return x + self.pe[:, :x.size(1)]
PyTorch로 배우는 Transformer 모델

위치 인코딩 생성하기

pos_encoding_layer = PositionalEncoding(d_model=512, max_seq_length=4)

pos_encoded_output = pos_encoding_layer(embedded_output)
print(pos_encoded_output.shape)
torch.Size([2, 4, 512])
PyTorch로 배우는 Transformer 모델

Vamos praticar!

PyTorch로 배우는 Transformer 모델

Preparing Video For Download...