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
- 06Gradient descent dynamics on quadraticsCritical point classification and saddle pointsStrict saddle propertyInexact Newton (Newton-CG)Stochastic gradient descentAdamLearning-rate schedules
- 00Canonical training and evaluation loopDevice placement and CPU-GPU transfersFull training checkpoint
- 09Mode composition and higher-order derivativesKrylov subspaces, Arnoldi and LanczosPower iteration
- 03Hessian-vector product
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 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 and trained solution , evaluate loss along their connecting segment:
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 and plot
Before viewing plots, understand what they can see. A random slice sees an average, not an extreme.
Proof
By symmetry is invariant under conjugation by any orthogonal matrix, so it is ; its trace is , so . Then . For the second result, condition on : .
∎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 and an outlier eigenvalue of , its contribution to mean curvature is . 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 parameters, slice-direction curvature is on the order of to % of , 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 and the next layer’s weights by , because . 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 is filter in layer (in a dense layer, the weight vector entering neuron ) and the corresponding part of a Gaussian direction, take
and set bias and normalization-parameter components to zero. Each filter is perturbed in proportion to its own size.
Proof
Layer filters of have norm , so ; layer filters have norm , so ; the rest are unchanged and biases unperturbed. Since is linear, , and for every 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 .
∎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.
Three readings, with these networks’ numbers. The non-residual full-batch network has the narrowest valley and largest of the four ( versus 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 leaves the function intact, the normalized slice identical (maximum measured difference: ), and multiplies by over 9 in the non-residual batch-16 network (). This rescaling composes the theorem’s on consecutive layer pairs (factors and cancel in intermediate layers); the same argument holds in the residual version because the whole hidden representation is multiplied by , so the normalized slice does not change. Third, “fraction of ” never reaches 2 %: the slice shows mean curvature, not maximum.
The Hessian spectrum
Hessian-vector products
With in the millions one cannot form , but can multiply it by a vector. The Hessian-vector product is the gradient’s directional derivative,
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,
with error if the third derivative of is Lipschitz (e.g. if is class ). This condition matters: with ReLU the gradient jumps when a neuron changes regime, and finite differences may give absurd values; the cells use for these measurements.
Power iteration and Lanczos
Using only products, power iteration gives the eigenvalue of greatest magnitude: eigenvector error decreases as and, because is symmetric, Rayleigh quotient error as . At training’s end it is usually , but not always: if the most negative eigenvalue has greater magnitude, power iteration converges to it. Separate extremes with a shift ( has dominant eigenvalue ) or, better, Lanczos.
Lanczos builds an orthonormal basis of the Krylov subspace in which is tridiagonal,
using a three-term recurrence: . Eigenvalues of (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 steps is bounded by a multiple of for power iteration and 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 steps used in diagnostics, the robust solution is full reorthogonalization: project each new vector against all previous vectors twice. It costs storage of vectors of size .
Spectral density and stochastic Lanczos
To estimate without computing eigenvalues, Ghorbani, Krishnan and Xiao (2019) used stochastic Lanczos quadrature. If and is unit, with weights summing to 1 and, by the previous section’s theorem, averaging for random . That sum is an integral against a discrete measure approximated by Gauss quadrature with nodes: Ritz values of with weights , where is the associated eigenvector of . Averaging a few probes and replacing each node by a Gaussian of width estimates 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 , 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 classes, on the order of ).
- 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 with outputs and Jacobians ,
The first term is positive semidefinite when is convex in the output (cross-entropy and squared error are), and has rank at most , 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 .
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.
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 parameters, reaches loss 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.
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 (, , , , ) to all shown digits, and the smallest, , which power iteration does not attempt. The spectrum has exactly the described shape: of , a second outlier of and % of 371 eigenvalues below 1 % of ; 87 are negative, all tiny. The next cell estimates density with stochastic Lanczos and compares exact.
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 error on the order of ; for a network of 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 , 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 does not change the function, for every . is linear with matrix , so differentiating twice by the chain rule yields ; at this is the stated formula. Block of is , 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 is positive semidefinite at a minimum and nonzero, .
∎Any minimum can be made arbitrarily sharp without changing predictions; Dinh et al. show the same for volume notions. In the first figure, with the batch-16 residual network moves from to 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 , gradient descent evolves as , and in the eigenvector basis each component is multiplied by per step. The component grows if . This is the classical rule, consistent with the descent lemma: with loss decreases each step. The usual reading was that a network of curvature must train with , and training diverges if curvature exceeds .
What happens in networks
Cohen, Kaur, Li, Kolter and Talwalkar (2021) measured 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.
In the simulation initial sharpness is . With it reaches around step 90 and overshoots to almost double; oscillation along the sharpest direction grows, loss jumps and sharpness abruptly falls to . After a couple more cycles, from step 300 it oscillates between and while loss falls from to under with intermittent increases. Halving at step 400 makes loss fall suddenly (the sharpest direction is stable again and oscillation damps), and sharpening resumes to the new line, reached around step 1300; somewhat later another loss spike appears and sharpness settles at . Timing matters: halving at step 600, with loss already lower, makes sharpening slower and at step 6000 sharpness remains without touching the line. With threshold is : sharpness rises to in 6000 steps, with loss already , and never reaches it. Without an edge there is no edge regime.
Why it does not explode: self-stabilization
Quadratic theory assumes 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 be the unit eigenvector of at reference point and displacement in that direction. Then
and if is simple, : the derivative of a simple eigenvalue is . The descent step therefore contains term . The cycle is:
- Sharpening: while , damps and grows for whatever reason (progressive sharpening).
- Explosion: when , component is multiplied by each step and oscillates with growing amplitude. Loss rises.
- Self-stabilization: with large, term dominates and gradient descent lowers sharpness, as if minimizing .
- Return: when 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 subject to : an implicit bias toward regions of sharpness at most . 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 ? Lewkowycz, Bahri, Dyer, Sohl-Dickstein and Gur-Ari (2020) described three regimes depending on . With , normal training. For somewhat above , loss grows for a few steps, curvature falls below and the network is “catapulted” into a flatter region where it converges. Beyond it diverges. In their analyzable model , and in ReLU networks they empirically found larger values on the order of . In the figure’s network causes a catapult: in the first 60 steps loss spikes twice (up to from ), sharpness oscillates strongly then settles around , below and exactly at , while loss falls to . With 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 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 below threshold.
- Momentum and Adam change the threshold. With heavy-ball momentum , the quadratic is stable if . For Adam, Cohen et al. (2022) observed the same phenomenon with preconditioned sharpness stabilizing at for .
- With small minibatches sharpness usually stabilizes below (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 at step 400.
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 , crosses around step 160 and stays slightly above, around , while loss falls. After halving at step 400, sharpening resumes, reaches the new 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 and are solutions trained from different seeds, their linear barrier is
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
with control point , and train by minimizing mean loss along the curve, , with stochastic descent: each step chooses a random and updates using the gradient of with respect to , which is . On real vision networks, the trained curve maintains nearly constant test accuracy end to end.
In this example the straight segment has a loss barrier of and its midpoint gets only % of test examples correct, versus and % at endpoints. The trained curve has no barrier (it remains below interpolated endpoint loss throughout) and its midpoint gets % 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 and , columns of ) does not change the function, so every solution has 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 from A instead of , and the straight segment to it has barrier with % midpoint accuracy.
Frankle, Dziugaite, Roy and Carbin (2020) studied the case without permutations: two copies start from the same point (weights after training steps) and differ only in minibatch order. For they are not linearly connected in standard networks; after a small , 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: , whose maximum over the ball occurs at
You will prove this in the exercises. For the outer gradient, Danskin’s theorem says that if maximizer is unique, , without differentiating with respect to . SAM uses that formula with instead of , equivalent to discarding , which contains the Hessian. The algorithm is:
- Compute on minibatch .
- Ascend: .
- Compute on the same minibatch.
- Take the base optimizer step (momentum SGD, Adam…) with from , not .
It costs two forward and backward passes per step: twice the base optimizer. Near a minimum, where , the second-order expansion gives : SAM penalizes spectral sharpness exactly, and the penalty matters only when is comparable to the sharp region’s size.
The figure shows three things. With and noise , 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 ( versus ): SAM changes the loss minimized, not only the path. With the ball fits in the hole and SAM behaves like SGD. With low noise (), 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 , 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 on its portion of the batch, size , and Foret et al. observed that small (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.
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 ( versus ) and somewhat higher training loss, with virtually equal test accuracy ( versus %). 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).
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}")npm run lab and open the connection link.The output contains an instructive trap. After 30 epochs SGD has less sharpness than SAM ( versus nearly ), but also about four times lower loss ( versus about ; 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 , SAM is in a flatter region ( versus ). Measuring sharpness without matching loss, like failing to match compute, can reverse the conclusion.
What is established and what is open
| Claim | Status |
|---|---|
| On a quadratic, GD diverges if ; with momentum , if | Theorem |
| Sharpness and minimum volume change under function-preserving reparameterizations | Theorem (Dinh et al.) |
| Filter-normalized slices are invariant under layer and BatchNorm-filter rescaling | Theorem (elementary) |
| An HVP costs about two gradients; Lanczos obtains spectrum extremes with tens of HVPs | Theorem and standard practice |
| Spectrum has mass near zero and a few outliers | Very robust empirical regularity |
| Progressive sharpening and edge of stability in full-batch GD | Very robust empirical regularity; partial theory (self-stabilization under assumptions) |
| Independent solutions are connected by low-loss curves | Robust empirical regularity in vision networks |
| Linear connectivity up to permutations | Robust in wide networks; conjectural generally |
| Large batches lead to sharper minima | Frequent, but depends on schedule and step count |
| SAM improves generalization | Frequent in vision; mechanism (flatness, -sharpness noise, implicit regularization) is debated |
| Flat minima generalize better because they are flat | Open hypothesis; correlational evidence is mixed and measure-dependent |
Common mistakes
Exercises
Step 1 of 4. How does evolve?
Step 1 of 4. What upper bound holds for on the ball?
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 ) in ascending order. hvp(v) is a black box returning for symmetric ; you cannot access . Each Lanczos step must call hvp exactly once. If 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)Summary
- slices need filter normalization to compare different weight scales, yet a random direction sees only .
- A Hessian-vector product costs about two gradients. Power iteration gives , 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 and stays there while loss falls nonmonotonically; Taylor’s cubic term explains self-stabilization. With somewhat above , 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 with first-order perturbation 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.