Ramp Up, Ease Down

OptimizersMedium+20 XP+20

Ramp Up, Ease Down

Modern training runs rarely keep one learning rate from start to finish. They warm up, starting below the target rate and climbing to it over the first few updates so that the wild gradients of freshly initialised weights cannot wreck the run. Then they decay along a smooth cosine curve down to a small floor, so the end of training takes the fine, settling steps it needs.

Number the updates s=1,2,…,Ts = 1, 2, \dots, Ts=1,2,…,T, where TTT is total_steps, and let WWW be warmup_steps.

Warmup, for s≤Ws \le Ws≤W. The rate climbs in equal increments and reaches the peak exactly on update WWW:

lrs=peak×sW\text{lr}_s = \text{peak} \times \frac{s}{W}lrs​=peak×Ws​

Cosine decay, for s>Ws > Ws>W. First measure how far through the decay phase this update is:

progress=s−WT−W\text{progress} = \frac{s - W}{T - W}progress=T−Ws−W​

then ease from the peak down to the floor:

lrs=min+(peak−min)×1+cos⁡(π⋅progress)2\text{lr}_s = \text{min} + (\text{peak} - \text{min}) \times \frac{1 + \cos(\pi \cdot \text{progress})}{2}lrs​=min+(peak−min)×21+cos(π⋅progress)​

The final update, s=Ts = Ts=T, has progress 111 and lands exactly on the floor. The cosine takes its argument in radians.

Task: write warmup_cosine(peak_lr, min_lr, warmup_steps, total_steps), returning the learning rate of every update in order: a list of total_steps floats, each rounded to 4 decimal places.

You can rely on total_steps ≥1\ge 1≥1, 0≤0 \le0≤ warmup_steps ≤\le≤ total_steps and 0≤0 \le0≤ min_lr ≤\le≤ peak_lr. warmup_steps can be 000, meaning no warmup at all, and it can equal total_steps, meaning the run ends before any decay begins.

Worked through, warmup_cosine(0.4, 0.0, 2, 6):

update sssphaseprogresslearning rate
1warmup0.4×12=0.20.4 \times \tfrac{1}{2} = 0.20.4×21​=0.2
2warmup0.4×22=0.40.4 \times \tfrac{2}{2} = 0.40.4×22​=0.4
3decay14\tfrac{1}{4}41​0.4×1+0.70712=0.34140.4 \times \tfrac{1 + 0.7071}{2} = 0.34140.4×21+0.7071​=0.3414
4decay24\tfrac{2}{4}42​0.4×1+02=0.20.4 \times \tfrac{1 + 0}{2} = 0.20.4×21+0​=0.2
5decay34\tfrac{3}{4}43​0.4×1−0.70712=0.05860.4 \times \tfrac{1 - 0.7071}{2} = 0.05860.4×21−0.7071​=0.0586
6decay44\tfrac{4}{4}44​0.4×1−12=0.00.4 \times \tfrac{1 - 1}{2} = 0.00.4×21−1​=0.0

The answer is [0.2, 0.4, 0.3414, 0.2, 0.0586, 0.0].

A schedule that is slightly wrong still trains, which is exactly why schedule bugs survive for so long. Get the conventions right: where the ramp starts, what the decay's progress is measured against, and where the floor enters the formula.

Examples

peak_lr = 0.1
min_lr = 0.01
warmup_steps = 3
total_steps = 10
returns [0.0333, 0.0667, 0.1, 0.0955, 0.0831, 0.065, 0.045, 0.0269, 0.0145, 0.01]
peak_lr = 0.5
min_lr = 0.05
warmup_steps = 0
total_steps = 5
returns [0.457, 0.3445, 0.2055, 0.093, 0.05]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run