One Step of Adam

OptimizationMedium+20 XP+15

One Step of Adam

Adam is the default optimiser for most of deep learning. It keeps two running averages per parameter — m, a smoothed gradient (momentum), and v, a smoothed squared gradient (how noisy this parameter has been) — and divides one by the square root of the other, so parameters with wild gradients take small steps and steady ones take large steps.

One update, given gradient g at timestep t:

m = β₁·m + (1 - β₁)·gnew momentum
v = β₂·v + (1 - β₂)·g²new second moment
m̂ = m / (1 - β₁ᵗ)bias-corrected
v̂ = v / (1 - β₂ᵗ)bias-corrected
w = w - lr · m̂ / (√v̂ + ε)the step

The bias correction exists because m and v both start at zero, which drags the first few updates toward zero. Dividing by 1 - βᵗ cancels that — and it fades away as t grows.

Task: write adam_step(w, g, m, v, t, lr=0.001, beta1=0.9, beta2=0.999, eps=1e-8), where w, g, m and v are equal-length lists. Return (w_new, m_new, v_new) — three lists, each value rounded to 6 decimal places.

  • Note t starts at 1, not 0.
  • Update m and v before using them, and return the uncorrected m and v — bias correction is used for the step only, never stored.

Examples

w = [1.0, -1.0]
g = [0.5, 0.5]
m = [0.0, 0.0]
v = [0.0, 0.0]
t = 1
lr = 0.1
returns [[0.9, -1.1], [0.05, 0.05], [0.00025, 0.00025]]
w = [0.0]
g = [1.0]
m = [0.0]
v = [0.0]
t = 1
returns [[-0.001], [0.1], [0.001]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run