Implement one step of the Adam optimizer
Adam is the default optimizer for training neural nets. It keeps a running mean m and a running mean of squares v of the gradient, corrects both for starting at zero, and scales each parameter's step separately.
Write adam_step(w, g, m, v, t, lr=1e-3, b1=0.9, b2=0.999, eps=1e-8) where t is the step number starting at 1. Return (new_w, new_m, new_v):
m = b1 m + (1 - b1) g
v = b2 v + (1 - b2) g ** 2
m_hat = m / (1 - b1 ** t), v_hat = v / (1 - b2 ** t)
w = w - lr m_hat / (sqrt(v_hat) + eps)
def adam_step(w, g, m, v, t, lr=1e-3, b1=0.9, b2=0.999, eps=1e-8)Understand the idea
Adam gives every parameter its own step size. It keeps m, a running average of gradients (direction), and v, a running average of squared gradients (typical size). Dividing m by sqrt(v) makes steps similar in size whether gradients are huge or tiny. Since m and v start at zero, early averages are too small, so both are divided by 1 - beta^t. Worked example: w = 1, g = 0.5, m = v = 0, t = 1, lr = 0.001. m = 0.1 x 0.5 = 0.05. v = 0.001 x 0.25 = 0.00025. m_hat = 0.05 / (1 - 0.9) = 0.5. v_hat = 0.00025 / (1 - 0.999) = 0.25. Step = 0.001 x 0.5 / (sqrt(0.25) + 1e-8) = 0.001, so w = 0.999. Notice the first step is about lr whatever the gradient size. Rule: m = b1 m + (1 - b1) g; v = b2 v + (1 - b2) g^2; bias-correct both; w -= lr m_hat / (sqrt(v_hat) + eps). Adam is the default optimizer for training neural networks.