9.1 Landscapes and Gradient Descent

Underneath their differences in momentum, adaptive preconditioning, or learning-rate schedules, all standard deep learning optimizers iterate the same fundamental operation: evaluate the gradient of the loss and step in the opposite direction. Why does that step make rapid progress on some objective functions and crawl on others, and why does increasing the learning rate beyond a threshold cause sudden divergence?

A network with dd parameters defines an empirical risk f:Rd→Rf: \mathbb{R}^d \to \mathbb{R} over a dd-dimensional parameter vector x\mathbf{x}. While generalization ultimately depends on the expected risk on unseen data (Section 2.6.1), the primary task of an optimization algorithm is to reduce the empirical objective f(x)f(\mathbf{x}) as quickly and reliably as possible. Traditional accounts of non-convex optimization often emphasize the danger of getting trapped in poor local minima. In high-dimensional neural networks, however, two other geometric features dominate training dynamics: ill-conditioning (large disparities in curvature across different directions) and saddle points.

In this section, we first analyze gradient descent on an ill-conditioned two-dimensional quadratic valley to establish the exact relationship between curvature, the maximum stable learning rate, and the iteration count. We then examine critical points, saddle points, and plateaus in high-dimensional loss landscapes, prove the general descent guarantee for smooth functions, show how the learning rate selects among local minima by their sharpness (leading to the edge of stability in neural network training), and introduce preconditioning as a remedy for ill-conditioning.

9.1.1 Optimization Landscapes and the Condition Number#

To isolate the effect of uneven curvature, consider the two-dimensional quadratic objective

f(x)=0.1x12+2x22,(9.1.1)f(\mathbf{x}) = 0.1 x_1^2 + 2 x_2^2, \tag{9.1.1}

whose unique minimum lies at the origin. The second derivative (curvature) is λ1=0.2\lambda_1 = 0.2 along the flat axis x1x_1 and λ2=4\lambda_2 = 4 along the steep axis x2x_2, producing elongated elliptical level sets that form a narrow valley.

Gradient descent with learning rate η>0\eta > 0 updates the iterate via x←x−η∇f(x)\mathbf{x} \leftarrow \mathbf{x} - \eta \nabla f(\mathbf{x}). Because ∇f(x)=(0.2x1,4x2)\nabla f(\mathbf{x}) = (0.2 x_1, 4 x_2), the two coordinates decouple and evolve multiplicatively on each step:

x1←(1−0.2η) x1,x2←(1−4η) x2.\begin{aligned} x_1 &\leftarrow (1 - 0.2\eta)\, x_1, \\ x_2 &\leftarrow (1 - 4\eta)\, x_2. \end{aligned}

Each coordinate places a competing constraint on η\eta:

  • Stability ceiling (steep direction): The steep coordinate x2x_2 contracts if and only if ∣1−4η∣<1|1 - 4\eta| \lt 1, which imposes the hard stability ceiling η<0.5\eta \lt 0.5.
  • Convergence pace (flat direction): For any stable step size η<0.5\eta \lt 0.5, the flat contraction factor satisfies 1−0.2η>0.91 - 0.2\eta > 0.9, meaning that each step removes less than 10%10\% of the remaining error along x1x_1.

We save the valley objective f_valley, its gradient valley_grad, a two-dimensional trajectory runner train_2d starting from (−5,−2)(-5, -2), and the plain gradient descent step gd_2d in d2l so that subsequent sections can benchmark every optimizer on the exact same surface.

VALLEY_CURVATURES = (0.2, 4.0)
h1, h2 = VALLEY_CURVATURES  # Curvatures of the valley along x1 and x2

def f_valley(x1, x2):
    """The ill-conditioned quadratic valley h1/2 x1^2 + h2/2 x2^2, with
    (h1, h2) = VALLEY_CURVATURES."""
    h1, h2 = VALLEY_CURVATURES
    return h1 / 2 * x1 ** 2 + h2 / 2 * x2 ** 2

def valley_grad(x1, x2):
    """Gradient of f_valley."""
    h1, h2 = VALLEY_CURVATURES
    return h1 * x1, h2 * x2

def train_2d(trainer, f_grad, steps=20, **hparams):
    """Run a 2D update rule from (-5, -2) and return the iterates."""
    x1, x2, s1, s2 = -5, -2, 0, 0  # s1, s2: state of stateful optimizers
    results = [(x1, x2)]
    for _ in range(steps):
        x1, x2, s1, s2 = trainer(x1, x2, s1, s2, f_grad, **hparams)
        results.append((x1, x2))
    print(f'step {steps}, x1: {float(x1):f}, x2: {float(x2):f}')
    return results

def gd_2d(x1, x2, s1, s2, f_grad, eta):
    """One step of gradient descent in 2D; the state stays zero."""
    g1, g2 = f_grad(x1, x2)
    return x1 - eta * g1, x2 - eta * g2, 0, 0

At η=0.45\eta = 0.45, just below the stability ceiling, the steep multiplier is 1−4(0.45)=−0.81 - 4(0.45) = -0.8, so x2x_2 overshoots the valley floor and flips sign on every step while shrinking by 20%20\% in magnitude. Meanwhile, the flat multiplier is 1−0.2(0.45)=0.911 - 0.2(0.45) = 0.91, so after 3030 steps from (−5,−2)(-5, -2) the flat coordinate still remains near −5×0.9130≈−0.3-5 \times 0.91^{30} \approx -0.3.

h = np.array([0.2, 4.0])  # Curvatures h1, h2 along x1 and x2

def gd_valley(eta, steps, x0=(-5.0, -2.0)):
    """Gradient descent on the valley; returns all iterates."""
    xs = [np.array(x0)]
    for _ in range(steps):
        xs.append(xs[-1] - eta * h * xs[-1])  # The gradient is h * x
    return np.stack(xs)

xs = gd_valley(0.45, steps=30)
d2l.plot(np.arange(31), [xs[:, 0], xs[:, 1]], 'step', 'coordinate',
         legend=['$x_1$', '$x_2$'])

Sweeping η\eta across (0,0.5](0, 0.5] shows how the overall convergence time (measured by the number of steps required to bring both coordinates within 1%1\% of their initial distance from the origin) depends on balancing these two factors:

print('  eta   factor x1   factor x2   steps to 1%')
for eta in [0.1, 0.2, 0.3, 0.4, 0.45, 2 / 4.2, 0.49, 0.5]:
    xs = gd_valley(eta, steps=1000)
    done = np.all(np.abs(xs) <= 0.01 * np.abs(xs[0]), axis=1)
    steps = int(np.argmax(done)) if done.any() else 'never'
    print(f'{eta:5.3f}   {1 - 0.2 * eta:9.3f}   {1 - 4 * eta:9.3f}   '
          f'{steps:>11}')
  eta   factor x1   factor x2   steps to 1%
0.100       0.980       0.600           228
0.200       0.960       0.200           113
0.300       0.940      -0.200            75
0.400       0.920      -0.600            56
0.450       0.910      -0.800            49
0.476       0.905      -0.905            47
0.490       0.902      -0.960           113
0.500       0.900      -1.000         never

The optimal step size equates the magnitudes of the flat and steep multipliers, 1−0.2η=−(1−4η)1 - 0.2\eta = -(1 - 4\eta), yielding η⋆=2/4.2≈0.476\eta^\star = 2 / 4.2 \approx 0.476, where both factors have magnitude 0.9050.905 and convergence to 1%1\% takes 4747 steps. Notice the sharp asymmetry near the stability threshold: dropping slightly below η⋆\eta^\star to η=0.45\eta = 0.45 costs only two extra steps (4949), whereas pushing slightly above to η=0.49\eta = 0.49 more than doubles the step count (113113).

This analysis extends immediately to any dd-dimensional positive-definite quadratic f(x)=12x⊤Hxf(\mathbf{x}) = \frac{1}{2} \mathbf{x}^\top \mathbf{H} \mathbf{x} with symmetric Hessian H≻0\mathbf{H} \succ \mathbf{0}. Expanding x=∑i=1dcivi\mathbf{x} = \sum_{i=1}^d c_i \mathbf{v}_i in the orthonormal eigenbasis of H\mathbf{H} (where Hvi=λivi\mathbf{H}\mathbf{v}_i = \lambda_i \mathbf{v}_i and 0<λmin⁡=λ1≤⋯≤λd=λmax⁡0 \lt \lambda_{\min} = \lambda_1 \le \cdots \le \lambda_d = \lambda_{\max}) decouples the gradient descent step along each eigenvector:

(I−ηH)∑i=1dcivi=∑i=1d(1−ηλi) civi.(9.1.2)(\mathbf{I} - \eta\mathbf{H}) \sum_{i=1}^d c_i \mathbf{v}_i = \sum_{i=1}^d (1 - \eta\lambda_i)\, c_i \mathbf{v}_i. \tag{9.1.2}

Stability requires ∣1−ηλi∣<1|1 - \eta\lambda_i| \lt 1 for all ii, which is governed by the largest eigenvalue:

η<2λmax⁡.(9.1.3)\eta \lt \frac{2}{\lambda_{\max}}. \tag{9.1.3}

Subject to this ceiling, progress along the flattest eigenvector v1\mathbf{v}_1 depends only on the condition number

κ=λmax⁡λmin⁡.(9.1.4)\kappa = \frac{\lambda_{\max}}{\lambda_{\min}}. \tag{9.1.4}

Rescaling the objective ff by a constant c>0c > 0 multiplies all eigenvalues by cc and divides the stable learning rate by cc, leaving the trajectory invariant; the dimensionless ratio κ\kappa captures the intrinsic geometric difficulty of the surface. Balancing the extreme contraction factors 1−ηλmin⁡=−(1−ηλmax⁡)1 - \eta\lambda_{\min} = -(1 - \eta\lambda_{\max}) gives the optimal constant learning rate η⋆=2/(λmin⁡+λmax⁡)\eta^\star = 2 / (\lambda_{\min} + \lambda_{\max}) and worst-case per-step contraction factor (κ−1)/(κ+1)≈1−2/κ(\kappa - 1)/(\kappa + 1) \approx 1 - 2/\kappa (Section 23.1.2). Reducing the error by a factor ϵ\epsilon therefore requires

t≈κ2log⁡1ϵ(9.1.5)t \approx \frac{\kappa}{2} \log \frac{1}{\epsilon} \tag{9.1.5}

steps. On our valley (κ=4/0.2=20\kappa = 4 / 0.2 = 20, ϵ=0.01\epsilon = 0.01), this formula predicts 10log⁡100≈4610 \log 100 \approx 46 steps, matching the 4747 steps observed above. Because tt scales linearly with κ\kappa, no scalar learning rate can overcome ill-conditioning; accelerating convergence requires changing the update direction itself.

9.1.2 Critical Points, Saddle Points, and Plateaus#

Unlike a convex quadratic bowl, a neural network loss surface is non-convex and possesses many critical points where ∇f(x)=0\nabla f(\mathbf{x}) = \mathbf{0}, as well as plateaus where ∥∇f(x)∥\|\nabla f(\mathbf{x})\| is vanishingly small. At any critical point of a twice-differentiable function f:Rd→Rf: \mathbb{R}^d \to \mathbb{R}, the eigenvalues of the Hessian H=∇2f(x)\mathbf{H} = \nabla^2 f(\mathbf{x}) classify the local geometry:

  • Local minimum: all dd eigenvalues are strictly positive (H≻0\mathbf{H} \succ \mathbf{0}).
  • Local maximum: all dd eigenvalues are strictly negative (H≺0\mathbf{H} \prec \mathbf{0}).
  • Saddle point: H\mathbf{H} has both positive and negative eigenvalues, curving upward along some eigenvectors and downward along others, as illustrated by f(x,y)=x2−y2f(x, y) = x^2 - y^2 at the origin (Figure 9.1.1).
  • Degenerate critical point: H\mathbf{H} has zero eigenvalues and no eigenvalues of opposite sign, so higher-order derivatives determine whether the point is an extremum (like x4x^4) or an inflection point (like x3x^3).
Figure 9.1.1:

The saddle surface z=x2−y2z=x^2-y^2 has a minimum along xx and a maximum along yy (left), as shown in the two cross-sections through the origin (right).

In high dimensions, saddle points vastly outnumber local minima. For a critical point to be a local minimum, every one of the dd Hessian eigenvalues must be positive; under a simple random-sign heuristic, all dd eigenvalues are positive with probability 2−d2^{-d} (and random matrix theory confirms that symmetric random matrices have eigenvalues split evenly around zero until the baseline loss is very low; see Exercise 4). Empirical Hessian measurements on neural networks confirm that critical points at high loss are overwhelmingly saddle points with many negative eigenvalues, while the fraction of negative eigenvalues drops toward zero only at low loss values (Dauphin et al., 2014).

Crucially, strict saddle points (critical points with at least one negative eigenvalue λ<0\lambda \lt 0) do not trap gradient descent. Along a downward-curving eigenvector with curvature −μ<0-\mu \lt 0, each gradient step amplifies the displacement by (1+ημ)>1(1 + \eta\mu) > 1. The stable manifold of initializations that converge into a strict saddle has measure zero, so gradient descent from a random initialization escapes with probability one (Lee et al., 2016). Starting at distance δ\delta from the ridge, reaching distance 11 along the unstable direction takes log⁡(1/δ)/log⁡(1+ημ)≈log⁡(1/δ)/(ημ)\log(1/\delta)/\log(1 + \eta\mu) \approx \log(1/\delta)/(\eta\mu) steps—logarithmic in δ\delta, though inversely proportional to the negative curvature μ\mu. Moreover, minibatch gradient noise actively kicks iterates off the ridge even when δ=0\delta = 0 (Exercise 1).

Figure 9.1.2:

Minimizing f(x)=tanh⁡xf(x)=\tanh x from x=4x=4 stalls on an activation plateau where f′(4)≈0.0013f'(4) \approx 0.0013 despite the absence of any critical point.

By contrast, plateaus arise without any critical point when activation derivatives saturate, as in f(x)=tanh⁡(x)f(x) = \tanh(x) at x=4x = 4 (Figure 9.1.2), where f′(4)=1−tanh⁡2(4)≈0.0013f'(4) = 1 - \tanh^2(4) \approx 0.0013 causes gradient descent with η=1\eta = 1 to spend 370370 steps creeping from x=4x = 4 to x=2x = 2. In deep networks, such vanishing gradients (Section 4.4) are eliminated primarily by architectural design: non-saturating activations (Section 4.1.4), normalization layers (Section 7.3), and residual connections (Section 7.4), leaving ill-conditioning as the central challenge for the optimizer.

Even though a neural network loss is globally non-convex (for instance, permuting the dd hidden units of a layer yields d!d! distinct parameter vectors with identical loss whose average collapses to a single-unit network of higher loss; Exercise 3), its local geometry around any iterate is governed by its Hessian spectrum. Empirical spectra of deep networks exhibit a massive bulk of eigenvalues near zero alongside a few large positive outlier eigenvalues (Ghorbani et al., 2019). The largest eigenvalue, called the sharpness λmax⁡\lambda_{\max}, caps the stable learning rate, while the flat bulk progresses at rate ηλi≪1\eta\lambda_i \ll 1, reproducing the narrow-valley bottleneck in high dimensions.

9.1.3 The Descent Guarantee and Stability of Minima#

On a non-quadratic objective, curvature varies from point to point. Why does the 2/λmax⁡2/\lambda_{\max} rule still govern step-size stability?

By a first-order Taylor expansion f(x+ϵ)≈f(x)+ϵ⊤∇f(x)f(\mathbf{x} + \boldsymbol{\epsilon}) \approx f(\mathbf{x}) + \boldsymbol{\epsilon}^\top \nabla f(\mathbf{x}) and the Cauchy–Schwarz inequality, the negative gradient −∇f(x)-\nabla f(\mathbf{x}) is the direction of steepest local descent. To guarantee that a finite step x−η∇f(x)\mathbf{x} - \eta \nabla f(\mathbf{x}) actually decreases ff, suppose ff is LL-smooth, meaning its gradient is LL-Lipschitz continuous (in one variable, ∣f′(y)−f′(x)∣≤L∣y−x∣|f'(y) - f'(x)| \le L|y - x|, or ∣f′′(x)∣≤L|f''(x)| \le L). Integrating the slope difference along a step ϵ\epsilon bounds ff above by a touching parabola of curvature LL:

f(x+ϵ)−f(x)−ϵf′(x)=∫0ϵ(f′(x+s)−f′(x)) ds≤∫0ϵLs ds=L2ϵ2.\begin{aligned} f(x + \epsilon) - f(x) - \epsilon f'(x) &= \int_0^\epsilon \big(f'(x + s) - f'(x)\big)\, ds \\ &\leq \int_0^\epsilon L s \, ds = \frac{L}{2} \epsilon^2. \end{aligned}

Substituting the gradient step ϵ=−ηf′(x)\epsilon = -\eta f'(x) (or ϵ=−η∇f(x)\boldsymbol{\epsilon} = -\eta \nabla f(\mathbf{x}) in dd dimensions, where ∥∇2f(x)∥2≤L\|\nabla^2 f(\mathbf{x})\|_2 \le L; Section 23.1.1) yields the descent lemma:

f(x−η∇f(x))≤f(x)−η(1−ηL2)∥∇f(x)∥2.(9.1.6)f(\mathbf{x} - \eta \nabla f(\mathbf{x})) \leq f(\mathbf{x}) - \eta \Big(1 - \frac{\eta L}{2}\Big) \|\nabla f(\mathbf{x})\|^2. \tag{9.1.6}

Whenever 0<η<2/L0 \lt \eta \lt 2/L, every gradient step strictly decreases ff at any non-critical point, with the largest guaranteed single-step decrease ∥∇f(x)∥2/(2L)\|\nabla f(\mathbf{x})\|^2 / (2L) occurring at η=1/L\eta = 1/L.

Now invert this perspective: fix the learning rate η\eta on a loss surface with multiple local minima of different curvatures. Near any local minimum x⋆x^\star with curvature λ=f′′(x⋆)>0\lambda = f''(x^\star) > 0, a gradient step multiplies a small displacement x−x⋆x - x^\star by 1−ηλ1 - \eta\lambda. Consequently:

  • If λ<2/η\lambda \lt 2/\eta, then ∣1−ηλ∣<1|1 - \eta\lambda| \lt 1 and the minimum is linearly stable (attracting nearby iterates).
  • If λ>2/η\lambda > 2/\eta, then 1−ηλ<−11 - \eta\lambda \lt -1 and the minimum is unstable (repelling any iterate that does not land on x⋆x^\star exactly).

Thus, the learning rate η\eta filters local minima by their sharpness rather than their depth: gradient descent can only converge to minima whose sharpness satisfies λmax⁡≤2/η\lambda_{\max} \le 2/\eta. We can observe this selection directly on f(x)=xcos⁡(0.15πx)f(x) = x\cos(0.15\pi x), which has a deep, sharper minimum near x=7.27x = 7.27 (f′′≈1.81f'' \approx 1.81) and a shallower, flatter minimum near x=−1.83x = -1.83 (f′′≈0.98f'' \approx 0.98), as summarized in Table 9.1.1.

Table 9.1.1. Local curvature f′′f'' and per-step displacement multiplier 1−ηf′′1 - \eta f'' at the two minima of f(x)=xcos⁡(0.15πx)f(x) = x \cos(0.15\pi x).
MinimumCurvature f′′f''Multiplier at η=0.5\eta = 0.5Multiplier at η=2\eta = 2
Deep (x=7.27x = 7.27)1.811.810.090.09 (stable)−2.62-2.62 (unstable)
Shallow (x=−1.83x = -1.83)0.980.980.510.51 (stable)−0.96-0.96 (stable)

We first define the 1D gradient descent runner gd and trajectory plotter show_trace:

def gd(eta, f_grad, x=10.0, steps=10):
    """Gradient descent from x; returns all iterates."""
    xs = [x]
    for _ in range(steps):
        x = x - eta * f_grad(x)
        xs.append(float(x))
    return xs

def show_trace(f, *runs, legend=None):
    """Draw the iterates of one or more runs on the graph of f."""
    n = max(abs(x) for xs in runs for x in xs)
    grid = d2l.arange(-n, n, 0.01)
    d2l.plot([grid, *runs], [f(grid), *[[f(x) for x in xs] for xs in runs]],
             '$x$', '$f(x)$', legend=legend, fmts=['-', '-o', '-s'])

Next we define f(x)=xcos⁡(0.15πx)f(x) = x\cos(0.15\pi x) along with its first derivative f_cos_grad and second derivative f_cos_hess:

c = d2l.tensor(0.15 * np.pi)

def f_cos(x):  # Objective function
    return x * d2l.cos(c * x)

def f_cos_grad(x):  # Its derivative
    return d2l.cos(c * x) - c * x * d2l.sin(c * x)

def f_cos_hess(x):  # Its second derivative
    return -2 * c * d2l.sin(c * x) - c**2 * x * d2l.cos(c * x)

Evaluating f_cos_hess at the two local minima and running gd from x=10x = 10 at η∈{0.5,2}\eta \in \{0.5, 2\} demonstrates how the stability ceiling 2/η2/\eta selects between the deep sharp minimum and the shallow flat minimum:

minima = [gd(0.5, f_cos_grad, x=x, steps=50)[-1] for x in (10.0, 0.0)]
print(', '.join(f"f''({x:.2f}) = {float(f_cos_hess(x)):.2f}" for x in minima))
runs = {eta: gd(eta, f_cos_grad, steps=100) for eta in (0.5, 2)}
for eta, xs in runs.items():
    print(f'eta {eta}, 2/eta = {2/eta:.0f}: x = {xs[10]:.3f} after 10 steps, '
          f'{xs[100]:.3f} after 100')
show_trace(f_cos, *[xs[:11] for xs in runs.values()],
           legend=['$f$', r'$\eta = 0.5$', r'$\eta = 2$'])
f''(7.27) = 1.81, f''(-1.83) = 0.98
eta 0.5, 2/eta = 4: x = 7.269 after 10 steps, 7.269 after 100
eta 2, 2/eta = 1: x = -1.528 after 10 steps, -1.821 after 100

Starting from x=10x = 10, the run with η=0.5\eta = 0.5 (2/η=4>1.812/\eta = 4 > 1.81) converges rapidly into the deep minimum at x=7.269x = 7.269. At η=2\eta = 2 (2/η=1<1.812/\eta = 1 \lt 1.81), the deep minimum is unstable (1−ηf′′=−2.621 - \eta f'' = -2.62), and the iterate settles instead into the flatter minimum near x=−1.83x = -1.83, where f′′=0.98<2/ηf'' = 0.98 \lt 2/\eta.

9.1.4 The Edge of Stability#

In neural network training, the relationship between sharpness λmax⁡\lambda_{\max} and the stability limit 2/η2/\eta becomes dynamic. Cohen et al. (2021) demonstrated that under full-batch gradient descent, the Hessian sharpness λmax⁡(∇2f(xt))\lambda_{\max}(\nabla^2 f(\mathbf{x}_t)) steadily increases as the loss falls progressive sharpening until it reaches the stability threshold 2/η2/\eta. Instead of diverging, the sharpness then hovers near 2/η2/\eta for the remainder of training while the loss continues to decrease non-monotonically. This operating regime is known as the edge of stability.

We can measure this phenomenon directly on a 25-parameter single-hidden-layer tanh⁡\tanh network fitting 1616 points of y=sin⁡(3x)y = \sin(3x) on [−2,2][-2, 2]. Because d=25d = 25, we can compute the exact 25×2525 \times 25 Hessian and its largest eigenvalue λmax⁡\lambda_{\max} every 500500 steps across 1010 random initializations for η=0.4\eta = 0.4 (2/η=52/\eta = 5) and η=0.25\eta = 0.25 (2/η=82/\eta = 8).

X = torch.linspace(-2, 2, 16)
Y = torch.sin(3 * X)

def mlp_loss(p):  # 8 hidden units: weights, biases, output weights, bias
    W1, b1, W2, b2 = p[:8], p[8:16], p[16:24], p[24]
    return 0.5 * ((torch.tanh(X[:, None] * W1 + b1) @ W2 + b2 - Y) ** 2).mean()

def sharpness(P):  # Largest eigenvalue of the Hessian, for each row of P
    H = torch.func.vmap(torch.func.hessian(mlp_loss))(P)
    return torch.linalg.eigvalsh(H)[:, -1]

def gd_sharpness(eta, P, steps=20000, every=500, last=1000):
    """Full-batch gradient descent from each row of P. Returns the sharpness
    every `every` steps, the final loss, and the fraction of the last `last`
    steps on which the loss rose."""
    grad_and_loss = torch.func.vmap(torch.func.grad_and_value(mlp_loss))
    sharp, losses = [], []
    for k in range(steps + 1):
        if k % every == 0:
            sharp.append(sharpness(P))
        g, loss = grad_and_loss(P)
        losses.append(loss)
        if k < steps:  # The last pass only measures
            P = P - eta * g
    losses = torch.stack(losses[-last - 1:])  # (last + 1, starts)
    return (torch.stack(sharp, 1), losses[-1],
            (losses[1:] > losses[:-1]).float().mean(0))

P0 = 0.5 * torch.randn(10, 25)  # Ten random starts, shared by both runs

Running gd_sharpness from the ten shared initializations P0 at η=0.4\eta = 0.4 (2/η=52/\eta = 5) and η=0.25\eta = 0.25 (2/η=82/\eta = 8) tabulates the initial and final sharpness, final loss, and fraction of late steps on which the loss rose:

runs = {eta: gd_sharpness(eta, P0) for eta in (0.4, 0.25)}
print('      start      |' + '|'.join(
    f'    eta {eta}, 2/eta = {2 / eta:.0f}     ' for eta in runs))
print('sharpness   loss |' + '|'.join([' sharpness    loss  rising '] * 2))
for i in range(len(P0)):
    print(f'{float(runs[0.4][0][i, 0]):9.2f} {float(mlp_loss(P0[i])):6.3f} |'
          + '|'.join(f' {float(s[i, -1]):9.2f} {float(l[i]):7.1e} '
                     f'{float(r[i]):6.0%} ' for s, l, r in runs.values()))
      start      |    eta 0.4, 2/eta = 5     |    eta 0.25, 2/eta = 8     
sharpness   loss | sharpness    loss  rising | sharpness    loss  rising 
     2.92  0.540 |      5.00 3.3e-04    50% |      8.00 3.5e-04    50% 
     2.45  0.257 |      5.00 1.9e-03    50% |      7.78 1.0e-04     0% 
     5.18  0.669 |      4.99 3.9e-04    50% |      7.98 1.4e-04    50% 
     3.46  0.323 |      4.99 4.1e-04    50% |      7.98 2.9e-04    49% 
     3.33  0.736 |      4.99 4.2e-04    50% |      8.01 2.0e-04    50% 
     4.62  0.805 |      4.99 3.9e-04    50% |      8.02 1.7e-04    50% 
     2.95  1.170 |      5.01 3.2e-04    50% |      7.98 7.4e-05     0% 
     3.98  1.408 |      5.00 3.0e-04     0% |      8.00 3.9e-04    50% 
     4.06  0.706 |      5.00 2.9e-04    50% |      8.00 2.3e-04     1% 
     3.19  0.376 |      5.00 2.7e-04    50% |      7.98 4.4e-05     0% 

Plotting the sharpness normalized by the stability threshold, λmax⁡/(2/η)\lambda_{\max} / (2/\eta), over all 20,00020{,}000 steps shows the sharpness rising toward the edge of stability at 11 for both learning rates:

curves = {rf'$\eta = {eta}$': eta / 2 * s for eta, (s, _, _) in runs.items()}
d2l.plot_curves(curves, 'step', r'sharpness$\,/\,(2/\eta)$',
                x=np.arange(0, 20001, 500), reference=1)

From the exact same initializations, the normalized sharpness λmax⁡/(2/η)\lambda_{\max} / (2/\eta) climbs to 11 and plateaus there: runs with η=0.4\eta = 0.4 arrest at sharpness λmax⁡≈5.0\lambda_{\max} \approx 5.0, while most runs with η=0.25\eta = 0.25 climb to λmax⁡≈8.0\lambda_{\max} \approx 8.0. Not every run gets there: at η=0.25\eta = 0.25 a few starts fit the data before the sharpness reaches 88, stay just below the threshold, and descend with hardly a rising step. For the runs at the threshold 2/η2/\eta, the loss typically rises on roughly 50%50\% of steps as the iterate oscillates along the sharpest eigenvector (1−ηλmax⁡≈−11 - \eta\lambda_{\max} \approx -1) while continuing to descend along the remaining 2424 flatter directions. Whenever λmax⁡\lambda_{\max} momentarily exceeds 2/η2/\eta, the growing oscillation along the sharpest eigenvector couples with the third-order derivatives of the loss to induce a restoring drift toward flatter regions, stabilizing λmax⁡\lambda_{\max} at 2/η2/\eta (Damian et al., 2023). This self-stabilization also explains why gradually ramping up η\eta at the start of training (learning-rate warmup, Section 9.7) steers the network into a region flat enough to tolerate the peak learning rate (Kalra and Barkeshli, 2024).

This experiment used full-batch gradient descent, whereas the rest of the chapter trains with momentum, Adam, and minibatches. The edge of stability survives all three, with a different threshold in each. Heavy-ball momentum with coefficient β\beta (Section 9.4) raises the stability limit from ηλmax⁡<2\eta\lambda_{\max} \lt 2 to ηλmax⁡<2(1+β)\eta\lambda_{\max} \lt 2(1 + \beta), and the sharpness settles at 2(1+β)/η2(1 + \beta)/\eta accordingly (Cohen et al., 2021). Adam (Section 9.5) divides every coordinate of the step by its own gradient scale, so the quantity that settles is the sharpness of the Hessian after the same rescaling, the preconditioned sharpness. With Adam's usual momentum coefficient β1=0.9\beta_1 = 0.9, its threshold is about 38/η38/\eta (Cohen et al., 2022). With minibatch gradients the sharpness stops rising below 2/η2/\eta, and the smaller the batch, the earlier it stops. In every case a larger learning rate means a lower ceiling on the sharpness, so the warmup argument carries over to the optimizers we use from here on.

9.1.5 Newton's Method and Preconditioning#

9.1.5.1 Second-Order Steps and Newton's Method#

Why does gradient descent struggle on the valley (9.1.1)? At (−5,−2)(-5, -2), the negative gradient (1,8)(1, 8) points almost directly across the steep wall rather than toward the origin (0,0)(0, 0). The steep coordinate x2x_2 requires η=1/4=0.25\eta = 1/4 = 0.25 to reach the valley floor in one step, whereas the flat coordinate x1x_1 requires η=1/0.2=5\eta = 1/0.2 = 5.

Newton's method supplies each direction with the inverse of its own local curvature by minimizing the second-order Taylor approximation around x\mathbf{x}:

f(x+ϵ)≈f(x)+ϵ⊤∇f(x)+12ϵ⊤Hϵ.(9.1.7)f(\mathbf{x} + \boldsymbol{\epsilon}) \approx f(\mathbf{x}) + \boldsymbol{\epsilon}^\top \nabla f(\mathbf{x}) + \frac{1}{2} \boldsymbol{\epsilon}^\top \mathbf{H} \boldsymbol{\epsilon}. \tag{9.1.7}

Setting the gradient with respect to ϵ\boldsymbol{\epsilon} to zero yields the Newton update:

x←x−H−1∇f(x).(9.1.8)\mathbf{x} \leftarrow \mathbf{x} - \mathbf{H}^{-1} \nabla f(\mathbf{x}). \tag{9.1.8}

On any positive-definite quadratic, the second-order expansion is exact and a single Newton step reaches the minimum regardless of the condition number κ\kappa. Near a regular local minimum of a general smooth function, Newton's method achieves quadratic convergence, doubling the number of accurate digits on every step (Section 23.2).

Despite this rapid local convergence, exact Newton steps are impractical for deep neural networks for three reasons:

  1. Computational cost: Even when using Hessian–vector products (Section 22.5.3.2) to avoid storing the d×dd \times d Hessian (101810^{18} entries for d=109d = 10^9), solving Hϵ=−∇f(x)\mathbf{H}\boldsymbol{\epsilon} = -\nabla f(\mathbf{x}) iteratively requires dozens of backpropagation passes per parameter update.
  2. Negative curvature: Because H\mathbf{H} acts symmetrically on all critical points, negative eigenvalues invert the step direction and drive iterates uphill toward saddle points or local maxima unless modified by damping or absolute-spectrum projections (Section 23.2.1).
  3. Sensitivity to minibatch noise: Inverting noisy curvature estimates near zero amplifies sampling noise catastrophically.

9.1.5.2 Diagonal Preconditioning#

Instead of inverting the full Hessian, practical deep learning optimizers keep the affordable core of second-order methods: rescaling each coordinate (or layer matrix) by an inexpensive estimate of its curvature. In general, any update of the form x←x−ηP−1∇f(x)\mathbf{x} \leftarrow \mathbf{x} - \eta \mathbf{P}^{-1} \nabla f(\mathbf{x}) is called preconditioned gradient descent, where the preconditioner P\mathbf{P} reduces the effective condition number of P−1/2HP−1/2\mathbf{P}^{-1/2}\mathbf{H}\mathbf{P}^{-1/2}.

The simplest choice is the diagonal preconditioner P=diag⁡(H)\mathbf{P} = \operatorname{diag}(\mathbf{H}), which divides each coordinate of the gradient by its own second derivative:

x←x−η diag(H)−1∇f(x).(9.1.9)\mathbf{x} \leftarrow \mathbf{x} - \eta \, \textrm{diag}(\mathbf{H})^{-1} \nabla f(\mathbf{x}). \tag{9.1.9}

On the axis-aligned valley where diag⁡(H)=(0.2,4)\operatorname{diag}(\mathbf{H}) = (0.2, 4), (9.1.9) contracts both coordinates by the identical factor 1−η1 - \eta on every step, reducing the effective condition number from κ=20\kappa = 20 to 11. At η=0.5\eta = 0.5, both coordinates drop below 1%1\% of their initial values in just 77 steps (0.57≈0.00780.5^7 \approx 0.0078) instead of 4747:

def precond_gd_2d(x1, x2, s1, s2, f_grad, eta):
    g1, g2 = f_grad(x1, x2)
    return x1 - eta * g1 / h1, x2 - eta * g2 / h2, 0, 0  # diag(H) = (h1, h2)

def steps_to_1pct(xs):  # First step with both coordinates within 1% of start
    return next(t for t, (x1, x2) in enumerate(xs)
                if abs(x1) <= 0.01 * 5 and abs(x2) <= 0.01 * 2)

plain = train_2d(gd_2d, valley_grad, steps=100, eta=2 / (h1 + h2))
precond = train_2d(precond_gd_2d, valley_grad, steps=10, eta=0.5)
print(f'steps to 1%: plain at its best rate {steps_to_1pct(plain)}, '
      f'preconditioned {steps_to_1pct(precond)}')
d2l.show_trace_2d(f_valley, precond)
step 100, x1: -0.000225, x2: -0.000090
step 10, x1: -0.004883, x2: -0.001953
steps to 1%: plain at its best rate 47, preconditioned 7

In deep networks, we are not given diag⁡(H)\operatorname{diag}(\mathbf{H}) directly, nor are the principal curvature directions aligned with the coordinate axes (rotating the valley by 45∘45^\circ makes the diagonal entries of H\mathbf{H} equal and renders diagonal preconditioning ineffective; Exercise 7). Later sections address both limitations: Adam (Section 9.5) estimates per-coordinate scales online from squared gradients, while Momentum (Section 9.4) and Muon (Section 9.6) accelerate progress across non-axis-aligned directions. First, however, we examine what happens when exact gradients are replaced by noisy minibatch estimates (Section 9.2).

9.1.6 Summary#

On a positive-definite quadratic with Hessian eigenvalues λmin⁡≤⋯≤λmax⁡\lambda_{\min} \le \cdots \le \lambda_{\max}, gradient descent is stable if and only if η<2/λmax⁡\eta \lt 2/\lambda_{\max}, and reaching relative accuracy ϵ\epsilon at the optimal constant step size η⋆=2/(λmin⁡+λmax⁡)\eta^\star = 2/(\lambda_{\min} + \lambda_{\max}) requires t≈(κ/2)log⁡(1/ϵ)t \approx (\kappa/2)\log(1/\epsilon) steps, where κ=λmax⁡/λmin⁡\kappa = \lambda_{\max}/\lambda_{\min} is the condition number. In high-dimensional non-convex landscapes, critical points at elevated loss are predominantly strict saddle points that gradient descent escapes along negative-curvature eigenvectors, while activation plateaus are largely prevented by modern activations, normalization layers, and residual connections. For any LL-smooth objective, the descent lemma guarantees monotonic decrease whenever 0<η<2/L0 \lt \eta \lt 2/L; conversely, a fixed learning rate η\eta destabilizes any minimum sharper than 2/η2/\eta, and full-batch neural network training sharpens progressively until λmax⁡\lambda_{\max} hovers near this edge of stability 2/η2/\eta. Rescaling the gradient by a curvature preconditioner reduces the effective condition number, and diagonal preconditioning eliminates axis-aligned ill-conditioning in O(d)O(d) memory, motivating the adaptive coordinate-wise methods of Section 9.5.

9.1.7 Exercises#

  1. [code] Saddle escape time. Consider the saddle surface f(x,y)=x2−μy2f(x, y) = x^2 - \mu y^2 with μ>0\mu > 0 (downward curvature 2μ2\mu), and start gradient descent with learning rate η\eta at (1,δ)(1, \delta).

    1. Show that the number of steps until ∣y∣≥1|y| \geq 1 is approximately log⁡(1/δ)/(2ημ)\log(1/\delta)/(2\eta\mu) for small ημ\eta\mu. Verify this estimate numerically for μ∈{1,0.01}\mu \in \{1, 0.01\} at δ=10−2\delta = 10^{-2} and η=0.1\eta = 0.1, and compare it with the steps required to shrink a positive-curvature coordinate of curvature 2μ2\mu by factor δ\delta.
    2. Set μ=1\mu = 1 and δ=0\delta = 0, add zero-mean Gaussian noise of standard deviation σ∈{10−3,10−1}\sigma \in \{10^{-3}, 10^{-1}\} to each gradient evaluation, and measure the escape time. Reconcile your findings with the measure-zero stable manifold result of Section 9.1.2.
  2. [code] Learning rate and sharpness. A two-layer scalar linear network predicts abab on input 11 with squared loss ℓ(a,b)=12(ab−1)2\ell(a, b) = \frac{1}{2}(ab - 1)^2, so every point on the hyperbola ab=1ab = 1 is a global minimizer.

    1. Show that the Hessian at a minimizer (a,b)(a, b) on ab=1ab = 1 has largest eigenvalue λmax⁡=a2+b2\lambda_{\max} = a^2 + b^2. Which minimizers are flattest?
    2. Run 200200 steps of gradient descent from (a,b)=(4,0.1)(a, b) = (4, 0.1) at η∈{0.05,0.1,0.15,0.2}\eta \in \{0.05, 0.1, 0.15, 0.2\}, and compare the final sharpness λmax⁡\lambda_{\max} against the stability threshold 2/η2/\eta.
  3. Permutation-symmetric minima and non-convexity. ● Let θ⋆\boldsymbol{\theta}^\star be a local minimum of a single-hidden-layer MLP with d≥2d \ge 2 hidden units at which no two hidden units share identical incoming weights.

    1. Show that permuting the hidden units yields d!d! distinct parameter vectors with identical loss, and prove that if the loss were convex, their average would also be a global minimizer equivalent to a single-hidden-unit network.
    2. For a tanh⁡\tanh activation, identify the sign-flip symmetry of each hidden unit and state the resulting number of equivalent minima.
  4. Eigenvalues of symmetric random matrices. ● Let M\mathbf{M} be a symmetric k×kk \times k random matrix with independent entries Mij=MjiM_{ij} = M_{ji} (i≤ji \le j) drawn from symmetric distributions pij(x)=pij(−x)p_{ij}(x) = p_{ij}(-x) (Wigner, 1958).

    1. Prove that a uniformly chosen eigenvalue λ\lambda of M\mathbf{M} satisfies P(λ>0)=P(λ<0)P(\lambda > 0) = P(\lambda \lt 0), and use Wigner's semicircle law on [−2σ,2σ][-2\sigma, 2\sigma] to state the limiting fraction of negative eigenvalues in a single large realization of M/k\mathbf{M}/\sqrt{k}.
    2. For k=2k = 2 with Mii∼N(0,1)M_{ii} \sim \mathcal{N}(0, 1) and M12∼N(0,1/2)M_{12} \sim \mathcal{N}(0, 1/2), compute the exact probability that both eigenvalues are positive and compare it with the independent coin-flip estimate 2−22^{-2}.
  5. The descent guarantee over many steps. Let ff be LL-smooth and bounded below by f⋆f^\star, and run gradient descent at η=1/L\eta = 1/L from x0\mathbf{x}_0.

    1. Sum (9.1.6) over TT steps to show that min⁡0≤t<T∥∇f(xt)∥2≤2L (f(x0)−f⋆)/T\min_{0 \le t \lt T} \|\nabla f(\mathbf{x}_t)\|^2 \le 2L\,(f(\mathbf{x}_0) - f^\star)/T. Does this bound require convexity?
    2. On the valley from (−5,−2)(-5, -2) at T=100T = 100, compare this upper bound with the actual squared gradient norm reached by the iterate.
  6. [code] Minima within reach and operating below the edge.

    1. Locate the four local minima of f(x)=xcos⁡(0.15πx)f(x) = x\cos(0.15\pi x) on (−20,30)(-20, 30), compute f′′f'' and the stability threshold 2/f′′2/f'' at each, and test gradient descent initialized 0.010.01 away from each minimum at 0.9×0.9\times and 1.1×1.1\times its threshold.
    2. On the 25-parameter network of Section 9.1.4, predict the final sharpness of gd_sharpness(0.5, P0) before running it, then test η=0.1\eta = 0.1 for 50,00050{,}000 steps (2/η=202/\eta = 20) and explain why runs that fit the data before reaching 2/η2/\eta remain monotonic (rising = 0%).
  7. [code] Diagonal preconditioning under rotation and Newton's convergence order. ●

    1. Rotate the valley by angle θ\theta via Hθ=Rθdiag⁡(0.2,4)Rθ⊤\mathbf{H}_\theta = \mathbf{R}_\theta \operatorname{diag}(0.2, 4)\mathbf{R}_\theta^\top. Compute the condition number of the diagonally preconditioned Hessian D−1/2HθD−1/2\mathbf{D}^{-1/2}\mathbf{H}_\theta\mathbf{D}^{-1/2} (where D=diag⁡(Hθ)\mathbf{D} = \operatorname{diag}(\mathbf{H}_\theta)) as a function of θ\theta, and verify numerically at θ=45∘\theta = 45^\circ that diagonal preconditioning reduces to a scalar learning-rate change with κ=20\kappa = 20.
    2. Run 1D Newton's method xt+1=xt−f′(xt)/f′′(xt)x_{t+1} = x_t - f'(x_t)/f''(x_t) on f(x)=cosh⁡(0.5x)f(x) = \cosh(0.5x) from x0=10x_0 = 10, estimate the local convergence order pp in ∣xt+1∣≈C∣xt∣p|x_{t+1}| \approx C|x_t|^p near 00, and derive p=3p = 3 from the Taylor expansion of x−2tanh⁡(0.5x)x - 2\tanh(0.5x).

Discussions