Backprop, Jacobians, Hessians: Why First-Order Wins

Why deep learning uses first-order optimisation: a PyTorch demo comparing SGD, L-BFGS, and Gauss-Newton on a GELU net, with Jacobians and Hessians.

Cover Image for Backprop, Jacobians, Hessians: Why First-Order Wins

A training run makes many small updates before its loss settles, so a method that needs fewer steps sounds appealing. The cost of a step matters too, especially as the network grows. Our earlier backpropagation and SGD examples use the gradient to choose an update. Methods that also use curvature have more information, but must obtain and work with it.

Counting steps alone favours curvature. Gauss-Newton reaches the noise floor in 30 iterations, L-BFGS in 40 and SGD in 20,000. L-BFGS is faster in elapsed time, taking 0.12 seconds against Gauss-Newton's 0.37. We trace gradients, Jacobians and Hessians on this 25-parameter network to explain the cost.

By the end, you will be able to estimate the memory and computation needed for full Newton on a 70-billion-parameter transformer.

Quick Win: Three Optimisers on One Loss Surface

Open In Colab

Fit a two-layer GELU net with 8 hidden units (25 weights and biases) to 40 noisy observations of sin⁡(2πx)\sin(2\pi x). Train it three ways from the same initialisation, log loss per iteration and per wall-clock second.

Convergence animation: SGD flattens out slowly while L-BFGS and Gauss-Newton drop to the noise floor within ~30 iterations

import torch
import torch.nn.functional as F

torch.manual_seed(0)
N = 40
x = torch.linspace(0.05, 0.95, N, dtype=torch.float64).unsqueeze(1)
y = torch.sin(2 * torch.pi * x) + 0.08 * torch.randn_like(x)

HIDDEN = 8  # 25 parameters total

def predict(theta, x):
    W1 = theta[:HIDDEN].view(HIDDEN, 1)
    b1 = theta[HIDDEN:2 * HIDDEN]
    W2 = theta[2 * HIDDEN:3 * HIDDEN].view(1, HIDDEN)
    b2 = theta[3 * HIDDEN:]
    return F.gelu(x @ W1.T + b1) @ W2.T + b2

def loss(theta):
    return 0.5 * ((predict(theta, x) - y) ** 2).mean()

The three trainers differ only in how they use loss(theta):

  • SGD + momentum computes ∇L\nabla \mathcal{L} via loss(theta).backward(), multiplies by a learning rate, and subtracts.
  • L-BFGS keeps the last 20 gradients and implicitly reconstructs an approximation to H−1H^{-1} from them. One backward pass per iteration.
  • Gauss-Newton (Levenberg-Marquardt) evaluates the full Jacobian of residuals with respect to parameters, forms J⊤JJ^\top J as a positive-semidefinite approximation to the Hessian, and solves a linear system at every step.
# Gauss-Newton: outer-product (J^T J) approximation to the Hessian
from torch.autograd.functional import jacobian
J = jacobian(lambda t: (predict(t, x) - y).squeeze(-1), theta)  # (N, W)
r = (predict(theta, x) - y).squeeze(-1).detach()
step = torch.linalg.solve(J.T @ J / N + damping * I, J.T @ r / N)
theta = theta - step

Here is the convergence per outer iteration (log scale on both axes so all three fit).

Loss versus iteration: Gauss-Newton reaches the noise floor in 30 iterations, L-BFGS in 40, SGD needs 20,000

Gauss-Newton wins on iterations. L-BFGS is a hair behind. SGD needs roughly a thousand times more updates to reach the same loss. That is the textbook result: more curvature information, fewer steps.

Now the plot the iteration-count story leaves out.

Loss versus wall-clock time: L-BFGS finishes in 0.12s, Gauss-Newton in 0.37s, SGD in 10s

On wall-clock time, L-BFGS wins: 0.12 seconds versus 0.37 for Gauss-Newton, and that is on a 25-parameter toy. Each Gauss-Newton step solves a W×WW \times W linear system; each L-BFGS step does two inner products of length WW. At 25 parameters the gap is 3x. At 25 million, it is billions.

All three recover the true sin⁡(2πx)\sin(2\pi x) from the noisy samples. The difference is entirely in how they got there.

Three network fits overlaid on the noisy sin(2πx) data: all three match the true curve to within the noise

What Just Happened?

1. Backpropagation is the cheap way to get the gradient

Forget the cartoon with arrows flowing backwards through a network for a moment. Backpropagation is, mathematically, the chain rule applied to a computation graph. For a two-layer network with weights W(1)W^{(1)} and W(2)W^{(2)} and a sum-of-squares loss En=12∑k(yk−tk)2E_n = \tfrac{1}{2}\sum_k (y_k - t_k)^2, the backpropagation equations write the gradient as

∂En∂wji(1)=δj xi,∂En∂wkj(2)=δk zj\frac{\partial E_n}{\partial w_{ji}^{(1)}} = \delta_j \, x_i, \qquad \frac{\partial E_n}{\partial w_{kj}^{(2)}} = \delta_k \, z_j

where δk=yk−tk\delta_k = y_k - t_k is the output error and δj=(1−zj2)∑kwkj(2)δk\delta_j = (1 - z_j^2)\sum_k w_{kj}^{(2)} \delta_k propagates it back through the hidden layer. The practical consequence: one forward pass, one backward pass, and every one of the network's WW weight derivatives is computed. Total cost: O(W)O(W).

The naive alternative is finite differences. Perturb each weight individually, re-run the forward pass, measure the change in loss. That costs WW forward passes instead of one. For a 70-billion-parameter language model it would be 70 billion forward passes per gradient step. Backpropagation is the difference between a feasible training loop and a computationally impossible one.

One observation is worth sitting with. The only reason deep learning exists is that one backward pass gives you WW numbers at O(W)O(W) cost. Every autograd framework on the planet is an industrial-strength version of that chain rule.

2. The Jacobian is a sideways backward pass

The Hessian and Jacobian names get shuffled around the literature, so it's worth pinning them down. For a network mapping inputs x\mathbf{x} to outputs y\mathbf{y}, the Jacobian is

Jki≡∂yk∂xiJ_{ki} \equiv \frac{\partial y_k}{\partial x_i}

This measures how much each output changes for a small wiggle in each input. It is the linear approximation of the network at a point. In a trained net, if the Jacobian is large along some input direction, the network is highly sensitive to that feature; if it is near zero, the model ignores it. For our trained network fitting sin⁡(2πx)\sin(2\pi x), the one-input Jacobian ∂y/∂x\partial y / \partial x should look like the derivative of the target function, 2πcos⁡(2πx)2\pi \cos(2\pi x).

Trained network output y(x) and its Jacobian ∂y/∂x, plotted against the true 2π cos(2πx)

It does, to within the same noise budget that sets the fit itself. Computing this costs one backward pass per input point, which is the same O(W)O(W) trick that makes backprop tractable. The useful mental model: the gradient is ∂L/∂θ\partial \mathcal{L} / \partial \theta (how loss changes when you wiggle weights), and the Jacobian is ∂y/∂x\partial y / \partial x (how outputs change when you wiggle inputs). Both are first-order objects; both are one backward pass.

3. The Hessian is expensive because it is big

The Hessian is the matrix of second derivatives of the loss with respect to the weights:

Hij=∂2L∂wi ∂wjH_{ij} = \frac{\partial^2 \mathcal{L}}{\partial w_i \, \partial w_j}

For WW parameters, this is a W×WW \times W matrix. Storing it is O(W2)O(W^2). Solving HΔθ=−gH \Delta \theta = -g for the Newton step is O(W3)O(W^3). The gradient costs O(W)O(W). That gap is the whole story.

Cost per optimiser step as a function of W: first-order O(W), L-BFGS O(mW), Hessian storage O(W²), Newton solve O(W³)

At W=105W = 10^5 (a small MLP), the Newton solve is roughly seven orders of magnitude more expensive than the gradient step. At W=1010W = 10^{10} (GPT-3 scale), the Hessian does not fit on Earth's hard drives, let alone on a single GPU. That is why you never see full Newton in a modern training loop.

The theorists' comeback is that Newton converges in far fewer iterations, so maybe the per-step cost is worth it. Sometimes, for small convex problems, yes. For neural networks, no: the loss surface is non-convex, and that breaks Newton in ways the textbook classical-optimisation view does not prepare you for.

4. Non-convex loss breaks plain Newton

Evaluate the full Hessian of our 25-parameter net at the initial weights. Check its eigenvalues.

Hessian eigenvalue spectrum at initialisation (13 of 25 negative) and at the Gauss-Newton optimum (10 negative, 15 positive)

Thirteen of twenty-five eigenvalues are negative at initialisation. Newton's direction −H−1g-H^{-1} g assumes HH is positive definite; along any direction where HH has a negative eigenvalue, the step points uphill. Dauphin et al. (2014, Identifying and attacking the saddle point problem in high-dimensional non-convex optimisation) showed that in high-dimensional neural networks this is the rule, not the exception. The loss surface is riddled with saddle points, and plain Newton is attracted to them rather than repelled.

That is why, in the experiment above, we used Gauss-Newton rather than full Newton. Gauss-Newton approximates the Hessian as J⊤JJ^\top J, where JJ is the Jacobian of residuals with respect to parameters. Because J⊤JJ^\top J is positive semi-definite by construction, the update direction is always a descent direction. This is the outer-product approximation, also known as the Levenberg-Marquardt method, and it is the second-order method you will see in regression packages like scipy.optimize.least_squares. Naive Newton with the full Hessian on the same net gets stuck at a loss of 0.27 (well above the noise floor of 0.003) and refuses to move.

The broader lesson: even if you could afford the Hessian, you would not want to use it on a non-convex loss. You would want J⊤JJ^\top J or some other positive-definite modification. And at that point you might as well skip the expensive matrix and use a quasi-Newton method that approximates H−1H^{-1} from gradient history at O(W)O(W) cost.

Going Deeper

Why modern activations quietly killed second-order

The classical derivations assume smooth activations: tanh⁡\tanh, sigmoid, logistic. All have continuous second derivatives. The Hessian of a two-layer tanh network is a well-defined object you can differentiate through. ReLU broke this.

Activation functions and their derivatives. Tanh and GELU have smooth second derivatives; ReLU's second derivative is zero almost everywhere and undefined at zero

Tanh was the textbook default until the early 2010s. Reading basic tutorials today, you still see it; the activation has been over 10 years past its retirement date and nobody uses it in production networks any more. ReLU took over in 2012 (Krizhevsky et al., AlexNet) because it trains faster and avoids vanishing gradients. Its trade-off: ReLU is piecewise linear, so h′′(a)=0h''(a) = 0 everywhere except at a=0a = 0 where it is undefined. A ReLU network's Hessian has zeros on most of its diagonal contributions and is uninformative as a curvature estimate. Second-order methods cannot extract the curvature they need because there is no curvature to extract.

GELU (Hendrycks & Gimpel, 2016), used in BERT, GPT-2, LLaMA, is smooth by construction: GELU(a)=aΦ(a)\text{GELU}(a) = a \Phi(a), where Φ\Phi is the Gaussian CDF. Its second derivative is a well-behaved bump. We chose GELU for this post for the same reason the classical treatments chose tanh: the Hessian exists and can be probed. The pattern is larger than any one activation: the field moved toward first-order methods partly because the activations moved toward piecewise-linear. If your gradient is informative and your Hessian is zero, you build optimisers around gradients.

The Hessian approximations people use in practice

Full Newton is impossible at scale, but second-order information is useful. The Hessian (or a proxy) gets used in four practical ways.

Diagonal approximation. Keep only the diagonal of HH, ignore the off-diagonal terms. Storage drops to O(W)O(W) and the inverse is trivial. Adagrad, RMSProp, and Adam are exactly this idea applied to squared-gradient accumulators, which are a stochastic diagonal approximation to the Fisher information matrix (which itself approximates the Hessian for log-likelihood losses). Every time you use Adam, you are using a cheap diagonal Hessian preconditioner.

Outer-product / Gauss-Newton. Approximate HH as J⊤JJ^\top J plus a damping term. Guaranteed positive semi-definite, cheap to assemble for regression losses, and the foundation of Levenberg-Marquardt. This is what our Quick Win used and what scientific computing packages still use for nonlinear least squares.

Quasi-Newton (L-BFGS). Never form the Hessian. Keep the last mm gradient differences and use the BFGS update formula to reconstruct a low-rank approximation to H−1H^{-1} on the fly. Storage is O(mW)O(mW) (mm around 10 to 20 in practice), per-step cost is O(mW)O(mW). L-BFGS is the go-to method for smooth non-stochastic optimisation (fitting logistic regressions, hyperparameter optimisation of GPs, variational inference with small numbers of parameters). It is the second-fastest thing in our Quick Win plot and the fastest in wall-clock terms.

Hessian-vector products via the R-operator. For many uses you do not need HH, only HvHv for some vector vv. Pearlmutter (1994) showed this can be computed in O(W)O(W) time with a single forward-backward pass variant, no matrix ever assembled. Martens's 2010 Hessian-Free optimisation for deep networks is the most famous application: use conjugate gradient on HvHv products to approximately solve HΔθ=−gH \Delta \theta = -g without ever materialising HH. It is how you can do Newton-ish steps at trillion-parameter scale.

The pattern repeats: the second you think a second-order method is out of reach, someone finds a way to extract just the part of it that is informative at first-order cost.

A brief Bayesian cameo

The Hessian also shows up in Bayesian inference. At the MAP weights, the Hessian of the negative log-posterior is the inverse covariance of the Laplace approximation to the posterior. The log determinant of that Hessian appears in the evidence framework as the Occam factor. A follow-up post extends this to Bayesian neural networks: predictions with uncertainty, and model evidence that balances fit against effective parameter count via the Hessian's eigenvalues. If the Hessian is expensive for optimisation, it is equally expensive for Bayesian inference, which is why modern Bayesian deep learning uses variational approximations or stochastic-gradient MCMC rather than Laplace. The problem is the same problem: W×WW \times W matrices at neural-network scale.

The Foundations

The key references behind this post are worth reading at source.

Rumelhart, Hinton, Williams (1986), Learning representations by back-propagating errors. The original backpropagation paper. A three-page Nature letter showing how hidden layers of a feed-forward network can learn distributed representations via gradient descent on a sum-of-squares error. Free on the Stanford CS229 site.

Pearlmutter (1994), Fast exact multiplication by the Hessian. Shows how to compute HvHv for any vector vv in O(W)O(W) time. The key trick is the R-operator R{⋅}\mathcal{R}\{\cdot\}: apply the directional derivative along vv to the forward and backward propagation equations, introducing companion variables R{aj},R{zj},R{δj}\mathcal{R}\{a_j\}, \mathcal{R}\{z_j\}, \mathcal{R}\{\delta_j\} for the hidden units and R{δk},R{yk}\mathcal{R}\{\delta_k\}, \mathcal{R}\{y_k\} for the outputs, so that v⊤H\mathbf{v}^\top \mathbf{H} falls out of a single forward-backward sweep with no matrix ever assembled.

Dauphin, Pascanu, Gulcehre, Cho, Ganguli, Bengio (2014), Identifying and attacking the saddle point problem in high-dimensional non-convex optimization. The saddle-point paper. Argues that in high-dimensional non-convex problems (neural networks), the difficulty is not local minima but saddle points, which trap Newton's method. Motivates saddle-free optimisation methods that flip the sign of negative Hessian eigenvalues. Free on arXiv:1406.2572.

Martens (2010), Deep learning via Hessian-free optimization. The paper that popularised HvHv products for deep learning. Combines Pearlmutter's trick with conjugate gradient and a positive-semidefinite Gauss-Newton surrogate. Briefly competitive with SGD for deep networks around 2010-2013 before Adam made the discussion moot. Free on the University of Toronto page.

Le Cun, Bottou, Orr, Müller (1998), Efficient BackProp. The practitioner's guide. Covers the diagonal Hessian approximation for learning-rate adaptation (precursor to Adam), the importance of input normalisation (precursor to batch normalisation), and why tanh is preferred to sigmoid in shallow nets (centred activations). A lot of what feels like modern deep-learning folk wisdom shows up in this 1998 chapter.

The clearest way to see backpropagation is as a disciplined application of the chain rule on a computation graph, rather than a mysterious "error signal" flowing backwards. A simple two-layer worked example plus the O(W)O(W) efficiency argument is the whole case for why gradient descent on neural networks works at all.

Interactive Tools

  • Gradient Descent Visualizer: The curvature this post declines to compute, seen from the outside. The ravine and Rosenbrock presets are exactly the ill-conditioned cases where first-order methods struggle and momentum patches over the gap
  • Overfitting Explorer: a polynomial-regression playground, the same dataset the evidence-framework post used. Shows how first-order gradient descent on a closed-form least-squares problem is unnecessary when the normal equations exist. The contrast is useful.
  • Regression Playground: Fit linear and polynomial regressions interactively. For a quadratic loss, the Hessian is constant and Newton converges in a single step. Second-order methods win decisively here.

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions