AI Wiki中文/EN

Adagrad: each coordinate keeps its own account

AdaGrad

Compute diagonal scaling from gradient history and test rare coordinates, epsilon and actual fitting.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Give an infrequent coordinate its own history

Two features can produce the same gradient today after very different histories. One has been active in every batch; the other has just appeared. A single global learning rate treats them alike. Diagonal Adagrad keeps a separate sum of squared gradients for each coordinate and uses it to scale the current update.

Duchi, Hazan and Singer’s 2011 paper develops a family of adaptive subgradient methods. Its diagonal construction motivates the unregularized update here. The fixed PyTorch 2.8 interface specifies the accumulator and epsilon convention. We implement a dense diagonal case, not the paper’s full matrix or constrained variants.

A diagonal metric changes the cost of moving

Let gₜ be the gradient at the old parameter vector, η a fixed positive base rate, and ε a positive denominator offset. All squares, roots and divisions below act coordinate by coordinate:

st,j=st−1,j+gt,j2,θt,j=θt−1,j−ηgt,jst,j+ε,s0,j=0.s_{t,j}=s_{t-1,j}+g_{t,j}^2,\qquad \theta_{t,j}=\theta_{t-1,j}-\frac{\eta g_{t,j}}{\sqrt{s_{t,j}}+\varepsilon},\qquad s_{0,j}=0.

Include the current gradient in s before dividing. Using yesterday’s accumulator computes another algorithm and can make the first update enormous. With a fixed η, the effective coefficient η/(√s+ε) cannot increase because s cannot decrease. The actual displacement can still increase when a later gradient is larger.

The update also minimizes a local linear loss plus a quadratic movement cost:

Ht=diag⁡(st+ε),Δt=arg⁡min⁡Δ{gt⊤Δ+12ηΔ⊤HtΔ}=−ηHt−1gt.H_t=\operatorname{diag}(\sqrt{s_t}+\varepsilon),\qquad \Delta_t=\arg\min_{\Delta}\left\{g_t^\top\Delta+\frac1{2\eta}\Delta^\top H_t\Delta\right\} =-\eta H_t^{-1}g_t.

Differentiating with respect to Δ gives g+HΔ/η=0. A large accumulated coordinate receives a high movement penalty. H is positive definite because ε is positive; this is not a measured Hessian, and the local surrogate is not the full objective.

For a coordinate with the same nonzero gradient c at every step:

gt,j=c≠0 ⟹ st,j=tc2,∣Δt,j∣=η∣c∣∣c∣t+ε.g_{t,j}=c\ne0\ \Longrightarrow\ s_{t,j}=tc^2,\qquad |\Delta_{t,j}|=\frac{\eta |c|}{|c|\sqrt t+\varepsilon}.

This explains the roughly inverse-square-root decay along persistently active coordinates. A rarely active coordinate has accumulated less squared gradient, but its actual importance still depends on the task. If gradients change their scale or distribution, old large gradients remain in the sum indefinitely.

With ε=0 and nonzero denominators, scaling an entire coordinate’s gradient history by a positive constant cancels between numerator and denominator. A fixed nonzero ε breaks exact invariance. Scaling ε by the same factor restores that algebraic cancellation; neither statement implies invariance to arbitrary rotations of the parameter space.

Inspect the accumulator, then fit a quadratic

The complete Python 3.12 / NumPy 1.26.4 program first sends four unit gradients to one coordinate and one to another. It then genuinely optimizes f=(θ₁−1)²/2+9(θ₂+1)²/2, starting at zero. The helper returns copies and explicitly checks shapes and accumulator sign.

import numpy as np


def step(theta,accumulator,gradient,rate=.5,eps=.1):
    p,s,g=[np.array(v,dtype=np.float64,copy=True) for v in (theta,accumulator,gradient)]
    if p.ndim!=1 or not 1<=p.size<=8 or s.shape!=p.shape or g.shape!=p.shape:raise ValueError('matching one-dimensional vectors required')
    if not all(np.isfinite(v).all() and np.all(np.abs(v)<=1e6) for v in (p,s,g)) or np.any(s<0):raise ValueError('finite bounded values and nonnegative accumulator required')
    if not np.isfinite(rate) or not np.isfinite(eps) or not 0<rate<=1 or not 0<eps<=1:raise ValueError('rate and epsilon must be in (0,1]')
    s+=g*g;effective=rate/(np.sqrt(s)+eps)
    return p-effective*g,s,effective


def fit(steps=8):
    p=np.zeros(2);s=np.zeros(2);target=np.array([1.,-1.]);curvature=np.array([1.,9.]);rows=[]
    for _ in range(steps):
        g=curvature*(p-target);p,s,effective=step(p,s,g)
        rows.append((p.copy(),s.copy(),float(np.sum(curvature*(p-target)**2)/2)))
    return rows


if __name__=='__main__':
    p=np.zeros(2);s=np.zeros(2)
    for g in ([1,0],[1,0],[1,0],[1,1]):p,s,e=step(p,s,g)
    print('frequent / rare accumulator:',s.tolist())
    print('same-gradient effective rates:',np.round(e,9).tolist())
    rows=fit()
    print('first fitted point:',np.round(rows[0][0],9).tolist())
    print('eight-step point / loss:',np.round(rows[-1][0],9).tolist(),round(rows[-1][2],9))
    a=step([0],[0],[1])[0][0];b=step([0],[0],[10])[0][0]
    print('fixed-epsilon scaling comparison:',round(a,9),round(b,9))

Actual output:

frequent / rare accumulator: [4.0, 1.0]
same-gradient effective rates: [0.238095238, 0.454545455]
first fitted point: [0.454545455, -0.494505495]
eight-step point / loss: [0.982124472, -0.989701623] 0.000637022
fixed-epsilon scaling comparison: -0.454545455 -0.495049505

The fourth shared gradient sees denominators 2.1 and 1.1. The first quadratic update is (5/11,−45/91), a hand-checkable reference. The accumulated values in the fitted run come from gradients at changing parameters, so they are not the constant-gradient formula above.

A dense d-coordinate step costs O(d) time and O(d) extra accumulator storage. No full d-by-d matrix is built. Saving only θ is insufficient for exact continuation: the accumulator, rate convention and data order matter too.

Adaptation does not remove tuning

The base rate and epsilon still matter. Initializing the accumulator to a positive value changes early updates; the cited API also offers an additional global rate decay, which is separate from coordinate adaptation. Neither option is used here.

Summing forever can make updates too conservative after a regime change. RMSProp replaces the sum with a moving average, trading long memory for responsiveness. Sparse gradients can reduce computation in a suitable implementation, but our dense arrays do not provide sparse-update performance.

The original regret results have online convex and domain assumptions. Successful fitting of this tiny quadratic does not establish convergence to a global optimum for a neural network. A large diagonal scale may reflect gradient units, noise or repeated exposure rather than a universally trustworthy curvature estimate.

Check which quantity shrinks

  1. Is s a sum of gradients or squared gradients?

Answer 1: Squared gradients, coordinate by coordinate.

  1. Must every displacement become smaller over time?

Answer 2: No. The effective coefficient decreases at fixed η, but the current gradient may increase.

  1. What breaks exact gradient-scale invariance in the displayed comparison?

Answer 3: Holding a positive epsilon fixed while scaling the gradient history.

  1. What state must accompany the parameters in a checkpoint?

Answer 4: The squared-gradient accumulator, plus the relevant rate and sampling state.

Move from cumulative to recent history

The paper supplies the diagonal metric and the fixed API the denominator convention. The repeated-coordinate and fitted-quadratic calculations are original. Continue with SGD, RMSProp and Adam.

Make a prediction, then check

What does Adagrad accumulate?

Choose one answer

Learning objectives

  • Derive the diagonal surrogate update.
  • Distinguish effective coefficient from displacement.

Prerequisites & connections

Explore related knowledge →

References

  1. Adaptive Subgradient Methods for Online Learning and Stochastic Optimization
    John Duchi; Elad Hazan; Yoram Singer · 2011
  2. Adagrad — 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. 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.