Optimisation: convex and not¶
Training a model means finding parameters that make a loss small. Convex optimisation tells you exactly when that is easy and how fast it goes; deep learning breaks every one of its assumptions and works anyway. This page gives you both: the clean theory (curvature, condition numbers, rates, Lagrange multipliers) and what is actually known about why gradient descent succeeds on non-convex networks.
10,000 ft
Every learning algorithm on this site is an optimiser wrapped around a loss: least squares and logistic regression (convex, solved exactly), SVMs (convex, solved through duality), neural networks (non-convex, solved approximately by stochastic gradient methods), RL policies (non-convex and non-stationary). The theory of convex optimisation, developed from the 1940s to the 1990s, supplies the vocabulary that every deep-learning optimiser paper still uses: smoothness, strong convexity, the condition number, momentum, preconditioning, convergence rates, constraints. The non-convex part of the story (saddle points, overparameterisation, implicit bias, the edge of stability) explains why training large networks is possible, and shapes the practical recipes in optimisers and the training recipe.
2,000 ft
You want \(\min_\theta f(\theta)\) and you can evaluate the gradient (often only a noisy estimate of it). The map:
- Gradient descent steps against the gradient; the step size must be below \(2/L\), where \(L\) is the largest curvature, or it diverges.
- Convergence speed is set by the ratio of largest to smallest curvature, \(\kappa\). Ill-conditioned problems zig-zag.
- Momentum cuts the dependence from \(\kappa\) to \(\sqrt\kappa\); preconditioning (Newton, Adam, Shampoo) rescales the problem to shrink \(\kappa\) itself.
- Stochastic gradients add noise: a constant step stalls at a noise floor, so you decay it (schedules).
- Non-convex deep-learning losses are dominated by saddle points, not bad local minima, and in overparameterised networks gradient methods reach near-zero training loss. Which minimum they reach (implicit bias) is what determines generalisation.
Ground level¶
The landscape, locally¶
Near any point \(\theta\), a smooth function looks like its second-order Taylor expansion:
with gradient \(\nabla f\) (direction of steepest ascent) and Hessian \(H\) (curvature in every direction). At a stationary point the gradient is zero and the Hessian's eigenvalues decide what it is: all positive is a local minimum, all negative a local maximum, mixed signs a saddle point, and some zero eigenvalues a flat or degenerate region. In a network with a billion parameters the Hessian has a billion eigenvalues, and as we will see, mixed signs are by far the most common case.
Convexity: the property that makes optimisation easy¶
A function is convex if the chord between any two points of its graph lies on or above the graph: \(f(t\mathbf{a} + (1-t)\mathbf{b}) \le t f(\mathbf{a}) + (1-t) f(\mathbf{b})\) for \(t \in [0, 1]\). Equivalent tests for smooth functions: the graph lies above every tangent plane, or the Hessian is positive semi-definite everywhere.
Convexity buys one enormous guarantee: every local minimum is a global minimum, and the set of minimisers is convex (a single point or a flat connected region). Any method that goes downhill and does not stop early gets the right answer, and its speed can be bounded.
Convex problems in machine learning are more common than you might think:
- Least squares \(\lVert X\mathbf{w} - \mathbf{y}\rVert^2\) (Hessian \(2X^\top X \succeq 0\)), ridge, and the lasso.
- Logistic and softmax regression: cross-entropy is convex in the logits (it is log-sum-exp minus a linear term), and logits are linear in the weights.
- SVMs, the hinge loss, and every negative log-likelihood of an exponential family in its natural parameters (distributions).
- The last layer of a network with everything below it frozen (linear probing).
Convexity is preserved by non-negative sums, by composing with an affine map, and by pointwise maxima, which is how you check most ML losses without computing a Hessian.
A neural network with a hidden layer is never convex in its weights, and there is a one-line reason: symmetry. Swap two hidden units (and their outgoing weights) and the network computes the same function, so it has the same loss. If \(\theta_1\) is a minimum, so is its permuted copy \(\theta_2\). If the loss were convex, the midpoint \(\frac12(\theta_1 + \theta_2)\) would also be a minimum, but the midpoint has two identical hidden units, a strictly weaker network that generally has higher loss. So the loss has many separate minima: at least one per permutation, \(n!\) for a layer of \(n\) units.
Gradient descent and the step size¶
Gradient descent repeats \(\theta_{t+1} = \theta_t - \eta\,\nabla f(\theta_t)\). The whole theory of its behaviour can be seen on a quadratic \(f(\theta) = \frac12 \theta^\top A\theta\) with \(A\) symmetric positive definite, eigenvalues \(\lambda_1 \le \dots \le \lambda_d\). In the eigenbasis the coordinates decouple, and each one evolves as
Three consequences follow immediately.
- The step-size limit. If \(\eta > 2/\lambda_d\) then \(|1 - \eta\lambda_d| > 1\) and the steepest direction diverges. The maximum curvature (the Lipschitz constant \(L\) of the gradient) caps the learning rate.
- The condition number. The slowest direction contracts by \((1 - \eta\lambda_1)\) per step. The best fixed step, \(\eta = 2/(\lambda_1 + \lambda_d)\), gives a worst-case contraction of \(\frac{\kappa - 1}{\kappa + 1}\) where \(\kappa = \lambda_d / \lambda_1\). For \(\kappa = 100\) that is 0.980 per step: you need roughly \(\kappa\) steps to make real progress.
- Zig-zagging. With a step tuned for the steep direction, the steep coordinate overshoots and flips sign each step while the shallow one crawls. That is the classic ravine picture.
The code below runs this on \(f = \frac12(x_1^2 + 100\,x_2^2)\), starting from \((1, 1)\), until \(f < 10^{-6}\). With \(\eta = 0.0199\) (just under the limit \(2/100 = 0.02\)) it takes 882 steps; with \(\eta = 0.0201\) it diverges; at the optimal \(\eta = 0.0198\) it takes 444 steps.
Momentum: from κ to √κ¶
Heavy-ball momentum (Polyak, 1964) keeps a running velocity: \(\mathbf{v}_{t+1} = \beta\mathbf{v}_t - \eta\nabla f(\theta_t)\), \(\theta_{t+1} = \theta_t + \mathbf{v}_{t+1}\). Along the shallow, consistent direction the velocity accumulates (the effective step grows to about \(\eta/(1-\beta)\)); along the steep, oscillating direction successive gradients cancel. Tuned optimally for a quadratic, the contraction per step becomes \(\frac{\sqrt\kappa - 1}{\sqrt\kappa + 1}\): for \(\kappa = 100\), 0.818 instead of 0.980. In the experiment it reaches the target in 69 steps instead of 444. Nesterov's accelerated gradient (1983) evaluates the gradient at the look-ahead point and achieves the same \(\sqrt\kappa\) dependence for all smooth convex functions, which is provably the best any first-order method can do. Gabriel Goh's Why Momentum Really Works is the definitive interactive explanation.
Newton's method and preconditioning¶
If you know the Hessian, Newton's method \(\theta_{t+1} = \theta_t - H^{-1}\nabla f(\theta_t)\) jumps to the minimum of the local quadratic. On an exact quadratic it converges in one step (the experiment confirms it), whatever \(\kappa\) is, because \(H^{-1}\) rescales every direction to the same curvature. Near a minimum of a smooth function it converges quadratically (the number of correct digits doubles each step).
Newton is not used to train networks, for three reasons. The Hessian of a model with \(d\) parameters has \(d^2\) entries (\(10^{18}\) for a billion parameters). The step needs a linear solve. And on a non-convex function, \(H^{-1}\nabla f\) points towards saddle points and maxima as readily as minima, because it treats negative curvature like positive curvature.
What survives is the idea of preconditioning: multiply the gradient by a cheap matrix \(P\) that approximates \(H^{-1}\), so that the problem looks better conditioned. Adam and RMSProp use a diagonal \(P\) built from running averages of squared gradients (a per-parameter learning rate); AdaGrad, K-FAC and Shampoo use richer structured approximations. Much of the history of deep learning optimisers is a search for a better \(P\) at near-diagonal cost (see optimisers). Normalisation layers attack the same problem from the other side, by reshaping the landscape so that it is better conditioned in the first place.
Stochastic gradients, noise floors and schedules¶
In machine learning \(f(\theta) = \frac1N\sum_i \ell_i(\theta)\) and you cannot afford the full gradient, so you use a minibatch estimate: unbiased, with variance proportional to \(1/B\) (probability foundations). Stochastic gradient descent with a constant step does not converge to the minimum; it converges to a cloud around it whose size is proportional to \(\eta\sigma^2\), where \(\sigma^2\) is the gradient noise. To reach the minimum the step must shrink, and Robbins and Monro (1951) gave the classical conditions: \(\sum_t \eta_t = \infty\) (you can still travel any distance) and \(\sum_t \eta_t^2 < \infty\) (the accumulated noise is finite), satisfied for example by \(\eta_t \propto 1/t\).
In the experiment below, 20,000 single-example SGD steps on a 10-dimensional linear regression leave an excess loss of 0.258 with constant \(\eta = 0.05\), 0.015 with constant \(\eta = 0.005\) (lower floor, slower start), and 0.0026 with a cosine schedule that starts at 0.05 and decays to 0. The schedule gets the fast early progress of a large step and the low floor of a small one. Warm-up followed by cosine or linear decay is the default for transformers for exactly this reason (plus the fact that early in training the curvature is high and a large step would diverge).
What the rates say¶
For an \(L\)-smooth function (gradient Lipschitz with constant \(L\); curvature at most \(L\)), the standard results, with \(t\) the number of steps:
| Setting | Method | Guarantee after \(t\) steps |
|---|---|---|
| Convex | GD, \(\eta = 1/L\) | \(f(\theta_t) - f^* = O(L\lVert\theta_0 - \theta^*\rVert^2 / t)\) |
| Convex | Nesterov | \(O(L\lVert\theta_0 - \theta^*\rVert^2 / t^2)\), optimal for first-order methods |
| \(\mu\)-strongly convex | GD | \(f(\theta_t) - f^* \le (1 - \mu/L)^t\,(f(\theta_0) - f^*)\) |
| \(\mu\)-strongly convex | Nesterov / heavy ball | contraction \(\approx (1 - \sqrt{\mu/L})\) per step |
| Convex, stochastic | SGD, \(\eta_t \propto 1/\sqrt t\) | \(O(1/\sqrt t)\) |
| Strongly convex, stochastic | SGD, \(\eta_t \propto 1/t\) | \(O(1/t)\) |
| Non-convex, smooth | GD | \(\min_{s \le t}\lVert\nabla f(\theta_s)\rVert^2 = O(L(f(\theta_0) - f^*)/t)\) |
| Non-convex, stochastic | SGD | \(\min_{s \le t}\mathbb{E}\lVert\nabla f(\theta_s)\rVert^2 = O(1/\sqrt t)\) |
Two lessons. Noise costs a lot: stochastic rates are polynomially slower than deterministic ones, which is why variance reduction and large batches matter. And for non-convex problems the only general guarantee is reaching a point with a small gradient, which could be a saddle. Bottou, Curtis and Nocedal (2018) is the standard review of these results for machine learning.
Non-convex, and why it works anyway¶
The surprise of deep learning is that a non-convex loss with \(n!\) symmetric copies of every minimum, in billions of dimensions, is minimised reliably by a first-order method with noisy gradients. The best current understanding has several parts.
- Saddles, not local minima, are the obstacle. At a random critical point of a high-dimensional function, it is overwhelmingly unlikely that all Hessian eigenvalues have the same sign; mixed signs (saddles) dominate, and critical points with high loss tend to be saddles. Dauphin et al. (2014) made this argument for neural networks. Gradient descent from a random start converges to a saddle with probability zero (Lee et al., 2016), though it can dawdle near one, and gradient noise helps it escape (Ge et al., 2015).
- Bad local minima are rare in wide networks. Empirically, independently trained networks reach similar losses, and their minima are joined by low-loss paths (Garipov et al., 2018; Draxler et al., 2018): the low-loss region is more like one connected valley floor than many isolated pits.
- Overparameterisation gives a different kind of niceness. A function satisfies the Polyak–Łojasiewicz (PL) condition if \(\lVert\nabla f\rVert^2 \ge 2\mu\,(f - f^*)\): wherever the loss is high, the gradient is big. That alone gives gradient descent a linear rate with no convexity at all (Karimi, Nutini and Schmidt, 2016), and sufficiently overparameterised networks satisfy a version of it over large regions (Liu, Zhu and Belkin, 2020). In the infinite-width limit, training behaves like a convex kernel regression (the neural tangent kernel).
- Optimisation is rarely the bottleneck. Standard networks can drive training loss to zero even on randomly relabelled data (Zhang et al., 2017). The question is not whether they reach a minimum but which one.
Which minimum: implicit bias, sharpness and the edge of stability¶
When a problem has many global minima, the algorithm picks one, and that choice is a hidden regulariser. The simplest case is exact: for an underdetermined least-squares problem (more unknowns than equations), gradient descent started at zero converges to the minimum-norm solution, because every gradient \(A^\top(A\theta - \mathbf{b})\) lies in the row space of \(A\), so the iterates never acquire a component in the null space. Start elsewhere and you converge to a different exact solution: the code finds residuals of \(10^{-15}\) in both cases, but norms of 0.540 (equal to the minimum-norm solution) and 3.016. For logistic regression on separable data, gradient descent converges in direction to the maximum-margin separator, the SVM solution, without any explicit regulariser (Soudry et al., 2018).
For deep networks, the leading heuristic is that flat minima (low curvature, where the loss changes little if you perturb the weights) generalise better than sharp ones, and that small batches and large learning rates steer towards flat regions (Keskar et al., 2017). Treat it as a heuristic: sharpness can be changed by reparameterising a network without changing the function it computes (Dinh et al., 2017). A cleaner empirical law is the edge of stability (Cohen et al., 2021): during full-batch training the top Hessian eigenvalue rises until it reaches about \(2/\eta\), the classical divergence threshold, and then hovers there while the loss keeps falling, non-monotonically. The step-size limit from the quadratic analysis is not just a constraint on training; the dynamics organise themselves around it. Li et al. (2018) shows how to visualise these landscapes, and how residual connections make them smoother.
Constraints: Lagrange multipliers and KKT¶
Many problems carry constraints: probabilities must sum to 1, a policy must stay close to a reference, a margin must be at least 1. The method of Lagrange multipliers handles equality constraints \(g(\theta) = 0\). At a constrained optimum you cannot improve \(f\) by moving along the constraint surface, so \(\nabla f\) must be perpendicular to the surface, that is parallel to \(\nabla g\):
which is the stationarity condition of the Lagrangian \(\mathcal{L}(\theta, \lambda) = f(\theta) - \lambda g(\theta)\). Worked example: minimise \(x^2 + y^2\) subject to \(x + y = 1\). Stationarity gives \(2x = \lambda\), \(2y = \lambda\), so \(x = y\), and the constraint gives \(x = y = 0.5\), \(\lambda = 1\), \(f = 0.5\). The multiplier has a meaning: it is the rate at which the optimal value changes as the constraint is relaxed (raise the 1 to \(1 + \epsilon\) and \(f^*\) rises by about \(\lambda\epsilon\)).
Inequality constraints \(h(\theta) \le 0\) add the Karush–Kuhn–Tucker (KKT) conditions: the multiplier must be non-negative, and complementary slackness says it is zero unless the constraint is active. In an SVM, the training points with non-zero multipliers are exactly the support vectors. Every convex problem also has a dual problem over the multipliers, often easier and more revealing: the SVM dual depends on data only through inner products, which is what makes the kernel trick possible (see kernels and SVMs). The maximum-entropy derivation on the distributions page and the closed-form optimal policy behind DPO on the information theory page are both Lagrangian calculations; TRPO is a KL-constrained policy update.
First principles¶
Why the negative gradient? Among all directions \(\mathbf{u}\) of unit length, the first-order change \(\nabla f^\top\mathbf{u}\) is most negative when \(\mathbf{u} = -\nabla f / \lVert\nabla f\rVert\) (by Cauchy–Schwarz). Steepest descent is "steepest" only for the Euclidean norm. Measure step length differently (by the change in a model's output distribution, say, using the Fisher information) and the steepest direction changes: that is the natural gradient, and a preconditioner is the same idea in disguise.
Why the step size is capped by curvature. If the gradient is \(L\)-Lipschitz, the function lies below a quadratic bowl with curvature \(L\) around every point (the descent lemma, below). Minimising that bowl gives the step \(1/L\) and a guaranteed decrease of \(\frac{1}{2L}\lVert\nabla f\rVert^2\) per step. Larger steps can overshoot the bowl's minimum and, past \(2/L\), increase \(f\). This is the theoretical reason learning rates must be tuned to the largest curvature, and why warm-up helps when early curvature is high.
Why condition number is the enemy. One step size must serve every direction. It must be small enough for the steepest direction (\(\eta < 2/\lambda_\text{max}\)), so the flattest direction moves at a rate of about \(\lambda_\text{min}/\lambda_\text{max} = 1/\kappa\). Every remedy (momentum, preconditioning, normalisation, good initialisation, residual connections) is a way to reduce the effective \(\kappa\) or to stop paying for it in full.
Why non-convex is not hopeless. Convexity is sufficient for easy optimisation, not necessary. What gradient descent really needs is that wherever it is not done, the gradient points somewhere useful: no flat high plateaus, no attracting bad minima, saddles that can be escaped. PL-type inequalities formalise this, and overparameterisation (more parameters than constraints imposed by the data) is the main mechanism that supplies it.
History¶
From Cauchy to Adam
Joseph-Louis Lagrange introduced multipliers for constrained problems in mechanics in 1788. Augustin-Louis Cauchy proposed gradient descent in 1847 to solve systems of equations from astronomy. William Karush (1939) and Harold Kuhn and Albert Tucker (1951) extended multipliers to inequalities. Herbert Robbins and Sutton Monro's 1951 A Stochastic Approximation Method founded SGD. Boris Polyak introduced the heavy-ball method in 1964 and Yurii Nesterov accelerated gradients in 1983, proving their optimality. Interior-point methods (Karmarkar, 1984) made large convex programs routine. For neural networks, backpropagation with SGD and momentum (Rumelhart, Hinton and Williams, 1986) was the workhorse for three decades; adaptive methods followed: AdaGrad (Duchi, Hazan and Singer, 2011), RMSProp (Hinton's 2012 lecture notes), Adam (Kingma and Ba, 2014) and AdamW (Loshchilov and Hutter, 2017).
The maths¶
Definitions
- \(f\) is convex if \(f(t\mathbf{a} + (1-t)\mathbf{b}) \le t f(\mathbf{a}) + (1-t)f(\mathbf{b})\); for differentiable \(f\), equivalently \(f(\mathbf{b}) \ge f(\mathbf{a}) + \nabla f(\mathbf{a})^\top(\mathbf{b} - \mathbf{a})\); for twice-differentiable \(f\), \(\nabla^2 f \succeq 0\).
- \(\mu\)-strongly convex: \(f(\mathbf{b}) \ge f(\mathbf{a}) + \nabla f(\mathbf{a})^\top(\mathbf{b} - \mathbf{a}) + \frac\mu2\lVert\mathbf{b} - \mathbf{a}\rVert^2\) (\(\nabla^2 f \succeq \mu I\)).
- \(L\)-smooth: \(\lVert\nabla f(\mathbf{a}) - \nabla f(\mathbf{b})\rVert \le L\lVert\mathbf{a} - \mathbf{b}\rVert\) (\(\nabla^2 f \preceq L I\)).
- Condition number \(\kappa = L/\mu\); for a quadratic, \(\lambda_\text{max}/\lambda_\text{min}\) of the Hessian.
- PL inequality: \(\frac12\lVert\nabla f(\theta)\rVert^2 \ge \mu\,(f(\theta) - f^*)\) for all \(\theta\).
Derivation: the descent lemma and GD's rate
For \(L\)-smooth \(f\), integrate the gradient along the segment from \(\mathbf{a}\) to \(\mathbf{b}\):
using Cauchy–Schwarz and the Lipschitz bound on the integrand. Put \(\mathbf{b} = \mathbf{a} - \eta\nabla f(\mathbf{a})\):
The decrease is positive for \(0 < \eta < 2/L\) and largest at \(\eta = 1/L\), where it is \(\frac{1}{2L}\lVert\nabla f\rVert^2\). Non-convex rate: summing over \(t\) steps, \(\frac{1}{2L}\sum_s \lVert\nabla f(\theta_s)\rVert^2 \le f(\theta_0) - f^*\), so \(\min_s \lVert\nabla f(\theta_s)\rVert^2 \le 2L(f(\theta_0) - f^*)/t\). PL rate: combining with \(\lVert\nabla f\rVert^2 \ge 2\mu(f - f^*)\) gives \(f(\theta_{t+1}) - f^* \le (1 - \mu/L)(f(\theta_t) - f^*)\), a linear rate without convexity (strong convexity implies PL, so this covers the strongly convex case too).
Derivation: gradient descent and momentum on a quadratic
For \(f = \frac12\theta^\top A\theta\) with eigenvalues \(\lambda_i \in [\mu, L]\), GD gives \(\theta_t = (I - \eta A)^t\theta_0\), so the error contracts by \(\rho(\eta) = \max_i |1 - \eta\lambda_i| = \max(|1 - \eta\mu|, |1 - \eta L|)\). This is minimised when the two are equal, \(\eta = 2/(\mu + L)\), giving \(\rho = \frac{L - \mu}{L + \mu} = \frac{\kappa - 1}{\kappa + 1}\).
Heavy ball, \(\theta_{t+1} = \theta_t - \eta A\theta_t + \beta(\theta_t - \theta_{t-1})\), is a two-term linear recurrence per eigen-direction with characteristic equation \(z^2 - (1 + \beta - \eta\lambda)z + \beta = 0\). When both roots are complex their modulus is \(\sqrt\beta\). Choosing \(\eta = \frac{4}{(\sqrt L + \sqrt\mu)^2}\) and \(\beta = \big(\frac{\sqrt\kappa - 1}{\sqrt\kappa + 1}\big)^2\) makes the roots complex for every \(\lambda \in [\mu, L]\), so the contraction is \(\sqrt\beta = \frac{\sqrt\kappa - 1}{\sqrt\kappa + 1}\).
Lagrangian, KKT and duality
Problem: minimise \(f(\theta)\) subject to \(h_i(\theta) \le 0\) and \(g_j(\theta) = 0\). Lagrangian \(\mathcal{L}(\theta, \boldsymbol\alpha, \boldsymbol\nu) = f(\theta) + \sum_i \alpha_i h_i(\theta) + \sum_j \nu_j g_j(\theta)\). KKT conditions at an optimum (necessary under mild regularity; sufficient for convex problems):
- Stationarity: \(\nabla f + \sum_i \alpha_i\nabla h_i + \sum_j \nu_j \nabla g_j = 0\).
- Primal feasibility: \(h_i \le 0\), \(g_j = 0\).
- Dual feasibility: \(\alpha_i \ge 0\).
- Complementary slackness: \(\alpha_i h_i(\theta) = 0\).
The dual function \(q(\boldsymbol\alpha, \boldsymbol\nu) = \min_\theta \mathcal{L}\) is concave and \(q \le f^*\) for any feasible multipliers (weak duality); for convex problems satisfying Slater's condition, \(\max q = f^*\) (strong duality).
Stochastic approximation
SGD \(\theta_{t+1} = \theta_t - \eta_t\,\mathbf{g}_t\) with \(\mathbb{E}[\mathbf{g}_t \mid \theta_t] = \nabla f(\theta_t)\) and bounded variance converges (for convex \(f\), to a minimiser) when \(\sum_t \eta_t = \infty\) and \(\sum_t \eta_t^2 < \infty\). With a constant step \(\eta\) on a strongly convex \(f\), \(\mathbb{E}[f(\theta_t)] - f^*\) converges to a floor of order \(\eta L\sigma^2/\mu\): halve the step, halve the floor, double the time to get there.
Build it¶
Gradient descent, momentum and Newton on an ill-conditioned quadratic (\(\kappa = 100\)):
import numpy as np
# f(x) = 0.5 * (1 * x1^2 + 100 * x2^2): condition number kappa = 100
lam = np.array([1.0, 100.0])
f = lambda x: 0.5 * np.sum(lam * x**2)
grad = lambda x: lam * x
x0 = np.array([1.0, 1.0])
def run(step, tol=1e-6, max_steps=100_000):
x, v = x0.copy(), np.zeros(2)
for t in range(1, max_steps + 1):
x, v = step(x, v)
if f(x) < tol: return t
if f(x) > 1e12: return "diverged"
return f"> {max_steps}"
for eta in [0.0199, 0.0201]: # stability limit is 2 / lambda_max = 0.02
print(f"GD eta={eta}: steps to f<1e-6:", run(lambda x, v: (x - eta * grad(x), v)))
eta = 2 / (lam.min() + lam.max()) # best fixed step for GD
print(f"GD eta={eta:.4f} (optimal):", run(lambda x, v: (x - eta * grad(x), v)))
k = lam.max() / lam.min() # heavy-ball momentum, optimal tuning
eta_m = 4 / (np.sqrt(lam.max()) + np.sqrt(lam.min()))**2
beta = ((np.sqrt(k) - 1) / (np.sqrt(k) + 1))**2
def heavy_ball(x, v):
v = beta * v - eta_m * grad(x)
return x + v, v
print(f"momentum eta={eta_m:.4f}, beta={beta:.3f}:", run(heavy_ball))
print("Newton (H^-1 g):", run(lambda x, v: (x - grad(x) / lam, v)))
print(f"contraction per step: GD {(k-1)/(k+1):.3f}, momentum {(np.sqrt(k)-1)/(np.sqrt(k)+1):.3f}")
GD eta=0.0199: steps to f<1e-6: 882
GD eta=0.0201: steps to f<1e-6: diverged
GD eta=0.0198 (optimal): 444
momentum eta=0.0331, beta=0.669: 69
Newton (H^-1 g): 1
contraction per step: GD 0.980, momentum 0.818
Implicit bias, and why SGD needs a schedule:
import numpy as np
rng = np.random.default_rng(0)
# 1) Implicit bias: 5 equations, 20 unknowns -> infinitely many exact solutions
A = rng.normal(size=(5, 20)); b = rng.normal(size=5)
x_min = np.linalg.pinv(A) @ b # the minimum-norm solution
for name, x in [("zero init", np.zeros(20)), ("random init", rng.normal(size=20))]:
x0 = x.copy()
for _ in range(20_000):
x = x - 0.01 * A.T @ (A @ x - b) # plain gradient descent on 0.5*|Ax-b|^2
print(f"{name:>11}: residual {np.linalg.norm(A @ x - b):.1e} |x| {np.linalg.norm(x):.3f} "
f"distance to min-norm {np.linalg.norm(x - x_min):.3f}")
print(f"min-norm |x| {np.linalg.norm(x_min):.3f}")
# 2) SGD: a constant step stalls at a noise floor; a decaying step keeps improving
N, d = 5_000, 10
X = rng.normal(size=(N, d)); w_star = rng.normal(size=d)
y = X @ w_star + rng.normal(scale=1.0, size=N)
w_ls = np.linalg.lstsq(X, y, rcond=None)[0]
excess = lambda w: np.mean((X @ (w - w_ls))**2) # loss above the best achievable
for label, sched in [("constant 0.05", lambda t: 0.05),
("constant 0.005", lambda t: 0.005),
("0.05 -> cosine -> 0", lambda t: 0.025 * (1 + np.cos(np.pi * t / 20_000)))]:
w = np.zeros(d)
for t in range(20_000):
i = rng.integers(N)
w -= sched(t) * (X[i] @ w - y[i]) * X[i] # one-example SGD step
print(f"{label:>20}: excess loss after 20k steps {excess(w):.5f}")
zero init: residual 5.7e-16 |x| 0.540 distance to min-norm 0.000
random init: residual 1.4e-15 |x| 3.016 distance to min-norm 2.967
min-norm |x| 0.540
constant 0.05: excess loss after 20k steps 0.25787
constant 0.005: excess loss after 20k steps 0.01531
0.05 -> cosine -> 0: excess loss after 20k steps 0.00261
Things to try
- Add a diagonal preconditioner to the quadratic experiment: divide each gradient coordinate by a running root-mean-square of its past values (RMSProp). How many steps now? Why does it help so much here, and why would it help less if the valley were rotated 45° (rotate with a 2×2 matrix and see)?
- Run GD on \(f(x, y) = x^2 - y^2 + \frac14 y^4\) from \((1, 10^{-8})\) and from \((1, 0)\). One escapes the saddle at the origin and one never does. Add a little Gaussian noise to the gradient and repeat.
- In the implicit-bias experiment, replace gradient descent with Adam. Does it still find the minimum-norm solution? (It does not, in general: the preconditioner changes the geometry, and so the implicit bias.)
- Track the largest Hessian eigenvalue (by power iteration on finite-difference Hessian-vector products) while training a tiny MLP with full-batch GD. Does it climb to \(2/\eta\) and stop, as the edge-of-stability paper predicts?
Common misconceptions¶
- "Neural networks get stuck in bad local minima." In large networks the empirical evidence points the other way: saddles and plateaus slow training; bad isolated minima are rarely the problem. Failure to train is more often an initialisation, normalisation or learning-rate issue (see the training recipe).
- "A smaller learning rate is always safer." It lowers the noise floor and avoids divergence, but it also slows progress, can strand you on plateaus, and changes the implicit bias (often towards sharper minima).
- "Adam is a second-order method." Its preconditioner is built from squared gradients, a rough proxy for curvature that coincides with the diagonal of the Fisher information only under specific conditions. It uses no Hessian information.
- "Convex means fast." Convex means correct. A convex problem with \(\kappa = 10^6\) is still painfully slow for gradient descent.
Check yourself¶
The largest eigenvalue of your loss Hessian is 400. What is the largest stable learning rate for plain gradient descent near this point?
\(2/400 = 0.005\). Above it, the steepest direction's error is multiplied by \(|1 - 400\eta| > 1\) every step and grows.
Why is logistic regression convex but a one-hidden-layer network is not?
Logistic loss is a convex function (log-sum-exp minus linear) of logits that are linear in the weights, and convexity survives composition with affine maps. In a network, the logits are non-linear functions of the first-layer weights, and the permutation symmetry of hidden units produces many separate minima whose average is not a minimum.
With κ = 10,000, roughly how many more steps does gradient descent need than heavy-ball momentum for the same accuracy?
GD's contraction is \(\approx 1 - 2/\kappa\), momentum's \(\approx 1 - 2/\sqrt\kappa\). Steps scale as \(\kappa\) versus \(\sqrt\kappa\): about 10,000 versus 100, so roughly 100 times more.
Minimise x + y subject to x² + y² = 1 using a Lagrange multiplier.
\(\nabla(x + y) = \lambda\nabla(x^2 + y^2)\) gives \(1 = 2\lambda x\) and \(1 = 2\lambda y\), so \(x = y\). The constraint gives \(x = y = \pm 1/\sqrt2\); the minimum is at \(x = y = -1/\sqrt2\) with value \(-\sqrt2\) (and \(\lambda = -1/\sqrt2\)). The other point is the maximum.
Why does SGD with a constant learning rate never converge exactly, and what two things do schedules trade off?
Each step adds noise of size proportional to \(\eta\) times the gradient's standard deviation, which does not vanish at the minimum (individual examples still have non-zero gradients). The iterates equilibrate in a cloud of size proportional to \(\eta\). Schedules trade early speed (large \(\eta\) travels far) against final precision (small \(\eta\) shrinks the cloud).
Hard: show that gradient descent from θ₀ = 0 on ½‖Aθ − b‖² can only converge to the minimum-norm solution.
Every gradient is \(A^\top(A\theta - \mathbf{b})\), which lies in the row space of \(A\). Starting at zero, every iterate is a sum of such vectors, so it lies in the row space. The exact solutions form \(\theta_\text{min} + \operatorname{null}(A)\), and the only one in the row space (orthogonal to the null space) is \(\theta_\text{min} = A^+\mathbf{b}\), which by Pythagoras has the smallest norm. Starting at \(\theta_0 \ne 0\) adds \(\theta_0\)'s null-space component, which GD never changes.
Go deeper¶
Papers
- Optimization Methods for Large-Scale Machine Learning — Bottou, Curtis and Nocedal, 2018. The review: SGD theory, noise, second-order ideas, written for ML.
- A Stochastic Approximation Method — Robbins and Monro, 1951. The origin of SGD and its step-size conditions.
- Identifying and attacking the saddle point problem — Dauphin et al., 2014. Why saddles, not local minima, dominate high-dimensional landscapes.
- Gradient Descent Converges to Minimizers — Lee, Simchowitz, Jordan and Recht, 2016. Random initialisation avoids strict saddles almost surely.
- Linear Convergence under the Polyak–Łojasiewicz Condition — Karimi, Nutini and Schmidt, 2016. Fast convergence without convexity, in a few pages.
- Visualizing the Loss Landscape of Neural Nets — Li et al., 2018. Filter-normalised plots; skip connections smooth the landscape.
- Gradient Descent on Neural Networks Typically Occurs at the Edge of Stability — Cohen et al., 2021. Sharpness rises to 2/η and stays there.
- The Implicit Bias of Gradient Descent on Separable Data — Soudry et al., 2018. Logistic regression drifts to the max-margin solution.
Videos and lectures
- Convex Optimization I, lecture 1 — Stephen Boyd, Stanford EE364A. The course that defines the field; full series on Stanford Engineering Everywhere.
- Gradient Descent, Step-by-Step — StatQuest. The mechanics, slowly, if you want a warm-up.
Articles
- Why Momentum Really Works — Gabriel Goh, Distill, 2017. The quadratic analysis above, interactive and complete.
- An overview of gradient descent optimization algorithms — Sebastian Ruder, 2016. Momentum, Nesterov, AdaGrad, RMSProp, Adam side by side.
Courses and books
- Convex Optimization — Boyd and Vandenberghe (free PDF). Chapters 2–5 (convex sets, functions, problems, duality) and 9 (unconstrained minimisation).
- Convex Optimization (10-725, Fall 2019) — Ryan Tibshirani, CMU. Lecture slides and notes with an ML slant: proximal methods, duality, rates.
- Deep Learning, chapter 8 — Goodfellow, Bengio and Courville. Optimisation for training deep models: ill-conditioning, saddles, cliffs.
Where this leads¶
- Optimisers: SGD, momentum, Adam, AdamW and schedules — the practical algorithms, built on this theory.
- Floating point, stability and log-sum-exp — what happens when the numbers themselves misbehave during optimisation.
- Kernels and support vector machines — Lagrangian duality turned into an algorithm.
- Initialisation and normalisation — reshaping the landscape so that optimisation is well conditioned from step one.
- Actor-critic and PPO — optimisation with a moving target and a trust region.