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

Token ID와 embedding lookup

~10 min · token-ids, embedding

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

토큰화 후 모든 토큰은 vocab 테이블에서 가져온 unique 정수 ID를 가져. vocab은 학습 시점에 고정, 절대 안 바뀌어 — ID는 모델 평생 안정적.

모든 트랜스포머의 첫 연산은 embedding lookup이야 — 각 토큰 ID에 대해 embedding 행렬의 해당 행을 가져와. 행렬 shape은 (vocab_size × d_model). d_model=4096이면 index 47458이 4096차원 벡터를 반환. 그 벡터가 토큰 의미에 대한 모델의 첫 추측이고, 이후 layer들이 정제해.

기억할 두 가지. 첫째, embedding 행렬은 학습되는 거 — 다른 가중치들이랑 같이 업데이트. 둘째, 많은 모던 모델에서 input embedding 행렬과 output projection(logit → vocab)이 가중치를 공유해 — 이걸 weight tying이라 부르고, vocab × d_model 파라미터 절약 + "이 토큰을 어떻게 읽냐"와 "이 토큰을 어떻게 예측하냐"를 묶어.

Code

Embedding lookup is just a row index·python
import torch
import torch.nn as nn

vocab_size, d_model = 128_000, 4096
emb = nn.Embedding(vocab_size, d_model)

ids = torch.tensor([47458, 5614, 15592])      # 3 tokens
vectors = emb(ids)                              # (3, 4096)
# Internally: vectors = emb.weight[ids]         # advanced indexing
Weight tying (Llama 3, Mistral, GPT-2)·python
# input embedding and output head share the same matrix
class TiedTransformer(nn.Module):
    def __init__(self, vocab, d_model):
        super().__init__()
        self.emb = nn.Embedding(vocab, d_model)
        # ... transformer blocks ...
    def head(self, hidden):
        # Use embedding weight transposed as the output projection
        return hidden @ self.emb.weight.T   # (seq, vocab) logits

External links

Exercise

작은 open-weight 모델(예: huggingface gpt2) 로드. model.transformer.wte.weight(input embedding)랑 model.lm_head.weight(output head) shape 찍고, 같은 텐서(weight-tied)인지 독립인지 확인 — 한쪽 변형해보고 다른 쪽 어떻게 되는지 검사.

Progress

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

댓글 0

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

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