Equations · Kingma and Ba, “Adam: A Method for Stochastic Optimization” (2015)

The Adam optimizer update rule, explained

Adam keeps a running average of the gradient and of its square for every parameter, and steps by their ratio. All operations on vectors are elementwise.

gt=∇θft(θt−1)mt=β1mt−1+(1−β1) gtvt=β2vt−1+(1−β2) gt2m^t=mt1−β1t,v^t=vt1−β2tθt=θt−1−αm^tv^t+ϵ\begin{aligned} g_t &= \nabla_\theta f_t(\theta_{t-1}) \\ m_t &= \beta_1 m_{t-1} + (1 - \beta_1)\, g_t \\ v_t &= \beta_2 v_{t-1} + (1 - \beta_2)\, g_t^2 \\ \hat{m}_t &= \frac{m_t}{1 - \beta_1^t}, \quad \hat{v}_t = \frac{v_t}{1 - \beta_2^t} \\ \theta_t &= \theta_{t-1} - \alpha \frac{\hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon} \end{aligned}

Open in the decoder →

Term by term

  1. gt=∇θft(θt−1)g_t = \nabla_\theta f_t(\theta_{t-1})

    The gradient of the loss on this step's mini-batch, at the current parameters. tt is the step number.

  2. mt, β1m_t, \ \beta_1

    A moving average of gradients (the "first moment"). β1=0.9\beta_1 = 0.9 by default: each step keeps 90% of the old average.

  3. vt, β2, gt2v_t, \ \beta_2, \ g_t^2

    A moving average of squared gradients (the "second moment"), with β2=0.999\beta_2 = 0.999. gt2g_t^2 squares each entry.

  4. m^t=mt1−β1t\hat{m}_t = \frac{m_t}{1 - \beta_1^t}

    Bias correction: mm and vv start at 0 and are too small early on; dividing by 1−βt1 - \beta^t fixes that. Here β1t\beta_1^t really is a power: β1\beta_1 to the tt.

  5. α\alpha

    The step size (learning rate), 0.0010.001 by default.

  6. m^tv^t+ϵ\frac{\hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon}

    The step direction: average gradient divided by its typical size, per parameter. ϵ=10−8\epsilon = 10^{-8} prevents division by zero.

A small worked example

First step, one parameter, gradient g1=2g_1 = 2: m1=0.1×2=0.2m_1 = 0.1 \times 2 = 0.2 and v1=0.001×4=0.004v_1 = 0.001 \times 4 = 0.004. Corrected: m^1=0.2/0.1=2\hat{m}_1 = 0.2/0.1 = 2, v^1=0.004/0.001=4\hat{v}_1 = 0.004/0.001 = 4. Step: α×2/4=α\alpha \times 2/\sqrt{4} = \alpha. The first step has size α\alpha however large the gradient is.

In code

import numpy as np

def adam_step(theta, g, m, v, t, alpha=1e-3, b1=0.9, b2=0.999, eps=1e-8):
    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)
    return theta - alpha * m_hat / (np.sqrt(v_hat) + eps), m, v

Every symbol in it

∇θL\nabla_\theta \mathcal{L}Nabla (gradient)xi,  Wq,  pθ,  dmodelx_i,\; W_q,\; p_\theta,\; d_{\text{model}}Subscript (index or label)pθ(x)p_\theta(x)Thetaβ1,β2\beta_1, \beta_2Betax2,  βt,  WQx^2,\; \beta^t,\; W^QSuperscript (power or label)y^\hat{y}Hat (estimate)ab\frac{a}{b}Fractionα\alphaAlphadk\sqrt{d_k}Square rootϵ\epsilonEpsilon

Other equations