Optimisation and gradient descent

"Training" a model means finding the parameters that make an error as small as possible. That is optimisation.

⏱ 22 minNeeds: Chapters 2 and 43 simulations
In plain words

You are on a hillside in thick fog and want to reach the lowest point of the valley. You cannot see the valley, but you can feel which way the ground slopes under your feet. Step downhill, feel again, step again. That is gradient descent. How long your steps are — the learning rate — decides whether you arrive, crawl, or tumble back and forth across the valley.

New to gradient descent?

Start with Chapter 10: the same ideas with one apple price, every step by hand, a lab, and a one-minute video. This chapter then adds the theory, momentum, Adam and stochastic gradients.

You will learn
Level 1 · basicLoss functions; gradient descent; learning rate Level 2 · standardMomentum, Adam, stochastic gradient descent Level 3 · advancedConvexity, convergence and conditioning
Simplest example first · roll down a parabola

Find the lowest point of $f(x) = (x - 3)^2$. We know the answer is $x = 3$, so we can watch gradient descent find it. The slope is $f'(x) = 2(x - 3)$. Start at $x_0 = 0$, where the slope is $-6$ (downhill to the right), and use $\eta = 0.25$: $$x_1 = 0 - 0.25(-6) = 1.5,\quad x_2 = 1.5 - 0.25(-3) = 2.25,\quad x_3 = 2.625,\ \dots$$ Each step halves the distance to $3$. Try $\eta = 0.5$ (one step lands exactly on 3), $\eta = 0.9$ (it overshoots back and forth) and $\eta = 1.1$ (it runs away).

1. The optimisation problem

Given a function $f:\mathbb R^n \to \mathbb R$ — the loss or objective — find $\mathbf x^*$ with $f(\mathbf x^*) \le f(\mathbf x)$ for all $\mathbf x$ (a global minimiser), or at least for all $\mathbf x$ near $\mathbf x^*$ (a local minimiser).

Theorem · First- and second-order conditions

If $\mathbf x^*$ is a local minimiser and $f$ is continuously differentiable near it, then $\nabla f(\mathbf x^*) = \mathbf 0$. If moreover $\nabla f(\mathbf x^*) = \mathbf 0$ and the Hessian $\nabla^2 f(\mathbf x^*)$ (matrix of second partial derivatives) is positive definite, then $\mathbf x^*$ is a strict local minimiser.

Nocedal & Wright, Numerical Optimization, 2nd ed., Springer (2006), chapter 2 "Fundamentals of Unconstrained Optimization".
Example · fitting a line (least squares)

Data $(x_k, y_k)$, model $y \approx a x + b$. Loss $L(a,b) = \frac1N\sum_k (a x_k + b - y_k)^2$ — the mean squared error. Setting $\partial L/\partial a = \partial L/\partial b = 0$ gives two linear equations (the "normal equations"). For a neural network the equations are nonlinear, with millions of unknowns, and we must iterate.

2. Gradient descent

The gradient $\nabla f$ points uphill (Chapter 2). So step the other way:

Definition · Gradient descent

$$\mathbf x_{k+1} = \mathbf x_k - \eta\,\nabla f(\mathbf x_k), \qquad k = 0, 1, 2, \dots$$ with learning rate (step size) $\eta > 0$.

Cauchy, "Méthode générale pour la résolution des systèmes d'équations simultanées", C. R. Acad. Sci. Paris 25 (1847) 536–538; Nocedal & Wright (2006), chapter 3.
Gradient descent on a landscapeclick anywhere to choose the starting point
Darker = lower loss; the star marks the minimum. In the long valley, a large learning rate zig-zags across it and a small one crawls along it — the problem is ill-conditioned. Momentum and Adam handle it far better. With "Two valleys", where you start decides which minimum you find.
Loss against iteration for the run abovelog scale
A straight line on this log plot means the loss falls by a constant factor each step — linear convergence. Upward spikes mean the learning rate is too large.

3. When does gradient descent work?

Definition · Convex function and L-smoothness

$f$ is convex if $f(\theta\mathbf x + (1-\theta)\mathbf y) \le \theta f(\mathbf x) + (1-\theta)f(\mathbf y)$ for all $\mathbf x, \mathbf y$ and $\theta\in[0,1]$: the chord lies above the graph, and every local minimiser is global. $f$ is $L$-smooth if $\|\nabla f(\mathbf x) - \nabla f(\mathbf y)\| \le L\|\mathbf x - \mathbf y\|$.

Boyd & Vandenberghe, Convex Optimization, Cambridge University Press (2004), chapter 3 — free online from the authors.
Theorem · Convergence of gradient descent

Let $f$ be convex and $L$-smooth with a minimiser $\mathbf x^*$. Gradient descent with $\eta = 1/L$ satisfies $$f(\mathbf x_k) - f(\mathbf x^*) \le \frac{L\,\|\mathbf x_0 - \mathbf x^*\|^2}{2k}.$$ If $f$ is also $\mu$-strongly convex, the error shrinks geometrically: $\|\mathbf x_k - \mathbf x^*\|^2 \le (1 - \mu/L)^k\|\mathbf x_0 - \mathbf x^*\|^2$. The ratio $\kappa = L/\mu$ is the condition number; large $\kappa$ (a long narrow valley) means slow convergence.

Nesterov, Introductory Lectures on Convex Optimization, Kluwer (2004), chapter 2; Bubeck, "Convex optimization: algorithms and complexity", Found. Trends Mach. Learn. 8 (2015) 231–357.

For a quadratic $f = \tfrac12\mathbf x^{\mathsf T}A\mathbf x$, $L$ and $\mu$ are the largest and smallest eigenvalues of $A$ (Chapter 4), and gradient descent diverges if $\eta > 2/L$ — the same "$h|\lambda| \le 2$" stability limit as Euler's method in Chapter 6. That is no coincidence: gradient descent is Euler's method for the "gradient flow" ODE (Ordinary Differential Equation) $\mathbf x'(t) = -\nabla f(\mathbf x)$.

Neural network losses are not convex. There are no global guarantees, but the same intuition — learning rate vs curvature, conditioning — explains most practical behaviour.

4. Momentum and Adam

Animation: on an elongated bowl, plain gradient descent zig-zags across the valley while momentum moves smoothly to the minimum.
Watch: Plain gradient descent (red) zig-zags across a narrow valley; momentum (green) builds up speed along it and arrives sooner.
Definition · Momentum (heavy ball) and Adam

Momentum: $\mathbf v_{k+1} = \beta\mathbf v_k - \eta\nabla f(\mathbf x_k)$, $\ \mathbf x_{k+1} = \mathbf x_k + \mathbf v_{k+1}$. Like a ball rolling with inertia: zig-zags cancel, consistent directions accumulate (Polyak, USSR Comput. Math. Math. Phys. 4(5), 1964, 1–17).

Adam: keep running averages of the gradient $\mathbf m$ and its square $\mathbf s$ (component-wise), $$\mathbf m_{k} = \beta_1\mathbf m_{k-1} + (1-\beta_1)\mathbf g_k,\quad \mathbf s_{k} = \beta_2\mathbf s_{k-1} + (1-\beta_2)\mathbf g_k^2,\quad \mathbf x_{k+1} = \mathbf x_k - \eta\,\frac{\hat{\mathbf m}_k}{\sqrt{\hat{\mathbf s}_k} + \epsilon},$$ with bias corrections $\hat{\mathbf m}_k = \mathbf m_k/(1-\beta_1^k)$, $\hat{\mathbf s}_k = \mathbf s_k/(1-\beta_2^k)$; defaults $\beta_1 = 0.9$, $\beta_2 = 0.999$, $\epsilon = 10^{-8}$. Each parameter gets its own effective step size.

Kingma & Ba, "Adam: A method for stochastic optimization", ICLR 2015 (arXiv:1412.6980).
In SciML

PINNs are usually trained with Adam for a few thousand steps, then refined with L-BFGS (Limited-memory Broyden–Fletcher–Goldfarb–Shanno method), a quasi-Newton method that builds an approximation of the Hessian from recent gradients (Liu & Nocedal, Math. Programming 45, 1989, 503–528). Ill-conditioning of the PINN loss is a known reason training stalls (Krishnapriyan et al., NeurIPS 2021; Rathore et al., "Challenges in training PINNs: a loss landscape perspective", ICML 2024).

5. Stochastic gradient descent

When the loss is an average over $N$ data points (or collocation points), $L = \frac1N\sum_k \ell_k$, computing the full gradient is expensive. Stochastic gradient descent uses a random mini-batch of points each step; the gradient is noisy but cheap and correct on average (Robbins & Monro, Ann. Math. Stat. 22, 1951, 400–407). Each full pass over the data is an epoch.

Fitting a line by (stochastic) gradient descent40 noisy points; model y = a·x + b
Batch size 40 is full gradient descent: smooth progress. Batch size 1 is pure SGD (Stochastic Gradient Descent): jittery but each step is 40 times cheaper. The best least-squares line is shown dashed.

6. Try it in Python

import numpy as np
import matplotlib.pyplot as plt

f = lambda p: (1 - p[0])**2 + 100 * (p[1] - p[0]**2)**2          # Rosenbrock
grad = lambda p: np.array([-2*(1 - p[0]) - 400*p[0]*(p[1] - p[0]**2), 200*(p[1] - p[0]**2)])

def run(method, lr, steps=3000):
    p = np.array([-1.2, 1.0]); m = np.zeros(2); s = np.zeros(2); v = np.zeros(2); hist = []
    for k in range(1, steps + 1):
        g = grad(p)
        if method == "gd":   p = p - lr * g
        if method == "mom":  v = 0.9 * v - lr * g; p = p + v
        if method == "adam":
            m = 0.9*m + 0.1*g; s = 0.999*s + 0.001*g*g
            p = p - lr * (m/(1 - 0.9**k)) / (np.sqrt(s/(1 - 0.999**k)) + 1e-8)
        hist.append(f(p))
    return p, hist

for method, lr in [("gd", 1e-3), ("mom", 1e-4), ("adam", 2e-2)]:
    p, h = run(method, lr)
    plt.semilogy(h, label=f"{method} (lr={lr}) -> {np.round(p, 3)}")
plt.xlabel("iteration"); plt.ylabel("loss"); plt.legend(); plt.grid(alpha=.3); plt.show()

For $f(x) = 5x^2$, gradient descent diverges if the learning rate exceeds…

Right: $f'(x) = 10x$, so $x_{k+1} = (1 - 10\eta)x_k$; this blows up when $|1 - 10\eta| > 1$, i.e. $\eta > 0.2 = 2/L$ with $L = 10$.

For a convex function, a point where $\nabla f = 0$ is…

Right — for convex functions, stationary points are global minimisers. That is why convex problems are "easy".

Key takeaways

Further reading