Module contents
Lesson 20 of 27Core 120 min

Adaptive methods: AdaGrad, RMSProp and Adam

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.

Before you start

Motivation: one learning rate for dissimilar parameters

Everything so far, from gradient descent on quadratics to stochastic momentum, shares a decision: one step η\eta 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 η\eta 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 η\eta 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⋆f - f^\star on a logarithmic scale
  • SGD
  • Momentum
  • AdaGrad
  • RMSProp
  • Adam
Surface
0.0020
0.0500
0.900
0.9900
0.00
k = 600
SGD (η=0.0020\eta = 0.0020): ff at kk0.239
Momentum (η=0.0020\eta = 0.0020): ff at kk1.8e−5
AdaGrad (η=0.0500\eta = 0.0500): ff at kk3.64
RMSProp (η=0.0500\eta = 0.0500): ff at kk0.257
Adam (η=0.0500\eta = 0.0500): ff at kk1.1e−4
Rosenbrock curved valley, f=(1−x)2+100(y−x2)2f = (1-x)^2 + 100(y - x^2)^2.
Six methods start at the same point on the selected surface (empty circle is the minimum). Above: paths on contours; below: f−f⋆f - f^\star 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\kappa = 10^4 and θ=0\theta = 0: with the best step, AdaGrad, RMSProp and Adam reach f≈0f \approx 0 while SGD remains at 2⋅10−42 \cdot 10^{-4}. Rotate to θ=45∘\theta = 45^\circ: 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 κ\kappa iterations. Rotate the bowl 45∘45^\circ and the advantage disappears: AdaGrad and RMSProp match SGD (2⋅10−42 \cdot 10^{-4}), Adam stays at 2⋅10−52 \cdot 10^{-5}, while momentum, adapting nothing, reaches 6⋅10−66 \cdot 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)R_T = o(T) has average loss per round tending to the best fixed point’s. Two examples: prediction with arriving examples (zt,yt)(\vb{z}_t, y_t) and ftf_t their logistic loss, and SGD training where ftf_t is minibatch tt‘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\mat{H}, write ∥z∥H2=z⊤Hz\norm{\vb{z}}_{\mat{H}}^2 = \vb{z}\T\mat{H}\vb{z} and ΠKH(y)=arg min⁡u∈K∥u−y∥H\Pi_{\mathcal{K}}^{\mat{H}}(\vb{y}) = \argmin_{\vb{u} \in \mathcal{K}}\norm{\vb{u} - \vb{y}}_{\mat{H}}.

Proof

With inner product ⟨a,b⟩H=a⊤Hb\inner{\vb{a}}{\vb{b}}_{\mat{H}} = \vb{a}\T\mat{H}\vb{b}, Rd\R^d is Euclidean and ΠKH\Pi_{\mathcal{K}}^{\mat{H}} is Euclidean projection onto K\mathcal{K} in that space, which does not increase distances to points of K\mathcal{K}. Thus ∥x+−u∥H2≤∥x−ηH−1g−u∥H2\norm{\vb{x}^+ - \vb{u}}_{\mat{H}}^2 \le \norm{\vb{x} - \eta\mat{H}\inv\vb{g} - \vb{u}}_{\mat{H}}^2, and expanding the square,

∥x−ηH−1g−u∥H2=∥x−u∥H2−2η (H−1g)⊤H(x−u)+η2 g⊤H−1HH−1g=∥x−u∥H2−2η g⊤(x−u)+η2∥g∥H−12.\norm{\vb{x} - \eta\mat{H}\inv\vb{g} - \vb{u}}_{\mat{H}}^2 = \norm{\vb{x} - \vb{u}}_{\mat{H}}^2 - 2\eta\,(\mat{H}\inv\vb{g})\T\mat{H}(\vb{x} - \vb{u}) + \eta^2\,\vb{g}\T\mat{H}\inv\mat{H}\mat{H}\inv\vb{g} = \norm{\vb{x} - \vb{u}}_{\mat{H}}^2 - 2\eta\,\vb{g}\T(\vb{x} - \vb{u}) + \eta^2\norm{\vb{g}}_{\mat{H}\inv}^2.

Solving for g⊤(x−u)\vb{g}\T(\vb{x} - \vb{u}) gives the result.

∎

With H=I\mat{H} = \mat{I} this is projected online gradient descent, xt+1=ΠK(xt−ηgt)\vb{x}_{t+1} = \Pi_{\mathcal{K}}(\vb{x}_t - \eta\vb{g}_t), and the lemma is the inequality used for projected gradient convergence. Summing over tt and using convexity, ft(xt)−ft(u)≤gt⊤(xt−u)f_t(\vb{x}_t) - f_t(\vb{u}) \le \vb{g}_t\T(\vb{x}_t - \vb{u}), gives the classical bound. Its proof is the first exercise; the statement is:

Regret grows as T\sqrt{T}, and average regret RT/TR_T/T tends to zero as 1/T1/\sqrt{T}. This is a worst-case bound and cannot be improved without extra assumptions (with linear losses of random signs any algorithm loses Ω(DGT)\Omega(DG\sqrt{T}) in expectation, and this is the same 1/T1/\sqrt{T} rate seen in SGD convergence). The crucial condition is knowing DD, GG and TT to set η\eta. 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\vb{x}_t does not depend on ξt\xi_t, E[ft(xt)∣ξ1:t−1]=F(xt)\E[f_t(\vb{x}_t) \mid \xi_{1:t-1}] = F(\vb{x}_t) and E[ft(u)]=F(u)\E[f_t(\vb{u})] = F(\vb{u}). Thus E[RT(u)]=∑tE[F(xt)−F(u)]\E[R_T(\vb{u})] = \sum_t \E[F(\vb{x}_t) - F(\vb{u})], and Jensen’s inequality, by convexity of FF, gives F(xˉ)≤1T∑tF(xt)F(\bar{\vb{x}}) \le \frac1T\sum_t F(\vb{x}_t).

∎

With online gradient descent this gives E[F(xˉ)]−F⋆≤DG/T\E[F(\bar{\vb{x}})] - F^\star \le DG/\sqrt{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\eta/\sqrt{t}, the version not needing TT and also achieving regret O(DGT)\bigO(DG\sqrt{T})) against AdaGrad, not yet defined but whose coordinate step you can guess, on linear losses in [−1,1]20[-1, 1]^{20} where each coordinate has its own appearance frequency.

InteractiveRegret live
Cumulative regret RtR_t against the best fixed decision
  • GD online
  • AdaGrad
nin_i is the number of rounds in which feature ii has nonzero gradient: 1788, 671, 354, 228, 168, ... for the five most frequent and 18 for the rarest.
Rounds TT
1.50
0.70
×1.00
×1.00
Online GD regret at T=2000T = 2000181
AdaGrad regret at T=2000T = 2000134
∑ini\sum_i\sqrt{n_i} (AdaGrad)214.8
d∑ini\sqrt{d\sum_i n_i} (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[-1,1]^{20} receive linear losses ft(x)=gt⊤xf_t(\vb{x}) = \vb{g}_t\T\vb{x}. Feature ii appears with probability 0.9 i−s0.9\,i^{-s} and, when present, its gradient is ±1\pm 1 with probability qq of being +1+1. Online GD uses η/t\eta/\sqrt{t} for every coordinate; AdaGrad uses η/ni(t)\eta/\sqrt{n_i(t)} for coordinate ii. With defaults and step scale 1 for both, online GD accumulates regret 181 at T=2000T = 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 ss to 0 so features are equally frequent and retune: what happens to the gap? Bottom readouts measure ∑ini\sum_i\sqrt{n_i} against d∑ini\sqrt{d\sum_i n_i}, 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=0s = 0 and each at its best step, both accumulate the same regret (291 and 292), because when all ni(t)n_i(t) are similar, η/ni(t)\eta/\sqrt{n_i(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)\mat{D} = \diag(\delta_1, \dots, \delta_d) with δi>0\delta_i > 0. Preconditioned gradient descent is xk+1=xk−η D−1∇f(xk)\vb{x}_{k+1} = \vb{x}_k - \eta\,\mat{D}\inv\grad f(\vb{x}_k). This is ordinary gradient descent in other coordinates: if z=D1/2x\vb{z} = \mat{D}^{1/2}\vb{x} and f~(z)=f(D−1/2z)\tilde f(\vb{z}) = f(\mat{D}^{-1/2}\vb{z}), then ∇f~(z)=D−1/2∇f(x)\grad\tilde f(\vb{z}) = \mat{D}^{-1/2}\grad f(\vb{x}), and a GD step on f~\tilde f, transformed back, is x←x−ηD−1∇f(x)\vb{x} \leftarrow \vb{x} - \eta\mat{D}\inv\grad f(\vb{x}). Thus lesson 7 rates apply using the preconditioned problem’s condition number. For quadratic Hessian A\mat{A}, it is κ(D−1/2AD−1/2)\kappa(\mat{D}^{-1/2}\mat{A}\mat{D}^{-1/2}) instead of κ(A)\kappa(\mat{A}).

When does a diagonal help? There is an exact two-dimensional answer, explaining the rotated-bowl figure. The two directions of a 2×22 \times 2 quadratic form angle θ\theta with the coordinate axes.

Proof

The scaling is [1ρρ1]\begin{bmatrix} 1 & \rho \\ \rho & 1\end{bmatrix} with ρ=A12/A11A22\rho = A_{12}/\sqrt{A_{11}A_{22}} and ∣A12∣=(L−μ)∣sin⁡θcos⁡θ∣\abs{A_{12}} = (L - \mu)\abs{\sin\theta\cos\theta}; its eigenvalues are 1±ρ1 \pm \rho, yielding κθ=(1+ρ)/(1−ρ)\kappa_\theta = (1 + \rho)/(1 - \rho). At θ=0\theta = 0, A12=0A_{12} = 0 and ρ=0\rho = 0. At θ=45∘\theta = 45^\circ, A11=A22=(μ+L)/2A_{11} = A_{22} = (\mu + L)/2 and ∣A12∣=(L−μ)/2\abs{A_{12}} = (L - \mu)/2, so ρ=(L−μ)/(L+μ)\rho = (L - \mu)/(L + \mu) and κθ=2L2μ=κ\kappa_\theta = \frac{2L}{2\mu} = \kappa. For optimality, scaling diag⁡(s1,s2)Adiag⁡(s1,s2)\diag(s_1, s_2)\mat{A}\diag(s_1, s_2) has determinant s12s22det⁡As_1^2s_2^2\det\mat{A} and trace A11s12+A22s22A_{11}s_1^2 + A_{22}s_2^2. For symmetric positive definite 2×22 \times 2 matrix with eigenvalues λ1≥λ2\lambda_1 \ge \lambda_2, (tr⁡)2/det⁡=(λ1+λ2)2/(λ1λ2)=κ+1/κ+2(\tr)^2/\det = (\lambda_1 + \lambda_2)^2/(\lambda_1\lambda_2) = \kappa + 1/\kappa + 2, increasing for κ≥1\kappa \ge 1: minimizing κ\kappa means minimizing that ratio. The ratio (A11s12+A22s22)2/(s12s22det⁡A)(A_{11}s_1^2 + A_{22}s_2^2)^2/(s_1^2s_2^2\det\mat{A}) is minimal when A11s12=A22s22A_{11}s_1^2 = A_{22}s_2^2 (arithmetic–geometric mean inequality, (a+b)2≥4ab(a + b)^2 \ge 4ab), the unit diagonal up to a common factor irrelevant to κ\kappa.

∎

With κ=104\kappa = 10^4, scaling gives κθ=1\kappa_\theta = 1 at θ=0∘\theta = 0^\circ, 25012501 at 15∘15^\circ, 75007500 at 30∘30^\circ and 1000010000 at 45∘45^\circ. 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\mat{A}‘s diagonal is never more than a dimension-order factor from optimal, so diag⁡(A)\diag(\mat{A}) is reasonable but still cannot touch off-axis structure.

One practical question remains: the method does not know A\mat{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)\mat{H}_t = \diag(\sqrt{G_{t,1}}, \dots, \sqrt{G_{t,d}}), where Gt,i=∑s≤tgs,i2G_{t,i} = \sum_{s \le t} g_{s,i}^2 is the sum of squared gradients of coordinate ii through round tt. With this Ht\mat{H}_t the lemma bounds regret by a controllable sum. The resulting update is AdaGrad.

A large or frequent gradient quickly increases Gt,iG_{t,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,i2G_{t,i} = g_{t,i}^2 the movement is η signo(gt,i)\eta\,\mathrm{signo}(g_{t,i}), of length η\eta, regardless of gradient scale. This answers the opening concern, as the next theorem proves.

Proof

Let u∈K\vb{u} \in \mathcal{K} be arbitrary. By convexity and the one-step lemma with H=Ht\mat{H} = \mat{H}_t,

RT(u)≤∑t=1Tgt⊤(xt−u)≤12η∑t=1T(∥xt−u∥Ht2−∥xt+1−u∥Ht2)+η2∑t=1T∥gt∥Ht−12.R_T(\vb{u}) \le \sum_{t=1}^{T}\vb{g}_t\T(\vb{x}_t - \vb{u}) \le \frac{1}{2\eta}\sum_{t=1}^{T}\Big(\norm{\vb{x}_t - \vb{u}}_{\mat{H}_t}^2 - \norm{\vb{x}_{t+1} - \vb{u}}_{\mat{H}_t}^2\Big) + \frac{\eta}{2}\sum_{t=1}^{T}\norm{\vb{g}_t}_{\mat{H}_t\inv}^2.

First sum. Regroup terms: they telescope except for the metric change,

∑t=1T(∥xt−u∥Ht2−∥xt+1−u∥Ht2)=∥x1−u∥H12+∑t=2T∥xt−u∥Ht−Ht−12−∥xT+1−u∥HT2.\sum_{t=1}^{T}\Big(\norm{\vb{x}_t - \vb{u}}_{\mat{H}_t}^2 - \norm{\vb{x}_{t+1} - \vb{u}}_{\mat{H}_t}^2\Big) = \norm{\vb{x}_1 - \vb{u}}_{\mat{H}_1}^2 + \sum_{t=2}^{T}\norm{\vb{x}_t - \vb{u}}_{\mat{H}_t - \mat{H}_{t-1}}^2 - \norm{\vb{x}_{T+1} - \vb{u}}_{\mat{H}_T}^2.

Since Ht−Ht−1\mat{H}_t - \mat{H}_{t-1} is diagonal with entries ≥0\ge 0, each term is ≤D∞2 tr⁡(Ht−Ht−1)\le D_\infty^2\,\tr(\mat{H}_t - \mat{H}_{t-1}), and the whole is bounded by D∞2tr⁡(HT)=D∞2∑iGT,iD_\infty^2\tr(\mat{H}_T) = D_\infty^2\sum_i\sqrt{G_{T,i}}.

Second sum. ∑t∥gt∥Ht−12=∑i∑tgt,i2/Gt,i\sum_t\norm{\vb{g}_t}_{\mat{H}_t\inv}^2 = \sum_i\sum_t g_{t,i}^2/\sqrt{G_{t,i}}. For at≥0a_t \ge 0 and At=∑s≤tas>0A_t = \sum_{s \le t}a_s > 0, we have at/At≤2(At−At−1)a_t/\sqrt{A_t} \le 2(\sqrt{A_t} - \sqrt{A_{t-1}}), since At−At−1=(At−At−1)(At+At−1)≤2At(At−At−1)A_t - A_{t-1} = (\sqrt{A_t} - \sqrt{A_{t-1}})(\sqrt{A_t} + \sqrt{A_{t-1}}) \le 2\sqrt{A_t}(\sqrt{A_t} - \sqrt{A_{t-1}}). Summing over tt (telescoping), ∑tat/At≤2AT\sum_t a_t/\sqrt{A_t} \le 2\sqrt{A_T}. Applied to each coordinate, the second sum is ≤2∑iGT,i\le 2\sum_i\sqrt{G_{T,i}}.

Combining them, RT(u)≤(D∞22η+η)∑iGT,iR_T(\vb{u}) \le \big(\frac{D_\infty^2}{2\eta} + \eta\big)\sum_i\sqrt{G_{T,i}}. Since u\vb{u} was arbitrary, this holds for RTR_T. Minimizing over η\eta (minimum of a/η+bηa/\eta + b\eta is 2ab2\sqrt{ab} at η=a/b\eta = \sqrt{a/b}) gives η=D∞/2\eta = D_\infty/\sqrt{2} and factor 2 D∞\sqrt{2}\,D_\infty.

∎

The bound contains what we wanted. If all gradients are bounded by G∞G_\infty, then ∥g1:T,i∥2≤G∞T\norm{g_{1:T,i}}_2 \le G_\infty\sqrt{T} and regret is O(D∞G∞ dT)\bigO(D_\infty G_\infty\,d\sqrt{T}), the same order as online gradient descent (which has D≤d D∞D \le \sqrt{d}\,D_\infty and G≤d G∞G \le \sqrt{d}\,G_\infty) up to a constant: in the worst case AdaGrad does not lose, and gains independence from TT and GG. But for sparse gradients, coordinate ii is active only nin_i rounds and ∥g1:T,i∥2≤G∞ni\norm{g_{1:T,i}}_2 \le G_\infty\sqrt{n_i}. Against online gradient descent tuned with knowledge of the future (giving D∑t∥gt∥22≤D∞G∞d∑iniD\sqrt{\sum_t\norm{\vb{g}_t}_2^2} \le D_\infty G_\infty\sqrt{d\sum_i n_i} on the cube), the ratio of bounds is, up to factor 2\sqrt{2},

∑inid∑ini≤1(Cauchy-Schwarz).\frac{\sum_{i}\sqrt{n_i}}{\sqrt{d\sum_{i}n_i}} \le 1 \quad \text{(Cauchy-Schwarz)}.

The ratio is 1 when all nin_i are equal and can be very small when very unequal. With frequencies pi=1/i2p_i = 1/i^2, the inequality of an extreme Zipf law, and d=1000d = 1000 features, it is 0.180.18: a bound about five times smaller; with d=104d = 10^4 it is 0.0760.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=4000t = 4000 (feature 1 is most frequent)
  • SGD
  • AdaGrad
  • frequency pᵢ
Mean logistic loss over the last 200 examples
  • SGD
  • AdaGrad
  • true weights
1.50
0.204
0.646
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=4000t = 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.9 i−sp_i = 0.9\,i^{-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.5s = 1.5, after 4000 examples SGD has learned 64% of the 12 rare weights and AdaGrad 92%; with s=2s = 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,iG_{t,i} only grows. Step η/Gt,i\eta/\sqrt{G_{t,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/t1/\sqrt{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 gg on one coordinate. AdaGrad has Gt=t g2G_t = t\,g^2 and step ηg/t g2=η/t\eta g/\sqrt{t\,g^2} = \eta/\sqrt{t}: after 10410^4 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,iG_{t,i} is replaced by an exponential average vt,iv_{t,i} of squares. Unrolling makes it clear: vt,i=(1−β2)∑s≤tβ2t−sgs,i2v_{t,i} = (1 - \beta_2)\sum_{s \le t}\beta_2^{t-s}g_{s,i}^2, a weighted average with geometric weights and effective window 1/(1−β2)1/(1 - \beta_2) iterations: 100 steps with β2=0.99\beta_2 = 0.99, 1000 with 0.9990.999. With constant gradient gg, vt=(1−β2t)g2→g2v_t = (1 - \beta_2^t)g^2 \to g^2 and the step tends to η\eta without switching off (compare η/t\eta/\sqrt{t}). For stationary gradients, vt,iv_{t,i} estimates E[gi2]\E[g_i^2], and RMSProp’s step is η gi/E[gi2]\eta\,g_i/\sqrt{\E[g_i^2]}: a normalized gradient with magnitude around η\eta.

A simple bound measures what one step can do: since vt,i≥(1−β2) gt,i2v_{t,i} \ge (1 - \beta_2)\,g_{t,i}^2, we have ∣gt,i∣/vt,i≤1/1−β2\abs{g_{t,i}}/\sqrt{v_{t,i}} \le 1/\sqrt{1 - \beta_2}, and with negligible ε\eps, each coordinate moves at most η/1−β2\eta/\sqrt{1 - \beta_2} per iteration: 10 η10\,\eta with β2=0.99\beta_2 = 0.99 and 31.6 η31.6\,\eta with 0.9990.999. The first step reaches this limit, when vv contains only one gradient, explaining why RMSProp’s η\eta is usually small (10−310^{-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∣|g_i| gradient
1001.0
vi\sqrt{v_i} accumulator
1001.0
η/(vi+ε)\eta/(\sqrt{v_i}+\varepsilon) multiplier
1.0e−30.100
∣Δxi∣|\Delta x_i| 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∣|x_i - 1| for each coordinate, on a log scale
  • coord. 1 (Adam)
  • coord. 2 (Adam)
  • coord. 2 (SGD, step 1/a₁)
Method
100
0.100
0.900
0.9990
1e−8.0
0.00
t = 1
Multiplier, coord. 11.0e−3
Multiplier, coord. 20.100
Multiplier ratio100
Scale ratio a1/a2a_1/a_2100
Error ∣xi−1∣|x_i - 1| at tt0.900 and 0.900
The multipliers adjust to each gradient’s scale: the large-gradient coordinate receives a step about 100100 times smaller, and both advance together.
Quadratic f=12(a1(x1−1)2+a2(x2−1)2)f = \tfrac12\big(a_1(x_1 - 1)^2 + a_2(x_2 - 1)^2\big) with a1/a2=100a_1/a_2 = 100. Each log-scale panel shows, for both coordinates, gradient, square root of accumulator, multiplier η/(v+ε)\eta/(\sqrt{v} + \eps) and actual step. With Adam, η=0.1\eta = 0.1 and β2=0.999\beta_2 = 0.999, multipliers differ by 100, exactly the inverse gradient ratio, and both coordinates fall together: at t=150t = 150 error is 1.3⋅10−41.3 \cdot 10^{-4} in both, while SGD with step 1/a11/a_1, solving the fast coordinate at once, leaves the slow one at 0.220.22. Switch to AdaGrad and watch the multiplier only decrease. Increase ε\eps to 1010: the slow coordinate multiplier stays at η/ε=0.01\eta/\eps = 0.01, SGD's step, and its error remains 0.220.22 again. Add noise and watch v\sqrt{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\beta_2 closely follows the gradient and gets noisy, while large β2\beta_2 smooths more but reacts slowly. And ε\eps sets a floor on the denominator: while v\sqrt{v} greatly exceeds ε\eps the multiplier is η/v\eta/\sqrt{v}, and when v\sqrt{v} falls below it the multiplier stays at η/ε\eta/\eps 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\vb{m}_t estimating its first moment, and a squared-gradient average vt\vb{v}_t 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\vb{m} with window about 1/(1−β1)=101/(1 - \beta_1) = 10 steps and v\vb{v} with window 10001000. The third row is bias correction, distinguishing Adam from “RMSProp with momentum”. Why? Since m0=0\vb{m}_0 = \vb{0}, the average carries the initial zero. At t=1t = 1, m1=(1−β1)g1=0.1 g1\vb{m}_1 = (1 - \beta_1)\vb{g}_1 = 0.1\,\vb{g}_1, only one tenth of what it should estimate, and v1=0.001 g12\vb{v}_1 = 0.001\,\vb{g}_1^2, one thousandth. Dividing by 1−βt1 - \beta^t exactly compensates for this carryover, as the next theorem proves.

Proof

Unrolling, mt=(1−β1)∑s=1tβ1t−sgs\vb{m}_t = (1 - \beta_1)\sum_{s=1}^{t}\beta_1^{t-s}\vb{g}_s. By linearity, E[mt]=(1−β1) μ∑s=1tβ1t−s=(1−β1) μ 1−β1t1−β1=(1−β1t) μ\E[\vb{m}_t] = (1 - \beta_1)\,\vb{\mu}\sum_{s=1}^{t}\beta_1^{t-s} = (1 - \beta_1)\,\vb{\mu}\,\frac{1 - \beta_1^t}{1 - \beta_1} = (1 - \beta_1^t)\,\vb{\mu}, and dividing by 1−β1t1 - \beta_1^t gives μ\vb{\mu}. Identically for v\vb{v} with β2\beta_2 and ν\vb{\nu}. If E[gs]=μs\E[\vb{g}_s] = \vb{\mu}_s, subtract μt\vb{\mu}_t to get 1−β11−β1t∑sβ1t−s(μs−μt)\frac{1 - \beta_1}{1 - \beta_1^t}\sum_s\beta_1^{t-s}(\vb{\mu}_s - \vb{\mu}_t), vanishing when μs≈μt\vb{\mu}_s \approx \vb{\mu}_t within the window.

∎

The practical consequence is key and less obvious than it seems. Factor 1/(1−βt)1/(1 - \beta^t) is huge initially and 1 at the end: with β2=0.999\beta_2 = 0.999 it is 10001000 at t=1t = 1, about 100.5100.5 at t=10t = 10, 1.581.58 at t=1000t = 1000 and 1.051.05 at t=3000t = 3000. Without v\vb{v} correction the denominator starts 1000\sqrt{1000} times too small and steps become absurdly large; without m\vb{m} correction the numerator starts too small. The corrections do not cancel because β1≠β2\beta_1 \ne \beta_2: without either, the step is multiplied by (1−β1t)/1−β2t(1 - \beta_1^t)/\sqrt{1 - \beta_2^t}, equal to 0.1/0.001≈3.160.1/\sqrt{0.001} \approx 3.16 at t=1t = 1 and 6.56.5 at t=10t = 10: several times too large. Easier to see than reason through:

InteractiveWhy correct bias
First moment mtm_t (gradient average, window ≈1/(1−β1)\approx 1/(1-\beta_1))
  • uncorrected m_t
  • corrected m̂_t
  • E[m_t] = (1 − β₁ᵗ) μ
  • μ
Second moment vtv_t (average of g2g^2, window ≈1/(1−β2)\approx 1/(1-\beta_2))
  • uncorrected v_t
  • corrected v̂_t
  • E[v_t] = (1 − β₂ᵗ) E[g²]
  • E[g²]
Adam step size, ∣Δt∣/η=∣m∣/v|\Delta_t|/\eta = |m|/\sqrt{v} with ε=0\varepsilon = 0
  • step with selected correction
  • steady-state value |μ|/√E[g²]
Typical β2\beta_2
0.900
0.9990
1.00
0.50
Horizon (steps)
Correction applied to step
First uncorrected step /η/\eta3.16
Step at t=10t = 10 with selected correction /η/\eta5.50
Steady-state step /η/\eta0.89
Time scale of vv: 1/(1−β2)1/(1-\beta_2)1000
Without correction, the first step is independent of the gradient: ∣Δ1∣/η=(1−β1)/1−β2=3.16|\Delta_1|/\eta = (1-\beta_1)/\sqrt{1-\beta_2} = 3.16. With β2\beta_2 close to 1, vv starts much smaller than E[g2]E[g^2] and the step spikes.
A stationary stream gt∼N(μ,σ2)g_t \sim \mathcal{N}(\mu, \sigma^2) with μ=1\mu = 1 and σ=0.5\sigma = 0.5 feeds both averages. Top and middle: mtm_t and vtv_t uncorrected and corrected against exact expected values (dashed). Bottom: step size ∣m∣/v\abs{m}/\sqrt{v} in η\eta units depending on correction. Uncorrected with β2=0.999\beta_2 = 0.999, first step is 3.16 η3.16\,\eta ((1−β1)/1−β2(1-\beta_1)/\sqrt{1-\beta_2} regardless of gradient); using expected values the step rises to 5.8 η5.8\,\eta at t=10t = 10 and remains 1.76 η1.76\,\eta at t=300t = 300 (select horizon 300), while the correct stationary step is 0.89 η0.89\,\eta. Change to β2=0.99\beta_2 = 0.99 and compare. Try correcting only mm or only vv 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]\eta\,\E[g]/\sqrt{\E[g^2]}, equal to η\eta if the gradient is deterministic and reduced to η μ/μ2+σ2\eta\,\mu/\sqrt{\mu^2 + \sigma^2} with noise standard deviation σ\sigma (in the figure, 0.894 η0.894\,\eta). Adam is thus a signal-to-noise method: it advances at speed η\eta 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 η\eta (§2.1): η\eta 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)\eta_t = \eta\sqrt{1 - \beta_2^t}/(1 - \beta_1^t) and ε^\hat{\eps} added to uncorrected vt\sqrt{\vb{v}_t}: since 1−β2t/(vt+ε^)=1/(v^t+ε^/1−β2t)\sqrt{1 - \beta_2^t}/(\sqrt{\vb{v}_t} + \hat{\eps}) = 1/(\sqrt{\hat{\vb{v}}_t} + \hat{\eps}/\sqrt{1 - \beta_2^t}), this equals the equation above with ε=ε^/1−β2t\eps = \hat{\eps}/\sqrt{1 - \beta_2^t}, larger than ε^\hat\eps initially (about 3232 times at t=1t = 1 with β2=0.999\beta_2 = 0.999). PyTorch uses the form above, adding ε\eps to the corrected v^t\hat{\vb{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 ε\eps is negligible, the step is independent of gradient scale.

Proof

Induction on tt. With gradient Sgt\mat{S}\vb{g}_t, sums Gt,iG_{t,i} and averages vt,iv_{t,i} are multiplied by si2s_i^2 and mt,im_{t,i} by sis_i (linear in gg and g2g^2, with bias correction depending only on tt). Then Gt,i\sqrt{G_{t,i}}, vt,i\sqrt{v_{t,i}} and v^t,i\sqrt{\hat v_{t,i}} are multiplied by sis_i, as are gt,ig_{t,i} or m^t,i\hat m_{t,i} by sis_i, so the quotient multiplying η\eta is unchanged and trajectories agree at t+1t + 1. In SGD, step −ηSgt-\eta\mat{S}\vb{g}_t does change.

∎

The key case is S=c I\mat{S} = c\,\mat{I}: multiplying loss by a constant c>0c > 0 does not change Adam’s trajectory, and multiplies SGD’s step by cc (the “Multiply loss by 1000” quiz and first code cell check this: with c=1000c = 1000, Adam’s trajectory changes by 10−1210^{-12} and SGD’s explodes). This is a real virtue: no need to retune η\eta 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\eps \ne 0 invariance breaks when v\sqrt{v} is not large relative to ε\eps. A nondiagonal variable change (rotation) is not Sg\mat{S}\vb{g} and changes the trajectory, as in the rotated bowl. The step is measured in parameter units, so rescaling parameters (x=c zx = c\,z) changes the path in xx: η\eta is a length in parameter space, and if two parameters have very different scales the same η\eta 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.

HyperparameterTypical valueWhat it controlsIncrease itDecrease it
η\eta10−310^{-3} (small networks); large transformers around 10−410^{-4} (6⋅10−56 \cdot 10^{-5} to 6⋅10−46 \cdot 10^{-4} in GPT-3, smaller for larger models)Coordinate step length in parameter unitsLarger steps and divergence riskSlow progress
β1\beta_10.90.9m\vb{m} window: 1/(1−β1)≈101/(1-\beta_1) \approx 10 stepsMore gradient smoothing, more inertiaCloser to RMSProp
β2\beta_20.9990.999; often 0.950.95 to 0.980.98 in language modelsv\vb{v} window: 1/(1−β2)≈10001/(1-\beta_2) \approx 1000 stepsVery stable scale, slow adaptationAgile but noisy scale; step may be large after a small gradient
ε\eps10−810^{-8}Denominator floorMore like SGD with momentum, step η/ε\eta/\epsMore adaptation, risk of huge steps if v→0\sqrt{v} \to 0

Why these numbers? β2\beta_2 is much larger than β1\beta_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\beta_2 of 0.9990.999 may remember a spike for a thousand iterations and unnecessarily damp the step or react slowly to a regime change; hence 0.950.95 is common (for example GPT-3 used β1=0.9\beta_1 = 0.9, β2=0.95\beta_2 = 0.95, ε=10−8\eps = 10^{-8} according to Brown et al., 2020). ε\eps is rarely changed until something fails; then its effect matters: the third code cell shows that with gradient scale 10−810^{-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 tt. 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 100100 and 11, SGD at step 1/L=1/1001/L = 1/100 needs 797 iterations because the curvature-11 coordinate contracts by 0.990.99 each step (even optimal step 2/(L+μ)=2/1012/(L + \mu) = 2/101 takes at least 401). AdaGrad and RMSProp take 35 and 27 iterations, Adam 115 (its inertia β1=0.9\beta_1 = 0.9 overshoots and oscillates slightly before settling). Scale invariance holds to arithmetic limits: multiplying loss by 10001000 changes Adam’s path by 10−1210^{-12} and sends SGD to 106010^{60}, i.e. divergence. On Rosenbrock, with each best step, Adam reaches 9⋅10−79 \cdot 10^{-7}, AdaGrad 5⋅10−45 \cdot 10^{-4}, while SGD and RMSProp remain at 4⋅10−24 \cdot 10^{-2} and 3.5⋅10−23.5 \cdot 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.6010.601 (SGD, η=0.20\eta = 0.20) to 0.5770.577 (AdaGrad, η=0.63\eta = 0.63), versus 0.5590.559 with true weights. The difference lies in rare features: SGD recovers 59 %59\,\% of their weight and AdaGrad 81 %81\,\%, with nearly equal results on frequent features (83 %83\,\% and 88 %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^]\E[\hat m] on a stationary stream (as in the theorem) and ε\eps‘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]\E[m_t] is 0.1000.100 at t=1t = 1, 0.6520.652 at t=10t = 10 and 0.9960.996 at t=50t = 50, versus exact (1−0.9t)⋅1(1 - 0.9^t)\cdot 1 values 0.1000.100, 0.6510.651 and 0.9950.995; E[m^t]\E[\hat m_t] is 11 in every row (apart from Monte Carlo error of a few thousandths), likewise v^\hat v with 1.25=μ2+σ21.25 = \mu^2 + \sigma^2. The second table shows ε\eps‘s effect: with ε=10−8\eps = 10^{-8} the step is η\eta while the gradient exceeds 10−610^{-6}, falls to η/2\eta/2 when the gradient equals ε\eps, and vanishes below. With ε=10−3\eps = 10^{-3} half the step is already lost for gradients 10−310^{-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−153 \cdot 10^{-15} after 100 steps: same formula, rounding differences. Adam state occupies 2.0142.014 times parameter memory (the two tensors exp_avg and exp_avg_sq, plus a step counter per parameter tensor), versus 1.0001.000 for SGD momentum. In float32 including gradients, each parameter costs 4+4+8=164 + 4 + 8 = 16 bytes with Adam and 88 with SGD without momentum.

What you needOptionNote
Train a network with Adamtorch.optim.Adam(params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8)This lesson’s formula, with ε\eps added to v^\sqrt{\hat v}.
Sparse features, huge embeddingstorch.optim.Adagrad(params, lr) or SparseAdamPyTorch AdaGrad defaults to ε=10−10\eps = 10^{-10}. SparseAdam updates only rows with gradients.
RMSProptorch.optim.RMSprop(params, lr, alpha=0.99)alpha is β2\beta_2. Other frameworks use different defaults (e.g. 0.90.9 in Keras) and place ε\eps differently.
Another update ruleSubclass torch.optim.OptimizerLike MiAdam: state lives in self.state[p].
Inspect state memorySum numel() * element_size() from opt.stateAdam: 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\mathcal{K} \subset \R^d be convex and closed with diameter ≤D\le D, and let f1,…,fTf_1, \dots, f_T be convex with subgradients gt∈∂ft(xt)\vb{g}_t \in \partial f_t(\vb{x}_t) of norm ≤G\le G. With x1∈K\vb{x}_1 \in \mathcal{K} and xt+1=ΠK(xt−ηgt)\vb{x}_{t+1} = \Pi_{\mathcal{K}}(\vb{x}_t - \eta\vb{g}_t), prove RT≤D22η+η2G2TR_T \le \frac{D^2}{2\eta} + \frac{\eta}{2}G^2T and deduce that with η=D/(GT)\eta = D/(G\sqrt{T}) regret is at most DGTDG\sqrt{T}.
0
Fix arbitrary u∈K\vb{u} \in \mathcal{K} and call gt∈∂ft(xt)\vb{g}_t \in \partial f_t(\vb{x}_t) the subgradient observed in round tt.

Step 1 of 4. Start with one round. What inequality holds for ∥xt+1−u∥2\norm{\vb{x}_{t+1} - \vb{u}}^2?

ProofCorrection 1/(1 − β₁ᵗ) removes bias
Prove: Let mt=β1mt−1+(1−β1)gtm_t = \beta_1 m_{t-1} + (1 - \beta_1)g_t with m0=0m_0 = 0 and E[gs]=μ\E[g_s] = \mu for every ss. Prove E[mt]=(1−β1t)μ\E[m_t] = (1 - \beta_1^t)\mu and hence m^t=mt/(1−β1t)\hat m_t = m_t/(1 - \beta_1^t) satisfies E[m^t]=μ\E[\hat m_t] = \mu.
0
Work with one coordinate. Expectation is linear, so independence of the gsg_s is unnecessary.

Step 1 of 3. What results from unrolling the recurrence?

NumericCorrection factor for v at t = 10
With β2=0.999\beta_2 = 0.999, what is correction factor 1/(1−β2t)1/(1 - \beta_2^t) by which Adam divides vtv_t at step t=10t = 10?
NumericAdaGrad's gain with Zipf-like features
There are d=1000d = 1000 features and feature ii is active in fraction pi=1/i2p_i = 1/i^2 of rounds, so ni=piTn_i = p_i T. AdaGrad's bound is proportional to ∑ini\sum_i\sqrt{n_i} and tuned online gradient descent's to d∑ini\sqrt{d\sum_i n_i}. What is the ratio ∑ini / d∑ini\sum_i\sqrt{n_i}\,/\,\sqrt{d\sum_i n_i}?
NumericCondition number reduction by a diagonal
A quadratic has Hessian A=[100991]\mat{A} = \begin{bmatrix} 100 & 9 \\ 9 & 1 \end{bmatrix}, condition number κ(A)≈535\kappa(\mat{A}) \approx 535. Precondition with its diagonal D=diag⁡(100,1)\mat{D} = \diag(100, 1). What is κ(D−1/2AD−1/2)\kappa(\mat{D}^{-1/2}\mat{A}\mat{D}^{-1/2})?
NumericAdam state memory
You train a 7⋅1097 \cdot 10^9-parameter model with Adam, storing m\vb{m} and v\vb{v} in float32 (4 bytes per value). How many GB (10910^9 bytes) does optimizer state alone occupy (excluding parameters, gradients and activations)?
QuizMultiply loss by 1000
You train with Adam (negligible ε\eps) and SGD, each with its own η\eta. You multiply loss by 10001000 without changing anything else. What happens to trajectories?
QuizAdaGrad's multiplier with constant gradient
A coordinate receives constant gradient g≠0g \ne 0 every round. With η=0.5\eta = 0.5 and negligible ε\eps, how do AdaGrad and RMSProp with β2=0.99\beta_2 = 0.99 steps evolve?
QuizWhen diagonal preconditioning does not help
On a quadratic with κ=104\kappa = 10^4 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)\hat m = m/(1 - \beta_1^t), v^=v/(1−β2t)\hat v = v/(1 - \beta_2^t) and update x−η m^/(v^+ε)\vb{x} - \eta\,\hat m/(\sqrt{\hat v} + \eps). 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)\bigO(\sqrt{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)\eta = D/(G\sqrt{T}) satisfies RT≤DGTR_T \le DG\sqrt{T}, and iterate averaging leads to SGD rate O(1/T)\bigO(1/\sqrt{T}).
  • AdaGrad updates xt+1,i=xt,i−η gt,i/Gt,ix_{t+1,i} = x_{t,i} - \eta\,g_{t,i}/\sqrt{G_{t,i}} with Gt,i=∑s≤tgs,i2G_{t,i} = \sum_{s \le t}g_{s,i}^2. Its regret is ≤(D∞2/(2η)+η)∑i∥g1:T,i∥2\le(D_\infty^2/(2\eta) + \eta)\sum_i\norm{g_{1:T,i}}_2, without knowing TT or GG, much smaller than online GD for sparse gradients (rare features receive large steps). Its drawback is that GG only grows and the step dies as 1/t1/\sqrt{t}.
  • RMSProp replaces the sum with exponential average vt=β2vt−1+(1−β2)gt2v_t = \beta_2v_{t-1} + (1 - \beta_2)g_t^2 (window 1/(1−β2)1/(1 - \beta_2)), keeping the step alive, with size ≤η/1−β2\le\eta/\sqrt{1 - \beta_2}.
  • Adam adds gradient average mtm_t and divides by 1−βt1 - \beta^t to remove zero-start bias: E[m^t]=E[g]\E[\hat m_t] = \E[g] under stationarity. Without correction, with β2=0.999\beta_2 = 0.999 the first step is 3.16 η3.16\,\eta instead of η\eta. The stationary step is η E[g]/E[g2]\eta\,\E[g]/\sqrt{\E[g^2]}: a signal-to-noise ratio.
  • They are invariant to gradient scale (f→cff \to cf does not change trajectory with ε=0\eps = 0), but not rotations: with θ=45∘\theta = 45^\circ diagonal scaling leaves κθ=κ\kappa_\theta = \kappa. η\eta remains the main hyperparameter, ε\eps marks the transition to SGD with momentum, and state costs two tensors per parameter.