蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 7 种学习率调度器轨迹、PyTorch 2.10 变更与联合检查点恢复实验

PYTHONWindows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。explore-lr-schedulers.py
explore-lr-schedulers.py261 行
"""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)
本例需在 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。

入口文件:projects/pytorch-lr-scheduler-lab/explore-lr-schedulers.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-lr-schedulers.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:PyTorch

课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a409.zip

下载课程关联工程包:PyTorch

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a428.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习