Appearance
第9章 · TinyGPT 预训练、恢复与生成 — 学习走查
状态:已完成 · Colab:已通过(复用第2章 notebook) · 教程:第9章 TinyGPT
本章范围核对
| 范围 | 状态 |
|---|---|
| 阶段一~三:模型结构 / one-batch overfit / checkpoint 与恢复 | 已读并真实执行 |
clean-room transformer-block 合同 | 已从空白接口独立实现 |
clean-room tinygpt-training 合同 | 已读合同与 smoke 要求,见未决项 |
| 真实 CLI 训练(smoke / train / inspect / resume) | 全部真实跑通 |
| 判分测试(train_cli / trainable_tinygpt / checkpoint_recovery) | 8 passed |
| 位置表示 / 长上下文 / 生产级问题 | 已读(概念层) |
本地执行
1. 判分测试
bash
PYTHONPATH=python python -m pytest python/tests/test_train_cli.py python/tests/test_trainable_tinygpt.py python/tests/test_checkpoint_recovery.py -qtext
8 passed in 5.81s2. 真实训练(不联网、不读凭据的合成 byte 语料)
smoke(configs/tiny-cpu.json,12 步):
json
{"command":"smoke","config_hash":"51eccf62...","data_hash":"378111c2...",
"final_loss":4.942299842834473,"final_validation_loss":4.91535758972168,
"initial_loss":5.5558037757873535,"initial_validation_loss":5.547776222229004,
"parameter_update_norm":1.6410134414104918,"status":"ok","steps":12,"tokenizer_hash":"byte-v1"}train(同一 config):数值与 smoke 完全一致(seed 固定,可复现)。
inspect-checkpoint:
json
{"checkpoint":"tinygpt.pt","config_hash":"51eccf62...","data_hash":"378111c2...",
"metric_keys":["initial_loss","initial_validation_loss","parameter_update_norm","train_loss","validation_loss"],
"model_config_hash":"a99b84b9...","status":"ok","step":12,"tokenizer_hash":"byte-v1"}resume(关键证据 —— 见疑惑 3 的完整调试过程):
用 steps=600 的 config 先跑 8 秒被时间上限打断(实际完成 499 步, 周期 checkpoint 落在 step 450),再用同一 config resume:
json
{"command":"resume","config_hash":"771095b7...","data_hash":"378111c2...",
"final_loss":0.9885908365249634,"final_validation_loss":0.9098686575889587,
"initial_loss":1.2986786365509033,"initial_validation_loss":1.3615665435791016,
"parameter_update_norm":2.4258744064497404,"status":"ok","steps":600}权重确实被恢复的证据:resume 的 initial_validation_loss = 1.3615665435791016, 与 checkpoint 里保存的 validation_loss = 1.3616(四舍五入)逐位一致。 如果权重没恢复,这个值应该回到全新模型的 5.5478。 config_hash 与 data_hash 也前后一致——正是本章判定信号要求的 「resume 前后 config_hash 一致,loss 曲线无跳变」。
3. clean-room transformer-block 实现(私有提交,不进仓库)
从空白接口独立实现 TransformerBlock(n_embd, n_head) / forward(x, causal=True) 与 rebuild_model_chain(config, dataset, output_dir):
- pre-norm 残差:
h = x + Attn(LN(x)),y = h + FFN(LN(h)) - FFN 用 GELU,隐层 4 倍,逐位置(无跨位置信息交换)
- 完整链:embedding → N×Block → LN → 输出投影(与 embedding 权重绑定)→ CE loss → generate
实测:
text
shape ok: True finite: True causal: True not identity: True
chain initial: 0.9875 → final: 0.8411, update_norm: 0.013470
generated: [0, 1, 1, 1, 1, 1, 1]
loss decreased: True update > 0: TrueColab 执行
本章 <ColabBadge> 复用第2章已跑通的 02_python_math.ipynb。 仓库 notebooks/ 下有 08_tinygpt_pretrain.ipynb,但本章 ColabBadge 指向第2章那份。 真实 TinyGPT 训练在本地 CPU 完成(约 1 秒/百步),不需要 GPU。
疑惑与修复
疑惑 1:为什么 resume 我不传 --config,config_hash 就对不上?
第一次 resume 我只写了 --resume-from,结果 config_hash 从 51eccf62 变成 135013df,而且 steps 从 12 变成 100。
修复后的理解:resume 子命令的 --config 是可选的,不传就落到 _default_config(steps=100)(cli.py:48-49)——那是一份完全不同的配置。 本章判定信号「resume 前后 config_hash 一致」要求显式传同一个 config。 这是我的调用错误,不是仓库 bug。
疑惑 2:为什么同一 config resume 会报 max_tokens or steps did not permit a training update?
传了同一份 tiny-cpu.json(steps=12)后,resume 直接报错。
修复后的理解:checkpoint 已经跑到 step 12,而 config 的 steps 也是 12, start_step >= end_step,循环一次都不执行,losses 为空 → 主动报错。 这个 fail-closed 行为是对的——它阻止了「假装恢复了但其实什么都没训」。 要演示 resume,必须让第一次运行在到达 steps 之前被中断。
疑惑 3(本章最有价值的发现):--max-seconds 打断的运行,到底存了哪一步?
我用 steps=4000 的 config 加 --max-seconds 3,CLI 报告 steps: 217, 但我去读 checkpoint 发现 step = 1、train_loss = 5.5558(初始 loss)—— 中断点附近的进度全部丢了。
顺着 train.py:155-158 读下来,周期 checkpoint 的保存条件是:
python
if step == start_step or step + 1 == end_step or (step + 1) % max(1, config.steps // 4) == 0:保存间隔是 config.steps // 4。steps=4000 → 间隔 1000, 而运行在第 217 步就被时间上限打断,于是唯一落盘的 checkpoint 是第 1 步。
修复后的理解(也是本章 fault 表的实际含义):本章故障表写 「checkpoint 仅存参数 → 恢复时步数/rng 漂移 → 完整 dump state_dict」。 仓库确实完整 dump 了 model + optimizer + step + data/tokenizer hash, 但保存频率由 steps//4 决定——steps 越大,中断时丢失的进度越多。 这是「存什么」和「多久存一次」两个独立问题,本章只强调了前者。
我改用 steps=600(间隔 150)重做,中断于 499 步时 checkpoint 落在 step 450, resume 后 initial_validation_loss 与 checkpoint 的 validation_loss 逐位一致, 证明恢复正确。
疑惑 4:parameter_update_norm 在 smoke 里是 1.64,在 600 步配置里是 15.85,越大越好吗?
不是。我一开始以为这个数越大说明「学得越多」。
修复后的理解:它是「初始参数快照 vs 结束参数」的 L2 距离, 衡量的是参数移动了多少,不是学得好不好。它必须 > 0(证明参数确实动了, 没有「优化器没同步到参数对象」那个故障),但它和 loss 下降没有单调关系—— 步数越多它自然越大。真正的质量指标是 final_loss < initial_loss 且 val loss 同步下降(不是只有 train loss 降)。
疑惑 5:为什么 max_tokens 也会限制步数?我有 600 步的预算却只跑到 499。
remaining_steps = (max_tokens - seen_tokens) // (batch_size × block_size)。 tiny-cpu.json 的 max_tokens=50000、batch=4、block=16 → 上限 781 步。
修复后的理解:max_tokens 是总 token 预算,steps 是步数预算, 实际能跑多少取两者较小值。这是双重闸门——防止配置写错时无界训练。 我设 steps=800 时直接报错,就是因为超过了 781 的 token 上限。
证据
bash
# 判分
PYTHONPATH=python python -m pytest python/tests/test_train_cli.py python/tests/test_trainable_tinygpt.py python/tests/test_checkpoint_recovery.py -q
→ 8 passed in 5.81sbash
# 真实训练(smoke / train / inspect / resume)
python -m llm_train.cli smoke --config configs/tiny-cpu.json --output-dir .artifacts/llm_train
python -m llm_train.cli train --config configs/tiny-cpu.json --output-dir .artifacts/llm_train
python -m llm_train.cli inspect-checkpoint .artifacts/llm_train/tinygpt.pt
python -m llm_train.cli resume --config <cfg> --resume-from <ckpt>
→ status=ok;initial 5.5558 → final 4.9423(12 步);resume 后 600 步到 0.9886text
# 恢复正确性的直接证据
checkpoint 保存的 validation_loss = 1.3616
resume 的 initial_validation_loss = 1.3615665435791016 ← 逐位一致,权重已恢复
config_hash / data_hash 前后一致bash
# clean-room transformer-block
→ shape/finite/causal/not-identity 全部通过;full-chain loss 0.9875 → 0.8411核心能力自查
- one-batch overfit 三要素 — 能。
initial_loss/final_loss/parameter_update_norm三者都从 CLI 输出真实拿到, 并解释了为什么 update_norm 大不等于学得好。 - 周期 checkpoint + 恢复 + deterministic smoke — 能,并额外发现了 保存频率
steps//4与max_tokens上限两个交互约束。 - 恢复后 loss/step 与不中断轨迹一致 — 部分验证。 我验证了「resume 的 initial_validation_loss == checkpoint 保存值」(权重恢复正确), 但没有做「同 config 下中断-恢复 vs 一口气跑完」的完整轨迹对拍—— 那需要固定 seed 与逐 step 对齐,已列入未决项。
- config_hash / data_hash / tokenizer_hash 三方校验 — 能。
load_checkpoint对 model_config_hash、data_hash、tokenizer_hash 全部校验, 任一不符即抛错(fail-closed)。
闭卷解释题要点:
- AdamW 三故障:① bias correction 漏写 → 前几步步长被低估; ② weight decay 混入梯度 → 被
sqrt(v̂)扭曲(第7章已实测); ③ checkpoint 只存参数 → 优化器动量与 step 丢失,恢复后轨迹漂移。 仓库的 dump 覆盖了 model + optimizer + step + 三个 hash。 - 为什么要 per-step seed:
train.py用torch.Generator().manual_seed(config.seed + step)逐步重置生成器。这样「中断-恢复」与「一口气跑完」消费到的 batch 序列完全一致, 不需要持久化进程 RNG 状态。这是让 resume 轨迹可对拍的关键设计。
未决项
- clean-room
tinygpt-training合同(train/generate)未实现。 本章真实训练走的是仓库llm_train.cli,不是我的 clean-room 实现。 该合同要求返回model/checkpoint_path/initial_loss/final_loss/parameter_update_norm/resumed,并支持resume_from续训。 已实现的是transformer-block合同(含完整链)。按协议记为未完成,不冒充实现过。 - 「中断-恢复 vs 不中断」的完整轨迹对拍未做。 只验证了权重恢复正确(initial_validation_loss 逐位一致), 没有验证恢复后的 loss 曲线与一口气跑完严格重合。
- KV cache / 位置表示 / 长上下文只做概念阅读,属第10章范围。
.artifacts/下的训练产物不入库(git-ignored), 本笔记只保留脱敏后的命令与数值。- 第3章遗留的 SVD / Eckart-Young-Mirsky 仍未数值验证,继续挂第11章。