Implement Polyak and stochastic weight averaging for SGD in NumPy

Quick Overview

Implement an exponential moving average and a uniform stochastic weight average of the SGD iterates in NumPy, returning both the final and the averaged weights. It tests the incremental mean recurrence, array handling without mutation, and why averaging helps when constant-step SGD keeps bouncing around the minimum.

Implement Polyak and stochastic weight averaging for SGD in NumPy

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement three NumPy functions: `ema_update` (exponential moving average), `swa_update` (uniform running mean), and `sgd_with_averaging`, which runs plain SGD and tracks an averaged copy of the weights. The last function returns `(final_params, averaged_params)`. The functions must behave as follows: - `ema_update(avg, params, decay)` returns a new float array `decay * avg + (1 - decay) * params`. It must not mutate its inputs. - `swa_update(avg, params, n_averaged)` returns `(avg + (params - avg) / (n + 1), n + 1)`. When `n_averaged == 0`, it returns `(copy of params, 1)` and ignores `avg`. - `sgd_with_averaging(grad_fn, x0, lr, n_steps, mode="ema", decay=0.99, swa_start=1)` runs, for each step `t = 1..n_steps`, the update `x = x - lr * grad_fn(x)`, then averages the post-step `x`. It never mutates `x0`. - With `mode="ema"`, initialize the average to `x0` and update it every step. With `mode="uniform"`, average only the iterates where `t >= swa_start`. If no iterate was averaged, return the final `x` as the average. - Any other `mode` raises `ValueError`. Example: ```python grad = lambda x: x # iterates: 0.5, 0.25, 0.125 sgd_with_averaging(grad, np.array([1.0]), 0.5, 3, mode="ema", decay=0.5) # -> ([0.125], [0.3125]) avg: 1 -> 0.75 -> 0.5 -> 0.3125 sgd_with_averaging(grad, np.array([1.0]), 0.5, 3, mode="uniform", swa_start=2) # -> ([0.125], [0.1875]) mean(0.25, 0.125) ema_update([1.0, 2.0], [3.0, -2.0], 0.9) # -> [1.2, 1.6] ``` ```hint Running mean without history Write the mean of n + 1 values in terms of the mean of the first n values and the new one. Then you never need to store the trajectory. ``` ```hint Which array gets averaged Average the iterate after the step, not the one you took the gradient at. Also check that `x0` and the arrays passed to the helpers come back unchanged. ``` ### What a Strong Answer Covers - Helpers that return new float arrays and never mutate their inputs, including the `n_averaged == 0` branch of `swa_update`. - Averaging the post-step iterate, with the EMA initialized at `x0` and the uniform mean gated on `t >= swa_start`. - The fallback when uniform mode never averages anything, and a `ValueError` for an unknown mode. - Time and memory cost: O(d) memory with no stored trajectory, O(T·d) time plus the gradient calls. - Why the averaged weights land closer to the minimum than the last iterate when the gradients are noisy. ### Follow-up Questions - Why does the uniform average converge under noisy gradients when the last iterate does not? - The EMA starts from `x0` and is biased early on. How would you correct that? - What extra step does SWA need for networks with BatchNorm?

Overview: Implement an exponential moving average and a uniform stochastic weight average of the SGD iterates in NumPy, returning both the final and the averaged weights. It tests the incremental mean recurrence, array handling without mutation, and why averaging helps when constant-step SGD keeps bouncing around the minimum.

General logo
General
Nov 25, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement three NumPy functions: ema_update (exponential moving average), swa_update (uniform running mean), and sgd_with_averaging, which runs plain SGD and tracks an averaged copy of the weights. The last function returns (final_params, averaged_params).

The functions must behave as follows:

  • ema_update(avg, params, decay) returns a new float array decay * avg + (1 - decay) * params . It must not mutate its inputs.
  • swa_update(avg, params, n_averaged) returns (avg + (params - avg) / (n + 1), n + 1) . When n_averaged == 0 , it returns (copy of params, 1) and ignores avg .
  • sgd_with_averaging(grad_fn, x0, lr, n_steps, mode="ema", decay=0.99, swa_start=1) runs, for each step t = 1..n_steps , the update x = x - lr * grad_fn(x) , then averages the post-step x . It never mutates x0 .
  • With mode="ema" , initialize the average to x0 and update it every step. With mode="uniform" , average only the iterates where t >= swa_start . If no iterate was averaged, return the final x as the average.
  • Any other mode raises ValueError .

Example:

grad = lambda x: x   # iterates: 0.5, 0.25, 0.125
sgd_with_averaging(grad, np.array([1.0]), 0.5, 3, mode="ema", decay=0.5)
# -> ([0.125], [0.3125])   avg: 1 -> 0.75 -> 0.5 -> 0.3125
sgd_with_averaging(grad, np.array([1.0]), 0.5, 3, mode="uniform", swa_start=2)
# -> ([0.125], [0.1875])   mean(0.25, 0.125)
ema_update([1.0, 2.0], [3.0, -2.0], 0.9)  # -> [1.2, 1.6]

What a Strong Answer Covers Guidance

  • Helpers that return new float arrays and never mutate their inputs, including the n_averaged == 0 branch of swa_update .
  • Averaging the post-step iterate, with the EMA initialized at x0 and the uniform mean gated on t >= swa_start .
  • The fallback when uniform mode never averages anything, and a ValueError for an unknown mode.
  • Time and memory cost: O(d) memory with no stored trajectory, O(T·d) time plus the gradient calls.
  • Why the averaged weights land closer to the minimum than the last iterate when the gradients are noisy.

Follow-up Questions Guidance

  • Why does the uniform average converge under noisy gradients when the last iterate does not?
  • The EMA starts from x0 and is biased early on. How would you correct that?
  • What extra step does SWA need for networks with BatchNorm?