Implement a stateful learning-rate scheduler with step and exponential decay
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `LRScheduler(base_lr, mode, gamma, step_size=None, min_lr=0.0)`. The epoch counter `last_epoch` starts at 0 with the learning rate equal to `base_lr`. Each `step()` increments `last_epoch` and returns the learning rate for the new epoch.
The learning rate at epoch `t` is:
- `mode="step"`: `lr_t = max(base_lr * gamma ** (t // step_size), min_lr)`
- `mode="exponential"`: `lr_t = max(base_lr * gamma ** t, min_lr)`
The class must also meet these requirements:
- `get_last_lr()` returns the current learning rate as a `float` without advancing the schedule.
- Raise `ValueError` for an unknown mode, `base_lr < 0`, `gamma <= 0`, or `min_lr < 0`.
- In `"step"` mode, raise `ValueError` when `step_size` is missing, not an integer, or less than 1.
Example:
```python
s = LRScheduler(base_lr=0.1, mode="step", gamma=0.5, step_size=3)
[s.get_last_lr()] + [s.step() for _ in range(7)]
# [0.1, 0.1, 0.1, 0.05, 0.05, 0.05, 0.025, 0.025]
s = LRScheduler(base_lr=1.0, mode="exponential", gamma=0.5, min_lr=0.2)
[s.get_last_lr()] + [s.step() for _ in range(4)]
# [1.0, 0.5, 0.25, 0.2, 0.2]
```
```hint Where the value comes from
You can update the learning rate from the previous value on every step, or compute it directly from `last_epoch`. Compare the two for rounding error and for restarting at an arbitrary epoch.
```
```hint Validation pitfalls
Decide what counts as an integer `step_size` (is `True` one? is `3.0`?), then make sure an invalid value such as `2.5` or `float("inf")` raises `ValueError` and not another exception type.
```
### What a Strong Answer Covers
- How each epoch's learning rate is obtained from `last_epoch`, and what that choice means for accumulated floating-point error.
- Where the `min_lr` floor is applied in both modes, consistent with the examples.
- Keeping `get_last_lr()` read-only and making `step()` advance the counter exactly once per call, with no off-by-one in the first returned value.
- Validation of every argument in the spec, including edge values of `step_size`, all ending in `ValueError`.
- The cost per call and where `step()` belongs in a training loop.
### Follow-up Questions
- How would you add linear warmup before the decay?
- How would you support checkpointing and resuming training?
- What changes if the scheduler is stepped once per batch instead of once per epoch?
Overview: Implement a Python learning-rate scheduler class that supports step decay and exponential decay with a minimum learning-rate floor. It tests how you compute a schedule without floating-point drift, validate constructor arguments, and keep step() and get_last_lr() consistent with the epoch counter.