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.