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 10710^7 to 101110^{11} 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 f(x)=12(x12+1000 x22)f(\mathbf{x}) = \tfrac12\bigl(x_1^2 + 1000\, x_2^2\bigr) starting at (1,1)(1, 1). Gradient descent with the optimal single step size, η=2/1001\eta = 2/1001, needs 6,160 steps to drive ff below 10−810^{-8}, because a step small enough to keep x2x_2 stable is a thousand times too small for x1x_1. 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 6,9086{,}908 and 315315 steps quoted there, because that section stopped on the distance to the minimizer and this one stops on the value of ff.) 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 45∘45^\circ. 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, tt indexes optimizer steps, hih_i denotes the curvature of coordinate ii, and λ\lambda 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 κ=hmax⁡/hmin⁡\kappa = h_{\max}/h_{\min}, because its single step size must stay below 2/hmax⁡2/h_{\max} (Section 23.1). The simplest setting where a remedy becomes visible is the two-variable diagonal quadratic,

f(x)=12(h1x12+h2x22),∂f∂xi=hixi.f(\mathbf{x}) = \tfrac12\bigl(h_1 x_1^2 + h_2 x_2^2\bigr), \qquad \frac{\partial f}{\partial x_i} = h_i x_i .

Because each partial derivative depends only on its own coordinate, nothing forces the two coordinates to share a step size. With a separate step ηi\eta_i for each coordinate, xix_i updates to xi−ηihixi=(1−ηihi) xix_i - \eta_i h_i x_i = (1 - \eta_i h_i)\, x_i, and choosing ηi=1/hi\eta_i = 1/h_i sends every coordinate to zero in a single step. For h=(1,1000)h = (1, 1000), the ideal steps are 11 and 10−310^{-3}. 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 hih_i 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 gi=hixig_i = h_i x_i has magnitude hi∣xi∣h_i |x_i|. 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, gi/∣gi∣g_i/|g_i| still has unit magnitude: normalization fixes the distance traveled per step at η\eta, rather than taking the true Newton step xix_i.

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 η/t\eta/\sqrt{t}—the classical choice in online and nonsmooth convex optimization—treats every coordinate identically. Suppose coordinate 1 receives a gradient of ±1\pm 1 at every step while coordinate 2 receives one only once every 10410^4 steps, as happens for a rare word's weight in a bag-of-words model. By t=104t = 10^4, a global schedule reduces both step sizes to η/100\eta/100, so the single piece of evidence about the rare coordinate moves it by only a hundredth of η\eta. If instead each coordinate accumulates its own squared gradients, the running sums are 10410^4 and 11, and dividing η\eta by their square roots gives the busy coordinate η/100\eta/100 while leaving the rare coordinate at η\eta.

This is AdaGrad (Duchi et al., 2011). Write gt⊙gt\mathbf{g}_t \odot \mathbf{g}_t for the vector of squared gradient entries (abbreviated as gt2\mathbf{g}_t^2 from here on), with square roots and divisions of vectors likewise applied elementwise. AdaGrad maintains the running sum st\mathbf{s}_t of squared gradients and divides the step by its square root:

st=st−1+gt⊙gt,xt+1=xt−ηst+ϵ gt,(23.5.1)\mathbf{s}_t = \mathbf{s}_{t-1} + \mathbf{g}_t \odot \mathbf{g}_t, \qquad \mathbf{x}_{t+1} = \mathbf{x}_t - \frac{\eta}{\sqrt{\mathbf{s}_t} + \epsilon}\, \mathbf{g}_t, \tag{23.5.1}

starting from s0=0\mathbf{s}_0 = \mathbf{0}, where a small constant ϵ\epsilon prevents division by zero (Section 9.5 in the main text places ϵ\epsilon 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 ∥d∥P=d⊤P d\|\mathbf{d}\|_{\mathbf{P}} = \sqrt{\mathbf{d}^\top \mathbf{P}\, \mathbf{d}} for a positive definite matrix P\mathbf{P}, the steepest descent direction is −P−1∇f-\mathbf{P}^{-1}\nabla f (Exercise 1 of Section 23.1). AdaGrad is steepest descent in the diagonal metric Pt=diag(st)\mathbf{P}_t = \mathrm{diag}(\sqrt{\mathbf{s}_t}): moving along coordinate ii is penalized in proportion to the accumulated evidence ∑τ≤tgτ,i2\sqrt{\sum_{\tau \le t} g_{\tau,i}^2} that its gradient has been large. A matrix such as Pt\mathbf{P}_t that rescales the gradient before taking a step is called a preconditioner. Whereas Newton's method uses the true curvature diag(hi)\mathrm{diag}(h_i), AdaGrad substitutes the gradient history (Exercise 1).

The regret view. AdaGrad was originally designed for online convex optimization, in which convex losses f1,f2,…f_1, f_2, \ldots arrive one at a time and the learner must choose xt\mathbf{x}_t before seeing ftf_t. Performance over TT rounds is measured by the regret, ∑t=1Tft(xt)−min⁡x∑t=1Tft(x)\sum_{t=1}^T f_t(\mathbf{x}_t) - \min_{\mathbf{x}} \sum_{t=1}^T f_t(\mathbf{x}): 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 TT) tends to zero.

On a convex set of Euclidean diameter D2D_2 with bounded gradients ∥gt∥≤G\|\mathbf{g}_t\| \le G, online gradient descent with a tuned global step size achieves regret of order D2GTD_2 G \sqrt{T} (proved in Exercise 4). AdaGrad, by contrast, achieves regret of order (Duchi et al., 2011)

D∞∑i=1d∑t=1Tgt,i2,D_\infty \sum_{i=1}^{d} \sqrt{\textstyle\sum_{t=1}^{T} g_{t,i}^2} ,

where D∞D_\infty is the diameter of the set in the ℓ∞\ell_\infty norm. Each of the dd coordinates pays only for its own gradient history rather than for the worst-case gradient norm across all coordinates.

On the box [−1,1]d[-1, 1]^d, we have D2=d D∞D_2 = \sqrt{d}\, D_\infty. When gradient mass concentrates on a small subset of coordinates, AdaGrad's bound is up to a factor of d\sqrt{d} smaller; when the mass is spread evenly across coordinates, the two bounds match. For one-hot gradients that hit coordinate ii with probability pip_i, the expected ratio of the two bounds is at most ∑ipi/d\sum_i \sqrt{p_i}/\sqrt{d} (Exercise 2). For uniform pip_i this ratio is 1.001.00 even though every individual gradient is sparse, whereas for word frequencies following Zipf's law with exponent 11 at d=104d = 10^4 it drops to 0.630.63. 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 σ2\sigma^2, the sum grows as st,i≈σ2ts_{t,i} \approx \sigma^2 t, so the effective step size shrinks as η/(σt)\eta/(\sigma\sqrt{t}). AdaGrad thus carries a built-in decay schedule tied to the step count rather than to optimization progress. That 1/t1/\sqrt{t} 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:

vt=β2 vt−1+(1−β2) gt2,xt+1=xt−ηvt+ϵ gt.(23.5.2)\mathbf{v}_t = \beta_2\, \mathbf{v}_{t-1} + (1 - \beta_2)\, \mathbf{g}_t^2, \qquad \mathbf{x}_{t+1} = \mathbf{x}_t - \frac{\eta}{\sqrt{\mathbf{v}_t} + \epsilon}\, \mathbf{g}_t . \tag{23.5.2}

Unrolling the recursion shows that vt\mathbf{v}_t assigns the squared gradient from kk steps ago the weight (1−β2)β2k(1 - \beta_2)\beta_2^k, so old gradients halve in weight roughly every log⁡2/(1−β2)\log 2/(1 - \beta_2) steps—every 7 steps at RMSProp's customary β2=0.9\beta_2 = 0.9, and every 693 steps at β2=0.999\beta_2 = 0.999. 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

mt=β1 mt−1+(1−β1) gt,m^t=mt/(1−β1t),vt=β2 vt−1+(1−β2) gt2,v^t=vt/(1−β2t),xt+1=xt−η  m^tv^t+ϵ,(23.5.3)\begin{aligned} \mathbf{m}_t &= \beta_1\, \mathbf{m}_{t-1} + (1 - \beta_1)\, \mathbf{g}_t, \qquad & \hat{\mathbf{m}}_t &= \mathbf{m}_t / (1 - \beta_1^t), \\ \mathbf{v}_t &= \beta_2\, \mathbf{v}_{t-1} + (1 - \beta_2)\, \mathbf{g}_t^2, \qquad & \hat{\mathbf{v}}_t &= \mathbf{v}_t / (1 - \beta_2^t), \\ \mathbf{x}_{t+1} &= \mathbf{x}_t - \eta\; \frac{\hat{\mathbf{m}}_t}{\sqrt{\hat{\mathbf{v}}_t} + \epsilon}, \end{aligned} \tag{23.5.3}

with m0=v0=0\mathbf{m}_0 = \mathbf{v}_0 = \mathbf{0} and the standard defaults β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999, and ϵ=10−8\epsilon = 10^{-8}. The first moment mt\mathbf{m}_t is the heavy-ball velocity of Section 23.1.3 scaled by 1−β11 - \beta_1, which turns a running sum into a weighted average and smooths the minibatch noise that plain RMSProp steps along directly.

Dividing by 1−β2t1 - \beta_2^t compensates for starting from v0=0\mathbf{v}_0 = \mathbf{0}. Unrolling the recursion gives vt=(1−β2)∑τ≤tβ2 t−τ gτ2\mathbf{v}_t = (1 - \beta_2) \sum_{\tau \le t} \beta_2^{\,t-\tau}\, \mathbf{g}_\tau^2. If the squared-gradient scale is stationary, with E[gτ2]=g2‾\mathbb{E}[\mathbf{g}_\tau^2] = \overline{\mathbf{g}^2} for every τ\tau, summing the geometric series yields

E[vt]=(1−β2) g2‾∑τ=1tβ2 t−τ=(1−β2t)g2‾.(23.5.4)\mathbb{E}[\mathbf{v}_t] = (1 - \beta_2)\, \overline{\mathbf{g}^2} \sum_{\tau=1}^{t} \beta_2^{\,t-\tau} = \left(1 - \beta_2^t\right) \overline{\mathbf{g}^2} . \tag{23.5.4}

Thus v^t\hat{\mathbf{v}}_t is an unbiased estimate of g2‾\overline{\mathbf{g}^2} at every step tt under stationarity, and the same calculation with β1\beta_1 shows that m^t\hat{\mathbf{m}}_t is unbiased for the mean gradient.

Without this correction, the initialization deficit is both large and long-lived: at the default β2=0.999\beta_2 = 0.999, v10\mathbf{v}_{10} captures only about 1%1\% of its stationary target, and even at t=1000t = 1000 it has reached just 63%63\% (Section 9.5). More striking is how the error evolves over time. Dropping both bias corrections mis-scales the update mt/vt\mathbf{m}_t/\sqrt{\mathbf{v}_t} by the factor (1−β1t)/1−β2t(1 - \beta_1^t)/\sqrt{1 - \beta_2^t}, which starts at 3.163.16 at t=1t = 1 and, perhaps surprisingly, climbs to a peak of 6.66.6 at t=12t = 12. 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.

Figure 23.5.1:

Bias correction in Adam. Left: starting from zero, the running average vt\mathbf{v}_t captures only the fraction 1−β2t1-\beta_2^t of the squared-gradient scale (63%63\% at t=1000t=1000 for β2=0.999\beta_2=0.999); dividing by 1−β2t1-\beta_2^t restores the full scale at every step. Right: without bias correction, the update mt/vt\mathbf{m}_t/\sqrt{\mathbf{v}_t} is inflated by (1−β1t)/1−β2t(1-\beta_1^t)/\sqrt{1-\beta_2^t}, starting at 3.163.16 at t=1t=1, peaking at 6.66.6 at t=12t=12 as the numerator fills in ten steps while the denominator takes a thousand, and returning to 11 only on the 1/(1−β2)1/(1-\beta_2) timescale. Uncorrected Adam thus takes its largest steps when its preconditioner rests on the fewest gradients.

Even an unbiased v^t\hat{\mathbf{v}}_t does not make the step size itself unbiased. Because Adam divides by v^t\sqrt{\hat{\mathbf{v}}_t} rather than v^t\hat{\mathbf{v}}_t, concavity of the square root biases the denominator downward: by Jensen's inequality, Ev^t<E[v^t]\mathbb{E}\sqrt{\hat{v}_t} \lt \sqrt{\mathbb{E}[\hat{v}_t]} unless v^t\hat{v}_t is constant. The first step is the extreme case. At t=1t = 1, m^1=g1\hat{m}_1 = g_1 and v^1=∣g1∣\sqrt{\hat{v}_1} = |g_1|, so the ratio is sign(g1)\mathrm{sign}(g_1) and the step has magnitude η\eta in every coordinate, whatever the gradient, rather than η ∣g1∣/σ\eta\,|g_1|/\sigma for a gradient of scale σ\sigma. We examine how much this matters in Section 23.5.4.

23.5.1.5 Scale Invariance#

In our opening example, h2=1000 h1h_2 = 1000\, h_1, 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 ϵ=0\epsilon = 0 and let C=diag(c1,…,cd)\mathbf{C} = \mathrm{diag}(c_1, \ldots, c_d) with every ci>0c_i > 0. Suppose two problems have gradients related by ∇f~(x)=C ∇f(x)\nabla \tilde{f}(\mathbf{x}) = \mathbf{C}\, \nabla f(\mathbf{x}) at every x\mathbf{x}. Then Adam with the same β1\beta_1, β2\beta_2, 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 ii's gradient rescaled by a positive constant cic_i. We denote its quantities with a tilde.

Proof. We proceed by induction on tt. Suppose the iterates agree up to xt\mathbf{x}_t. Then g~τ=Cgτ\tilde{\mathbf{g}}_\tau = \mathbf{C}\mathbf{g}_\tau for every τ≤t\tau \le t. Because the recursions for m\mathbf{m} and v\mathbf{v} are linear in gτ\mathbf{g}_\tau and gτ2\mathbf{g}_\tau^2, we obtain m~t,i=cimt,i\tilde{m}_{t,i} = c_i m_{t,i} and v~t,i=ci2vt,i\tilde{v}_{t,i} = c_i^2 v_{t,i}. The bias-correction denominators are the same scalars in both problems, so the corrected ratio m^t,i/v^t,i\hat{m}_{t,i}/\sqrt{\hat{v}_{t,i}} of the second problem is cim^t,i/(civ^t,i)=m^t,i/v^t,ic_i \hat{m}_{t,i}/(c_i \sqrt{\hat{v}_{t,i}}) = \hat{m}_{t,i}/\sqrt{\hat{v}_{t,i}}. The updates therefore coincide, giving x~t+1=xt+1\tilde{\mathbf{x}}_{t+1} = \mathbf{x}_{t+1}. ■\blacksquare

On the diagonal quadratic, ∇f(x)=diag(h) x\nabla f(\mathbf{x}) = \mathrm{diag}(h)\,\mathbf{x} is simply the gradient of the round bowl 12∥x∥2\tfrac12\|\mathbf{x}\|^2 multiplied by C=diag(h)\mathbf{C} = \mathrm{diag}(h). Consequently, Adam on the 1000:11000{:}1 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 12x2\tfrac12 x^2,

xt+1=xt(1−ηv^t)(β1=0),x_{t+1} = x_t \Bigl(1 - \frac{\eta}{\sqrt{\hat{v}_t}}\Bigr) \qquad (\beta_1 = 0),

where v^t\hat{v}_t averages the past squares xτ2x_\tau^2 for τ≤t\tau \le t. Because earlier iterates were larger, v^t\sqrt{\hat{v}_t} exceeds ∣xt∣|x_t| from the second step onward, so each update moves by less than η\eta and contracts geometrically by the factor 1−η/v^t1 - \eta/\sqrt{\hat{v}_t}. At η=0.1\eta = 0.1, this factor tightens from 0.90.9 at t=1t = 1 to 0.670.67 at t=48t = 48 as v^t\hat{v}_t catches up with the shrinking iterates. The iterates themselves are completely independent of h2/h1h_2/h_1. Only the stopping test depends on the curvature ratio, because f(xt)=12(h1+h2) xt2f(\mathbf{x}_t) = \tfrac12(h_1 + h_2)\, x_t^2 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 κ\kappa.

What the step count does depend on is the starting distance measured in units of η\eta, since the early steps have length roughly η\eta 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, ϵ>0\epsilon > 0 breaks the symmetry once a coordinate's gradients shrink to the order of ϵ\epsilon. 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 η sign(gt)\eta\,\mathrm{sign}(\mathbf{g}_t) in only three special cases—at t=1t = 1; when β1=β2=0\beta_1 = \beta_2 = 0 (Exercise 5d); and, for β1=0\beta_1 = 0, whenever each coordinate's gradient magnitude stays constant over the memory of v^\hat{\mathbf{v}}.

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 β1=0\beta_1 = 0, which only rescales; and Adam with its default momentum β1=0.9\beta_1 = 0.9. To rotate the problem by an angle θ\theta, we replace diag(h)\mathrm{diag}(h) with Aθ=Rθ diag(h) Rθ⊤\mathbf{A}_\theta = \mathbf{R}_\theta\, \mathrm{diag}(h)\, \mathbf{R}_\theta^\top, where Rθ\mathbf{R}_\theta is the 2×22 \times 2 rotation matrix, and rotate the starting point alongside it, x0=Rθ(1,1)⊤\mathbf{x}_0 = \mathbf{R}_\theta (1, 1)^\top, so that the initial point retains the same components along both curvature axes. At θ=π/4\theta = \pi/4, this gives A=(500.5−499.5−499.5500.5)\mathbf{A} = \left(\begin{smallmatrix}500.5 & -499.5\\ -499.5 & 500.5\end{smallmatrix}\right). 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 11 and 10001000. 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 0.0020.002 to 22 (spaced by factors of about three), reading each row at its best entry. The grid deliberately skips η=1\eta = 1: because Adam's first step has length η\eta in every coordinate (Section 23.5.4), starting at (1,1)(1, 1) with η=1\eta = 1 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 (β1=0\beta_1 = 0) 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 1/η1/\eta, because the early steps have length about η\eta 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 +η/2+\eta/2 and −η/2-\eta/2. Adam has thus traded one unknown (the curvature) for another: the distance to the minimizer in units of η\eta.

Adding Adam's default momentum (β1=0.9\beta_1 = 0.9) brings the count to between 165 and 205 steps across the entire range of step sizes from 0.020.02 to 22. Two features stand out. The first is robustness: a hundredfold change in η\eta 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 0.1%0.1\% of its stability limit (2+2β)/λmax⁡(2 + 2\beta)/\lambda_{\max} (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 β\sqrt\beta contraction limit from Section 23.1.3: an iteration with momentum β\beta contracts any mode with complex roots at rate β\sqrt\beta 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 β1=0.9\beta_1 = 0.9, the contraction factor is 0.9≈0.95\sqrt{0.9} \approx 0.95 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 η=2\eta = 2, 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 η/v^t\eta/\sqrt{\hat{\mathbf{v}}_t} of scaling-only Adam (ϵ=0\epsilon = 0, η=0.1\eta = 0.1). 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 1000:11000{:}1—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 0.10.1 to 0.330.33 as v^t\hat{v}_t adapts to the shrinking gradients. Raising the curvature ratio from 11 to 10310^3 to 10510^5 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 η\eta, and barely feels the curvature at all.

Why is a 45∘45^\circ rotation fatal to all of this? The rotated matrix has diagonal entries near 500500, and its steep direction (−1,1)/2(-1, 1)/\sqrt{2} 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 v^\hat{v} 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 (β1=0\beta_1 = 0) thus reverts to gradient descent whose step size is dictated by the steep mode, leaving the flat mode to crawl. Adam with β1=0.9\beta_1 = 0.9 reverts to heavy ball: its momentum is close to the optimal 0.880.88, but its effective step η/v^t\eta/\sqrt{\hat{v}_t} 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, v^\hat{\mathbf{v}} decreases and the effective step size grows until it crosses the stability limit 2/hmax⁡2/h_{\max} of the steep mode. At η=0.2\eta = 0.2—the optimal step size for the aligned valley—the loss drops to about 10−310^{-3} around t=1,700t = 1{,}700, at which point the steep mode begins to oscillate. That steady oscillation locks the gradient magnitude in place, driving v^t→gt2\hat{\mathbf{v}}_t \to \mathbf{g}_t^2 so that the update collapses to the sign step η sign(gt)\eta\,\mathrm{sign}(\mathbf{g}_t) of length η2\eta\sqrt{2} across the valley. The iterate is trapped forever in a two-cycle of amplitude η/2\eta/\sqrt{2} with loss f=250 η2=10f = 250\,\eta^2 = 10 (Exercise 5 verifies this formula across the step-size grid). Momentum averages out these alternating steps, which is why the β1=0.9\beta_1 = 0.9 runs eventually reach the target tolerance. Figure 23.5.2 illustrates all three behaviors on a valley shallow enough to plot clearly.

Figure 23.5.2:

Comparison on a two-dimensional valley (κ=20\kappa=20; the text's runs use κ=103\kappa=10^3, 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 β1=0\beta_1=0) moves both coordinates at the same speed and curves smoothly into the minimum. (c) Rotating the valley and starting point by 45∘45^\circ misaligns the coordinate axes from the curvature directions, leaving the iterate creeping along the valley floor (f=0.19f=0.19 after 40 steps, versus 4×10−74\times10^{-7} 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 gτgτ⊤\mathbf{g}_\tau\mathbf{g}_\tau^\top 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 C>2C > 2 and consider online optimization over x∈[−1,1]x \in [-1, 1] with the periodic losses

ft(x)={C x,t mod 3=1,−x,otherwise.(23.5.5)f_t(x) = \begin{cases} C\,x, & t \bmod 3 = 1, \\ -x, & \textrm{otherwise}. \end{cases} \tag{23.5.5}

Run Adam without bias correction, with β1=0\beta_1 = 0, β2=1/(1+C2)\beta_2 = 1/(1 + C^2), step sizes ηt=η/t\eta_t = \eta/\sqrt{t} satisfying η<1−β2\eta \lt \sqrt{1 - \beta_2}, and projection of each iterate back onto [−1,1][-1, 1], starting from x1=1x_1 = 1. Then xt>0x_t > 0 for every tt and x3k+1=1x_{3k+1} = 1 for every k≥0k \ge 0. Each three-step period adds at least 2C−4>02C - 4 > 0 to the regret, so the average regret never tends to zero. (Reddi et al., 2018)

Here, projection onto [−1,1][-1, 1] is simply clipping (Section 23.6 treats projection in general). Because the gradients over each three-step period sum to C−2>0C - 2 > 0, the best fixed point in hindsight is x⋆=−1x^\star = -1. Yet Adam returns to x=+1x = +1, the worst point in the interval, at the start of every period. Each period costs Adam at least C−2C - 2 (it incurs CC on the first step at x=1x = 1, and at least −1-1 on each of the other two), whereas x⋆=−1x^\star = -1 incurs −(C−2)-(C - 2), producing a regret increment of at least 2C−42C - 4 per period. The proof proceeds by induction over periods; Exercise 3 works through the key step, where η<1−β2\eta \lt \sqrt{1 - \beta_2} ensures that the downward step stays inside (0,1](0, 1]. Nor is this failure an artifact of setting β1=0\beta_1 = 0: the same paper constructs, for every fixed pair with β1<β2\beta_1 \lt \sqrt{\beta_2}, 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 C=4C = 4 and β2=1/17\beta_2 = 1/17, once vv has settled into its steady periodic cycle. Following the gradients +4,−1,−1+4, -1, -1, the second-moment estimate vv takes the values 15.1215.12, 1.831.83, and 1.051.05, so v\sqrt{v} is 3.893.89, 1.351.35, and 1.021.02. The three resulting displacements −ηgt/vt-\eta g_t/\sqrt{v_t} are

−1.03 η,+0.74 η,+0.98 η,-1.03\,\eta, \qquad +0.74\,\eta, \qquad +0.98\,\eta,

yielding a net drift of +0.69 η+0.69\,\eta per period toward +1+1. Normalization caps the rare large gradient +C+C to a move of roughly η\eta—barely larger than the move from a gradient of size 11—and vv forgets the C2C^2 spike within two steps. Together, the two −1-1 gradients therefore push xx farther upward than the single +C+C gradient pulls it downward. By contrast, plain SGD with step ηgt/C\eta g_t/C moves by −η-\eta, +0.25 η+0.25\,\eta, and +0.25 η+0.25\,\eta, for a net −0.5 η-0.5\,\eta 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 +1+1 at every step size.

To repair this flaw, Reddi et al. (2018) proposed AMSGrad, which replaces vt\mathbf{v}_t in the denominator with its running maximum v~t=max⁡(v~t−1,vt)\tilde{\mathbf{v}}_t = \max(\tilde{\mathbf{v}}_{t-1}, \mathbf{v}_t) of the uncorrected average. The effective step ηt/v~t\eta_t/\sqrt{\tilde{v}_t} is then nonincreasing, so a large gradient is never forgotten. In our periodic example, v~\tilde{v} remains pinned at 15.1215.12 throughout, changing the three displacements to −1.03 η-1.03\,\eta, +0.26 η+0.26\,\eta, and +0.26 η+0.26\,\eta—a net −0.51 η-0.51\,\eta toward the optimum. Adam should therefore converge to +1+1, while AMSGrad and SGD converge to −1-1. The cell below tests all three with the same 1/t1/\sqrt{t} decay starting from x=0x = 0, 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 η\eta in the proposition, and η=0.5<16/17\eta = 0.5 \lt \sqrt{16/17}, so the step-size hypothesis holds. Even from the midpoint of the interval, Adam still marches straight to +1+1: from t≈300t \approx 300 onward it returns to +1+1 at every period and never drops below 0.970.97. Meanwhile, AMSGrad and SGD steadily approach the optimum −1-1 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 ℓ2\ell_2 penalty λ2∥w∥2\tfrac{\lambda}{2}\|\mathbf{w}\|^2 to the loss adds λw\lambda \mathbf{w} to the gradient, and the resulting update wt−η (gt+λwt)=(1−ηλ) wt−η gt\mathbf{w}_t - \eta\,(\mathbf{g}_t + \lambda \mathbf{w}_t) = (1 - \eta\lambda)\, \mathbf{w}_t - \eta\, \mathbf{g}_t is simultaneously a gradient step on the loss and a uniform shrinkage of the weights (Section 9.5.3, which writes x\mathbf{x} for the weights). Inside Adam, however, those two mechanisms diverge. Feeding the penalized gradient into (23.5.3) and isolating the decay term (setting β1=0\beta_1 = 0 for clarity, so the update is −η (gt+λwt)/(v^t+ϵ)-\eta\,(\mathbf{g}_t + \lambda\mathbf{w}_t)/(\sqrt{\hat{\mathbf{v}}_t} + \epsilon)), the per-step shrinkage of coordinate ii becomes

coupled (ℓ2 through Adam):η λv^t,i+ϵ  wt,iversusdecoupled:η λ wt,i.(23.5.6)\textrm{coupled ($\ell_2$ through Adam):}\quad \frac{\eta\,\lambda}{\sqrt{\hat{v}_{t,i}} + \epsilon}\; w_{t,i} \qquad \textrm{versus} \qquad \textrm{decoupled:}\quad \eta\,\lambda\, w_{t,i} . \tag{23.5.6}

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:

wt+1=(1−ηλ) wt−η  m^tv^t+ϵ.(23.5.7)\mathbf{w}_{t+1} = (1 - \eta\lambda)\, \mathbf{w}_t - \eta\; \frac{\hat{\mathbf{m}}_t}{\sqrt{\hat{\mathbf{v}}_t} + \epsilon}. \tag{23.5.7}

Every coordinate now shrinks by the same factor 1−ηλ1 - \eta\lambda per step, just as in SGD, and the moment averages track only the loss gradient.

torch.optim.Adam(weight_decay=...) adds λw\lambda\mathbf{w} 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 σ\sigma, then v^≈σ\sqrt{\hat{v}} \approx \sigma, so we expect coupled Adam to shrink the weight to roughly e−ηλT/σe^{-\eta\lambda T/\sigma} after TT steps, whereas AdamW should shrink every weight to (1−ηλ)T(1 - \eta\lambda)^T regardless of σ\sigma. Below, we initialize 10410^4 weights with noise scale σ=10\sigma = 10 and 10410^4 with σ=0.1\sigma = 0.1, all at w=1w = 1, run 4,000 steps of each method with η=10−3\eta = 10^{-3} and λ=0.1\lambda = 0.1, 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 λ\lambda gives the two groups coupled decay rates of 10−510^{-5} and 10−310^{-3} per step—a hundredfold difference. The noisy weights retain 0.960.96 of their initial magnitude as predicted, while the quiet weights drop to about 0.030.03, slightly above the 0.0180.018 estimate. That small shortfall has a straightforward cause: near w=1w = 1, the penalty gradient λw=0.1\lambda w = 0.1 on a quiet weight is comparable to its noise and inflates its own v^\hat{v}, slowing its initial decay. Under AdamW, by contrast, both groups finish right at 0.67=(1−ηλ)40000.67 = (1 - \eta\lambda)^{4000}. 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 λ\lambda takes on a surprisingly different meaning.

Proposition (fixed points of coupled and decoupled decay). Let the gradient g(w)=∇ℓ(w)\mathbf{g}(\mathbf{w}) = \nabla\ell(\mathbf{w}) of a loss ℓ\ell be exact (noiseless), let ϵ>0\epsilon > 0, and call w\mathbf{w} a fixed point of an update if the update vanishes there once the moment estimates have settled. (a) Adam on ℓ+λ2∥w∥2\ell + \tfrac{\lambda}{2}\|\mathbf{w}\|^2 has a fixed point at w\mathbf{w} if and only if ∇ℓ(w)+λw=0\nabla\ell(\mathbf{w}) + \lambda\mathbf{w} = \mathbf{0}, the same stationary point as SGD on the penalized loss. (b) AdamW has a fixed point at w\mathbf{w} if and only if, for every coordinate ii,

λ wi(∣gi∣+ϵ)=−gi,gi=∂iℓ(w).(23.5.8)\lambda\, w_i \bigl(|g_i| + \epsilon\bigr) = -g_i , \qquad g_i = \partial_i \ell(\mathbf{w}). \tag{23.5.8}

Every fixed point of AdamW therefore lies strictly inside the box ∣wi∣<1/λ|w_i| \lt 1/\lambda, and as ϵ→0\epsilon \to 0 the condition reduces to a dichotomy: either gi=0g_i = 0, or ∣wi∣=1/λ|w_i| = 1/\lambda with wiw_i opposite in sign to gig_i.

Proof. At a fixed point, the vector u\mathbf{u} fed into the moment averages is constant, so m^t→u\hat{\mathbf{m}}_t \to \mathbf{u} and v^t→u2\hat{\mathbf{v}}_t \to \mathbf{u}^2. (a) For coupled Adam, u=g+λw\mathbf{u} = \mathbf{g} + \lambda\mathbf{w}, and coordinate ii's update approaches −η ui/(∣ui∣+ϵ)-\eta\, u_i/(|u_i| + \epsilon), which vanishes if and only if ui=0u_i = 0. (b) For AdamW, u=g\mathbf{u} = \mathbf{g}, so coordinate ii's update approaches −ηλwi−η gi/(∣gi∣+ϵ)-\eta\lambda w_i - \eta\, g_i/(|g_i| + \epsilon); setting this to zero and multiplying through by (∣gi∣+ϵ)/η(|g_i| + \epsilon)/\eta yields (23.5.8). Taking absolute values gives ∣wi∣=∣gi∣/(λ(∣gi∣+ϵ))<1/λ|w_i| = |g_i|/\bigl(\lambda(|g_i| + \epsilon)\bigr) \lt 1/\lambda. Letting ϵ→0\epsilon \to 0 turns the condition into λwi∣gi∣=−gi\lambda w_i |g_i| = -g_i, which holds precisely when gi=0g_i = 0 or λwi=−sign(gi)\lambda w_i = -\mathrm{sign}(g_i). ■\blacksquare

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 1−λ∣wi∣=ϵ/(∣gi∣+ϵ)1 - \lambda|w_i| = \epsilon/(|g_i| + \epsilon), at ϵ=10−8\epsilon = 10^{-8} every coordinate either sits within a fraction ϵ/∣gi∣\epsilon/|g_i| of the box boundary or has a gradient of order ϵ\epsilon.

A one-dimensional example makes the contrast concrete. Consider ℓ(w)=12(w−3)2\ell(w) = \tfrac12 (w - 3)^2, whose unconstrained minimizer is w=3w = 3. With λ=14\lambda = \tfrac14, coupled Adam rests at the penalized minimizer 3/(1+λ)=2.43/(1 + \lambda) = 2.4, whereas AdamW rests at 3.03.0: the box ∣w∣≤4|w| \le 4 does not bind, so decoupled decay leaves the minimizer untouched. With λ=1\lambda = 1, coupled Adam rests at 1.51.5, while AdamW is pinned at 1.01.0, right on the boundary of the box.

The two interpretations of λ\lambda 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 λ\lambda into the radius 1/λ1/\lambda of an ℓ∞\ell_\infty constraint box (Xie and Li, 2024). Exercise 6 connects this box directly to constrained optimization.

23.5.4 Warmup#

At step t=1t = 1, Adam's bias-corrected moments are m^1=g1\hat{\mathbf{m}}_1 = \mathbf{g}_1 and v^1=g12\hat{\mathbf{v}}_1 = \mathbf{g}_1^2, so the update is simply η sign(g1)\eta\,\mathrm{sign}(\mathbf{g}_1)—a step of full size η\eta in every coordinate. A coordinate whose gradient is 10−610^{-6} moves just as far as one whose gradient is 10310^3, 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 v^t\hat{\mathbf{v}}_t, which at t=1t = 1 rests on a single sample. A simple experiment shows that something else is at work.

Is a step of size η\eta actually too large? Not for a coordinate with a consistent gradient, whose steady-state step is also η\eta. For a coordinate whose gradient is pure noise, however, it is wasted motion. To measure how large that wasted motion is, we draw 2×1042 \times 10^4 independent gradient coordinates from N(0,1)\mathcal{N}(0, 1) at each step, run default Adam, and track the root-mean-square update in units of η\eta. We compare four curves: standard Adam; Adam with v^t\hat{\mathbf{v}}_t replaced by the exact variance σ2=1\sigma^2 = 1 (eliminating preconditioner estimation error entirely); Adam with both bias corrections removed; and Adam multiplied by a linear warmup over the first 2020 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 1.00 η1.00\,\eta, drops to 0.33 η0.33\,\eta by t=10t = 10, and settles within about fifty steps at (1−β1)/(1+β1) η=0.23 η\sqrt{(1 - \beta_1)/(1 + \beta_1)}\,\eta = 0.23\,\eta—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 v^t\hat{\mathbf{v}}_t with the exact variance leaves the RMS update unchanged to within 0.010.01 at every step (the sampling noise of 2×1042 \times 10^4 coordinates). The fourfold inflation comes from the momentum average, which needs roughly 1/(1−β1)=101/(1 - \beta_1) = 10 steps to average out independent noise. What the preconditioner actually does at t=1t = 1 is equalize coordinates of different scales, an effect hidden when every coordinate shares σ=1\sigma = 1.

Bias correction matters far more. Without it, the opening update jumps to 3.16 η3.16\,\eta—matching the (1−β1)/1−β2(1 - \beta_1)/\sqrt{1 - \beta_2} factor in Figure 23.5.1—and the transient stretches from ten steps to hundreds: the update is still around 0.75 η0.75\,\eta at t=100t = 100 and 0.29 η0.29\,\eta at t=1000t = 1000, because the uncorrected vt\mathbf{v}_t fills on the slow 1/(1−β2)=10001/(1 - \beta_2) = 1000 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 2020 steps tames what remains, keeping the warmup curve below 0.26 η0.26\,\eta 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 2/λmax⁡2/\lambda_{\max} 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 xt+1=xt−η Pt−1gt\mathbf{x}_{t+1} = \mathbf{x}_t - \eta\, \mathbf{P}_t^{-1} \mathbf{g}_t for a positive definite matrix Pt\mathbf{P}_t: gradient descent uses P=I\mathbf{P} = \mathbf{I}, Newton's method uses the Hessian ∇2f\nabla^2 f, 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 4096×40964096 \times 4096 weight matrix already has 1.7×1071.7 \times 10^7 parameters; its full curvature matrix would contain 2.8×10142.8 \times 10^{14} 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 y=Wa\mathbf{y} = \mathbf{W}\mathbf{a} with weight matrix W∈Rm×n\mathbf{W} \in \mathbb{R}^{m \times n}, input a∈Rn\mathbf{a} \in \mathbb{R}^n, and output gradient δ=∂ℓ/∂y∈Rm\boldsymbol{\delta} = \partial\ell/\partial\mathbf{y} \in \mathbb{R}^m. The gradient with respect to W\mathbf{W} is the rank-one outer product δa⊤\boldsymbol{\delta}\mathbf{a}^\top. Writing vec(V)\mathrm{vec}(\mathbf{V}) for the vector obtained by stacking the columns of a matrix V\mathbf{V}, we have vec(δa⊤)=a⊗δ\mathrm{vec}(\boldsymbol{\delta}\mathbf{a}^\top) = \mathbf{a} \otimes \boldsymbol{\delta}, where the Kronecker product B⊗D\mathbf{B} \otimes \mathbf{D} is the block matrix whose (i,j)(i, j) block is bijDb_{ij}\mathbf{D}.

The outer-product curvature of this layer—the block of the Fisher information matrix E[∇log⁡p ∇log⁡p⊤]\mathbb{E}[\nabla\log p\,\nabla\log p^\top] (which we will study in Section 24.6) corresponding to W\mathbf{W}—is therefore E[(aa⊤)⊗(δδ⊤)]\mathbb{E}\bigl[(\mathbf{a}\mathbf{a}^\top) \otimes (\boldsymbol{\delta}\boldsymbol{\delta}^\top)\bigr]. K-FAC (Martens and Grosse, 2015) approximates this expectation by the Kronecker product Sin⊗Sout\mathbf{S}_{\mathrm{in}} \otimes \mathbf{S}_{\mathrm{out}}, where Sin=E[aa⊤]\mathbf{S}_{\mathrm{in}} = \mathbb{E}[\mathbf{a}\mathbf{a}^\top] is n×nn \times n and Sout=E[δδ⊤]\mathbf{S}_{\mathrm{out}} = \mathbb{E}[\boldsymbol{\delta}\boldsymbol{\delta}^\top] is m×mm \times m. 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,

(Sin⊗Sout)−1vec(V)=vec(Sout−1 V Sin−1).(23.5.9)\bigl(\mathbf{S}_{\mathrm{in}} \otimes \mathbf{S}_{\mathrm{out}}\bigr)^{-1} \mathrm{vec}(\mathbf{V}) = \mathrm{vec}\bigl(\mathbf{S}_{\mathrm{out}}^{-1}\, \mathbf{V}\, \mathbf{S}_{\mathrm{in}}^{-1}\bigr). \tag{23.5.9}

To verify this identity, write column jj of the product DVB\mathbf{D}\mathbf{V}\mathbf{B} as ∑kbkj Dvk\sum_k b_{kj}\, \mathbf{D}\mathbf{v}_k, where vk\mathbf{v}_k is column kk of V\mathbf{V}. Stacking these columns produces the block product (B⊤⊗D) vec(V)(\mathbf{B}^\top \otimes \mathbf{D})\,\mathrm{vec}(\mathbf{V}), so vec(DVB)=(B⊤⊗D) vec(V)\mathrm{vec}(\mathbf{D}\mathbf{V}\mathbf{B}) = (\mathbf{B}^\top \otimes \mathbf{D})\,\mathrm{vec}(\mathbf{V}). Using (B⊗D)−1=B−1⊗D−1(\mathbf{B} \otimes \mathbf{D})^{-1} = \mathbf{B}^{-1} \otimes \mathbf{D}^{-1} together with the symmetry of the factors, setting B=Sin−1\mathbf{B} = \mathbf{S}_{\mathrm{in}}^{-1} and D=Sout−1\mathbf{D} = \mathbf{S}_{\mathrm{out}}^{-1} yields (23.5.9). In this way, a curvature matrix with (mn)2(mn)^2 entries is inverted and applied through two modest inverses of sizes nn and mm. The cell below compares the storage and operation counts for our 4096×40964096 \times 4096 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 2.8×10142.8 \times 10^{14} entries down to 3.4×1073.4 \times 10^7, and cuts the inversion cost from 4.7×10214.7 \times 10^{21} operations to roughly 1.4×10111.4 \times 10^{11}.

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 G↦Pl−aG Pr−a\mathbf{G} \mapsto \mathbf{P}_{\mathrm{l}}^{-a}\mathbf{G}\,\mathbf{P}_{\mathrm{r}}^{-a} applied to a layer's gradient matrix G\mathbf{G} (bold, distinguishing it from the scalar gradient bound GG 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 a=1a = 1. 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 Pl=∑tGtGt⊤\mathbf{P}_{\mathrm{l}} = \sum_t \mathbf{G}_t\mathbf{G}_t^\top and Pr=∑tGt⊤Gt\mathbf{P}_{\mathrm{r}} = \sum_t \mathbf{G}_t^\top\mathbf{G}_t with a=14a = \tfrac14. Muon (Jordan et al., 2024) can be viewed as memoryless Shampoo: using only the current matrix G=UΣV⊤\mathbf{G} = \mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top (assumed square and invertible),

(GG⊤)−1/4 G (G⊤G)−1/4=UΣ−1/2 Σ Σ−1/2V⊤=UV⊤,\bigl(\mathbf{G}\mathbf{G}^\top\bigr)^{-1/4}\, \mathbf{G}\, \bigl(\mathbf{G}^\top\mathbf{G}\bigr)^{-1/4} = \mathbf{U}\boldsymbol{\Sigma}^{-1/2}\, \boldsymbol{\Sigma}\, \boldsymbol{\Sigma}^{-1/2}\mathbf{V}^\top = \mathbf{U}\mathbf{V}^\top ,

which is the polar factor of G\mathbf{G}. It preserves the singular vectors of G\mathbf{G} 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 ϵ=0\epsilon = 0, 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 45∘45^\circ, 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 ℓ2\ell_2 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 λ\lambda into the radius 1/λ1/\lambda of an ℓ∞\ell_\infty 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#

  1. AdaGrad from the metric view. Exercise 1b of Section 23.1 showed that the steepest descent direction under the norm ∥d∥P=d⊤Pd\|\mathbf{d}\|_{\mathbf{P}} = \sqrt{\mathbf{d}^\top \mathbf{P} \mathbf{d}} is proportional to −P−1∇f-\mathbf{P}^{-1}\nabla f.

    1. Set Pt=diag(st)+ϵI\mathbf{P}_t = \mathrm{diag}\bigl(\sqrt{\mathbf{s}_t}\bigr) + \epsilon \mathbf{I} with st=∑τ≤tgτ2\mathbf{s}_t = \sum_{\tau \le t} \mathbf{g}_\tau^2 and recover (23.5.1).
    2. Replace the objective ff by cfcf for a constant c>0c > 0 and set ϵ=0\epsilon = 0. How does the AdaGrad update change? How would it change if Pt\mathbf{P}_t were built from st\mathbf{s}_t instead of st\sqrt{\mathbf{s}_t}? Compare both with gradient descent and with Newton's method.
    3. Let the gradients of one coordinate be i.i.d. with E[gt,i2]=σ2\mathbb{E}[g_{t,i}^2] = \sigma^2. How fast does the effective step of that coordinate decay in tt under each of the two choices, and how does it depend on σ\sigma?
  2. Concentrated gradients and AdaGrad's bound. Up to constant factors, projected online gradient descent with a tuned global step has regret D2GTD_2 G \sqrt{T} on a convex set of Euclidean diameter D2D_2 when ∥gt∥≤G\|\mathbf{g}_t\| \le G (Exercise 4). Diagonal AdaGrad has regret D∞∑i=1d∑t=1Tgt,i2D_\infty \sum_{i=1}^{d} \sqrt{\sum_{t=1}^{T} g_{t,i}^2}, where D∞D_\infty is the diameter of the set in the ℓ∞\ell_\infty norm (Duchi et al., 2011). Take the box [−1,1]d[-1, 1]^d and one-hot gradients: at each step one coordinate ii, drawn independently with probability pip_i, receives the gradient +1+1 or −1-1, and all other coordinates receive 00.

    1. 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 ∑ipi/d\sum_i \sqrt{p_i}/\sqrt{d}.
    2. Evaluate the ratio for uniform pip_i and for Zipf frequencies pi∝i−αp_i \propto i^{-\alpha} with d=104d = 10^4 and α∈{1,2,3}\alpha \in \{1, 2, 3\}.
    3. Word frequencies in natural text follow Zipf's law with α≈1\alpha \approx 1, and your ratio there is about 0.630.63. How much of the factor d\sqrt{d} of Section 23.5.1 does a bag-of-words model obtain? Which distribution of gradient mass would obtain all of it?
  3. The Reddi example by hand. Take C=4C = 4, β1=0\beta_1 = 0, the proposition's β2=1/(1+C2)=1/17\beta_2 = 1/(1 + C^2) = 1/17, and no bias correction, as in online.

    1. Assume a fixed step η\eta, an iterate in the interior of [−1,1][-1, 1], and vtv_t settled into its periodic pattern. Write vav_a for the value of vv after the +C+C step, solve the three-step recursion for vav_a in closed form, and derive the periodic values 15.1215.12, 1.831.83, 1.051.05 and the three displacements of the text. Compute SGD's three steps ηgt/C\eta g_t/C. Which steps does Adam enlarge relative to SGD, and why?
    2. AMSGrad replaces vtv_t by v~t=max⁡(v~t−1,vt)\tilde{v}_t = \max(\tilde{v}_{t-1}, v_t). Show that its effective step ηt/v~t\eta_t/\sqrt{\tilde{v}_t} is nonincreasing in tt whenever ηt\eta_t is. Compute its three displacements in the periodic regime and show that the net displacement is −0.51 η-0.51\,\eta.
    3. The proposition needs η<1−β2\eta \lt \sqrt{1 - \beta_2} for the steps ηt=η/t\eta_t = \eta/\sqrt{t}. Show where this is used: starting a period at x=1x = 1, use v≥(1−β2)C2v \ge (1-\beta_2)C^2 after the +C+C gradient to show that the first step of the period lands in (0,1)(0, 1), so that the projection does not act on it.
  4. Regret of online gradient descent. ● Projected online gradient descent plays xt+1=ΠC(xt−ηtgt)\mathbf{x}_{t+1} = \Pi_{\mathcal{C}}(\mathbf{x}_t - \eta_t \mathbf{g}_t) with gt=∇ft(xt)\mathbf{g}_t = \nabla f_t(\mathbf{x}_t), where ΠC\Pi_{\mathcal{C}} is the Euclidean projection onto a closed convex set C\mathcal{C} of diameter DD, ∥gt∥≤G\|\mathbf{g}_t\| \le G, and the steps ηt\eta_t are nonincreasing (Zinkevich, 2003).

    1. Prove that the regret satisfies
∑t=1Tft(xt)−min⁡x∈C∑t=1Tft(x)  ≤  D22ηT+G22∑t=1Tηt.(23.5.10)\sum_{t=1}^{T} f_t(\mathbf{x}_t) - \min_{\mathbf{x} \in \mathcal{C}} \sum_{t=1}^{T} f_t(\mathbf{x}) \;\le\; \frac{D^2}{2\eta_T} + \frac{G^2}{2} \sum_{t=1}^{T} \eta_t. \tag{23.5.10}

Start from ft(xt)−ft(x)≤gt⊤(xt−x)f_t(\mathbf{x}_t) - f_t(\mathbf{x}) \le \mathbf{g}_t^\top(\mathbf{x}_t - \mathbf{x}) and use that the projection does not increase distances to points of C\mathcal{C}.

  1. Show that ηt=D/(Gt)\eta_t = D/(G\sqrt{t}) gives regret at most 32DGT\tfrac32 DG\sqrt{T}, and that for ηt=c/t\eta_t = c/t the bound grows linearly in TT for every c>0c > 0.
  2. Combine these two bounds with the decay rates of Exercise 1c to explain why AdaGrad divides by st\sqrt{\mathbf{s}_t} rather than by st\mathbf{s}_t.
  1. [code] Rotation sensitivity. ● Use rotated, run and the update factories of the #adaptive-stochastic-methods-adam-vs-gd cell.

    1. Show that the iterates of gradient descent and of heavy ball on Aθ\mathbf{A}_\theta from Rθ(1,1)⊤\mathbf{R}_\theta(1, 1)^\top are Rθ\mathbf{R}_\theta times their iterates on the aligned valley, so that their step counts do not depend on θ\theta.
    2. For β1=0\beta_1 = 0 at θ=π/4\theta = \pi/4, print ff after 40,00040{,}000 steps at each η\eta of the table's grid and compare it with the value 250 η2250\,\eta^2 of the text. Which component of Adam supplies what survives of its advantage over gradient descent?
    3. Print Adam's effective per-coordinate steps at θ=π/16\theta = \pi/16. Why does even this small rotation remove most of the step-size ratio that Adam builds on the aligned valley?
    4. Exercise 4 of Section 23.1 identifies −sign(g)-\mathrm{sign}(\mathbf{g}) as the steepest direction under the ℓ∞\ell_\infty norm and −UV⊤-\mathbf{U}\mathbf{V}^\top as the steepest direction under the spectral norm, where G=UΣV⊤\mathbf{G} = \mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top. Show that Adam with β1=β2=0\beta_1 = \beta_2 = 0 and ϵ=0\epsilon = 0 steps along −sign(gt)-\mathrm{sign}(\mathbf{g}_t). Then let Q1\mathbf{Q}_1 and Q2\mathbf{Q}_2 be orthogonal, show that the map G↦UV⊤\mathbf{G} \mapsto \mathbf{U}\mathbf{V}^\top commutes with G↦Q1GQ2\mathbf{G} \mapsto \mathbf{Q}_1 \mathbf{G} \mathbf{Q}_2, and give a 2×22 \times 2 example in which the sign map does not. What does this suggest about the rotation sensitivity of Muon compared with Adam?
  2. [extended] AdamW's implicit ℓ∞\ell_\infty constraint. ●● The proposition of Section 23.5.3 found that the fixed points of AdamW lie in the box ∣wi∣<1/λ|w_i| \lt 1/\lambda and, as ϵ→0\epsilon \to 0, on its boundary wherever the gradient does not vanish. Xie and Li (2024) prove that if full-batch AdamW with β1≤β2\beta_1 \le \beta_2 and a nonincreasing step schedule with divergent sum converges, its limit is a KKT point of min⁡wℓ(w)\min_{\mathbf{w}} \ell(\mathbf{w}) subject to ∥w∥∞≤1/λ\|\mathbf{w}\|_\infty \le 1/\lambda.

    1. A feasible w\mathbf{w} is a KKT point of this problem (Section 23.6 derives the conditions in general) when every coordinate satisfies ∂iℓ(w)=0\partial_i \ell(\mathbf{w}) = 0 if ∣wi∣<1/λ|w_i| \lt 1/\lambda and wi ∂iℓ(w)≤0w_i\, \partial_i \ell(\mathbf{w}) \le 0 if ∣wi∣=1/λ|w_i| = 1/\lambda. Show that at such a point no feasible direction decreases ℓ\ell to first order.
    2. Set ϵ=0\epsilon = 0, the setting of the theorem, in the AdamW condition (23.5.8). Show that a coordinate with ∂iℓ≠0\partial_i \ell \ne 0 satisfies the KKT conditions. Why does the condition alone not show ∣wi∣≤1/λ|w_i| \le 1/\lambda for a coordinate whose gradient vanishes?
    3. Generate linearly separable logistic-regression data with n=100n = 100, d=5d = 5, standard normal features, and labels yi=sign(xi⊤wtrue)y_i = \mathrm{sign}(\mathbf{x}_i^\top \mathbf{w}_{\mathrm{true}}), so that the unregularized loss has no finite minimizer. Run full-batch AdamW with ϵ=10−16\epsilon = 10^{-16} for 5×1045 \times 10^4 steps, with η\eta decaying from 10−210^{-2} to 00 by a cosine schedule, for λ∈{0.05,0.1,0.2}\lambda \in \{0.05, 0.1, 0.2\}. Compare the result with the solution of the box-constrained problem computed by projected gradient descent, which here clips every coordinate to [−1/λ,1/λ][-1/\lambda, 1/\lambda] after each gradient step, and with Adam on ℓ+λ2∥w∥2\ell + \tfrac{\lambda}{2}\|\mathbf{w}\|^2.
    4. Repeat the AdamW runs with minibatch gradients of size 1010 and 5050. Where does the iterate end up relative to the box, and why?
    5. What does λ\lambda control in AdamW according to these results, and how does that differ from the Gaussian-prior reading of λ\lambda in Section 24.6?
  3. The Kronecker identity and its cost. Use column stacking for vec\mathrm{vec}.

    1. Prove vec(DVB)=(B⊤⊗D) vec(V)\mathrm{vec}(\mathbf{D}\mathbf{V}\mathbf{B}) = (\mathbf{B}^\top \otimes \mathbf{D})\,\mathrm{vec}(\mathbf{V}) by writing out column jj of the product, and prove (B⊗D)(B′⊗D′)=(BB′)⊗(DD′)(\mathbf{B} \otimes \mathbf{D})(\mathbf{B}' \otimes \mathbf{D}') = (\mathbf{B}\mathbf{B}') \otimes (\mathbf{D}\mathbf{D}').
    2. Deduce (23.5.9) for symmetric invertible factors. Which formula replaces it for factors that are not symmetric, and which for row stacking?
    3. For an m×nm \times n layer, count the operations needed to invert the full mn×mnmn \times mn matrix and apply it, against inverting the two factors and applying them by (23.5.9) (O(m3+n3+mn(m+n))O(m^3 + n^3 + mn(m + n))). Evaluate both counts at m=n=4096m = n = 4096 and at m=4096m = 4096, n=16384n = 16384.
    4. For a single gradient G=UΣV⊤\mathbf{G} = \mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top, set Pl=GG⊤\mathbf{P}_{\mathrm{l}} = \mathbf{G}\mathbf{G}^\top and Pr=G⊤G\mathbf{P}_{\mathrm{r}} = \mathbf{G}^\top\mathbf{G}. Show that the Shampoo step Pl−1/4G Pr−1/4\mathbf{P}_{\mathrm{l}}^{-1/4}\mathbf{G}\,\mathbf{P}_{\mathrm{r}}^{-1/4} equals UV⊤\mathbf{U}\mathbf{V}^\top. What must the inverse fourth root mean when G\mathbf{G} is not square, and which singular vectors does the result keep?

Discussions