56 / 90

第 56 天:第 8 周总复习:从优化器到检查点,以及资源规划

回忆并串联第 50-55 天(AdamW、学习率调度、训练步、采样、评估、检查点),再补上云端训练唯一需要的新工具:参数、显存与算力的估算。

模型与预训练 480 分钟有效研习(8 小时)
01 120 分钟

新内容:参数、显存与算力估算

Agent 辅助工程检查

前置要求

第 47 天的块参数统计、第 48 天的权重共享、第 50 天的 AdamW、第 55 天的检查点。

学习目标

精确统计 GPT 的参数量,换算为推理和训练显存,并用 6ND 法则估算训练 FLOPs、时长和费用。

操作指引

这是今天唯一的新内容,其余时间复习第 8 周。第 58、59、64、65 天会复用这些公式。
1. 参数(d = n_embd,V = 词表大小,L = 上下文长度):嵌入 V*d + L*d;每块 12*d^2(注意力 4*d^2,MLP 8*d^2)+ 4*d(两个 LayerNorm);最终 LayerNorm 2*d;共享权重的输出头不额外计数。该公式不含线性层偏置:GPT-2 每块有 9*d 个(QKV 3d、注意力输出 d、MLP 4d + d)。用 PyTorch 的 sum(p.numel()) 核对结果;同一公式算出 GPT-2 Medium(350M:d = 1,024,24 块)为 354,601,984,含偏置为 354,823,168。
2. 仅权重的显存:每个参数 4 字节(FP32)、2(FP16/BF16)、1(INT8)、0.5(INT4)。
3. 混合精度 AdamW 训练每个参数占 16 字节(ZeRO 论文):FP16 权重 2 + FP16 梯度 2 + FP32 主权重、一阶矩、二阶矩 4 + 4 + 4。激活值另算,随批大小和上下文增长;CUDA 上下文约再加 1 GB。
4. 算力:C = 6 * N * D FLOPs(前向 2ND,反向 4ND)。时长 = C / (GPU 数 * 峰值 FLOP/s * MFU * 3600),MFU 通常为 30-50%。

自主演练与记录

1. GPT-2 Small:V = 50,257,L = 1,024,n_layer = 12,n_embd = 768,共享输出头。用上面的公式统计参数量,再算出包含 GPT-2 线性层偏置时的参数量。FP16 权重占多少字节?
2. 一个 10 亿参数的模型用混合精度 AdamW 训练,在当前批大小下激活值需要 8 GB。能放进 24 GB 的 GPU 吗?
3. 在一张 A100(BF16 峰值 312 TFLOP/s)上以 40% MFU、每小时 $1.50 用 10B token 训练 125M 模型。给出 FLOPs、时长和费用。

独立掌握标准

能分别在含和不含线性层偏置时得到精确参数量,用每参数 16 字节法则预测显存不足,并由 6ND 和 MFU 算出时长与费用。

权威源资源与权利证明

linking arXiv non-exclusive license / Open Access

Scaling Laws for Neural Language Models

作者 / 机构: Jared Kaplan, Sam McCandlish, Tom Henighan, Tom B. Brown, Benjamin Chess, Rewon Child, Scott Gray, Alec Radford, Jeffrey Wu, Dario Amodei | 原始出处链接 ↗

对应章节 / 时间戳: Section 2.1 Parameter and Compute Scaling of Transformers (C ≈ 6N FLOPs per token)

验证版本与日期: arXiv:2001.08361v1 (Verified: 2026-10-30)

入选理由:

Foundational empirical study formulating power laws governing cross-entropy loss with respect to model parameters N, dataset size D, and compute C.

来源前置条件:

Basic calculus, logarithms, and parameter counting fundamentals.

安全回退方案(离线弹性):

Scaling formulas, power-law exponents, and parameter compute trade-offs are derived in the lesson text.

对比候选资源与选型分析 (2)

Early formulation of power-law scaling; Kaplan focuses explicitly on autoregressive transformer language models.

General vision/translation scaling; Kaplan specifically establishes modern decoder-only LLM compute budgeting.

linking CC-BY 4.0

Transformer Math 101

作者 / 机构: Quentin Anthony, Stella Biderman, Hailey Schoelkopf | 原始出处链接 ↗

对应章节 / 时间戳: Compute Requirements (C = 6PD) and Memory Requirements: Training

验证版本与日期: EleutherAI Research Blog (Verified: 2026-10-30)

入选理由:

Widely cited, practical industry guide deriving 6ND compute FLOPs, activation memory, KV cache size, and VRAM estimation.

来源前置条件:

Transformer matrix dimensions and matrix multiplication FLOP counting.

安全回退方案(离线弹性):

The 6ND derivation (2ND forward, 4ND backward) and peak VRAM estimation models are fully worked out in the curriculum.

对比候选资源与选型分析 (2)

Rigorous academic formulation; Transformer Math 101 provides accessible step-by-step arithmetic equations.

Kaplan et al. Section 2.1 Compute Budgeting ↗ compared_alternative [Open Access]

Original 6ND approximation; EleutherAI expands on activation memory and KV cache.

linking arXiv non-exclusive license / Open Access

ZeRO: Memory Optimizations Toward Training Trillion Parameter Models

作者 / 机构: Samyam Rajbhandari, Jeff Rasley, Olatunji Ruwase, Yuxiong He | 原始出处链接 ↗

对应章节 / 时间戳: Section 3.1 Model States: Optimizer States, Gradients and Parameters (2Ψ + 2Ψ + KΨ = 16Ψ bytes, K = 12)

验证版本与日期: SC20 / arXiv:1910.02054v3 (Verified: 2026-10-30)

入选理由:

Source of the 16 bytes per parameter accounting for mixed-precision Adam that the lesson's memory arithmetic uses.

来源前置条件:

Adam optimizer mechanics from Day 34 and parameter memory arithmetic.

安全回退方案(离线弹性):

Complete analytical formulas for bytes-per-parameter across AdamW vs SGD and mixed precision are fully provided.

对比候选资源与选型分析 (2)

Focuses on tensor slicing and inter-GPU communication; ZeRO provides the standard breakdown of optimizer and parameter memory footprints.

Micikevicius et al. Mixed Precision Training ↗ compared_alternative [Open Access]

Foundational mixed-precision paper; ZeRO formalizes the exact 16-byte Adam state footprint.

02 120 分钟

复习练习:AdamW、调度、裁剪与采样(第 50-52 天)

独立掌握检查(无 AI 辅助)

前置要求

第 50 天的 AdamW 与学习率调度、第 51 天的训练步与梯度裁剪、第 52 天的采样。闭卷完成,之后再用第 50-52 天的笔记核对。

学习目标

凭记忆重算一次 AdamW 更新、调度的关键节点、裁剪系数,以及温度加 top-p 后的分布。

操作指引

这是提取练习:先作答,再对照笔记。1) 按第 50 天写出带偏差修正和解耦权重衰减的 AdamW 更新式,并回忆哪些张量不做衰减。2) 写出第 50 天线性预热加余弦衰减的 get_lr(it)。3) 写出第 51 天的五行训练步和裁剪规则。4) 按第 52 天应用温度和 top-p。

自主演练与记录

1. 一次 AdamW 更新:w0 = 2.0,g = 0.4,lr = 0.01,weight_decay = 0.1,beta1 = 0.9,beta2 = 0.999,忽略 eps。求 m_hat、v_hat 和 w1。
2. 按第 50 天的规则,以下哪些做权重衰减:注意力 W^Q、LayerNorm 增益、MLP 偏置、token 嵌入?
3. 用 100 步预热到 lr_max = 1e-3,在第 1,100 步余弦衰减到 lr_min = 1e-4。给出第 50、100、600、1,100 和 2,000 步的 lr。
4. 全局梯度范数为 4.0,max_norm = 1.0。clip_grad_norm_ 会给每个梯度乘以多少?按顺序写出训练步。
5. logits [2, 1, 0],温度 0.5:求概率,再求 top-p = 0.9 之后的分布。

独立掌握标准

不看笔记即可正确得到 w1 = 1.988、五个调度值、裁剪系数 0.25 和 top-p 后的分布,并给出正确的衰减分组。

权威源资源与权利证明

linking arXiv non-exclusive license / Open Access

Decoupled Weight Decay Regularization

作者 / 机构: Ilya Loshchilov, Frank Hutter | 原始出处链接 ↗

对应章节 / 时间戳: Section 2 Decoupling the Weight Decay from the Gradient-Based Update (Algorithm 2, AdamW)

验证版本与日期: ICLR 2019 / arXiv:1711.05101v3 (Verified: 2026-10-30)

入选理由:

Foundational primary literature defining AdamW, demonstrating that L2 regularization does not equal decoupled weight decay in adaptive gradient algorithms.

来源前置条件:

Stochastic gradient descent, L2 regularization, and momentum concepts from Days 31-33.

安全回退方案(离线弹性):

All update equations and mathematical proofs are self-contained in the curriculum lessons.

对比候选资源与选型分析 (2)

Original Adam algorithm implementing L2 regularization via gradient addition, leading to sub-optimal generalization compared to decoupled weight decay.

PyTorch torch.optim.AdamW documentation ↗ compared_alternative [Modified BSD]

Standard library reference; Loshchilov & Hutter provides theoretical mathematical derivations and empirical justification.

linking MIT

nanoGPT: train.py pretraining loop

作者 / 机构: Andrej Karpathy | 原始出处链接 ↗

对应章节 / 时间戳: train.py: optimizer = model.configure_optimizers(weight_decay, learning_rate, (beta1, beta2), device_type); train.py: get_lr(it): linear warmup over warmup_iters, cosine decay to min_lr by lr_decay_iters; clip_grad_norm_(grad_clip) in the training loop

验证版本与日期: Git master commit 71c3905 (Verified: 2026-10-30)

入选理由:

Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.

来源前置条件:

Python, PyTorch, and Day 46-48 Transformer model architecture.

安全回退方案(离线弹性):

Runnable pretraining scripts and step-by-step tensor mechanics are fully self-contained in the curriculum lessons.

对比候选资源与选型分析 (2)
Hugging Face Accelerate / Trainer ↗ compared_alternative [Apache-2.0]

Heavy abstraction layer wrapping distributed training; nanoGPT exposes raw PyTorch loops without framework overhead.

Megatron-LM (NVIDIA) ↗ compared_alternative [BSD-3-Clause]

High-performance enterprise distributed framework; unsuitable for local educational first-principles comprehension.

03 120 分钟

复习实践:诚实评估与可恢复的检查点(第 53-55 天)

Agent 辅助工程检查

前置要求

第 53 天的评估与困惑度、第 54 天的失败案例库与消融实验、第 55 天的检查点,以及用于估算大小的第 56 天活动 1。

学习目标

把第 8 周的评估和检查点规则用在一次小型预训练上:诚实解读数字、诊断失败、估算可恢复检查点的大小。

操作指引

你在审查同事的一次 124M 参数训练(活动 1 中的 N = 124,356,864)。1) 按第 53 天把验证损失换算成困惑度并判断是否过拟合。2) 用第 54 天的失败案例库给样本的失败分类,并计算 Distinct-2。3) 按第 55 天的规则检查其检查点,再用今天的估算方法算出大小。

自主演练与记录

1. 最终训练损失 1.62,最佳验证损失在第 3,000 步为 2.0794,第 5,000 步验证损失为 2.31。求最佳困惑度,判断是否过拟合,并说明应保留哪个检查点。
2. 同事先打乱 token 再按 90/10 切分。问题在哪里?正确的切分方法是什么?
3. 一个贪心解码样本为“a b a b a b”。说出失败类型并计算 Distinct-2。
4. 他们的检查点只保存了 model.state_dict(),恢复后损失突然跳高。解释原因,并写出一个能干净恢复、采用原子写入的 payload。
5. 包含 FP32 权重和 AdamW 两个矩时,这个检查点有多大?

独立掌握标准

能给出 PPL 8.0 和正确的检查点选择,指出泄漏和循环,算出 Distinct-2 = 0.4,解释恢复后的跳高,写出完整的原子 payload,并估算其大小约为 1.49 GB。

权威源资源与权利证明

linking MIT

nanoGPT: model.py architecture implementation

作者 / 机构: Andrej Karpathy | 原始出处链接 ↗

对应章节 / 时间戳: N/A

验证版本与日期: Git master (Verified: 2026-10-30)

入选理由:

Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.

来源前置条件:

Python, PyTorch, and Day 43-45 attention fundamentals.

安全回退方案(离线弹性):

Local models and classes in the curriculum mirror nanoGPT semantics directly.

对比候选资源与选型分析 (2)
GPT-2 TensorFlow source (OpenAI) ↗ compared_alternative [Modified MIT License]

Original legacy TensorFlow 1.x code; nanoGPT provides clean modern PyTorch equivalent.

Llama 2 / 3 PyTorch source (Meta) ↗ compared_alternative [Llama 2 Community License]

Includes advanced production features (RoPE, GQA), but nanoGPT's simplicity is ideal for the core Days 46-48 assembly.

linking arXiv non-exclusive license / Open Access

The Curious Case of Neural Text Degeneration

作者 / 机构: Ari Holtzman, Jan Buys, Li Du, Maxwell Forbes, Yejin Choi | 原始出处链接 ↗

对应章节 / 时间戳: N/A

验证版本与日期: ICLR 2020 / arXiv:1904.09751v2 (Verified: 2026-10-30)

入选理由:

Primary source introducing Nucleus (Top-p) sampling and analyzing the failure of greedy decoding (loops, repetition).

来源前置条件:

Softmax probabilities, cumulative probability distributions from Days 25-27 and 41-42.

安全回退方案(离线弹性):

Top-p truncation algorithms and worked probability cutoffs are completely explained in the lesson.

对比候选资源与选型分析 (2)

Introduces top-k sampling; Holtzman et al. dynamic nucleus threshold is compared directly against top-k.

Hugging Face Generation Strategies Guide ↗ compared_alternative [Apache 2.0]

Practical library guide; Holtzman provides the foundational mathematical reasoning.

04 120 分钟

第 8 周测评:124M 预训练的训练前计划(第 50-56 天)

独立掌握检查(无 AI 辅助)

前置要求

第 50-55 天以及第 56 天活动 1-3。闭卷,声明不使用 AI;可以使用计算器。

学习目标

独立写出一份完整、可核查的训练前计划,把第 8 周的优化器、训练循环、评估和检查点规则与今天的资源估算结合起来。

操作指引

为活动 1 的模型(N = 124,356,864)规划一次 2.5B token 的预训练,使用一张 A100 40 GB(峰值 312 TFLOP/s,假设 MFU 为 35%),每小时 $1.20。每个优化器步使用 524,288 个 token(微批次 16 x 1,024 个 token,累积 32 步)。计划中的每个数字都要写出公式,并注明哪些数字是需要用最初几个真实步核对的预测值。

自主演练与记录

1. 覆盖 2.5B token 需要多少个优化器步?预热 2% 是多少步?lr_max = 6e-4、lr_min = 6e-5 时,余弦阶段中点的 lr 是多少(第 50 天)?
2. 按每参数 16 字节计算静态训练显存。能放进 40 GB 吗?真正限制微批次大小的是什么?
3. 总 FLOPs、时长和费用。
4. 写出评估和检查点策略:多久调用一次 estimate_loss、如何选择保留的检查点、检查点包含什么、报告哪些内容(第 51、53、55 天)。
5. 用两句话写出最终报告中这个规模的模型能说明什么、不能说明什么(第 54 天)。

独立掌握标准

能给出 4,769 步、约 95 步预热、中点 lr 3.3e-4、约 1.99 GB 静态显存、1.865e18 FLOPs、约 4.74 小时和 $5.69、完整的评估与检查点策略以及诚实的能力说明,并写出每个数字的公式。

权威源资源与权利证明

linking arXiv non-exclusive license / Open Access

Decoupled Weight Decay Regularization

作者 / 机构: Ilya Loshchilov, Frank Hutter | 原始出处链接 ↗

对应章节 / 时间戳: N/A

验证版本与日期: ICLR 2019 / arXiv:1711.05101v3 (Verified: 2026-10-30)

入选理由:

Foundational primary literature defining AdamW, demonstrating that L2 regularization does not equal decoupled weight decay in adaptive gradient algorithms.

来源前置条件:

Stochastic gradient descent, L2 regularization, and momentum concepts from Days 31-33.

安全回退方案(离线弹性):

All update equations and mathematical proofs are self-contained in the curriculum lessons.

对比候选资源与选型分析 (2)

Original Adam algorithm implementing L2 regularization via gradient addition, leading to sub-optimal generalization compared to decoupled weight decay.

PyTorch torch.optim.AdamW documentation ↗ compared_alternative [Modified BSD]

Standard library reference; Loshchilov & Hutter provides theoretical mathematical derivations and empirical justification.

linking BSD-3-Clause

PyTorch Tutorial: Saving and Loading Models

作者 / 机构: PyTorch Documentation Team | 原始出处链接 ↗

对应章节 / 时间戳: Saving & Loading a General Checkpoint for Inference and/or Resuming Training

验证版本与日期: PyTorch 2.x Documentation (Verified: 2026-10-30)

入选理由:

Official documentation detailing state_dict serialization, optimizer state saving, and safe loading patterns.

来源前置条件:

Python, PyTorch tensors and nn.Module basics.

安全回退方案(离线弹性):

All checkpoint serialization semantics, dictionary schema keys, and safe recovery steps are self-contained in lesson code.

对比候选资源与选型分析 (2)
TensorFlow tf.train.Checkpoint Guide ↗ compared_alternative [Apache 2.0]

TensorFlow trackable checkpoint architecture; PyTorch's explicit dictionary is our target implementation standard.

Hugging Face Safetensors Documentation ↗ compared_alternative [Apache 2.0]

Safetensors provides safe zero-copy tensor storage without pickle, compared directly when discussing pickle execution risks.