51 / 90

第 51 日:運行預訓練閉環:損失追蹤、檢查點保存與故障診斷

組裝前向-損失-反向-步進完整訓練循環,實現訓練/驗證集損失估算,安全存取檢查點,診斷損失爆炸與梯度異常。

模型、預訓練與 LoRA 480 分鐘專注學習(8 小時)
01 120 分鐘

預訓練核心步進:前向、損失、反向傳播與梯度裁剪

Agent 輔助工程分析

先修要求

第 49 日數據加載器與第 50 日 AdamW 優化器。

學習目標

執行經典的 5 步訓練迭代,理解 set_to_none=True 的顯存釋放機制,施加全局 L2 範數梯度裁剪。

實驗指南

學習來源:在本活動現有的閱讀與練習時段內,參考 CS336 Assignment 1: Basics (Spring 2025 tagged release) 的 tests/adapters.py: run_gradient_clipping; tests/test_nn_utils.py: test_gradient_clipping,用自己的話解釋一處與本地任務的聯繫。保留現有練習與驗收檢查;若外部資料無法存取,使用課程自寫的解釋。在每個預訓練步進中:(1) optimizer.zero_grad(set_to_none=True) 釋放梯度張量;(2) logits, loss = model(x, y) 計算前向傳播與交叉熵損失;(3) loss.backward() 累加梯度;(4) torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) 將全局梯度 L2 模長約束至不超過 1.0;(5) optimizer.step() 更新參數。分析梯度裁剪防止權重暴走的重要機理。

實戰與預測記錄

1. 給出執行一次完整訓練迭代的 Python 代碼。
2. 若未裁剪的全局梯度模長 ||g||_2 = 5.0 且 max_norm = 1.0,各個參數的梯度會被乘以何種縮放比例?
3. 為何 optimizer.zero_grad(set_to_none=True) 在工程性能上顯著優於默認的 zero_grad()?

獨立掌握標準

學習者能夠編寫規範的 5 步訓練邏輯,準確計算梯度裁剪係數,並闡明 set_to_none=True 的顯存優勢。

權威來源與學術版權說明

linking MIT

CS336 Assignment 1: Basics (Spring 2025 tagged release)

作者/提供方: Stanford University CS336 Staff | 原始來源鏈接 ↗

對應章節/時間戳: tests/adapters.py: run_gradient_clipping; tests/test_nn_utils.py: test_gradient_clipping

核驗版本與日期: spring2025 tag; README, tests and MIT LICENSE checked 2026-11-01

入選理由:

Lead assignment-driven source for pretraining component practice and tests. nanoGPT remains a compact historical code-reading companion, not the current recommended training curriculum.

先修背景:

Fluent Python, PyTorch, and linear algebra

安全降級(離線韌性):

Local self-contained pretraining scripts run on standard local CPUs or budget GPUs without Stanford cluster dependency.

候選來源對比與遴選分析 (2)
Karpathy nanoGPT ↗ compared_alternative [MIT]

Simpler code layout, useful complementary reference for minimal PyTorch Transformer.

Hugging Face Transformers Course ↗ compared_alternative [Apache-2.0]

High-level API focus rather than building from raw tensor fundamentals.

linking MIT

nanoGPT: train.py pretraining loop

作者/提供方: Andrej Karpathy | 原始來源鏈接 ↗

對應章節/時間戳: train.py: training loop (while True): forward under ctx, scaler.scale(loss).backward(), clip_grad_norm_(grad_clip), scaler.step(optimizer)

核驗版本與日期: 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.

02 120 分鐘

訓練集與驗證集損失估算及過擬合追蹤

獨立完成核心推導

先修要求

活動 51-01 與 PyTorch 自動求導機制。

學習目標

在 torch.no_grad() 與 model.eval() 環境下實現 estimate_loss 函數,監控訓練集與驗證集損失差異以檢測過擬合。

實驗指南

單批次訓練損失具有較強隨機噪聲。為了準確評估模型泛化能力,需定期(如每 250 步)分別在 train 和 val 上採樣 200 個批次並取均值。切換至 model.eval() 關閉 Dropout 隨機性,並在 torch.no_grad() 上下文中運行以避免在顯存中保留龐大的反向傳播計算圖。

實戰與預測記錄

1. 給出 estimate_loss(model, eval_iters) 的 Python 實現。
2. 若在 estimate_loss 中遺漏了 torch.no_grad(),會引發何種嚴重的顯存故障?
3. 如何通過訓練集與驗證集損失曲線的分離趨勢診斷過擬合?

獨立掌握標準

獨立實現規範的評估函數,正確配置 eval 模式與 no_grad,並準確認定過擬合特徵。

權威來源與學術版權說明

linking MIT

nanoGPT: train.py pretraining loop

作者/提供方: Andrej Karpathy | 原始來源鏈接 ↗

對應章節/時間戳: train.py: estimate_loss() averages eval_iters batches per split; run every eval_interval

核驗版本與日期: 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.

linking MIT

CS336 Assignment 1: Basics (Spring 2025 tagged release)

作者/提供方: Stanford University CS336 Staff | 原始來源鏈接 ↗

對應章節/時間戳: README setup; tests/adapters.py; tests/test_optimizer.py; tests/test_nn_utils.py; tests/test_serialization.py

核驗版本與日期: spring2025 tag; README, tests and MIT LICENSE checked 2026-11-01

入選理由:

Lead assignment-driven source for pretraining component practice and tests. nanoGPT remains a compact historical code-reading companion, not the current recommended training curriculum.

先修背景:

Fluent Python, PyTorch, and linear algebra

安全降級(離線韌性):

Local self-contained pretraining scripts run on standard local CPUs or budget GPUs without Stanford cluster dependency.

候選來源對比與遴選分析 (2)
Karpathy nanoGPT ↗ compared_alternative [MIT]

Simpler code layout, useful complementary reference for minimal PyTorch Transformer.

Hugging Face Transformers Course ↗ compared_alternative [Apache-2.0]

High-level API focus rather than building from raw tensor fundamentals.

03 120 分鐘

檢查點序列化、原子保存與訓練恢復

Agent 輔助工程分析

先修要求

活動 51-01 與 51-02。

學習目標

將模型權重、AdamW 優化器動量狀態、迭代步數與驗證集損失序列化為檢查點,實現精確無縫續訓。

實驗指南

學習來源:在本活動現有的閱讀與練習時段內,參考 CS336 Assignment 1: Basics (Spring 2025 tagged release) 的 tests/adapters.py: run_save_checkpoint, run_load_checkpoint; tests/test_serialization.py: test_checkpointing,用自己的話解釋一處與本地任務的聯繫。保留現有練習與驗收檢查;若外部資料無法存取,使用課程自寫的解釋。預訓練通常持續數天,極易因硬件故障或算力搶佔而中斷。檢查點必須持久化保存:model.state_dict()、optimizer.state_dict()、iter_num、best_val_loss 與 config。為防止保存過程中斷產生損壞的半寫文件,應採用原子寫入模式(先寫入臨時文件,再用 os.replace 重命名)。

實戰與預測記錄

1. 給出包含原子寫入機制的大模型檢查點保存代碼片段。
2. 給出從檢查點恢復模型與優化器狀態的代碼。
3. 若在恢復訓練時僅加載了模型權重而漏掉了 optimizer.state_dict(),會引發何種優化異常?

獨立掌握標準

學習者能夠編寫魯棒的原子檢查點存取代碼,並準確解釋優化器狀態丟失引發的冷啟動異常。

權威來源與學術版權說明

linking MIT

CS336 Assignment 1: Basics (Spring 2025 tagged release)

作者/提供方: Stanford University CS336 Staff | 原始來源鏈接 ↗

對應章節/時間戳: tests/adapters.py: run_save_checkpoint, run_load_checkpoint; tests/test_serialization.py: test_checkpointing

核驗版本與日期: spring2025 tag; README, tests and MIT LICENSE checked 2026-11-01

入選理由:

Lead assignment-driven source for pretraining component practice and tests. nanoGPT remains a compact historical code-reading companion, not the current recommended training curriculum.

先修背景:

Fluent Python, PyTorch, and linear algebra

安全降級(離線韌性):

Local self-contained pretraining scripts run on standard local CPUs or budget GPUs without Stanford cluster dependency.

候選來源對比與遴選分析 (2)
Karpathy nanoGPT ↗ compared_alternative [MIT]

Simpler code layout, useful complementary reference for minimal PyTorch Transformer.

Hugging Face Transformers Course ↗ compared_alternative [Apache-2.0]

High-level API focus rather than building from raw tensor fundamentals.

linking MIT

nanoGPT: train.py pretraining loop

作者/提供方: Andrej Karpathy | 原始來源鏈接 ↗

對應章節/時間戳: train.py: checkpoint dict {'model', 'optimizer', 'model_args', 'iter_num', 'best_val_loss', 'config'} written with torch.save to out_dir/ckpt.pt; the init_from == 'resume' branch reloads it

核驗版本與日期: 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.

04 120 分鐘

預訓練閉環實操與異常診斷考核

完全獨立閉卷考核

先修要求

完成活動 51-01 至 51-03。

學習目標

獨立運行完整的預訓練腳本,誠實記錄觀測指標,診斷預訓練異常(損失突變為 NaN、陷入平台等)。

實驗指南

在閉卷環境下診斷大模型預訓練中最常見的運行異常:(1) 損失突變發散為 NaN;(2) 損失長時間停滯在 ln(V) ≈ 10.8。在小型數據集上執行 50 步參考訓練,並如實彙報損失下降指標,嚴禁作出無依據的收斂承諾。

實戰與預測記錄

1. 列舉導致預訓練損失變為 NaN 的三大主因及相應修復方案。
2. 若損失在訓練上千步後依然死鎖在 10.8 左右,表明哪個系統環節發生了故障?
3. 彙報在小型詞元數據集上運行 50 步訓練所觀測到的實際損失變化特徵。

獨立掌握標準

學習者能夠準確排查常見預訓練異常,並在不作無根據收斂保證的前提下客觀描述訓練行為。

權威來源與學術版權說明

linking MIT

nanoGPT: train.py pretraining loop

作者/提供方: Andrej Karpathy | 原始來源鏈接 ↗

對應章節/時間戳: train.py: config defaults, get_lr(it) and the training loop (while True)

核驗版本與日期: 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.

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.