Build a warmup plus cosine schedule with warm restarts

Why it matters SGDR-style restarts are a built-in PyTorch scheduler and common in vision and Kaggle training.

Cosine schedules with restarts let a run escape a bad region and give several good checkpoints, one per cycle.

Write sgdr_schedule(n_steps, lr_max, lr_min, warmup, T0, Tmult). For step s < warmup, lr = lr_max * (s + 1) / warmup. After warmup, let u = s - warmup. Cycles have lengths T0, T0 * Tmult, T0 * Tmult^2, ... (Tmult is a positive integer). Find the cycle containing u and the position t inside it; then lr = lr_min + 0.5 * (lr_max - lr_min) * (1 + cos(pi * t / T_i)), where T_i is that cycle's length. Return a list of n_steps floats.

Signaturedef sgdr_schedule(n_steps, lr_max, lr_min, warmup, T0, Tmult)

Example

sgdr_schedule(6, 1.0, 0.0, 0, 2, 2) is [1.0, 0.5, 1.0, 0.8536, 0.5, 0.1464] (rounded).

Understand the idea

A cosine schedule lowers the learning rate smoothly, like easing off the accelerator as you approach a parking spot. Warm restarts suddenly raise it back to the top and start a new, usually longer, cosine. The jump shakes the model out of a narrow valley, and the end of each cycle is a good snapshot.

Tiny example: T0 = 2, Tmult = 2, lr_max = 1, lr_min = 0. Steps 0 and 1 are cycle 1: cos(0) gives 1.0, cos(pi/2) gives 0.5. Step 2 restarts cycle 2 of length 4: 1.0, then 0.854, 0.5, 0.146.

Rule: lr = lr_min + 0.5 (lr_max - lr_min)(1 + cos(pi * t / T_i)), with T_i = T0 * Tmult^i, after a linear warmup.

PyTorch ships this as CosineAnnealingWarmRestarts, and snapshot ensembles save a model at the end of each cycle.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplesgdr_schedule(6, 1.0, 0.0, 0, 2, 2)
  • Sample 2: warmupsgdr_schedule(7, 0.1, 0.01, 3, 4, 1)
  • Test 3: tmult 3sgdr_schedule(14, 1.0, 0.1, 1, 1, 3)