247. 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 ** 2m_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)Adam against plain gradient descent
Adam scales each coordinate by its own running gradient size (β1 = 0.9, β2 = 0.999, bias corrected), so both directions move at a similar pace.
- step
- 0
- w1
- -4
- w2
- 1.5
- loss
- 30.5
Example 1
Input: adam_step([1.0, -2.0], [0.5, -3.0], [0.0, 0.0], [0.0, 0.0], 1)[0]
Output: [0.999, -1.999]
Example 2
Input: adam_step([1.0], [0.5], [0.0], [0.0], 1)[1:]
Output: ([0.05], [0.00025])
Example 3
Input: adam_step([0.3, 0.1], [0.2, -0.1], [0.05, 0.02], [0.001, 0.0004], 10, lr=0.01)[0]
Output: [0.296911, 0.099394]
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
Hint 1
Follow the four lines exactly.
Hint 2
Bias correction uses the step number t, not t - 1.
Common mistakes
- Without the correction (the buggy version) the first steps are far too small or too large.
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.
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.
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.
Topics
Companies2
- Meta the topic appears in interview reports Machine Learning interview questions, page 10 (KatKat)
- Netflix the topic appears in interview reports Netflix Machine Learning Engineer Interview Process
From public interview reports and guides. Not affiliated with or endorsed by these companies.