23.5 Adaptive Methods
The transformers in this book, like most large neural networks, are trained with Adam or its variant AdamW (Section 9.5.3) rather than with plain stochastic gradient descent. A primary reason is the step size. The methods of Section 23.4 apply a single step size to every coordinate, adjusting it only over time. Yet a modern network has to parameters whose curvatures differ by orders of magnitude and are unknown in advance. When all coordinates share one step size, the steepest direction caps the step and the flat directions barely move. This section asks how an optimizer can choose a separate step size for each coordinate from the gradients alone—and where that strategy breaks down.
Our running example illustrates how much is at stake. Consider the narrow valley starting at . Gradient descent with the optimal single step size, , needs 6,160 steps to drive below , because a step small enough to keep stable is a thousand times too small for . The heavy-ball method of Section 23.1, which adds a fraction of the previous step to each new one, cuts that to 296 steps. (Both counts are a little below the and steps quoted there, because that section stopped on the distance to the minimizer and this one stops on the value of .) An optimizer that gives each coordinate its own step size, estimated purely from the gradients it has observed, needs only a few dozen. Even more striking is what that count does not depend on: make the valley a hundred times narrower still, and the iteration count grows by just six steps.
Headline counts like these are easy to produce and easy to misread, so much of this section is devoted to making the comparison fair. We will run heavy ball at its theoretically optimal settings, give Adam a simple sweep of step sizes, and also rotate the valley by . Under that fairer test, Adam's advantage looks quite different from what the first count suggests.
The underlying mechanism is simple: divide each coordinate's step by the root mean square of its past gradients, as AdaGrad, RMSProp, and Adam do. We first prove that this normalization makes Adam blind to the scale of each coordinate, and then follow that symmetry to the boundaries where it breaks: a rotation of the valley, a periodic sequence of convex losses, weight decay, the opening steps of training, and the matrix structure of a layer. Two results carry the most weight: the scale-invariance proposition and the fixed-point analysis of AdamW. The regret bounds for AdaGrad and the structured preconditioners at the end can be skipped on a first reading. Throughout, indexes optimizer steps, denotes the curvature of coordinate , and is the weight-decay coefficient.
23.5.1 Per-Coordinate Step Sizes#
23.5.1.1 A Diagonal Quadratic#
Gradient descent on a quadratic requires a number of steps proportional to the condition number , because its single step size must stay below (Section 23.1). The simplest setting where a remedy becomes visible is the two-variable diagonal quadratic,
Because each partial derivative depends only on its own coordinate, nothing forces the two coordinates to share a step size. With a separate step for each coordinate, updates to , and choosing sends every coordinate to zero in a single step. For , the ideal steps are and . This is Newton's method for a diagonal Hessian, and the condition number vanishes from the iteration count.
Two obstacles stand between this ideal and a practical optimizer: the curvatures are unknown and shift over the course of training, and the gradients we observe are noisy minibatch estimates. We must therefore infer each coordinate's step size from the gradients alone, using gradient magnitude as a proxy. On the diagonal quadratic, the gradient entry has magnitude . Whenever coordinates are of comparable size, a coordinate with large gradients also has high curvature, so dividing by its gradient magnitude effectively divides by its curvature. When coordinates differ sharply in scale, however, still has unit magnitude: normalization fixes the distance traveled per step at , rather than taking the true Newton step .
23.5.1.2 AdaGrad#
Varying curvature is one reason to give each coordinate its own step size. A second, independent reason is that coordinates are updated at very different frequencies. A global decaying step size such as —the classical choice in online and nonsmooth convex optimization—treats every coordinate identically. Suppose coordinate 1 receives a gradient of at every step while coordinate 2 receives one only once every steps, as happens for a rare word's weight in a bag-of-words model. By , a global schedule reduces both step sizes to , so the single piece of evidence about the rare coordinate moves it by only a hundredth of . If instead each coordinate accumulates its own squared gradients, the running sums are and , and dividing by their square roots gives the busy coordinate while leaving the rare coordinate at .
This is AdaGrad (Duchi et al., 2011). Write for the vector of squared gradient entries (abbreviated as from here on), with square roots and divisions of vectors likewise applied elementwise. AdaGrad maintains the running sum of squared gradients and divides the step by its square root:
starting from , where a small constant prevents division by zero (Section 9.5 in the main text places inside the square root, which makes no qualitative difference here). Each coordinate's step size now decays according to its own gradient history rather than the global step count.
The metric view. Steepest descent depends on how we measure step length. Under the weighted norm for a positive definite matrix , the steepest descent direction is (Exercise 1 of Section 23.1). AdaGrad is steepest descent in the diagonal metric : moving along coordinate is penalized in proportion to the accumulated evidence that its gradient has been large. A matrix such as that rescales the gradient before taking a step is called a preconditioner. Whereas Newton's method uses the true curvature , AdaGrad substitutes the gradient history (Exercise 1).
The regret view. AdaGrad was originally designed for online convex optimization, in which convex losses arrive one at a time and the learner must choose before seeing . Performance over rounds is measured by the regret, : the cumulative excess loss relative to the best fixed point chosen in hindsight. An algorithm learns in this framework when its average regret (regret divided by ) tends to zero.
On a convex set of Euclidean diameter with bounded gradients , online gradient descent with a tuned global step size achieves regret of order (proved in Exercise 4). AdaGrad, by contrast, achieves regret of order (Duchi et al., 2011)
where is the diameter of the set in the norm. Each of the coordinates pays only for its own gradient history rather than for the worst-case gradient norm across all coordinates.
On the box , we have . When gradient mass concentrates on a small subset of coordinates, AdaGrad's bound is up to a factor of smaller; when the mass is spread evenly across coordinates, the two bounds match. For one-hot gradients that hit coordinate with probability , the expected ratio of the two bounds is at most (Exercise 2). For uniform this ratio is even though every individual gradient is sparse, whereas for word frequencies following Zipf's law with exponent at it drops to . AdaGrad's advantage therefore comes from the concentration of gradient mass on certain coordinates, not from sparsity by itself.
The square root in (23.5.1) is not arbitrary: it is the exact exponent that balances the two competing terms in the regret proof (Exercise 4c).
Outside online convex optimization, however, unbounded accumulation becomes AdaGrad's main weakness. Under persistent gradient noise of variance , the sum grows as , so the effective step size shrinks as . AdaGrad thus carries a built-in decay schedule tied to the step count rather than to optimization progress. That rate is optimal for convex regret, but on long nonconvex training runs it causes the step size to decay relentlessly whether or not the loss is still improving, leaving almost no step size by the time the optimizer reaches a late plateau.
23.5.1.3 RMSProp#
RMSProp (Tieleman and Hinton, 2012) fixes this decay by replacing the all-time sum with an exponential moving average, keeping the scale estimate responsive to recent gradients:
Unrolling the recursion shows that assigns the squared gradient from steps ago the weight , so old gradients halve in weight roughly every steps—every 7 steps at RMSProp's customary , and every 693 steps at . Step sizes no longer vanish by construction. The trade-off is that any single large gradient is forgotten on that same timescale, a vulnerability we will exploit in a counterexample below.
23.5.1.4 Adam and Its Bias Correction#
Adam (Kingma and Ba, 2015) combines RMSProp's second-moment estimate with an exponential moving average of the gradient itself, and corrects both averages for their initialization at zero. In the notation of Section 9.5, the update reads
with and the standard defaults , , and . The first moment is the heavy-ball velocity of Section 23.1.3 scaled by , which turns a running sum into a weighted average and smooths the minibatch noise that plain RMSProp steps along directly.
Dividing by compensates for starting from . Unrolling the recursion gives . If the squared-gradient scale is stationary, with for every , summing the geometric series yields
Thus is an unbiased estimate of at every step under stationarity, and the same calculation with shows that is unbiased for the mean gradient.
Without this correction, the initialization deficit is both large and long-lived: at the default , captures only about of its stationary target, and even at it has reached just (Section 9.5). More striking is how the error evolves over time. Dropping both bias corrections mis-scales the update by the factor , which starts at at and, perhaps surprisingly, climbs to a peak of at . The first-moment average fills in roughly ten steps, whereas the second-moment average needs about a thousand. Figure 23.5.1 plots both the deficit and the resulting step inflation.
Bias correction in Adam. Left: starting from zero, the running average captures only the fraction of the squared-gradient scale ( at for ); dividing by restores the full scale at every step. Right: without bias correction, the update is inflated by , starting at at , peaking at at as the numerator fills in ten steps while the denominator takes a thousand, and returning to only on the timescale. Uncorrected Adam thus takes its largest steps when its preconditioner rests on the fewest gradients.
Even an unbiased does not make the step size itself unbiased. Because Adam divides by rather than , concavity of the square root biases the denominator downward: by Jensen's inequality, unless is constant. The first step is the extreme case. At , and , so the ratio is and the step has magnitude in every coordinate, whatever the gradient, rather than for a gradient of scale . We examine how much this matters in Section 23.5.4.
23.5.1.5 Scale Invariance#
In our opening example, , yet Adam crosses the valley as if that thousandfold ratio did not exist. The reason is an exact symmetry of the update, and it is the central result of this section.
Proposition (Adam ignores the scale of each coordinate). Let and let with every . Suppose two problems have gradients related by at every . Then Adam with the same , , step schedule, and starting point produces identical iterates on both problems, as long as the updates remain defined.
In other words, the second problem is the first with coordinate 's gradient rescaled by a positive constant . We denote its quantities with a tilde.
Proof. We proceed by induction on . Suppose the iterates agree up to . Then for every . Because the recursions for and are linear in and , we obtain and . The bias-correction denominators are the same scalars in both problems, so the corrected ratio of the second problem is . The updates therefore coincide, giving .
On the diagonal quadratic, is simply the gradient of the round bowl multiplied by . Consequently, Adam on the valley traces, step for step, the exact same trajectory as Adam on the round bowl—and on the bowl, two coordinates started at equal values remain equal forever. Each coordinate follows the same one-dimensional iteration on ,
where averages the past squares for . Because earlier iterates were larger, exceeds from the second step onward, so each update moves by less than and contracts geometrically by the factor . At , this factor tightens from at to at as catches up with the shrinking iterates. The iterates themselves are completely independent of . Only the stopping test depends on the curvature ratio, because weights the common iterate by the curvatures. Making the valley far narrower should therefore add only a handful of geometric contraction steps, never a factor of .
What the step count does depend on is the starting distance measured in units of , since the early steps have length roughly per coordinate regardless of curvature. An experiment in the next subsection checks both predictions directly.
In short, Adam measures every coordinate in units of its own gradient size, making coordinate-wise scaling invisible to it. Three caveats bound this invariance. First, breaks the symmetry once a coordinate's gradients shrink to the order of . Second, the proposition says nothing about a change of basis that mixes coordinates, which we test next on the rotated valley. Third, Adam is not in general sign descent: its update reduces to the sign step in only three special cases—at ; when (Exercise 5d); and, for , whenever each coordinate's gradient magnitude stays constant over the memory of .
23.5.2 Coordinate Scaling and Its Limits#
23.5.2.1 Aligned and Rotated Valleys#
How much of gradient descent's 6,160 steps does coordinate scaling alone eliminate, and does that gain survive when the valley is rotated? To separate per-coordinate scaling from momentum, we compare four methods: gradient descent at its optimal single step size; heavy ball at its optimal step size and momentum; Adam with , which only rescales; and Adam with its default momentum . To rotate the problem by an angle , we replace with , where is the rotation matrix, and rotate the starting point alongside it, , so that the initial point retains the same components along both curvature axes. At , this gives . The code below defines the valley, a loop that counts steps to reach the target tolerance, and the three optimizer updates.
h = np.array([1.0, 1000.0]) # curvatures h_i, kappa = 1000
def rotated(theta):
"""A = R diag(h) R^T and the start R (1, 1): the valley turned by theta."""
c, s = np.cos(theta), np.sin(theta)
R = np.array([[c, -s], [s, c]])
return R @ np.diag(h) @ R.T, R @ np.ones(2)
def run(step, A, x0, K=40000, tol=1e-8):
"""First t with f(x_t) = x_t^T A x_t / 2 < tol, or None within K steps."""
x, state = x0.copy(), {}
for t in range(1, K + 1):
x = step(x, A @ x, t, state)
if 0.5 * x @ A @ x < tol:
return t
return None
def gd(eta):
return lambda x, g, t, state: x - eta * g
def heavy_ball(eta, beta):
def step(x, g, t, state):
state['d'] = beta * state.get('d', 0.0) - eta * g # velocity
return x + state['d']
return step
def adam(eta, beta1=0.9, beta2=0.999, eps=1e-8):
def step(x, g, t, state):
state['m'] = beta1 * state.get('m', 0.0) + (1 - beta1) * g
state['v'] = beta2 * state.get('v', 0.0) + (1 - beta2) * g * g
m_hat, v_hat = state['m'] / (1 - beta1**t), state['v'] / (1 - beta2**t)
return x - eta * m_hat / (np.sqrt(v_hat) + eps)
return step
Before reading the step counts, notice what information each method is given. Gradient descent and heavy ball run at their theoretically optimal settings, computed in closed form from the true curvatures and . That is a generous handicap, since in practice nobody knows the extreme curvatures of a neural network. Adam has no closed-form formula, so we give it what a practitioner would use: a log-spaced sweep of seven step sizes from to (spaced by factors of about three), reading each row at its best entry. The grid deliberately skips : because Adam's first step has length in every coordinate (Section 23.5.4), starting at with would land directly on the origin in one step. That would be a coincidence of the starting point, not a fair measure of optimizer speed.
mu, L = h.min(), h.max()
rho = (np.sqrt(L) - np.sqrt(mu)) / (np.sqrt(L) + np.sqrt(mu))
tuned = {'GD, eta = 2/(mu + L)': gd(2 / (mu + L)),
'heavy ball, tuned': heavy_ball(4 / (np.sqrt(L) + np.sqrt(mu))**2,
rho**2)}
valleys = {'aligned': rotated(0.0), 'rotated 45': rotated(np.pi / 4)}
print(f'{"steps to f < 1e-8":28s}{"aligned":>9s}{"rotated 45":>12s}')
for name, step in tuned.items():
hits = [run(step, *problem) for problem in valleys.values()]
print(f'{name:28s}{hits[0] or "never":>9}{hits[1] or "never":>12}')
etas = np.geomspace(0.002, 2.0, 7) # step sizes for Adam
print(f'\n{"Adam, eta =":28s}' + ''.join(f'{eta:>7.2g}' for eta in etas))
for beta1 in (0.0, 0.9):
for name, problem in valleys.items():
hits = [run(adam(eta, beta1=beta1), *problem) for eta in etas]
print(f'{f"beta1 = {beta1}, {name}":28s}'
+ ''.join(f'{k or "never":>7}' for k in hits))
steps to f < 1e-8 aligned rotated 45
GD, eta = 2/(mu + L) 6160 6160
heavy ball, tuned 296 296
Adam, eta = 0.002 0.0063 0.02 0.063 0.2 0.63 2
beta1 = 0.0, aligned 2122 760 249 78 22 never never
beta1 = 0.0, rotated 45 never never never never never never never
beta1 = 0.9, aligned 2033 648 195 165 205 170 196
beta1 = 0.9, rotated 45 12862 9292 5898 3171 1581 799 559
Consider the aligned valley first. Per-coordinate scaling alone () needs just 22 steps at its best step size, compared with 6,160 for gradient descent and 296 for heavy ball—thirteen times fewer steps than a heavy-ball method given both true curvatures, from an optimizer told neither. That row also clarifies what tuning Adam actually adjusts. The iteration count scales roughly as , because the early steps have length about and the total count mainly reflects the distance to the minimizer measured in step lengths. At the two largest step sizes, however, scaling alone never converges: the iterate overshoots the minimum and settles into a cycle that bounces each coordinate between and . Adam has thus traded one unknown (the curvature) for another: the distance to the minimizer in units of .
Adding Adam's default momentum () brings the count to between 165 and 205 steps across the entire range of step sizes from to . Two features stand out. The first is robustness: a hundredfold change in shifts the iteration count by only a quarter, and the two largest step sizes that cycled forever without momentum now converge cleanly because the momentum average damps the alternating signs. Heavy ball enjoys no such margin: its optimal step size sits within of its stability limit (Exercise 8a of Section 23.1), so its 296-step result presupposes near-exact knowledge of the largest curvature. The second feature is the price of that robustness: momentum makes Adam roughly seven times slower than scaling alone. The cause is the contraction limit from Section 23.1.3: an iteration with momentum contracts any mode with complex roots at rate per step, and no faster. After per-coordinate scaling, both coordinates effectively run on a round bowl of condition number one, where the optimal momentum is zero. With , the contraction factor is per step, which predicts roughly 230 steps to reach the tolerance, closely matching the observed counts. Momentum that accelerates progress along an ill-conditioned valley acts as a brake on a round bowl, yet Adam's default applies it unconditionally.
Now turn to the rotated valley. Gradient descent and heavy ball require the exact same number of steps as before, because their updates are rotation-invariant and simply rotate with the problem. Adam's updates are not. Scaling alone fails to reach the tolerance at every single step size on the grid. Adam with momentum does converge, but only toward the upper end of the grid: its best count is 559 at , nearly twice heavy ball's 296, and at the smallest step size it needs 12,862 steps—twice as many as plain gradient descent. Its step-size robustness vanishes too, with counts now spanning more than a twentyfold range across the grid.
The fair verdict therefore has two halves. When the coordinate axes align with the principal curvature directions, per-coordinate scaling beats a perfectly tuned heavy ball by an order of magnitude while requiring far less prior knowledge. When the valley is rotated, the benefit of diagonal scaling disappears completely; whatever convergence remains comes from momentum, and a well-tuned heavy ball performs that job twice as fast. Let us examine both halves in closer detail.
On the aligned valley, our scale-invariance proposition predicts that both coordinates follow identical iterates while the stiff coordinate receives an effective step a thousand times smaller. Below, we print the iterates and effective step sizes of scaling-only Adam (, ). The last two lines then test what actually controls the iteration count by varying the curvature ratio across five orders of magnitude and moving the starting point a hundred times farther from the origin.
A, x = rotated(0.0)
step, state, eta, gap = adam(0.1, beta1=0.0, eps=0.0), {}, 0.1, 0.0
for t in range(1, 49):
x = step(x, A @ x, t, state)
gap = max(gap, abs(x[0] - x[1]))
if t in (1, 10, 48):
eff = eta / np.sqrt(state['v'] / (1 - 0.999**t))
print(f't = {t:2d}: x = {x[0]:.3g}, {x[1]:.3g}; '
f'eta/sqrt(v_hat) = {eff[0]:.3g}, {eff[1]:.3g}')
print(f'largest |x_1 - x_2| over the run: {gap:.1e}')
counts = [run(adam(0.1, beta1=0.0), np.diag([1.0, r]), np.ones(2))
for r in (1.0, 1e3, 1e5)]
print('steps to f < 1e-8 at curvature ratios 1, 1e3, 1e5:', *counts)
print('steps from (100, 100) at ratio 1e3:',
run(adam(0.1, beta1=0.0), A, 100 * np.ones(2)))
t = 1: x = 0.9, 0.9; eta/sqrt(v_hat) = 0.1, 0.0001
t = 10: x = 0.262, 0.262; eta/sqrt(v_hat) = 0.152, 0.000152
t = 48: x = 3.91e-06, 3.91e-06; eta/sqrt(v_hat) = 0.329, 0.000329
largest |x_1 - x_2| over the run: 5.6e-17
steps to f < 1e-8 at curvature ratios 1, 1e3, 1e5: 40 48 54
steps from (100, 100) at ratio 1e3: 4145
From the very first step, the effective step sizes stand in the exact ratio —the true curvature ratio recovered from gradient magnitudes alone, without ever forming a Hessian. The two coordinates agree to floating-point precision throughout, and the effective step on the flat coordinate grows from to as adapts to the shrinking gradients. Raising the curvature ratio from to to increases the step count only from 40 to 48 to 54: a hundred-thousandfold worsening in conditioning costs just fourteen extra steps. Moving the starting point a hundred times farther away, however, pushes the count to 4,145. The iteration count measures starting distance in units of , and barely feels the curvature at all.
Why is a rotation fatal to all of this? The rotated matrix has diagonal entries near , and its steep direction projects equally onto both coordinate axes. Every coordinate's gradient is therefore dominated by the steep mode, so both coordinates accumulate nearly identical scale estimates (across the runs, their values agree to within one percent). Because a per-coordinate preconditioner assigns only one scalar to each coordinate, it cannot shrink the steep component of a coordinate's gradient without equally shrinking its flat component. With equal scales on both coordinates, the preconditioner reduces to a scalar multiple of the identity. Scaling-only Adam () thus reverts to gradient descent whose step size is dictated by the steep mode, leaving the flat mode to crawl. Adam with reverts to heavy ball: its momentum is close to the optimal , but its effective step is governed by gradient history rather than curvature, leaving even the best grid point twice as slow as tuned heavy ball.
Without momentum, the rotated run ends in oscillation. As the steep component initially shrinks, decreases and the effective step size grows until it crosses the stability limit of the steep mode. At —the optimal step size for the aligned valley—the loss drops to about around , at which point the steep mode begins to oscillate. That steady oscillation locks the gradient magnitude in place, driving so that the update collapses to the sign step of length across the valley. The iterate is trapped forever in a two-cycle of amplitude with loss (Exercise 5 verifies this formula across the step-size grid). Momentum averages out these alternating steps, which is why the runs eventually reach the target tolerance. Figure 23.5.2 illustrates all three behaviors on a valley shallow enough to plot clearly.
Comparison on a two-dimensional valley (; the text's runs use , whose contours are too thin to draw) from the same starting point. (a) Gradient descent with a single step size near the stability limit oscillates across the steep direction while crawling along the flat one. (b) Per-coordinate normalization (Adam with ) moves both coordinates at the same speed and curves smoothly into the minimum. (c) Rotating the valley and starting point by misaligns the coordinate axes from the curvature directions, leaving the iterate creeping along the valley floor ( after 40 steps, versus in (b)).
Per-coordinate scaling eliminates ill-conditioning if and only if the coordinate axes align with the eigenvectors of the curvature. Scaling changes the metric by a diagonal matrix, and no diagonal matrix can capture curvature along directions that mix coordinates. A full matrix built from outer products rotates with the problem and avoids this flaw, but storing and inverting it is far too expensive for large neural networks. The structured preconditioners at the end of this section address this limitation for weight matrices by using compact factors that mix coordinates.
23.5.2.2 A Convex Counterexample to Adam#
RMSProp and Adam forget past gradients, whereas AdaGrad remembers them indefinitely. Can that forgetting make even a simple convex problem unsolvable? Reddi et al. (2018) showed that it can, using a one-dimensional periodic sequence of convex losses.
Proposition (Adam need not converge). Let and consider online optimization over with the periodic losses
Run Adam without bias correction, with , , step sizes satisfying , and projection of each iterate back onto , starting from . Then for every and for every . Each three-step period adds at least to the regret, so the average regret never tends to zero. (Reddi et al., 2018)
Here, projection onto is simply clipping (Section 23.6 treats projection in general). Because the gradients over each three-step period sum to , the best fixed point in hindsight is . Yet Adam returns to , the worst point in the interval, at the start of every period. Each period costs Adam at least (it incurs on the first step at , and at least on each of the other two), whereas incurs , producing a regret increment of at least per period. The proof proceeds by induction over periods; Exercise 3 works through the key step, where ensures that the downward step stays inside . Nor is this failure an artifact of setting : the same paper constructs, for every fixed pair with , both an online convex sequence and a stochastic convex problem on which Adam fails to converge.
We can see the mechanism directly in a single period with and , once has settled into its steady periodic cycle. Following the gradients , the second-moment estimate takes the values , , and , so is , , and . The three resulting displacements are
yielding a net drift of per period toward . Normalization caps the rare large gradient to a move of roughly —barely larger than the move from a gradient of size —and forgets the spike within two steps. Together, the two gradients therefore push farther upward than the single gradient pulls it downward. By contrast, plain SGD with step moves by , , and , for a net toward the optimum. Unlike the noise floor of constant-step SGD (Section 23.4), Adam's wrong-way drift does not disappear as the step size shrinks: it points toward at every step size.
To repair this flaw, Reddi et al. (2018) proposed AMSGrad, which replaces in the denominator with its running maximum of the uncorrected average. The effective step is then nonincreasing, so a large gradient is never forgotten. In our periodic example, remains pinned at throughout, changing the three displacements to , , and —a net toward the optimum. Adam should therefore converge to , while AMSGrad and SGD converge to . The cell below tests all three with the same decay starting from , the midpoint of the interval, so that Adam is not even initialized at the bad endpoint.
def online(update, C=4.0, T=15000, alpha=0.5):
"""Projected iterates on the periodic losses; beta_1 = 0, no bias correction."""
beta2 = 1 / (1 + C * C)
x, v, vmax, xs = 0.0, 0.0, 0.0, []
for t in range(1, T + 1):
g = C if t % 3 == 1 else -1.0 # rare +C, frequent -1
v = beta2 * v + (1 - beta2) * g * g
vmax = max(vmax, v) # running maximum (AMSGrad)
x = min(1.0, max(-1.0, x - alpha / np.sqrt(t) * update(g, v, vmax, C)))
xs.append(x)
return xs
updates = {'adam': lambda g, v, vmax, C: g / (np.sqrt(v) + 1e-8),
'amsgrad': lambda g, v, vmax, C: g / (np.sqrt(vmax) + 1e-8),
'sgd': lambda g, v, vmax, C: g / C}
print('x_t at t = 30 300 3000 15000 (x* = -1)')
for name, update in updates.items():
xs = online(update)
print(f'{name:9s}' + ''.join(f'{xs[t - 1]:9.3f}' for t in (30, 300, 3000, 15000)))
x_t at t = 30 300 3000 15000 (x* = -1)
adam 0.745 1.000 1.000 1.000
amsgrad -0.953 -0.985 -0.995 -0.998
sgd -0.954 -0.986 -0.995 -0.998
Here alpha plays the role of in the proposition, and
, so the step-size hypothesis holds. Even from
the midpoint of the interval, Adam still marches straight to : from
onward it returns to at every period and never drops
below . Meanwhile, AMSGrad and SGD steadily approach the optimum
and agree to two decimal places. This counterexample proves that Adam lacks
a general convex convergence guarantee, though it should be read as an
existence result rather than a prediction of failure on typical deep
learning problems.
23.5.3 Decoupled Weight Decay#
23.5.3.1 Coupled and Decoupled Decay#
Almost every modern training recipe includes weight decay, which forces an adaptive optimizer to make a design choice: should the decay term pass through the preconditioner? Under SGD, the distinction does not exist. Adding an penalty to the loss adds to the gradient, and the resulting update is simultaneously a gradient step on the loss and a uniform shrinkage of the weights (Section 9.5.3, which writes for the weights). Inside Adam, however, those two mechanisms diverge. Feeding the penalized gradient into (23.5.3) and isolating the decay term (setting for clarity, so the update is ), the per-step shrinkage of coordinate becomes
In coupled Adam, the preconditioner divides both the loss gradient and the penalty gradient, so a coordinate's shrinkage rate is inversely proportional to its gradient scale: weights with large gradients are barely decayed, while quiet weights are decayed heavily. AdamW (Loshchilov and Hutter, 2019) decouples the two operations so that only the loss gradient passes through the preconditioner while weight decay acts directly on the parameters:
Every coordinate now shrinks by the same factor per step, just as in SGD, and the moment averages track only the loss gradient.
torch.optim.Adam(weight_decay=...) adds to the gradient:
it implements the coupled rule. torch.optim.AdamW implements the decoupled
rule (23.5.7).
The sharpest test of (23.5.6) is a weight whose loss gradient is pure zero-mean noise, leaving weight decay as the only systematic drift. If the noise has standard deviation , then , so we expect coupled Adam to shrink the weight to roughly after steps, whereas AdamW should shrink every weight to regardless of . Below, we initialize weights with noise scale and with , all at , run 4,000 steps of each method with and , and compare the group means with these predictions.
sigma, eta, lam, T, n = np.array([[10.0], [0.1]]), 1e-3, 0.1, 4000, 10_000
rng = np.random.default_rng()
def decay(decoupled, beta1=0.9, beta2=0.999, eps=1e-8):
"""Mean of w over n weights per noise scale after T Adam steps from w = 1."""
w, m, v = np.ones((2, n)), np.zeros((2, n)), np.zeros((2, n))
for t in range(1, T + 1):
g = sigma * rng.standard_normal((2, n)) # loss gradient: pure noise
if decoupled:
w = (1 - eta * lam) * w # decay outside the preconditioner
else:
g = g + lam * w # l2 penalty inside the gradient
m = beta1 * m + (1 - beta1) * g
v = beta2 * v + (1 - beta2) * g * g
w = w - eta * (m / (1 - beta1**t)) / (np.sqrt(v / (1 - beta2**t)) + eps)
return w.mean(axis=1)
print('per-step decay rates: coupled', eta * lam / sigma.ravel(), ' AdamW', eta * lam)
print('mean w, coupled:', decay(False).round(3),
' predictions exp(-eta lam T / sigma):', np.exp(-eta * lam * T / sigma.ravel()).round(3))
print('mean w, AdamW: ', decay(True).round(3),
' prediction (1 - eta lam)^T:', round((1 - eta * lam)**T, 3))per-step decay rates: coupled [1.e-05 1.e-03] AdamW 0.0001
mean w, coupled: [0.961 0.027] predictions exp(-eta lam T / sigma): [0.961 0.018]
mean w, AdamW: [0.67 0.67] prediction (1 - eta lam)^T: 0.67
A single value of gives the two groups coupled decay rates of and per step—a hundredfold difference. The noisy weights retain of their initial magnitude as predicted, while the quiet weights drop to about , slightly above the estimate. That small shortfall has a straightforward cause: near , the penalty gradient on a quiet weight is comparable to its noise and inflates its own , slowing its initial decay. Under AdamW, by contrast, both groups finish right at . For AdamW this prediction is exact in expectation, because the normalized noise steps have mean zero and the multiplicative decay is identical at every step.
23.5.3.2 Fixed Points#
The pure-noise experiment has no stationary point because its gradients never settle. With exact gradients, however, an optimizer can come to rest, and at a fixed point takes on a surprisingly different meaning.
Proposition (fixed points of coupled and decoupled decay). Let the gradient of a loss be exact (noiseless), let , and call a fixed point of an update if the update vanishes there once the moment estimates have settled. (a) Adam on has a fixed point at if and only if , the same stationary point as SGD on the penalized loss. (b) AdamW has a fixed point at if and only if, for every coordinate ,
Every fixed point of AdamW therefore lies strictly inside the box , and as the condition reduces to a dichotomy: either , or with opposite in sign to .
Proof. At a fixed point, the vector fed into the moment averages is constant, so and . (a) For coupled Adam, , and coordinate 's update approaches , which vanishes if and only if . (b) For AdamW, , so coordinate 's update approaches ; setting this to zero and multiplying through by yields (23.5.8). Taking absolute values gives . Letting turns the condition into , which holds precisely when or .
This proposition characterizes fixed points; it does not assert that one exists or that the iterates converge to it. Nor is the dichotomy merely a limiting curiosity: since , at every coordinate either sits within a fraction of the box boundary or has a gradient of order .
A one-dimensional example makes the contrast concrete. Consider , whose unconstrained minimizer is . With , coupled Adam rests at the penalized minimizer , whereas AdamW rests at : the box does not bind, so decoupled decay leaves the minimizer untouched. With , coupled Adam rests at , while AdamW is pinned at , right on the boundary of the box.
The two interpretations of are thus completely distinct. In the noise-dominated regime of training, AdamW applies uniform per-step shrinkage across all coordinates while coupled Adam distorts it by gradient scale. At exact-gradient fixed points, the roles flip: coupled Adam preserves the maximum a posteriori (MAP) solution of a Gaussian prior on the weights (Section 24.6), whereas AdamW turns into the radius of an constraint box (Xie and Li, 2024). Exercise 6 connects this box directly to constrained optimization.
23.5.4 Warmup#
At step , Adam's bias-corrected moments are and , so the update is simply —a step of full size in every coordinate. A coordinate whose gradient is moves just as far as one whose gradient is , on the evidence of a single minibatch. Warmup ramps the step size up from near zero over the opening steps of training (Goyal et al., 2017), keeping these early updates small. It is tempting to blame this early instability on the preconditioner , which at rests on a single sample. A simple experiment shows that something else is at work.
Is a step of size actually too large? Not for a coordinate with a consistent gradient, whose steady-state step is also . For a coordinate whose gradient is pure noise, however, it is wasted motion. To measure how large that wasted motion is, we draw independent gradient coordinates from at each step, run default Adam, and track the root-mean-square update in units of . We compare four curves: standard Adam; Adam with replaced by the exact variance (eliminating preconditioner estimation error entirely); Adam with both bias corrections removed; and Adam multiplied by a linear warmup over the first steps.
n, T, beta1, beta2, eps, T_w = 20_000, 3000, 0.9, 0.999, 1e-8, 20
m, v = np.zeros(n), np.zeros(n)
rms = {'Adam': [], 'exact variance': [], 'no bias correction': [],
f'warmup over {T_w} steps': []}
for t in range(1, T + 1):
g = rng.standard_normal(n) # pure noise, sigma = 1
m = beta1 * m + (1 - beta1) * g
v = beta2 * v + (1 - beta2) * g * g
m_hat, v_hat = m / (1 - beta1**t), v / (1 - beta2**t)
step = m_hat / (np.sqrt(v_hat) + eps) # Adam's update / eta
for r, u in zip(rms.values(), (step, m_hat, m / (np.sqrt(v) + eps),
min(1.0, t / T_w) * step)):
r.append(np.sqrt(np.mean(u**2)))
d2l.plot(np.arange(1, T + 1), list(rms.values()), 't', 'RMS update / eta',
legend=list(rms), xscale='log')
ts = (1, 2, 3, 10, 20, 30, 100, 1000, 3000)
print(f'{"t:":24s}' + ''.join(f'{t:>6d}' for t in ts))
for name, r in rms.items():
print(f'{name + ":":24s}' + ''.join(f'{r[t - 1]:6.2f}' for t in ts))t: 1 2 3 10 20 30 100 1000 3000
Adam: 1.00 0.71 0.58 0.33 0.26 0.24 0.23 0.23 0.23
exact variance: 1.00 0.71 0.58 0.33 0.26 0.24 0.23 0.23 0.23
no bias correction: 3.16 3.02 2.87 2.17 1.61 1.32 0.74 0.29 0.24
warmup over 20 steps: 0.05 0.07 0.09 0.17 0.26 0.24 0.23 0.23 0.23
Standard Adam starts with an RMS update of , drops to by , and settles within about fifty steps at —the steady-state size of an exponential moving average of independent unit noise. On a pure noise coordinate, Adam's opening steps are therefore roughly four times larger than their steady-state size, and this transient lasts about ten steps.
Is the noisy preconditioner to blame? The second curve says no. Replacing with the exact variance leaves the RMS update unchanged to within at every step (the sampling noise of coordinates). The fourfold inflation comes from the momentum average, which needs roughly steps to average out independent noise. What the preconditioner actually does at is equalize coordinates of different scales, an effect hidden when every coordinate shares .
Bias correction matters far more. Without it, the opening update jumps to —matching the factor in Figure 23.5.1—and the transient stretches from ten steps to hundreds: the update is still around at and at , because the uncorrected fills on the slow timescale. An uncorrected optimizer would need a thousand-step warmup merely to undo its own zero initialization. With bias correction in place, a linear ramp over just steps tames what remains, keeping the warmup curve below throughout.
That accounts for warmups of tens of steps, not the thousands of steps often used in large-scale training. Longer warmups respond to a second mechanism absent from this noise model: curvature. A step size is stable only below the ceiling imposed by the steepest curvature direction (Section 23.1.2). Immediately after random initialization, that curvature can be unusually large and shift rapidly, so a step size that is safe later in training may initially be unstable. Section 9.7.3 revisits both mechanisms on a real neural network and measures the opening step sizes directly.
23.5.5 Structured Preconditioners#
23.5.5.1 Kronecker Factors#
Our rotated valley defeated every diagonal preconditioner. All of the methods in this section share the preconditioned form for a positive definite matrix : gradient descent uses , Newton's method uses the Hessian , and Adam uses a diagonal matrix estimated from past gradients. A full curvature matrix captures steepness along any direction—aligned with the axes or not—but it is far too large to store. A single weight matrix already has parameters; its full curvature matrix would contain entries, requiring roughly two petabytes in double precision.
What makes a middle ground possible is that neural network parameters are organized into matrices. Consider a linear layer with weight matrix , input , and output gradient . The gradient with respect to is the rank-one outer product . Writing for the vector obtained by stacking the columns of a matrix , we have , where the Kronecker product is the block matrix whose block is .
The outer-product curvature of this layer—the block of the Fisher information matrix (which we will study in Section 24.6) corresponding to —is therefore . K-FAC (Martens and Grosse, 2015) approximates this expectation by the Kronecker product , where is and is . This factorization would be exact if inputs and output gradients were statistically independent; nobody expects that to hold in a trained network, but the approximation is adopted because it can be inverted cheaply.
Specifically, the inverse of a Kronecker product acts directly on the unstacked gradient matrix. For symmetric invertible factors,
To verify this identity, write column of the product as , where is column of . Stacking these columns produces the block product , so . Using together with the symmetry of the factors, setting and yields (23.5.9). In this way, a curvature matrix with entries is inverted and applied through two modest inverses of sizes and . The cell below compares the storage and operation counts for our layer.
m = n = 4096
print(f'stored entries: full {(m * n)**2:.1e}, two factors {m**2 + n**2:.1e}')
print(f'flops to invert: full {(m * n)**3:.1e}, two factors {m**3 + n**3:.1e}')
stored entries: full 2.8e+14, two factors 3.4e+07
flops to invert: full 4.7e+21, two factors 1.4e+11
Factoring cuts storage from entries down to , and cuts the inversion cost from operations to roughly .
23.5.5.2 K-FAC, Shampoo and Muon#
The Kronecker identity leaves two choices open: which matrices to factor, and what exponent to apply to them. Modern structured optimizers share the two-sided preconditioning form applied to a layer's gradient matrix (bold, distinguishing it from the scalar gradient bound of the regret analysis). Together, they form a natural progression from Adam's diagonal scaling to matrix-level normalization.
K-FAC constructs its factors from the second moments of layer inputs and output gradients with exponent . It approximates preconditioning by the Fisher information matrix—the natural gradient (Amari, 1998), which is the metric view of AdaGrad using the Fisher matrix as the metric. For softmax cross-entropy and squared loss, the Fisher matrix (with labels sampled from the model) coincides with the Gauss–Newton matrix, a positive semidefinite approximation to the Hessian that drops the term involving second derivatives of the network. For these losses, K-FAC therefore approximates genuine curvature.
Shampoo (Gupta et al., 2018) instead builds its left and right factors directly from accumulated gradient matrices in the spirit of AdaGrad, setting and with . Muon (Jordan et al., 2024) can be viewed as memoryless Shampoo: using only the current matrix (assumed square and invertible),
which is the polar factor of . It preserves the singular vectors of while setting every singular value to one. Where Adam equalizes the coordinates of the update, Muon equalizes its singular directions—and unlike per-coordinate normalization, this map commutes with orthogonal rotations of the rows and columns (Exercise 5d). Muon as a practical optimizer, which applies this orthogonalization to the momentum matrix, is covered in the main text (Section 9.6), while the Newton–Schulz iteration that computes the polar factor using matrix multiplications alone is analyzed in Section 21.5.4.2.
None of these three methods reproduces full Newton's method. Muon stores no second-moment matrices and requires only a handful of matrix products per step, whereas K-FAC and Shampoo invert or take matrix roots of their two factors, typically amortizing that cost over several steps. Moreover, every positive result in this section assumes that curvature aligns either with the coordinate axes or with the Kronecker structure of individual layers. Because the true curvature of a deep neural network is neither diagonal nor fixed, explaining why these adaptive methods perform as well as they do in practice remains an active open question.
23.5.6 Summary#
Dividing each coordinate's update by the root mean square of its past gradients, the common thread linking AdaGrad, RMSProp, and Adam, removes the condition number whenever curvature aligns with the coordinate axes. With , Adam's iterates are strictly invariant to per-coordinate rescaling, allowing scaling alone to beat an optimally tuned heavy-ball method by an order of magnitude on an aligned valley. Rotate the valley by , however, and that advantage vanishes: scaling alone never converges, and Adam with momentum takes roughly twice as many steps as heavy ball.
Forgetting past gradients introduces further subtleties. On a periodic sequence of convex losses, Adam's short second-moment memory can drive it to the worst point of the domain, a failure fixed by AMSGrad's running maximum. With weight decay, passing an penalty through Adam scales each coordinate's shrinkage inversely with its gradient size while preserving the MAP fixed point; AdamW decouples the decay so that every coordinate shrinks uniformly per step, turning into the radius of an box at exact-gradient fixed points.
Finally, Adam's opening updates on pure-noise coordinates are roughly four times larger than their steady-state size because of the momentum average rather than the preconditioner, and dropping bias correction inflates them much further for hundreds of steps; longer practical warmups address early curvature instead. Beyond diagonal scaling, Kronecker-factored preconditioners such as K-FAC, Shampoo, and Muon capture cross-coordinate structure within weight matrices using two compact factors, with Muon equalizing the singular directions of a layer's update.
23.5.7 Exercises#
-
AdaGrad from the metric view. Exercise 1b of Section 23.1 showed that the steepest descent direction under the norm is proportional to .
- Set with and recover (23.5.1).
- Replace the objective by for a constant and set . How does the AdaGrad update change? How would it change if were built from instead of ? Compare both with gradient descent and with Newton's method.
- Let the gradients of one coordinate be i.i.d. with . How fast does the effective step of that coordinate decay in under each of the two choices, and how does it depend on ?
-
Concentrated gradients and AdaGrad's bound. Up to constant factors, projected online gradient descent with a tuned global step has regret on a convex set of Euclidean diameter when (Exercise 4). Diagonal AdaGrad has regret , where is the diameter of the set in the norm (Duchi et al., 2011). Take the box and one-hot gradients: at each step one coordinate , drawn independently with probability , receives the gradient or , and all other coordinates receive .
- Compute both bounds. For AdaGrad, bound the expectation of each square root with Jensen's inequality, and show that the ratio of the AdaGrad bound to the gradient-descent bound is at most .
- Evaluate the ratio for uniform and for Zipf frequencies with and .
- Word frequencies in natural text follow Zipf's law with , and your ratio there is about . How much of the factor of Section 23.5.1 does a bag-of-words model obtain? Which distribution of gradient mass would obtain all of it?
-
The Reddi example by hand. Take , , the proposition's , and no bias correction, as in
online.- Assume a fixed step , an iterate in the interior of , and settled into its periodic pattern. Write for the value of after the step, solve the three-step recursion for in closed form, and derive the periodic values , , and the three displacements of the text. Compute SGD's three steps . Which steps does Adam enlarge relative to SGD, and why?
- AMSGrad replaces by . Show that its effective step is nonincreasing in whenever is. Compute its three displacements in the periodic regime and show that the net displacement is .
- The proposition needs for the steps . Show where this is used: starting a period at , use after the gradient to show that the first step of the period lands in , so that the projection does not act on it.
-
Regret of online gradient descent. ● Projected online gradient descent plays with , where is the Euclidean projection onto a closed convex set of diameter , , and the steps are nonincreasing (Zinkevich, 2003).
- Prove that the regret satisfies
Start from and use that the projection does not increase distances to points of .
- Show that gives regret at most , and that for the bound grows linearly in for every .
- Combine these two bounds with the decay rates of Exercise 1c to explain why AdaGrad divides by rather than by .
-
[code] Rotation sensitivity. ● Use
rotated,runand the update factories of the#adaptive-stochastic-methods-adam-vs-gdcell.- Show that the iterates of gradient descent and of heavy ball on from are times their iterates on the aligned valley, so that their step counts do not depend on .
- For at , print after steps at each of the table's grid and compare it with the value of the text. Which component of Adam supplies what survives of its advantage over gradient descent?
- Print Adam's effective per-coordinate steps at . Why does even this small rotation remove most of the step-size ratio that Adam builds on the aligned valley?
- Exercise 4 of Section 23.1 identifies as the steepest direction under the norm and as the steepest direction under the spectral norm, where . Show that Adam with and steps along . Then let and be orthogonal, show that the map commutes with , and give a example in which the sign map does not. What does this suggest about the rotation sensitivity of Muon compared with Adam?
-
[extended] AdamW's implicit constraint. ●● The proposition of Section 23.5.3 found that the fixed points of AdamW lie in the box and, as , on its boundary wherever the gradient does not vanish. Xie and Li (2024) prove that if full-batch AdamW with and a nonincreasing step schedule with divergent sum converges, its limit is a KKT point of subject to .
- A feasible is a KKT point of this problem (Section 23.6 derives the conditions in general) when every coordinate satisfies if and if . Show that at such a point no feasible direction decreases to first order.
- Set , the setting of the theorem, in the AdamW condition (23.5.8). Show that a coordinate with satisfies the KKT conditions. Why does the condition alone not show for a coordinate whose gradient vanishes?
- Generate linearly separable logistic-regression data with , , standard normal features, and labels , so that the unregularized loss has no finite minimizer. Run full-batch AdamW with for steps, with decaying from to by a cosine schedule, for . Compare the result with the solution of the box-constrained problem computed by projected gradient descent, which here clips every coordinate to after each gradient step, and with Adam on .
- Repeat the AdamW runs with minibatch gradients of size and . Where does the iterate end up relative to the box, and why?
- What does control in AdamW according to these results, and how does that differ from the Gaussian-prior reading of in Section 24.6?
-
The Kronecker identity and its cost. Use column stacking for .
- Prove by writing out column of the product, and prove .
- Deduce (23.5.9) for symmetric invertible factors. Which formula replaces it for factors that are not symmetric, and which for row stacking?
- For an layer, count the operations needed to invert the full matrix and apply it, against inverting the two factors and applying them by (23.5.9) (). Evaluate both counts at and at , .
- For a single gradient , set and . Show that the Shampoo step equals . What must the inverse fourth root mean when is not square, and which singular vectors does the result keep?