← PyTorch From First Principles

组装:可盘问的语言模型

组装小 GPT 风格语言模型,用全书诊断栈盘问它——分词器与目标契约、注意力干预、参数核算、学习性能台账、编译、生成、配对评估——让成品保持可检查而不是魔法。

这里有同样小语言模型同样数据上的两次训练跑。唯一区别是 batching 函数里一行。

CORRECT     y = data[i+1 : i+block+1]        the next-token shift
MISALIGNED  y = data[i   : i+block]          no shift

step      correct val    misaligned val
   0          3.6695          2.6469
  250          1.1038          0.0007
  500          0.4730          0.0004
  750          0.3940          0.0003
 1000          0.3690          0.0002
 1250          0.3581          0.0002
 1500          0.3558          0.0001

错位跑的损失掉到 0.0001——正确跑 0.36 的三千分之一。dashboard 每数看它都是见过最好的训练跑。什么都不抛。形状相同:x 是 [B, T],y 是 [B, T],损失是带 grad_fn 的有限标量。

再从每个生成:

correct:    'The planet measures the ancient planet because measures it near the water.
             A sudden market builds a hidden market again. When that planet counts slowly, '
misaligned: 'The                                                                          '

错位模型学了恒等任务。y[:, t] == x[:, t] 时答案已在同样位置 present:残差流里装着词元 t 的嵌入,因果自注意力也允许 attend 自己这个位置。网因而有极便宜的路从可见词元到目标词元。损失一路奖励错任务。抓住它的不是更好的损失曲线——是训练开始前检查的一行:

assert torch.equal(x[:, 1:], y[:, :-1])      # does the target still describe the input?

那是第 11 章的第一 link,整章的缩影。

损失能主动误导。变好的指标不是模型在学想要的东西的证据——大到藏得住错误的模型要每台仪器。

我们在哪

十四章,十四台仪器。第 2 章问哪个张量先错而不是先不合法。第 3 章问梯度通路断在哪。第 5 章问 PyTorch 以为什么属于模型。第 6 章问训练循环到底在等哪里。第 7 章问模型实际看到了什么。第 8 章把卷积几何推导进形状台账。第 9 章让特征空间可观测。第 10 章问哪个位置和哪个位置比。第 11 章逐 link 证明学习链。第 12 章把性能定位到阶段与算子。第 13 章找到第一个不再成立的编译器假设。第 14 章问两跑差真不真。

每样都从一小系统上的一构造失败挣来。

本章建第一个大到装不进脑子的系统——GPT 风格语言模型,约八十万参数,四十多张量,前向走 文本 → 词元 → 嵌入 → 注意力 → 残差块 → logits → 损失,还有生成的第二执行模式。单仪器 certify 不了它。但书里建的每台仪器现在都是问它的问题:

tokenizer + batching   does the target still describe the input?      Chapter 11
embeddings             what does PyTorch think belongs to the model?  Chapter 5
attention              can a future token change an earlier output?   Chapter 10
block assembly         where does the shape ledger first diverge?     Chapter 8
first training steps    which link in the learning chain is broken?    Chapter 11
throughput and memory  which phase, at which sequence length?         Chapter 12
compilation            did it help, and did correctness hold?         Chapter 13
comparison             is this run really different from that one?     Chapter 14

读完本章的读者应该说得出哪台仪器回答 Transformer 的哪个问题,不用人告诉伸手拿对的。这才是本书真正的 deliverable。模型是演示。

环境

本章每数、跟踪、生成样本都来自 experiments/ch15/ 下提交代码跑出:

Python   3.11.4
PyTorch  2.6.0+cu118
GPU      NVIDIA GeForce RTX 2060, compute capability 7.5

模型 deliberate 小:n_layer=4、n_head=4、n_embd=128、block_size=64、字符级词表。它有 804,224 参数,这块 GPU 上一分钟内训到收敛;种子 sweep 全算实验套件约二十分钟算子。大模型教不出这个尺寸仪器还没 show 的东西。

数据是自包含合成语料——20 万字符类英语句子,从小固定词表与五模板生成:

That garden repeats that small garden because repeats it by the door. Near the water,
that hidden shadow carries that shadow. When a river holds again, a golden river holds.

无下载,无版权文本:语料从种子可复现,有真可学结构——词边界、模板语法、常见 bigram、标点——训好的模型产出可认(虽然 nonsense)的输出,生成实验才有意义。experiments/ch15/corpus.py 建它。

流水线

text
  ↓  tokenizer            characters ↔ integer IDs
token IDs  [B, T]
  ↓  batching             x = window;  y = window shifted by one
  ↓  token + position embedding
[B, T, C]
  ↓  transformer blocks   pre-norm attention + MLP, residual, ×n_layer
  ↓  final LayerNorm
  ↓  lm_head              [B, T, vocab] logits
  ↓  cross entropy        vs the shifted targets
loss  → backward → AdamW → repeat
  ↓
generation               feed the model its own output, one token at a time

流水线里两边界真新,占本章大半 attention:文本 → 词元 ID,训练 → 生成。之间的一切是书里建过的零件的组合。

数据:分词器

字符分词器是一对字典。要紧的是往返无损,ID 在范围。

class CharTokenizer:
    def __init__(self, text):
        self.chars = sorted(set(text))
        self.stoi = {c: i for i, c in enumerate(self.chars)}
        self.itos = {i: c for c, i in self.stoi.items()}
        self.vocab_size = len(self.chars)

    def encode(self, s):  return [self.stoi[c] for c in s]
    def decode(self, ids): return "".join(self.itos[int(i)] for i in ids)
  round-trip decode(encode(s)) == s        True   for the full corpus
  full corpus tensor: dtype int64  min 0  max 36  vocab 37

往返检查是第 7 章契约思想在输入边界:下游信任何东西前先证明变换无损。dtype 检查重要因为词元 ID 是下标,不是连续值。nn.Embedding 期待整数下标张量;浮点 ID 传进去是边界契约错,先在那里诊断,再讨论模型的表示。

分词器错时造成的失败是越界 ID 到达嵌入表:

emb = nn.Embedding(vocab_size, 8)
emb(torch.tensor([[0, 1, vocab_size]]))       # one past the end
IndexError: index out of range in self

这正是人们贴进搜索框的报错。机制是数据/分词器侧产出的 ID 与嵌入表实际拥有的行之间的契约 mismatch:不同语料拟合的分词器、词表更小的 stale 检查点、模型从没定尺寸的特殊词元 ID 都能造出它。这个语料 2000 字符样本拟合的分词器就缺字符 S,全文本遇到大写 S 句子就 KeyError: 'S'。边界验证分词器往返、ID 范围、模型词表尺寸,这类失败到不了训练。

数据:batching 与对齐契约

def get_batch(source, batch_size, block_size):
    starts = torch.randint(0, len(source) - block_size - 1, (batch_size,))
    x = torch.stack([source[i : i + block_size]     for i in starts])
    y = torch.stack([source[i + 1 : i + block_size + 1] for i in starts])
    return x, y

x 每位置预测下个词元,y 是 x 左移一。契约:

assert torch.equal(x[:, 1:], y[:, :-1])

这是开篇的检查。值得重述为什么它是 build 里单最值钱的一行:错位失败损失里 invisible(损失变好)、形状里 invisible(都是 [B, T])、梯度里 invisible(有限且处处流动),产出打分漂亮、生成空的模型。唯一看得见的地方是这里,输入与目标的关系——第 11 章的 TASK 边界,第一要证明、最先被跳过的东西。

模型:嵌入与位置

self.token_embedding = nn.Embedding(vocab_size, n_embd)      # [V, C]
self.position_embedding = nn.Embedding(block_size, n_embd)   # [block, C]
...
x = self.drop(self.token_embedding(idx) + self.position_embedding(pos))

无位置信号或顺序相关掩码的基于内容自注意力是置换等变。这个模型的因果掩码已引入顺序约束——前面位置看不到后面——但没提供模型这里用的显式 learned 位置身份。那来自位置嵌入。idx 是 [B, T];token_embedding(idx) 是 [B, T, C];position_embedding(arange(T)) 是 [T, C],跨 batch 广播。这是第 2 章的广播,deliberate 用的。

两嵌入表都是 nn.Module 属性,所以注册——出现在模型的已注册参数/state 结构里,优化器在 model.parameters() 上建好后,可训练参数能被优化器拥有。第 5 章的问题——PyTorch 以为什么属于模型?——这里构造回答。权重绑定稍后让对象同一性再次重要:共享两名字与拥有两独立参数不是一回事,优化器构造后绑定造出第 11 章教审计的 exactly 那种 stale 参数 mismatch。

模型:注意力

第 10 章仔细建了注意力:头拆分是特征轴的划分、[B, H, T, T] 分数矩阵、key 上 softmax、因果掩码,以及关键的——“正确”在四层是四种意思(形状、轴语义、数值不变式、行为)。本章不重推导任何一个。打包:

def split_heads(x, n_head):
    B, T, C = x.shape
    return x.view(B, T, n_head, C // n_head).transpose(1, 2)   # [B, H, T, D]

def merge_heads(x):
    B, H, T, D = x.shape
    return x.transpose(1, 2).contiguous().view(B, T, H * D)     # [B, T, C]

class CausalSelfAttention(nn.Module):
    def forward(self, x):
        q, k, v = self.qkv(x).chunk(3, dim=-1)
        q, k, v = (split_heads(t, self.n_head) for t in (q, k, v))
        y = F.scaled_dot_product_attention(q, k, v, is_causal=True,
                                           dropout_p=self.dropout if self.training else 0.0)
        return self.resid_dropout(self.proj(merge_heads(y)))

is_causal=True 的 F.scaled_dot_product_attention 就是整个机制——第 10 章与手写实现对过。模型尺度仍值得查的两样是 Level 2(头拆分保数据吗)与 Level 4(真因果吗),形状里都看不见。

Level 2 — 头拆分往返。 split_heads 后 merge_heads 须精确返回原张量。错版——q.reshape(B, H, T, D) 而不是 q.view(B, T, H, D).transpose(1, 2)——产出形状相同、把序列切成头尺寸块而不是划分特征轴的张量。下面形状台账抓住它;形状断言抓不住。

Level 4 — 干预证因果。 三角掩码是断言。证据是行为:模型放评估模式,只改位置 i 之后的词元,重跑,要求 0..i 输出在陈述的数值 tolerance 内一致、某后缀输出真变。

正确模型训后:

  max |Δ logits| at positions 0..i  :  0.000e+00      the past did not move
  max |Δ logits| at positions i+1.. :  varies         the future did

这次跑前缀精确零;更 portable 的契约是前缀 delta 留在后端 dtype 恰当的 tolerance 内。第二数也重要:后缀 delta 也零,测试可能因干预无可观测 effect 而过。

现在 is_causal=False 训同样模型:

                        causal      non-causal
  val loss (1000 steps)  0.369        0.023          16x lower -- looks extraordinary
  past Δ after training   0.000e+00    1.03e+01       the past moved by 10 logits

  causal sample:      'The planet measures the ancient planet because measures it by the door.'
  non-causal sample:  'The       h    ,      hh  h   ,,  ,,, , ,    h h h h h h h h h h h h h h'

非因果模型能从位置 t attend 位置 t+1,其输入词元正好是位置 t 的下词元目标(边界除外)。损失一路奖励泄漏。检查掩码能提示 bug;未来词元干预是证明模型真用了不该用的信息的行好吧证据——第 10 章的 Level 4,全尺度。

模型:MLP、块、组装

剩下是组合。逐词元 MLP(Linear → GELU → Linear → Dropout,隐层 4C)每位置独立作用,保留 [B, T, C]。pre-norm 块把注意力与 MLP 包进残差连接:

def forward(self, x):
    x = x + self.attn(self.ln1(x))
    x = x + self.mlp(self.ln2(x))
    return x

每块保留 [B, T, C],堆叠 trivial 的不变式。完整模型加嵌入、块堆、终 LayerNorm、lm_head 到词表 logits 投影。

验证组装,第 8 章形状台账跑完整前向——每阶段一行,每行带形状与该阶段欠的不变式:

  SHAPE LEDGER   B=2 T=16 C=128 H=4 V=37
    token_embedding    (2, 16, 128)   (B,T,C)=(2,16,128)                  ok
    position_embedding (16, 128)      (T,C)=(16,128)                      ok
    tok + pos          (2, 16, 128)   (B,T,C) by broadcast                ok
    head split         (2, 4, 16, 32) merge(split(q)) == q  (round trip)  ok
    block[0..3]        (2, 16, 128)   (B,T,C) preserved                   ok
    lm_head            (2, 16, 37)    (B,T,V)=(2,16,37)                    ok
    flatten for CE     (32, 37)       (B*T,V)=(32,37)                     ok
  first divergence: none

现在错头 reshape 建模型跑同样台账:

    head split         (2, 4, 16, 32) merge(split(q)) == q  (round trip)  X  <-- FIRST DIVERGENCE
    block[0..3]        (2, 16, 128)   (B,T,C) preserved                   ok
    lm_head            (2, 16, 37)    (B,T,V)=(2,16,37)                    ok
  first divergence: head split

坏拆分的输出形状 (2, 4, 16, 32)——与正确版相同。下游每行仍 ok。前向不抛,模型训到 mediocre 损失从不说为什么。往返行是看到它的那行,因为它查数据不查维度。这是第 8 章的第一次分歧规则与第 10 章的 Level 2,组合。

参数核算

def param_count(model):
    seen = set()
    total = 0
    for p in model.parameters():
        if id(p) in seen:
            continue
        seen.add(id(p))
        total += p.numel()
    return total
  THIS MODEL   n_layer=4 n_head=4 n_embd=128 vocab=37       total 808,960
    mlp                             526,848   65.1%
    attention                       262,144   32.4%
    embeddings (tok + pos)           12,928    1.6%
    lm_head (output projection)       4,736    0.6%
    layernorm                         2,304    0.3%

流传的说法是小语言模型嵌入主导。subword 尺度 true——同样核算 GPT-2-small 尺度:

  n_layer=12 n_embd=768 vocab=50257                          total 124,356,864
    mlp                          56,623,104   45.5%
    embeddings (tok + pos)       39,383,808   31.7%     <- the token table alone is 31%
    attention                    28,311,552   22.8%

—词元嵌入表 alone 约 38.6M 参数,典范 124.4M tied GPT-2-small 计数的约 31%。但字符尺度词表 37,词元表只有 37 × 128 = 4,736 个值,MLP 主导。重要变量是词表对模型宽/body 的比,不是“嵌入主导”的通用规则。知道自己在哪个 regime 才知道下节多大意义。

权重绑定

输入嵌入把词元 ID 映成向量;输出 lm_head 把向量映回词元分布。两者都是关于同样词表的 [vocab, n_embd] 矩阵,标准设计共享它们:

self.lm_head.weight = self.token_embedding.weight

绑定生效验证——第 5 章的纪律,因为跑起来的赋值什么都没证明:

  tied:   lm_head.weight is token_embedding.weight  ->  True
  untied: same object                               ->  False
  config   params   parameter tensors   shares storage
  tied     804,224           44          True
  untied   808,960           45          False

上面 GPT-2-small 配置,不绑定输出投影多 50,257 × 768 = 38,597,376 参数。绑定省掉那个矩阵:典范 tied 模型参数数的约 31%,假设不绑定 total 的约 24%。这里只去掉 4,736,不绑定模型的约 0.6%。所以这个模型的问题主要不是内存;是共享输入输出表示改行为够不够 resolve。配对种子 sweep(四种子,各 2000 步,两边同样种子):

  seed     tied   untied   untied - tied
     0   0.3525   0.3520      -0.0005
     1   0.3517   0.3519      +0.0002
     2   0.3554   0.3527      -0.0027
     3   0.3518   0.3515      -0.0003
  mean untied - tied: -0.0008   stdev 0.0011   (1/4 favour tied)

配对均差 -0.0008(untied - tied),标准差 0.0011,四配对 delta 没确立任一方向的稳定优势。下面六种子基线 variation 也远大于观测均值 shift,但那个范围是 context,不是统计等价阈值。honest 结果是四配对种子 resolvable 不了。参数省 exact;表示 effect 是经验问题,这个实验不够强到说更好、更差、等价。

训练:证明在发生

第 11 章把“模型学吗”变成一固定 batch 上可检查后果的链:

TASK → OBJECTIVE → DEPENDENCY → GRADIENT → OWNERSHIP → UPDATE → CAPABILITY

Transformer 上跑它的学习台账,加两 capstone 尺度增项。OBJECTIVE 加初始化 sanity 检查:均匀预测交叉熵 ln(vocab_size),这个 deliberate 小 logit 初始化下初始损失同量级期待。那是参照,不是每语言模型初始化的通用不变量。CAPABILITY 是一小 batch 过拟合,这个尺寸模型训练机器装得下这些样本的最强单端到端证明。

  LEARNING LEDGER   TinyGPT   batch (8, 32)
    TASK      alignment       x[:,1:] == y[:,:-1]                       ok
              id range        [0, 36] of 37                             ok
    OBJECTIVE initial loss    3.668   ln(vocab) = 3.611   ratio 1.02    ok
              one-example CE  manual 3.52942 vs 3.52942                 ok
    GRADIENT  present         44/44                                     ok
              finite          44/44                                     ok
    OWNERSHIP owned           44/44                                     ok
    UPDATE    moved           44/44                                     ok
  first divergence: none

  CAPABILITY -- overfit one tiny batch (8 x 32):
    step   0  loss 3.6557
    step 100  loss 0.0230
    step 200  loss 0.0083
    step 300  loss 0.0045
    step 399  loss 0.0029

每 link 成立;模型 400 步把一 batch 干到近零损失。现在初始损失检查为抓而存在的 fault。权重绑定但跳过小尺度初始化——嵌入表留 PyTorch 默认 N(0, 1),绑定的 lm_head 继承它:

    TASK      alignment       x[:,1:] == y[:,:-1]                       ok
    OBJECTIVE initial loss    119.463   ln(vocab) = 3.611   ratio 33.08  <-- FIRST DIVERGENCE
    GRADIENT  present         44/44                                     ok
    OWNERSHIP owned           44/44                                     ok
    UPDATE    moved           44/44                                     ok
  first divergence: OBJECTIVE/initial loss

链过 TASK,OBJECTIVE 度量先看着错:绑定输出矩阵继承嵌入表 N(0, 1) 尺度,这跑产出巨大 spiky logits,损失均匀预测参照的 33 倍。下游机械检查仍报告健康——梯度在,优化器拥有参数,一步动它们。那证明系统能从这个起点更新;不证明训练干净恢复或量化不跑那个实验多坏。台账的活干完了:在下降损失被误当成功前点名最早意外的后果。

性能

第 12 章性能台账:拆步,再 sweep 要紧的轴。

  WORKLOAD  TinyGPT 4L/4H/128d | training step | batch 64 x 64 | CUDA

  PHASE DECOMPOSITION (median ms, synchronized)
    forward       3.428   31.5%
    loss          0.165    1.5%
    backward      6.176   56.8%
    optimizer     1.104   10.2%
    sum          10.872

反向主导 57%——与第 12 章 shallow MLP 相反,那里 3000 万参数上 AdamW 步是最大阶段。这里模型只有约 80 万参数,优化器 comparatively 便宜,四 Transformer 块的反向传播主导测得的步。这个阶段分解本身不证明 scaled_dot_product_attention 是反向里主导算子;那要 profiler 或别的算子层实验。第 12 章的课成立:先定位再优化,证据支撑到哪定位到哪。

batch 与序列长 sweep:

  BATCH SIZE SWEEP (block_size 64)
     batch   ms/step   tokens/s   peak MiB
        16     9.98     102,601      77.1
        32     9.74     210,347     113.6
        64    11.04     370,930     187.2
       128    17.04     480,788     337.1
       256    31.19     525,278     634.6

  SEQUENCE LENGTH SWEEP (batch 32) -- the transformer-specific axis
     block   ms/step   tokens/s   peak MiB
        16    10.09      50,721      56.2
        32    10.14     101,025      77.0
        64     9.72     210,728     113.6
       128    11.47     357,221     187.3
       256    20.65     396,659     337.3

batch 与序列长都提吞吐、回报递减,都提峰值内存——但速率不同。batch 128 翻倍到 256 测得峰值大致翻倍;序列长 128 翻倍到 256 这个跑峰值内存与步时间约 1.8×。第 12 章测了显式物化 [B, H, T, T] 分数/概率张量的手工注意力实现,因而直接暴露二次内存增长。这个实验选的 SDPA 后端内存高效,不物化那些同样完整张量,这个范围测得峰值分配温和得多。逻辑稠密注意力关系仍序列长两两;物理分配取决于选定的核。

编译

第 13 章的问题,问一次:torch.compile 对这个模型帮忙了吗,正确性成立吗?

  WORKLOAD  TinyGPT training step | batch 64 x 64 | float32 | CUDA

  config                    first call    steady ms   vs eager
  eager                             -         9.37      1.00x
  compiled                    ~60 s cold      8.12      1.15x
                              ~2 s warm

  correctness: max |Δ logits| eager vs compiled, same weights = 1.9e-06

稳态小加速——这个测量约 1.15×,别的跑约 1.3×——首调用代价冷 Inductor 缓存约一分钟、缓存热约两秒。编译 logits 与 eager 差至多 1.9e-06,陈述 tolerance 下正确性检查过;单测量不必把差指派到某 fuse/重排机制。

摊销好算。测得稳态省 9.37 - 8.12 = 1.25 ms/step。60 s 冷编译要约 60,000 / 1.25 ≈ 48,000 复用步回本。2 s 热缓存首调用要约 1,600 步。典范 3000 步跑热代价轻松摊销、冷代价摊销不了。编值不值取决于缓存 state 与 workload 寿命,不只稳态加速存在否。

整编译节就这些。第 13 章拥有图断裂、守卫、重编译、冷热缓存 split;编译模型慢了或一直重编,调查搬那里。这里是台账的一行。

生成是另一个程序

训练与生成让同样权重走不同的代码。训练是一固定 batch 上一次前向加目标。生成是把模型自己的输出喂回去的循环,有训练从不练的失败模式。

采样策略,同样训好的模型,同样种子:

  greedy (argmax)      'The machine crosses the machine, because the gentle machine crosses at
                        dawn. That machine carries that machine, because that gentle machine...'
  temperature 0.5      'The hidden market crosses the hidden market again. The golden window
                        counts the golden window without warning. That signal builds that...'
  temperature 1.0      'The quiet shadow remembers the quiet shadow by the door. When one
                        garden watches without warning, one restless garden watches...'
  temperature 1.5      'The quiet small window builds Quietly. Quietly, that restless window
                        answers that window. For years, this narrow forest thout warning...'
  temp 1.0 + top_k 10  'The hidden market crosses the hidden market by the door. When one
                        garden watches without warning, one restless garden watches...'

贪心确定,这个样本掉进强重复续写(“the machine crosses the machine…”)。温度 0.5 向高概率续写 sharpen;温度 1.5 分布 flatten 到这个样本出现拼写错(thout warning)与奇怪大小写;top_k 采样前去掉最高候选外的所有。这些设置没有通用“正确”——它们改采样分布,有用 trade-off 取决于生成任务。

生成时 dropout 没关。 model.eval() 这里不是可选——它是关 dropout 的东西。模型 train() 模式生成,每调答案不同,因为 dropout 随机叠在采样随机上。这是第 11 章 eval() vs no_grad() 区分以生成 bug 到来:torch.no_grad() 省内存不动 dropout;要紧的是 model.eval()。TinyGPT.generate 调 self.eval() 并 finally 恢复之前模式——第 10 章注意力模块的模式。

生成超过上下文长。 模型有 block_size 行位置表。更长序列喂进去在契约处抛:

  ValueError: sequence length 84 exceeds block_size 64

generate 循环每步 idx[:, -block_size:] 截断;删掉那行上下文迟早长过 block_size hit 这个。forward 里显式 raise 是第 8 章的原则——契约处失败,信息点名问题,不在嵌入查找里四十行后。

代价结构。 天真生成每步重编码整个可见前缀:

  new tokens   wall s   ms/token
          32    0.102     3.183
          64    0.219     3.418
         128    0.413     3.229
         256    0.863     3.370
         512    1.730     3.379

每词元毫秒大致平,因为 block_size 64、截断 cap 可见上下文:窗口满后每调用最多 64 位置重算一 Transformer 前向。cap 下天真生成每新词元整个可见前缀重跑。稠密自注意力里那次前向含可见长 T 下 O(T²) 注意力交互(加逐词元投影/MLP O(T)),每生成词元代价随上下文涨,窗口饱和前。

KV 缓存改算子而不只是让同样循环快:每层存过去 key/value,新词元投影算一次,新 query 对缓存 T key/value attend,新词元注意力 work O(T) 而不是全 T × T 注意力 pass 重算。它还引入可变生成 state、缓存内存、驱逐/窗口语义、新正确性契约。这就是 deliberate 不在这个 build 里:先确立无状态基线。

run 记录与这个模型的基线 variation

这个模型任意两训练跑比较前——绑定 vs 不绑定、新学习率、重构——第 14 章说先知道同样配置单种子差多少。

  ONE RUN RECORD
  {
    "seed": 0,           "config_hash": "0ead31df3032",   "params": 804224,
    "torch": "2.6.0+cu118",                               "device": "cuda",
    "final_train_loss": 0.3487,   "final_val_loss": 0.3525,
    "peak_mib": 174.9,            "wall_s": 31.54
  }

    BASELINE VARIATION   TinyGPT 4L/4H/128d, 2000 steps, 6 seeds
    seed    train      val
       0   0.3487   0.3525
       1   0.3475   0.3517
       2   0.3505   0.3554
       3   0.3459   0.3518
       4   0.3484   0.3493
       5   0.3476   0.3515
    val loss   median 0.3518   stdev 0.0018   spread 0.0061
    wall time  median 28.8 s    spread 9.6 s   (machine contention, not the model)

这六同样配置种子验证损失跨 0.0061、标准差 0.0018。经验 variation 给比较 scale:错位、因果、初始化失败相对它动指标巨大,effect 不 subtle。权重绑定配对均值只动 0.0008,四配对种子 resolvable 不了。别把六种子 min/max spread promote 成通用检测阈值——第 14 章说明配对比较有时 resolve 比非配对范围小的 effect。这里 honest 的陈述更窄:已有配对证据下权重绑定仍 not resolved。

去掉了大半魔法

回头看模型是什么:

embedding lookup
+ learned positional representation
+ repeated (pre-norm attention, pre-norm MLP) residual blocks
+ final layer normalization
+ linear projection to vocabulary logits
+ cross entropy against the next-token shift
+ gradient descent with AdamW

没有 pipeline() 调用,没有预训练检查点,没有隐藏服务。前向每张量都点名、定形状、跟踪到来源。

这不让前沿系统简单。规模彻底改变工程:上千加速器分布式训练、万亿词元数据流水线、自定义注意力核、学习率 schedule 与优化器变体、结构 refinement、量化、各自深栈的推理系统。那些层引入这个小模型没有的失败模式。

但核心路径不再 opaque。大系统做出意外的事,本书教的问题仍有用——这张量是什么,哪个契约该成立,第一个后果分歧在哪?规模上那些问题旁边加新的分布式系统问题,实验更贵,但要证据的纪律活下来。

LLM 时代的程序员

助手能生成本章每类。它写分词器、注意力模块、训练循环、采样函数、检查点代码。它生成自信流利的损失不降解释。敲代码不再是值钱的部分。

理解 runtime 是。生成的系统 misbehave,有用的问题是:

Does the target still describe the input?            (alignment)
Are the token IDs in range?                          (tokenizer)
Can a future token change an earlier output?          (causality)
Where does the shape ledger first diverge?            (assembly)
Is the initial loss plausible for the declared initialization, with ln(vocab) as the uniform reference? (initialization)
Do gradients exist and are they finite?               (the chain)
Does the optimizer own the parameters?               (ownership)
Did the parameters actually move?                     (update)
Can the model overfit one tiny batch?                 (capability)
Which phase, at which sequence length, is the cost?   (performance)
Did compilation help, and did correctness hold?       (compilation)
Is this run really different from the last one?       (comparison)

源代码能提示很多问题的答案,检查 alone 确立不了 runtime 事实。本书的仪器把断言变成观测:实际形状、实际梯度、实际参数同一性、实际干预 delta、实际计时。这就是本书大半讲调试的原因:代码几秒生成的 workflow 里,代码实际做了什么的证据是稀缺资源。

在生成的语言模型上用 AI

Transformer 正是助手最自信产出、最自信误诊的 artifact。下面 prompt 拒绝解释,先要链。

Here is a generated GPT-style language model that trains but generates poorly
(or trains suspiciously well, or is slow). Do not propose a fix or explain the
loss yet.

Prove the chain, in order, and stop at the first link without evidence:

 1. TOKENIZER   decode(encode(s)) == s on real text; every ID in [0, vocab).
 2. ALIGNMENT   torch.equal(x[:, 1:], y[:, :-1]) on a real batch.
  3. CAUSALITY   put the model in eval mode; change only tokens after position i.
                Report the max delta on the prefix AND suffix. The prefix must
                remain within a stated numerical tolerance and the suffix should
                change, or the intervention is not informative.
 4. SHAPE       a per-stage ledger from [B,T] to logits, with the head-split
                round trip merge(split(q)) == q. Name the first divergence.
 5. INIT        compare initial loss with the initialization contract; use
                ln(vocab_size) as the uniform-predictor reference, not a universal
                required value.
 6. REGISTRATION every expected parameter in named_parameters(); note any tied.
 7. GRADIENTS   present and finite for every parameter after one backward.
 8. OWNERSHIP   the optimizer's parameter ids vs the model's.
 9. UPDATE      snapshot, step, confirm every parameter moved.
10. CAPABILITY  can it overfit one tiny fixed batch to near-zero loss?

Only after all ten hold: is the loss actually good (compare to ln(vocab) and to
a validation set), and where does the step spend its time?

Do not suggest architecture changes, hyperparameter tuning, more data, a better
tokenizer, mixed precision or torch.compile until a specific link has failed.

赚回位置的是第三句:前缀后缀最大 delta 都报。让“检查因果”的助手看掩码宣布三角形。干预可证伪——前缀非零 delta 是事实,后缀零 delta 说明测试什么都没证明——正是抓住本章最 convincing 失败的检查。

助手写得出整个模型,看得到 batching 代码,但源码检查不是 runtime 目标对齐的证明。让它证明链,不只解释损失。

你现在应该能回答什么

“损失降得快——训得好。” 快得可疑?这个语料正确模型 bottom 在 ln(vocab)/10 附近;奔 0.001 去的损失说明模型找到比下词元便宜预测的东西。查 torch.equal(x[:, 1:], y[:, :-1]),干预查因果。

“验证损失 excellent。” 比正确模型好?本章非因果模型 0.023 对因果模型 0.37。指标奖励看得见答案的模型。庆祝前跑未来词元干预。

“模型跑了,所以形状对。” 错头 reshape 终形状对、下游形状全对。跟踪台账;抓住它的行是头拆分往返,不是任何形状断言。

“生成垃圾,所以模型没训好。” 或:dropout 还开着(model.eval()?)、上下文没截到 block_size、采样分布被极端温度/top_k 压塌或扭曲。top_k=1 effectively 贪心选择,不是模型坏了的证据。生成是独立程序独立 bug;重训前查它们。

“慢。” 哪个阶段,哪个序列长,怎么测?性能台账拆步;序列长 sweep 是 Transformer-specific 轴。“慢”无阶段无形状不是诊断。

“加 AMP 编译它。” 哪个基线对,正确性成立吗?第 12 章契约与第 13 章正确性检查原样适用。更快错答案不是优化。

“LLM 写了训练循环,看起来对。” 那证明链:对齐、初始损失、梯度、归属、移动、一小 batch 过拟合。“看起来对”是本章每失败的 state。

练习

  1. 错位失败。 复现开篇:y = data[i : i+block] 训。两损失曲线与每生成样本各记。再从因果掩码解释,为什么从词元 t 预测词元 t 几乎免费。
  2. 分词器 forensics。 语料截断样本建分词器,全语料编码它。抓住 KeyError。再越界 ID 喂 nn.Embedding 抓住 IndexError。写防两者的两行检查。
  3. 干预证因果。 训好的因果模型拿来。只改位置 i 之后的词元,确认 0..i 输出不动。is_causal=False 重训,验证损失变好而干预挂。两 delta 都报。
  4. 形状台账。 完整模型逐阶段台账实现。reshape(B, H, T, D) 弄坏头拆分,确认输出形状不变,往返行抓住。再弄坏合,同样。
  5. 两尺度参数核算。 按模块数这个模型的参数。再 vocab_size=32000、n_embd=512 配置同样算。找出嵌入表超过一 Transformer 块的词表尺寸,解释对权重绑定什么意思。
  6. 权重绑定,测得。 自己 workload 绑定 vs 不绑定配对种子 sweep 跑。逐种子 delta、均值 spread、基线种子 variation context 报告。行为 effect resolve 否说清;别拿基线 min/max 范围当等价阈值。再决定绑不绑,exact 参数省与 uncertain 行为 effect 分开。
  7. 学习台账。 新鲜模型跑链。再逐个引入:detach 残差流、子模块替换后建的优化器、10x 学习率。每种说出台账报告的第一 link。
  8. 生成代价。 可见上下文长 block_size 下每词元毫秒测,再 sliding 窗口饱和后 show 发生什么。解释天真全前缀稠密注意力每前向为什么 O(T²) 两两 work 再算 cap 前。再估 KV 缓存怎么把新词元注意力 work 变成 O(T) 而加缓存内存 state。
  9. 这个模型的基线 variation。 同样配置八种子跑。验证损失分布报告。再自认为好的变化同样八种子评估。配对 delta judge effect,基线分布当 context,别把 min/max spread 当正式阈值。
  10. 没见过的模型上整流水线。 拿没写过的 GPT 实现。不改按顺序跑本章每台仪器,每项一行 verdict:分词器、对齐、因果、形状台账、初始化、学习台账、性能台账、生成模式。认出第一个挂的,或 certify 全过。

终检查表

按仪器组织,每项本章演示过。

TASK (Chapter 11)
  [ ] decode(encode(text)) == text
  [ ] every token ID in [0, vocab_size)
  [ ] torch.equal(x[:, 1:], y[:, :-1])          the next-token shift
  [ ] train/validation split is a real holdout

MODEL STRUCTURE (Chapters 5, 8, 10)
  [ ] n_embd % n_head == 0
  [ ] split_heads then merge_heads round-trips exactly
  [ ] every block preserves [B, T, C]; logits are [B, T, vocab]
  [ ] every expected parameter is in named_parameters(); tied weights verified
    [ ] future-token intervention leaves the prefix unchanged within tolerance and changes the suffix

OBJECTIVE AND LEARNING (Chapter 11)
    [ ] initial loss is plausible for the declared initialization; ln(vocab_size) is the uniform reference
  [ ] loss is finite; one-example cross entropy reproduces by hand
  [ ] gradients present and finite for every parameter
  [ ] optimizer owns every trainable parameter
  [ ] parameters move after a step
  [ ] the model overfits one tiny batch

PERFORMANCE (Chapters 12, 13)
  [ ] the step is decomposed into phases, synchronized
  [ ] throughput and peak memory measured, not assumed
  [ ] batch-size and sequence-length behaviour measured
  [ ] compilation benchmarked warm, correctness checked

GENERATION (this chapter)
  [ ] greedy works before sampling is added
  [ ] context truncated to block_size every step
  [ ] model.eval() -- dropout is off
  [ ] temperature > 0; top-k bounded by vocab size; probs finite

COMPARABILITY (Chapter 14)
    [ ] this model's seed-only baseline variation is measured
  [ ] comparisons use shared seeds when pairing is valid
  [ ] the run record carries config, tokenizer, seed, environment

本书建了什么,没建什么

十五章,从一标量参数开始,到拆得开的语言模型结束。through-line 从不是模型——是让隐藏结构可见、找到它与意图第一次分歧的 practice。

本书 deliberate 没建的,每样现在挂哪:

  • KV 缓存与 fast 推理——挂本章生成循环:天真全前缀前向在可见上下文上重算稠密注意力,缓存改新词元注意力复用过去 key/value、对它们做 O(T) 注意力 work。
  • 分布式训练——挂第 12 章阶段分解与第 5 章参数归属,现在跨进程。
  • 更好分词(BPE、byte-level)——挂文本→ID 边界与第 7 章表示契约;模型不在乎 ID 怎么造的。
  • AMP 之外的量化混合精度——挂第 12 章 dtype 与内存核算。
  • Serving、batching、流——挂第 6 章生产者/消费者模型与第 12 章延迟 vs 吞吐区分。
  • 规模评估——挂第 14 章基线 variation 测量与评估路径 fingerprint。

首性原理 build 里暴露核心机制,这些一概不需要。生产规模上几个成自己独立的基础工程 concern。优势是它们现在挂在已能检查的系统上,approach 时问加了什么 state、哪个契约变了、什么证据说明干预帮忙——而不是孤立 API 调进来 hope over。

最后的话

PyTorch 里最有用的技能不是记函数名。是看着跑的模型问:

What tensor is this?
What shape should it have, and what does each dimension mean?
Where did this value come from?
Does the gradient reach this parameter, and did the optimizer move it?
Is the target still describing the input?
What did this optimization actually improve?
Is this run really better, or does it just look that way?

答得出这些,抽象不再魔法。助手替你写下一千行时,还知道怎么查它们 work 不 work。

这就是全部要点。GPT 风格模型重要,但从不是终点。终点是模型做出没预料的事时,你不猜就知道怎么查为什么。