Implement a ReduceLROnPlateau learning rate scheduler with patience and cooldown
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `ReduceLROnPlateau`, which wraps an object exposing a mutable `optimizer.lr`. Each call to `step(metric)` updates the scheduler state, possibly scales `lr` by `factor`, and returns the current `lr` as a `float`.
```python
class ReduceLROnPlateau:
def __init__(self, optimizer, mode="min", factor=0.1, patience=10,
threshold=1e-4, threshold_mode="rel", cooldown=0,
min_lr=0.0, eps=1e-8): ...
def step(self, metric): ... # returns the current lr as a float
```
Requirements:
- `best` starts at `inf` (`min`) or `-inf` (`max`). Improvement for `min`: `a < best*(1-threshold)` (rel) or `a < best-threshold` (abs). `max` mirrors this with `1+threshold` / `+threshold`. NaN never improves.
- Each step: increment `last_epoch`. On improvement set `best` and reset `num_bad_epochs`, otherwise increment it.
- Then, if `cooldown_counter > 0`: decrement it and set `num_bad_epochs = 0`.
- Then, if `num_bad_epochs > patience`: set `lr = max(lr*factor, min_lr)` (only if the drop exceeds `eps`), set `cooldown_counter = cooldown`, reset `num_bad_epochs`.
- The constructor raises `ValueError` if `factor` is not in (0, 1), `mode` or `threshold_mode` is invalid, or `patience`/`cooldown` is negative.
Example:
```python
# opt is any object with a writable lr attribute
opt.lr = 1.0
s = ReduceLROnPlateau(opt, factor=0.5, patience=2)
[s.step(m) for m in [1.0, 1.0, 1.0, 1.0]] # [1.0, 1.0, 1.0, 0.5]
opt.lr = 1.0
s = ReduceLROnPlateau(opt, factor=0.5, patience=0, cooldown=2)
[s.step(3.0) for _ in range(6)] # [1.0, 0.5, 0.5, 0.5, 0.25, 0.25]
```
```hint Order of the checks
Trace the second example on paper, one call at a time. The order of the improvement test, the cooldown branch and the patience check decides when the second drop happens.
```
### What a Strong Answer Covers
- The improvement test for both modes and both threshold modes, with the right starting value of `best`
- The three updates in each `step` done in the specified order, so that cooldown suppresses bad-epoch counting
- The floor at `min_lr` and the `eps` check that skips negligible changes
- NaN metrics and constructor validation handled as specified
- A trace of the examples that reproduces the expected learning rates
### Follow-up Questions
- Why does the scheduler zero `num_bad_epochs` during cooldown, and what would happen without that reset?
- In `rel` mode with `mode="min"`, what goes wrong when the monitored metric can be negative?
- The validation metric is noisy from epoch to epoch. How does that noise interact with `patience` and `threshold`, and what would you change?
- How would you extend the scheduler to an optimizer with several parameter groups, each with its own learning rate?
Overview: Implement a ReduceLROnPlateau learning rate scheduler that tracks the best validation metric, counts epochs without improvement, cuts the learning rate once patience runs out, and then waits out a cooldown. It tests careful state handling, relative and absolute thresholds, and NaN behavior.