Introduce methods adapting each coordinate's step from its gradient history. Derive AdaGrad from online convex optimization and regret, then RMSProp's exponential average and Adam's bias correction, interpreting all as diagonal preconditioning.
After this lesson you can
Define regret in online convex optimization and prove online gradient descent's O(√T) bound.
Derive AdaGrad as online gradient descent with adaptive diagonal preconditioning and explain its advantage for sparse gradients.
Explain why RMSProp replaces the sum with an exponential average and which AdaGrad problem this solves.
Write Adam with bias correction, justify the correction under stationarity and implement it from scratch.
Interpret adaptive methods as diagonal preconditioning and reason about their invariance and non-invariance to rescaling.
Motivation: one learning rate for dissimilar parameters
Everything so far, from gradient descent on quadratics to stochastic momentum, shares a decision: one step η for every parameter. Convenient, but often poor for two distinct reasons worth separating.
The first is scale. In a network, output-layer and first-layer gradients can differ by orders of magnitude, as can a bias and a weight matrix. An η that does not explode on the large-gradient coordinate leaves the small-gradient coordinate nearly motionless, the coordinate-wise analogue of lesson 3’s ill-conditioning. The second is frequency. In a language model, the embedding-matrix row for “of” gets a gradient on nearly every example; a rare word’s row gets one every million steps. With fixed η the common word moves at full speed and the rare one barely learns, yet the rare one often carries more information.
The lesson’s idea is simple to state: look at each coordinate’s gradient history and divide its step by the scale that history reveals. Coordinates with large or frequent gradients get small steps; those with small or rare gradients get large ones. Three methods follow: AdaGrad (2011), RMSProp (2012) and Adam (2014), now among the most widely used for network training. We examine exactly what they promise and what they do not.
Three questions guide us. What guarantee can such a method offer when problem scale is unknown? What changes from AdaGrad to RMSProp and then Adam, and why is each change needed? What kind of ill-conditioning do they not fix? The next figure maps what follows: six methods, four surfaces and the ability to tune each step for fair comparison.
InteractiveOptimizer race
f−f⋆ on a logarithmic scale
SGD
Momentum
AdaGrad
RMSProp
Adam
Surface
k = 600
SGD (η=0.0020): f at k0.239
Momentum (η=0.0020): f at k1.8e−5
AdaGrad (η=0.0500): f at k3.64
RMSProp (η=0.0500): f at k0.257
Adam (η=0.0500): f at k1.1e−4
Rosenbrock curved valley, f=(1−x)2+100(y−x2)2.
Six methods start at the same point on the selected surface (empty circle is the minimum). Above: paths on contours; below: f−f⋆ on a log scale. Play and select tune η to give each method its best step from a grid: the only honest comparison. Choose the bowl with κ=104 and θ=0: with the best step, AdaGrad, RMSProp and Adam reach f≈0 while SGD remains at 2⋅10−4. Rotate to θ=45∘: what happens to the adaptive advantage? Notice momentum, adapting nothing, does much of the work. Add noise and see which method settles and which orbits the minimum.
Take this from the figure, confirmed below. On the axis-aligned bowl, dividing each coordinate by its scale completely undoes ill-conditioning, while SGD at its best step still needs around κ iterations. Rotate the bowl 45∘ and the advantage disappears: AdaGrad and RMSProp match SGD (2⋅10−4), Adam stays at 2⋅10−5, while momentum, adapting nothing, reaches 6⋅10−6 with or without rotation: scaling coordinates is not rotating, and a method seeing only axes cannot fix a slow direction tilted relative to them. On nonquadratic surfaces like Rosenbrock or Beale, results depend on the problem: no method always wins, so we need to understand each one.
Online convex optimization and regret
AdaGrad analysis arises from a broader framework than descent on a fixed dataset: decisions made one after another, without seeing the future. It underlies adaptive methods and is also the language of bandits and recommendation systems.
Regret measures what is lost by not knowing functions in advance, versus someone who chose the best fixed point in hindsight. No probabilistic assumptions: the adversary can be worst possible, even adapting to the player. An algorithm with sublinear regret RT=o(T) has average loss per round tending to the best fixed point’s. Two examples: prediction with arriving examples (zt,yt) and ft their logistic loss, and SGD training where ft is minibatch t‘s loss.
The first method is natural: take a gradient step on the last loss and project. The whole analysis fits in a one-step lemma, stated with an arbitrary metric because we will reuse it for AdaGrad. For symmetric positive definite H, write ∥z∥H2=z⊤Hz and ΠKH(y)=argminu∈K∥u−y∥H.
Proof
With inner product ⟨a,b⟩H=a⊤Hb, Rd is Euclidean and ΠKH is Euclidean projection onto K in that space, which does not increase distances to points of K. Thus ∥x+−u∥H2≤x−ηH−1g−uH2, and expanding the square,
With H=I this is projected online gradient descent, xt+1=ΠK(xt−ηgt), and the lemma is the inequality used for projected gradient convergence. Summing over t and using convexity, ft(xt)−ft(u)≤gt⊤(xt−u), gives the classical bound. Its proof is the first exercise; the statement is:
Regret grows as T, and average regret RT/T tends to zero as 1/T. This is a worst-case bound and cannot be improved without extra assumptions (with linear losses of random signs any algorithm loses Ω(DGT) in expectation, and this is the same 1/T rate seen in SGD convergence). The crucial condition is knowing D, G and T to set η. AdaGrad aims to avoid exactly that.
The connection to SGD is a two-line result justifying online analysis even when the goal is optimization:
Proof
Since xt does not depend on ξt, E[ft(xt)∣ξ1:t−1]=F(xt) and E[ft(u)]=F(u). Thus E[RT(u)]=∑tE[F(xt)−F(u)], and Jensen’s inequality, by convexity of F, gives F(xˉ)≤T1∑tF(xt).
∎
With online gradient descent this gives E[F(xˉ)]−F⋆≤DG/T, the rate of SGD’s iterate average. Any improvement in online regret improves what training can guarantee.
Before continuing, play with regret. The figure pits online gradient descent (one step for all coordinates, η/t, the version not needing T and also achieving regret O(DGT)) against AdaGrad, not yet defined but whose coordinate step you can guess, on linear losses in [−1,1]20 where each coordinate has its own appearance frequency.
InteractiveRegret live
Cumulative regret Rt against the best fixed decision
GD online
AdaGrad
ni is the number of rounds in which feature i has nonzero gradient: 1788, 671, 354, 228, 168, ... for the five most frequent and 18 for the rarest.
Rounds T
Online GD regret at T=2000181
AdaGrad regret at T=2000134
∑ini (AdaGrad)214.8
d∑ini (GD online)280.2
Ratio of the two0.77
AdaGrad has 26 % less regret: rare features receive large steps and frequent ones small steps, while online GD has one step for all and cannot do both at once.
Twenty parameters in [−1,1]20 receive linear losses ft(x)=gt⊤x. Feature i appears with probability 0.9i−s and, when present, its gradient is ±1 with probability q of being +1. Online GD uses η/t for every coordinate; AdaGrad uses η/ni(t) for coordinate i. With defaults and step scale 1 for both, online GD accumulates regret 181 at T=2000 and AdaGrad 134. Select tune: online GD's best step is ×1.78 and regret falls to 160, still above untuned AdaGrad, which reaches 106 at its best scale (×0.56). Lower s to 0 so features are equally frequent and retune: what happens to the gap? Bottom readouts measure ∑ini against d∑ini, the quantities controlling the bounds, and their ratio.
Two observations prepare the next sections. No single step is good for all coordinates: online GD at its best step loses more than untuned AdaGrad. And AdaGrad’s advantage depends on unequal frequencies, a data property rather than an algorithm property: with s=0 and each at its best step, both accumulate the same regret (291 and 292), because when all ni(t) are similar, η/ni(t) is the same step for every coordinate.
Diagonal preconditioning: changing the metric coordinate by coordinate
Before AdaGrad, understand its change. Let D=diag(δ1,…,δd) with δi>0. Preconditioned gradient descent is xk+1=xk−ηD−1∇f(xk). This is ordinary gradient descent in other coordinates: if z=D1/2x and f~(z)=f(D−1/2z), then ∇f~(z)=D−1/2∇f(x), and a GD step on f~, transformed back, is x←x−ηD−1∇f(x). Thus lesson 7 rates apply using the preconditioned problem’s condition number. For quadratic Hessian A, it is κ(D−1/2AD−1/2) instead of κ(A).
When does a diagonal help? There is an exact two-dimensional answer, explaining the rotated-bowl figure. The two directions of a 2×2 quadratic form angle θ with the coordinate axes.
Proof
The scaling is [1ρρ1] with ρ=A12/A11A22 and ∣A12∣=(L−μ)∣sinθcosθ∣; its eigenvalues are 1±ρ, yielding κθ=(1+ρ)/(1−ρ). At θ=0, A12=0 and ρ=0. At θ=45∘, A11=A22=(μ+L)/2 and ∣A12∣=(L−μ)/2, so ρ=(L−μ)/(L+μ) and κθ=2μ2L=κ. For optimality, scaling diag(s1,s2)Adiag(s1,s2) has determinant s12s22detA and trace A11s12+A22s22. For symmetric positive definite 2×2 matrix with eigenvalues λ1≥λ2, (tr)2/det=(λ1+λ2)2/(λ1λ2)=κ+1/κ+2, increasing for κ≥1: minimizing κ means minimizing that ratio. The ratio (A11s12+A22s22)2/(s12s22detA) is minimal when A11s12=A22s22 (arithmetic–geometric mean inequality, (a+b)2≥4ab), the unit diagonal up to a common factor irrelevant to κ.
∎
With κ=104, scaling gives κθ=1 at θ=0∘, 2501 at 15∘, 7500 at 30∘ and 10000 at 45∘. This is exactly the bowl figure: a diagonal fixes only scale mismatch between axes, not correlation between them. In high dimensions, van der Sluis’s (1969) result says A‘s diagonal is never more than a dimension-order factor from optimal, so diag(A) is reasonable but still cannot touch off-axis structure.
One practical question remains: the method does not know A. It does know gradients, and adaptive methods posit that each coordinate’s gradient scale is an acceptable substitute, learned along the way and useful even for nonquadratic functions. AdaGrad is the first guaranteed realization.
AdaGrad: the self-adjusting step
Apply the one-step lemma with Ht=diag(Gt,1,…,Gt,d), where Gt,i=∑s≤tgs,i2 is the sum of squared gradients of coordinate i through round t. With this Ht the lemma bounds regret by a controllable sum. The resulting update is AdaGrad.
A large or frequent gradient quickly increases Gt,i, damping that coordinate’s step. A coordinate with almost no past gradient keeps a small accumulator, and when it finally receives one, the step is large: with Gt,i=gt,i2 the movement is ηsigno(gt,i), of length η, regardless of gradient scale. This answers the opening concern, as the next theorem proves.
Proof
Let u∈K be arbitrary. By convexity and the one-step lemma with H=Ht,
Since Ht−Ht−1 is diagonal with entries ≥0, each term is ≤D∞2tr(Ht−Ht−1), and the whole is bounded by D∞2tr(HT)=D∞2∑iGT,i.
Second sum.∑t∥gt∥Ht−12=∑i∑tgt,i2/Gt,i. For at≥0 and At=∑s≤tas>0, we have at/At≤2(At−At−1), since At−At−1=(At−At−1)(At+At−1)≤2At(At−At−1). Summing over t (telescoping), ∑tat/At≤2AT. Applied to each coordinate, the second sum is ≤2∑iGT,i.
Combining them, RT(u)≤(2ηD∞2+η)∑iGT,i. Since u was arbitrary, this holds for RT. Minimizing over η (minimum of a/η+bη is 2ab at η=a/b) gives η=D∞/2 and factor 2D∞.
∎
The bound contains what we wanted. If all gradients are bounded by G∞, then ∥g1:T,i∥2≤G∞T and regret is O(D∞G∞dT), the same order as online gradient descent (which has D≤dD∞ and G≤dG∞) up to a constant: in the worst case AdaGrad does not lose, and gains independence from T and G. But for sparse gradients, coordinate i is active only ni rounds and ∥g1:T,i∥2≤G∞ni. Against online gradient descent tuned with knowledge of the future (giving D∑t∥gt∥22≤D∞G∞d∑ini on the cube), the ratio of bounds is, up to factor 2,
d∑ini∑ini≤1(Cauchy-Schwarz).
The ratio is 1 when all ni are equal and can be very small when very unequal. With frequencies pi=1/i2, the inequality of an extreme Zipf law, and d=1000 features, it is 0.18: a bound about five times smaller; with d=104 it is 0.076, about thirteen times. These are exactly the regret figure’s readouts. This is why the rule just seen trained word vectors with rare features (GloVe, Pennington et al., 2014, used AdaGrad) and linear classifiers for advertising or text with millions of features.
InteractiveRare and frequent features
SGD
AdaGrad
Rows: the 24 features from most frequent (top) to rarest (bottom). Columns: time, from 0 to 4000 examples. Blue shows the fraction of true weight learned; red indicates the wrong sign.
Fraction learned per feature at t=4000 (feature 1 is most frequent)
SGD
AdaGrad
frequency pᵢ
Mean logistic loss over the last 200 examples
SGD
AdaGrad
true weights
t = 4000
Loss over the last 1000 examples, SGD0.563
Same, AdaGrad0.538
Same, with true weights0.528
Rare features learned, SGD64 %
Rare features learned, AdaGrad92 %
At t=4000, AdaGrad has learned 92 % of the weight of the 12 rare features and SGD 64 %. A feature appearing once in a hundred examples accumulates little gradient, so AdaGrad gives it a larger step.
Logistic regression with 24 binary features of frequency pi=0.9i−s and larger true weights for rare features. SGD and AdaGrad traverse the same stream of 4000 examples, each with its best step. Each heatmap shows, per feature (rows, frequent to rare) and over time (columns), the fraction of its true weight learned. With s=1.5, after 4000 examples SGD has learned 64% of the 12 rare weights and AdaGrad 92%; with s=2, 19% versus 69%. Play and watch bottom rows. Mistune SGD's step: can it catch AdaGrad on rare features without destabilizing frequent ones?
There is a cost in the same mechanism: Gt,ionly grows. Step η/Gt,i can only fall, and if gradients do not vanish (as with SGD noise or a nonconvex loss explored for a long time), it decays as 1/t until nearly extinguished. For convex online optimization that is desirable, guaranteeing convergence. In long training it is not.
RMSProp: forgetting to avoid switching off
Imagine a constant-size gradient g on one coordinate. AdaGrad has Gt=tg2 and step ηg/tg2=η/t: after 104 steps one hundredth of the initial step. Sensible for a static convex problem. In a network, where the landscape changes as the model moves and gradient magnitudes decrease or increase in phases, what happened ten thousand iterations ago should not govern the current step. The remedy is forgetting: instead of summing all squares, use an exponential average weighting recent ones more.
This is AdaGrad with one change: sum Gt,i is replaced by an exponential averagevt,i of squares. Unrolling makes it clear: vt,i=(1−β2)∑s≤tβ2t−sgs,i2, a weighted average with geometric weights and effective window 1/(1−β2) iterations: 100 steps with β2=0.99, 1000 with 0.999. With constant gradient g, vt=(1−β2t)g2→g2 and the step tends to η without switching off (compare η/t). For stationary gradients, vt,i estimates E[gi2], and RMSProp’s step is ηgi/E[gi2]: a normalized gradient with magnitude around η.
A simple bound measures what one step can do: since vt,i≥(1−β2)gt,i2, we have ∣gt,i∣/vt,i≤1/1−β2, and with negligible ε, each coordinate moves at most η/1−β2 per iteration: 10η with β2=0.99 and 31.6η with 0.999. The first step reaches this limit, when v contains only one gradient, explaining why RMSProp’s η is usually small (10−3 or less).
Forgetting costs AdaGrad’s guarantee: no comparably clean regret theorem exists for RMSProp, and small convex problems where it fails to converge are known (see next lesson with Adam). In return, the step stays alive and adapts to the present. The next figure shows each coordinate’s behavior when two parameters have gradient scales 100 and 1.
InteractiveSteps by coordinate
∣gi∣ gradient
1001.0
vi accumulator
1001.0
η/(vi+ε) multiplier
1.0e−30.100
∣Δxi∣ actual step
0.1000.100
Log-scale bars, each panel with a fixed range throughout the run. Orange: coordinate 1 (large scale). Teal: coordinate 2.
Error ∣xi−1∣ for each coordinate, on a log scale
coord. 1 (Adam)
coord. 2 (Adam)
coord. 2 (SGD, step 1/a₁)
Method
t = 1
Multiplier, coord. 11.0e−3
Multiplier, coord. 20.100
Multiplier ratio100
Scale ratio a1/a2100
Error ∣xi−1∣ at t0.900 and 0.900
The multipliers adjust to each gradient’s scale: the large-gradient coordinate receives a step about 100 times smaller, and both advance together.
Quadratic f=21(a1(x1−1)2+a2(x2−1)2) with a1/a2=100. Each log-scale panel shows, for both coordinates, gradient, square root of accumulator, multiplier η/(v+ε) and actual step. With Adam, η=0.1 and β2=0.999, multipliers differ by 100, exactly the inverse gradient ratio, and both coordinates fall together: at t=150 error is 1.3⋅10−4 in both, while SGD with step 1/a1, solving the fast coordinate at once, leaves the slow one at 0.22. Switch to AdaGrad and watch the multiplier only decrease. Increase ε to 10: the slow coordinate multiplier stays at η/ε=0.01, SGD's step, and its error remains 0.22 again. Add noise and watch v when the gradient stops vanishing.
Three lessons from the figure. Adaptation works: each coordinate’s multiplier calibrates itself to its gradient scale. It balances two forces: small β2 closely follows the gradient and gets noisy, while large β2 smooths more but reacts slowly. And ε sets a floor on the denominator: while v greatly exceeds ε the multiplier is η/v, and when v falls below it the multiplier stays at η/ε and the method behaves like SGD at that step. This regime change causes one common mistake below.
Adam: first and second moments, and bias correction
RMSProp normalizes the gradient, but it normalizes the current iteration’s gradient with all its noise. Momentum averages past gradients and filters noise. Adam, adaptive moment estimation (Kingma and Ba, 2014), combines both: an exponential gradient average mt estimating its first moment, and a squared-gradient average vt estimating the second, used together for the step. There is also a technical detail without which the method would fail initially.
The first two equations are exponential averages: m with window about 1/(1−β1)=10 steps and v with window 1000. The third row is bias correction, distinguishing Adam from “RMSProp with momentum”. Why? Since m0=0, the average carries the initial zero. At t=1, m1=(1−β1)g1=0.1g1, only one tenth of what it should estimate, and v1=0.001g12, one thousandth. Dividing by 1−βt exactly compensates for this carryover, as the next theorem proves.
Proof
Unrolling, mt=(1−β1)∑s=1tβ1t−sgs. By linearity, E[mt]=(1−β1)μ∑s=1tβ1t−s=(1−β1)μ1−β11−β1t=(1−β1t)μ, and dividing by 1−β1t gives μ. Identically for v with β2 and ν. If E[gs]=μs, subtract μt to get 1−β1t1−β1∑sβ1t−s(μs−μt), vanishing when μs≈μt within the window.
∎
The practical consequence is key and less obvious than it seems. Factor 1/(1−βt) is huge initially and 1 at the end: with β2=0.999 it is 1000 at t=1, about 100.5 at t=10, 1.58 at t=1000 and 1.05 at t=3000. Without v correction the denominator starts 1000 times too small and steps become absurdly large; without m correction the numerator starts too small. The corrections do not cancel because β1=β2: without either, the step is multiplied by (1−β1t)/1−β2t, equal to 0.1/0.001≈3.16 at t=1 and 6.5 at t=10: several times too large. Easier to see than reason through:
InteractiveWhy correct bias
First moment mt (gradient average, window ≈1/(1−β1))
uncorrected m_t
corrected m̂_t
E[m_t] = (1 − β₁ᵗ) μ
μ
Second moment vt (average of g2, window ≈1/(1−β2))
uncorrected v_t
corrected v̂_t
E[v_t] = (1 − β₂ᵗ) E[g²]
E[g²]
Adam step size, ∣Δt∣/η=∣m∣/v with ε=0
step with selected correction
steady-state value |μ|/√E[g²]
Typical β2
Horizon (steps)
Correction applied to step
First uncorrected step /η3.16
Step at t=10 with selected correction /η5.50
Steady-state step /η0.89
Time scale of v: 1/(1−β2)1000
Without correction, the first step is independent of the gradient: ∣Δ1∣/η=(1−β1)/1−β2=3.16. With β2 close to 1, v starts much smaller than E[g2] and the step spikes.
A stationary stream gt∼N(μ,σ2) with μ=1 and σ=0.5 feeds both averages. Top and middle: mt and vt uncorrected and corrected against exact expected values (dashed). Bottom: step size ∣m∣/v in η units depending on correction. Uncorrected with β2=0.999, first step is 3.16η ((1−β1)/1−β2 regardless of gradient); using expected values the step rises to 5.8η at t=10 and remains 1.76η at t=300 (select horizon 300), while the correct stationary step is 0.89η. Change to β2=0.99 and compare. Try correcting only m or only v and explain why the resulting step is better or worse.
The step panel contains a third result deeper than bias. At stationarity, Adam’s step in one coordinate is ηE[g]/E[g2], equal to η if the gradient is deterministic and reduced to ημ/μ2+σ2 with noise standard deviation σ (in the figure, 0.894η). Adam is thus a signal-to-noise method: it advances at speed η in coordinates with consistent direction and slows noise-dominated ones. Kingma and Ba use this to justify that the effective step is approximately bounded by η (§2.1): η acts as a trust radius around the current point in parameter units.
One implementation detail: the paper writes an efficient version with ηt=η1−β2t/(1−β1t) and ε^ added to uncorrected vt: since 1−β2t/(vt+ε^)=1/(v^t+ε^/1−β2t), this equals the equation above with ε=ε^/1−β2t, larger than ε^ initially (about 32 times at t=1 with β2=0.999). PyTorch uses the form above, adding ε to the corrected v^t root, which we implement.
What adaptive methods preserve and break
All three share an algebraic property explaining why Adam’s learning rate looks so different from SGD’s. When ε is negligible, the step is independent of gradient scale.
Proof
Induction on t. With gradient Sgt, sums Gt,i and averages vt,i are multiplied by si2 and mt,i by si (linear in g and g2, with bias correction depending only on t). Then Gt,i, vt,i and v^t,i are multiplied by si, as are gt,i or m^t,i by si, so the quotient multiplying η is unchanged and trajectories agree at t+1. In SGD, step −ηSgt does change.
∎
The key case is S=cI: multiplying loss by a constant c>0 does not change Adam’s trajectory, and multiplies SGD’s step by c (the “Multiply loss by 1000” quiz and first code cell check this: with c=1000, Adam’s trajectory changes by 10−12 and SGD’s explodes). This is a real virtue: no need to retune η when loss normalization changes, and in a network with very different layer gradients each parameter has its own scale. But mind what it does not say. With ε=0 invariance breaks when v is not large relative to ε. A nondiagonal variable change (rotation) is not Sg and changes the trajectory, as in the rotated bowl. The step is measured in parameter units, so rescaling parameters (x=cz) changes the path in x: η is a length in parameter space, and if two parameters have very different scales the same η is too large for one and too small for the other.
Reading hyperparameters
Each Adam hyperparameter has a concrete interpretation for choosing it and diagnosing troubled training. Keep a small reference table.
Hyperparameter
Typical value
What it controls
Increase it
Decrease it
η
10−3 (small networks); large transformers around 10−4 (6⋅10−5 to 6⋅10−4 in GPT-3, smaller for larger models)
Coordinate step length in parameter units
Larger steps and divergence risk
Slow progress
β1
0.9
m window: 1/(1−β1)≈10 steps
More gradient smoothing, more inertia
Closer to RMSProp
β2
0.999; often 0.95 to 0.98 in language models
v window: 1/(1−β2)≈1000 steps
Very stable scale, slow adaptation
Agile but noisy scale; step may be large after a small gradient
ε
10−8
Denominator floor
More like SGD with momentum, step η/ε
More adaptation, risk of huge steps if v→0
Why these numbers? β2 is much larger than β1 because gradient scale is better measured with a long window, while direction should be followed quickly. With large language models, where gradients have occasional spikes, β2 of 0.999 may remember a spike for a thousand iterations and unnecessarily damp the step or react slowly to a regime change; hence 0.95 is common (for example GPT-3 used β1=0.9, β2=0.95, ε=10−8 according to Brown et al., 2020). ε is rarely changed until something fails; then its effect matters: the third code cell shows that with gradient scale 10−8 actual step is half expected.
Implementation from scratch
First, all three methods share an interface: a stateful object with step(x, g) returning the new point. State consists of accumulators, and Adam’s bias correction uses counter t. The cell compares them on the coordinate-step figure’s problem, checks invariance to loss scale, and reproduces the Rosenbrock comparison with each best step from a grid.
[ ]AdaGrad, RMSProp and Adam from scratchBrowser
import numpy as np
class SGD:
def __init__(self, lr):
self.lr = lr
def step(self, x, g):
return x - self.lr * g
class AdaGrad:
def __init__(self, lr, eps=1e-8):
self.lr, self.eps, self.G = lr, eps, 0.0
def step(self, x, g):
self.G = self.G + g * g # suma de cuadrados: no olvida nada
return x - self.lr * g / (np.sqrt(self.G) + self.eps)
class RMSProp:
def __init__(self, lr, beta2=0.99, eps=1e-8):
self.lr, self.beta2, self.eps, self.v = lr, beta2, eps, 0.0
def step(self, x, g):
self.v = self.beta2 * self.v + (1 - self.beta2) * g * g # media exponencial
return x - self.lr * g / (np.sqrt(self.v) + self.eps)
class Adam:
def __init__(self, lr, beta1=0.9, beta2=0.999, eps=1e-8):
self.lr, self.beta1, self.beta2, self.eps = lr, beta1, beta2, eps
self.m, self.v, self.t = 0.0, 0.0, 0
def step(self, x, g):
self.t += 1
self.m = self.beta1 * self.m + (1 - self.beta1) * g
self.v = self.beta2 * self.v + (1 - self.beta2) * g * g
m_hat = self.m / (1 - self.beta1 ** self.t) # corrección de sesgo
v_hat = self.v / (1 - self.beta2 ** self.t)
return x - self.lr * m_hat / (np.sqrt(v_hat) + self.eps)
def run(opt, grad, x0, steps):
x = np.array(x0, dtype=float)
path = [x]
for _ in range(steps):
x = opt.step(x, grad(x))
path.append(x)
return np.array(path)
# Dos parámetros con curvaturas 100 y 1; el mínimo está en (3, 3)
a = np.array([100.0, 1.0])
grad = lambda x: a * (x - 3)
def hit(path, tol=1e-3):
err = np.abs(path - 3).max(axis=1)
idx = np.flatnonzero(err < tol)
return int(idx[0]) if len(idx) else None
methods = {
"SGD (1/100)": lambda: SGD(1 / 100),
"AdaGrad": lambda: AdaGrad(0.9),
"RMSProp": lambda: RMSProp(0.1),
"Adam": lambda: Adam(0.1),
}
print("iteraciones hasta |x - 3| < 1e-3 en las dos coordenadas")
for name, make in methods.items():
print(f" {name:12s}", hit(run(make(), grad, [0, 0], 3000)))
# Invariancia frente a la escala de la pérdida: multiplicar f por 1000 no cambia a Adam
scaled = lambda x: 1000 * grad(x)
d_adam = np.abs(run(Adam(0.1, eps=1e-12), grad, [0, 0], 200) - run(Adam(0.1, eps=1e-12), scaled, [0, 0], 200)).max()
d_sgd = np.abs(run(SGD(1 / 100), grad, [0, 0], 20) - run(SGD(1 / 100), scaled, [0, 0], 20)).max()
print("pérdida x1000, máxima diferencia de trayectoria: Adam", f"{d_adam:.1e}", " SGD", f"{d_sgd:.1e}")
# Rosenbrock: mejor f tras 600 pasos con el mejor paso de una rejilla
def f_r(p): return (1 - p[0]) ** 2 + 100 * (p[1] - p[0] ** 2) ** 2
def g_r(p): return np.array([-2 * (1 - p[0]) - 400 * p[0] * (p[1] - p[0] ** 2), 200 * (p[1] - p[0] ** 2)])
etas = 10 ** (np.arange(-12, 5) / 4)
print("Rosenbrock, 600 pasos desde (-1.2, 1)")
for name, make in {"SGD": SGD, "AdaGrad": AdaGrad, "RMSProp": RMSProp, "Adam": Adam}.items():
best = (np.inf, None)
for e in etas:
with np.errstate(all="ignore"):
path = run(make(e), g_r, [-1.2, 1.0], 600)
if not np.all(np.isfinite(path)) or np.abs(path).max() > 1e4:
continue
fin = f_r(path[-1])
if fin < best[0]:
best = (fin, e)
print(f" {name:8s} mejor eta = {best[1]:.4f} f(x_600) = {best[0]:.2e}")
Paths confirm theory. With curvatures 100 and 1, SGD at step 1/L=1/100 needs 797 iterations because the curvature-1 coordinate contracts by 0.99 each step (even optimal step 2/(L+μ)=2/101 takes at least 401). AdaGrad and RMSProp take 35 and 27 iterations, Adam 115 (its inertia β1=0.9 overshoots and oscillates slightly before settling). Scale invariance holds to arithmetic limits: multiplying loss by 1000 changes Adam’s path by 10−12 and sends SGD to 1060, i.e. divergence. On Rosenbrock, with each best step, Adam reaches 9⋅10−7, AdaGrad 5⋅10−4, while SGD and RMSProp remain at 4⋅10−2 and 3.5⋅10−2 (in the figure, momentum at its best step beats all): a curved surface is not corrected by scaling alone, but inertia and a normalized step progress much better down the valley.
Second cell: sparse-feature logistic regression, the figure’s model with a different data sample. Compare SGD with AdaGrad using the class above, each at its best grid step, in one pass through data (online loss, measured before each example’s update).
[ ]AdaGrad with sparse featuresBrowser
rng = np.random.default_rng(3)
n, d = 4000, 24
p = 0.9 * np.arange(1, d + 1) ** -1.5
w_star = rng.choice([-1.0, 1.0], d) * (0.8 + 3.2 * (np.arange(d) / (d - 1)) ** 1.3)
X = (rng.random((n, d)) < p).astype(float)
X = X[X.sum(axis=1) > 0]
n = len(X)
y = np.where(rng.random(n) < 1 / (1 + np.exp(-X @ w_star)), 1.0, -1.0)
def stream_loss(opt):
"""Una sola pasada: pérdida de cada ejemplo antes de actualizar con él (pérdida online)."""
w, tot = np.zeros(d), 0.0
for xi, yi in zip(X, y):
z = xi @ w
tot += np.logaddexp(0, -yi * z)
g = -yi / (1 + np.exp(yi * z)) * xi # gradiente de log(1 + e^{-y z})
w = opt.step(w, g)
return tot / n, w
oracle = np.mean(np.logaddexp(0, -y * (X @ w_star)))
print(f"{n} ejemplos, {d} rasgos; pérdida con los pesos verdaderos: {oracle:.3f}")
rare = slice(d // 2, d)
for name, make in [("SGD", SGD), ("AdaGrad", AdaGrad)]:
best = min(((stream_loss(make(lr))[0], lr) for lr in 10 ** np.linspace(-1.2, 0.8, 9)))
loss, w = stream_loss(make(best[1]))
learned = np.clip(w * np.sign(w_star) / np.abs(w_star), 0, 1.5)
print(f"{name:8s} mejor lr = {best[1]:.2f} pérdida online = {loss:.3f} "
f"fracción aprendida de los 12 raros = {learned[rare].mean():.2f}, de los 12 frecuentes = {learned[:12].mean():.2f}")
With each best step, online loss falls from 0.601 (SGD, η=0.20) to 0.577 (AdaGrad, η=0.63), versus 0.559 with true weights. The difference lies in rare features: SGD recovers 59% of their weight and AdaGrad 81%, with nearly equal results on frequent features (83% and 88%). SGD cannot step more on rare features without destabilizing frequent ones; AdaGrad can because its step is inversely proportional to each feature’s accumulated history. This moderately improves loss and greatly changes what the model knows about important features.
The third cell checks bias correction by measuring E[m^] on a stationary stream (as in the theorem) and ε‘s effect on Adam’s first step.
[ ]Adam bias and the role of εBrowser
# Flujo estacionario g_t ~ N(mu, sigma^2), 20000 repeticiones independientes
rng = np.random.default_rng(0)
mu, sigma, T, R = 1.0, 0.5, 50, 20000
g = mu + sigma * rng.normal(size=(R, T))
beta1, beta2 = 0.9, 0.999
m = np.zeros(R); v = np.zeros(R)
print(" t E[m_t] E[m_t^] E[v_t] E[v_t^] (verdad: E[g] = 1, E[g^2] = 1.25)")
for t in range(1, T + 1):
m = beta1 * m + (1 - beta1) * g[:, t - 1]
v = beta2 * v + (1 - beta2) * g[:, t - 1] ** 2
if t in (1, 2, 5, 10, 50):
c1, c2 = 1 - beta1 ** t, 1 - beta2 ** t
print(f"{t:4d} {m.mean():7.3f} {(m / c1).mean():7.3f} {v.mean():8.4f} {(v / c2).mean():7.3f}")
# Primer paso sin corregir: (1 - beta1) / sqrt(1 - beta2), sea cual sea el gradiente
print("primer paso sin corregir / lr:", round((1 - beta1) / np.sqrt(1 - beta2), 3), "con beta2 = 0.99:", round((1 - beta1) / np.sqrt(1 - 0.99), 3))
# El papel de epsilon: primer paso de Adam (corregido) = lr * |g| / (|g| + eps)
print("\n escala del gradiente paso/lr con eps=1e-8 con eps=1e-3")
for scale in (1.0, 1e-3, 1e-6, 1e-8, 1e-10):
row = [scale / (scale + eps) for eps in (1e-8, 1e-3)]
print(f"{scale:20.0e} {row[0]:20.4f} {row[1]:12.4f}")
The first table expresses the theorem in numbers. E[mt] is 0.100 at t=1, 0.652 at t=10 and 0.996 at t=50, versus exact (1−0.9t)⋅1 values 0.100, 0.651 and 0.995; E[m^t] is 1 in every row (apart from Monte Carlo error of a few thousandths), likewise v^ with 1.25=μ2+σ2. The second table shows ε‘s effect: with ε=10−8 the step is η while the gradient exceeds 10−6, falls to η/2 when the gradient equals ε, and vanishes below. With ε=10−3 half the step is already lost for gradients 10−3. The preceding figure’s regime change, now measured.
The professional version: torch.optim.Adam
In a real network the loop is not written by hand: use a torch.optim.Optimizer over a module’s parameters(), with the gradient autograd leaves in p.grad in the usual training loop. The next cell writes Adam as an Optimizer subclass and compares it to torch.optim.Adam on an MLP, in float64 on CPU. It also measures state memory: two tensors per parameter.
[ ]Custom Adam versus torch.optim.Adam and state memoryLocal GPU
import torch
torch.manual_seed(0)
torch.set_default_dtype(torch.float64) # float64: la comparación es de fórmulas, no de redondeo
class MiAdam(torch.optim.Optimizer):
"""Adam con corrección de sesgo, escrito como una subclase de Optimizer."""
def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8):
super().__init__(params, dict(lr=lr, betas=betas, eps=eps))
@torch.no_grad()
def step(self):
for grupo in self.param_groups:
b1, b2 = grupo["betas"]
for p in grupo["params"]:
if p.grad is None:
continue
st = self.state[p]
if not st: # estado perezoso: se crea en el primer paso
st["t"] = 0
st["m"] = torch.zeros_like(p)
st["v"] = torch.zeros_like(p)
st["t"] += 1
st["m"].mul_(b1).add_(p.grad, alpha=1 - b1) # m <- b1 m + (1-b1) g
st["v"].mul_(b2).addcmul_(p.grad, p.grad, value=1 - b2) # v <- b2 v + (1-b2) g^2
c1, c2 = 1 - b1 ** st["t"], 1 - b2 ** st["t"]
denom = (st["v"] / c2).sqrt().add_(grupo["eps"])
p.addcdiv_(st["m"], denom, value=-grupo["lr"] / c1)
def mlp():
torch.manual_seed(1)
return torch.nn.Sequential(torch.nn.Linear(8, 16), torch.nn.Tanh(), torch.nn.Linear(16, 16), torch.nn.Tanh(), torch.nn.Linear(16, 1))
X = torch.randn(200, 8)
y = torch.sin(X[:, :1] * 2) + 0.1 * torch.randn(200, 1)
def entrenar(opt_cls, pasos=100, **kw):
red = mlp()
opt = opt_cls(red.parameters(), **kw)
for _ in range(pasos):
opt.zero_grad()
torch.nn.functional.mse_loss(red(X), y).backward()
opt.step()
return red, opt
r1, o1 = entrenar(MiAdam, lr=1e-2)
r2, o2 = entrenar(torch.optim.Adam, lr=1e-2)
dif = max((p1 - p2).abs().max().item() for p1, p2 in zip(r1.parameters(), r2.parameters()))
print(f"máxima diferencia de parámetros tras 100 pasos: {dif:.2e}")
def bytes_estado(opt):
return sum(t.numel() * t.element_size() for s in opt.state.values() for t in s.values() if torch.is_tensor(t))
n_par = sum(p.numel() for p in r2.parameters())
b_par = sum(p.numel() * p.element_size() for p in r2.parameters())
_, o3 = entrenar(torch.optim.SGD, lr=1e-2, momentum=0.9)
print(f"{n_par} parámetros ({b_par} B en float64)")
print(f"estado de Adam: {bytes_estado(o2)} B = {bytes_estado(o2) / b_par:.3f} x los parámetros; SGD con momentum: {bytes_estado(o3) / b_par:.3f} x")
print("tensores de estado por parámetro en torch.optim.Adam:", sorted(next(iter(o2.state.values())).keys()))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
The implementations differ by 3⋅10−15 after 100 steps: same formula, rounding differences. Adam state occupies 2.014 times parameter memory (the two tensors exp_avg and exp_avg_sq, plus a step counter per parameter tensor), versus 1.000 for SGD momentum. In float32 including gradients, each parameter costs 4+4+8=16 bytes with Adam and 8 with SGD without momentum.
PyTorch AdaGrad defaults to ε=10−10. SparseAdam updates only rows with gradients.
RMSProp
torch.optim.RMSprop(params, lr, alpha=0.99)
alpha is β2. Other frameworks use different defaults (e.g. 0.9 in Keras) and place ε differently.
Another update rule
Subclass torch.optim.Optimizer
Like MiAdam: state lives in self.state[p].
Inspect state memory
Sum numel() * element_size() from opt.state
Adam: two tensors per parameter, 8 bytes per parameter in float32.
Common mistakes
Exercises
ProofThe DG√T bound for online gradient descent
Prove: Let K⊂Rd be convex and closed with diameter ≤D, and let f1,…,fT be convex with subgradients gt∈∂ft(xt) of norm ≤G. With x1∈K and xt+1=ΠK(xt−ηgt), prove RT≤2ηD2+2ηG2T and deduce that with η=D/(GT) regret is at most DGT.
0
Fix arbitrary u∈K and call gt∈∂ft(xt) the subgradient observed in round t.
Step 1 of 4. Start with one round. What inequality holds for ∥xt+1−u∥2?
ProofCorrection 1/(1 − β₁ᵗ) removes bias
Prove: Let mt=β1mt−1+(1−β1)gt with m0=0 and E[gs]=μ for every s. Prove E[mt]=(1−β1t)μ and hence m^t=mt/(1−β1t) satisfies E[m^t]=μ.
0
Work with one coordinate. Expectation is linear, so independence of the gs is unnecessary.
Step 1 of 3. What results from unrolling the recurrence?
NumericCorrection factor for v at t = 10
With β2=0.999, what is correction factor 1/(1−β2t) by which Adam divides vt at step t=10?
NumericAdaGrad's gain with Zipf-like features
There are d=1000 features and feature i is active in fraction pi=1/i2 of rounds, so ni=piT. AdaGrad's bound is proportional to ∑ini and tuned online gradient descent's to d∑ini. What is the ratio ∑ini/d∑ini?
NumericCondition number reduction by a diagonal
A quadratic has Hessian A=[100991], condition number κ(A)≈535. Precondition with its diagonal D=diag(100,1). What is κ(D−1/2AD−1/2)?
NumericAdam state memory
You train a 7⋅109-parameter model with Adam, storing m and v in float32 (4 bytes per value). How many GB (109 bytes) does optimizer state alone occupy (excluding parameters, gradients and activations)?
QuizMultiply loss by 1000
You train with Adam (negligible ε) and SGD, each with its own η. You multiply loss by 1000 without changing anything else. What happens to trajectories?
QuizAdaGrad's multiplier with constant gradient
A coordinate receives constant gradient g=0 every round. With η=0.5 and negligible ε, how do AdaGrad and RMSProp with β2=0.99 steps evolve?
QuizWhen diagonal preconditioning does not help
On a quadratic with κ=104 you compare SGD at its best step with AdaGrad. When do you expect AdaGrad to add almost nothing?
CodeA vectorized Adam step
Implement adam_step(params, grads, state, lr=1e-3, betas=(0.9, 0.999), eps=1e-8), returning new parameters (an array of the same shape as params without modifying the original) and updating state in place. state is an initially empty dictionary that must hold 't' (step counter), 'm' and 'v'. Use bias correction m^=m/(1−β1t), v^=v/(1−β2t) and update x−ηm^/(v^+ε). It must work with arrays of any shape.
import numpy as np
def adam_step(params, grads, state, lr=1e-3, betas=(0.9, 0.999), eps=1e-8):
"""Un paso de Adam: devuelve los nuevos parámetros y actualiza state ('t', 'm', 'v')."""
b1, b2 = betas
if not state:
state["t"] = 0
state["m"] = np.zeros_like(params, dtype=float)
state["v"] = np.zeros_like(params, dtype=float)
# tu código: actualiza t, m y v, corrige el sesgo y calcula el nuevo punto
return params - lr * grads
Shift+Enter to run
Summary
Key idea
Adaptive methods divide each coordinate’s step by its gradient-history scale: AdaGrad sums squares and guarantees O(T) regret adapting to sparsity, RMSProp averages with forgetting to keep the step alive, and Adam adds a gradient average and bias correction. All are diagonal preconditioners: they fix scale mismatch between axes, not a tilted slow direction.
Online convex optimization measures regret against the best fixed point. Projected online gradient descent with η=D/(GT) satisfies RT≤DGT, and iterate averaging leads to SGD rate O(1/T).
AdaGrad updates xt+1,i=xt,i−ηgt,i/Gt,i with Gt,i=∑s≤tgs,i2. Its regret is ≤(D∞2/(2η)+η)∑i∥g1:T,i∥2, without knowing T or G, much smaller than online GD for sparse gradients (rare features receive large steps). Its drawback is that G only grows and the step dies as 1/t.
RMSProp replaces the sum with exponential average vt=β2vt−1+(1−β2)gt2 (window 1/(1−β2)), keeping the step alive, with size ≤η/1−β2.
Adam adds gradient average mt and divides by 1−βt to remove zero-start bias: E[m^t]=E[g] under stationarity. Without correction, with β2=0.999 the first step is 3.16η instead of η. The stationary step is ηE[g]/E[g2]: a signal-to-noise ratio.
They are invariant to gradient scale (f→cf does not change trajectory with ε=0), but not rotations: with θ=45∘ diagonal scaling leaves κθ=κ. η remains the main hyperparameter, ε marks the transition to SGD with momentum, and state costs two tensors per parameter.