Math-04.优化-05.学习率与调度

本页专讲学习率 $\eta$ 及其调度(learning rate schedule)——往往比换优化器更影响训练成败。

段末注释Warmup(预热)在训练初期线性增大学习率,避免大 lr 下 Adam 二阶矩未稳定时的更新过激;Cosine decay(余弦退火)后期平滑降低 lr。

系列入口00.系列规划 | 前置:04 Adam


1. 学习率的作用(D2–D3)

图 1 lr 过大 vs 过小

更新 $\boldsymbol{\theta}_{t+1} = \boldsymbol{\theta}_t - \eta \mathbf{g}_t$:

$\eta$ 现象
过大 loss 震荡、发散、NaN
过小 收敛慢、陷 plateau
合适 稳定下降、良好泛化

经验:从 $10^{-3}$(Adam)或 $0.1$(SGD+动量)试起;观察 train/val loss 曲线调参。


2. 常见调度策略(D3)

图 2 调度曲线对比

Step decay:每 $T$ epoch 乘 $\gamma$(如 0.1)

$$
\eta_t = \eta_0 \cdot \gamma^{\lfloor t/T \rfloor}
$$

Cosine annealing

$$
\eta_t = \eta_{\min} + \frac{1}{2}(\eta_{\max} - \eta_{\min})\left(1 + \cos\frac{t\pi}{T}\right)
$$

Warmup + cosine(Transformer 预训练常见):

  • $t < T_w$:$\eta_t = \eta_{\max} \cdot t / T_w$
  • $t \ge T_w$:cosine 降至 $\eta_{\min}$

OneCycleLR:先升后降,Super-Convergence 论文。

ReduceLROnPlateau:验证 loss 平台时自动降 lr。


3. 与 batch size(D6–D7)

图 3 大 batch 与 lr scaling

Linear scaling rule(Goyal et al.):batch 增 $k$ 倍,lr 近似增 $k$ 倍(需 warmup 配合)。

场景 建议
小数据 tabular lr $10^{-3}$–$10^{-2}$,小 batch
ImageNet SGD lr 0.1,batch 256,Momentum
BERT/GPT 预训练 warmup 4k–10k steps + cosine
LoRA 微调 lr $10^{-4}$–$10^{-3}$,常 高于 全量微调
酶/蛋白 LM AdamW + cosine + 小 warmup

Math-03/20 LoRA酶改造-06


4. 局限(D8)

图 4 局限

误用 说明
无 warmup 大 batch 初期不稳定
调度与 epoch/step 混淆 PyTorch scheduler 按 step 或 epoch 需对齐
只调 lr 不调 weight decay AdamW 两者耦合任务表现
复制论文 lr 不改 batch scaling 规则失效

5. PyTorch 示例(D12)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import torch
from torch.optim.lr_scheduler import CosineAnnealingLR, LinearLR, SequentialLR

model = torch.nn.Linear(10, 1)
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)

warmup = LinearLR(opt, start_factor=0.01, total_iters=100)
cosine = CosineAnnealingLR(opt, T_max=900, eta_min=1e-6)
scheduler = SequentialLR(opt, schedulers=[warmup, cosine], milestones=[100])

for step in range(1000):
# ... loss.backward(); opt.step()
scheduler.step()
if step % 200 == 0:
print(step, scheduler.get_last_lr()[0])

6. 小结

Warmup + cosine 是大模型训练标配;LoRA 微调常用较大 constant lr 或短 cosine。工程细节见 10 DL 训练实践

系列导航04 Adam | 10 DL 实践

-------------本文结束感谢您的阅读-------------