The nonconvex reality: saddle points, negative curvature and benign landscapes
Study realistic guarantees for nonconvex optimization, including saddle points, perturbed gradient descent, benign landscapes and the PL condition in overparameterized models.
After this lesson you can
- Explain why general nonconvex optimization is intractable and identify realistic first- and second-order stationarity guarantees.
- Define the strict saddle property and explain why small-step GD avoids strict saddles from almost every initialization.
- Implement perturbed GD and measure its escape time against plain GD near a saddle.
- Prove that rank-one symmetric factorization has no spurious local minima.
- Explain how overparameterization induces the PL condition and why SGD converges linearly in the interpolation regime.
Before you start
- 06Critical point classification and saddle pointsSecond-order optimality conditionsGradient descent convergence to stationary pointsPolyak-Łojasiewicz conditionStochastic gradient descentSGD convergence for convex problemsGradient descent dynamics on quadraticsSGD convergence for nonconvex problems
- 02Spectral theoremRayleigh quotient
- 08NP-hardness and NP-completenessPolynomial-time reduction
- 03Linearization and tangent planeStability by linearization
- 09Fixed-point iteration
- 00autograd dynamic graphDevice placement and CPU-GPU transfers
Motivation: networks are nonconvex and yet they train
All the module’s convergence theory rests, in one way or another, on convexity: the rate of GD, Nesterov acceleration, dual certificates. A neural network’s loss is not convex, not because of a technical detail but for a structural reason visible in the smallest possible example: a two-layer, one-neuron linear “network”, , fitted to datum with squared loss,
Its global minimizers form the hyperbola , which has two branches. The midpoint of and is the origin, where . Since the set of minimizers of a convex function is convex, cannot be convex. The origin is also a critical point: vanishes at , and its Hessian there is , with eigenvalues . It is a saddle.
The same happens in any network. Permuting a layer’s hidden neurons (and the corresponding weight rows and columns) does not change the function computed by the network, so every global minimum is accompanied by its permuted copies, and the segment joining two of them often passes through worse configurations. A real network has an astronomical number of these symmetries, and between two isolated minima separated by a barrier the mountain pass theorem guarantees (under compactness conditions) a critical point that is not a minimum.
Yet SGD trains networks with billions of parameters reliably. This lesson studies why that is not a miracle, and how far what can be proved goes:
- The impossible. Deciding whether a point is a local minimum is already NP-hard in general. We must settle for more modest goals: first- and second-order stationary points.
- The real obstacle. In high dimension, high-loss critical points are almost always saddles, not bad minima.
- Saddles are not traps. GD does not converge to a strict saddle except from a measure-zero set, although it may take a long time to leave; with perturbations it escapes in polynomial time.
- Benign landscapes. Important nonconvex problems (factorization, PCA, matrix completion) have no spurious local minima.
- Overparameterization. In sufficiently wide networks, with many more parameters than data, the loss satisfies the Polyak–Łojasiewicz condition near initialization, and GD and SGD converge linearly.
What cannot be guaranteed
In lesson 8 you saw that GD with step finds a point with in iterations without any convexity: the nonconvex stationarity result. But a stationary point may be a minimum, saddle or maximum. Can we ask for more? Can we at least check whether the point reached is a local minimum?
In general, no. Recall the classification of critical points: if the Hessian is positive definite, the point is a strict minimum; if it has a negative eigenvalue, it is not a minimum. The problem lies in the semidefinite case, where second-order conditions decide nothing and higher orders must be examined. The extreme case is a homogeneous degree-4 polynomial, whose gradient and Hessian at the origin vanish.
Proof
There are three steps.
Local minimum equals copositivity. is homogeneous of degree 4, , so is a local minimum if and only if for every (if it were negative at some , it would be negative at with arbitrarily small ). With , which ranges over the entire orthant , this says for all : that is copositive.
Copositivity and cliques. Let be a graph with adjacency matrix and clique number (the size of its largest clique). The Motzkin–Straus theorem (1965) says on the simplex . With ( is the all-ones matrix) and using on , this is . Take . On the simplex, , and by homogeneity it suffices to consider the simplex:
Reduction. CLIQUE, deciding whether , is NP-complete, and is a polynomial reduction from CLIQUE to deciding that is not a local minimum of . The problem is in NP because a rational with is a verifiable certificate, and one of polynomial size exists: the minimizer of on the simplex is attained in the relative interior of a face, where it solves a linear system with the data of .
∎Murty and Kabadi’s original reduction starts from SUBSET SUM; the one above, via the Motzkin–Straus theorem, is shorter and gives the same result.
The cell constructs a graph with (a hexagon with two chords forming two triangles) and checks both sides of the equivalence. With , the triangle indicator witnesses that is not copositive, and is negative along curve however small is. With , the value on the triangle is exactly 0 and the sampled minimum is positive; but note that sampling never proves copositivity: this asymmetry between finding a witness and certifying its absence is exactly that of NP versus co-NP.
import itertools
import numpy as np
n = 6
aristas = [(i, (i + 1) % n) for i in range(n)] + [(0, 2), (3, 5)] # C6 y dos cuerdas: triángulos {0,1,2} y {3,4,5}
A = np.zeros((n, n))
for i, j in aristas:
A[i, j] = A[j, i] = 1
def omega(A):
"""Número de clique por fuerza bruta (exponencial: solo para grafos diminutos)."""
m = len(A)
return max(r for r in range(1, m + 1) for S in itertools.combinations(range(m), r)
if all(A[i, j] for i, j in itertools.combinations(S, 2)))
B = np.ones((n, n)) - A # J − A
w = omega(A)
rng = np.random.default_rng(0)
Z = rng.dirichlet(0.3 * np.ones(n), size=200_000) # puntos del símplex
print(f"ω(G) = {w}; mín. muestreado de xᵀBx en el símplex = {np.einsum('si,ij,sj->s', Z, B, Z).min():.4f} (1/ω = {1/w:.4f})")
def f(x, M): # f(x) = Σ M_ij x_i² x_j²: gradiente y hessiano nulos en 0
z = x * x
return z @ M @ z
tri = np.array([1, 1, 1, 0, 0, 0]) / 3 # indicadora del triángulo {0, 1, 2}
for k in (2, 3):
M = k * B - np.ones((n, n))
pmin = np.einsum('si,ij,sj->s', Z, M, Z).min()
print(f"k = {k}: zᵀMz en el triángulo = {tri @ M @ tri:+.4f}; mín. muestreado = {pmin:+.4f}; "
f"f(t·√z) con t = 1e-3: {f(1e-3 * np.sqrt(tri), M):+.2e}")The practical consequence is clear: no efficient algorithm can guarantee local minima in general (unless P = NP), much less global ones. What we can ask for is what the gradient and Hessian measure.
First- and second-order stationarity
The scale is not arbitrary: it is the only combination of (units of per length cubed) and (units of per length) with curvature units. With it the definition is invariant to rescaling and the result is natural: a local minimum satisfies both conditions with , and near it they hold with small . The converse fails only in degenerate cases, and excluding them requires an assumption about .
The robust version divides space into three regions, each with a progress argument: gradient descent in the first, negative-curvature descent in the second and local linear convergence in the third. Under it, a second-order -point with sufficiently small must be near a local minimum.
Three examples clarify the ideas:
- at the origin: Hessian with eigenvalues . Strict saddle.
- at the origin: Hessian , positive semidefinite. Passes the second-order test and is not a minimum (). Non-strict saddle.
- The monkey saddle : gradient and Hessian vanish at the origin. Three valleys and three ridges that no second-order test distinguishes from a minimum.
Non-strict saddles are exactly where the difficulty in Murty and Kabadi’s theorem lies, and they must be excluded by assumption.
Saddles everywhere: the high-dimensional argument
Why worry more about saddles than bad local minima? Because in high dimension they are overwhelmingly more numerous. The naive argument: at a “generic” critical point the Hessian has eigenvalues, and to be a minimum they must all be positive. If their signs were independent coins, the probability would be . Reality is even more extreme, because eigenvalues of a random matrix repel one another: for the GOE matrix (symmetric with Gaussian entries), Dean and Majumdar (2006) calculated that
which decays as , not . With parameters, is so small that no conceivable sampling would find a minimum “at random.”
The argument becomes quantitative in a concrete model. In an isotropic Gaussian field , Bray and Dean (2007) calculated that, conditional on being a critical point with value , the Hessian is a GOE matrix shifted in proportion to . When its spectrum fills a semicircle of fixed radius centered at , a decreasing function of . The critical point’s index , the fraction of negative eigenvalues, is then the mass of the semicircle to the left of 0:
for the radius-2 semicircle. The important conclusion is that the index grows with loss. High-loss critical points are saddles with many escape directions; index-zero points (minima) concentrate in a narrow band near the bottom, where the entire semicircle has moved to the right of zero.
Empirical evidence in real networks points the same way. Dauphin, Pascanu, Gulcehre, Cho, Ganguli and Bengio (2014) located critical points of small perceptrons trained on reduced versions of MNIST and CIFAR-10 (using Newton’s method, which, as we will see, is attracted to saddles) and observed a monotonic relation between training error and index, as in the figure. Choromanska, Henaff, Mathieu, Ben Arous and LeCun (2015) obtained the same structure in multilayer ReLU networks after reducing them to a spherical spin glass, with independence assumptions the authors themselves recognize as unrealistic.
An exact case: the linear network
The factorization with is a two-layer linear network with tied weights (a linear autoencoder), and its critical points are known exactly. With , :
- critical points are, up to rotations , matrices whose columns are for a subset of indices with (and zero columns to fill up to );
- their loss is ;
- their index, the number of negative Hessian eigenvalues, is
Each term counts an escape: swap a chosen direction for a better missing one, or fill an empty column with any missing direction. The only critical point with no exits is , the global minimum. You will verify the formula numerically, with a critical-point finder and the Hessian, in the implementation section. This is the pattern of Baldi and Hornik (1989) for linear autoencoders and the archetype of what we call a benign landscape.
GD avoids strict saddles almost surely
Begin with the quadratic, where everything is explicit. For with , GD with step is the linear iteration analyzed in GD on quadratics, and in the eigenvector basis
If and , the component contracts; if , it grows as . GD converges to saddle if and only if has no component in negative- or zero-curvature directions: if is in subspace , the saddle’s stable manifold. If , has dimension less than and zero Lebesgue measure.
For a general , near a critical point GD resembles its linearization, and the tool converting that intuition into a theorem is stability by linearization of dynamical systems, applied to the fixed-point iteration with .
Proof
is an injective local diffeomorphism. Its differential is , with eigenvalues , hence invertible everywhere. And is injective: if , then and , which with forces . In particular, the preimage under (and ) of a null set is null.
Local stable manifold. At a strict saddle , has eigenvalue . The center-stable manifold theorem gives a neighborhood of and a submanifold of dimension equal to the number of eigenvalues of modulus (less than , hence measure zero) containing every point whose future orbit remains in .
Globalization. If , there exists with for every , so and : a countable union of null sets. If there are infinitely many saddles, cover them with countably many neighborhoods (every subset of is Lindelöf) and repeat the argument.
∎Lee et al. proved the result for isolated saddles; the globalization step for infinitely many non-isolated saddles is due to Panageas and Piliouras.
This result is reassuring and misleading at the same time. It says GD eventually escapes every strict saddle, but not when. In the quadratic, if has component in the curvature direction , escaping to distance costs
iterations, an unbounded quantity as . And the situation can be much worse: Du, Jin, Lee, Jordan, Singh and Póczos (2017) constructed smooth functions in with a chain of saddles where each leaves GD near the stable manifold of the next; with reasonable random initialization, GD takes time exponential in to escape them all.
Perturbed GD: escaping in polynomial time
The figure suggests the remedy. If the problem near a saddle is a tiny unstable component, give it a reasonable size: add noise when the gradient is small. Jin, Ge, Netrapalli, Kakade and Jordan (2017) turned this into an algorithm with guarantees.
Far from stationary points PGD is GD. Near one, the perturbation is a bet: if the point is (almost) a local minimum, the perturbation barely raises and GD returns; if it is a saddle, with high probability the perturbation falls outside a narrow strip around the stable manifold and negative curvature amplifies it. The time taken by this escape from saddle points can be precisely bounded in the quadratic model, and the bound makes the general case work.
Proof
Component evolves as , with and . The density of , the marginal of one coordinate of the uniform ball, is
where the bound is Gautschi’s inequality, . Since , for any the “strip” event , that is, , has probability . Choose : outside the strip, as soon as , and .
∎Notice both dependencies. In and the bound is logarithmic: the dangerous strip has width in a ball of radius , and its probability is small even when dimension is enormous. And it does not depend on at all: even if GD has arrived exactly at the stable manifold, a single perturbation suffices. This is what “Measure 200 trials” in the figure measures: from to mean escape goes from about 64 to about 94 iterations.
In a nonquadratic , the Hessian changes along the path and the strip ceases to be a strip. Jin et al.’s argument replaces it with coupling: if two perturbed points differ by , the difference between their trajectories grows as while both remain near the saddle (quadratic approximation error is controlled with ), so at least one escapes. Therefore the set of perturbations that stay stuck has width less than in direction : it is a thin “pancake” and its relative volume in the ball is .
Up to logarithms, this is the same number of iterations GD needs for a first-order point. Escaping saddles is almost free. Combined with the strict-saddle property, the theorem gives convergence to a local minimum in polynomial time. Three comments place it in context:
- SGD already has noise. Ge, Huang, Jin and Yuan (2015) proved that SGD escapes strict saddles in polynomial time if isotropic noise is added to each stochastic gradient. Daneshmand, Kohler, Lucchi and Hofmann (2018) showed that adding it is not even necessary: it suffices that the intrinsic minibatch noise of SGD has nonzero variance along negative-curvature directions, as observed in practice.
- Newton is attracted to saddles. Near a saddle, the Newton step points toward the critical point in every direction, including negative-curvature directions: on a quadratic it jumps exactly to the saddle. Dauphin et al. used it precisely to find them, and proposed saddle-free Newton, which uses (absolute eigenvalues) to reverse the direction in negative components.
- Second order with guarantees. Cubic regularization of Newton (Nesterov and Polyak, 2006) and trust-region methods find -stationary second-order points in iterations, each more expensive.
Benign landscapes
Escaping saddles solves half the problem. The other half is bad local minima, and there is no generic algorithm for them. What does exist is a class of problems where they do not occur.
With the previous two sections the consequence is immediate: in a benign landscape, small-step GD converges to a global minimum for almost every initialization (Lee et al.), and PGD does so in polynomial time if the strict-saddle property is robust (Jin et al.). The basic example is symmetric rank-one factorization.
There are two key calculations. Expanding, , hence
Condition is an eigenvector equation: . And at each bad critical point there is an explicit escape direction, : at with , curvature is ; at the origin, . You will give the complete proof in the first guided exercise.
The same phenomenon, with more work, appears in real problems:
- PCA. Maximizing the Rayleigh quotient over the unit sphere is nonconvex, but by the spectral theorem its critical points are unit eigenvectors and only the leading one (and its opposite) is a local maximum; at all others there is a second-order ascent direction, toward , as in the previous theorem’s strict saddles. The rank- version is the linear network of the preceding section.
- Matrix sensing and completion. Recovering a low-rank matrix from linear measurements satisfying the restricted isometry property (Bhojanapalli, Neyshabur and Srebro, 2016), or from a random sample of entries with a suitable regularizer (Ge, Lee and Ma, 2016), has, with high probability, a landscape without spurious local minima.
- Phase retrieval and deep linear networks. Sun, Qu and Wright (2018) proved phase retrieval with enough Gaussian measurements is benign. In deep linear networks, Kawaguchi (2016) proved every local minimum is global, although from two hidden layers onward non-strict saddles appear, without negative eigenvalues.
Overparameterization, the PL condition and interpolation
There is another way to guarantee convergence without convexity that does not require describing all critical points: the PL condition, , under which GD converges linearly (lesson 8). A network with hidden layers does not satisfy it everywhere (it has saddles, like the origin of , where the gradient vanishes but the loss does not), but wide networks satisfy it near their initialization, and that suffices.
Write the squared loss of a model (the predictions as a function of parameters) as , with residual , Jacobian and tangent kernel
Proof
, hence .
∎This is the PL condition induced by overparameterization: if in a region, satisfies PL there with constant and with (Liu, Zhu and Belkin call it PL*). The lemma explains why more parameters than data are needed: has rank at most , so if is singular, and there is no guarantee. With the kernel can be positive definite, though counting is not enough: it must remain well-conditioned along the whole path.
Proof
By induction, suppose . The descent lemma with and the previous lemma give for , yielding the rate. For path length: since is -smooth, (apply the descent lemma at and use ). Then, with ,
using . Thus and induction closes. The same sum shows is Cauchy; its limit lies in (closed) and makes vanish by continuity.
∎It remains to see why wide networks satisfy the hypothesis. With the usual parametrization of tangent-kernel analyses (outputs scaled by , with the width), model Hessian has norm in fixed-radius balls (Liu, Zhu and Belkin, 2020), so barely moves in . If at initialization , which happens with high probability for distinct inputs and large , the hypothesis holds throughout the ball. Radius does not grow with ; what improves with width is the constancy of .
SGD in the interpolation regime
The figure shows something that appears to contradict what was learned in convex SGD convergence: SGD with constant step converging linearly to zero loss, without any noise floor. The reason is the solution structure.
In the interpolation regime, for each , so stochastic-gradient variance vanishes at the solution. Quantitatively, if each is -smooth and nonnegative with minimum 0, , and averaging gives
Noise is proportional to the loss, not a constant . That is why there is no need to reduce the step: noise switches itself off.
The proof is four lines from the descent lemma and you will reconstruct it in the second guided exercise. The constant is not the best possible: finer analyses (Ma, Bassily and Belkin, 2018) permit, in quadratic problems, steps of order and quantitatively explain the benefit of minibatches up to a critical size. But the qualitative conclusion is what matters: in the interpolation regime, constant-step SGD converges linearly like GD, and according to Ma et al. a step with a critical-sized minibatch advances almost as much as a GD step at a fraction of its cost. Compare this with general nonconvex SGD convergence from lesson 19, which only guaranteed stationarity with decreasing steps.
Implementation from scratch
First, the race in the figure: GD versus perturbed GD on , measuring escape time as a function of initial distance to the stable manifold and comparing it with prediction .
import numpy as np
gam, eta = 0.5, 0.1
def grad(z):
"""f(x, y) = ‖x‖² − γy² + y⁴/4 con z = (x₁, ..., x_{d−1}, y): silla estricta en 0, mínimos en y = ±√(2γ)."""
g = 2 * z.copy()
g[-1] = -2 * gam * z[-1] + z[-1] ** 3
return g
def escapo(z):
return abs(z[-1]) >= np.sqrt(gam)
def gd(z0, max_iter=100_000):
z = z0.copy()
for k in range(max_iter):
if escapo(z):
return k
z -= eta * grad(z)
return None
def pgd(z0, rng, radius=0.05, g_thresh=0.05, t_wait=25, max_iter=100_000):
z, ultimo, d = z0.copy(), -t_wait, len(z0)
for k in range(max_iter):
if escapo(z):
return k
if np.linalg.norm(grad(z)) <= g_thresh and k - ultimo >= t_wait:
u = rng.standard_normal(d)
z += radius * rng.random() ** (1 / d) * u / np.linalg.norm(u) # uniforme en la bola
ultimo = k
z -= eta * grad(z)
return None
rng = np.random.default_rng(0)
print(" |y0| GD predicción PGD")
for p in (2, 4, 8, 12, 16):
z0 = np.array([1.8, 10.0 ** -p])
pred = np.log(np.sqrt(gam) * 10.0 ** p) / np.log(1 + 2 * eta * gam)
print(f" 1e-{p:<4d} {gd(z0):5d} {pred:9.0f} {pgd(z0, rng):7d}")
print(" y0 = 0: GD tras 5000 iteraciones:", gd(np.array([1.8, 0.0]), max_iter=5000), " PGD:", pgd(np.array([1.8, 0.0]), rng))GD takes about 24 more iterations per decimal digit of (it is ), and the linear prediction is accurate except for a few iterations: those at the beginning, when does not yet dominate, and the final push of term . PGD escapes in time independent of . Now, the dimension dependence predicted by the proposition:
for d in (2, 10, 100, 1000):
z0 = np.zeros(d)
z0[0] = 1.8
ts = np.array([pgd(z0, rng) for _ in range(100)])
print(f"d = {d:5d}: escape medio {ts.mean():5.1f} iteraciones, percentil 95: {np.percentile(ts, 95):5.1f}")Multiplying dimension by 10 adds about 10 iterations, on the order of : the perturbation component in the unstable direction is of order , and escaping it costs a logarithm.
Rank- factorization is benign. Run it from 40 random initializations at once and verify that all reach optimal value :
rng = np.random.default_rng(1)
n, k, ensayos = 30, 3, 40
Q, _ = np.linalg.qr(rng.standard_normal((n, n)))
lam = np.r_[5.0, 3.0, 2.0, rng.uniform(0, 1, n - 3)] # semidefinida positiva, hueco tras el tercero
M = (Q * lam) @ Q.T
f_opt = np.sum(np.sort(lam)[:-k] ** 2) # ‖M‖² − (λ₁² + λ₂² + λ₃²)
U = rng.standard_normal((ensayos, n, k)) * 0.3 # 40 inicializaciones a la vez
for it in range(2000):
R = U @ U.transpose(0, 2, 1) - M # UUᵀ − M en cada ensayo
U -= 0.01 * 4 * R @ U
gap = np.sum((U @ U.transpose(0, 2, 1) - M) ** 2, axis=(1, 2)) - f_opt
print(f"f(U) − f* tras 2000 pasos, en {ensayos} inicializaciones: máx = {gap.max():.1e}, mín = {gap.min():.1e}")Hessian spectrum at critical points
Now a miniature Dauphin et al. lab, on linear network with : locate critical points by minimizing (with Levenberg–Marquardt: the residual is and its Jacobian is the Hessian), measure their index and compare with the exact formula. The Hessian is never formed from hand-written second derivatives: everything comes from the Hessian-vector product, the directional derivative of the gradient,
which is all that can be calculated in a large network. Using it, the Lanczos algorithm estimates extreme eigenvalues without forming the matrix.
n, k = 6, 2
lam = np.array([6.0, 5, 4, 3, 2, 1])
M = np.diag(lam)
P = n * k
def f_lin(U):
return np.sum((U @ U.T - M) ** 2)
def grad_lin(U):
return 4 * (U @ U.T - M) @ U
def hvp(U, D):
"""Producto hessiano-vector exacto: derivada direccional de 4(UUᵀ − M)U en la dirección D."""
return 4 * (D @ U.T + U @ D.T) @ U + 4 * (U @ U.T - M) @ D
def hessiano(U):
return np.array([hvp(U, e.reshape(n, k)).ravel() for e in np.eye(P)])
def lanczos(matvec, dim, m, rng):
"""m pasos de Lanczos con reortogonalización completa; devuelve los valores de Ritz."""
Q = np.zeros((m + 1, dim))
alpha, beta = np.zeros(m), np.zeros(m)
q = rng.standard_normal(dim)
Q[0] = q / np.linalg.norm(q)
for j in range(m):
w = matvec(Q[j])
alpha[j] = w @ Q[j]
w -= Q[: j + 1].T @ (Q[: j + 1] @ w)
beta[j] = np.linalg.norm(w)
if beta[j] < 1e-12:
m = j + 1
break
Q[j + 1] = w / beta[j]
T = np.diag(alpha[:m]) + np.diag(beta[: m - 1], 1) + np.diag(beta[: m - 1], -1)
return np.linalg.eigvalsh(T)
def buscar_critico(U, iters=50, mu=1e-3):
"""Minimiza ½‖∇f‖² por Levenberg-Marquardt."""
for _ in range(iters):
g, H = grad_lin(U).ravel(), hessiano(U)
if np.linalg.norm(g) < 1e-12:
break
for _ in range(30):
Un = U - np.linalg.solve(H @ H + mu * np.eye(P), H @ g).reshape(n, k)
if np.linalg.norm(grad_lin(Un)) < np.linalg.norm(g):
U, mu = Un, max(mu / 3, 1e-14)
break
mu *= 4
else:
break
return U, np.linalg.norm(grad_lin(U))
def indice_formula(S):
fuera = [j for j in range(n) if j not in S]
return sum(sum(lam[j] > lam[i] for j in fuera) for i in S) + (k - len(S)) * len(fuera)
rng = np.random.default_rng(0)
vistos = {}
for _ in range(60):
U, gn = buscar_critico(rng.standard_normal((n, k)) * rng.uniform(0.3, 2))
if gn > 1e-9:
continue
S = tuple(i for i in range(n) if (U @ U.T)[i, i] > lam[i] / 2) # autovectores elegidos
ev = np.linalg.eigvalsh(hessiano(U))
ritz = lanczos(lambda v: hvp(U, v.reshape(n, k)).ravel(), P, 10, rng)
vistos[S] = (f_lin(U), int((ev < -1e-6).sum()), indice_formula(S), ev.min(), ritz.min())
print(f"{len(vistos)} puntos críticos distintos (salvo rotaciones) en 60 búsquedas")
print(" S pérdida índice fórmula λ_min λ_min con Lanczos (10 pasos)")
for S, (fv, idx, fo, lm, lr) in sorted(vistos.items(), key=lambda kv: kv[1][0]):
print(f" {str(S):10s} {fv:6.1f} {idx:6d} {fo:7d} {lm:9.3f} {lr:12.3f}")The search finds critical points of almost all types (minimizing is indifferent to type, like Newton’s method), and the measured index matches the formula in all cases. The table, ordered by loss, reproduces the random-matrix model trend: more loss, more escape directions. Two cautions about the technique. Here, with 10 steps in 12 dimensions, Lanczos gives almost exact ; in a real network a few dozen steps are used in millions of dimensions, and precision depends on separation of the extreme from the rest of the spectrum. And Lanczos with one initial vector does not see multiplicities: a Krylov space holds a single vector from each eigenspace, so counting negative eigenvalues with its Ritz values underestimates the index when eigenvalues repeat, as here. The index needs the full spectrum, block Lanczos, or an estimate of spectral density.
Finally, the coin comparison: the probability that a GOE matrix is positive definite, by Monte Carlo, versus .
rng = np.random.default_rng(0)
print(" n P(todos > 0) ln P / n² 2^(−n)")
for n_ in range(1, 6):
A_ = rng.standard_normal((100_000, n_, n_))
p = (np.linalg.eigvalsh((A_ + A_.transpose(0, 2, 1)) / 2)[:, 0] > 0).mean()
print(f" {n_} {p:.2e} {np.log(p) / n_**2:+.3f} {2.0**-n_:.2e}")Already at the probability is about 180 times lower than , and slowly approaches limit (corrections are of order ).
Width, tangent kernel and linear convergence
The network from the last figure, in NumPy: train several widths with GD and measure along the path.
N = 8
X = np.linspace(-1, 1, N)
Y = np.sin(3 * X) + 0.4 * np.random.default_rng(3).standard_normal(N)
def entrena(m, pasos=1500, eta=1.5, sgd=False, seed=0):
"""Red f(x) = m^(−1/2) Σ a_j tanh(w_j x + b_j); devuelve las pérdidas y λ_min(K) cada 100 pasos."""
rng = np.random.default_rng(seed)
w, b, a = 8 * rng.standard_normal(m), rng.uniform(-8, 8, m), rng.standard_normal(m)
s = 1 / np.sqrt(m)
perdidas, lmins = [], []
for t in range(pasos + 1):
H = np.tanh(np.outer(X, w) + b) # (N, m)
r = s * H @ a - Y
perdidas.append(0.5 * np.mean(r ** 2))
D = s * (1 - H ** 2) * a # ∂f/∂b_j en cada dato
J = np.hstack([D * X[:, None], D, s * H]) # jacobiano (N, 3m)
if t % 100 == 0:
lmins.append(np.linalg.eigvalsh(J @ J.T / N)[0])
if t == pasos:
break
if sgd:
i = rng.integers(N)
paso = J[i] * r[i]
else:
paso = J.T @ r / N
w, b, a = w - eta * paso[:m], b - eta * paso[m:2 * m], a - eta * paso[2 * m:]
return np.array(perdidas), np.array(lmins)
print(" m parámetros L(0) L(750) L(1500) mín λ_min(K)")
for m in (2, 8, 64, 256):
L, lm = entrena(m)
print(f"{m:4d} {3 * m:8d} {L[0]:.2e} {L[750]:.2e} {L[-1]:.2e} {max(lm.min(), 0):.1e}")With the kernel is singular and the loss stays at ; with , and loss falls many orders of magnitude. And SGD with one example per step and constant step, in a narrow and a wide network:
for m in (2, 256):
L, _ = entrena(m, pasos=3000, eta=1.0, sgd=True)
print(f"m = {m:3d}: L(1000) = {L[1000]:.1e} L(2000) = {L[2000]:.1e} L(3000) = {L[3000]:.1e}")In the wide network, which interpolates, loss falls linearly with constant step; in the narrow one, which cannot interpolate, SGD bounces around a positive loss.
The library version
In a real network nobody forms the Hessian. Automatic differentiation libraries calculate Hessian-vector products in two passes (forward over the gradient, or double backpropagation), costing on the order of two gradients, and scipy.sparse.linalg.eigsh runs Lanczos on a LinearOperator. The following snippet does in PyTorch what the linear network cell does, on the tiny tanh network from the preceding note. It is reference code, not an executable cell: in a real network it would run on the GPU (with device="cuda" on tensors, as in device placement), and the dynamic autograd graph allows the gradient to be differentiated again.
import numpy as np
import torch
from torch.func import grad, hessian, jvp
from scipy.sparse.linalg import LinearOperator, eigsh
dt = torch.float64
X = torch.linspace(-1, 1, 8, dtype=dt)
Y = torch.sin(3 * X) + 0.4 * torch.tensor(np.random.default_rng(3).standard_normal(8), dtype=dt)
h = 4
P = 3 * h + 1
def loss(t):
w, b, a, c = t[:h], t[h:2 * h], t[2 * h:3 * h], t[3 * h]
return 0.5 * ((torch.tanh(X[:, None] * w + b) @ a + c - Y) ** 2).mean()
g_fn = grad(loss)
def hvp(t, v): # derivada direccional del gradiente: H v sin formar H
return jvp(g_fn, (t,), (v,))[1]
def lanczos_smallest(t, k=6):
op = LinearOperator((P, P), dtype=np.float64,
matvec=lambda v: hvp(t, torch.as_tensor(v.ravel(), dtype=dt)).numpy())
return eigsh(op, k=k, which="SA", tol=1e-10, return_eigenvectors=False)
# Con t_c un punto crítico (por ejemplo, el que devuelve Levenberg-Marquardt sobre ½‖∇f‖²):
# lanczos_smallest(t_c) coincide con los menores valores de torch.linalg.eigvalsh(hessian(loss)(t_c)).
For large networks, the standard tool is stochastic Lanczos quadrature, which estimates the full Hessian spectral density from a few dozen Lanczos steps with random vectors (implemented, for example, in PyHessian). You will see it applied in the next lesson.
Common mistakes
Three common mistakes in this subject have already appeared where appropriate: treating a plateau as a local minimum, extrapolating benign landscapes to general deep networks, and confusing overparameterization with good generalization. The fourth appears as soon as curvature is measured in a real network.
Exercises
More than one answer may be correct.
Step 1 of 4. What are the critical points?
Step 1 of 4. Which inequality do you start from?
perturbed_gd(grad, x0, eta, radius, g_thresh, t_wait, n_iter, rng), returning (x, kicks): the final iterate and the list of iterations at which perturbation occurred. At each iteration k = 0, ..., n_iter - 1: if g_thresh and there has never been a perturbation or at least t_wait iterations have passed since the last, add to x a uniform point in the ball of radius radius (generate the direction with rng.standard_normal and the radius with rng.random) and record k; then take step x = x - eta * grad(x).import numpy as np
def perturbed_gd(grad, x0, eta, radius, g_thresh, t_wait, n_iter, rng):
x = np.array(x0, dtype=float)
kicks = []
for k in range(n_iter):
# tu código: perturbación uniforme en la bola cuando el gradiente es pequeño
x = x - eta * grad(x)
return x, kicksSummary
- Verifying that a point is a local minimum is NP-hard (Murty and Kabadi): at the origin of a quartic, local minimality equals copositivity, which encodes CLIQUE. Realistic targets are first-order () and second-order () stationary points.
- A strict saddle has . If all saddles are strict, second-order points are local minima; degenerate saddles (, the monkey saddle) are what must be excluded.
- In high dimension, high-loss critical points are saddles: in a Gaussian field the index grows with loss, and the probability that a GOE Hessian is positive definite decays as .
- GD with converges to a strict saddle only from a measure-zero set (Lee et al.), but escape time grows as with distance to the stable manifold, and may be exponential in . Perturbed GD escapes with probability in time logarithmic in and , and finds second-order points in iterations (Jin et al.).
- A landscape is benign if every local minimum is global and every other critical point is a strict saddle. Factorization , PCA, matrix sensing and completion are benign; general nonlinear networks are not.
- With more parameters than data, with tangent kernel . If in a ball of radius , GD converges linearly to zero loss; in wide networks barely changes and the hypothesis holds.
- In the interpolation regime SGD noise is proportional to loss, , and constant-step SGD converges linearly under PL. All this concerns optimization, not generalization.