v9.1.1
Menu

Adam Optimizer Step

hardFREECalculus & OptimizationOptimizationCV: Mathematical Foundations

Implement a single step of the Adam optimizer, widely used in deep learning.

Adam (Adaptive Moment Estimation) combines momentum and RMSprop, adapting learning rates per-parameter:

Algorithm (single step at time tt):

  1. Compute gradient gtg_t at current parameters
  2. Update biased first moment: mt=β1mt−1+(1−β1)gtm_t = \beta_1 m_{t-1} + (1-\beta_1) g_t
  3. Update biased second moment: vt=β2vt−1+(1−β2)gt2v_t = \beta_2 v_{t-1} + (1-\beta_2) g_t^2
  4. Bias correction: m^t=mt1−β1t\hat{m}_t = \frac{m_t}{1-\beta_1^t}, v^t=vt1−β2t\hat{v}_t = \frac{v_t}{1-\beta_2^t}
  5. Update parameters: θt=θt−1−αm^tv^t+ϵ\theta_t = \theta_{t-1} - \alpha \frac{\hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon}

Typical hyperparameters: α=0.001\alpha=0.001, β1=0.9\beta_1=0.9, β2=0.999\beta_2=0.999, ϵ=10−8\epsilon=10^{-8}

Example

Input
params = [1.0, 2.0]
grads = [0.1, 0.2]
m = [0.0, 0.0]
v = [0.0, 0.0]
t = 1
lr = 0.001
beta1 = 0.9
beta2 = 0.999
Output
{'params': [0.999, 1.999], 'm': [0.01, 0.02], 'v': [0.00001, 0.00004]}
Reasoning
  • Inputs: two parameters θ0=[1.0,2.0]\theta_0 = [1.0, 2.0] with gradients g1=[0.1,0.2]g_1 = [0.1, 0.2]; both moment estimates start at zero and this is the first step, t=1t = 1. All maths is element-wise.
  • First moment: m1=0.9⋅0+0.1⋅g1=[0.01,0.02]m_1 = 0.9 \cdot 0 + 0.1 \cdot g_1 = [0.01, 0.02], still pulled toward its zero start.
  • Second moment: v1=0.999⋅0+0.001⋅g12=0.001⋅[0.01,0.04]=[0.00001,0.00004]v_1 = 0.999 \cdot 0 + 0.001 \cdot g_1^2 = 0.001 \cdot [0.01, 0.04] = [0.00001, 0.00004].
  • Bias correction undoes that pull toward zero: m^1=m1/(1−0.9)=[0.1,0.2]\hat{m}_1 = m_1 / (1 - 0.9) = [0.1, 0.2] and v^1=v1/(1−0.999)=[0.01,0.04]\hat{v}_1 = v_1 / (1 - 0.999) = [0.01, 0.04]. At t=1t = 1 they recover exactly g1g_1 and g12g_1^2.
  • Update: v^1=[0.1,0.2]\sqrt{\hat{v}_1} = [0.1, 0.2], so the ratio m^1/(v^1+ϵ)≈[1,1]\hat{m}_1 / (\sqrt{\hat{v}_1} + \epsilon) \approx [1, 1] and θ1=[1,2]−0.001⋅[1,1]=[0.999,1.999]\theta_1 = [1, 2] - 0.001 \cdot [1, 1] = [0.999, 1.999]. The ϵ\epsilon only shifts the 10th decimal, lost when rounding to 6 places.
  • Notice: both parameters moved by exactly α\alpha even though one gradient is twice the other. The step size ignores the gradient's raw scale.

Constraints

  • params: Current parameter values (list)
  • grads: Gradients at current params (list)
  • m, v: First and second moment estimates (lists)
  • t: Current timestep (int >= 1)
  • Return: Dict with new 'params', 'm', 'v'
  • Round to 6 decimal places

Learn this in

More from CV: Mathematical Foundations

solution.py

Test results

Sign in to run your code against the test cases.