Equations · Loshchilov and Hutter, “Decoupled Weight Decay Regularization” (2019)

The AdamW update rule (decoupled weight decay), explained

AdamW is Adam with weight decay applied directly to the weights, outside the adaptive step. Adding an L2 penalty to the loss instead sends the decay through Adam's per-parameter scaling, which weakens it for exactly the weights with large gradients. AdamW is the default optimizer for training Transformers.

θt=θt−1−ηt(α m^tv^t+ϵ+λ θt−1)\theta_t = \theta_{t-1} - \eta_t\left(\alpha\,\frac{\hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon} + \lambda\,\theta_{t-1}\right)

Open in the decoder →

Term by term

  1. θt, θt−1\theta_t, \ \theta_{t-1}

    The parameters after and before step tt.

  2. m^t, v^t\hat{m}_t, \ \hat{v}_t

    Adam's bias-corrected moving averages of the gradient and the squared gradient, computed exactly as in Adam.

  3. α m^tv^t+ϵ\alpha\,\frac{\hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon}

    The usual Adam step, with step size α\alpha.

  4. λ θt−1\lambda\,\theta_{t-1}

    The decoupled weight decay: shrink every weight toward zero by a fixed fraction λ\lambda, regardless of its gradient history.

  5. ηt\eta_t

    A schedule multiplier, such as a cosine schedule, applied to both parts. In PyTorch's version the decay is scaled by the learning rate: θ←θ−lr⋅λ θ\theta \leftarrow \theta - \mathrm{lr} \cdot \lambda\,\theta.

A small worked example

PyTorch defaults, lr=0.001\mathrm{lr} = 0.001 and λ=0.01\lambda = 0.01; one weight θ=2\theta = 2 with gradient 0.50.5 on the first step. Decay: 0.001×0.01×2=0.000020.001 \times 0.01 \times 2 = 0.00002. Adam step: m^/v^=1\hat{m}/\sqrt{\hat{v}} = 1 on step one, so 0.0010.001. New weight: 2−0.00002−0.001=1.998982 - 0.00002 - 0.001 = 1.99898. With L2 in the loss instead, the gradient becomes 0.5+0.01×2=0.520.5 + 0.01 \times 2 = 0.52, and Adam's normalization makes the first step exactly 0.0010.001 again: the decay vanished.

In code

import numpy as np

def adamw_step(theta, g, m, v, t, lr=1e-3, b1=0.9, b2=0.999, eps=1e-8, wd=0.01):
    theta = theta - lr * wd * theta            # decoupled decay (PyTorch's scaling)
    m = b1 * m + (1 - b1) * g
    v = b2 * v + (1 - b2) * g**2
    m_hat, v_hat = m / (1 - b1**t), v / (1 - b2**t)
    return theta - lr * m_hat / (np.sqrt(v_hat) + eps), m, v

Every symbol in it

pθ(x)p_\theta(x)Thetaxi,  Wq,  pθ,  dmodelx_i,\; W_q,\; p_\theta,\; d_{\text{model}}Subscript (index or label)y^\hat{y}Hat (estimate)α\alphaAlphaab\frac{a}{b}Fractiondk\sqrt{d_k}Square rootϵ\epsilonEpsilonλ∥w∥22\lambda \|\mathbf{w}\|_2^2Lambdaη\etaEta

Other equations