Learning-Rate Schedule: Linear Warm-up With Cosine Annealing
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `compute_lr(step, total_steps, warmup_steps, lr_max, lr_min)`, returning the learning rate (a `float`) at a given step. The schedule warms up linearly from `0` to `lr_max`, then decays to `lr_min` along a half cosine.
- If `step < 0`, raise `ValueError`.
- For `0 <= step < warmup_steps`: `lr = lr_max * step / warmup_steps`.
- For `warmup_steps <= step < total_steps`: `progress = (step - warmup_steps) / (total_steps - warmup_steps)` and `lr = lr_min + 0.5 * (lr_max - lr_min) * (1 + cos(pi * progress))`.
- For `step >= total_steps`, return `lr_min`.
Example:
```python
compute_lr(5, 110, 10, 1.0, 0.1) # 0.5 (warm-up)
compute_lr(10, 110, 10, 1.0, 0.1) # 1.0 (peak)
compute_lr(60, 110, 10, 1.0, 0.1) # 0.55 (cosine midpoint)
compute_lr(500, 110, 10, 1.0, 0.1) # 0.1 (past the end)
compute_lr(0, 100, 0, 0.5, 0.0) # 0.5 (no warm-up)
```
```hint Denominators
Check which denominators can be zero under the constraints, and make sure the branch that uses each one never runs in that case.
```
### Constraints & Assumptions
- `0 <= warmup_steps < total_steps`, both integers.
- `0 <= lr_min <= lr_max`, all finite.
- Results are compared with `rtol=1e-7`.
### What a Strong Answer Covers
- All four cases, with the inclusive and exclusive boundaries exactly as specified
- No division by zero when `warmup_steps` is 0
- A decay that starts exactly at `lr_max` at step `warmup_steps` and returns `lr_min` from step `total_steps` on
- A check of the given examples, including the floating-point value at the cosine midpoint
### Follow-up Questions
- Why warm up at all, and what can go wrong if training starts at `lr_max`?
- How would you extend this to cosine annealing with warm restarts, where the rate resets to `lr_max` at the start of each cycle?
- How would you compute the whole schedule as a NumPy array without a Python loop, and what does that change about the zero warm-up case?
Overview: Implement a learning-rate schedule that warms up linearly from zero to a peak, then decays to a floor along a half cosine. It tests piecewise boundary handling, avoiding division by zero when there is no warm-up, and checking a schedule against worked values.