859. Fix Adam missing bias correction
Why it matters Adam is in every training loop. Without bias correction the first steps are far too small or too large, depending on the betas, which shows up as slow or unstable warm starts.
The starter code below runs, but it has a realistic bug. Read the spec, find the bug and fix it. Keep the function name and signature.
adam_run(w, grads, lr=0.1, b1=0.9, b2=0.999, eps=1e-8) should apply Adam for len(grads) steps, starting from m = v = 0, and return the final weights. For step t = 1, 2, ...:
- m = b1 * m + (1 - b1) * g and v = b2 * v + (1 - b2) * g ** 2
- m_hat = m / (1 - b1 ** t) and v_hat = v / (1 - b2 ** t)
- w = w - lr * m_hat / (sqrt(v_hat) + eps)
Inputs: w is a list or ndarray of shape (d,). grads is a list of gradients, each of shape (d,). An empty grads list returns w unchanged.
Return an ndarray of floats with shape (d,). No rounding.
def adam_run(w, grads, lr=0.1, b1=0.9, b2=0.999, eps=1e-8)Example 1
Input: adam_run([1.0, -1.0], [[0.5, -2.0]])
Output: [0.9, -0.9]
Example 2
Input: w = [0.0], grads = [[1.0], [1.0], [1.0]], lr = 0.01
Output: [-0.03]
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Compute the first step by hand: what should m_hat be?
Hint 2
The step counter t already exists in the loop.
Hint 3
Add m_hat and v_hat before the weight update.
Common mistakes
- Correcting with the global step t + 1 instead of t.
- Putting eps inside the sqrt (a different variant).
- Mutating the caller's array in place.
Understand the idea
m and v start at zero, so early on they are biased towards zero: after one step m = 0.1 g and v = 0.001 g^2. Dividing by 1 - b1^t and 1 - b2^t undoes that, so the very first update has size about lr in each coordinate. Without it the first step is about 0.1 / sqrt(0.001) = 3.16 times too big.
Shapes and data flow
w, m, v, g: (d,).