BLOGLLM Logo
Go Pro
Guest
Not signed in
所有博客课程练习面试准备系列标签书签价格
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboard游戏
Articles
练习 / Optimizers13 of 18 in topic

252. 构建带有热重启的 warmup 加 cosine 调度器

MediumOptimizers

重要性 SGDR 风格的重启是 PyTorch 内置的 scheduler,在视觉任务和 Kaggle 训练中非常常见。

带有重启的 Cosine schedules 可以让训练过程跳出糟糕的区域,并提供多个优秀的 checkpoint,每个 cycle 提供一个。

编写 sgdr_schedule(n_steps, lr_max, lr_min, warmup, T0, Tmult)。对于 step s < warmup,lr = lr_max * (s + 1) / warmup。在 warmup 之后,令 u = s - warmup。Cycle 的长度分别为 T0, T0 * Tmult, T0 * Tmult^2, ... (Tmult 是一个正整数)。找到包含 u 的 cycle 以及其内部的位置 t;然后 lr = lr_min + 0.5 * (lr_max - lr_min) * (1 + cos(pi * t / T_i)),其中 T_i 是该 cycle 的长度。返回一个包含 n_steps 个 float 的列表。

函数def sgdr_schedule(n_steps, lr_max, lr_min, warmup, T0, Tmult)
Play with it

Cosine annealing with warm restarts

Each cycle decays from 1 to 0 along a cosine and then jumps back. The multiplier makes each cycle longer than the one before.

00.510255075100125steplr (max 1, min 0)
step
45
lr (max 1, min 0)
0.308658
peak on chart
1

Drag across the chart to read any step.

示例 1

输入: sgdr_schedule(6, 1.0, 0.0, 0, 2, 2)

输出: [1.0, 0.5, 1.0, 0.8536, 0.5, 0.1464] (rounded)

示例 2

输入: n_steps = 6, lr_max = 1.0, lr_min = 0.0, warmup = 0, T0 = 2, Tmult = 2

输出: [1.0, 0.5, 1.0, 0.853553, 0.5, 0.146447]

示例 3

输入: n_steps = 7, lr_max = 0.1, lr_min = 0.01, warmup = 3, T0 = 4, Tmult = 1

输出: [0.033333, 0.066667, 0.1, 0.1, 0.08682, 0.055, 0.02318]

约束条件

  • Python 3 standard library. Code runs in your browser.
  • Your code must pass all 3 tests to be accepted.
提示 1

从 u 中不断减去 cycle 长度,直到它落在当前 cycle 内,每次减去时将长度乘以 Tmult。

提示 2

使用 while 循环来寻找 cycle。

提示 3

t 是 cycle 内部的位置,从 0 开始。

提示 4

当 t = 0 时,cosine 项的结果为 lr_max。

常见错误
  • 忘记增加 cycle 的长度。
  • warmup 从 0 开始线性增加,导致第一步的 lr 为 0。
理解思路

Cosine schedule 会平滑地降低学习率,就像开车接近停车位时松开油门一样。Warm restarts 会突然将其拉回最高点并开始一个新的、通常更长的 cosine 过程。这种跳跃能让模型从狭窄的局部极小值中震荡出来,而每个 cycle 的结束点都是一个很好的 snapshot。

Worked example

T0 = 2, Tmult = 2, lr_max = 1, lr_min = 0. Steps 0 和 1 属于 cycle 1: cos(0) 得到 1.0, cos(pi/2) 得到 0.5. Step 2 重启长度为 4 的 cycle 2: 1.0, 然后是 0.854, 0.5, 0.146.

在线性 warmup 之后,lr = lr_min + 0.5 (lr_max - lr_min)(1 + cos(pi * t / T_i)), 其中 T_i = T0 * Tmult^i。

PyTorch 将其实现为 CosineAnnealingWarmRestarts,而 snapshot ensembles 会在每个 cycle 结束时保存模型。

主题
Optimizers
相似题目
  • 实现 Adam 优化器的一个步骤Medium
  • 运行带有解耦权重衰减的 sign-based Lion 优化器Medium
  • 执行一次 Centered RMSProp 步进Medium
  • 使用 Lookahead 封装优化器Medium
所有 Optimizers 道题目
反馈
252 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import math
​
def sgdr_schedule(n_steps, lr_max, lr_min, warmup, T0, Tmult):
# your code here
pass
​

Run 会在浏览器中检查这些用例,无需登录。 Submit 会检查所有 3 个测试。

Ctrl/按 + 回车 运行
© BlogLLM, Bengaluru, India关于条款隐私退款DMCA联系我们RSS