AdaGrad Optimizer With Per-Coordinate Step Sizes
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement an AdaGrad optimizer in Python with NumPy. The class is constructed as `AdaGrad(lr=0.1, eps=1e-8, initial_accumulator=0.0)` and has two methods, `step(params, grads)` and `effective_lr()`.
Each call to `step` adds `grads ** 2` to the per-coordinate accumulator `G`, then returns `params - lr * grads / (sqrt(G) + eps)`. Epsilon sits outside the square root. `effective_lr()` returns `lr / (sqrt(G) + eps)` for every coordinate.
Example:
```python
opt = AdaGrad(lr=0.1)
opt.step([1.0, -2.0, 0.5], [0.5, -4.0, 0.0]) # -> ~[0.9, -1.9, 0.5]
opt.accumulator # -> [0.25, 16.0, 0.0]
# A fresh optimizer over two coordinates, run for 10 steps:
# coordinate 0 gets gradient 1.0 on every step (dense),
# coordinate 1 gets gradient 1.0 on step 1 only (sparse).
opt = AdaGrad(lr=0.1)
p = [0.0, 0.0]
for i in range(10):
p = opt.step(p, [1.0, 1.0 if i == 0 else 0.0])
opt.effective_lr() # -> ~[0.1/sqrt(10), 0.1], about [0.0316, 0.1]
```
```hint Where the state comes from
The constructor never sees a parameter array, so the accumulator's shape is only known on the first call. Before you write anything in place, check what `np.asarray` returns when it is given an array that is already float64.
```
### Constraints & Assumptions
- `params` and `grads` are array-likes (Python lists or NumPy arrays). Compute in float64.
- On the first `step`, initialise `self.accumulator` to `initial_accumulator` with the shape of `params` (float64).
- Increment `self.t` on every step.
- Return a new array. Never mutate `params` or `grads`.
- A shape mismatch between `params` and `grads` raises `ValueError`.
- Calling `effective_lr()` before any step raises `RuntimeError`.
### What a Strong Answer Covers
- The order of operations inside `step`: which accumulator value the denominator uses, and where epsilon goes.
- Lazy creation of the accumulator (shape, dtype, starting value) and the step counter.
- The two error cases, and a guarantee that the caller's arrays are never modified.
- Why the sparse coordinate in the example ends with a step size about `sqrt(10)` times larger than the dense one.
- Per-step time and the extra memory the optimizer holds.
### Follow-up Questions
- Why does AdaGrad's learning rate eventually stall, and how do RMSProp and Adam fix it?
- How would you apply AdaGrad efficiently to a huge sparse embedding table?
- What changes if `eps` is placed inside the square root?
Overview: Implement the AdaGrad optimizer in NumPy, with a per-coordinate accumulator of squared gradients, a step method and an effective learning rate method. It tests adaptive step sizes, lazy state setup, input validation and how gradient frequency changes the step size of each coordinate.