Nesterov Accelerated Gradient Step
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `nesterov_step(params, velocity, grad_fn, lr, momentum)`, which evaluates the gradient once at the look-ahead point and returns `(new_params, new_velocity)`. Also implement `nesterov_optimize(grad_fn, x0, lr, momentum, n_steps)`, which starts from `x0` with zero velocity, applies `n_steps` steps and returns the final `(params, velocity)`.
One step follows this update:
```python
lookahead = params + momentum * velocity
new_velocity = momentum * velocity - lr * grad_fn(lookahead)
new_params = params + new_velocity
```
For example, on $f(x) = x^2$:
```python
grad_fn = lambda x: 2 * x
nesterov_step(np.array([1.0]), np.array([0.0]), grad_fn, 0.1, 0.9)
# -> (array([0.8]), array([-0.2]))
nesterov_optimize(grad_fn, np.array([1.0]), 0.1, 0.9, 3)
# -> (array([0.17792]), array([-0.31808]))
```
In the single step the velocity starts at zero, so the look-ahead point is the current parameter 1.0, its gradient is 2.0, and the velocity becomes -0.2.
```hint Watch the inputs
Expressions such as `params + momentum * velocity` build new arrays, while `+=` writes into an existing one. Also check what your step does when `momentum = 0`.
```
### Constraints & Assumptions
- Inputs are 1-D arrays of matching shape. Return `float64` NumPy arrays.
- Call `grad_fn` exactly once per step. Never mutate `params`, `velocity` or `x0`.
- `n_steps = 0` returns `x0` and a zero velocity.
### What a Strong Answer Covers
- Evaluating the gradient at the look-ahead point, once per step
- Applying the velocity and parameter updates in the right order with the stated sign convention
- Returning new `float64` arrays without mutating any input, including the `n_steps = 0` case
- Cost per step and how the update relates to plain gradient descent
### Follow-up Questions
- How does this differ from classical (heavy-ball) momentum?
- How would you rewrite the update so the gradient is taken at the stored parameters?
- What happens to the iterates on this quadratic if you raise `momentum` toward 1 with `lr` fixed?
Overview: Implement one Nesterov accelerated gradient step in NumPy, with the gradient taken at the look-ahead point, plus a loop that runs it for a fixed number of steps from zero velocity. Tests the momentum update order, sign conventions, and returning new arrays without mutating inputs.