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.