Cosine Annealing With Warm Restarts
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement SGDR-style cosine annealing. Cycle `i` has length `t0 * t_mult**i`, and within a cycle the rate is `min_lr + 0.5 * (base_lr - min_lr) * (1 + cos(pi * t_cur / length))`, restarting at `base_lr` at every cycle boundary.
- `cycle_position(step, t0, t_mult=1)` returns `(cycle_index, t_cur, cycle_length)`, with `0 ≤ t_cur < cycle_length`.
- `cosine_warm_restarts_lr(step, base_lr, min_lr, t0, t_mult=1)` returns a Python `float`.
- `lr_schedule(num_steps, base_lr, min_lr, t0, t_mult=1)` returns a `float64` `np.ndarray` of shape `(num_steps,)` for steps `0..num_steps-1` (empty when `num_steps == 0`).
For example:
```python
cycle_position(5, t0=2, t_mult=2) # (1, 3, 4)
cycle_position(14, t0=2, t_mult=2) # (3, 0, 16) restarts at 0, 2, 6, 14, 30
cosine_warm_restarts_lr(2, base_lr=1.0, min_lr=0.2, t0=3) # 0.4
[cosine_warm_restarts_lr(s, 0.1, 0.0, 4) for s in range(4)]
# [0.1, 0.0854, 0.05, 0.0146]
```
```hint Where the cycles start
With `t_mult > 1` the restart points are running sums of a geometric series. Walk the cycles from step 0 and be careful about what happens when a step lands exactly on a boundary.
```
```hint Integer checks in Python
`isinstance(True, int)` is `True`, so a plain integer check lets bools through.
```
### Constraints & Assumptions
- `t0` and `t_mult` must be integers ≥ 1 (bools and floats like `1.5` rejected), else raise `ValueError`.
- `step < 0` or `num_steps < 0` → `ValueError`.
- You may assume `0 ≤ min_lr ≤ base_lr`.
### What a Strong Answer Covers
- A correct mapping from a global step to its cycle index, position and cycle length, for both `t_mult == 1` and `t_mult > 1`, including steps that land exactly on a restart.
- The cosine formula applied to the position inside the cycle, returned as a Python float that equals `base_lr` at every restart and stays at or above `min_lr`.
- Input validation that rejects bools, floats and values below 1 for `t0` and `t_mult`, and negative step counts.
- A `float64` schedule of the right shape, including the empty case, and the cost per step.
### Follow-up Questions
- How would you compute `cycle_position` in constant time when `t_mult > 1`, and what can go wrong numerically?
- How would you build `lr_schedule` in O(n) total time?
- How would you add a linear warmup at the start of training, or shrink `base_lr` after every restart?
- Why can warm restarts help training compared with a single cosine decay, and how do they affect when you take checkpoints?
Overview: Implement a cosine annealing learning-rate schedule with warm restarts, where cycle lengths grow by an integer factor and the rate resets at every boundary. Tests mapping a global step to its cycle, boundary handling, strict input validation in Python, and building the full schedule as a NumPy array.