AnyLearn
All lessons
Mathintermediate

Gradients, Jacobians, and Hessians: Calculus in Many Dimensions

One derivative becomes three objects once a function has many inputs and many outputs. This lesson builds the gradient, the Jacobian and the Hessian, shows what each one actually tells you, and explains why curvature decides how many steps an optimiser needs and why nobody ever writes the Hessian down.

Updated · AI-authored, review-gated · how lessons are made

Not signed in: your progress and quiz score won't be saved.
Progress1 / 10

One input at a time

A loss depends on millions of parameters at once, but the derivative machinery only knows how to handle one. So freeze all but one and differentiate normally. That is a partial derivative, written f/xi\partial f / \partial x_i, and it answers a deliberately narrow question: how does ff respond to this coordinate alone, with everything else held still?

Collect all of them into a vector and you have the gradient:

f(x)=[fx1, fx2, , fxn]T\nabla f(x) = \left[\frac{\partial f}{\partial x_1},\ \frac{\partial f}{\partial x_2},\ \dots,\ \frac{\partial f}{\partial x_n}\right]^{\mathsf{T}}

Definition: The gradient of a scalar function is the vector of its partial derivatives. It has exactly as many entries as the function has inputs, which is why a gradient in a language model is the same size as the model.

Full lesson text

All 10 steps on one page, for reading, reference, and search.

Show

1. One input at a time

A loss depends on millions of parameters at once, but the derivative machinery only knows how to handle one. So freeze all but one and differentiate normally. That is a partial derivative, written f/xi\partial f / \partial x_i, and it answers a deliberately narrow question: how does ff respond to this coordinate alone, with everything else held still?

Collect all of them into a vector and you have the gradient:

f(x)=[fx1, fx2, , fxn]T\nabla f(x) = \left[\frac{\partial f}{\partial x_1},\ \frac{\partial f}{\partial x_2},\ \dots,\ \frac{\partial f}{\partial x_n}\right]^{\mathsf{T}}

Definition: The gradient of a scalar function is the vector of its partial derivatives. It has exactly as many entries as the function has inputs, which is why a gradient in a language model is the same size as the model.

2. Why the gradient points the steepest way up

Partial derivatives only describe moves along the axes. To move in an arbitrary direction uu, with u=1\|u\| = 1, take the directional derivative:

Duf(x)=f(x)uD_u f(x) = \nabla f(x) \cdot u

Now ask which unit uu makes that largest. It is a dot product with a fixed vector, so the Cauchy-Schwarz inequality answers immediately: it is maximised when uu points the same way as f(x)\nabla f(x), and the maximum value is f(x)\|\nabla f(x)\|.

Two facts come out of that one line. The gradient's direction is the steepest ascent, which is why descent moves the other way. Its magnitude is the steepest possible rate of change at that point, which is the number people mean by "gradient norm" when they watch it explode during training.

3. Steepest with respect to what, exactly?

That derivation quietly assumed something. "Unit vector" means u=1\|u\| = 1 in the ordinary Euclidean norm, so steepest ascent means steepest per unit of Euclidean distance in parameter space.

Change the units of one parameter and the geometry changes with them. Suppose ff depends on a weight measured in metres and you switch to kilometres. The function is the same function; the same physical move is now a different-sized step; and the direction the gradient calls steepest has rotated.

Gotcha: The gradient is not an intrinsic "downhill" arrow. It is downhill relative to a particular notion of distance, and that notion is an arbitrary choice inherited from how you happened to parameterise the model. Adam, RMSProp and every other per-parameter learning rate scheme is in effect a rescaling of that geometry, which is why they can outrun plain gradient descent without ever computing a better gradient.

4. Many outputs: the Jacobian

A neural network layer is not a scalar function. It maps nn numbers to mm numbers, so there is a derivative for every input-output pair. Stack them into a matrix and you have the Jacobian JJ, with Jij=fi/xjJ_{ij} = \partial f_i / \partial x_j: one row per output, one column per input.

FunctionDerivative objectShape
f:RRf: \mathbb{R} \to \mathbb{R}derivativescalar
f:RnRf: \mathbb{R}^n \to \mathbb{R}gradientn×1n \times 1
f:RnRmf: \mathbb{R}^n \to \mathbb{R}^mJacobianm×nm \times n
f:RnRf: \mathbb{R}^n \to \mathbb{R}, second orderHessiann×nn \times n

The gradient is just the Jacobian of a function with one output, transposed. Everything in the table is the same idea counted differently, and getting the count right is most of the work in practice.

5. The transposes that fill every backward pass

Take a linear layer y=Wxy = Wx with WW of shape (4,3)(4, 3). The Jacobian y/x\partial y / \partial x is WW itself, shape (4,3)(4, 3). But the backward pass multiplies by its transpose:

import numpy as np

W = np.random.randn(4, 3)      # layer R^3 -> R^4
x = np.random.randn(3)
y = W @ x                      # forward

dL_dy = np.random.randn(4)     # gradient arriving from above
dL_dx = W.T @ dL_dy            # (3,)   : Jacobian transpose times a vector
dL_dW = np.outer(dL_dy, x)     # (4, 3) : same shape as W

Gotcha: Textbooks disagree on whether a derivative matrix is laid out as the Jacobian or its transpose, the numerator and denominator conventions. Frameworks sidestep the argument with a rule you can always fall back on: a gradient has the same shape as the thing it is a gradient of. dL_dW is shaped like W, always. If your shapes do not line up, you have the convention backwards.

6. Second order: the Hessian

Differentiate every entry of the gradient with respect to every input and you get the Hessian, the n×nn \times n matrix of second partial derivatives, Hij=2f/xixjH_{ij} = \partial^2 f / \partial x_i \partial x_j. For any function whose second partials are continuous, mixed partials commute, so HH is symmetric.

It is the coefficient of the quadratic term in the multivariable Taylor expansion, the direct analogue of ff'' from the previous lesson:

f(x+h)f(x)+f(x)Th+12hTHhf(x + h) \approx f(x) + \nabla f(x)^{\mathsf{T}} h + \tfrac{1}{2} h^{\mathsf{T}} H h

The gradient tells you which way the surface tilts. The Hessian tells you how fast that tilt is changing, which is the same as asking how far you can trust the gradient before it goes stale.

7. Reading curvature off the eigenvalues

The Hessian is symmetric, so it has real eigenvalues and orthogonal eigenvectors. Each eigenvector is a direction, and its eigenvalue is the curvature along that direction: positive means the surface bends upward, negative means downward.

Predict first

You reach a point where every partial derivative is exactly zero. Is it a minimum?

This is why "the optimiser got stuck in a local minimum" is usually the wrong diagnosis for a large model. Flat regions around saddle points, where the gradient is small but not zero, slow training far more often than genuine basins do.

8. Conditioning: the number that decides how long you wait

The ratio of largest to smallest Hessian eigenvalue is the condition number κ\kappa. Geometrically it is how elongated the bowl is: κ=1\kappa = 1 is a perfect circle, large κ\kappa is a narrow ravine where the steepest direction points across the valley rather than along it.

Kantorovich's classical analysis of steepest descent on a quadratic gives the price directly. Each step shrinks the gap to the optimum by a factor of (κ1κ+1)2\left(\frac{\kappa - 1}{\kappa + 1}\right)^2, so the iterations needed grow linearly with κ\kappa:

Gradient-descent steps to cut the loss gap tenfold
iterations0200400600262958288576k=2k=10k=50k=100k=500k=1000
Source: Computed from the classical steepest-descent contraction factor ((k-1)/(k+1))^2 for a quadratic of condition number k

A badly conditioned problem is not harder to differentiate. It is harder to follow, and the cost is paid entirely in wall-clock time.

9. Why nobody writes the Hessian down

Curvature is genuinely useful, and the classic use of it, Newton's method, steps to xH1fx - H^{-1}\nabla f, which is condition-number-blind and converges in far fewer iterations. It is also unusable at scale, for a reason that is pure arithmetic.

A model with 10910^9 parameters has a Hessian with 101810^{18} entries. In 32-bit floats that is 4 exabytes, and inverting it is worse than storing it.

In practice: What survives is the Hessian-vector product HvHv. Pearlmutter showed in 1994 that HvHv can be computed exactly at roughly the cost of one gradient, without ever forming HH, by differentiating the gradient in a single direction. Everything second-order that runs on real models, Newton-Krylov methods, curvature-aware optimisers, sharpness measurements, is built on that product rather than on the matrix.

10. When the parameters are not free

Everything so far assumed you may move anywhere. Add a constraint g(x)=0g(x) = 0 and f=0\nabla f = 0 stops being the right stopping condition, because the best point on the constraint surface is usually not flat.

The correct condition is still pure calculus. At a constrained optimum you cannot improve ff without leaving the surface, which happens exactly when the two gradients are parallel:

f(x)=λg(x)\nabla f(x) = \lambda \nabla g(x)

The multiplier λ\lambda measures how much the optimum would improve if the constraint were relaxed slightly, which makes it a price rather than a bookkeeping device. Generalising this equation to inequality constraints produces the KKT conditions and Lagrangian duality, the subject of the separate Lagrangian Duality lesson in this catalogue. The calculus you need for it is the calculus in this lesson.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. A function maps 512 inputs to 128 outputs. What shape is its Jacobian?
    • 512 x 512
    • 128 x 128
    • 128 x 512
    • 512 x 128
  2. Why is the gradient only the direction of steepest ascent in a qualified sense?
    • Steepest is measured per unit of Euclidean distance, and rescaling a parameter changes that geometry
    • Because it is an approximation that ignores second-order terms
    • Because partial derivatives only exist along the coordinate axes
    • Because it points uphill rather than downhill
  3. At a point where the gradient is exactly zero, the Hessian has both positive and negative eigenvalues. What is the point?
    • A local minimum
    • A local maximum
    • A point where the function is not differentiable
    • A saddle point: downhill in some directions and uphill in others
  4. Your loss surface has a Hessian condition number of about 1000. What does that predict?
    • Gradients will be inaccurate and need a smaller finite-difference step
    • Gradient descent needs on the order of hundreds of steps for each tenfold reduction in the loss gap
    • The optimum is a saddle point rather than a minimum
    • The Hessian cannot be symmetric
  5. Why do second-order methods for large models use Hessian-vector products instead of the Hessian?
    • Hv can be computed at about the cost of one gradient, while H itself has n squared entries and cannot be stored
    • Hv is a better approximation of curvature than H is
    • The Hessian is not symmetric for neural networks, so it cannot be inverted
    • Automatic differentiation is unable to compute second derivatives

Related lessons

Math
intermediate

The Chain Rule, and Why Depth Is Hard

A deep network is a composition, so its derivative is a product of Jacobians. This lesson builds the chain rule from one variable up to matrix form, shows that the order you multiply that product in changes the cost tenfold, and explains vanishing gradients as an arithmetic consequence rather than a mystery.

10 steps·~15 min
Math
intermediate

The Derivative Is a Local Linear Model

Machine learning uses the derivative as a search strategy, not a symbolic exercise. This lesson builds it as the best local linear approximation, derives the gradient descent update from it, and shows why estimating derivatives numerically loses half your digits and costs one function evaluation per parameter.

10 steps·~15 min
Math
advanced

Newton's method and the interior point revolution

Second derivatives buy something gradients cannot: a step shaped by curvature, immune to conditioning, converging quadratically. This lesson builds Newton's method, then layers it on a log barrier to get interior point methods, the machinery that made large constrained problems solvable with a certificate rather than a hope.

13 steps·~20 min
Math
intermediate

Gradient descent: choosing the step and knowing the rate

Gradient descent is three lines of code and a hundred years of theory. This lesson derives why a safe step size is one over the smoothness constant, why the condition number governs everything, and why acceleration reaching order one over k squared is provably the best any first-order method can do.

11 steps·~17 min