Early Stopping with Best Checkpoint Restore
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `EarlyStopping(patience=5, min_delta=0.0, mode="min")`. Each `step(value, params)` records a validation value and a dict of NumPy arrays and returns `True` once training should stop. `restore()` returns the best checkpoint.
Requirements:
- Improvement: `value < best_value - min_delta` (`"min"`) or `value > best_value + min_delta` (`"max"`). The first call always improves. `NaN` never improves.
- On improvement: update `best_value`, `best_step` (0-based call index), reset `wait` to 0 and deep-copy `params`. Otherwise `wait += 1`.
- When `wait >= patience`: set `stopped = True` and `stop_step` to that call's index. Later calls return `True` and change no state (including `num_steps`).
- `restore()` returns a fresh independent copy each call. It raises `RuntimeError` if no checkpoint exists.
- Raise `ValueError` for non-integer or `< 1` `patience`, negative `min_delta`, or a `mode` other than `"min"`/`"max"`.
Example:
```python
es = EarlyStopping(patience=3)
[es.step(v, p) for v in [1.0, 0.9, 0.95, 0.92, 0.91]]
# -> [False, False, False, False, True]
# best_step == 1, best_value == 0.9, wait == 3, stop_step == 4
```
```hint Test the sentinel
Starting `best_value` at plus or minus infinity makes most first values win. Check which first value would still fail a strict comparison against it.
```
```hint Who else holds the arrays
Training loops often update weights in place. Think about which objects the stored checkpoint and the result of `restore()` point at.
```
### Clarifying Questions to Ask
- Does an integer-valued float such as `3.0` count as a valid `patience`, and should a boolean be rejected?
- If the first value is `NaN`, should the next non-NaN value count as the first improvement?
### What a Strong Answer Covers
- A mode-aware improvement test with `min_delta` that treats `NaN` as never improving and lets the first call improve for every non-NaN value, including an infinite one.
- Copying the parameters on improvement and on every `restore()` call, with `RuntimeError` when no checkpoint exists.
- Correct `wait`, `stopped` and `stop_step` updates, with no state change (including `num_steps`) once stopped.
- Validation of `patience`, `min_delta` and `mode`, and a trace of the example.
### Follow-up Questions
- How would you support a relative `min_delta` instead of an absolute one?
- How would you avoid the memory cost of copying large models at every improvement?
- How would you combine early stopping with a learning-rate scheduler like `ReduceLROnPlateau`?
Overview: Implement an early stopping monitor with patience, min_delta and min or max mode that keeps a copy of the best parameters and restores it on request. Tests improvement logic, NaN and edge-case handling, input validation, and avoiding aliasing bugs with NumPy arrays.