仅解码器语言模型(GPT)

Dive into Deep Learning · §11.2

仅解码器语言模型(GPT)
因果堆叠与绑定嵌入 · 字节级预训练 · SwiGLU 与 RNN 基线 · 采样 · 加载 GPT-2 · 现代配方

一个长度为 T 的窗口可训练 T 个预测问题

动机

  • 自回归语言模型通过链式法则分解序列概率:P(x_{1:T+1}) = \prod_{t=1}^T P(x_{t+1} \mid x_{1:t})。
  • 并行强制教学:仅解码器 GPT 不必为长度 1, \dots, T 的前缀分别运行 T 次前向传播,而是在因果掩码下通过单次并行前向传播为所有 T 个前缀预测打分。

GPT 架构:嵌入、因果堆叠与绑定输出头

架构概览

  • 输入嵌入(\mathbf{E} \in \mathbb{R}^{V \times d}):将离散词元编号 x_1, \dots, x_T 映射为 \mathbb{R}^{B \times T \times d} 中的初始残差流向量。
  • 因果 Transformer 堆叠(L 个块):每个 TransformerBlock 对残差流依次施加因果自注意力与逐位置 FFN。
  • 最终规范化与权重绑定输出头(\mathbf{E}^\top):将规范化后的残差流向量投影为词表对数几率 \mathbf{Z} = \mathrm{Norm}(\mathbf{H}^{(L)})\mathbf{E}^\top \in \mathbb{R}^{B \times T \times V},复用 \mathbf{E} 可节省 V d 个参数(在 GPT-2 Small 中为 38.6\text{M})。
A GPT from bottom to top: token ids, the token embedding E, L pre-norm transformer blocks with causal attention and a feed-forward network on the residual stream, a final norm, and a tied head that reuses E to produce next-token logits.

带 RoPE 与 GQA 的融合因果自注意力

因果注意力

  • 融合 QKV 投影:将 \mathbf{X} 乘以单个矩阵 \mathbf{W}_{qkv} \in \mathbb{R}^{d \times (d + 2 H_{\text{kv}} d_h)},再拆分为 H 个查询头与 H_{\text{kv}} \le H 个键值头。
  • RoPE + 因果掩码(is_causal=True):按位置角度旋转查询与键,并将 s > t 掩蔽为 -\infty,使得 \partial \mathbf{z}_t / \partial \mathbf{x}_s = \mathbf{0}。

位置信息:学习表对比 RoPE

位置编码

  • pos='learned'(GPT-2,2019):在堆叠最底层一次性加上 pos_emb(T_{\max} \times d)查表行 \mathbf{p}_t \in \mathbb{R}^d;硬上限为 T_{\max} = 1{,}024。
  • pos='rope'(默认 / Llama / Qwen):使用预计算的 d2l.rope_tables(T, head_width) 在每个注意力层内旋转 (\mathbf{q}_t, \mathbf{k}_s),得到可扩展至 32\text{K}–1\text{M} 词元的相对位置分数。

十行代码实现完整的 GPT 前向传播

前向实现

给定形状为 (batch, T) 的词元编号 X,GPT.forward 同时返回每个位置形状为 (batch, T, V) 的下一词元对数几率:

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 cosine/sine tables for positions 0, ..., T - 1
        tables = d2l.rope_tables(X.shape[1], self.head_width, device=X.device)
    for blk in self.blks:                 # L pre-norm causal Transformer blocks
        H = blk(H, tables=tables)
    return F.linear(self.norm(H), self.token_emb.weight)  # Weight-tied (batch, T, V)

将输出投影绑定到 self.token_emb.weight,意味着罕见词元无论出现在输入前缀中,还是作为 softmax 分母中的对比项,都能获得梯度更新。

按深度缩放的权重初始化(1/√(2L))

初始化

  • init_weights 从 \mathcal{N}(0, 0.02^2) 采样嵌入与投影权重,并将两个残差写回矩阵(W_o、W_2)按 1/\sqrt{2L} 缩放。
  • 共有 2L 个子层向前置规范化残差流写回,这种缩放使初始残差流方差从第 1 块起就保持在嵌入方差附近。
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)

自回归交叉熵目标

训练目标

给定输入窗口 \mathbf{x} = (x_1, \dots, x_T) 和移位目标 \mathbf{y} = (x_2, \dots, x_{T+1}),训练最小化全部 B \times T 个位置上的平均负对数似然:

\mathcal{L}(\boldsymbol{\theta}) = -\frac{1}{BT} \sum_{b=1}^{B} \sum_{t=1}^{T} \log \mathrm{softmax}\bigl(\mathbf{z}_{b,t}(\boldsymbol{\theta})\bigr)_{x_{b, t+1}}

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]]

在 WikiText-103 上进行字节级语言建模

语料与初始化检验

我们在 WikiText-103 的 270\text{M} 原始 UTF-8 字节上训练一个 6 块字节级 GPT(V = 256, d = 256, H = 8, L = 6, T = 128,4.79\text{M} 参数):

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
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

训练前合理性检验:在第 0 步,随机对数几率给每个字节赋予近似均匀的概率 1/256,因此初始损失(5.5\text{--}5.7\text{ nats/byte})接近 \ln 256 \approx 5.55\text{ nats/byte}。

现代预训练优化器(LMOptimizer)

优化配方

  • LMOptimizer 结合了 AdamW(\eta_{\max} = 2 \times 10^{-3})、线性预热 + 余弦衰减以及全局梯度裁剪(\le 1.0): \eta_t = \eta_{\max} \cdot \frac{1}{2}\Bigl(1 + \cos\bigl(\pi \tfrac{t - t_w}{S - t_w}\bigr)\Bigr)
  • 选择性权重衰减(仅对二维矩阵施加 \lambda = 0.1):豁免嵌入(*emb*)、一维 RMSNorm 增益与偏置。

训练曲线与经验熵标尺

训练结果

  • 快速收敛:在 1{,}000 步(8.2\text{M} 字节,语料的 \sim 3\%)内,验证交叉熵从 \approx 5.6 降至 1.34\text{ nats/byte}(\approx 1.93\text{ bits/byte})。
  • 同一批字节上的计数基准:
    • 均匀猜测(\ln 256):5.55\text{ nats/byte}
    • 经验一元频率:3.17\text{ nats/byte}
    • 经验二元转移:2.45\text{ nats/byte}

step 1000: train 1.36, validation 1.34 nats per byte; 14 s of training

训练曲线与经验熵标尺(续)

训练结果

一元与二元标尺直接通过对前 10\text{M} 训练字节计数得到:

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

对照消融:种子波动对比 SwiGLU 增益

实验严谨性

为了区分真正的架构改进与随机初始化噪声,我们用三个独立随机种子训练 act='swiglu',并用三个种子训练参数量匹配的 act='gelu':

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
  • 高度可重复性:三个随机种子之间的验证损失差异小于 0.01\text{ nats/byte}。
  • SwiGLU 优势显著:在相同参数量(4.79\text{M})和单步耗时下,SwiGLU 领先 GELU \sim 0.06\text{ nats/byte}(> 5\times 种子波动)。
  • 后置规范化对照:使用相同 100 步预热或无预热的 pre_norm=False 块最终停在一元熵 3.17\text{ nats/byte}——子层输出压过规范化残差流,所有词元收敛到相同向量且无法恢复。改用 500 步预热后,后置规范化可训练至约 1.38,略逊于前置规范化(1.34)。

与参数量匹配的循环模型对比

Transformer 对比 RNNLM

我们在三个学习率下训练参数量匹配的 d2l.RNNLM(d_{\text{rnn}} = 1{,}920,4.74\text{M} 参数),并观察窗口位置 t \in \{0, 1, 4, 16, 64, 127\} 处的验证损失:

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

为何差距随上下文位置 t 拉大:在 t = 0(1 字节上下文)处,两个模型均约为 2.5\text{ nats}(二元下界为 2.45)。到 t = 16 \dots 127 时,RNN 停在约 1.4\text{ nats},因为历史必须挤过 t 步顺序 \tanh 变换;而 GPT 以 O(1) 跳直接关注任意先前字节,达到约 1.3\text{ nats}。

自回归解码:温度与 Top-k

采样机制

  • 每一步解码中,GPT.generate 用温度 \tau > 0 缩放对数几率 \mathbf{z}_t \in \mathbb{R}^V,并截断至 top-k 候选: p_v = \frac{\exp(z_{t,v} / \tau)}{\sum_{u \in \mathcal{V}_k} \exp(z_{t,u} / \tau)}

自回归解码:温度与 Top-k(续)

采样机制

\tau = 0.7, k = 8 将概率质量集中在通顺的英文单词上,而 \tau = 2.0 则趋向平坦乱码:

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'

加载预训练 OpenAI GPT-2 Small(124M)

检查点加载

  • 将 GPT-2 的 2019 年配置(norm='layer'、act='gelu'、pos='learned'、bias=True)传入 d2l.GPT,即可精确实例化 GPT-2 Small 架构:
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)

陷阱:在 PyTorch 中转置 Conv1D 权重

权重布局陷阱

OpenAI 最初的 TensorFlow GPT-2 代码使用 Conv1D 层,按 (in_features, out_features) 存储权重矩阵,而 PyTorch 的 nn.Linear 按 (out_features, in_features) 存储:

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 layout: (in, out)
        module.weight.copy_(W.T if W.ndim == 2 else W)  # Transpose 2D matrices
        module.bias.copy_(weights[key + '.bias'])

静默错误隐患:因为 c_proj 是形状为 (768, 768) 的方阵,漏写 .T 也能通过所有形状断言——只有用真实文本做困惑度检验才能发现矩阵被转置。

用困惑度与生成文本验证加载的 GPT-2 Small

检查点验证

在《时间机器》上评估加载的 124.4M 参数 gpt2 模型,单词元交叉熵为 3.89\text{ nats}(困惑度 e^{3.89} \approx 49,而均匀猜测为 50{,}257),且贪婪与采样续写均连贯通顺:

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

GPT-2 Small 的贪婪与采样续写

检查点验证

Alan Turing theorized that computers would one day become the most powerful
    machines on the planet.

The computer is a computer that
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.

现代开源权重 LLM 的架构配方

前沿对比

  • 2023–2025 年间各大开源权重仅解码器模型家族均共享我们的默认 GPT 骨干(RMSNorm、RoPE、SwiGLU)。
  • 两条前沿分化轴:
    1. KV 缓存压缩(§11.3):GQA(32{:}8 或 64{:}8)、5{:}1 局部/全局窗口(Gemma 3)或低秩 MLA(DeepSeek-V3)。
    2. FFN 稀疏化(§11.7):稠密 SwiGLU 对比细粒度 MoE(128–256 个专家)。

概念检验:参数量、困惑度与对称性

检验理解

用三道具体计算检验理解:

  1. 估算 GPT-2 Medium 参数量:GPT-2 Medium 有 L = 24 个块、宽度 d = 1024、词表 V = 50{,}257、T_{\max} = 1024 个学习位置以及权重绑定输出头。估算其总参数量。
  2. 作为有效分支因子的困惑度:我们的字节级 GPT 达到 1.35\text{ nats/byte},而 GPT-2 Small 在《时间机器》上达到 3.89\text{ nats/token}。这两种损失分别对应多少个等概率选项?
  3. 零层权重绑定陷阱:若 num_blks=0 且 \mathbf{E} 的所有行均为单位范数,在 \mathbf{z}_t = \mathbf{e}_{x_t}\mathbf{E}^\top 中,哪个下一词元 x_{t+1} 总是获得最高对数几率?

答案:

  1. \approx 355\text{M} 参数:块内 24 \times 12(1024)^2 \approx 302.0\text{M} + 50{,}257 \times 1024 \approx 51.5\text{M}(token_emb)+ 1.0\text{M}(pos_emb)。
  2. 字节模型为 256 个字节中的 e^{1.35} \approx 3.9 个字节;GPT-2 为 50{,}257 个子词中的 e^{3.89} \approx 49 个子词词元。
  3. x_{t+1} = x_t(重复当前词元):对称格拉姆矩阵 \mathbf{E}\mathbf{E}^\top 在对角线 j = i 处取得 \mathbf{e}_i^\top \mathbf{e}_j 的最大值。注意力和 FFN 打破了这一对称性。

小结:构建与训练仅解码器 GPT

核心要点

  • 因果堆叠与绑定输出头:融合 \mathbf{W}_{qkv}、RoPE、下三角掩码与共享 \mathbf{E} \in \mathbb{R}^{V \times d} 在单次前向传播中训练全部 T 个前缀预测。
  • 1/√(2L) 初始化与 LMOptimizer:仅对二维矩阵施加权重衰减的 AdamW 配合预热 + 余弦衰减,在 1{,}000 步内达到 1.34\text{ nats/byte}。
  • 对照基线与 GPT-2 加载:SwiGLU 领先 GELU 0.06\text{ nats};可直接加载官方 124M GPT-2。