Module contents
Lesson 24 of 27Research 120 min

Loss landscapes of deep learning

Study real network loss geometry through experiments and partial theory: avoiding misleading visualizations, the Hessian spectrum, sharpness and flat minima, the edge of stability, mode connectivity, and SAM as an optimizer seeking flat regions. Critically assess an open research literature.

After this lesson you can

  • Visualize 1D and 2D loss slices using filter-normalized random directions and explain their artifacts.
  • Estimate Hessian extreme eigenvalues and spectral density using power iteration and Lanczos with Hessian-vector products.
  • Reproduce the edge of stability: sharpness rises to 2/η and oscillates near it as loss decreases nonmonotonically.
  • Find a low-loss path between independent solutions and measure the linear interpolation barrier.
  • Implement SAM and critically discuss sharpness and generalization in light of reparameterizations.

Before you start

Motivation: debugging training requires knowing the terrain

You train your GPT with large-batch gradient descent and, instead of decreasing smoothly, loss rises and falls in a sawtooth for thousands of steps without exploding. Halve the learning rate and the curve smooths briefly, but the teeth return. Another day you train two copies of the same model with different seeds, average their weights and get worse than chance; if both start from the same pretrained model, the average works as well as each. A colleague claims their optimizer generalizes better because it “finds flat minima.”

All three observations concern the geometry of loss L(θ)\Loss(\theta) in a space of millions of dimensions: its curvature, how curvature changes during training, and whether solutions are isolated or connected by valleys. The previous lesson studied what can be proved about that geometry (the strict saddle property and benign landscapes); this one studies what is measured. We build diagnostics from scratch (loss slices, Hessian-vector products, power iteration and Lanczos), reproduce phenomena that changed thinking about training (the Hessian spectrum, edge of stability, mode connectivity), and finish with SAM, an optimizer deliberately seeking flat regions.

A qualification runs through the lesson. This literature is empirical and still open: some claims are theorems, some robust regularities, and others hypotheses cited as facts. We distinguish them; the last section organizes them.

Viewing a landscape of millions of dimensions

Linear interpolation

The simplest tool is a one-dimensional slice. Given initialization θ0\theta_0 and trained solution θ⋆\theta^\star, evaluate loss along their connecting segment:

g(t)=L((1−t) θ0+t θ⋆),t∈[−0.25,1.25].g(t) = \Loss\big((1 - t)\,\theta_0 + t\,\theta^\star\big), \qquad t \in [-0.25, 1.25].

Goodfellow, Vinyals and Saxe (2015) did this with contemporary networks and nearly always found a monotonic curve: no barrier between initialization and solution, even though the optimizer’s actual trajectory is not that line. Later work (Lucas et al., 2021) confirmed monotonicity is common but not universal: it fails especially with adaptive optimizers such as Adam at large learning rates and generally in networks moving far from initialization. This observation concerns a slice, not the training path.

Random one- and two-dimensional slices

To look around a solution, choose one or two directions δ1,δ2∈Rp\vb{\delta}_1, \vb{\delta}_2 \in \R^p and plot

f(α,β)=L(θ⋆+α δ1+β δ2).f(\alpha, \beta) = \Loss(\theta^\star + \alpha\,\vb{\delta}_1 + \beta\,\vb{\delta}_2).

Before viewing plots, understand what they can see. A random slice sees an average, not an extreme.

Proof

By symmetry E[δ^δ^⊤]\E[\hat{\vb{\delta}}\hat{\vb{\delta}}\T] is invariant under conjugation by any orthogonal matrix, so it is c Ic\,\mat{I}; its trace is E[∥δ^∥2]=1\E[\norm{\hat{\vb{\delta}}}^2] = 1, so c=1/pc = 1/p. Then E[δ^⊤Hδ^]=E[tr⁡(Hδ^δ^⊤)]=tr⁡(H E[δ^δ^⊤])=tr⁡H/p\E[\hat{\vb{\delta}}\T\mat{H}\hat{\vb{\delta}}] = \E[\tr(\mat{H}\hat{\vb{\delta}}\hat{\vb{\delta}}\T)] = \tr(\mat{H}\,\E[\hat{\vb{\delta}}\hat{\vb{\delta}}\T]) = \tr\mat{H}/p. For the second result, condition on δ^1\hat{\vb{\delta}}_1: E[(δ^1⊤δ^2)2∣δ^1]=δ^1⊤ E[δ^2δ^2⊤] δ^1=1/p\E[(\hat{\vb{\delta}}_1\T\hat{\vb{\delta}}_2)^2 \given \hat{\vb{\delta}}_1] = \hat{\vb{\delta}}_1\T\,\E[\hat{\vb{\delta}}_2\hat{\vb{\delta}}_2\T]\,\hat{\vb{\delta}}_1 = 1/p.

∎

Curvature along a random direction is the mean of eigenvalues. If the Hessian has a handful of large eigenvalues and hundreds of thousands nearly zero, as we will see, a random slice passes almost orthogonal to high-curvature directions and averages them with the rest: with p=106p = 10^6 and an outlier eigenvalue of 200200, its contribution to mean curvature is 2×10−42\times 10^{-4}. Thus a random slice of a large network nearly always looks like a smooth bowl, and drawing conclusions from it is risky. In the following figure’s networks, with only p=1731p = 1731 parameters, slice-direction curvature is on the order of 0.10.1 to 22 % of λmax⁡\lambda_{\max}, and even less after some rescalings.

Filter normalization

The second problem is scale. A ReLU network computes the same function if a layer’s weights and bias are multiplied by c>0c > 0 and the next layer’s weights by 1/c1/c, because ReLU⁡(cz)=c ReLU⁡(z)\relu(c z) = c\,\relu(z). With batch normalization something stronger holds: each filter followed by BatchNorm can be freely rescaled (normalization scale invariance). A fixed-size perturbation means different things for a large-weight and small-weight layer, so comparing slices across different weight scales compares scale, not geometry.

Li, Xu, Taylor, Studer and Goldstein (2018) proposed normalizing each direction filter by filter. If θℓ,i\theta_{\ell, i} is filter ii in layer ℓ\ell (in a dense layer, the weight vector entering neuron ii) and dℓ,i\vb{d}_{\ell, i} the corresponding part of a Gaussian direction, take

δℓ,i=dℓ,i∥dℓ,i∥ ∥θℓ,i∥,\vb{\delta}_{\ell, i} = \frac{\vb{d}_{\ell, i}}{\norm{\vb{d}_{\ell, i}}}\,\norm{\theta_{\ell, i}},

and set bias and normalization-parameter components to zero. Each filter is perturbed in proportion to its own size.

Proof

Layer ℓ\ell filters of TcθT_c\theta have norm c∥θℓ,i∥c\norm{\theta_{\ell, i}}, so δℓ,i′=c δℓ,i\vb{\delta}'_{\ell, i} = c\,\vb{\delta}_{\ell, i}; layer ℓ+1\ell + 1 filters have norm ∥θℓ+1,j∥/c\norm{\theta_{\ell+1, j}}/c, so δℓ+1,j′=δℓ+1,j/c\vb{\delta}'_{\ell+1, j} = \vb{\delta}_{\ell+1, j}/c; the rest are unchanged and biases unperturbed. Since TcT_c is linear, Tcθ+αδ1′+βδ2′=Tc(θ+αδ1+βδ2)T_c\theta + \alpha\vb{\delta}'_1 + \beta\vb{\delta}'_2 = T_c(\theta + \alpha\vb{\delta}_1 + \beta\vb{\delta}_2), and fTcφ=fφf_{T_c\varphi} = f_\varphi for every φ\varphi by ReLU’s positive homogeneity. The same filter-by-filter argument holds for a filter followed by BatchNorm, whose output is unchanged by multiplying it by c>0c > 0.

∎

Notice what the theorem does not say: it does not make the slice invariant to every reparameterization (rescaling one neuron changes next-layer row norms unequally), nor fix the preceding theorem’s averaging problem. It corrects scale, not dimension.

InteractiveSlicing the loss
  • trained solution θ⋆\theta^\star (slice center)
  • contours: loss 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 40
Height: log⁡(1+L)\log(1 + L), clipped at L=60L = 60; color: log⁡10L\log_{10} L, on the same scale for all four networks. Slice L(θ⋆+αδ1+βδ2)L(\theta^\star + \alpha\vb{\delta}_1 + \beta\vb{\delta}_2) with α,β∈[−1,1]\alpha, \beta \in [-1, 1].
Architecture
Batch size
Rescaling (same function)
Loss at θ⋆\theta^\star0.0436
Mean loss in disk α2+β2≤1/4\alpha^2 + \beta^2 \le 1/44.485
λmax⁡\lambda_{\max} of full Hessian17.34
Curvature along δ1\vb{\delta}_1: δ^1⊤Hδ^1\hat{\vb{\delta}}_1\T\mat{H}\hat{\vb{\delta}}_10.0537
Fraction of λmax⁡\lambda_{\max} seen by δ1\vb{\delta}_10.31 %
∥θ⋆∥2\norm{\theta^\star}_220.0
Test accuracy96.9 %
Full batch and no residuals: the narrowest of the four valleys and the one with largest λmax⁡\lambda_{\max}. Compare the residual network or batch 16.
Precomputed 2D slices of four ReLU MLPs with 7 hidden layers of 16 neurons (one input layer and six 16-to-16 layers; 1731 parameters), trained with momentum SGD and small weight decay on a spiral problem: without and with residual connections in the six 16-to-16 layers, and with batch 16 or full batch (600). Rotate the surface and view contours. Start with the non-residual full-batch network and compare the others. Then apply rescalings c=1/4c = 1/4 and c=8c = 8, multiplying the first layer and all hidden biases by cc and the output layer by 1/c1/c without changing the function: with filter normalization the slice does not move, without it it does. Also inspect λmax⁡\lambda_{\max} and what fraction the slice direction sees.

Three readings, with these networks’ numbers. The non-residual full-batch network has the narrowest valley and largest λmax⁡\lambda_{\max} of the four (17.317.3 versus 7.57.5 at batch 16), consistent with Keskar et al.’s (2017) large-batch observations; the residual network is wider and smoother, like Li et al.’s ResNets, although the difference is moderate in such a small network. Second, rescaling by c=1/4c = 1/4 leaves the function intact, the normalized slice identical (maximum measured difference: 00), and multiplies λmax⁡\lambda_{\max} by over 9 in the non-residual batch-16 network (7.5→69.77.5 \to 69.7). This rescaling composes the theorem’s TcT_c on consecutive layer pairs (factors cc and 1/c1/c cancel in intermediate layers); the same argument holds in the residual version because the whole hidden representation is multiplied by cc, so the normalized slice does not change. Third, “fraction of λmax⁡\lambda_{\max}” never reaches 2 %: the slice shows mean curvature, not maximum.

The Hessian spectrum

Hessian-vector products

With pp in the millions one cannot form ∇2L(θ)∈Rp×p\hess\Loss(\theta) \in \R^{p\times p}, but can multiply it by a vector. The Hessian-vector product is the gradient’s directional derivative,

∇2L(θ) v= ⁣d ⁣dε∇L(θ+εv)∣ε=0,\hess\Loss(\theta)\,\vb{v} = \frac{\dd}{\dd\varepsilon}\grad\Loss(\theta + \varepsilon\vb{v})\Big|_{\varepsilon = 0},

and automatic differentiation computes it exactly at the cost of about two gradients by composing forward mode over reverse mode (mode composition; Pearlmutter’s 1994 trick, used in Newton-CG). From scratch a centered difference suffices,

∇2L(θ) v≈∇L(θ+εv)−∇L(θ−εv)2ε,\hess\Loss(\theta)\,\vb{v} \approx \frac{\grad\Loss(\theta + \varepsilon\vb{v}) - \grad\Loss(\theta - \varepsilon\vb{v})}{2\varepsilon},

with error O(ε2)\bigO(\varepsilon^2) if the third derivative of L\Loss is Lipschitz (e.g. if L\Loss is class C4C^4). This condition matters: with ReLU the gradient jumps when a neuron changes regime, and finite differences may give absurd values; the cells use tanh⁡\tanh for these measurements.

Power iteration and Lanczos

Using only Hv\mat{H}\vb{v} products, power iteration gives the eigenvalue of greatest magnitude: eigenvector error decreases as ∣λ2/λ1∣k\abs{\lambda_2/\lambda_1}^k and, because H\mat{H} is symmetric, Rayleigh quotient error as ∣λ2/λ1∣2k\abs{\lambda_2/\lambda_1}^{2k}. At training’s end it is usually λmax⁡\lambda_{\max}, but not always: if the most negative eigenvalue has greater magnitude, power iteration converges to it. Separate extremes with a shift (H−λmax⁡I\mat{H} - \lambda_{\max}\mat{I} has dominant eigenvalue λmin⁡−λmax⁡\lambda_{\min} - \lambda_{\max}) or, better, Lanczos.

Lanczos builds an orthonormal basis q1,…,qk\vb{q}_1, \dots, \vb{q}_k of the Krylov subspace span⁡{q1,Hq1,…,Hk−1q1}\spn\{\vb{q}_1, \mat{H}\vb{q}_1, \dots, \mat{H}^{k-1}\vb{q}_1\} in which H\mat{H} is tridiagonal,

Qk⊤HQk=Tk=[α1β1β1α2⋱⋱⋱βk−1βk−1αk],\mat{Q}_k\T\mat{H}\mat{Q}_k = \mat{T}_k = \begin{bmatrix} \alpha_1 & \beta_1 & & \\ \beta_1 & \alpha_2 & \ddots & \\ & \ddots & \ddots & \beta_{k-1} \\ & & \beta_{k-1} & \alpha_k \end{bmatrix},

using a three-term recurrence: βjqj+1=Hqj−αjqj−βj−1qj−1\beta_j\vb{q}_{j+1} = \mat{H}\vb{q}_j - \alpha_j\vb{q}_j - \beta_{j-1}\vb{q}_{j-1}. Eigenvalues of Tk\mat{T}_k (Ritz values) approximate spectrum extremes much sooner than power iteration: for the largest eigenvalue of a positive semidefinite matrix with random start and no eigenvalue-gap assumption, expected relative error after kk steps is bounded by a multiple of ln⁡p/k\ln p / k for power iteration and (ln⁡p/k)2(\ln p / k)^2 for Lanczos (Kuczyński and Woźniakowski, 1992). Each step costs one Hessian-vector product.

In floating point the three-term recurrence loses orthogonality as soon as a Ritz value converges, producing spurious copies (“ghosts”) of already found eigenvalues. For the k≲100k \lesssim 100 steps used in diagnostics, the robust solution is full reorthogonalization: project each new vector against all previous vectors twice. It costs storage of kk vectors of size pp.

Spectral density and stochastic Lanczos

To estimate ϕ\phi without computing pp eigenvalues, Ghorbani, Krishnan and Xiao (2019) used stochastic Lanczos quadrature. If H=∑iλiuiui⊤\mat{H} = \sum_i \lambda_i\vb{u}_i\vb{u}_i\T and v\vb{v} is unit, v⊤g(H)v=∑iwi g(λi)\vb{v}\T g(\mat{H})\vb{v} = \sum_i w_i\,g(\lambda_i) with weights wi=(ui⊤v)2w_i = (\vb{u}_i\T\vb{v})^2 summing to 1 and, by the previous section’s theorem, averaging 1/p1/p for random v\vb{v}. That sum is an integral against a discrete measure approximated by Gauss quadrature with kk nodes: Ritz values θj\theta_j of Tk\mat{T}_k with weights τj=(e1⊤yj)2\tau_j = (\vb{e}_1\T\vb{y}_j)^2, where yj\vb{y}_j is the associated eigenvector of Tk\mat{T}_k. Averaging a few probes v\vb{v} and replacing each node by a Gaussian of width σ\sigma estimates ϕ\phi at a cost of a few hundred Hessian-vector products.

What is observed in networks

Empirical studies agree on a distinctive shape (Sagun et al., 2017; Ghorbani et al., 2019; Papyan, 2019):

  • A huge mass near zero. Most eigenvalues are tiny relative to λmax⁡\lambda_{\max}, with a small negative tail that does not entirely vanish by training’s end.
  • A few outlier eigenvalues separated from the rest, their count tied to data structure (for classification with KK classes, on the order of KK).
  • Architecture dependence: without batch normalization outliers are larger and more separated; Ghorbani et al. connect their suppression with BatchNorm accelerating training.

Gauss–Newton decomposition helps explain the shape. For L(θ)=1n∑iℓ(fθ(xi),yi)\Loss(\theta) = \frac{1}{n}\sum_i \ell(f_\theta(\vb{x}_i), y_i) with outputs fθ(xi)∈RKf_\theta(\vb{x}_i) \in \R^K and Jacobians Ji=∂fθ(xi)/∂θ∈RK×p\mat{J}_i = \partial f_\theta(\vb{x}_i)/\partial\theta \in \R^{K\times p},

∇2L(θ)=1n∑i=1nJi⊤ ∇f2ℓi Ji⏟G (Gauss-Newton, semidefinida positiva)+1n∑i=1n∑k=1K∂ℓi∂fk ∇θ2fk(xi).\hess\Loss(\theta) = \underbrace{\frac{1}{n}\sum_{i=1}^n \mat{J}_i\T\,\hess_f\ell_i\,\mat{J}_i}_{\mat{G}\ \text{(Gauss-Newton, semidefinida positiva)}} + \frac{1}{n}\sum_{i=1}^n\sum_{k=1}^K \frac{\partial\ell_i}{\partial f_k}\,\hess_\theta f_k(\vb{x}_i).

The first term is positive semidefinite when ℓ\ell is convex in the output (cross-entropy and squared error are), and has rank at most nKnK, leaving many exactly zero directions under overparameterization; near an interpolating solution, the second term is multiplied by small residuals. This is the structure used by Gauss–Newton, explaining concentration near zero and why outliers inherit class structure from Ji\mat{J}_i.

Now the tools from scratch. The first cell defines a NumPy MLP with hand-written gradient (checked against finite differences), trains it by gradient descent on a three-class spiral problem, and reproduces Goodfellow et al.’s linear interpolation.

[ ]A NumPy MLP and linear interpolationBrowser
import numpy as np
import matplotlib.pyplot as plt

def espirales(n_por_clase=100, K=3, ruido=0.35, semilla=0):
    rng = np.random.default_rng(semilla)
    X, y = [], []
    for k in range(K):
        r = np.linspace(0.15, 1.0, n_por_clase)
        t = 2 * np.pi * k / K + 3.2 * r + ruido * rng.normal(size=n_por_clase)
        X.append(2 * np.c_[r * np.cos(t), r * np.sin(t)])
        y.append(np.full(n_por_clase, k))
    return np.vstack(X), np.concatenate(y)

class MLP:
    """Perceptrón multicapa con todos los parámetros aplanados en un único vector theta."""
    def __init__(self, capas, act="relu", perdida="ce"):
        self.formas = list(zip(capas[:-1], capas[1:]))
        self.p = sum(a * b + b for a, b in self.formas)
        self.act, self.perdida = act, perdida

    def capas(self, th):
        i = 0
        for a, b in self.formas:
            W = th[i:i + a * b].reshape(a, b); i += a * b
            yield W, th[i:i + b]; i += b

    def iniciar(self, semilla):
        rng = np.random.default_rng(semilla)
        escala = 2.0 if self.act == "relu" else 1.0          # He para ReLU, LeCun para tanh
        return np.concatenate([np.r_[rng.normal(size=a * b) * np.sqrt(escala / a), np.zeros(b)]
                               for a, b in self.formas])

    def salida(self, th, X):
        h, Ws = X, list(self.capas(th))
        for l, (W, b) in enumerate(Ws):
            h = h @ W + b
            if l < len(Ws) - 1:
                h = np.maximum(h, 0) if self.act == "relu" else np.tanh(h)
        return h

    def perdida_y_grad(self, th, X, y):
        Ws = list(self.capas(th))
        hs = [X]
        for l, (W, b) in enumerate(Ws):
            z = hs[-1] @ W + b
            if l < len(Ws) - 1:
                z = np.maximum(z, 0) if self.act == "relu" else np.tanh(z)
            hs.append(z)
        m, s = len(X), hs[-1]
        if self.perdida == "ce":
            z = s - s.max(1, keepdims=True)
            lse = np.log(np.exp(z).sum(1))
            L = (lse - z[np.arange(m), y]).mean()        # log-suma-exp estable
            D = np.exp(z - lse[:, None]); D[np.arange(m), y] -= 1; D /= m
        else:                                            # error cuadrático: L = (1/2m) sum (s - y)^2
            r = s - y
            L = 0.5 * np.mean(r ** 2); D = r / m
        g = []
        for l in range(len(Ws) - 1, -1, -1):
            g = [hs[l].T @ D, D.sum(0)] + g
            if l > 0:
                D = D @ Ws[l][0].T
                D = D * (hs[l] > 0) if self.act == "relu" else D * (1 - hs[l] ** 2)
        return L, np.concatenate([x.ravel() for x in g])

    def precision(self, th, X, y):
        return (self.salida(th, X).argmax(1) == y).mean()

X, y = espirales(semilla=0)
Xte, yte = espirales(semilla=1)
red = MLP([2, 16, 16, 3], act="tanh")      # tanh: suave, para que el Hessiano exista en todas partes
f = lambda th: red.perdida_y_grad(th, X, y)

# comprobación del gradiente por diferencias centradas en 5 coordenadas
th0 = red.iniciar(0)
L0, g0 = f(th0)
rng = np.random.default_rng(1)
for i in rng.choice(red.p, 5, replace=False):
    e = np.zeros(red.p); e[i] = 1e-6
    print(f"coord {i:3d}: analítico {g0[i]: .6e}   numérico {(f(th0 + e)[0] - f(th0 - e)[0]) / 2e-6: .6e}")

th = th0.copy()
for _ in range(1500):
    th -= 0.5 * f(th)[1]
print(f"p = {red.p} parámetros; pérdida final {f(th)[0]:.4f}; precisión train {red.precision(th, X, y):.3f}, "
      f"test {red.precision(th, Xte, yte):.3f}")

# Goodfellow et al.: la pérdida en el segmento que une la inicialización con la solución
a = np.linspace(-0.25, 1.25, 61)
seg = np.array([f((1 - t) * th0 + t * th)[0] for t in a])
dentro = (a >= 0) & (a <= 1)
print("¿monótona entre 0 y 1?", bool(np.all(np.diff(seg[dentro]) <= 1e-12)))
plt.figure(figsize=(6, 3.2))
plt.semilogy(a, seg)
plt.axvline(0, color="gray", lw=0.8); plt.axvline(1, color="gray", lw=0.8)
plt.xlabel("t   (θ = (1 − t) θ₀ + t θ*)"); plt.ylabel("pérdida de entrenamiento")
plt.title("Interpolación lineal desde la inicialización"); plt.tight_layout(); plt.show()

The network has 371371 parameters, reaches loss 0.00310.0031 and the segment from initialization is monotonic: Goodfellow et al.’s result in miniature. Now Hessian-vector products, power iteration and Lanczos with full reorthogonalization, compared with the full Hessian, still formable here.

[ ]Hessian-vector product, power iteration and LanczosBrowser
def hvp(f, th, v, eps=1e-4):
    """Producto Hessiano-vector por diferencias centradas del gradiente: dos gradientes, error O(eps²)."""
    return (f(th + eps * v)[1] - f(th - eps * v)[1]) / (2 * eps)

def potencia(Hv, dim, iters=100, semilla=0):
    v = np.random.default_rng(semilla).normal(size=dim)
    v /= np.linalg.norm(v)
    for _ in range(iters):
        w = Hv(v)
        lam = v @ w                      # cociente de Rayleigh
        v = w / np.linalg.norm(w)
    return lam, v

def lanczos(Hv, dim, k, semilla=0):
    """k pasos de Lanczos con reortogonalización completa. Devuelve los nodos y pesos de la tridiagonal T_k."""
    rng = np.random.default_rng(semilla)
    Q = np.zeros((dim, k)); alfa = np.zeros(k); beta = np.zeros(k)
    q = rng.normal(size=dim); q /= np.linalg.norm(q)
    for j in range(k):
        Q[:, j] = q
        w = Hv(q)
        alfa[j] = q @ w
        for _ in range(2):               # Gram-Schmidt dos veces: «twice is enough»
            w -= Q[:, :j + 1] @ (Q[:, :j + 1].T @ w)
        beta[j] = np.linalg.norm(w)
        if beta[j] < 1e-10:
            k = j + 1; break
        q = w / beta[j]
    T = np.diag(alfa[:k]) + np.diag(beta[:k - 1], 1) + np.diag(beta[:k - 1], -1)
    nodos, U = np.linalg.eigh(T)
    return nodos, U[0] ** 2

cuenta = {"hvp": 0}
def Hv(v):
    cuenta["hvp"] += 1
    return hvp(f, th, v)

lam_pot, _ = potencia(Hv, red.p, 100)
print(f"potencia (100 HVP):   λ_max = {lam_pot:.5f}")
cuenta["hvp"] = 0
nodos, _ = lanczos(Hv, red.p, 30)
print(f"Lanczos ({cuenta['hvp']} HVP): cinco mayores = {np.round(nodos[-5:], 5)}   menor = {nodos[0]:.5f}")

# Hessiano completo (solo porque p es pequeño): p productos con la base canónica
H = np.column_stack([hvp(f, th, e) for e in np.eye(red.p)])
H = (H + H.T) / 2
ev = np.linalg.eigvalsh(H)
print(f"exacto:              cinco mayores = {np.round(ev[-5:], 5)}   menor = {ev[0]:.5f}")
print(f"traza = {ev.sum():.4f};  |λ| < 1 % de λ_max: {np.mean(np.abs(ev) < 0.01 * ev[-1]):.1%} de los {red.p} autovalores;"
      f"  negativos por debajo de −1e-6: {np.sum(ev < -1e-6)}")

With 30 Hessian-vector products Lanczos reproduces the five largest exact eigenvalues (1.2451.245, 0.7280.728, 0.2790.279, 0.2120.212, 0.0810.081) to all shown digits, and the smallest, −0.00069-0.00069, which power iteration does not attempt. The spectrum has exactly the described shape: λmax⁡\lambda_{\max} of 1.2451.245, a second outlier of 0.7280.728 and 97.897.8 % of 371 eigenvalues below 1 % of λmax⁡\lambda_{\max}; 87 are negative, all tiny. The next cell estimates density with stochastic Lanczos and compares exact.

[ ]Spectral density by stochastic LanczosBrowser
def slq(Hv, dim, rejilla, sigma, k=40, sondas=8):
    """Cuadratura de Lanczos estocástica (Ghorbani et al., 2019): densidad suavizada con núcleos gaussianos."""
    nodos, pesos = [], []
    for s in range(sondas):
        n_, w_ = lanczos(Hv, dim, k, semilla=100 + s)
        nodos.append(n_); pesos.append(w_ / sondas)
    n_ = np.concatenate(nodos); w_ = np.concatenate(pesos)
    dens = (w_[None, :] * np.exp(-(rejilla[:, None] - n_[None, :]) ** 2 / (2 * sigma ** 2))).sum(1)
    return dens / (np.sqrt(2 * np.pi) * sigma)

rejilla = np.linspace(ev[0] - 0.02, ev[-1] + 0.05, 600)
sigma = 0.01 * (ev[-1] - ev[0])
densidad = slq(Hv, red.p, rejilla, sigma)
exacta = (np.exp(-(rejilla[:, None] - ev[None, :]) ** 2 / (2 * sigma ** 2)).sum(1)
          / (red.p * np.sqrt(2 * np.pi) * sigma))
print(f"masa de la densidad SLQ en la rejilla: {np.trapezoid(densidad, rejilla):.3f};  "
      f"error L1 frente a la exacta suavizada: {np.trapezoid(np.abs(densidad - exacta), rejilla):.3f}")
fig, ax = plt.subplots(figsize=(7, 3.2))
ax.semilogy(rejilla, exacta + 1e-6, color="gray", lw=3, alpha=0.5, label="exacta (suavizada)")
ax.semilogy(rejilla, densidad + 1e-6, lw=1.5, label="Lanczos estocástico, 8 × 40 HVP")
ax.plot(ev[-6:], np.full(6, 2e-6), "v", color="C3", label="seis mayores autovalores")
ax.set_ylim(1e-6, None); ax.set_xlabel("λ"); ax.set_ylabel("densidad (escala log)"); ax.legend()
plt.tight_layout(); plt.show()

With 320 Hessian-vector products, less than one per parameter, estimated density matches exact density with L1L^1 error on the order of 10−210^{-2}; for a network of 10710^7 parameters cost would be the same. Log scale is essential: linear scale would show only the zero peak.

Sharpness, flat minima and reparameterization

The intuition that “flat” minima generalize better than “sharp” ones is old. Hochreiter and Schmidhuber (1997) framed it through description length: if loss is low over a large region around θ⋆\theta^\star, θ⋆\theta^\star needs little precision to describe, and a model described with few bits generalizes better. Keskar et al. (2017) revived it with a striking experiment: large-batch training converges to sharper minima and generalizes worse.

The problem is that none is a property of the function computed by the network: it depends on parameterization.

Proof

Since TcT_c does not change the function, L(Tcθ)=L(θ)\Loss(T_c\theta) = \Loss(\theta) for every θ\theta. TcT_c is linear with matrix Dc\mat{D}_c, so differentiating twice by the chain rule yields Dc ∇2L(Tcθ) Dc=∇2L(θ)\mat{D}_c\,\hess\Loss(T_c\theta)\,\mat{D}_c = \hess\Loss(\theta); at θ⋆\theta^\star this is the stated formula. Block (1,1)(1, 1) of Dc−1HDc−1\mat{D}_c\inv\mat{H}\mat{D}_c\inv is c−2H11c^{-2}\mat{H}_{11}, and a symmetric matrix’s largest eigenvalue is at least that of any principal submatrix (use a Rayleigh quotient with vectors supported in the first block). Since H11\mat{H}_{11} is positive semidefinite at a minimum and nonzero, λmax⁡(H11)>0\lambda_{\max}(\mat{H}_{11}) > 0.

∎

Any minimum can be made arbitrarily sharp without changing predictions; Dinh et al. show the same for volume notions. In the first figure, with c=8c = 8 the batch-16 residual network moves from λmax⁡=3.8\lambda_{\max} = 3.8 to 37.037.0 with unchanged test accuracy. The conclusion is not that sharpness is useless, but that it can only be compared under a fixed parameterization, or using measures designed to be invariant: adaptive sharpness normalized by each weight’s scale (Kwon et al., 2021), or PAC-Bayes bounds where perturbations scale with weights (the precise relation between flatness and generalization is studied in learning theory).

Does sharpness predict generalization? Evidence is mixed. In Jiang et al.’s (2020) large-scale study with thousands of convolutional networks, PAC-Bayes-style flatness measures were among the best correlated with generalization error. Conversely, Andriushchenko et al. (2023) found that in modern settings (transformers, fine-tuning pretrained models, strong augmentation), even adaptive sharpness does not consistently predict which of two models generalizes better. An optimizer reducing sharpness is measurable; that this causes better generalization is a hypothesis.

The edge of stability

What quadratic theory says

On a quadratic L(θ)=12(θ−θ⋆)⊤H(θ−θ⋆)\Loss(\theta) = \tfrac{1}{2}(\theta - \theta^\star)\T\mat{H}(\theta - \theta^\star), gradient descent evolves as θt+1−θ⋆=(I−ηH)(θt−θ⋆)\theta_{t+1} - \theta^\star = (\mat{I} - \eta\mat{H})(\theta_t - \theta^\star), and in the eigenvector basis each component is multiplied by 1−ηλi1 - \eta\lambda_i per step. The λmax⁡\lambda_{\max} component grows if ηλmax⁡>2\eta\lambda_{\max} > 2. This is the classical rule, consistent with the descent lemma: with η<2/L\eta < 2/L loss decreases each step. The usual reading was that a network of curvature λmax⁡\lambda_{\max} must train with η<2/λmax⁡\eta < 2/\lambda_{\max}, and training diverges if curvature exceeds 2/η2/\eta.

What happens in networks

Cohen, Kaur, Li, Kolter and Talwalkar (2021) measured λmax⁡\lambda_{\max} during full-batch gradient descent across dozens of architectures (MLPs, convolutional networks, transformers) and losses (squared error and cross-entropy), always finding the same sequence.

Both halves are surprising. Progressive sharpening says gradient descent moves toward increasingly curved regions unprompted. The second says that upon reaching the classical instability threshold it does not diverge: it stays there and keeps learning.

InteractiveThe edge of stability
Sharpness and stability threshold
  • sharpness λmax⁡\lambda_{\max}
  • 2/η2/\eta
Training loss (log scale)
0.200
Speed
Step0
2/η2/\eta10.00
Sharpness λmax⁡\lambda_{\max}calculating
ηλmax⁡/2\eta\lambda_{\max}/2…
Loss∞
Real browser simulation: a tanh 6-16-16-16-1 MLP (673 parameters) with squared error on 128 random-label examples, trained with full-batch gradient descent. Every 10 steps sharpness is measured with four power iterations on Hessian-vector products. The first 400 steps with η=0.2\eta = 0.2 run automatically: watch λmax⁡\lambda_{\max} rise to the dashed 2/η2/\eta line and stay there while loss falls unevenly. Once stopped, halve η\eta and press ‘Play’: the line jumps to 2020 and sharpness rises again to meet it around step 1300. Also try catapult and divergence scenarios, and a very small η\eta.

In the simulation initial sharpness is λ0≈3.5\lambda_0 \approx 3.5. With η=0.2\eta = 0.2 it reaches 2/η=102/\eta = 10 around step 90 and overshoots to almost double; oscillation along the sharpest direction grows, loss jumps and sharpness abruptly falls to 55. After a couple more cycles, from step 300 it oscillates between 1010 and 11.511.5 while loss falls from 0.530.53 to under 0.070.07 with intermittent increases. Halving η\eta at step 400 makes loss fall suddenly (the sharpest direction is stable again and oscillation damps), and sharpening resumes to the new 2/η=202/\eta = 20 line, reached around step 1300; somewhat later another loss spike appears and sharpness settles at 19.919.9. Timing matters: halving at step 600, with loss already lower, makes sharpening slower and at step 6000 sharpness remains 19.219.2 without touching the line. With η=0.02\eta = 0.02 threshold is 100100: sharpness rises to 4141 in 6000 steps, with loss already 0.0060.006, and never reaches it. Without an edge there is no edge regime.

Why it does not explode: self-stabilization

Quadratic theory assumes H\mat{H} does not change. In a network it does, and Damian, Nichani and Lee (2023) showed that change explains the phenomenon with a third-order Taylor expansion. Let u\vb{u} be the unit eigenvector of λmax⁡\lambda_{\max} at reference point θ†\theta^\dagger and x=u⊤(θ−θ†)x = \vb{u}\T(\theta - \theta^\dagger) displacement in that direction. Then

∇L(θ†+xu)≈∇L(θ†)+x S(θ†) u+x22 ∇3L(θ†)[u,u],\grad\Loss(\theta^\dagger + x\vb{u}) \approx \grad\Loss(\theta^\dagger) + x\,S(\theta^\dagger)\,\vb{u} + \frac{x^2}{2}\,\grad^3\Loss(\theta^\dagger)[\vb{u}, \vb{u}],

and if λmax⁡\lambda_{\max} is simple, ∇3L[u,u]=∇S\grad^3\Loss[\vb{u}, \vb{u}] = \grad S: the derivative of a simple eigenvalue is u⊤(∂H)u\vb{u}\T(\partial\mat{H})\vb{u}. The descent step therefore contains term −η x22∇S-\eta\,\tfrac{x^2}{2}\grad S. The cycle is:

  1. Sharpening: while ηS<2\eta S < 2, xx damps and SS grows for whatever reason (progressive sharpening).
  2. Explosion: when ηS>2\eta S > 2, component xx is multiplied by ∣1−ηS∣>1\abs{1 - \eta S} > 1 each step and oscillates with growing amplitude. Loss rises.
  3. Self-stabilization: with x2x^2 large, term −ηx22∇S-\eta\tfrac{x^2}{2}\grad S dominates and gradient descent lowers sharpness, as if minimizing SS.
  4. Return: when ηS<2\eta S < 2 again, oscillation damps and step 1 returns.

The net effect, proved by Damian et al. under precise assumptions, is that gradient descent at the edge approximately follows the constrained problem min⁡L(θ)\min \Loss(\theta) subject to S(θ)≤2/ηS(\theta) \le 2/\eta: an implicit bias toward regions of sharpness at most 2/η2/\eta. The edge does not contradict quadratic theory; it uses it alongside the cubic term it ignores.

The catapult phase

What if initial sharpness already exceeds 2/η2/\eta? Lewkowycz, Bahri, Dyer, Sohl-Dickstein and Gur-Ari (2020) described three regimes depending on ηλ0\eta\lambda_0. With η<2/λ0\eta < 2/\lambda_0, normal training. For η\eta somewhat above 2/λ02/\lambda_0, loss grows for a few steps, curvature falls below 2/η2/\eta and the network is “catapulted” into a flatter region where it converges. Beyond ηmax⁡\eta_{\max} it diverges. In their analyzable model ηmax⁡=4/λ0\eta_{\max} = 4/\lambda_0, and in ReLU networks they empirically found larger values on the order of 12/λ012/\lambda_0. In the figure’s network η=2.6/λ0\eta = 2.6/\lambda_0 causes a catapult: in the first 60 steps loss spikes twice (up to 1.41.4 from 0.530.53), sharpness oscillates strongly then settles around 2.72.7, below λ0=3.5\lambda_0 = 3.5 and exactly at 2/η2/\eta, while loss falls to 10−310^{-3}. With η=2.8/λ0\eta = 2.8/\lambda_0 it diverges: the window exists but here is much narrower than in Lewkowycz et al.’s model, and its width depends on the model.

Practical consequences

  • Warmup. Starting with small η\eta and increasing it lets the network enter lower-curvature regions before using the large rate. Gilmer et al. (2022) interpret some effectiveness of learning-rate schedule warmup this way: it keeps ηλmax⁡\eta\lambda_{\max} below threshold.
  • Momentum and Adam change the threshold. With heavy-ball momentum β\beta, the quadratic is stable if ηλ<2+2β\eta\lambda < 2 + 2\beta. For Adam, Cohen et al. (2022) observed the same phenomenon with preconditioned sharpness λmax⁡(Pt−1∇2L)\lambda_{\max}(\mat{P}_t\inv\hess\Loss) stabilizing at (2+2β1)/((1−β1)η)=38/η(2 + 2\beta_1)/((1 - \beta_1)\eta) = 38/\eta for β1=0.9\beta_1 = 0.9.
  • With small minibatches sharpness usually stabilizes below 2/η2/\eta (Cohen et al., 2021; Jastrzębski et al., 2020): stochastic gradient descent noise adds its own limit.
  • Beware cross-entropy late in training: as margins grow, probabilities saturate and curvature falls by itself. The edge appears for a phase, then sharpness decreases.

The next NumPy cell reproduces the experiment with a model like the figure’s (another seed), including halving η\eta at step 400.

[ ]The edge of stability in NumPyBrowser
def nitidez(f, th, v, iters):
    """Iteración de la potencia con arranque en caliente: devuelve lambda_max y el vector actualizado."""
    for _ in range(iters):
        w = hvp(f, th, v); lam = v @ w; v = w / np.linalg.norm(w)
    return lam, v

rng = np.random.default_rng(0)
Xr = rng.normal(size=(128, 6)); yr = np.sign(rng.normal(size=(128, 1)))   # etiquetas ±1 aleatorias
red_mse = MLP([6, 16, 16, 16, 1], act="tanh", perdida="mse")
g_mse = lambda t: red_mse.perdida_y_grad(t, Xr, yr)
th_e = red_mse.iniciar(0)
v = rng.normal(size=red_mse.p); v /= np.linalg.norm(v)
hist = []
for k in range(1600):
    eta = 0.2 if k < 400 else 0.1                 # en el paso 400, la tasa se divide por dos
    L, g = g_mse(th_e)
    if k % 20 == 0:
        S, v = nitidez(g_mse, th_e, v, 15 if k == 0 else 4)
        hist.append((k, L, S, 2 / eta))
    th_e -= eta * g
hist = np.array(hist)
for k, L, S, u in hist[::8]:
    print(f"paso {int(k):5d}   pérdida {L:.4f}   nitidez {S:6.2f}   2/η = {u:4.0f}")
fig, ax = plt.subplots(1, 2, figsize=(11, 3.4))
ax[0].semilogy(hist[:, 0], hist[:, 1]); ax[0].set_title("pérdida (GD de lote completo)"); ax[0].set_xlabel("paso")
ax[1].plot(hist[:, 0], hist[:, 2], label="nitidez λ_max"); ax[1].plot(hist[:, 0], hist[:, 3], "--", color="gray", label="2/η")
ax[1].set_xlabel("paso"); ax[1].legend(); plt.tight_layout(); plt.show()

Sharpness starts at 3.33.3, crosses 2/η=102/\eta = 10 around step 160 and stays slightly above, around 12.512.5, while loss falls. After halving η\eta at step 400, sharpening resumes, reaches the new 2/η=202/\eta = 20 line around step 1100 and stays slightly above, with a loss spike around step 1440. The full phenomenon in 673 parameters: no transformer is needed. (Edge dynamics are chaotic: another NumPy or BLAS version changes exact numbers after a few hundred steps, but not the pattern.)

Mode connectivity

Return to averaging two networks. If θA\theta_A and θB\theta_B are solutions trained from different seeds, their linear barrier is

B(θA,θB)=max⁡t∈[0,1][L((1−t)θA+tθB)−((1−t)L(θA)+tL(θB))],B(\theta_A, \theta_B) = \max_{t \in [0, 1]}\Big[\Loss\big((1 - t)\theta_A + t\theta_B\big) - \big((1 - t)\Loss(\theta_A) + t\Loss(\theta_B)\big)\Big],

the largest rise above linear interpolation of endpoint losses (Entezari et al., 2022). For independently trained networks it is usually large: the midpoint is a poor model. For years this was interpreted as solutions being isolated minima in different valleys. They are not.

Garipov et al. (2018) and independently Draxler et al. (2018) found such paths. Garipov’s method is direct: parameterize a curve, such as quadratic Bézier

φC(t)=(1−t)2 θA+2t(1−t) C+t2 θB,\varphi_C(t) = (1 - t)^2\,\theta_A + 2t(1 - t)\,C + t^2\,\theta_B,

with control point C∈RpC \in \R^p, and train CC by minimizing mean loss along the curve, Et∼Unif⁡[0,1][L(φC(t))]\E_{t \sim \Unif[0, 1]}\big[\Loss(\varphi_C(t))\big], with stochastic descent: each step chooses a random tt and updates CC using the gradient of L(φC(t))\Loss(\varphi_C(t)) with respect to CC, which is 2t(1−t)∇L(φC(t))2t(1 - t)\grad\Loss(\varphi_C(t)). On real vision networks, the trained curve maintains nearly constant test accuracy end to end.

InteractivePaths between solutions
AB
  • straight segment
  • trained curve (control CC)
  • your curve (control PP)
Second solution
Segment barrier0.490
Trained curve barrier0.000
Your curve barrier0.490
Test at t=1/2t = 1/2: line / curve73.1 / 97.9 %
Test of A / B94.8 / 96.1 %
∥B−A∥2\norm{B - A}_226.8
The straight segment between A and B crosses a mountain. Drag control point P to curve the path and find the valley.
Two 2-32-32-3 MLPs (1251 parameters) trained from different seeds, A and B, and training loss in the plane containing A, B and control point C of a trained Bézier curve. Coordinates are in units of ∥B−A∥\norm{B - A}. Drag control point PP of your own curve and compare loss along all three paths below. Then switch to ‘Permuted B’: the same network B with neurons reordered to resemble A.

In this example the straight segment has a loss barrier of 0.490.49 and its midpoint gets only 7373 % of test examples correct, versus 9595 and 9696 % at endpoints. The trained curve has no barrier (it remains below interpolated endpoint loss throughout) and its midpoint gets 9898 % correct: A and B lie in the same valley, but the valley is curved.

Permutation symmetries and linear connectivity

Part of the mountain is an illusion created by symmetry. Permuting hidden-layer neurons (rows of W(ℓ)\mat{W}^{(\ell)} and b(ℓ)\vb{b}^{(\ell)}, columns of W(ℓ+1)\mat{W}^{(\ell+1)}) does not change the function, so every solution has ∏ℓdℓ!\prod_\ell d_\ell! equivalent copies and independent training runs end at copies with different neuron orders. Entezari et al. (2022) conjectured that accounting for permutations, SGD solutions are linearly connected; Ainsworth, Hayase and Srinivasa (2023) confirmed this in many wide networks with weight matching, choosing each layer’s permutation by solving a linear assignment problem (the Hungarian algorithm) maximizing similarity between A and permuted B weights. In the figure, “permuted B” computes exactly B’s function, lies 15.115.1 from A instead of 26.826.8, and the straight segment to it has barrier 0.0060.006 with 9696 % midpoint accuracy.

Frankle, Dziugaite, Roy and Carbin (2020) studied the case without permutations: two copies start from the same point θk\theta_k (weights after kk training steps) and differ only in minibatch order. For k=0k = 0 they are not linearly connected in standard networks; after a small kk, an early fraction of training, they are. This stability against SGD noise makes weight averaging of models fine-tuned from the same pretraining work: Wortsman et al.’s (2022) “model soups” and model merging.

SAM: deliberately seek flat regions

If flat regions are desirable, request them explicitly. Foret, Kleiner, Mobahi and Neyshabur (2021) proposed minimizing worst-case loss in a ball around the weights.

Solving the inner maximum each step is expensive. SAM approximates it to first order: L(w+ε)≈L(w)+ε⊤∇L(w)\Loss(\vb{w} + \vb{\varepsilon}) \approx \Loss(\vb{w}) + \vb{\varepsilon}\T\grad\Loss(\vb{w}), whose maximum over the ball occurs at

ε^(w)=ρ ∇L(w)∥∇L(w)∥2.\hat{\vb{\varepsilon}}(\vb{w}) = \rho\,\frac{\grad\Loss(\vb{w})}{\norm{\grad\Loss(\vb{w})}_2}.

You will prove this in the exercises. For the outer gradient, Danskin’s theorem says that if maximizer ε⋆(w)\vb{\varepsilon}^\star(\vb{w}) is unique, ∇LρSAM(w)=∇L(w+ε⋆(w))\grad\Loss^{\mathrm{SAM}}_\rho(\vb{w}) = \grad\Loss(\vb{w} + \vb{\varepsilon}^\star(\vb{w})), without differentiating ε⋆\vb{\varepsilon}^\star with respect to w\vb{w}. SAM uses that formula with ε^\hat{\vb{\varepsilon}} instead of ε⋆\vb{\varepsilon}^\star, equivalent to discarding (∂ε^/∂w)⊤∇L(w+ε^)(\partial\hat{\vb{\varepsilon}}/\partial\vb{w})\T\grad\Loss(\vb{w} + \hat{\vb{\varepsilon}}), which contains the Hessian. The algorithm is:

  1. Compute g=∇LB(w)\vb{g} = \grad\Loss_{\mathcal{B}}(\vb{w}) on minibatch B\mathcal{B}.
  2. Ascend: ε^=ρ g/∥g∥2\hat{\vb{\varepsilon}} = \rho\,\vb{g}/\norm{\vb{g}}_2.
  3. Compute gSAM=∇LB(w+ε^)\vb{g}_{\mathrm{SAM}} = \grad\Loss_{\mathcal{B}}(\vb{w} + \hat{\vb{\varepsilon}}) on the same minibatch.
  4. Take the base optimizer step (momentum SGD, Adam…) with gSAM\vb{g}_{\mathrm{SAM}} from w\vb{w}, not w+ε^\vb{w} + \hat{\vb{\varepsilon}}.

It costs two forward and backward passes per step: twice the base optimizer. Near a minimum, where ∇L≈0\grad\Loss \approx \vb{0}, the second-order expansion gives LρSAM≈L+12ρ2λmax⁡\Loss^{\mathrm{SAM}}_\rho \approx \Loss + \tfrac{1}{2}\rho^2\lambda_{\max}: SAM penalizes spectral sharpness exactly, and the penalty matters only when ρ\rho is comparable to the sharp region’s size.

InteractiveSAM's perturbation
A, sharpB, flat
step 0 of 1500
  • SGD and its direction −∇L(w)-\nabla L(\vb{w})
  • SAM and its direction −∇L(w+ε^)-\nabla L(\vb{w} + \hat{\vb{\varepsilon}})
  • ball of radius ρ\rho and ε^=ρ g/∥g∥\hat{\vb{\varepsilon}} = \rho\,\vb{g}/\norm{\vb{g}}
  • exact maximum in the ball
η=0.05\eta = 0.05, 1500 steps; sharp minimum: L=−0.043L = -0.043, λmax⁡≈20\lambda_{\max} \approx 20; flat minimum: L=0L = 0, λmax⁡=0.9\lambda_{\max} = 0.9.
0.25
1.00
Plane color
Step kk0
L(wk)L(\vb{w}_k)0.0452
L(wk+ε^)L(\vb{w}_k + \hat{\vb{\varepsilon}}), first order0.599
max⁡∥ε∥≤ρL(wk+ε)\max_{\norm{\vb{\varepsilon}} \le \rho} L(\vb{w}_k + \vb{\varepsilon})0.604
Angle between ε^\hat{\vb{\varepsilon}} and the exact maximizer14.2°
SGD endpoint…
SAM endpoint…
Ending in flat basin across 20 seeds…
A 2D loss with a narrow hole at A, slightly deeper (λmax⁡≈20\lambda_{\max} \approx 20), inside a broad bowl centered at B (λmax⁡=0.9\lambda_{\max} = 0.9). SGD (orange) and SAM (blue) start at the same point inside the hole with the same minibatch noise. Replay SAM's trajectory: each step shows the radius-ρ\rho ball, perturbation ε^\hat{\vb{\varepsilon}} (magenta), exact ball maximizer (red circle) and both descent directions. Color the plane by SAM loss to see the hole disappear as ρ\rho grows. Try ρ=0.1\rho = 0.1, lower noise to 0.50.5 and drag the starting point.

The figure shows three things. With ρ=0.25\rho = 0.25 and noise σ=1\sigma = 1, SGD stays in the hole in all 20 seeds and SAM ends in the broad bowl in 18 of 20, even though loss there is higher (00 versus −0.043-0.043): SAM changes the loss minimized, not only the path. With ρ=0.1\rho = 0.1 the ball fits in the hole and SAM behaves like SGD. With low noise (σ=0.5\sigma = 0.5), SAM leaves the hole but oscillates at its edge because normalized perturbation crosses the ridge repeatedly: the ball maximum is always on the other side. SAM can become trapped near saddle points of L\Loss, a known stability-analysis result (Kim et al., 2023); minibatch noise gets it out in practice.

SAM from scratch with controlled compute

Two practical details matter. First, in distributed training each device computes its own ε^\hat{\vb{\varepsilon}} on its portion of the batch, size mm, and Foret et al. observed that small mm (m-sharpness) generalizes better than the full-batch version; Andriushchenko and Flammarion (2022) argue much of SAM’s effect depends on this stochasticity. Second, any fair comparison must give the base optimizer the same number of gradients. The cell compares three options on a problem with 10 % changed labels.

[ ]SAM from scratch versus GD with equal computeBrowser
def entrenar(f, th, eta, pasos, rho=0.0):
    """GD (rho = 0) o SAM (rho > 0) de lote completo. Devuelve theta y el número de gradientes calculados."""
    grads = 0
    for _ in range(pasos):
        L, g = f(th); grads += 1
        if rho > 0:
            eps = rho * g / (np.linalg.norm(g) + 1e-12)   # ascenso: perturbación de primer orden
            g = f(th + eps)[1]; grads += 1               # gradiente en el punto perturbado
        th = th - eta * g                                # el paso se da desde th, no desde th + eps
    return th, grads

Xn, yn = espirales(semilla=3, ruido=0.45)
yn = yn.copy(); vol = np.random.default_rng(4).random(len(yn)) < 0.1
yn[vol] = (yn[vol] + 1) % 3                              # 10 % de etiquetas cambiadas
Xt2, yt2 = espirales(n_por_clase=300, semilla=5, ruido=0.45)
red2 = MLP([2, 16, 16, 3], act="tanh")
f2 = lambda t: red2.perdida_y_grad(t, Xn, yn)
t0 = red2.iniciar(7)
for nombre, rho, pasos in [("GD, 600 pasos", 0.0, 600), ("GD, 1200 pasos", 0.0, 1200), ("SAM ρ = 0.1, 600 pasos", 0.1, 600)]:
    t_, ng = entrenar(f2, t0.copy(), 0.3, pasos, rho)
    lam, _ = potencia(lambda v: hvp(f2, t_, v), red2.p, 40)
    print(f"{nombre:24s} gradientes {ng:5d}   pérdida {f2(t_)[0]:.3f}   λ_max {lam:6.3f}   "
          f"precisión test {red2.precision(t_, Xt2, yt2):.3f}")

With equal gradients (1200), SAM ends at less than half GD’s sharpness (2.142.14 versus 4.794.79) and somewhat higher training loss, with virtually equal test accuracy (94.994.9 versus 95.395.3 %). On this small problem flatness is achieved without better generalization. In large-scale vision Foret et al. reported consistent improvements; this toy case does not refute them but reminds us “flatter” and “generalizes better” are distinct claims to measure separately.

The library version

In PyTorch the exact Hessian-vector product is obtained by composing torch.func.jvp over torch.func.grad (forward over reverse) or double backward; ARPACK Lanczos is in scipy.sparse.linalg.eigsh, accepting an LinearOperator; and SAM is a two-phase wrapper around any optimizer. For large networks PyHessian (Yao et al., 2020) packages power iteration, stochastic Lanczos and Hutchinson trace estimation. The cell runs on CPU with a small model; on your machine change device for real networks (device placement).

[ ]Exact HVP, ARPACK Lanczos and SAM in PyTorchLocal GPU
import numpy as np
import torch
from torch.func import functional_call, grad, jvp
from scipy.sparse.linalg import LinearOperator, eigsh

torch.manual_seed(0)
device = "cpu"          # en tu máquina, "cuda" para redes de verdad; aquí basta la CPU
X = torch.randn(512, 10, device=device)
y = (X[:, 0] * X[:, 1] > 0).long() + (X[:, 2] > 0.5).long()           # 3 clases
modelo = torch.nn.Sequential(torch.nn.Linear(10, 64), torch.nn.Tanh(), torch.nn.Linear(64, 64),
                             torch.nn.Tanh(), torch.nn.Linear(64, 3)).to(device)
modelo.eval()           # sin dropout ni BatchNorm en modo entrenamiento al medir curvatura

class SAM(torch.optim.Optimizer):
    """SAM (Foret et al., 2021) como envoltorio de cualquier optimizador base."""
    def __init__(self, params, base, rho=0.05, **kw):
        super().__init__(params, dict(rho=rho, **kw))
        self.base = base(self.param_groups, **kw)

    @torch.no_grad()
    def primer_paso(self):
        normas = [p.grad.norm() for g in self.param_groups for p in g["params"] if p.grad is not None]
        escala = self.param_groups[0]["rho"] / (torch.stack(normas).norm() + 1e-12)
        for g in self.param_groups:
            for p in g["params"]:
                if p.grad is None: continue
                e = p.grad * escala
                p.add_(e); self.state[p]["e"] = e        # w <- w + eps
        self.zero_grad()

    @torch.no_grad()
    def segundo_paso(self):
        for g in self.param_groups:
            for p in g["params"]:
                if "e" in self.state[p]: p.sub_(self.state[p]["e"])   # vuelve a w
        self.base.step()                                 # paso con el gradiente de w + eps
        self.zero_grad()

def perdida_de(params):
    return torch.nn.functional.cross_entropy(functional_call(modelo, params, (X,)), y)

def nitidez(modelo, k=3):
    params = {n: p.detach() for n, p in modelo.named_parameters()}
    nombres, formas = list(params), [p.shape for p in params.values()]
    tam = [p.numel() for p in params.values()]
    g = grad(perdida_de)
    def hvp(v):           # hacia delante sobre hacia atrás: derivada direccional del gradiente
        partes = torch.split(torch.as_tensor(v, dtype=torch.float32, device=device), tam)
        tang = {n: t.view(s) for n, t, s in zip(nombres, partes, formas)}
        _, hv = jvp(g, (params,), (tang,))
        return torch.cat([hv[n].reshape(-1) for n in nombres]).double().cpu().numpy()
    p = sum(tam)
    op = LinearOperator((p, p), matvec=hvp, dtype=np.float64)
    return eigsh(op, k=k, which="LA", tol=1e-4, return_eigenvectors=False)[::-1]

for nombre, rho in [("SGD", 0.0), ("SAM", 0.05)]:
    torch.manual_seed(1)
    for capa in modelo:
        if hasattr(capa, "reset_parameters"): capa.reset_parameters()
    opt = SAM(modelo.parameters(), torch.optim.SGD, rho=rho, lr=0.1, momentum=0.9) if rho > 0 else \
          torch.optim.SGD(modelo.parameters(), lr=0.1, momentum=0.9)
    pasadas, a_igual_perdida = 0, None
    for epoca in range(30):
        for idx in torch.randperm(512).split(32):
            perdida = torch.nn.functional.cross_entropy(modelo(X[idx]), y[idx])
            perdida.backward(); pasadas += 1
            if rho > 0:
                opt.primer_paso()
                torch.nn.functional.cross_entropy(modelo(X[idx]), y[idx]).backward(); pasadas += 1
                opt.segundo_paso()
            else:
                opt.step(); opt.zero_grad()
        with torch.no_grad():
            L = perdida_de(dict(modelo.named_parameters())).item()
        if a_igual_perdida is None and L < 0.08:      # primera época con pérdida de entrenamiento < 0.08
            a_igual_perdida = (epoca + 1, L, nitidez(modelo, k=1)[0])
    print(f"{nombre}: al final, pérdida {L:.4f} y tres mayores autovalores {np.round(nitidez(modelo), 3)};  "
          f"{pasadas} pasadas hacia atrás")
    e, Le, S = a_igual_perdida
    print(f"      primera época con pérdida < 0.08: la {e} (pérdida {Le:.4f}), con λ_max = {S:.3f}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The output contains an instructive trap. After 30 epochs SGD has less sharpness than SAM (0.370.37 versus nearly 11), but also about four times lower loss (0.0120.012 versus about 0.050.05; SAM’s last digits vary slightly across machines due to parallel summation order), and with cross-entropy curvature falls by itself as loss approaches zero. Comparing when each first crosses loss 0.080.08, SAM is in a flatter region (0.860.86 versus 1.121.12). Measuring sharpness without matching loss, like failing to match compute, can reverse the conclusion.

What is established and what is open

ClaimStatus
On a quadratic, GD diverges if ηλmax⁡>2\eta\lambda_{\max} > 2; with momentum β\beta, if ηλmax⁡>2+2β\eta\lambda_{\max} > 2 + 2\betaTheorem
Sharpness and minimum volume change under function-preserving reparameterizationsTheorem (Dinh et al.)
Filter-normalized slices are invariant under layer and BatchNorm-filter rescalingTheorem (elementary)
An HVP costs about two gradients; Lanczos obtains spectrum extremes with tens of HVPsTheorem and standard practice
Spectrum has mass near zero and a few outliersVery robust empirical regularity
Progressive sharpening and edge of stability in full-batch GDVery robust empirical regularity; partial theory (self-stabilization under assumptions)
Independent solutions are connected by low-loss curvesRobust empirical regularity in vision networks
Linear connectivity up to permutationsRobust in wide networks; conjectural generally
Large batches lead to sharper minimaFrequent, but depends on η\eta schedule and step count
SAM improves generalizationFrequent in vision; mechanism (flatness, mm-sharpness noise, implicit regularization) is debated
Flat minima generalize better because they are flatOpen hypothesis; correlational evidence is mixed and measure-dependent

Common mistakes

Exercises

QuizThe misleading slice
You train the same BatchNorm network twice, without and with strong weight decay, and plot 2D slices using fixed-norm Gaussian directions without filter normalization. The weight-decay network looks much sharper. What is the most likely explanation?
NumericWhere does sharpness stabilize?
You train by full-batch gradient descent at constant rate η=0.02\eta = 0.02. Under the edge-of-stability phenomenon, around what value should λmax⁡(∇2L)\lambda_{\max}(\hess\Loss) stabilize if progressive sharpening is sufficient?
NumericThe edge with momentum
With heavy-ball momentum, θt+1=θt−η∇L(θt)+β(θt−θt−1)\theta_{t+1} = \theta_t - \eta\grad\Loss(\theta_t) + \beta(\theta_t - \theta_{t-1}), β=0.9\beta = 0.9 and η=0.01\eta = 0.01, at what λ\lambda does iteration on a quadratic of curvature λ\lambda cease to be stable?
NumericSharpening a minimum without changing the function
At minimum θ⋆=(θ1,θ2)\theta^\star = (\theta_1, \theta_2) of a ReLU network, the Hessian block for θ1\theta_1 has largest eigenvalue λmax⁡(H11)=0.5\lambda_{\max}(\mat{H}_{11}) = 0.5. Apply reparameterization Tc(θ1,θ2)=(c θ1,θ2/c)T_c(\theta_1, \theta_2) = (c\,\theta_1, \theta_2/c) with c=0.1c = 0.1. What is the best lower bound Dinh et al.'s theorem gives for λmax⁡\lambda_{\max} of the Hessian at Tcθ⋆T_c\theta^\star?
NumericWhat a random slice sees
A network has p=106p = 10^6 parameters. At its minimum the Hessian has λmax⁡=200\lambda_{\max} = 200, nine other outliers summing to 300300, and the rest sum to 2020. What is expected curvature δ^⊤Hδ^\hat{\vb{\delta}}\T\mat{H}\hat{\vb{\delta}} along a uniformly random unit direction?
QuizA contaminated measurement
You measure λmax⁡\lambda_{\max} of a dropout and BatchNorm model by power iteration with finite-difference Hessian-vector products on random 64-example minibatches in training mode. Values vary greatly across runs and grow as ε\varepsilon decreases. What fixes the measurement?
ProofQuadratic divergence and why the edge does not contradict it
Prove: Let L(θ)=12(θ−θ⋆)⊤H(θ−θ⋆)\Loss(\theta) = \tfrac{1}{2}(\theta - \theta^\star)\T\mat{H}(\theta - \theta^\star) with symmetric H\mat{H} and largest eigenvalue λmax⁡>0\lambda_{\max} > 0. If λmax⁡>2/η\lambda_{\max} > 2/\eta, gradient descent at rate η\eta diverges from almost every initial point. In networks the edge of stability (sharpness above 2/η2/\eta without divergence) does not contradict this.
0
Write et=θt−θ⋆\vb{e}_t = \theta_t - \theta^\star and let H=∑iλiuiui⊤\mat{H} = \sum_i \lambda_i\vb{u}_i\vb{u}_i\T be its spectral decomposition.

Step 1 of 4. How does et\vb{e}_t evolve?

ProofSAM's first-order perturbation
Prove: If ∇L(w)≠0\grad\Loss(\vb{w}) \neq \vb{0}, the maximizer of linear approximation L(w)+ε⊤∇L(w)\Loss(\vb{w}) + \vb{\varepsilon}\T\grad\Loss(\vb{w}) in the ball ∥ε∥2≤ρ\norm{\vb{\varepsilon}}_2 \le \rho is ε^(w)=ρ ∇L(w)/∥∇L(w)∥2\hat{\vb{\varepsilon}}(\vb{w}) = \rho\,\grad\Loss(\vb{w})/\norm{\grad\Loss(\vb{w})}_2, and therefore ε⋆(w)≈ε^(w)\vb{\varepsilon}^\star(\vb{w}) \approx \hat{\vb{\varepsilon}}(\vb{w}).
0
Let g=∇L(w)\vb{g} = \grad\Loss(\vb{w}). Maximize linear function ε↦ε⊤g\vb{\varepsilon} \mapsto \vb{\varepsilon}\T\vb{g} on the ball.

Step 1 of 4. What upper bound holds for ε⊤g\vb{\varepsilon}\T\vb{g} on the ball?

CodePower iteration and Lanczos with a black-box HVP
Implement top_eigenvalue(hvp, dim, iters=100, seed=0), returning (lam, v) with the largest-magnitude eigenvalue estimate (Rayleigh quotient) and an associated unit vector, and lanczos_extremes(hvp, dim, k, seed=0), performing k Lanczos steps with full reorthogonalization and returning Ritz values (eigenvalues of tridiagonal Tk\mat{T}_k) in ascending order. hvp(v) is a black box returning Hv\mat{H}\vb{v} for symmetric H\mat{H}; you cannot access H\mat{H}. Each Lanczos step must call hvp exactly once. If βj\beta_j vanishes (invariant subspace), stop and return Ritz values obtained so far.
import numpy as np

def top_eigenvalue(hvp, dim, iters=100, seed=0):
  v = np.random.default_rng(seed).normal(size=dim)
  v /= np.linalg.norm(v)
  lam = 0.0
  # tu código: iteración de la potencia con el cociente de Rayleigh
  return lam, v

def lanczos_extremes(hvp, dim, k, seed=0):
  q = np.random.default_rng(seed).normal(size=dim)
  q /= np.linalg.norm(q)
  # tu código: recurrencia de tres términos, reortogonalización completa y valores de Ritz
  return np.zeros(k)
Shift+Enter to run

Summary

Key idea
Deep-learning loss geometry can be measured with Hessian-vector products, but every measure has a trap: random slices see mean curvature, sharpness depends on parameterization and comparison loss, and gradient descent does not remain where a quadratic predicts but at the edge λmax⁡≈2/η\lambda_{\max} \approx 2/\eta.
  • L(θ⋆+αδ1+βδ2)\Loss(\theta^\star + \alpha\vb{\delta}_1 + \beta\vb{\delta}_2) slices need filter normalization to compare different weight scales, yet a random direction sees only tr⁡H/p\tr\mat{H}/p.
  • A Hessian-vector product costs about two gradients. Power iteration gives λmax⁡\lambda_{\max}, reorthogonalized Lanczos both extremes and stochastic Lanczos spectral density: huge mass near zero and a few outliers.
  • Spectral, worst-case and volume sharpness agree locally, but none is invariant: rescaling ReLU layers changes it without changing the function. Its generalization relationship is an open empirical question.
  • With full-batch gradient descent sharpness grows (progressive sharpening) to 2/η2/\eta and stays there while loss falls nonmonotonically; Taylor’s cubic term explains self-stabilization. With η\eta somewhat above 2/λ02/\lambda_0, catapult sends the network to a flatter region.
  • Independent solutions are usually connected by low-loss curves; after accounting for neuron permutations often also by a straight segment, and copies sharing early training are linearly connected.
  • SAM minimizes max⁡∥ε∥≤ρL(w+ε)\max_{\norm{\vb{\varepsilon}} \le \rho}\Loss(\vb{w} + \vb{\varepsilon}) with first-order perturbation ρ∇L/∥∇L∥\rho\grad\Loss/\norm{\grad\Loss} and the gradient at the perturbed point: twice the cost per step, reduced sharpness and often better generalization, although whether flatness causes it is unclear.