C.W.K.
Stream
Lesson 06 of 12 · published

Learned positional embedding (BERT, GPT-2)

~10 min · learned-pos, bert, gpt-2

Level 0Token
0 XP0/94 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

sinusoidal 인코딩의 가장 단순한 대안: token embedding처럼 위치별 embedding을 처음부터 학습. embedding 행렬 shape (max_seq_len × d_model). 위치 0은 자기 행, 위치 1은 자기 행, 등.

BERT랑 GPT-2가 이걸 써. 구현 간단, 학습 중 예측 가능한 동작, sinusoidal로는 못 잡는 위치 의존 패턴 잡을 수 있어(예: "위치 0은 항상 [CLS] 토큰 차지하니까 그 embedding이 특화 가능"). 비용: max_seq_len × d_model 파라미터 추가, 그리고 — 결정적으로 — max_seq_len 너머 외삽 불가. max_seq_len=1024로 학습된 모델은 위치 1500에 대한 embedding이 없어.

이 하드 캡 때문에 BERT(max 512)랑 GPT-2(max 1024)가 시대 대비 짧은 컨텍스트 가졌던 거야. 더 긴 컨텍스트 얻으려면 (a) 처음부터 긴 시퀀스로 사전학습, (b) 위치 embedding을 사후 보간하고 fine-tune("Position Interpolation" 기법), (c) 다른 위치 인코딩으로 통째 갈아치우기. 모던 LLM은 (c)를 골랐어.

Code

Learned positional embedding·python
import torch.nn as nn

class GPT2Embeddings(nn.Module):
    def __init__(self, vocab, d_model, max_len=1024):
        super().__init__()
        self.tok = nn.Embedding(vocab, d_model)
        self.pos = nn.Embedding(max_len, d_model)
        self.max_len = max_len
    def forward(self, ids):
        seq_len = ids.shape[-1]
        if seq_len > self.max_len:
            raise ValueError(f"seq {seq_len} > max_len {self.max_len}")
        positions = torch.arange(seq_len, device=ids.device)
        return self.tok(ids) + self.pos(positions)

External links

Exercise

GPT-2 로드해서 model.transformer.wpe.weight(학습된 positional embedding) 검사. shape는? 각 위치 벡터의 L2 norm을 위치에 대해 플롯. 어떤 위치가 다른 위치보다 더 '사용'되나? 이게 학습 분포에 대해 뭘 말해주나?

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.