nanoGPT 모델 구조 — GPT 모델 정의 읽기

nanoGPT 모델 구조

nanoGPT의 model.py는 GPT 언어 모델의 전체 정의를 단일 파일에 담아요. 코드가 곧 문서라고 할 만큼 구조가 명확해서, Transformer 디코더의 정수를 직접 따라갈 수 있어요.

출처: https://raw.githubusercontent.com/karpathy/nanoGPT/master/model.py

핵심 클래스

  • LayerNorm — 바이어스 선택이 가능한 레이어노름이에요.
  • CausalSelfAttention — 모든 헤드의 key/query/value를 c_attn 한 Linear로 한 번에 내보내고, 출력은 c_proj로 정리해요. PyTorch 2.0 이상에서는 scaled_dot_product_attention(Flash Attention)을 쓰고, 그렇지 않으면 하삼각 마스크(bias)로 수동 구현해요.
  • MLPc_fc → GELU → c_proj 구조의 피드포워드예요.
  • Blockx = x + attn(ln_1(x)), x = x + mlp(ln_2(x))의 잔차 블록이에요.

GPTConfig 기본값

GPTConfig의 기본값은 GPT-2와 맞아요.

@dataclass
class GPTConfig:
    block_size: int = 1024
    vocab_size: int = 50304  # GPT-2 vocab_size of 50257, padded up to nearest multiple of 64 for efficiency
    n_layer: int = 12
    n_head: int = 12
    n_embd: int = 768
    dropout: float = 0.0
    bias: bool = True  # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster

가중치 공유와 초기화

self.transformer.wte.weight = self.lm_head.weight로 토큰 임베딩과 LM 헤드를 공유(weight tying)하고, 잔차 투영은 GPT-2 논문대로 0.02/√(2·n_layer) 스케일로 초기화해요.

사전학습 로드

GPT.from_pretrainedgpt2, gpt2-medium, gpt2-large, gpt2-xl을 지원해요. 각각 124M/350M/774M/1558M 파라미터이고, vocab_size=50257, block_size=1024, bias=True로 고정돼요.

더 알아보기