Deep-ML | Temporal Averaging of Adam's Iterates: Polyak Mean and a Bias-Corrected EMATemporal Averaging of Adam's Iterates: Polyak Mean and a Bias-Corrected EMA
Temporal Averaging of Adam's Iterates: Polyak Mean and a Bias-Corrected EMA
```python
import numpy as np
last, pol, ema = adam_with_averages(lambda th, t: np.zeros_like(th), np.array([1.0, -2.0]), 5)
print([last.tolist(), pol.tolist(), np.round(ema, 10).tolist()])
```
Output:
[[1.0, -2.0], [1.0, -2.0], [1.0, -2.0]]
Reasoning:
The gradient is always 0, so Adam never moves and every iterate equals the start. Both averages must then return the start exactly; the EMA does only because its sum of weights, 1 - b^5, is divided out.
With noisy gradients the last iterate of an optimizer jitters around the optimum, and an average of recent iterates is usually closer. The Adam paper suggests two averages that add one line to the loop: the Polyak-Ruppert mean of all iterates, and an exponential moving average of the parameters that starts at 0 and is bias-corrected like Adam's moments. Run Adam and keep both.
grad(theta, t): returns the (possibly noisy) gradient at theta for timestep t (1-based), same shape as theta.
theta0: the starting parameters (1-D). steps=T≥1.
Adam, element-wise, with m0=v0=0: gt=grad(theta_{t-1}, t), mt=β1mt−1+(1−β1)gt, vt=β2vt−1+(1−β2)gt2, θt=θt−1−αm^t/(v^t+ϵ) with m^t=mt/(1−β1t), v^t=vt/(1−β2t).
Averages over the iterates θ1,…,θT (not θ0), with b = avg_decay, or β2 when it is None:
θˉTP=T1∑t=1Tθt,θˉt=bθˉt−1+(1−b)θt,θˉ0=0,θ^T=1−bTθˉT.
Returns (theta_T, polyak_mean, ema_corrected), three float arrays of the shape of theta0.