Skip to content

← Optimizers & Training step 6 of 8

Medium End-to-End

Learning Rate Scheduler

A learning-rate schedule supplies a step size for each training update. Cosine annealing lowers that rate along a smooth cosine curve. Here, build the schedule as an array; do not create an optimizer or train a model.

Your task

Implement cosine_schedule(lr_max, lr_min, T):

  • lr_max and lr_min are finite floats with 0 <= lr_min <= lr_max.
  • T is a positive integer giving the number of values to return.

For every integer step t from 0 through T - 1, compute:

lr[t] = lr_min + 0.5 * (lr_max - lr_min) * (1 + cos(pi * t / T))

Use radians for cosine and ordinary division for t / T. Return a one-dimensional float32 tensor of shape (T,), in increasing step order. There is no warmup or restart in this schedule.

The endpoint matters

At t = 0, the formula gives lr_max. It reaches lr_min at t = T, but that step is not included in the returned array. Use T as the denominator, not T - 1, and do not append an extra minimum value.

For T = 1, return just [lr_max]. If lr_min = lr_max, every returned value is that same rate. With distinct bounds, the mathematical schedule decreases toward the minimum; floating-point rounding can make nearby values equal.

Example

For lr_max = 0.1, lr_min = 0 and T = 3, the cosine arguments are 0, pi/3 and 2*pi/3. Their cosines are 1, 0.5 and -0.5, so return approximately [0.1, 0.075, 0.025]. There are exactly three values, and the last is above zero.