Skip to content
Mathematical foundations Foundation 23 min read

Derivatives and gradients

A derivative is the best linear approximation to a function near a point; a gradient is that idea for a function of millions of variables, packed into one vector that points uphill. Training a neural network is nothing more than computing the gradient of the loss and stepping the other way, billions of times.

10,000 ft

Almost all of modern AI is trained by gradient-based optimisation: define a loss that measures how wrong the model is, compute how the loss changes as each parameter changes (the gradient), and nudge every parameter downhill. This is true of linear regression (linear regression), of every deep network (backpropagation), of LLM pre-training and of RLHF (post-training). Gradients with respect to inputs, rather than parameters, explain saliency maps and adversarial examples. The next page, the chain rule and Jacobians, shows how gradients are computed efficiently through deep compositions; optimisation covers what to do with them.

2,000 ft

The derivative \(f'(x)\) is the slope of the tangent line: near \(x\), \(f(x+h)\approx f(x) + f'(x)\,h\). For a function of many variables, each partial derivative measures sensitivity to one input with the others held fixed, and the gradient \(\nabla f\) stacks them into a vector. Its dot product with any direction gives the rate of change in that direction, so it points in the direction of steepest ascent and is perpendicular to the contour lines. Gradient descent repeats \(\boldsymbol{\theta}\leftarrow\boldsymbol{\theta} - \eta\nabla L(\boldsymbol{\theta})\); the learning rate \(\eta\) must be small enough for the linear approximation to hold.

The training loop is a gradient loop
The training loop is a gradient loop. parameters θ, loss L(θ) on a batch, gradient ∇L(θ), θ ← θ − η ∇L(θ), forward pass, backward pass, repeatThe training loop is a gradient loop. parameters θ, loss L(θ) on a batch, gradient ∇L(θ), θ ← θ − η ∇L(θ), forward pass, backward pass, repeat

Ground level

The derivative as the best linear approximation

The textbook definition is a limit of slopes:

\[ f'(x) = \lim_{h\to0}\frac{f(x+h)-f(x)}{h}. \]

The more useful way to read it, the one that generalises to any number of dimensions, is that \(f'(x)\) is the number that makes

\[ f(x+h) = f(x) + f'(x)\,h + \text{(error that shrinks faster than }h). \]

Zoom in on a smooth curve and it looks like a straight line; the derivative is that line's slope. Worked example: \(f(x)=x^2\) at \(x=3\) has \(f'(3)=6\), so \(f(3.01)\approx 9 + 6(0.01) = 9.06\). The true value is \(9.0601\): the error, \(0.0001 = h^2\), is much smaller than \(h\).

(1, 1)secant, slope 2.8tangent y = 2x − 1y = x²
The secant through (1, 1) and (1.8, 3.24) has slope 2.8. As the second point slides toward (1, 1), the slope approaches 2, the slope of the tangent y = 2x − 1, which is the best straight-line approximation of x² near x = 1.

The derivatives you will actually use

Rules (each follows from the limit definition): linearity \((af+bg)' = af'+bg'\); product \((fg)' = f'g+fg'\); quotient; and the chain rule \((f\circ g)'(x) = f'(g(x))\,g'(x)\), which gets its own page because backpropagation is nothing else. The functions that appear in ML again and again:

\(f(x)\) \(f'(x)\) Where it appears
\(x^n\) \(nx^{n-1}\) squared error, polynomial features
\(e^x\) \(e^x\) softmax, likelihoods
\(\ln x\) \(1/x\) log-likelihood, cross-entropy
\(\sigma(x)=\dfrac{1}{1+e^{-x}}\) \(\sigma(x)\,(1-\sigma(x))\) logistic regression, gates in LSTMs
\(\tanh x\) \(1-\tanh^2x\) older activations, RNNs
\(\operatorname{ReLU}(x)=\max(0,x)\) \(1\) if \(x>0\), \(0\) if \(x<0\) the default hidden activation
\(\operatorname{softplus}(x)=\ln(1+e^x)\) \(\sigma(x)\) a smooth ReLU

Notice two facts with big consequences. The sigmoid's derivative is at most \(0.25\) (at \(x=0\)) and nearly zero for \(\lvert x\rvert>5\), so stacking many sigmoids multiplies many small numbers: vanishing gradients. ReLU's derivative is exactly 1 on its active side, which is a large part of why it made deep networks trainable (activations).

Not quite differentiable. \(\operatorname{ReLU}\), \(\lvert x\rvert\) and \(\max\) have kinks. At a kink there is no single tangent, but there is a set of valid "supporting" slopes (the subgradient: for ReLU at 0, anything in \([0,1]\)). Frameworks simply pick one value (PyTorch and JAX use 0 for ReLU at exactly 0), and because hitting exactly 0 has probability zero with real-valued data, it does not matter in practice.

Computing derivatives numerically

You can always approximate a derivative by a finite difference. Two formulas:

\[ \text{forward: } \frac{f(x+h)-f(x)}{h} = f'(x) + O(h), \qquad \text{central: } \frac{f(x+h)-f(x-h)}{2h} = f'(x) + O(h^2). \]

The error in the forward formula is about \(\tfrac{h}{2}f''(x)\); the central formula cancels that term (see The maths). But \(h\) cannot be made arbitrarily small, because subtracting two nearly equal floating-point numbers loses precision. For \(f=\sin\) at \(x=1\) in float64:

\(h\) forward error central error
\(10^{-1}\) \(4.3\times10^{-2}\) \(9.0\times10^{-4}\)
\(10^{-3}\) \(4.2\times10^{-4}\) \(9.0\times10^{-8}\)
\(10^{-5}\) \(4.2\times10^{-6}\) \(1.1\times10^{-11}\)
\(10^{-8}\) \(1.4\times10^{-8}\) \(3.0\times10^{-9}\)
\(10^{-11}\) \(1.2\times10^{-6}\) \(1.2\times10^{-6}\)

The error first falls (truncation error shrinks) and then rises (rounding error grows like \(\epsilon_\text{machine}/h\)). The best \(h\) is around \(10^{-8}\) for forward and \(10^{-5}\) for central differences in float64 (numerical computing). Finite differences are far too expensive to train with (one or two extra loss evaluations per parameter: 2 billion evaluations per step for a 1B-parameter model), but they are the standard way to check an analytic gradient: the gradient check.

Partial derivatives and the gradient

A loss depends on many parameters. The partial derivative \(\partial f/\partial x_i\) is the ordinary derivative in \(x_i\) with every other variable frozen. For \(f(x,y) = x^2y + 3y\):

\[ \frac{\partial f}{\partial x} = 2xy, \qquad \frac{\partial f}{\partial y} = x^2 + 3 . \]

At \((1,2)\) these are \(4\) and \(4\). The gradient collects all the partials into one vector with the same shape as the input:

\[ \nabla f(\mathbf{x}) = \left(\frac{\partial f}{\partial x_1},\dots,\frac{\partial f}{\partial x_n}\right). \]

And the linear approximation now reads \(f(\mathbf{x}+\mathbf{h})\approx f(\mathbf{x}) + \nabla f(\mathbf{x})\cdot\mathbf{h}\): the change in \(f\) is the dot product of the gradient with the step. Check at \((1,2)\) with \(\mathbf{h} = (0.01, 0.01)\): predicted change \(4(0.01)+4(0.01) = 0.08\); actual \(f(1.01, 2.01) - f(1,2) = 8.0804 - 8 = 0.0804\).

Shape rule

The gradient of a scalar with respect to a tensor has the same shape as that tensor. The gradient of the loss with respect to a \(4096\times4096\) weight matrix is a \(4096\times4096\) matrix. If your hand-derived gradient has a different shape, it is wrong (tensors).

Why the gradient points uphill

Move a small step \(t\) in a unit direction \(\mathbf{u}\). The rate of change of \(f\), the directional derivative, is

\[ D_{\mathbf{u}}f = \lim_{t\to0}\frac{f(\mathbf{x}+t\mathbf{u}) - f(\mathbf{x})}{t} = \nabla f\cdot\mathbf{u} = \lVert\nabla f\rVert\cos\theta , \]

where \(\theta\) is the angle between \(\mathbf{u}\) and the gradient (dot products). Three conclusions drop out at once:

  1. \(D_{\mathbf{u}}f\) is largest when \(\theta = 0\): the gradient is the direction of steepest ascent, and its length \(\lVert\nabla f\rVert\) is that steepest rate.
  2. It is most negative when \(\theta=180^\circ\): \(-\nabla f\) is the direction of steepest descent.
  3. It is zero when \(\theta = 90^\circ\): moving perpendicular to the gradient keeps \(f\) constant, so the gradient is perpendicular to the level sets (contour lines).
∇f = (1.2, 3.2)−∇f: steepest descentlevel set f = 1min
Contours of f(x, y) = x² + 4y². At (0.6, 0.4) the gradient (2x, 8y) = (1.2, 3.2) is perpendicular to the contour f = 1 and points across the contours, not toward the minimum. On an elongated bowl, steepest descent is not the shortest way down.

That last observation in the caption is the start of all of optimisation theory. The negative gradient is the best direction locally, but on a stretched bowl it points mostly across the valley, so gradient descent zig-zags.

Gradient descent

The algorithm is one line. Starting from some \(\boldsymbol{\theta}_0\), repeat

\[ \boldsymbol{\theta}_{t+1} = \boldsymbol{\theta}_t - \eta\,\nabla L(\boldsymbol{\theta}_t), \]

with learning rate (step size) \(\eta>0\). By the linear approximation, \(L(\boldsymbol{\theta}-\eta\nabla L)\approx L(\boldsymbol{\theta}) - \eta\lVert\nabla L\rVert^2\), a decrease, as long as \(\eta\) is small enough that the approximation holds.

Worked example: the zig-zag and the cliff. Minimise \(f(x,y) = x^2 + 10y^2\) (gradient \((2x, 20y)\)) from \((1,1)\). Each step multiplies \(x\) by \((1-2\eta)\) and \(y\) by \((1-20\eta)\).

step \(\eta=0.09\): \(x\) \(y\) \(f\) \(\eta = 0.11\): \(x\) \(y\) \(f\)
0 1.000 1.000 11.00 1.000 1.000 11.00
1 0.820 −0.800 7.07 0.780 −1.200 15.01
2 0.672 0.640 4.55 0.608 1.440 21.11
3 0.551 −0.512 2.93 0.475 −1.728 30.09
5 0.371 −0.328 1.21 0.289 −2.488 62.00

At \(\eta = 0.09\) the steep \(y\) direction overshoots and flips sign every step (factor \(-0.8\)) while the shallow \(x\) direction crawls (factor \(0.82\)). At \(\eta=0.11\) the \(y\) factor is \(-1.2\) and the iteration diverges even though \(x\) is still improving. The threshold is \(\eta < 2/20 = 0.1\), set by the steepest curvature; eigenvectors, SVD and PCA derives the general rule \(\eta<2/\lambda_{\max}\). Try it yourself:

In deep learning the loss is an average over billions of examples, so each step uses the gradient on a small random mini-batch instead: stochastic gradient descent. The mini-batch gradient is an unbiased but noisy estimate of the full gradient. Everything else (momentum, Adam, schedules, warm-up) is refinement of this loop (optimisers and schedules).

Gradients of the losses that matter

Three results worth knowing by heart (derived in The maths):

  • Squared error, linear model. \(L(\mathbf{w}) = \frac1n\lVert X\mathbf{w}-\mathbf{y}\rVert^2 \Rightarrow \nabla L = \frac2nX^\top(X\mathbf{w}-\mathbf{y})\). Setting it to zero gives the normal equations \(X^\top X\mathbf{w} = X^\top\mathbf{y}\).
  • Logistic regression (binary cross-entropy). With \(p_i = \sigma(\mathbf{x}_i\cdot\mathbf{w})\): \(\nabla L = \frac1nX^\top(\mathbf{p}-\mathbf{y})\).
  • Softmax cross-entropy. With logits \(\mathbf{z}\), probabilities \(\mathbf{p} = \operatorname{softmax}(\mathbf{z})\) and one-hot target \(\mathbf{y}\): \(\partial L/\partial\mathbf{z} = \mathbf{p}-\mathbf{y}\).

The last one is the gradient that trains every language model: for each position, push up the logit of the token that actually came next by \(1-p\) and push down every other token's logit by its probability (the language-modelling objective). "Prediction minus target" appears in all three because each is the negative log-likelihood of an exponential-family distribution with its natural link function (estimation).

Useful vector identities, all following from the definition: \(\nabla_{\mathbf{x}}(\mathbf{a}\cdot\mathbf{x}) = \mathbf{a}\); \(\nabla_{\mathbf{x}}\lVert\mathbf{x}\rVert^2 = 2\mathbf{x}\); \(\nabla_{\mathbf{x}}(\mathbf{x}^\top A\mathbf{x}) = (A+A^\top)\mathbf{x}\), which is \(2A\mathbf{x}\) for symmetric \(A\).

Second derivatives: curvature

The second derivative measures how the slope changes, i.e. curvature. The quadratic (second-order Taylor) approximation is

\[ f(\mathbf{x}+\mathbf{h}) \approx f(\mathbf{x}) + \nabla f\cdot\mathbf{h} + \tfrac12\mathbf{h}^\top H\mathbf{h}, \qquad H_{ij} = \frac{\partial^2 f}{\partial x_i\partial x_j}, \]

where \(H\) is the Hessian, a symmetric matrix (for smooth \(f\)). At a point where \(\nabla f = \mathbf{0}\) (a stationary point), the Hessian decides what you are standing on: all eigenvalues positive, a minimum; all negative, a maximum; mixed signs, a saddle. In high dimensions saddles vastly outnumber minima among the stationary points of typical non-convex losses, and the obstacle to training is more often slow progress near saddles and plateaus than getting trapped in bad local minima (Dauphin et al., 2014). A function whose Hessian is positive semi-definite everywhere is convex: every local minimum is global (optimisation). Newton's method uses the Hessian, \(\mathbf{x}\leftarrow\mathbf{x} - H^{-1}\nabla f\), but for \(n\) parameters \(H\) has \(n^2\) entries, a non-starter at \(n = 10^9\); Adam and friends are cheap diagonal stand-ins.

Gradients with respect to the input

Nothing stops you differentiating the loss with respect to the input instead of the weights. Two famous uses:

  • Saliency maps. \(\lvert\partial(\text{class score})/\partial\,\text{pixel}\rvert\) highlights the pixels the prediction is most sensitive to (Simonyan, Vedaldi and Zisserman, 2013). The first, crudest interpretability tool.
  • Adversarial examples. The fast gradient sign method perturbs an image by \(\mathbf{x}' = \mathbf{x} + \varepsilon\operatorname{sign}(\nabla_{\mathbf{x}}L)\) (Goodfellow, Shlens and Szegedy, 2014). The sign maximises the linearised loss increase under an L∞ budget (no pixel changes by more than \(\varepsilon\)): the first-order change is \(\varepsilon\sum_i\lvert\partial L/\partial x_i\rvert\), which grows with the number of input dimensions. That high-dimensional linear argument is the paper's explanation for why tiny, invisible perturbations flip predictions (robustness).

History

From fluxions to backprop

Isaac Newton (fluxions, from the 1660s) and Gottfried Wilhelm Leibniz (published 1684) independently invented calculus; Leibniz's \(dy/dx\) notation won. Augustin-Louis Cauchy put derivatives on the foundation of limits in the 1820s, and in 1847 he also proposed the method of steepest descent for solving systems of equations: the first gradient descent (Lemaréchal, "Cauchy and the gradient method"). Karl Weierstrass gave the modern ε–δ rigour. Herbert Robbins and Sutton Monro's 1951 stochastic approximation paper is the ancestor of SGD: it showed that noisy gradient estimates still converge if the step sizes shrink appropriately. Computing gradients efficiently through long compositions (reverse-mode differentiation, Linnainmaa 1970) and applying it to neural networks (Rumelhart, Hinton and Williams, 1986) is the story of the next page.

First principles

Why linear approximation is the right definition. We want a notion of "rate of change" that works for any number of inputs and outputs and composes cleanly. Slopes of secant lines do not generalise (there is no "division by a vector"), but linear approximations do: a function is differentiable at \(\mathbf{x}\) if there is a linear map \(L\) with \(f(\mathbf{x}+\mathbf{h}) = f(\mathbf{x}) + L\mathbf{h} + o(\lVert\mathbf{h}\rVert)\). For a scalar function of a vector, every linear map to \(\mathbb{R}\) is a dot product with some fixed vector, and that vector is the gradient. For a vector function, \(L\) is a matrix, the Jacobian, and the chain rule becomes matrix multiplication (next page).

Why stepping against the gradient must decrease the loss. If \(\nabla L\ne\mathbf{0}\), then \(L(\boldsymbol{\theta}-\eta\nabla L) = L(\boldsymbol{\theta}) - \eta\lVert\nabla L\rVert^2 + o(\eta)\). For small enough \(\eta>0\) the negative middle term dominates the remainder. So gradient descent makes progress whenever it is not at a stationary point. How small is "small enough" depends on curvature, which the descent lemma below quantifies.

Why the gradient, and not some other direction? Among all steps of a fixed small length, the one that decreases the linearised loss the most is \(-\nabla L/\lVert\nabla L\rVert\) (Cauchy–Schwarz). But "fixed length" is measured in the Euclidean norm. Measure step length differently, say by how much the model's predictions change (natural gradient) or by the L∞ norm (giving sign-based updates, as in FGSM and, roughly, Adam's early steps), and the steepest direction changes. Gradient descent is steepest descent under one particular geometry, and much of optimiser design is choosing a better geometry.

What breaks without differentiability? Gradient descent needs a slope to follow. Losses that are piecewise constant, such as accuracy or the number of correct tokens, have zero gradient almost everywhere. That is why we train on smooth surrogates (cross-entropy) while reporting the metric we care about, and why non-differentiable objectives (human preference, a game outcome) need tricks such as the log-derivative estimator of reinforcement learning (policy gradients).

The maths

Definitions. For \(f:\mathbb{R}^n\to\mathbb{R}\): \(\dfrac{\partial f}{\partial x_i}(\mathbf{x}) = \lim_{h\to0}\dfrac{f(\mathbf{x}+h\mathbf{e}_i)-f(\mathbf{x})}{h}\); \(\nabla f = (\partial_1f,\dots,\partial_nf)\); \(D_{\mathbf{u}}f = \nabla f\cdot\mathbf{u}\) (for differentiable \(f\)); Hessian \(H_{ij} = \partial_i\partial_jf\).

Derivation: why central differences are O(h²)

Taylor-expand around \(x\):

\[ f(x\pm h) = f(x) \pm hf'(x) + \tfrac{h^2}{2}f''(x) \pm \tfrac{h^3}{6}f'''(x) + O(h^4). \]

Forward: \(\dfrac{f(x+h)-f(x)}{h} = f'(x) + \tfrac h2f''(x) + O(h^2)\), error \(O(h)\). Central: subtracting the two expansions cancels the even terms, \(\dfrac{f(x+h)-f(x-h)}{2h} = f'(x) + \tfrac{h^2}{6}f'''(x) + O(h^4)\), error \(O(h^2)\). With \(f=\sin\), \(x=1\), \(h=10^{-3}\): predicted central error \(\tfrac{10^{-6}}{6}\lvert\cos 1\rvert\approx 9.0\times10^{-8}\), exactly what the table shows. Rounding adds roughly \(\epsilon/h\) with \(\epsilon\approx 10^{-16}\), which wins once \(h\) is tiny.

Derivation: the descent lemma and the 2/L learning-rate limit

Say \(\nabla L\) is \(\beta\)-Lipschitz ("\(\beta\)-smooth": \(\lVert\nabla L(\mathbf{a})-\nabla L(\mathbf{b})\rVert\le\beta\lVert\mathbf{a}-\mathbf{b}\rVert\); for twice-differentiable \(L\) this means every Hessian eigenvalue has magnitude at most \(\beta\)). Then for any step \(\mathbf{d}\),

\[ L(\boldsymbol{\theta}+\mathbf{d}) \le L(\boldsymbol{\theta}) + \nabla L\cdot\mathbf{d} + \tfrac\beta2\lVert\mathbf{d}\rVert^2 . \]

Put \(\mathbf{d} = -\eta\nabla L\):

\[ L(\boldsymbol{\theta}-\eta\nabla L) \le L(\boldsymbol{\theta}) - \eta\left(1 - \tfrac{\beta\eta}{2}\right)\lVert\nabla L\rVert^2 . \]

The bracket is positive for \(0<\eta<2/\beta\), so the loss is guaranteed to decrease; the guaranteed decrease is largest at \(\eta = 1/\beta\). In the worked example \(\beta = 20\) (the largest curvature of \(x^2+10y^2\)), so the limit is \(\eta<0.1\), matching the divergence at \(0.11\).

Derivation: the gradient of softmax cross-entropy is p − y

Let \(p_k = e^{z_k}/\sum_j e^{z_j}\) and \(L = -\sum_k y_k\ln p_k\) with \(\sum_ky_k = 1\). Since \(\ln p_k = z_k - \ln\sum_je^{z_j}\),

\[ L = -\sum_k y_kz_k + \Big(\sum_ky_k\Big)\ln\sum_je^{z_j} = -\sum_ky_kz_k + \ln\sum_je^{z_j}. \]

Differentiate with respect to \(z_i\): the first term gives \(-y_i\); the second gives \(e^{z_i}/\sum_je^{z_j} = p_i\). So \(\partial L/\partial z_i = p_i - y_i\). The binary case with \(p = \sigma(z)\) gives \(p - y\) in the same way, and the chain rule through \(z = \mathbf{x}\cdot\mathbf{w}\) multiplies by \(\mathbf{x}\), giving \(\nabla_{\mathbf{w}}L = (p-y)\,\mathbf{x}\).

Derivation: the gradient of a quadratic form

\(f(\mathbf{x}) = \mathbf{x}^\top A\mathbf{x} = \sum_{i,j}x_iA_{ij}x_j\). Then \(\partial f/\partial x_k = \sum_jA_{kj}x_j + \sum_ix_iA_{ik} = (A\mathbf{x})_k + (A^\top\mathbf{x})_k\), so \(\nabla f = (A+A^\top)\mathbf{x}\). With \(f = \lVert X\mathbf{w}-\mathbf{y}\rVert^2 = \mathbf{w}^\top X^\top X\mathbf{w} - 2\mathbf{y}^\top X\mathbf{w} + \mathbf{y}^\top\mathbf{y}\), this gives \(\nabla f = 2X^\top X\mathbf{w} - 2X^\top\mathbf{y} = 2X^\top(X\mathbf{w}-\mathbf{y})\).

Build it

NumPy: finite-difference accuracy, a gradient check for logistic regression, and plain gradient descent.

import numpy as np
rng = np.random.default_rng(0)

# 1. Forward vs central differences on f(x) = sin(x) at x = 1 (exact f' = cos 1)
f, x0, exact = np.sin, 1.0, np.cos(1.0)
print(" h        forward err   central err")
for h in [1e-1, 1e-3, 1e-5, 1e-8, 1e-11]:
    fwd = (f(x0 + h) - f(x0)) / h
    cen = (f(x0 + h) - f(x0 - h)) / (2 * h)
    print(f"{h:7.0e}   {abs(fwd - exact):10.2e}   {abs(cen - exact):10.2e}")

# 2. Logistic-regression loss: analytic gradient vs numerical gradient check
X = rng.standard_normal((100, 3))
y = (X @ np.array([2.0, -1.0, 0.5]) + 0.3 * rng.standard_normal(100) > 0).astype(float)

def loss(w):
    p = 1 / (1 + np.exp(-(X @ w)))
    return -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))

def grad(w):
    p = 1 / (1 + np.exp(-(X @ w)))
    return X.T @ (p - y) / len(y)                      # the famous (p - y)

w = np.array([0.1, 0.2, -0.3])
num = np.array([(loss(w + e) - loss(w - e)) / 2e-5 for e in 1e-5 * np.eye(3)])
print("analytic :", grad(w).round(6))
print("numerical:", num.round(6), " rel. error:", f"{np.linalg.norm(num - grad(w)) / np.linalg.norm(num):.1e}")

# 3. Gradient descent on that loss
for step in range(201):
    if step % 50 == 0:
        print(f"step {step:3d}  loss {loss(w):.4f}  w {w.round(3)}  |grad| {np.linalg.norm(grad(w)):.4f}")
    w -= 1.0 * grad(w)                                  # learning rate 1.0

Output:

 h        forward err   central err
  1e-01     4.29e-02     9.00e-04
  1e-03     4.21e-04     9.01e-08
  1e-05     4.21e-06     1.11e-11
  1e-08     1.41e-08     2.97e-09
  1e-11     1.17e-06     1.17e-06
analytic : [-0.357421  0.226353 -0.132642]
numerical: [-0.357421  0.226353 -0.132642]  rel. error: 4.4e-11
step   0  loss 0.7272  w [ 0.1  0.2 -0.3]  |grad| 0.4434
step  50  loss 0.1270  w [ 3.441 -2.002  0.805]  |grad| 0.0316
step 100  loss 0.0976  w [ 4.444 -2.607  1.069]  |grad| 0.0187
step 150  loss 0.0848  w [ 5.116 -2.997  1.249]  |grad| 0.0137
step 200  loss 0.0774  w [ 5.633 -3.29   1.39 ]  |grad| 0.0109

Two things to notice. The gradient check agrees to a relative error of \(4\times10^{-11}\); anything below about \(10^{-6}\) in float64 means the analytic gradient is right. And the weights keep growing while the loss creeps down: the data are almost linearly separable, so scaling \(\mathbf{w}\) up keeps making the predictions more confident and the loss smaller. The direction \((5.63, -3.29, 1.39)\), normalised, is already close to the true \((2, -1, 0.5)\) up to scale, but without regularisation the norm never settles. That is one reason to add weight decay (regularisation).

Things to try

  • Repeat the finite-difference table in float32 (np.float32). Where is the best \(h\) now? (Hint: \(\epsilon_{32}\approx1.2\times10^{-7}\).)
  • Implement a gradient check for the softmax cross-entropy gradient \(\mathbf{p}-\mathbf{y}\) with 5 classes.
  • Run gradient descent on \(x^2+10y^2\) with \(\eta\) = 0.05, 0.09, 0.099 and 0.101 and plot the paths. Then add momentum (\(\mathbf{v}\leftarrow\mu\mathbf{v} - \eta\nabla f\), \(\mathbf{x}\leftarrow\mathbf{x}+\mathbf{v}\)) with \(\mu=0.9\).
  • On the logistic model, perturb one input by \(\varepsilon\operatorname{sign}(\nabla_{\mathbf{x}}L)\) with \(\varepsilon = 0.1, 0.3, 1\) and watch its predicted probability change: a one-example FGSM.
  • Add an L2 penalty \(\tfrac\lambda2\lVert\mathbf{w}\rVert^2\) (gradient \(\lambda\mathbf{w}\)) with \(\lambda=0.01\) and confirm the weights now converge.

Common misconceptions

  • "The negative gradient points at the minimum." It points in the locally steepest direction, perpendicular to the contours. On an elongated bowl that can be almost at right angles to the direction of the minimum.
  • "A zero gradient means you found a minimum." It could be a maximum or, far more often in high dimensions, a saddle point.
  • "Smaller learning rates are always safer." They are more stable, but too small wastes compute and can leave you stuck on plateaus; schedules exist because the best step size changes during training.
  • "Numerical gradients are exact if h is tiny enough." Rounding error grows as \(h\) shrinks; there is an optimal \(h\).

Check yourself

Compute ∇f for f(x, y) = e^{xy} + y² at (0, 1).

\(\partial f/\partial x = ye^{xy} = 1\); \(\partial f/\partial y = xe^{xy}+2y = 2\). So \(\nabla f(0,1) = (1, 2)\).

In which unit direction does f(x, y) = 3x − 4y increase fastest, and at what rate?

\(\nabla f = (3,-4)\), so the direction is \((3,-4)/5 = (0.6, -0.8)\) and the rate is \(\lVert\nabla f\rVert = 5\).

Show that σ'(x) = σ(x)(1 − σ(x)), and give its maximum value.

\(\sigma = (1+e^{-x})^{-1}\), so \(\sigma' = e^{-x}(1+e^{-x})^{-2} = \sigma\cdot\dfrac{e^{-x}}{1+e^{-x}} = \sigma(1-\sigma)\). It is maximised at \(\sigma = 1/2\) (\(x=0\)), value \(1/4\).

For logits z = (2, 1, 0) and target class 0, what is the gradient of the cross-entropy with respect to z?

\(\operatorname{softmax}(2,1,0) = (e^2, e, 1)/(e^2+e+1)\approx(0.665, 0.245, 0.090)\). Gradient \(\mathbf{p}-\mathbf{y}\approx(-0.335, 0.245, 0.090)\): raise the correct logit, lower the others in proportion to their probabilities. The components sum to zero.

A loss has Hessian eigenvalues between 0.5 and 50 everywhere. What learning rates guarantee descent, and which is the 'safest-fastest' choice from the descent lemma?

\(\beta = 50\), so any \(\eta<2/50 = 0.04\) guarantees decrease; \(\eta = 1/\beta = 0.02\) maximises the guaranteed decrease per step.

Why is finite differencing useless for training a 1-billion-parameter model but valuable for testing it?

Each partial derivative needs one or two extra full loss evaluations, so a single gradient would need \(10^9\)–\(2\times10^9\) forward passes, versus about three forward-pass costs for backprop. For testing you only check a handful of random coordinates or random directions, which is cheap and catches wrong analytic gradients.

Hard: explain, with the dot product, why FGSM's perturbation becomes more effective as the input dimension grows.

For a linearised loss the change is \(\nabla_{\mathbf{x}}L\cdot\boldsymbol{\delta}\). Under \(\lVert\boldsymbol{\delta}\rVert_\infty\le\varepsilon\) the maximum is at \(\boldsymbol{\delta} = \varepsilon\operatorname{sign}(\nabla_{\mathbf{x}}L)\) and equals \(\varepsilon\lVert\nabla_{\mathbf{x}}L\rVert_1\). If the typical gradient component has magnitude \(m\), this is about \(\varepsilon\,m\,n\) for \(n\) inputs: it grows linearly with dimension while each pixel's change stays invisible. That is Goodfellow et al.'s linearity explanation.

Go deeper

Papers

Videos and lectures

Articles and blog posts

Courses and books

Where this leads