Guarded Momentum SGD With LR Backoff
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `GuardedSGD.step(params, grads)`, a momentum SGD step that updates `params` in place and returns `True` if applied or `False` if skipped. Any non-finite gradient (`NaN`, `+Inf`, `-Inf`) triggers a skip and a learning-rate backoff.
The step must meet these requirements:
- On the first call, set `velocity` to `float64` zeros shaped like `params` (even if that call is skipped).
- On a finite step, compute `v = momentum*v + grads`, then `params -= lr*v`. Increment `step_count` and `good_steps`.
- On a skip, leave `params`, `velocity` and `step_count` unchanged, zero `grads` in place, set `lr = max(lr*backoff_factor, min_lr)`, increment `num_skipped`, and reset `good_steps` to 0.
- If `growth_interval > 0` and `good_steps == growth_interval` after a finite step, set `lr = min(lr*growth_factor, max_lr)` and reset `good_steps` to 0.
- Return a Python `bool` (tests use `is True` / `is False`).
The constructor is provided, and `max_lr` defaults to the initial `lr`. Only implement `step`.
```python
import numpy as np
class GuardedSGD:
def __init__(self, lr, momentum=0.0, backoff_factor=0.5, min_lr=0.0,
growth_factor=2.0, growth_interval=0, max_lr=None):
self.lr = float(lr)
self.momentum = float(momentum)
self.backoff_factor = float(backoff_factor)
self.min_lr = float(min_lr)
self.growth_factor = float(growth_factor)
self.growth_interval = int(growth_interval)
self.max_lr = float(lr) if max_lr is None else float(max_lr)
self.velocity = None
self.step_count = 0
self.num_skipped = 0
self.good_steps = 0
def step(self, params, grads):
...
```
Example:
```python
opt = GuardedSGD(lr=0.1, momentum=0.9)
p = np.array([1.0, -2.0])
opt.step(p, np.array([0.5, 1.0])) # True, p -> [0.95, -2.1]
g = np.array([np.nan, 3.0])
opt.step(p, g) # False, p unchanged, g -> [0, 0], lr -> 0.05
opt.step(p, np.array([0.2, -0.4])) # True, v -> [0.65, 0.5], p -= 0.05 * v
```
```hint Order of operations
Decide whether the step will be applied before you touch any optimizer state. Think about what a single NaN would do to every later step if it ever reached the velocity buffer.
```
```hint In place means the caller sees it
The caller keeps its own references to `params` and `grads`. Check which of your statements write into those arrays and which only rebind a local name.
```
### What a Strong Answer Covers
- Checks the whole gradient for finiteness before changing any state, and still initializes `velocity` on a first call that gets skipped.
- Updates `params` and zeros `grads` in place, so both changes are visible to the caller.
- Applies the backoff with the `min_lr` floor and the growth with the `max_lr` cap, and resets the good-step streak on skips and after growth.
- Keeps the counters consistent: `step_count` and `good_steps` move only on applied steps, `num_skipped` only on skips.
- Returns a real Python `bool`, and states the time and memory cost per step.
### Follow-up Questions
- How does this relate to dynamic loss scaling in mixed-precision training?
- How would you make the skip decision consistent across data-parallel workers?
- Should a NaN step also reset or decay the momentum buffer?
- If every gradient comes back non-finite, what happens to the learning rate, and how would you detect that the run is stuck?
Overview: Implement the step method of a momentum SGD optimizer that skips any update with NaN or infinite gradients, backs off the learning rate on a skip, and grows it again after a streak of good steps. It tests optimizer state handling, in-place NumPy updates, and the ideas behind dynamic loss scaling.