11.2  디코더 전용 언어 모델(GPT)

단일 TransformerBlock(11.1절)은 \(d\) 차원 토큰 표현 시퀀스를 동일한 형상 \((B, T, d)\) 의 시퀀스로 사상합니다. 인과적 트랜스포머 블록 스택을 자기회귀 생성형 사전학습 트랜스포머(Generative Pre-trained Transformer, GPT) (Radford 기타 2018년, 2019년; Brown 기타 2020년) 로 만들려면 두 경계 층 사이에 \(L\) 개의 블록을 감싸 넣습니다(그림 11.2.1).

  1. 입력 임베딩: 토큰 임베딩 테이블 \(\mathbf{E} \in \mathbb{R}^{V \times d}\) 가 이산 토큰 ID \(x_1, \dots, x_T \in \{0, \dots, V-1\}\) 를 \(\mathbb{R}^d\) 의 벡터로 사상합니다(어텐션 내부에서 회전 위치 임베딩을 쓰지 않을 때는 학습된 절대 위치 임베딩 \(\mathbf{P} \in \mathbb{R}^{T_{\max} \times d}\) 를 선택적으로 더함).
  2. 최종 정규화와 언어 모델링 헤드: \(L\) 개의 인과적 TransformerBlock 층을 통과한 뒤 최종 정규화 층이 잔차 스트림 \(\mathbf{H}^{(L)}\) 을 안정화하고, 선형 헤드가 각 위치 \(t\) 를 다음 토큰 로짓 \(\mathbf{Z} = \textrm{Norm}(\mathbf{H}^{(L)})\mathbf{E}^\top \in \mathbb{R}^{B \times T \times V}\) 으로 투영합니다. 이때 출력 투영 가중치를 입력 임베딩 테이블 \(\mathbf{E}\) 와 공유(가중치 공유, weight tying)합니다 (Press 와/과 Wolf 2017년; Inan 기타 2017년).

11.2.1 블록에서 언어 모델로

그림 11.2.1: 아래에서 위로 따라가는 GPT 구조. 테이블 \(\mathbf{E}\) 가 토큰 ID를 잔차 스트림에 임베딩하고, \(L\) 개의 인과적 TransformerBlock 층이 스트림을 읽고 쓰며, 최종 정규화와 전치 테이블 \(\mathbf{E}^\top\) 가 각 위치의 벡터를 어휘 사전 전체의 로짓으로 변환합니다. 여기에 그린 현대 구성은 각 어텐션 층 내부에서 RoPE로 쿼리와 키를 회전시키며, GPT-2는 그 대신 최하단에서 학습된 위치 벡터를 한 번 더합니다.

각 블록 내부에서 CausalAttention은 쿼리, 키, 값 투영을 하나로 융합하고, 그룹 쿼리 어텐션(num_kv_heads \(\le\) num_heads, 10.3절)을 지원하며, 선택적으로 RoPE(rope=True, 10.4절)를 통해 쿼리와 키를 회전시키고, 위치 \(t\) 가 \(s \le t\) 인 위치에만 어텐션을 기울이도록 인과 마스크를 적용합니다.

class CausalAttention(nn.Module):
    """Fused causal self-attention, optionally rotary; num_kv_heads <
    num_heads shares each key-value head across a group of queries."""
    def __init__(self, num_hiddens, num_heads, *, bias=False, rope=False,
                 num_kv_heads=None):
        super().__init__()
        self.num_heads, self.rope = num_heads, rope
        self.num_kv_heads = num_kv_heads or num_heads
        self.kv_hiddens = self.num_kv_heads * (num_hiddens // num_heads)
        self.W_qkv = nn.Linear(num_hiddens, num_hiddens + 2 * self.kv_hiddens,
                               bias=bias)
        self.W_o = nn.Linear(num_hiddens, num_hiddens, bias=bias)

    def qkv(self, X, offset=0, tables=None):
        """Queries, keys, and values of X, each (batch, heads, length, head
        width), at positions offset, offset + 1, ...; tables, if given, are
        the d2l.rope_tables of these positions."""
        B, T, D = X.shape
        q, k, v = self.W_qkv(X).split([D, self.kv_hiddens, self.kv_hiddens],
                                      -1)
        q = q.reshape(B, T, self.num_heads, -1).transpose(1, 2)
        k, v = (u.reshape(B, T, self.num_kv_heads, -1).transpose(1, 2)
                for u in (k, v))
        if self.rope:
            q, k = (d2l.rope(u, offset, tables=tables) for u in (q, k))
        return q, k, v

    def forward(self, X, keys=None, values=None, mask=None, tables=None):
        # Self-attention: X also serves as the keys and the values, and the
        # mask is causal, so a block's mask argument must stay None
        if mask is not None:
            raise ValueError('CausalAttention applies its own mask')
        q, k, v = self.qkv(X, tables=tables)
        Y = F.scaled_dot_product_attention(
            q, k, v, is_causal=True,
            enable_gqa=self.num_kv_heads < self.num_heads)
        return self.W_o(Y.transpose(1, 2).flatten(2))  # (batch, length, d)
class CausalAttention(nnx.Module):
    """Causal self-attention, optionally rotary; num_kv_heads < num_heads
    shares each key-value head across a group of queries."""
    def __init__(self, num_hiddens, num_heads, *, bias=False, rope=False,
                 num_kv_heads=None, rngs):
        self.num_heads, self.rope = num_heads, rope
        self.num_kv_heads = num_kv_heads or num_heads
        self.kv_hiddens = self.num_kv_heads * (num_hiddens // num_heads)
        self.W_qkv = d2l.Linear(num_hiddens,
                                num_hiddens + 2 * self.kv_hiddens,
                                use_bias=bias, rngs=rngs)
        self.W_o = d2l.Linear(num_hiddens, num_hiddens, use_bias=bias,
                              rngs=rngs)

    def qkv(self, X, offset=0, tables=None):
        """Queries, keys, and values of X, each (batch, heads, length, head
        width), at positions offset, offset + 1, ...; tables, if given, are
        the d2l.rope_tables of these positions."""
        B, T, D = X.shape
        q, k, v = jnp.split(self.W_qkv(X), [D, D + self.kv_hiddens], axis=-1)
        q = q.reshape(B, T, self.num_heads, -1).swapaxes(1, 2)
        k, v = (u.reshape(B, T, self.num_kv_heads, -1).swapaxes(1, 2)
                for u in (k, v))
        if self.rope:
            q, k = (d2l.rope(u, offset, tables=tables) for u in (q, k))
        return q, k, v

    @staticmethod
    @jax.checkpoint  # The backward pass recomputes the T x T weights
    def attend(q, k, v):
        """Causal attention of (batch, length, heads, head width) queries,
        keys, and values."""
        return jax.nn.dot_product_attention(q, k, v, is_causal=True)

    def __call__(self, X, keys=None, values=None, mask=None, tables=None):
        # Self-attention: X also serves as the keys and the values, and the
        # mask is causal, so a block's mask argument must stay None
        if mask is not None:
            raise ValueError('CausalAttention applies its own mask')
        q, k, v = self.qkv(X, tables=tables)
        Y = self.attend(*(u.swapaxes(1, 2) for u in (q, k, v)))
        return self.W_o(Y.reshape(*X.shape[:2], -1))  # (batch, length, d)

GPT 클래스는 설정 가능한 TransformerBlock 모듈 num_blks개를 쌓고(기본값은 norm='rms', act='swiglu', pos='rope', pre_norm=True이며 GPT-2의 norm='layer', act='gelu', pos='learned', bias=True도 함께 지원함) 출력 투영 가중치를 토큰 임베딩 테이블 token_emb와 공유합니다.

class GPT(nn.Module):
    """Decoder-only transformer language model built from configurable
    blocks."""
    CausalAttention = CausalAttention  # A subclass may replace it

    def __init__(self, vocab_size, *, num_hiddens=256, num_heads=8,
                 num_blks=6, max_len=1024, pos='rope', norm='rms',
                 act='swiglu', pre_norm=True, bias=False, dropout=0,
                 num_kv_heads=None, ffn_factory=None):
        super().__init__()
        assert pos in ('rope', 'learned'), f'unknown pos: {pos!r}'
        self.pos, self.max_len, self.num_hiddens = pos, max_len, num_hiddens
        self.head_width = num_hiddens // num_heads
        self.token_emb = nn.Embedding(vocab_size, num_hiddens)
        nn.init.normal_(self.token_emb.weight, std=0.02)
        if pos == 'learned':
            self.pos_emb = nn.Embedding(max_len, num_hiddens)
            nn.init.normal_(self.pos_emb.weight, std=0.02)
        attn = lambda: self.CausalAttention(
            num_hiddens, num_heads, bias=bias, rope=pos == 'rope',
            num_kv_heads=num_kv_heads)
        self.blks = nn.ModuleList([
            d2l.TransformerBlock(num_hiddens, num_heads, dropout=dropout,
                                 norm=norm, act=act, pre_norm=pre_norm,
                                 bias=bias, attn_factory=attn,
                                 ffn_factory=ffn_factory)
            for _ in range(num_blks)])
        self.norm = (nn.RMSNorm if norm == 'rms'
                     else nn.LayerNorm)(num_hiddens, eps=1e-5)
        self.init_weights()

    def forward(self, X):                     # X: (batch, T) token ids
        H, tables = self.token_emb(X), None   # (batch, T, d)
        if self.pos == 'learned':
            H = H + self.pos_emb(torch.arange(X.shape[1], device=X.device))
        else:  # RoPE angles of positions 0, ..., T - 1, for every block
            tables = d2l.rope_tables(X.shape[1], self.head_width,
                                     device=X.device)
        for blk in self.blks:                 # L blocks, causal attention
            H = blk(H, tables=tables)
        return F.linear(self.norm(H), self.token_emb.weight)  # (batch, T, V)
class GPT(nnx.Module):
    """Decoder-only transformer language model built from configurable
    blocks."""
    CausalAttention = CausalAttention  # A subclass may replace it

    def __init__(self, vocab_size, *, num_hiddens=256, num_heads=8,
                 num_blks=6, max_len=1024, pos='rope', norm='rms',
                 act='swiglu', pre_norm=True, bias=False, dropout=0,
                 num_kv_heads=None, ffn_factory=None, rngs):
        assert pos in ('rope', 'learned'), f'unknown pos: {pos!r}'
        self.pos, self.max_len, self.num_hiddens = pos, max_len, num_hiddens
        self.head_width = num_hiddens // num_heads
        init = nnx.initializers.normal(0.02)
        self.token_emb = d2l.Embed(vocab_size, num_hiddens,
                                   embedding_init=init, rngs=rngs)
        if pos == 'learned':
            self.pos_emb = nnx.Embed(max_len, num_hiddens,
                                     embedding_init=init, rngs=rngs)
        attn = lambda rngs: self.CausalAttention(
            num_hiddens, num_heads, bias=bias, rope=pos == 'rope',
            num_kv_heads=num_kv_heads, rngs=rngs)
        self.blks = nnx.List([
            d2l.TransformerBlock(num_hiddens, num_heads, dropout=dropout,
                                 norm=norm, act=act, pre_norm=pre_norm,
                                 bias=bias, attn_factory=attn,
                                 ffn_factory=ffn_factory, rngs=rngs)
            for _ in range(num_blks)])
        self.norm = (nnx.RMSNorm if norm == 'rms'
                     else nnx.LayerNorm)(num_hiddens, epsilon=1e-5, rngs=rngs)
        self.init_weights(rngs)

    def __call__(self, X):                    # X: (batch, T) token ids
        H, tables = self.token_emb(X), None   # (batch, T, d)
        if self.pos == 'learned':
            H = H + self.pos_emb(jnp.arange(X.shape[1]))
        else:  # RoPE angles of positions 0, ..., T - 1, for every block
            tables = d2l.rope_tables(X.shape[1], self.head_width)
        for blk in self.blks:                 # L blocks, causal attention
            H = blk(H, tables=tables)
        return self.token_emb.attend(self.norm(H))  # (batch, T, V), tied

GPT-2 (Radford 기타 2019년) 및 11.1.2.2절 의 분석을 따라 init_weights는 선형 및 임베딩 가중치를 \(\mathcal{N}(0, 0.02^2)\) 에서 표집하되, 각 블록의 두 잔차 출력 투영(attention.W_o와 ffn.W_2)은 \(1 / \sqrt{2L}\) 배로 스케일링합니다.

@d2l.add_to_class(GPT)
def init_weights(self):
    """GPT-2's initialization of the linear layers: N(0, 0.02^2) weights and
    zero biases; W_o and W_2, which write to the stream, get std
    0.02 / sqrt(2L)."""
    L = len(self.blks)
    for name, m in self.named_modules():
        if isinstance(m, nn.Linear):
            std = 0.02 / (2 * L) ** 0.5 if name.endswith(
                ('W_o', 'W_2')) else 0.02
            nn.init.normal_(m.weight, std=std)
            if m.bias is not None:
                nn.init.zeros_(m.bias)
@d2l.add_to_class(GPT)
def init_weights(self, rngs):
    """GPT-2's initialization of the linear layers: N(0, 0.02^2) weights and
    zero biases; W_o and W_2, which write to the stream, get std
    0.02 / sqrt(2L)."""
    L = len(self.blks)
    for path, m in nnx.iter_graph(self):
        if isinstance(m, nnx.Linear):
            std = 0.02 / (2 * L) ** 0.5 if path[-1] in ('W_o', 'W_2') else 0.02
            m.kernel[...] = std * jax.random.normal(rngs.params(),
                                                    m.kernel.shape)
            if m.bias is not None:
                m.bias[...] = jnp.zeros(m.bias.shape)

11.2.2 WikiText-103에서 바이트 수준 GPT 학습하기

밑바닥부터 수행하는 실험을 외부 의존성 없이 완결적으로 유지하고 토크나이저에 따른 부수 효과를 배제하기 위해, 길이 \(T = 128\) 바이트인 윈도 \(B = 64\) 개로 이루어진 미니배치(스텝당 \(8{,}192\) 토큰)를 사용해 WikiText-103 (Merity 기타 2016년) 의 원시 UTF-8 바이트(\(V = 256\)) 위에서 직접 학습합니다.

data = d2l.WikiText103(batch_size=64, num_steps=128)
print(f'{len(data.train) / 1e6:.0f}M training bytes, '
      f'{len(data.val) / 1e6:.2f}M validation bytes, '
      f'vocabulary of {len(data.vocab)}')
270M training bytes, 1.14M validation bytes, vocabulary of 256
data = d2l.WikiText103(batch_size=64, num_steps=128)
print(f'{len(data.train) / 1e6:.0f}M training bytes, '
      f'{len(data.val) / 1e6:.2f}M validation bytes, '
      f'vocabulary of {len(data.vocab)}')
270M training bytes, 1.14M validation bytes, vocabulary of 256

또한 바로 학습에 투입할 수 있도록 새로 초기화된 GPT를 생성하는 편의 생성자 gpt(...)를 정의합니다.

gpt는 모델을 GPU로 옮기고 torch.compile로 컴파일하며 fp32 행렬 곱이 tf32 텐서 코어를 활용하도록 설정합니다.

gpt는 모델마다 d2l.get_key()에서 새로운 무작위 가중치를 표집합니다.

torch.set_float32_matmul_precision('high')  # fp32 matmuls may use tf32

def gpt(*args, **kwargs):  # A fresh model, on the GPU, compiled
    return torch.compile(GPT(*args, **kwargs).to(d2l.try_gpu()))
def gpt(*args, **kwargs):  # Fresh random weights for every model
    return GPT(*args, **kwargs, rngs=nnx.Rngs(d2l.get_key()))

11.2.2.1 자기회귀 목적 함수

입력 윈도 \(\mathbf{x} = (x_1, \dots, x_T)\) 와 한 칸 이동한 타깃 윈도 \(\mathbf{y} = (x_2, \dots, x_{T+1})\) 이 주어졌을 때, 인과 마스크는 출력 로짓의 \(t\) 번째 행 \(\mathbf{z}_t \in \mathbb{R}^V\) 이 오직 \((x_1, \dots, x_t)\) 에만 의존하도록 보장합니다. 학습 과정은 \(T\) 개 모든 위치에 걸친 평균 교차 엔트로피 손실을 병렬로 최소화합니다.

\[ \mathcal{L}(\boldsymbol{\theta}) = -\frac{1}{T}\sum_{t=1}^{T} \log \textrm{softmax}(\mathbf{z}_t)_{x_{t+1}}. \tag{11.2.1}\]

아무 학습도 일어나지 않은 초기화 시점에는 모델이 모든 바이트에 거의 균등한 확률 \(1/V\) 을 부여하므로, 초기 교차 엔트로피 손실은 \(\ln V = \ln 256 \approx 5.55\) nats/byte에 가깝습니다. 먼저 \(5 \times 5\) 하삼각 인과 마스크와 함께 한 칸 이동한 입력–타깃 윈도 쌍 (X[0], Y[0])을 살펴봅니다.

start = data.train.tobytes().find(b'the European lobster')
X, Y = data.windows(data.train, [start])  # One window and its targets
print('X[0]:', repr(data.vocab.decode(X[0, :24].tolist())))
print('Y[0]:', repr(data.vocab.decode(Y[0, :24].tolist())))
print(np.asarray(d2l.causal_mask(5)).astype(int))
X[0]: 'the European lobster ) a'
Y[0]: 'he European lobster ) an'
[[1 0 0 0 0]
 [1 1 0 0 0]
 [1 1 1 0 0]
 [1 1 1 1 0]
 [1 1 1 1 1]]
start = data.train.tobytes().find(b'the European lobster')
X, Y = data.windows(data.train, [start])  # One window and its targets
print('X[0]:', repr(data.vocab.decode(X[0, :24].tolist())))
print('Y[0]:', repr(data.vocab.decode(Y[0, :24].tolist())))
print(np.asarray(d2l.causal_mask(5)).astype(int))
X[0]: 'the European lobster ) a'
Y[0]: 'he European lobster ) an'
[[1 0 0 0 0]
 [1 1 0 0 0]
 [1 1 1 0 0]
 [1 1 1 1 0]
 [1 1 1 1 1]]

새로 초기화된 6-블록 GPT(약 \(\approx 4.79\textrm{M}\) 개 매개변수)를 검증 미니배치에서 평가하면 학습 전 교차 엔트로피가 \(\ln 256 \approx 5.55\) nats/byte 근처에 자리함을 확인할 수 있습니다.

model = gpt(len(data.vocab), max_len=128)
loss = math.log(d2l.lm_perplexity(model, [next(data.val_dataloader())]))
print(f'{d2l.num_params(model) / 1e6:.2f}M parameters; loss before '
      f'training {loss:.2f} nats per byte, log 256 = {math.log(256):.2f}')
4.79M parameters; loss before training 5.66 nats per byte, log 256 = 5.55
model = gpt(len(data.vocab), max_len=128)
loss = math.log(d2l.lm_perplexity(model, [next(data.val_dataloader())]))
print(f'{d2l.num_params(model) / 1e6:.2f}M parameters; loss before '
      f'training {loss:.2f} nats per byte, log 256 = {math.log(256):.2f}')
4.79M parameters; loss before training 5.51 nats per byte, log 256 = 5.55

11.2.2.2 학습 레시피(LMOptimizer)

현대 LLM 사전학습은 AdamW(9.5절, 기본적으로 표준 모멘텀 매개변수 \(\beta_1 = 0.9, \beta_2 = 0.999\) 를 쓰며 대규모 배치 실행에서는 \(\beta_2 = 0.95\) 사용)에 선택적 가중치 감쇠(임베딩, 편향, 1차원 정규화 스케일은 제외하고 2차원 선형 투영 행렬에만 가중치 감쇠 \(\lambda = 0.1\) 적용), 선형 웜업 후 코사인 학습률 감쇠(9.7절), 그리고 전역 그레이디언트 노름 클리핑(\(\|\nabla \mathcal{L}\|_2 \le 1.0\))을 결합합니다.

class LMOptimizer:
    """AdamW with weight decay on the weight matrices only, a linear warmup
    and a cosine decay of the learning rate, and gradient-norm clipping."""
    def __init__(self, model, lr, num_steps, warmup, weight_decay=0.1,
                 max_norm=1.0):
        named = list(model.named_parameters())
        # Embedding tables are named *emb* (token_emb, pos_emb) by convention
        decay = [p for n, p in named if p.ndim == 2 and 'emb' not in n]
        rest = [p for n, p in named if p.ndim != 2 or 'emb' in n]
        self.optimizer = torch.optim.AdamW(
            [{'params': decay, 'weight_decay': weight_decay},
             {'params': rest, 'weight_decay': 0.0}], lr=lr)
        self.scheduler = torch.optim.lr_scheduler.LambdaLR(
            self.optimizer, lambda t: d2l.cosine_warmup(t, num_steps, warmup))
        self.params, self.max_norm = decay + rest, max_norm

    def zero_grad(self):
        self.optimizer.zero_grad()

    def step(self):
        nn.utils.clip_grad_norm_(self.params, self.max_norm)
        self.optimizer.step()
        self.scheduler.step()
def lm_decay_mask(params):
    """Decay the weight matrices; exempt embeddings, gains, and biases."""
    # Embedding tables are named *emb* (token_emb, pos_emb) by convention
    return jax.tree_util.tree_map_with_path(
        lambda path, p: p.ndim == 2 and 'emb' not in str(path), params)

@optax.inject_hyperparams
def lm_adamw(lr=0.0, num_steps=1, warmup=0, weight_decay=0.0, max_norm=1.0):
    """The transformation of LMOptimizer, with its hyperparameters as state."""
    schedule = lambda t: lr * d2l.cosine_warmup(t, num_steps, warmup)
    return optax.chain(
        optax.clip_by_global_norm(max_norm),
        optax.adamw(schedule, weight_decay=weight_decay, mask=lm_decay_mask))

class LMOptimizer(nnx.Optimizer):
    """AdamW with weight decay on the weight matrices only, a linear warmup
    and a cosine decay of the learning rate, and gradient-norm clipping."""
    tx = lm_adamw()  # Shared by all instances: the step compiles once
    def __init__(self, model, lr, num_steps, warmup, weight_decay=0.1,
                 max_norm=1.0):
        super().__init__(model, LMOptimizer.tx, wrt=nnx.Param)
        hyperparams = dict(lr=lr, num_steps=num_steps, warmup=warmup,
                           weight_decay=weight_decay, max_norm=max_norm)
        for name, value in hyperparams.items():
            self.opt_state.hyperparams[name][...] = value

6-블록 바이트 수준 GPT(\(d = 256, H = 8, L = 6\), 약 \(\approx 4.8\textrm{M}\) 개 매개변수)를 1,000 스텝(약 \(\approx 8.2\textrm{M}\) 바이트) 동안 학습시키면 검증 교차 엔트로피가 영어 위키백과 텍스트의 경험적 유니그램 엔트로피(\(3.17\) nats/byte)와 경험적 바이그램 엔트로피(\(2.45\) nats/byte)보다 훨씬 낮은 수준까지 내려갑니다.

model = gpt(len(data.vocab), max_len=128)
num_steps, every = 1000, 50
optimizer = LMOptimizer(model, lr=2e-3, num_steps=num_steps, warmup=100)
steps, train_curve, val_curve, timer = [], [], [], d2l.Timer()
for step in range(every, num_steps + 1, every):
    timer.start()
    losses = d2l.train_steps(model, data, optimizer, every)
    timer.stop()  # Training time only, without the validation passes
    steps.append(step)
    train_curve.append(sum(losses) / every)
    val_curve.append(math.log(d2l.lm_perplexity(model, data.val_dataloader())))
d2l.plot(steps, [train_curve, val_curve], 'step', 'loss (nats)',
         legend=['train', 'validation'], fmts=('-', '--'))
print(f'step {num_steps}: train {train_curve[-1]:.2f}, '
      f'validation {val_curve[-1]:.2f} nats per byte; '
      f'{timer.sum():.0f} s of training')
step 1000: train 1.36, validation 1.34 nats per byte; 14 s of training

model = gpt(len(data.vocab), max_len=128)
num_steps, every = 1000, 50
optimizer = LMOptimizer(model, lr=2e-3, num_steps=num_steps, warmup=100)
steps, train_curve, val_curve, timer = [], [], [], d2l.Timer()
for step in range(every, num_steps + 1, every):
    timer.start()
    losses = d2l.train_steps(model, data, optimizer, every)
    timer.stop()  # Training time only, without the validation passes
    steps.append(step)
    train_curve.append(sum(losses) / every)
    val_curve.append(math.log(d2l.lm_perplexity(model, data.val_dataloader())))
d2l.plot(steps, [train_curve, val_curve], 'step', 'loss (nats)',
         legend=['train', 'validation'], fmts=('-', '--'))
print(f'step {num_steps}: train {train_curve[-1]:.2f}, '
      f'validation {val_curve[-1]:.2f} nats per byte; '
      f'{timer.sum():.0f} s of training')
step 1000: train 1.36, validation 1.35 nats per byte; 29 s of training

비교 기준을 삼기 위해 학습 말뭉치의 첫 \(10\textrm{M}\) 바이트에서 경험적 유니그램 및 바이그램 바이트 엔트로피를 직접 계산하여, 6-블록 트랜스포머가 국소적인 문자 통계를 얼마나 넘어서는지 확인해 봅니다.

text = data.train[:10**7].astype(np.int64)  # The first 10M training bytes
V = len(data.vocab)
unigram = np.bincount(text, minlength=V) / len(text)
pairs = np.bincount(text[:-1] * V + text[1:], minlength=V * V).reshape(V, V)
bigram = pairs / np.maximum(pairs.sum(1, keepdims=True), 1)
p = unigram[unigram > 0]
print(f'unigram {-(p * np.log(p)).sum():.2f}, '
      f'bigram {-np.log(bigram[text[:-1], text[1:]]).mean():.2f} '
      f'nats per byte')
unigram 3.17, bigram 2.45 nats per byte
text = data.train[:10**7].astype(np.int64)  # The first 10M training bytes
V = len(data.vocab)
unigram = np.bincount(text, minlength=V) / len(text)
pairs = np.bincount(text[:-1] * V + text[1:], minlength=V * V).reshape(V, V)
bigram = pairs / np.maximum(pairs.sum(1, keepdims=True), 1)
p = unigram[unigram > 0]
print(f'unigram {-(p * np.log(p)).sum():.2f}, '
      f'bigram {-np.log(bigram[text[:-1], text[1:]]).mean():.2f} '
      f'nats per byte')
unigram 3.17, bigram 2.45 nats per byte

11.2.3 통제된 비교 실험

11.2.3.1 실행 간 산포와 FFN 활성화 함수(SwiGLU 대 GELU)

무작위 시드 잡음과 실질적인 아키텍처 개선 효과를 구분하기 위해, 기본 SwiGLU 모델과 매개변수 수를 맞춘 GELU 모델(act='gelu')을 각각 독립적인 시드 세 개로 학습시킵니다.

def train_lm(model, data, lr=2e-3, num_steps=1000, warmup=100):
    """Train with the recipe of the main run; return milliseconds per step."""
    optimizer = LMOptimizer(model, lr=lr, num_steps=num_steps, warmup=warmup)
    # One untimed call of 50 steps warms up (JAX compiles), the rest is timed
    bench = d2l.Benchmark(lambda: d2l.train_steps(model, data, optimizer, 50),
                          warmup=1, repeats=num_steps // 50 - 1)
    return 1000 * bench.time / 50

runs = {'swiglu': [val_curve[-1]], 'gelu': []}  # The main run comes first
times = {'swiglu': [], 'gelu': []}  # Milliseconds per step
for act, repeats in (('swiglu', 2), ('gelu', 3)):
    for _ in range(repeats):
        net = gpt(len(data.vocab), act=act, max_len=128)
        times[act].append(train_lm(net, data))
        runs[act].append(math.log(d2l.lm_perplexity(net,
                                                    data.val_dataloader())))
    print(f'{act:>6} ({d2l.num_params(net):,} parameters): validation '
          + ', '.join(f'{v:.3f}' for v in runs[act])
          + f'; mean {np.mean(runs[act]):.3f}, range {np.ptp(runs[act]):.3f}')
swiglu (4,788,992 parameters): validation 1.339, 1.344, 1.343; mean 1.342, range 0.005
  gelu (4,787,456 parameters): validation 1.402, 1.402, 1.402; mean 1.402, range 0.000
def train_lm(model, data, lr=2e-3, num_steps=1000, warmup=100):
    """Train with the recipe of the main run; return milliseconds per step."""
    optimizer = LMOptimizer(model, lr=lr, num_steps=num_steps, warmup=warmup)
    # One untimed call of 50 steps warms up (JAX compiles), the rest is timed
    bench = d2l.Benchmark(lambda: d2l.train_steps(model, data, optimizer, 50),
                          warmup=1, repeats=num_steps // 50 - 1)
    return 1000 * bench.time / 50

runs = {'swiglu': [val_curve[-1]], 'gelu': []}  # The main run comes first
times = {'swiglu': [], 'gelu': []}  # Milliseconds per step
for act, repeats in (('swiglu', 2), ('gelu', 3)):
    for _ in range(repeats):
        net = gpt(len(data.vocab), act=act, max_len=128)
        times[act].append(train_lm(net, data))
        runs[act].append(math.log(d2l.lm_perplexity(net,
                                                    data.val_dataloader())))
    print(f'{act:>6} ({d2l.num_params(net):,} parameters): validation '
          + ', '.join(f'{v:.3f}' for v in runs[act])
          + f'; mean {np.mean(runs[act]):.3f}, range {np.ptp(runs[act]):.3f}')
swiglu (4,788,992 parameters): validation 1.347, 1.342, 1.348; mean 1.346, range 0.006
  gelu (4,787,456 parameters): validation 1.404, 1.398, 1.395; mean 1.399, range 0.009

무작위 시드에 따른 실행 간 변동 폭은 \(\sim 0.01\) nats/byte에 불과한 반면, 동일한 매개변수 및 FLOP 예산에서 SwiGLU는 GELU를 일관되게 \(\sim 0.06\) nats/byte 앞섭니다.

train_lm을 활용하면 11.1절 의 또 다른 설계 선택지인 정규화 배치도 검증할 수 있습니다. 초기화 시점만 놓고 보면 11.1.2.2절 에서 확인했듯 init_weights가 사용하는 가중치 스케일 \(0.02\) 에서는 사후 정규화에도 별다른 문제가 없었습니다. 토큰들은 서로 분리된 채 유지되고 쿼리 그레이디언트도 살아남습니다. 하지만 사후 정규화가 실제로 학습까지 똑같이 잘되는지는 별개의 문제입니다. 사후 정규화 블록(pre_norm=False)을 쓴 동일 모델을 웜업 500 스텝, 본 실험과 같은 100 스텝, 웜업 없음의 세 조건으로 학습시켜 봅시다. 최대 학습률은 세 실험 모두 본 실험과 동일합니다.

for warmup in (500, 100, 0):  # Post-norm: long, pre-norm's, and no warmup
    net = gpt(len(data.vocab), pre_norm=False, max_len=128)
    train_lm(net, data, warmup=warmup)
    loss = math.log(d2l.lm_perplexity(net, data.val_dataloader()))
    print(f'post-norm, warmup {warmup:>3}: validation {loss:.3f}')
post-norm, warmup 500: validation 1.381
post-norm, warmup 100: validation 3.174
post-norm, warmup   0: validation 3.174
for warmup in (500, 100, 0):  # Post-norm: long, pre-norm's, and no warmup
    net = gpt(len(data.vocab), pre_norm=False, max_len=128)
    train_lm(net, data, warmup=warmup)
    loss = math.log(d2l.lm_perplexity(net, data.val_dataloader()))
    print(f'post-norm, warmup {warmup:>3}: validation {loss:.3f}')
post-norm, warmup 500: validation 1.375
post-norm, warmup 100: validation 3.174
post-norm, warmup   0: validation 3.174

결과는 웜업 길이에 따라 갈립니다. 사전 정규화 모델을 바이트당 약 \(1.34\) nats까지 학습시켰던 100 스텝 웜업 조건에서 사후 정규화 모델은 \(3.17\) 에 머무르며, 웜업 없는 실행도 마찬가지입니다. 이 숫자는 앞서 계산한 유니그램 엔트로피와 정확히 같습니다. 즉, 이 두 모델은 각 바이트의 출현 빈도만 배웠을 뿐 선행 바이트에 대해서는 아무것도 배우지 못했습니다. 초기 업데이트가 너무 컸기 때문입니다. 몇 스텝 만에 학습률이 정점으로 치솟으면 어텐션과 FFN 서브층의 출력이 그것이 더해지는 정규화된 잔차 스트림보다 훨씬 커집니다. 그러면 뒤따르는 정규화 이후 모든 토큰이 거의 똑같은 최종 벡터로 수렴하고, 모든 위치에서 벡터가 같으니 바이트 빈도밖에 예측할 수 없게 됩니다. 토큰들을 다시 떼어 놓을 수 있는 그레이디언트 역시 토큰 산포와 함께 수축하므로(11.1.2.2절) 학습이 끝내 회복되지 않습니다.

웜업을 500 스텝으로 늘리면 서브층 출력이 스트림보다 작게 유지되어 사후 정규화 모델도 사전 정규화 모델보다 약간 뒤처지는 바이트당 약 \(1.38\) nats까지 학습됩니다. 결국 사전 정규화에는 충분한 웜업이 사후 정규화에는 부족합니다. 그 경계가 정확히 어디인지는 단정할 수 없습니다. 경계가 칼로 자르듯 뚜렷하지 않아서 중간 정도의 웜업 길이에서는 어떤 실행은 학습되고 어떤 실행은 붕괴하기 때문입니다. 이것이 바로 Xiong 기타 (2020년) 에서 원형 트랜스포머에 대해 보고한 현상입니다. 사후 정규화는 긴 웜업을 필요로 하는 반면, 사전 정규화는 웜업 없이도 학습되며 더 빠르게 수렴합니다.

11.2.3.2 동등 규모의 순환 신경망 기준선과의 비교

동일한 매개변수 수(\(d_{\textrm{rnn}} = 1920\), 약 \(\approx 4.7\textrm{M}\) 개 매개변수)와 학습 스텝이 주어졌을 때, 6-블록 GPT는 순환 언어 모델(d2l.RNNLM, 8.4.2절)과 비교해 어떤 성능을 보일까요? RNN 학습률을 \(\{10^{-3}, 2\times 10^{-3}, 4\times 10^{-3}\}\) 에 걸쳐 탐색하고 윈도 위치 \(t \in \{0, \dots, 127\}\) 에 따른 검증 손실(loss_by_position)을 비교해 봅니다.

def rnnlm(vocab_size, num_hiddens):  # The tanh RNN LM of the Basics
    return d2l.RNNLM(d2l.RNN(256, num_hiddens), vocab_size).to(d2l.try_gpu())

@torch.inference_mode()
def loss_by_position(model, data):
    """Mean validation loss in nats at each position of the window."""
    device = next(model.parameters()).device
    total, count = 0, 0
    for X, Y in data.val_dataloader():
        logits = model(X.to(device))  # (batch, T, V)
        total += F.cross_entropy(logits.transpose(1, 2), Y.to(device),
                                 reduction='none').sum(0)
        count += len(X)
    return (total / count).tolist()
def rnnlm(vocab_size, num_hiddens):  # The tanh RNN LM of the Basics
    rngs = nnx.Rngs(d2l.get_key())
    return d2l.RNNLM(d2l.RNN(256, num_hiddens, rngs=rngs), vocab_size,
                     rngs=rngs)

@nnx.jit
def position_loss_sum(model, X, Y):
    """Loss in nats at each position, summed over the batch."""
    return optax.softmax_cross_entropy_with_integer_labels(model(X), Y).sum(0)

def loss_by_position(model, data):
    """Mean validation loss in nats at each position of the window."""
    total, count = 0, 0
    for X, Y in data.val_dataloader():
        total += position_loss_sum(model, jnp.asarray(X), jnp.asarray(Y))
        count += len(X)
    return (total / count).tolist()

이제 후보 최대 학습률 \(\{10^{-3}, 2\times 10^{-3}, 4\times 10^{-3}\}\) 마다 두 개의 RNNLM 시드를 학습시키고, 가장 성능이 좋은 순환 신경망 실행을 윈도 위치 \(t \in \{0, 1, 4, 16, 64, 127\}\) 에 걸쳐 GPT와 비교합니다.

rnn_runs = []  # (validation loss, model, ms per step) of every run
for lr in (1e-3, 2e-3, 4e-3):
    for _ in range(2):
        rnn = rnnlm(len(data.vocab), 1920)
        ms = train_lm(rnn, data, lr=lr)
        rnn_runs.append((np.mean(loss_by_position(rnn, data)), rnn, ms))
    print(f'RNN ({d2l.num_params(rnn):,} parameters), peak rate {lr:g}: '
          'validation ' + ', '.join(f'{r[0]:.3f}' for r in rnn_runs[-2:]))
best = min(rnn_runs, key=lambda run: run[0])
positions = (0, 1, 4, 16, 64, 127)
print('validation loss at positions', ', '.join(map(str, positions)))
for name, net, ms in (('GPT', model, np.mean(times['swiglu'])),
                      ('best RNN', *best[1:])):
    loss = loss_by_position(net, data)
    print(f'{name:>8}: ' + ' '.join(f'{loss[t]:.2f}' for t in positions)
          + f'; {ms:.1f} ms per training step')
RNN (4,739,072 parameters), peak rate 0.001: validation 1.461, 1.461
RNN (4,739,072 parameters), peak rate 0.002: validation 1.474, 1.459
RNN (4,739,072 parameters), peak rate 0.004: validation 1.548, 1.649
validation loss at positions 0, 1, 4, 16, 64, 127
     GPT: 2.47 2.15 1.49 1.33 1.33 1.30; 14.1 ms per training step
best RNN: 2.49 2.15 1.56 1.45 1.45 1.44; 10.6 ms per training step
rnn_runs = []  # (validation loss, model, ms per step) of every run
for lr in (1e-3, 2e-3, 4e-3):
    for _ in range(2):
        rnn = rnnlm(len(data.vocab), 1920)
        ms = train_lm(rnn, data, lr=lr)
        rnn_runs.append((np.mean(loss_by_position(rnn, data)), rnn, ms))
    print(f'RNN ({d2l.num_params(rnn):,} parameters), peak rate {lr:g}: '
          'validation ' + ', '.join(f'{r[0]:.3f}' for r in rnn_runs[-2:]))
best = min(rnn_runs, key=lambda run: run[0])
positions = (0, 1, 4, 16, 64, 127)
print('validation loss at positions', ', '.join(map(str, positions)))
for name, net, ms in (('GPT', model, np.mean(times['swiglu'])),
                      ('best RNN', *best[1:])):
    loss = loss_by_position(net, data)
    print(f'{name:>8}: ' + ' '.join(f'{loss[t]:.2f}' for t in positions)
          + f'; {ms:.1f} ms per training step')
RNN (4,737,152 parameters), peak rate 0.001: validation 1.454, 1.463
RNN (4,737,152 parameters), peak rate 0.002: validation 1.444, 1.482
RNN (4,737,152 parameters), peak rate 0.004: validation 1.715, 1.608
validation loss at positions 0, 1, 4, 16, 64, 127
     GPT: 2.47 2.16 1.49 1.34 1.33 1.32; 13.0 ms per training step
best RNN: 2.50 2.15 1.54 1.44 1.44 1.42; 10.9 ms per training step

단 1바이트의 문맥만 주어지는 위치 \(t = 0\) 에서는 GPT와 RNNLM이 거의 동일한 손실에서 출발합니다. 그러나 앞선 프리픽스 문맥이 길어질수록(\(t \to 127\)) 트랜스포머의 검증 손실이 RNN보다 훨씬 가파르게 떨어집니다. 과거 이력을 \(t\) 번의 순차적 순환 스텝으로 압축해 전달하는 대신 셀프 어텐션이 임의의 이전 바이트를 \(O(1)\) 홉 만에 직접 읽어 오기 때문입니다.

11.2.4 모델에서 샘플링하기

자기회귀 생성(GPT.generate)은 한 번에 토큰 하나씩을 이어붙입니다. 매 스텝마다 현재 프리픽스를 모델에 통과시키고, 마지막 위치의 로짓 \(\mathbf{z}_t\) 를 온도(temperature) \(\tau > 0\) 으로 나눈 뒤, 선택적으로 가장 큰 상위-\(k\)(top-k)개 로짓을 제외한 나머지를 \(-\infty\) 로 마스킹하고 (Fan 기타 2018년), \(\textrm{softmax}(\mathbf{z}_t / \tau)\) 에서 다음 토큰을 표집합니다(\(\tau \to 0\) 극한인 탐욕적 디코딩은 top_k=1인 경우에 해당함).

@d2l.add_to_class(GPT)
@torch.inference_mode()
def generate(self, prefix, num_tokens, temperature=1.0, top_k=None):
    """Sample a continuation of the token-id list prefix."""
    ids = torch.tensor(prefix, device=next(self.parameters()).device)
    for _ in range(num_tokens):  # The tokens stay on the device
        logits = self(ids[None, -self.max_len:])[0, -1] / temperature
        if top_k is not None:
            cutoff = torch.topk(logits, top_k).values[-1]
            logits[logits < cutoff] = -torch.inf
        ids = torch.cat((ids, torch.multinomial(F.softmax(logits, -1), 1)))
    return ids.tolist()
@nnx.jit(static_argnames='top_k')
def _gpt_sample_next(model, buf, t, key, temperature, top_k):
    """Sample the token after the first t tokens of buf and append it.

    A full buffer (t equal to its length) drops its oldest token first."""
    logits = model(buf)[0, t - 1] / temperature
    if top_k is not None:
        cutoff = jax.lax.top_k(logits, top_k)[0][-1]
        logits = jnp.where(logits < cutoff, -jnp.inf, logits)
    token = jax.random.categorical(key, logits)
    n = buf.shape[1]
    buf = jnp.where(t == n, jnp.roll(buf, -1, axis=1), buf)
    return buf.at[0, jnp.minimum(t, n - 1)].set(token), token

@d2l.add_to_class(GPT)
def generate(self, prefix, num_tokens, temperature=1.0, top_k=None):
    """Sample a continuation of the token-id list prefix."""
    n, ctx = self.max_len, list(prefix)[-self.max_len:]
    # One buffer of fixed shape (1, max_len): the step compiles once
    buf, t = jnp.asarray([ctx + [0] * (n - len(ctx))]), len(ctx)
    tokens = []
    for key in jax.random.split(d2l.get_key(), num_tokens):
        buf, token = _gpt_sample_next(self, buf, t, key, temperature, top_k)
        tokens.append(token)
        t = min(t + 1, n)
    return list(prefix) + [int(i) for i in jax.device_get(tokens)]

세 가지 (temperature, top_k) 설정으로 'The history of the ' 뒤에 이어지는 120바이트를 샘플링해 보면, 낮은 온도와 상위-\(k\) 필터링이 다양성과 국소적 일관성 사이를 어떻게 절충하는지 확인할 수 있습니다.

prefix = data.vocab.encode('The history of the ')
for temperature, top_k in ((1.0, None), (0.7, 8), (2.0, None)):
    out = model.generate(prefix, 120, temperature=temperature, top_k=top_k)
    d2l.print_wrapped(f'T={temperature}, top_k={top_k}: '
                      + repr(data.vocab.decode(out)))
T=1.0, top_k=None: 'The history of the 2010 lead in Cecil . The shiwn trees
    about his improvement appearances helped attack actual film songs , were
    aportimely'
T=0.7, top_k=8: 'The history of the story to the ship wife . \n = = =
    Control = = = \n The contrast of the final part of the time , and
    interviewers , and the'
T=2.0, top_k=None: 'The history of the
    lar��\u038d\u038d���Е�;v���ױ����岙��Ӄ�\x1c,ϐ \n
    Trenreodoviti��Ě�\x08q���nve VS ÷tu KopaxodSq ;
    �t3nĀohjnetoKcckakizonþon U�6'
prefix = data.vocab.encode('The history of the ')
for temperature, top_k in ((1.0, None), (0.7, 8), (2.0, None)):
    out = model.generate(prefix, 120, temperature=temperature, top_k=top_k)
    d2l.print_wrapped(f'T={temperature}, top_k={top_k}: '
                      + repr(data.vocab.decode(out)))
T=1.0, top_k=None: 'The history of the 17th August Hackrulka – Africa in the
    WABI . " After played a " water had listing in view to a reverse task ,
    in the S'
T=0.7, top_k=8: 'The history of the side , when the former service of more
    society was really for the moved . The second became the ring of the
    central acti'
T=2.0, top_k=None: "The history of the tuh�ux Telecovcuvlly YotaNevofry
    Gate\x154��|�f Dudtlvbur\x1aet��2�� ' asprarx �ieques ou82CR Fl� Yez����
    hurri�Nfi wr�gmh si�"

11.2.5 사전학습된 GPT-2(124M) 불러오기

앞서 구현한 GPT 클래스는 norm='layer', act='gelu', pos='learned', bias=True를 지원하므로, OpenAI의 124M 매개변수 GPT-2 Small 아키텍처(\(V = 50{,}257, d = 768, H = 12, L = 12, T_{\max} = 1024\))를 그대로 인스턴스화하고 공식 model.safetensors 가중치와 바이트 수준 BPE 토크나이저(gpt2_tokenizer)를 직접 불러올 수 있습니다.

GPT2_URL = 'https://huggingface.co/openai-community/gpt2/resolve/main/'
d2l.DATA_HUB['gpt2-weights'] = (
    GPT2_URL + 'model.safetensors',
    '89a76996d7c6ee89b86618a265483aab73e61d50')
d2l.DATA_HUB['gpt2-merges'] = (
    GPT2_URL + 'merges.txt', '396d4d8ec90cb02f4d56e049e0e4add868bcd943')
d2l.DATA_HUB['gpt2-encoder'] = (
    GPT2_URL + 'vocab.json', 'f0223209235343bc067d7da838328bced8085ae1')

def gpt2_tokenizer():
    """GPT-2's byte-level BPE tokenizer, assembled by tiktoken."""
    import tiktoken  # lazy: d2l itself does not require tiktoken
    from tiktoken.load import data_gym_to_mergeable_bpe_ranks
    return tiktoken.Encoding(
        'gpt2', explicit_n_vocab=50257,
        pat_str=d2l.BPETokenizer.GPT2_PATTERN,
        mergeable_ranks=data_gym_to_mergeable_bpe_ranks(
            d2l.download('gpt2-merges', '../data/gpt2'),
            d2l.download('gpt2-encoder', '../data/gpt2')),
        special_tokens={'<|endoftext|>': 50256})

enc = gpt2_tokenizer()
ids = enc.encode('Attention is all you need.')
print(ids, [enc.decode([i]) for i in ids])
[8086, 1463, 318, 477, 345, 761, 13] ['Att', 'ention', ' is', ' all', ' you', ' need', '.']

GPT2_URL = 'https://huggingface.co/openai-community/gpt2/resolve/main/'
d2l.DATA_HUB['gpt2-weights'] = (
    GPT2_URL + 'model.safetensors',
    '89a76996d7c6ee89b86618a265483aab73e61d50')
d2l.DATA_HUB['gpt2-merges'] = (
    GPT2_URL + 'merges.txt', '396d4d8ec90cb02f4d56e049e0e4add868bcd943')
d2l.DATA_HUB['gpt2-encoder'] = (
    GPT2_URL + 'vocab.json', 'f0223209235343bc067d7da838328bced8085ae1')

def gpt2_tokenizer():
    """GPT-2's byte-level BPE tokenizer, assembled by tiktoken."""
    import tiktoken  # lazy: d2l itself does not require tiktoken
    from tiktoken.load import data_gym_to_mergeable_bpe_ranks
    return tiktoken.Encoding(
        'gpt2', explicit_n_vocab=50257,
        pat_str=d2l.BPETokenizer.GPT2_PATTERN,
        mergeable_ranks=data_gym_to_mergeable_bpe_ranks(
            d2l.download('gpt2-merges', '../data/gpt2'),
            d2l.download('gpt2-encoder', '../data/gpt2')),
        special_tokens={'<|endoftext|>': 50256})

enc = gpt2_tokenizer()
ids = enc.encode('Attention is all you need.')
print(ids, [enc.decode([i]) for i in ids])
[8086, 1463, 318, 477, 345, 761, 13] ['Att', 'ention', ' is', ' all', ' you', ' need', '.']
표 11.2.1: OpenAI GPT-2 safetensors 체크포인트 키와 GPT 모듈 속성의 대응 관계(Conv1D 가중치의 형상은 (in, out)임).
체크포인트 텐서 GPT 속성 비고
wte.weight token_emb 출력 헤드와 가중치 공유 (V x d)
wpe.weight pos_emb 학습된 위치 벡터 1,024개
h.i.ln_1, h.i.ln_2 blks[i].norm1, blks[i].norm2 어텐션 전·FFN 전 LayerNorm
h.i.attn.c_attn blks[i].attention.W_qkv 융합 QKV (Conv1D)
h.i.attn.c_proj blks[i].attention.W_o 출력 투영 (Conv1D)
h.i.mlp.c_fc, h.i.mlp.c_proj blks[i].ffn.W_1, blks[i].ffn.W_2 2층 GELU MLP (Conv1D)
ln_f norm 출력 헤드 직전의 최종 LayerNorm

nn.Linear는 (out, in) 형상으로 저장하므로 load_gpt2는 모든 Conv1D 가중치를 전치합니다.

nnx.Linear 커널은 Conv1D와 같은 (in, out) 레이아웃이므로 load_gpt2는 가중치를 그대로 복사합니다.

def load_gpt2():
    """GPT-2 small (124M) as a GPT with the released weights, in eval
    mode."""
    from safetensors.torch import load_file  # lazy, like tiktoken above
    gpt2 = GPT(vocab_size=50257, num_hiddens=768, num_heads=12, num_blks=12,
               max_len=1024, pos='learned', norm='layer', act='gelu',
               pre_norm=True, bias=True)
    weights = load_file(d2l.download('gpt2-weights', '../data/gpt2'))
    with torch.no_grad():
        gpt2.token_emb.weight.copy_(weights['wte.weight'])
        gpt2.pos_emb.weight.copy_(weights['wpe.weight'])
        gpt2.norm.weight.copy_(weights['ln_f.weight'])
        gpt2.norm.bias.copy_(weights['ln_f.bias'])
        for i, blk in enumerate(gpt2.blks):
            modules = {f'h.{i}.ln_1': blk.norm1, f'h.{i}.ln_2': blk.norm2,
                       f'h.{i}.attn.c_attn': blk.attention.W_qkv,
                       f'h.{i}.attn.c_proj': blk.attention.W_o,
                       f'h.{i}.mlp.c_fc': blk.ffn.W_1,
                       f'h.{i}.mlp.c_proj': blk.ffn.W_2}
            for key, module in modules.items():
                W = weights[key + '.weight']  # Conv1D: (in, out)
                module.weight.copy_(W.T if W.ndim == 2 else W)
                module.bias.copy_(weights[key + '.bias'])
    return gpt2.eval()

gpt2 = load_gpt2().to(d2l.try_gpu())
print(f'{d2l.num_params(gpt2) / 1e6:.1f}M parameters')
124.4M parameters
def load_gpt2():
    """GPT-2 small (124M) as a GPT with the released weights, in eval
    mode."""
    from safetensors.numpy import load_file  # lazy, like tiktoken above
    gpt2 = GPT(vocab_size=50257, num_hiddens=768, num_heads=12, num_blks=12,
               max_len=1024, pos='learned', norm='layer', act='gelu',
               pre_norm=True, bias=True, rngs=nnx.Rngs(d2l.get_key()))
    weights = {k: jnp.asarray(v) for k, v in load_file(
        d2l.download('gpt2-weights', '../data/gpt2')).items()}
    gpt2.token_emb.embedding[...] = weights['wte.weight']
    gpt2.pos_emb.embedding[...] = weights['wpe.weight']
    gpt2.norm.scale[...] = weights['ln_f.weight']
    gpt2.norm.bias[...] = weights['ln_f.bias']
    for i, blk in enumerate(gpt2.blks):
        for norm, key in ((blk.norm1, f'h.{i}.ln_1'),
                          (blk.norm2, f'h.{i}.ln_2')):
            norm.scale[...] = weights[key + '.weight']
            norm.bias[...] = weights[key + '.bias']
        for linear, key in ((blk.attention.W_qkv, f'h.{i}.attn.c_attn'),
                            (blk.attention.W_o, f'h.{i}.attn.c_proj'),
                            (blk.ffn.W_1, f'h.{i}.mlp.c_fc'),
                            (blk.ffn.W_2, f'h.{i}.mlp.c_proj')):
            # Conv1D stores (in, out), exactly nnx.Linear's kernel layout
            linear.kernel[...] = weights[key + '.weight']
            linear.bias[...] = weights[key + '.bias']
    gpt2.eval()
    return gpt2

gpt2 = load_gpt2()
print(f'{d2l.num_params(gpt2) / 1e6:.1f}M parameters')
124.4M parameters

타임머신(The Time Machine)의 첫 문단에 대한 토큰당 교차 엔트로피(약 \(\approx 3.9\) nats/token, 즉 혼란도 \(\approx 49\))를 계산하고 이어지는 문장을 생성해 봄으로써 불러온 체크포인트를 검증합니다.

text = ("The Time Machine, by H. G. Wells. The Time Traveller was "
        "expounding a recondite matter to us.")
x = torch.tensor(enc.encode(text), device=d2l.try_gpu())[None]
with torch.inference_mode():
    logits = gpt2(x)
loss = F.cross_entropy(logits[0, :-1], x[0, 1:])
print(f'per-token loss {loss.item():.2f}, '
      f'perplexity {loss.exp().item():.0f}')
per-token loss 3.89, perplexity 49
text = ("The Time Machine, by H. G. Wells. The Time Traveller was "
        "expounding a recondite matter to us.")
x = jnp.asarray(enc.encode(text))[None]
loss = optax.softmax_cross_entropy_with_integer_labels(
    gpt2(x)[0, :-1], x[0, 1:]).mean()
print(f'per-token loss {loss:.2f}, perplexity {jnp.exp(loss):.0f}')
per-token loss 3.89, perplexity 49

사전학습된 가중치가 검증되었으므로 탐욕적 디코딩(top_k=1)으로 gpt2.generate에 프롬프트를 넣어 결정론적 연속 문장을 생성할 수 있습니다.

out = gpt2.generate(enc.encode('Alan Turing theorized that computers '
                               'would one day become'), 16, top_k=1)
d2l.print_wrapped(enc.decode(out))
Alan Turing theorized that computers would one day become the most powerful
    machines on the planet.

The computer is a computer that
out = gpt2.generate(enc.encode('Alan Turing theorized that computers '
                               'would one day become'), 16, top_k=1)
d2l.print_wrapped(enc.decode(out))
Alan Turing theorized that computers would one day become the most powerful
    machines on the planet.

The computer is a computer that

서브워드 토큰 40개에 대해 확률적 상위-\(k\) 샘플링(temperature=0.8, top_k=50)으로 전환하면 유창하고 다양한 완성 결과를 얻습니다.

out = gpt2.generate(enc.encode('The secret of a good deep learning '
                               'textbook is'), 40, temperature=0.8,
                    top_k=50)
d2l.print_wrapped(enc.decode(out))
The secret of a good deep learning textbook is that it can be read by
    anyone. The easiest way to learn a deep learning language is to read the
    book, or the software. It's also the easiest way to learn a framework.
out = gpt2.generate(enc.encode('The secret of a good deep learning '
                               'textbook is'), 40, temperature=0.8,
                    top_k=50)
d2l.print_wrapped(enc.decode(out))
The secret of a good deep learning textbook is the fact that you can combine
    a great set of experiments with your own knowledge to create a good,
    consistent textbook that won't only be better but also be easier to read
    and understand.

This

11.2.6 현대 표준 레시피

2019년의 load_gpt2() 설정과 기본 GPT 설정을 비교하면 현대 오픈 가중치 디코더 전용 언어 모델을 규정하는 네 가지 핵심 업그레이드가 분명히 드러납니다(표 11.2.2).

  1. 정규화: LayerNorm 대신 편향 없는 사전 정규화 RMSNorm(11.1.2.4절)을 사용하며, 흔히 헤드별 QK-Norm(11.1.2.5절)이나 서브층 출력 정규화(OLMo 2, Gemma 3)를 함께 배치합니다.
  2. 위치 인코딩: 고정된 학습 위치 테이블 wpe 대신 각 어텐션 층 내부에 회전 위치 임베딩(RoPE)(10.4절)을 적용합니다.
  3. 피드포워드 신경망: 2층 GELU MLP 대신 편향 없는 게이트형 SwiGLU(또는 GeGLU)를 사용합니다.
  4. 추론 캐시 및 용량 확장: 그룹 쿼리 어텐션(GQA), 슬라이딩 윈도 어텐션, 또는 저계수 잠재 압축(MLA)으로 KV 캐시를 줄이고(11.3절), 전문가 혼합(MoE) 층(11.7절)으로 토큰당 FLOPs 증가 없이 총 매개변수 수를 키웁니다.
표 11.2.2: 2023년부터 2025년 사이 기술 보고서에 발표된 7개 오픈 가중치 모델 계열의 아키텍처. 어텐션 및 캐시: 11.3.3절. 정규화: 11.1절. 위치 인코딩: 10.4절. 전문가 혼합: 11.7절.
모델 어텐션 및 캐시 정규화 위치 인코딩 FFN 밀집 또는 MoE
Mistral 7B (2023) (Jiang 기타 2023년) GQA \(32{:}8\); 슬라이딩 윈도 4096 RMSNorm, 사전 RoPE, 밑 \(10^4\) SwiGLU 밀집
Llama 3 (2024) GQA \(32{:}8\) (8B), \(64{:}8\) (70B), \(128{:}8\) (405B) RMSNorm, 사전 RoPE, 밑 \(5 \times 10^5\) SwiGLU 밀집
Qwen3 (2025) (Yang 기타 2025년) GQA: \(64{:}8\) 밀집 (32B), \(64{:}4\) MoE (235B-A22B) RMSNorm, 사전; QK-norm RoPE, 밑 \(10^6\); YaRN SwiGLU 밀집 및 MoE: 전문가 128개, 활성 8개
OLMo 2/3 (2024/25) (Team OLMo 기타 2025년; Team OLMo 2025년) MHA (7B), GQA (32B); OLMo 3: 4층 중 3층에 윈도 4096 서브층 출력 RMSNorm; QK-norm RoPE SwiGLU 밀집
DeepSeek-V3 (2024) (DeepSeek-AI 기타 2024년) MLA: KV를 512차원 잠재 벡터로 압축 RMSNorm, 사전 분리형 RoPE (64차원 공유 키) SwiGLU MoE: 전문가 256개 + 공유 1개, 활성 8개
Gemma 3 (2025) (Gemma Team 2025년) GQA; 국소:전역 \(5{:}1\), 윈도 1024 RMSNorm, 사전 및 사후; QK-norm RoPE, 전역 밑 \(10^6\), 국소 밑 \(10^4\) GeGLU 밀집
gpt-oss (2025) (OpenAI 2025년) GQA \(64{:}8\); 격층 윈도 128; 학습된 싱크 RMSNorm, 사전 RoPE; YaRN SwiGLU, 클램핑 적용 MoE: 전문가 128개 또는 32개, 활성 4개

11.2.7 요약

디코더 전용 GPT는 토큰 임베딩 테이블 \(\mathbf{E} \in \mathbb{R}^{V \times d}\) 와 최종 정규화 및 가중치 공유 출력 투영 \(\mathbf{E}^\top\) 사이에 \(L\) 개의 인과적 TransformerBlock 층을 배치하여 단 한 번의 병렬 순전파로 \(T\) 개 모든 시퀀스 위치의 다음 토큰 로짓을 예측합니다(식 11.2.1). AdamW(2차원 행렬에만 선택적 가중치 감쇠 적용), 선형 웜업, 코사인 감쇠, 그레이디언트 클리핑을 결합한 LMOptimizer로 학습하면 4.8M 매개변수 규모의 바이트 수준 GPT가 1,000 스텝 이내에 영어 텍스트의 바이그램 엔트로피보다 훨씬 낮은 손실에 도달합니다. 매개변수 수와 연산량을 맞춘 통제 비교에서 SwiGLU는 \(0.01\)-nat 시드 산포 대비 약 \(0.06\) nats/byte 차이로 GELU를 능가하며, 문맥 위치 \(t\) 가 깊어질수록 GPT는 동등 규모의 RNNLM 대비 격차를 꾸준히 벌립니다. 현대 오픈 가중치 LLM들(표 11.2.2)은 이 사전 정규화 RMSNorm + RoPE + SwiGLU/GeGLU 레시피를 공유하며, 주로 KV 캐시를 어떻게 압축하는지(11.3절) 그리고 밀집 FFN을 전문가 혼합으로 대체하는지(11.7절)에서 차별화됩니다.

11.2.8 연습 문제

  1. 학습 레시피(LMOptimizer) 절제 실험. LMOptimizer는 네 가지 요소를 결합합니다. 선택적 가중치 감쇠(2차원 가중치 행렬에만 \(\lambda = 0.1\)), 선형 웜업(100 스텝), 코사인 감쇠, 전역 그레이디언트 클리핑(\(\|\nabla \mathcal{L}\|_2 \le 1.0\))입니다. 한 번에 요소 하나씩을 끄면서 6-블록 바이트 수준 GPT를 1,000 스텝 동안 학습시켜 보십시오: (a) 임베딩과 RMSNorm 이득을 포함한 모든 매개변수에 가중치 감쇠 적용, (b) 웜업 없음(warmup=0), (c) 상수 학습률(내내 lr=2e-3 유지), (d) 그레이디언트 클리핑 없음. 어떤 단일 변경이 검증 손실을 가장 크게 악화시킵니까?

  2. GPT-2 체크포인트 텐서 매핑 점검. GPT-2 model.safetensors 파일은 148개의 가중치/편향 텐서(및 12개의 레거시 인과 마스크 버퍼 h.i.attn.bias)를 담고 있습니다. d2l.num_params(gpt2)가 파일 내 148개 매개변수 텐서의 총 원소 수(\(124{,}439{,}808\))와 정확히 일치하는지 확인하는 짧은 검증 코드를 작성하고, 사용 중인 프레임워크의 선형 층 가중치 레이아웃에 비추어 불러올 때 c_attn.weight를 전치해야 하는지 여부를 설명하십시오.

  3. 0층 가중치 공유 임베딩 기준선(\(L = 0\)). num_blks=0인 GPT를 생각합시다. 입력 토큰 \(x_t\) 가 \(\mathbf{e}_{x_t}\) 로 임베딩되고 RMSNorm으로 정규화된 뒤 \(\mathbf{E}^\top\) 와 내적되어 로짓 \(\mathbf{z}_t \propto \mathbf{e}_{x_t} \mathbf{E}^\top\) 를 생성합니다.

    1. 0-블록 모델은 어떤 부류의 통계적 언어 모델(\(n\)-그램 차수)을 표현할 수 있습니까?
    2. \(\mathbf{E}\) 의 모든 행이 동일한 노름을 가질 때 입력과 출력 임베딩을 공유하면(\(\mathbf{W}_{\textrm{LM}} = \mathbf{E}^\top\)) 왜 대칭 행렬 \(\mathbf{E}\mathbf{E}^\top\) 가 항상 대각 성분 \(x_{t+1} = x_t\) 에 가장 큰 값을 부여하게 되며, 가중치를 분리한 모델이나 1-블록 모델은 이 대칭성을 어떻게 깨뜨립니까?
  4. 토크나이저 간 바이트당 비트 수 비교(바이트 수준 GPT 대 BPE GPT-2). 바이트 수준 모델은 교차 엔트로피를 nats/byte 단위로 보고하는 반면, GPT-2는 nats/subword-token 단위로 보고합니다.

    1. enc.encode가 \(N_T\) 개의 서브워드 토큰으로 토큰화하는 \(N_B\) UTF-8 바이트 분량의 임의의 구절에서, 토큰당 평균 음의 로그 가능도가 \(\mathcal{L}_{\textrm{tok}}\)(단위: nats/token)인 서브워드 모델의 정확한 바이트당 비트 수(bits-per-byte, bpb)가 \(\textrm{bpb} = \frac{N_T \, \mathcal{L}_{\textrm{tok}}}{N_B \ln 2}\) 임을 보이십시오.
    2. WikiText-103 검증 세트의 첫 10,000바이트에서 4.8M 매개변수 바이트 수준 model과 사전학습된 124M 매개변수 gpt2를 모두 바이트당 비트 수로 평가하십시오.
  5. 상위-\(p\)(핵, nucleus) 샘플링. 온도 스케일링된 확률을 내림차순으로 정렬하고 누적 확률이 \(p\) 를 초과하는 최소 프리픽스 너머의 토큰들을 마스킹하는 선택적 top_p 인자(\(0 < p < 1\)) (Holtzman 기타 2020년) 로 GPT.generate를 확장하십시오. 프롬프트 "Alan Turing theorized that computers would"에 대해 top_p=0.9, temperature=0.8 설정과 필터링 없는 temperature=1.2 설정에서 gpt2가 생성한 문장을 비교하십시오.

  6. QK-Norm에 따른 학습률 안정성. 표준 CausalAttention과 CausalAttention.qkv 내부에서 q 및 k에 RMSNorm(d_h)을 적용하는 변형(11.1.2.5절)에 대해 최대 학습률 \(\eta \in \{2\times 10^{-3}, 6\times 10^{-3}, 1.5\times 10^{-2}\}\) 을 탐색하며 6-블록 바이트 수준 GPT를 학습시키십시오. QK-Norm은 안정적인 최대 학습률을 어떻게 이동시킵니까?

토론