AI Wiki中文/EN

Momentum: keep track of the moving state

动量优化

Trace an exact quadratic, a nonmonotone loss and the consequences of resetting or rescaling momentum.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The update has a memory of its own

An ordinary gradient step depends on the current gradient. A momentum step also carries an optimizer state from earlier gradients. This state is not a neural network’s hidden state and does not become an input feature; it changes how weights move during training.

Sutskever and colleagues, Section 2, write classical momentum using a displacement velocity. The fixed PyTorch 2.8 documentation highlights a different buffer convention. We will fit a two-coordinate quadratic and inspect both conventions, including a case in which the first momentum step increases the loss.

Track the sign and units of the state

Let β lie in [0,1), ηₜ be positive, and v₀ be zero. In the displacement convention, v has the same units as θ:

vt+1=βvt−ηt∇f(θt),θt+1=θt+vt+1,vt+1=−∑j=0tβt−jηj∇f(θj)(v0=0).v_{t+1}=\beta v_t-\eta_t\nabla f(\theta_t),\qquad \theta_{t+1}=\theta_t+v_{t+1},\qquad v_{t+1}=-\sum_{j=0}^{t}\beta^{t-j}\eta_j\nabla f(\theta_j) \quad(v_0=0).

The last expression follows by repeated substitution. Persistent gradients accumulate, but so can a persistent wrong direction. With a constant gradient and rate, velocity approaches −ηg/(1−β); comparing momentum and plain SGD at the same nominal learning rate does not match their long-run displacement on that artificial constant-gradient field.

For a quadratic coordinate f(x)=λx²/2 with positive curvature λ and fixed η, substitute vₜ=xₜ−xₜ₋₁ to obtain the second-order recurrence:

xt+1=(1+β−ηλ)xt−βxt−1,r2−(1+β−ηλ)r+β=0.x_{t+1}=(1+\beta-\eta\lambda)x_t-\beta x_{t-1},\qquad r^2-(1+\beta-\eta\lambda)r+\beta=0.

The roots describe contraction, oscillation or divergence along that coordinate. Momentum can be stable even where the same learning rate makes plain gradient descent unstable, but increasing β does not remove the need to choose η. For this positive-curvature scalar recurrence, β in [0,1) and ηλ strictly between zero and 2(1+β) put both roots inside the unit circle; the endpoints are excluded.

An exact two-coordinate example

Use f(x,y)=(x²+9y²)/2, initial position (1,1), zero velocity, η=1/4 and β=1/4. The roots are repeated at 1/2 for x and −1/2 for y. Matching the first two positions gives the first two identities below. The last two expressions introduce a gradient-unit buffer b:

xt=(1+t/2)2−t,yt=(1+3t/2)(−1/2)t,bt+1=βbt+gt,θt+1=θt−ηtbt+1.x_t=(1+t/2)2^{-t},\qquad y_t=(1+3t/2)(-1/2)^t,\qquad b_{t+1}=\beta b_t+g_t,\qquad \theta_{t+1}=\theta_t-\eta_t b_{t+1}.

The first step moves to (3/4,−5/4), raising loss from 5 to 117/16. Later steps shrink the oscillation. The program compares six steps against plain gradient descent with its own fixed rate 1/5; it does not handicap the baseline by using the unstable rate 1/4.

For a constant learning rate and matching initialization, the buffer convention is equivalent under vₜ=−ηbₜ. If the rate changes, the displacement stored from earlier steps contains their earlier rates; multiplying an unscaled accumulated gradient by the new rate does something different. Exact continuation also requires the velocity, not just the position.

Inspect positions, losses and a checkpoint

This complete standard-library Python 3.12 program uses rational arithmetic for a positive diagonal quadratic. Its heavy_ball function accepts an explicit rate sequence and optional initial velocity. The separate scalar buffer example uses f(θ)=θ²/2 and is intentionally small enough to check by hand.

from fractions import Fraction as F


def heavy_ball(initial,curvatures,rates,beta=F(1,4),velocity=None):
    theta=tuple(F(v) for v in initial);lam=tuple(F(v) for v in curvatures);rates=tuple(F(v) for v in rates);beta=F(beta)
    velocity=tuple(F(0) for _ in theta) if velocity is None else tuple(F(v) for v in velocity)
    if not 1<=len(theta)<=8 or len(lam)!=len(theta) or len(velocity)!=len(theta):raise ValueError('matching dimensions from one to eight required')
    if any(not 0<v<=100 for v in lam) or not 0<=beta<1 or len(rates)>64 or any(not 0<v<=1 for v in rates):raise ValueError('bounded positive curvature/rates and beta in [0,1) required')
    history=[(theta,velocity,sum(l*t*t for l,t in zip(lam,theta))/2)]
    for rate in rates:
        velocity=tuple(beta*v-rate*l*t for v,l,t in zip(velocity,lam,theta))
        theta=tuple(t+v for t,v in zip(theta,velocity))
        history.append((theta,velocity,sum(l*t*t for l,t in zip(lam,theta))/2))
    return history


def gradient_buffer(rates,beta=F(1,4)):
    theta=F(1);buffer=F(0);history=[theta]
    for rate in rates:
        buffer=beta*buffer+theta
        theta-=F(rate)*buffer;history.append(theta)
    return history


if __name__=='__main__':
    run=heavy_ball((1,1),(1,9),[F(1,4)]*6)
    gd=heavy_ball((1,1),(1,9),[F(1,5)]*6,beta=0)
    for t,(theta,velocity,loss) in enumerate(run):print(t,[str(v) for v in theta],str(loss))
    print('six-step gradient-descent loss:',str(gd[-1][2]))
    rates=(F(1,4),F(1,8))
    print('changed-rate displacement / gradient-buffer endpoints:',str(heavy_ball((1,),(1,),rates)[-1][0][0]),str(gradient_buffer(rates)[-1]))
    prefix=heavy_ball((1,1),(1,9),[F(1,4)]*3)
    continued=heavy_ball(prefix[-1][0],(1,9),[F(1,4)]*3,velocity=prefix[-1][1])
    print('checkpoint continuation matches:',continued[-1]==run[-1])

Actual output:

0 ['1', '1'] 5
1 ['3/4', '-5/4'] 117/16
2 ['1/2', '1'] 37/8
3 ['5/16', '-11/16'] 557/256
4 ['3/16', '7/16'] 225/256
5 ['7/64', '-17/64'] 1325/4096
6 ['1/16', '5/32'] 229/2048
six-step gradient-descent loss: 16777216/48828125
changed-rate displacement / gradient-buffer endpoints: 19/32 5/8
checkpoint continuation matches: True

After six steps the momentum position is (1/16,5/32), with loss 229/2048. The decreasing loss over this short comparison does not prove momentum wins on every function or at every stopping time. In the two-step rate-change example, displacement momentum ends at 19/32; the gradient buffer ends at 5/8. That difference is a convention change, not floating-point noise.

The state needed for continuation is (θ,v) plus the remaining schedule and any sampler state in stochastic training. The test resumes at step three and obtains the exact uninterrupted endpoint. Resetting v at that boundary generally changes the run. An ordinary d-coordinate step takes O(d) arithmetic for this diagonal objective and O(d) extra velocity storage; the returned history is optional.

Momentum is not a monotone-loss rule

Velocity can carry the iterate across a narrow valley or beyond a minimum. Overshoot can be part of a convergent trajectory, as our exact example shows; it can also signal divergence. Judge it using a specified objective, bounded run and stability analysis rather than a single dramatic step.

The formulas here have no dampening, weight decay, clipping or adaptive preconditioner. The cited PyTorch interface initializes a momentum buffer from the first gradient, with dampening affecting later updates; a clone must match those details before claiming equality. Our numerical convention comparison uses zero dampening and does not execute PyTorch.

A deterministic quadratic exposes curvature cleanly, whereas stochastic gradients add noise and nonconvex models change local curvature along the path. Hyperparameters derived for one quadratic are not universal deep-learning defaults. Checkpointing, learning-rate schedules and state reset decisions are part of the algorithm, not merely file-management details.

Continue the trajectory correctly

  1. Does the first loss increase contradict convergence in this example?

Answer 1: No. The exact coordinate formulas tend to zero despite the initial overshoot.

  1. What extra state is needed beyond θ for exact deterministic continuation?

Answer 2: The velocity and the remaining optimizer schedule.

  1. When is v=−ηb a valid fixed conversion between the two conventions?

Answer 3: With constant η, matching initialization and matching update options; changing η generally breaks that fixed conversion.

  1. What happens when β=0?

Answer 4: The displacement update reduces to ordinary gradient descent with the supplied learning rate.

Compare algorithms with their state definitions attached

The paper supplies the classical displacement formulation and the documentation makes the implementation distinction explicit. Our quadratic, closed-form roots, baseline comparison and resume test are original. The paper’s deep-network experiments were not reproduced. Continue with SGD, Nesterov acceleration and weight decay.

Make a prediction, then check

What generally changes if velocity is reset halfway through training?

Choose one answer

Learning objectives

  • Derive the quadratic coordinate recurrence.
  • Preserve velocity and schedule when resuming.

Prerequisites & connections

Explore related knowledge →

References

  1. On the importance of initialization and momentum in deep learning
    Ilya Sutskever; James Martens; George Dahl; Geoffrey Hinton · 2013
  2. SGD — PyTorch 2.8
    PyTorch contributors

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. Bidirectional alignment/Jacobians, injected network faults, exhaustive learning curves and stochastic paths, exact momentum trajectories, Nesterov reparameterization and a smooth accelerated bound instance are checked. Bidirectional RNN/debugging use NumPy1.26.4; the other four 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.