PyTorch 学习率调度器
核对 StepLR、CosineAnnealing、ReduceLROnPlateau、SequentialLR 预热退火、CyclicLR/OneCycleLR 按批步进、自定义 LRScheduler 与断点状态恢复。
学完这一章,你能够
- 核对 StepLR、CosineAnnealing、ReduceLROnPlateau、SequentialLR 预热退火、CyclicLR/OneCycleLR 按批步进、自定义 LRScheduler 与断点状态恢复。
学习率调度作用、调用时机与状态保存
学习率决定每步参数更新幅值:过大易震荡发散,过小收敛缓慢。PyTorch 调度器遵循标准顺序——每轮或每批先执行 optimizer.step(),再执行 scheduler.step(),并用 scheduler.get_last_lr() 读取当前学习率。特别注意断点续训细节:像 StepLR 这类在步进时基于 optimizer 当前 lr 乘以 gamma 的调度器,恢复时必须同时保存并加载 optimizer.state_dict() 与 scheduler.state_dict(),只加载调度器字典会导致恢复后的学习率错位。
固定衰减与自适应/余弦调度器
固定衰减族包括 StepLR(每隔 step_size 轮乘 gamma,如 init=0.1, step=10, gamma=0.1 在第 10 轮降至 0.01、第 20 轮降至 0.001)、MultiStepLR(在指定 milestones 处衰减,如 [5, 15])与 ExponentialLR(每轮乘 gamma,通常取 0.9~0.99,避免过快衰减至零)。
ReduceLROnPlateau 根据验证指标停滞自动降学习率(监控 loss 用 mode='min',监控 accuracy 用 mode='max')。重要版本核对:PyTorch 2.10 已移除 verbose=True 参数,传入会报 TypeError,应改为显式读取 get_last_lr();本站实测连续停滞后学习率精确折半至 0.05。CosineAnnealingLR 按余弦曲线平滑退火至 eta_min,CosineAnnealingWarmRestarts 则周期重启学习率以探索多个局部极小值。
预热组合(SequentialLR)与按批循环调度
大批量与 Transformer 训练通常在初期配合 LinearLR 线性预热(或 ConstantLR 常数阶段),再用 SequentialLR(optimizer, schedulers=[warmup, cosine], milestones=[warmup_epochs]) 串联余弦退火——编写时切勿漏传 optimizer 与 milestones。本站实测 5 轮线性预热接 25 轮余弦退火:第 1 轮 lr=0.0028、第 5 轮达峰 0.01、第 30 轮平稳收束至 1e-5。
CyclicLR(支持 triangular、triangular2、exp_range 三种振幅模式)与 OneCycleLR 必须按 batch 而非按 epoch 调用 step()!本站实测 CyclicLR(triangular2) 第二个周期的振幅严格减半;OneCycleLR(max_lr=0.1, total_steps=30, div_factor=10, final_div_factor=1000) 在步进 29 次(连同初始步共 30 步)期间先升至 0.1 峰值,最终降至 initial_lr / final_div_factor = 1e-5(注意 final_div_factor 除的是 initial_lr 而非 max_lr)。
自定义调度器、实测轨迹对比与选型速查
更灵活的策略可用 LambdaLR 为多参数组传入独立乘数函数列表(如主干与分类头分别衰减),或继承 torch.optim.lr_scheduler.LRScheduler(PyTorch 2.0+ 公开基类)实现自定义 get_lr()。本站实测自定义 WarmupCosineScheduler 在第 5 步达到峰值 0.01 并退火至 1e-5,同时验证与优化器联合保存 state_dict 后续训 lr 完全一致。下图展示实测 7 种调度器的学习率曲线。

生产模板常将 Warmup + CosineAnnealing、梯度裁剪与验证集最优检查点结合。下表汇总 CyclicLR 三种模式、按任务选型建议与常见排错要点。
CyclicLR 三种振幅模式对比
| mode | 振幅变化 | 特点 |
|---|---|---|
| triangular | 每周期振幅恒定 | 稳定周期探索 |
| triangular2 | 每周期振幅减半 | 前期探索、后期逐步收敛 |
| exp_range | 按 gamma^iterations 指数衰减 | 振幅连续平滑收缩 |
按任务场景的调度器选型参考
| 场景 | 推荐调度器 | 理由 |
|---|---|---|
| 快速实验 / 原型验证 | ReduceLROnPlateau | 按验证指标自适应衰减,省心 |
| 图像分类(固定 epoch) | CosineAnnealingLR | 曲线平滑、收敛质量稳健 |
| Transformer / BERT | SequentialLR (LinearLR + Cosine) | 初期预热稳定注意力梯度 |
| 资源有限,快速训练 | OneCycleLR | 超收敛策略,按 batch 步进 |
| 大模型精调(fine-tune) | LinearLR + ConstantLR | 温和预热后低学习率稳定微调 |
| 不确定 epoch 数 | ReduceLROnPlateau | 不依赖预先设定 T_max |
| 目标检测(YOLO/Faster-RCNN) | MultiStepLR / OneCycleLR | 贴合检测阶段式收敛或快训 |
| 希望跳出局部最优 | CosineAnnealingWarmRestarts | 周期重启探索多收敛盆地 |
学习率调度常见问题排查
| 问题 | 解决方法 |
|---|---|
| 调度器没有生效 | 确认 scheduler.step() 在 optimizer.step() 之后被调用 |
| CyclicLR / OneCycleLR 没变化 | 这两个调度器需在每个 batch 迭代内调用而非每 epoch |
| ReduceLROnPlateau 不触发 | 核对 mode(loss 选 'min'、acc 选 'max')及 patience,勿传已移除的 verbose |
| 恢复训练后 LR 不对 | 同时保存并恢复 optimizer.state_dict() 与 scheduler.state_dict() |
| 多参数组 LR 设置 | 给 LambdaLR 传入与 param_groups 等长的 lambda 列表 |
运行 7 种学习率调度器轨迹、PyTorch 2.10 变更与联合检查点恢复实验
"""Independent PyTorch 2.10 CPU observations for all built-in and custom LR schedulers."""
import argparse
import hashlib
import json
import math
import platform
import tempfile
from pathlib import Path
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim.lr_scheduler import (
ConstantLR,
CosineAnnealingLR,
CosineAnnealingWarmRestarts,
CyclicLR,
ExponentialLR,
LambdaLR,
LinearLR,
LRScheduler,
MultiStepLR,
OneCycleLR,
ReduceLROnPlateau,
SequentialLR,
StepLR,
)
class WarmupCosineScheduler(LRScheduler):
def __init__(self, optimizer, warmup_epochs: int, total_epochs: int, min_lr: float = 1e-6, last_epoch: int = -1):
self.warmup_epochs = warmup_epochs
self.total_epochs = total_epochs
self.min_lr = min_lr
super().__init__(optimizer, last_epoch)
def get_lr(self):
epoch = self.last_epoch
if epoch < self.warmup_epochs:
factor = (epoch + 1) / self.warmup_epochs
return [base_lr * factor for base_lr in self.base_lrs]
progress = min(1.0, (epoch - self.warmup_epochs) / max(1, self.total_epochs - self.warmup_epochs))
cosine = 0.5 * (1.0 + math.cos(math.pi * progress))
return [self.min_lr + (base_lr - self.min_lr) * cosine for base_lr in self.base_lrs]
def simulate(factory, steps: int, init_lr: float = 0.1, momentum: float = 0.0):
p = nn.Parameter(torch.zeros(1))
opt = optim.SGD([p], lr=init_lr, momentum=momentum)
sch = factory(opt)
lrs = []
for _ in range(steps):
opt.step()
sch.step()
lrs.append(round(opt.param_groups[0]["lr"], 6))
return lrs
def sha(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def run_cases(fig_dir: Path | None):
torch.manual_seed(2026)
cases = []
figures = {}
# 1. Fixed decay schedulers: StepLR, MultiStepLR, ExponentialLR
step_lrs = simulate(lambda o: StepLR(o, step_size=10, gamma=0.1), 30)
multi_lrs = simulate(lambda o: MultiStepLR(o, milestones=[10, 20, 25], gamma=0.1), 30)
exp_lrs = simulate(lambda o: ExponentialLR(o, gamma=0.95), 30)
c1_ok = step_lrs[9] == 0.01 and step_lrs[19] == 0.001 and multi_lrs[24] == 0.0001 and exp_lrs[0] == 0.095 and exp_lrs[-1] < 0.025
cases.append(dict(
name="fixed_decay_schedulers",
inputs=dict(init_lr=0.1, steps=30),
prerequisites="StepLR(step=10,g=0.1)、MultiStepLR([10,20,25]) 与 ExponentialLR(g=0.95)",
action="验证阶梯、多里程碑与指数衰减在对应轮次后的精确学习率数值。",
expected=dict(step_e10=0.01, step_e20=0.001, multi_e25=0.0001, exp_e1=0.095),
actual=dict(step_e10=step_lrs[9], step_e20=step_lrs[19], multi_e25=multi_lrs[24], exp_e1=exp_lrs[0]),
passed=c1_ok,
))
# 2. Adaptive & cosine schedulers: ReduceLROnPlateau (min/max + verbose removed), CosineAnnealingLR, WarmRestarts
p1 = nn.Parameter(torch.zeros(1))
o1 = optim.SGD([p1], lr=0.01)
plat_min = ReduceLROnPlateau(o1, mode="min", factor=0.5, patience=2, min_lr=1e-4)
for m in [1.0, 0.9, 0.9, 0.9, 0.9]:
plat_min.step(m)
min_lr_after = round(o1.param_groups[0]["lr"], 6)
p2 = nn.Parameter(torch.zeros(1))
o2 = optim.SGD([p2], lr=0.01)
plat_max = ReduceLROnPlateau(o2, mode="max", factor=0.5, patience=2)
for acc in [0.5, 0.7, 0.7, 0.7, 0.7]:
plat_max.step(acc)
max_lr_after = round(o2.param_groups[0]["lr"], 6)
verbose_removed = False
try:
ReduceLROnPlateau(o1, verbose=True)
except TypeError:
verbose_removed = True
cos_lrs = simulate(lambda o: CosineAnnealingLR(o, T_max=30, eta_min=1e-4), 30)
warm_lrs = simulate(lambda o: CosineAnnealingWarmRestarts(o, T_0=10, T_mult=2, eta_min=1e-4), 30)
# WarmRestarts resets back to 0.1 at step index 9 (after 10th step) and step index 29 (10+20)
c2_ok = min_lr_after == 0.005 and max_lr_after == 0.005 and verbose_removed and abs(cos_lrs[-1] - 0.0001) < 1e-6 and warm_lrs[9] == 0.1 and warm_lrs[29] == 0.1
cases.append(dict(
name="adaptive_and_cosine_schedulers",
inputs=dict(plateau_patience=2, T_max=30, T_0=10, T_mult=2),
prerequisites="PyTorch 2.10 ReduceLROnPlateau(min/max)、CosineAnnealingLR 与 CosineAnnealingWarmRestarts",
action="核对停滞后减半、verbose 移除、余弦退火抵达 eta_min 及周期倍增重启回到初始值。",
expected=dict(plat_min_halved=0.005, plat_max_halved=0.005, verbose_removed=True, cos_min=0.0001, warm_restarted=True),
actual=dict(plat_min_halved=min_lr_after, plat_max_halved=max_lr_after, verbose_removed=verbose_removed, cos_min=cos_lrs[-1], warm_restarted=(warm_lrs[9] == 0.1 and warm_lrs[29] == 0.1)),
passed=c2_ok,
))
# 3. Warmup & SequentialLR: LinearLR, ConstantLR, SequentialLR([warmup, cosine], milestones=[5])
lin_lrs = simulate(lambda o: LinearLR(o, start_factor=0.1, end_factor=1.0, total_iters=5), 6, init_lr=0.01)
const_lrs = simulate(lambda o: ConstantLR(o, factor=0.5, total_iters=3), 5, init_lr=0.01)
seq_lrs = simulate(
lambda o: SequentialLR(
o,
schedulers=[
LinearLR(o, start_factor=0.1, end_factor=1.0, total_iters=5),
CosineAnnealingLR(o, T_max=25, eta_min=1e-5),
],
milestones=[5],
),
30,
init_lr=0.01,
)
c3_ok = lin_lrs[4] == 0.01 and const_lrs[0] == 0.005 and const_lrs[2] == 0.01 and seq_lrs[4] == 0.01 and seq_lrs[-1] < 0.0005
cases.append(dict(
name="warmup_linear_constant_sequential",
inputs=dict(init_lr=0.01, warmup_epochs=5, total_epochs=30),
prerequisites="SequentialLR 串联 LinearLR 预热与 CosineAnnealingLR 退火",
action="验证线性预热升至目标学习率、ConstantLR 阶段结束后恢复、以及串联调度器平滑先升后降。",
expected=dict(linear_reaches_peak=0.01, const_restores=0.01, seq_peak_e5=0.01, seq_decays_tail=True),
actual=dict(linear_reaches_peak=lin_lrs[4], const_restores=const_lrs[2], seq_peak_e5=seq_lrs[4], seq_decays_tail=seq_lrs[-1] < 0.0005),
measurements=dict(seq_e1=seq_lrs[0], seq_e5=seq_lrs[4], seq_e30=seq_lrs[-1]),
passed=c3_ok,
))
# 4. Per-batch cyclic schedulers: CyclicLR (3 modes) & OneCycleLR
cyc_tri = simulate(lambda o: CyclicLR(o, base_lr=0.001, max_lr=0.01, step_size_up=5, mode="triangular"), 20, init_lr=0.001, momentum=0.9)
cyc_tri2 = simulate(lambda o: CyclicLR(o, base_lr=0.001, max_lr=0.01, step_size_up=5, mode="triangular2"), 20, init_lr=0.001, momentum=0.9)
cyc_exp = simulate(lambda o: CyclicLR(o, base_lr=0.001, max_lr=0.01, step_size_up=5, mode="exp_range", gamma=0.95), 20, init_lr=0.001, momentum=0.9)
one_lrs = simulate(lambda o: OneCycleLR(o, max_lr=0.1, steps_per_epoch=10, epochs=3, pct_start=0.3, div_factor=25.0, final_div_factor=1e4), 29, init_lr=0.01, momentum=0.9)
# Note: OneCycleLR total_steps=30 covers initial step 0 plus 29 step() calls; final_div_factor divides initial_lr (0.004)
c4_ok = cyc_tri[4] == 0.01 and cyc_tri2[14] < cyc_tri2[4] and cyc_exp[14] < cyc_exp[4] and max(one_lrs) > 0.095 and one_lrs[-1] < 1e-5
cases.append(dict(
name="cyclic_and_onecycle_per_batch",
inputs=dict(base_lr=0.001, max_lr=0.01, onecycle_max_lr=0.1, total_steps=30),
prerequisites="按 batch 调用 CyclicLR 三种模式与 OneCycleLR",
action="验证 triangular 等幅、triangular2 与 exp_range 振幅衰减,以及 OneCycleLR 单周期先升后降。",
expected=dict(tri_peak=0.01, tri2_damped=True, exp_damped=True, onecycle_peak_and_decay=True),
actual=dict(tri_peak=cyc_tri[4], tri2_damped=cyc_tri2[14] < cyc_tri2[4], exp_damped=cyc_exp[14] < cyc_exp[4], onecycle_peak_and_decay=(max(one_lrs) > 0.095 and one_lrs[-1] < 1e-5)),
measurements=dict(onecycle_peak=max(one_lrs), onecycle_final=one_lrs[-1]),
passed=c4_ok,
))
# 5. Custom LambdaLR (multi-param-group) + WarmupCosineScheduler(LRScheduler) + state_dict resume
backbone_p = nn.Parameter(torch.zeros(2))
head_p = nn.Parameter(torch.zeros(2))
opt_g = optim.Adam([{"params": [backbone_p], "lr": 1e-4}, {"params": [head_p], "lr": 1e-3}])
lam = LambdaLR(opt_g, lr_lambda=[lambda e: 0.95 ** e, lambda e: 0.85 ** e])
for _ in range(5):
opt_g.step()
lam.step()
g_lrs = [round(v, 7) for v in lam.get_last_lr()]
custom_lrs = simulate(lambda o: WarmupCosineScheduler(o, warmup_epochs=5, total_epochs=30, min_lr=1e-5), 30, init_lr=0.01)
# Save/resume state_dict equivalence for StepLR
p_a, p_b = nn.Parameter(torch.zeros(1)), nn.Parameter(torch.zeros(1))
o_a, o_b = optim.SGD([p_a], lr=0.01), optim.SGD([p_b], lr=0.01)
s_a = StepLR(o_a, step_size=3, gamma=0.5)
s_b = StepLR(o_b, step_size=3, gamma=0.5)
for _ in range(4):
o_a.step()
s_a.step()
with tempfile.TemporaryDirectory() as tmp:
sp = Path(tmp) / "sch.pth"
torch.save({"optimizer": o_a.state_dict(), "scheduler": s_a.state_dict()}, sp)
ckpt = torch.load(sp, weights_only=True)
o_b.load_state_dict(ckpt["optimizer"])
s_b.load_state_dict(ckpt["scheduler"])
o_a.step(); s_a.step()
o_b.step(); s_b.step()
resume_match = s_a.get_last_lr() == s_b.get_last_lr()
c5_ok = g_lrs[0] < 1e-4 and g_lrs[1] < 1e-3 and max(custom_lrs[:6]) == 0.01 and custom_lrs[-1] < 5e-4 and resume_match
cases.append(dict(
name="custom_lambda_subclass_and_resume",
inputs=dict(backbone_lr=1e-4, head_lr=1e-3, custom_warmup=5),
prerequisites="多参数组 LambdaLR、继承 LRScheduler 及 scheduler.state_dict() 恢复",
action="验证分组独立衰减、自定义 WarmupCosineScheduler 曲线与调度器状态恢复一致性。",
expected=dict(multi_group_decayed=True, custom_peaked_and_decayed=True, state_dict_resume_exact=True),
actual=dict(multi_group_decayed=(g_lrs[0] < 1e-4 and g_lrs[1] < 1e-3), custom_peaked_and_decayed=(max(custom_lrs[:6]) == 0.01 and custom_lrs[-1] < 5e-4), state_dict_resume_exact=resume_match),
measurements=dict(group_lrs_e5=g_lrs, custom_peak=max(custom_lrs[:6]), custom_final=custom_lrs[-1]),
passed=c5_ok,
))
# 6. Plot observed LR trajectories
if fig_dir is not None:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig_dir.mkdir(parents=True, exist_ok=True)
fig, axes = plt.subplots(1, 2, figsize=(9.4, 3.6), dpi=140)
xs = list(range(1, 31))
axes[0].plot(xs, step_lrs, label="StepLR (step=10, g=0.1)", color="#174d79")
axes[0].plot(xs, cos_lrs, label="CosineAnnealingLR", color="#ae511d")
axes[0].plot(xs, exp_lrs, label="ExponentialLR (g=0.95)", color="#2a7f62")
axes[0].plot(xs, warm_lrs, label="WarmRestarts (T0=10, mult=2)", color="#7d4ea8", linestyle="--")
axes[0].set_title("Epoch-Based LR Schedulers (init=0.1)", fontsize=10)
axes[0].set_xlabel("Epoch")
axes[0].set_ylabel("LR")
axes[0].grid(True, alpha=0.3)
axes[0].legend(fontsize=7.5)
axes[1].plot(xs, seq_lrs, label="SequentialLR (Warmup+Cosine)", color="#174d79", linewidth=2)
axes[1].plot(list(range(1, len(one_lrs) + 1)), [v * 0.1 for v in one_lrs], label="OneCycleLR (scaled x0.1)", color="#ae511d", linewidth=2)
axes[1].plot(list(range(1, 21)), cyc_tri2, label="CyclicLR (triangular2)", color="#2a7f62", linestyle="--")
axes[1].set_title("Warmup / OneCycle / Cyclic Trajectories", fontsize=10)
axes[1].set_xlabel("Step / Epoch")
axes[1].set_ylabel("LR")
axes[1].grid(True, alpha=0.3)
axes[1].legend(fontsize=7.5)
fig.tight_layout()
out_png = fig_dir / "lr-schedulers-compare.png"
fig.savefig(out_png)
plt.close(fig)
figures["lr-schedulers-compare.png"] = sha(out_png)
mpl_ver = matplotlib.__version__
else:
mpl_ver = None
cases.append(dict(
name="observed_lr_curves_plot",
inputs=dict(steps=30),
prerequisites="固定初始学习率下的 7 种调度器实测轨迹",
action="输出阶梯/余弦/重启与预热/单周期/循环调度器对比图。",
expected=dict(steps_recorded=30),
actual=dict(steps_recorded=len(seq_lrs)),
measurements=dict(figure_generated="lr-schedulers-compare.png" in figures),
passed=len(seq_lrs) == 30,
))
payload = dict(version=platform.python_version(), torch=torch.__version__, system=platform.system(), cases=cases)
if mpl_ver:
payload["matplotlib"] = mpl_ver
payload["figures"] = figures
print(json.dumps(payload, ensure_ascii=False))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--figures", type=Path, default=None)
args = parser.parse_args()
run_cases(args.figures)
- 核对 Step/MultiStep/Exponential/Cosine/WarmRestarts、ReduceLROnPlateau 移除 verbose、SequentialLR 预热退火、Cyclic/OneCycle 按批轨迹、自定义子类及联合 state_dict 恢复并输出对比图。
所需环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。
当前源码 SHA256:2c7de0eb2f97179d722ad84a6142c9393cf3f6d87544e15908c9d0ae78b696ce
本地运行
解压后按 README 选择对应构建并运行脚本。
所需环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。
ZIP SHA256:c1c3131bca1fa11843ab952fa0b6676a0c42e6d485b823a6fac9e3d5dcfb0526
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么恢复 StepLR 断点续训时,不能只加载 scheduler.state_dict() 而忽略 optimizer.state_dict()?
展开参考解答
StepLR 在步进时直接基于 optimizer.param_groups 中的当前 lr 乘以 gamma;若仅恢复调度器计数器而不恢复优化器状态,学习率会留在新建优化器的初始值而与原训练轨迹错位。