50 / 90

第 50 日:優化動力學:AdamW 解耦權重衰減與學習率調度

推導 AdamW 權重更新公式,對比解耦權重衰減與 L2 正則化的本質差異,實現線性預熱與餘弦退火調度器。

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

AdamW 解耦權重衰減數學推導

Agent 輔助工程分析

先修要求

第 31-33 日梯度下降與動量法;L2 正則化概念。

學習目標

推導 AdamW 參數更新公式 w_{t+1} = w_t (1 - eta * lambda) - eta * m_hat_t / (sqrt(v_hat_t) + eps),闡釋傳統 Adam 中 L2 正則化的失真原因。

實驗指南

在標準 Adam 中若使用傳統 L2 正則化,其方式是將 lambda * w 直接加到損失梯度上。經過自適應二階動量除法後,歷史梯度大的參數受到的實際衰減被極度壓縮,而梯度小的參數卻被過度衰減。Loshchilov & Hutter (2019) 提出了 AdamW,將權重衰減與梯度動量解耦。計算 w_0 = 1.0, lambda = 0.1, eta = 0.01, g_1 = 0.5, beta_1 = 0.9, beta_2 = 0.999, eps = 1e-8 下的第 1 步更新。

實戰與預測記錄

1. 分別寫出含 L2 正則化的傳統 Adam 與 AdamW 的權重更新公式。
2. 手算第 1 步更新下的 m_hat_1, v_hat_1 及更新後的參數 w_1。
3. 為何解耦權重衰減能顯著改善 Transformer 模型的泛化表現?

獨立掌握標準

學習者能夠推導兩種更新公式,並手算驗證第 1 步數值結果。

權威來源與學術版權說明

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)

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

參數分組隔離:2D 與 1D 張量衰減規則

獨立完成核心推導

先修要求

活動 50-01 及第 46-48 日 Transformer 架構實現。

學習目標

將模型參數劃分為參與權重衰減(二維矩陣)與不衰減(一維偏置/歸一化向量)兩組,構建規範的優化器實例。

實驗指南

學習來源:在本活動現有的閱讀與練習時段內,參考 CS336 Assignment 1: Basics (Spring 2025 tagged release) 的 tests/adapters.py: get_adamw_cls; tests/test_optimizer.py: test_adamw,用自己的話解釋一處與本地任務的聯繫。保留現有練習與驗收檢查;若外部資料無法存取,使用課程自寫的解釋。在現代 LLM 預訓練(如 nanoGPT、LLaMA、GPT-3)中,權重衰減必須僅施加於 2D 權重矩陣(線性變換投影層、自注意力 QKV 與輸出投影、FFN 線性層)。一維偏置項與一維歸一化參數(LayerNorm 或 RMSNorm 的縮放向量 gamma)絕不能施加權重衰減。對 gamma 進行衰減會使其趨向於 0,導致殘差信號放大失真,引發訓練發散。

實戰與預測記錄

1. 編寫參數分組函數 configure_optimizers(model, weight_decay, learning_rate, betas, device)。
2. 針對包含 Linear 層(權重形狀 (768, 768),偏置形狀 (768))與 RMSNorm(縮放形狀 (768))的模型,指出哪些參數參與衰減。
3. 若錯誤地對 RMSNorm 縮放向量 gamma 施加了權重衰減,會引發何種病態表現?

獨立掌握標準

學習者能夠基於張量維度實現嚴謹的參數隔離,並給出合理的架構設計依據。

權威來源與學術版權說明

linking MIT

CS336 Assignment 1: Basics (Spring 2025 tagged release)

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

對應章節/時間戳: tests/adapters.py: get_adamw_cls; tests/test_optimizer.py: test_adamw

核驗版本與日期: 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: optimizer = model.configure_optimizers(weight_decay, learning_rate, (beta1, beta2), device_type); the 2D-decay / 1D-no-decay split is in model.py GPT.configure_optimizers

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

學習率調度策略:線性預熱與餘弦退火

Agent 輔助工程分析

先修要求

活動 50-01 與 50-02。

學習目標

實現結合線性預熱(Linear Warmup)與餘弦衰減(Cosine Decay)的學習率計算函數 get_lr(it),驗證各里程碑步數的精確取值。

實驗指南

學習來源:在本活動現有的閱讀與練習時段內,參考 CS336 Assignment 1: Basics (Spring 2025 tagged release) 的 tests/adapters.py: run_get_lr_cosine_schedule; tests/test_optimizer.py: test_get_lr_cosine_schedule,用自己的話解釋一處與本地任務的聯繫。保留現有練習與驗收檢查;若外部資料無法存取,使用課程自寫的解釋。大模型預訓練需要動態學習率調度。前 T_warmup 步學習率從 0 線性增加至 eta_max,以防止初始巨大雜亂梯度破壞權重;隨後在 T_max 步內沿餘弦曲線平滑退火至 eta_min = 0.1 * eta_max;超過 T_max 後恆定維持在 eta_min。

實戰與預測記錄

1. 給出 eta(t) 的分段數學表達式。
2. 在 eta_max = 6e-4, eta_min = 6e-5, T_warmup = 1000, T_max = 5000 下,計算 t=0, 1000, 3000, 5000 時的精確學習率。
3. 為何在 LLM 預訓練中平滑餘弦衰減明顯優於階梯式離散衰減?

獨立掌握標準

學習者能夠手算關鍵里程碑步數的學習率,並編寫出通過斷言的餘弦調度函數。

權威來源與學術版權說明

linking MIT

CS336 Assignment 1: Basics (Spring 2025 tagged release)

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

對應章節/時間戳: tests/adapters.py: run_get_lr_cosine_schedule; tests/test_optimizer.py: test_get_lr_cosine_schedule

核驗版本與日期: 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 arXiv non-exclusive license / Open Access

Decoupled Weight Decay Regularization

作者/提供方: Ilya Loshchilov, Frank Hutter | 原始來源鏈接 ↗

對應章節/時間戳: Appendix B.2 Adam with Cosine Annealing and Warm Restarts

核驗版本與日期: 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: get_lr(it): linear warmup over warmup_iters, cosine decay to min_lr by lr_decay_iters

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

獨立優化器配置與數值驗證考核

完全獨立閉卷考核

先修要求

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

學習目標

獨立編寫包含參數分組隔離與學習率調度的完整優化器構建模組,斷言驗證各參數組衰減狀態。

實驗指南

在閉卷環境下完成 Transformer 的 AdamW 初始化腳本,設置超參數 betas=(0.9, 0.95)、eps=1e-8、weight_decay=0.1,並對優化器參數組施加斷言檢測。

實戰與預測記錄

1. 給出包含解耦分組配置的完整 Python 代碼。
2. 提供一條斷言語句,確保任何 ndim < 2 的張量其 weight_decay 嚴格不大於 0。
3. 為何在語言模型預訓練中通常將 beta_2 設為 0.95,而非傳統的 0.999?

獨立掌握標準

獨立交付通過參數組斷言的優化器配置代碼,並清晰闡明 beta_2=0.95 的工程動因。

權威來源與學術版權說明

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

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.