AI Wiki中文/EN

Adam: correct the initialization, keep the history

Adam

Inspect both moving moments, exact correction identities, zero-gradient motion and checkpoint state.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Average the direction as well as its scale

RMSProp uses recent squared gradients to scale a current gradient. Adam also averages the gradient in the numerator. The stored direction can therefore persist after a sign change or a zero gradient, while the denominator follows a separate history.

Kingma and Ba’s Algorithm 1 specifies these two histories and their initialization correction. We use the fixed v 9 manuscript, dated January 2017, of the ICLR 2015 paper. The PyTorch 2.8 Adam API provides a concrete implementation contract; the example below uses ordinary Adam without decay or AMSGrad.

Correction removes the initial zero weight

Let β₁ and β₂ lie in [0,1). Each operation is coordinatewise, with gₜ measured at θₜ₋₁:

mt=β1mt−1+(1−β1)gt,vt=β2vt−1+(1−β2)gt2,m0=v0=0.m_t=\beta_1m_{t-1}+(1-\beta_1)g_t,\qquad v_t=\beta_2v_{t-1}+(1-\beta_2)g_t^2,\qquad m_0=v_0=0.

v is a second raw moment estimate, not a centered variance. The powers in the correction below are ordinary scalar powers of the coefficients; the counter starts at one on the first update:

m^t=mt1−β1t,v^t=vt1−β2t,θt=θt−1−ηm^tv^t+ε.\widehat m_t=\frac{m_t}{1-\beta_1^t},\qquad \widehat v_t=\frac{v_t}{1-\beta_2^t},\qquad \theta_t=\theta_{t-1}-\eta\frac{\widehat m_t}{\sqrt{\widehat v_t}+\varepsilon}.

For a constant gradient c, mₜ=c(1−β₁ᵗ) and vₜ=c²(1−β₂ᵗ). Correcting them recovers c and c² exactly, apart from rounding. More generally the correction normalizes the exponential weights, whose sum was below one because of the zero initialization.

Calling this an unbiased estimate of the current gradient moment additionally requires a stationary moment assumption. Gradients along a changing optimization trajectory need not satisfy that assumption. Initialization correction does not remove sampling bias, model bias or nonstationarity.

Expanding the first recurrence explains the history weights. Algebra also gives an alternative update ordering:

mt=(1−β1)∑i=1tβ1t−igi,ηm^tv^t+ε=η1−β2t1−β1tmtvt+ε1−β2t.m_t=(1-\beta_1)\sum_{i=1}^t\beta_1^{t-i}g_i,\qquad \eta\frac{\widehat m_t}{\sqrt{\widehat v_t}+\varepsilon} =\frac{\eta\sqrt{1-\beta_2^t}}{1-\beta_1^t} \frac{m_t}{\sqrt{v_t}+\varepsilon\sqrt{1-\beta_2^t}}.

The epsilon must be rescaled in the alternative denominator. Moving the correction into a scalar learning rate while leaving the same epsilon unchanged generally changes the result. For a first scalar gradient 2, β₁=β₂=1/2, η=ε=0.1, the corrected step magnitude is 2/21; omitting correction gives 0.1/(√2+0.1).

A zero gradient can still produce motion

When gₜ=0, m decays rather than necessarily vanishing. Consequently Adam can move even with an explicit current zero gradient. A parameter omitted because its gradient is absent can be treated differently by a framework. Our function always processes the supplied numerical gradient.

Keep both moments and the counter

The complete Python 3.12 / NumPy 1.26.4 program uses β₁=β₂=1/2 to make the state arithmetic visible. These are teaching values, not recommended defaults. A prescribed gradient trace tests sign changes and a zero; a separate run actually fits f=(θ₁−1)²/2+4(θ₂+1)²/2.

import numpy as np


def adam_step(state,gradient,rate=.1,betas=(.5,.5),eps=.1):
    p,m,v,t=state;p,m,v,g=[np.array(x,dtype=np.float64,copy=True) for x in (p,m,v,gradient)]
    b1,b2=betas
    if p.ndim!=1 or not 1<=p.size<=8 or any(x.shape!=p.shape for x in (m,v,g)):raise ValueError('matching one-dimensional vectors required')
    if not all(np.isfinite(x).all() for x in (p,m,v,g)) or np.any(v<0):raise ValueError('finite states and nonnegative second moment required')
    if type(t) is not int or not 0<=t<10000 or not all(np.isfinite(x) for x in (rate,b1,b2,eps)):raise ValueError('finite options and valid counter required')
    if not 0<rate<=1 or not 0<=b1<1 or not 0<=b2<1 or not 0<eps<=1:raise ValueError('invalid optimizer options')
    t+=1;m=b1*m+(1-b1)*g;v=b2*v+(1-b2)*g*g
    mh=m/(1-b1**t);vh=v/(1-b2**t)
    p-=rate*mh/(np.sqrt(vh)+eps)
    if not all(np.isfinite(x).all() for x in (p,m,v)):raise ValueError('nonfinite update')
    return p,m,v,t


def initial(d=2):return np.zeros(d),np.zeros(d),np.zeros(d),0


if __name__=='__main__':
    state=initial(1)
    for g in (2.,-.5,0.,3.):
        state=adam_step(state,[g]);p,m,v,t=state
        print(t,'p / m / v:',[round(float(x[0]),9) for x in (p,m,v)])
    target=np.array([1.,-1.]);curvature=np.array([1.,4.]);state=initial()
    for _ in range(12):state=adam_step(state,curvature*(state[0]-target))
    loss=float(np.sum(curvature*(state[0]-target)**2)/2)
    print('fitted point / loss:',np.round(state[0],9).tolist(),round(loss,9))
    corrected=.1*2/(2+.1);uncorrected=.1/(np.sqrt(2)+.1)
    print('first corrected / uncorrected step magnitude:',round(corrected,9),round(uncorrected,9))

Actual output:

1 p / m / v: [-0.095238095, 1.0, 2.0]
2 p / m / v: [-0.120400173, 0.25, 1.125]
3 p / m / v: [-0.136241792, 0.125, 0.5625]
4 p / m / v: [-0.206913631, 1.5625, 4.78125]
fitted point / loss: [0.96398604, -1.046420495] 0.004958227
first corrected / uncorrected step magnitude: 0.095238095 0.066040883

The third audit gradient is zero, but the parameter still changes because m is nonzero. The fitted model recomputes its gradient at each iterate, rather than reusing the audit sequence. Tests independently expand the weighted histories, compare both epsilon-consistent update forms and resume from a saved (θ,m,v,t) state.

Each dense d-coordinate step takes O(d) work and stores two additional d-vectors plus a counter. Resetting only the counter while keeping the moments applies the wrong initialization correction; resetting the moments while keeping θ also changes the run. A full training checkpoint must preserve the sampler and schedule as well.

Practical success and convergence theorems are different evidence

Adam has useful empirical performance, but its name is not a convergence guarantee. Reddi, Kale and Kumar’s ICLR 2018 paper identifies problems in earlier analysis and constructs a convex failure example; the linked arXiv posting is from 2019. We do not reproduce that counterexample or claim the original regret bound as a blanket theorem.

Finite epsilon prevents exact scale cancellation in general. Separate β values also mean that the numerator and denominator average different windows, so interpreting their ratio as a calibrated statistical confidence score is unjustified. Neither a small current gradient nor a small parameter step proves that the full training objective has reached its optimum.

Weight decay, AMSGrad, clipping and mixed precision change the relevant computation. The cited API exposes both ordinary and optional decoupled behavior; state the chosen options instead of assuming every call named Adam uses identical regularization. The next article isolates that difference.

Which part of the state explains the movement?

  1. Is v a centered variance estimate?

Answer 1: No. It is a moving estimate of the raw second moment.

  1. Why can Adam move on an explicit zero-gradient step?

Answer 2: Its first moment may still contain earlier nonzero gradients.

  1. Does correcting zero initialization remove nonstationarity?

Answer 3: No. It normalizes historical weights; changing moment distributions remain a separate issue.

  1. What else changes when moving the bias correction outside the denominator?

Answer 4: Epsilon must be scaled by sqrt(1−β₂ᵗ) in the displayed equivalent formula.

Specify the variant before comparing results

The original algorithm, its later theoretical critique and the fixed API support different claims and should remain distinguishable. Our state traces, epsilon identity and fitted quadratic are original. Continue with RMSProp, AdamW and learning-rate schedules.

Make a prediction, then check

Can Adam move with an explicit current gradient of zero?

Choose one answer

Learning objectives

  • Derive initialization correction and its assumptions.
  • Preserve counter and moment state when resuming.

Prerequisites & connections

Explore related knowledge →

References

  1. Adam: A Method for Stochastic Optimization — arXiv1412.6980v9
    Diederik P. Kingma; Jimmy Ba · 2015
  2. Adam — PyTorch 2.8
    PyTorch contributors
  3. On the Convergence of Adam and Beyond — ICLR2018, arXiv1904.09237v1
    Sashank J. Reddi; Satyen Kale; Sanjiv Kumar · 2018

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.

  • Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
  • Four focused CPython3.12.4 tests passed per chapter. Adaptive accumulators and moments, coefficient/update ordering, checkpoint continuation and schedule boundaries are checked against expanded histories, exact products, literal values and known stability cases. Adagrad/Adam/AdamW use NumPy1.26.4; the other five use the standard library.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.