Why gradients?
Start with sections 2–4, then section 7. Return to the directional-derivative proof after you understand a gradient-descent update. An optimizer is a rule for updating the model’s adjustable numbers.
For L(a, b) = a² + 2b², the gradient at (1, 2) is [2, 8]. The first entry measures change along a while b stays fixed. The second measures change along b while a stays fixed. With step size 0.1, subtract [0.2, 0.8] to reach (0.8, 1.2). The loss falls from 9 to 3.52.
Check: why subtract the gradient?
The gradient points toward the steepest local increase under the usual Euclidean length measure. Subtracting it moves toward a local decrease when the step is small enough. A large step can still overshoot and increase the loss.
1. Motivation
Introduction
Training repeatedly asks one practical question: which small parameter change should reduce the current loss? The gradient supplies a local direction, and the model measures, updates, and checks again rather than searching every possibility.
- Learning goal
Explain why training uses local gradient information and preview the complete update cycle in this guide.
- Before you start
Functions, coordinates, basic derivatives, and the idea of a model parameter and loss.
Lesson plan
- Frame learning as changing parameters to reduce a measured loss.
- See how one local slope replaces an impractical search over all changes.
- Preview the measure, differentiate, update, and recheck cycle used throughout training.
The problem: a model has many adjustable numbers, but one loss value. We need a reliable direction for changing every number. This guide builds that direction from one-variable slopes, then proves what the gradient means.
A neural network is a parameterised function $f_\theta : \mathcal{X} \to \mathcal{Y}$ with $\theta \in \mathbb{R}^n$, where $n$ ranges from $10^5$ in a small CNN to $10^{12}$ in a frontier LLM. Training means choosing $\theta$ to minimise
$$L(\theta) = \tfrac{1}{N}\sum_{i=1}^{N}\ell\bigl(f_\theta(x_i),\,y_i\bigr).$$Because $\theta$ is high-dimensional and $L$ non-convex, we cannot solve $\nabla L(\theta)=0$ in closed form. We iterate: evaluate $L$ and its gradient, step, repeat. Every practical optimiser — SGD, Adam, Muon — is a recipe for using the gradient wisely.
2. Prerequisites Recap
Introduction
Near a smooth point, a complicated function behaves approximately like a flat tilted surface. A small move can therefore be paired with a slope vector through a dot product to predict the nearby change.
- Learning goal
Use differentiability and inner products to understand and calculate the local linear approximation behind gradient methods.
- Before you start
Functions, vectors, dot products, limits as an idea, and one-variable derivatives.
Lesson plan
- Interpret differentiability as a reliable linear prediction for sufficiently small moves.
- Review the inner product as a measure of aligned vector components.
- Combine a gradient and displacement to predict a function's local change.
Readiness check: for f(x)=x², can you calculate f(3)=9 and understand that a small change in x changes f(x)? The next sections define all multi-input notation from that starting point.
2.1 Differentiability
$f:\mathbb{R}^n\to\mathbb{R}$ is differentiable at $x$ iff there is a linear map $Df(x)$ such that $f(x+h) = f(x) + Df(x)\cdot h + o(\|h\|)$. The gradient $\nabla f(x)$ is the vector representing this map under the standard inner product: $Df(x)\cdot h = \langle \nabla f(x),\, h\rangle$.
2.2 Inner product
On $\mathbb{R}^n$, $\langle a,b\rangle = a^\top b$. Cauchy–Schwarz: $|\langle a,b\rangle|\le\|a\|\|b\|$, with equality iff $a$ and $b$ are parallel. This single inequality drives the steepest-ascent theorem in §6.
3. Partial Derivatives
Introduction
For a function of three variables, changing one input while freezing the other two gives one partial derivative. At the point 1, 2, 0, the worked function produces sensitivities 4, 1, and 1.
- Learning goal
Calculate all partial derivatives of a multivariable function and evaluate them accurately at a chosen point.
- Before you start
Single-variable derivative rules, algebraic substitution, powers, sine, and points in three-dimensional coordinates.
Lesson plan
- Freeze all but one variable and differentiate with respect to that input.
- Repeat for every variable while keeping the expression and notation organized.
- Substitute the chosen point and interpret each resulting directional sensitivity.
Predict one partial. For f(x,y)=x²+3y, hold y fixed and increase x. At x=2, the partial derivative with respect to x is 4. Holding one variable fixed is the key action.
$f(x,y,z) = x^2 y + 3yz^2 + \sin z$. Then $\partial_x f=2xy$, $\partial_y f=x^2+3z^2$, $\partial_z f=6yz+\cos z$. At $(1,2,0)$: $\nabla f = (4,\,1,\,1)$.
Existence of partials does not imply differentiability. A sufficient condition is that all partials are continuous near $x$ — such functions are $C^1$.
4. The Gradient
Introduction
At the point 2, 1, a two-input function has partial derivatives 4 and 3. Collecting them gives gradient 4, 3, a vector of length 5 that summarizes the local slope.
- Learning goal
Build a gradient from partial derivatives and read its direction, magnitude, and field across points.
- Before you start
Partial derivatives, two-dimensional vectors, vector length calculations, and reading simple coordinate plots.
Lesson plan
- Calculate one partial derivative for each input at the same point.
- Collect the values into a gradient and calculate its length.
- Use the field explorer to compare gradient vectors across the surface.
The gradient collects one partial derivative per input. For the same function at (2,1), it is [4,3]. The vector's shape matches the input shape because it gives one local sensitivity for each input coordinate.
The map $x \mapsto \nabla f(x)$ is a vector field. Two geometric facts follow from the formalism in §6: the gradient is orthogonal to level sets, and it points in the direction of steepest local increase with magnitude equal to that rate.
4.1 Gradient field explorer
The canvas below draws level curves of $f(x,y)=(x-1)^2+4(y+2)^2$ and the gradient vector field. Hover (or drag) to read off the gradient and its magnitude at any point.
Interactive · Gradient field with hover inspection
5. Directional Derivatives
Introduction
The gradient 4, 3 predicts different rates for different unit directions. Moving along the first axis gives rate 4, while moving along the normalized gradient gives the largest rate, 5.
- Learning goal
Calculate directional derivatives as vector projections and compare local rates for several chosen unit directions.
- Before you start
Gradients, dot products, vector length, unit vectors, and basic trigonometry.
Lesson plan
- Represent a chosen two-dimensional movement direction correctly as a unit vector.
- Project the gradient onto that direction using a dot product.
- Explore how rotating the direction changes the rate and reveals the maximum.
Check a direction: with gradient [4,3] and unit direction [1,0], the directional derivative is 4. Moving only along the second axis gives 3. A mixed direction combines both through a dot product.
For a unit vector $u$, the directional derivative is $D_u f(x) = \lim_{h\to 0}[f(x+hu)-f(x)]/h$. If $f$ is differentiable, $D_u f(x) = \langle \nabla f(x),\,u\rangle$.
5.1 Direction explorer
Fix a point. Rotate the direction vector $u$ and watch the rate $D_u f = \|\nabla f\|\cos\theta$ vary sinusoidally with the angle $\theta$ between $u$ and $\nabla f$. The maximum rate is $\|\nabla f\|$, achieved when $u$ points along the gradient.
Interactive · Directional derivative $D_u f$ at a fixed point
6. Steepest Ascent — A Proof
Introduction
For gradient 4, 3, no unit direction can produce a directional rate above 5. The Cauchy-Schwarz inequality proves this exact bound and shows exactly when the bound is reached.
- Learning goal
Prove why the gradient gives the steepest-ascent direction and connect that result to level-set geometry.
- Before you start
Directional derivatives, dot products, unit vectors, vector length, and inequalities.
Lesson plan
- Express every directional rate as the gradient's dot product with a unit vector.
- Apply Cauchy-Schwarz and identify the equality condition that reaches the bound.
- Use the result to explain why gradients meet level sets at right angles.
Before the proof, predict the result: among unit-length directions, the gradient direction should give the largest local increase. The proof turns this claim into a dot-product bound. Equality identifies when the bound is reached.
Among all unit vectors $u$, $D_u f(x) = \langle \nabla f(x), u\rangle$ is maximised at $u^\star = \nabla f(x)/\|\nabla f(x)\|$, with value $\|\nabla f(x)\|$. Symmetrically, steepest descent is $-u^\star$.
Proof
By Cauchy–Schwarz, $\langle \nabla f,u\rangle \le \|\nabla f\|\|u\| = \|\nabla f\|$ since $\|u\|=1$. Equality holds iff $u\parallel\nabla f$ and is a positive multiple, which forces $u = \nabla f/\|\nabla f\|$. $\square$
Corollary: orthogonality to level sets
If $\gamma(t)$ lies in $\{x: f(x)=c\}$, then $f(\gamma(t))=c$ for all $t$. Differentiating: $0 = \langle \nabla f(\gamma(t)), \gamma'(t)\rangle$. So $\nabla f$ is orthogonal to every tangent vector of the level set.
7. Gradient Descent
Introduction
For a bowl-shaped loss starting at parameter 3, a learning rate of 0.1 reduces loss from 4 to about 1.05 after three updates. Larger steps can move faster, oscillate, or diverge.
- Learning goal
Perform several gradient-descent updates and choose stable learning rates using curvature and visual trajectory evidence.
- Before you start
Gradient vectors, derivatives of quadratic functions, repeated updates, coordinate points, and basic algebra.
Lesson plan
- Calculate several one-dimensional updates and track parameter and loss values.
- Explore two-dimensional parameter trajectories where unequal curvature causes visible zig-zagging behavior.
- Derive a stable learning-rate bound and compare optimizer paths on Rosenbrock loss.
Calculate one step. If w=3, gradient is 4, and learning rate is 0.1, descent gives w=3−0.1×4=2.6. A positive gradient leads to a smaller parameter because descent moves opposite the increase direction.
The simplest optimiser: iterate
$$\boxed{\theta_{k+1} = \theta_k - \eta\,\nabla L(\theta_k)}$$where $\eta>0$ is the learning rate. A first-order Taylor expansion gives $L(\theta - \eta\nabla L) = L(\theta) - \eta\|\nabla L\|^2 + o(\eta)$, so for small $\eta$ the loss drops by approximately $\eta\|\nabla L\|^2$.
7.1 One-dimensional demo
Experiment · $L(w)=(w-1)^2$, start at $w_0=3$
Regimes: $\eta<0.5$ converges monotonically · $\eta=0.5$ converges in one step · $0.5<\eta<1.0$ oscillates with decay · $\eta\ge 1.0$ diverges. The threshold $\eta=1$ matches the theory $2/\lambda_{\max}=2/2=1$.
7.2 Two-dimensional ill-conditioned bowl
The loss $L(w,b)=(w-1)^2 + 4(b+2)^2$ has Hessian with eigenvalues $2$ and $8$, giving $\kappa=4$. The optimal step is $\eta < 2/\lambda_{\max}=0.25$. Larger $\eta$ causes the canonical zig-zag.
Experiment · trajectory on the bowl $L(w,b)=(w-1)^2+4(b+2)^2$
7.2.1 Learning-rate bound, derived
For $L(\theta)=\tfrac{1}{2}\theta^\top A\theta - b^\top\theta + c$ with $A\succ 0$, gradient descent becomes $\theta_{k+1}-\theta^\star = (I-\eta A)(\theta_k-\theta^\star)$, which converges iff $|1-\eta\lambda_i|<1$ for all eigenvalues $\lambda_i$. This forces
$$\boxed{0 < \eta < \frac{2}{\lambda_{\max}(A)}}.$$Convergence rate is $(\kappa-1)/(\kappa+1)$ per step, so $\kappa\gg 1$ means slow convergence — the motivation for adaptive and second-order methods.
7.3 Optimiser race on Rosenbrock
The Rosenbrock function $f(x,y)=(1-x)^2+100(y-x^2)^2$ has a narrow curved valley with minimum at $(1,1)$. It is the classic test for optimisers. Run them head-to-head on the same landscape.
Experiment · compare SGD, SGD+momentum, and Adam
8. Numerical Gradient Checking
Introduction
A backward pass can silently return a wrong gradient even when the loss decreases. At parameters 3 and negative 1, centered finite differences reproduce analytic gradients 4 and 8 to high precision.
- Learning goal
Check an analytic gradient numerically with centered differences and interpret both absolute and relative disagreement.
- Before you start
Derivatives, function evaluation, subtraction, small decimal values, and Python arrays.
Lesson plan
- Perturb one parameter upward and downward while holding the others fixed.
- Form a centered difference and compare it with the analytic derivative.
- Use relative error and suitable step sizes to diagnose a broken implementation.
Gradient checking asks whether two independent calculations agree: backpropagation and a small finite difference. Use it as a correctness test on a tiny deterministic case. Do not use the finite difference as the training algorithm.
Always verify analytic gradients numerically before training. The centred-difference formula has $O(\varepsilon^2)$ truncation error:
$$\frac{\partial L}{\partial \theta_i} \approx \frac{L(\theta+\varepsilon e_i)-L(\theta-\varepsilon e_i)}{2\varepsilon}.$$With $\varepsilon=10^{-5}$ and double precision, relative error should be $\sim 10^{-9}$. Anything above $10^{-5}$ is a bug.
import numpy as np
def L(w, b): return (w-1)**2 + 4*(b+2)**2
def analytic(w, b): return np.array([2*(w-1), 8*(b+2)])
def numerical(w, b, eps=1e-5):
dw = (L(w+eps, b) - L(w-eps, b)) / (2*eps)
db = (L(w, b+eps) - L(w, b-eps)) / (2*eps)
return np.array([dw, db])
a, n = analytic(3, -1), numerical(3, -1)
print(np.abs(a - n) / (np.abs(a) + 1e-12)) # ~1e-11
9. The Hessian and Conditioning
Introduction
Two directions can have different curvature even at the same point. A quadratic loss with Hessian entries 2 and 8 bends four times more strongly in one direction, affecting stability and convergence.
- Learning goal
Read a Hessian matrix, classify critical points, measure conditioning, and explain one Newton update.
- Before you start
Gradients, second derivatives, matrices, eigenvalues as directional scaling, and quadratic functions.
Lesson plan
- Differentiate the gradient to form the matrix of second partial derivatives.
- Use eigenvalue signs to classify minima, maxima, and saddle points.
- Connect unequal curvature to conditioning, learning-rate limits, and Newton's method.
Picture two curvatures. A bowl can be steep left-to-right and shallow front-to-back. One learning rate then moves too aggressively on one axis and too slowly on the other. The Hessian records this local curvature interaction.
The second-order structure of $L$ is captured by
$$H_{ij}(\theta) = \partial_i\partial_j L(\theta),\qquad L(\theta+\Delta) = L(\theta)+\langle\nabla L,\Delta\rangle+\tfrac{1}{2}\Delta^\top H\,\Delta + o(\|\Delta\|^2).$$Classifying critical points ($\nabla L=0$)
| Spectrum of $H$ | Local behaviour |
|---|---|
| All $\lambda_i>0$ | Strict local minimum |
| All $\lambda_i<0$ | Strict local maximum |
| Mixed signs | Saddle point |
| Some $\lambda_i=0$, rest same sign | Degenerate |
Newton's method
$$\theta_{k+1} = \theta_k - H(\theta_k)^{-1}\,\nabla L(\theta_k).$$Rescales each direction by its curvature; quadratic convergence near a minimum. Cost $O(n^3)$ motivates quasi-Newton (L-BFGS) and second-order preconditioners (Shampoo, Muon).
10. Backpropagation
Introduction
A simple calculation path changes an input by factor 2 and then changes loss by factor negative 3. Reverse-mode differentiation multiplies those local effects to obtain total derivative negative 6.
- Learning goal
Trace reverse-mode gradients through a computation graph and connect the process to neural-network backpropagation equations.
- Before you start
Chain rule, gradients, matrix-vector products, and basic neural-network layer notation.
Lesson plan
- Compare forward mode and reverse mode by the derivatives each one propagates.
- Read the four backpropagation equations and identify every local factor.
- Walk backward through the interactive graph while accumulating shared gradient contributions.
Trace one path: if x changes u by a factor of 2 and u changes the loss by a factor of -3, then x changes the loss by 2×(-3)=-6. Backpropagation reuses such local factors from output to input.
For a composition $L=\ell\circ f_K\circ\cdots\circ f_1(\theta)$, the chain rule gives $\nabla_\theta L = J_1^\top\cdots J_K^\top \nabla_{f_K}\ell$. Naively computing all $n$ components costs $O(n)$ forward passes. Backprop evaluates the entire gradient in one reverse pass.
10.1 Forward vs. reverse mode
| Mode | Direction | Cost | Good when |
|---|---|---|---|
| Forward | left→right | $n$ forward passes | $n\ll m$ |
| Reverse | right→left | 1 forward + 1 reverse | $m\ll n$ (always in ML) |
10.2 The four backprop equations
For $z^{(\ell)}=W^{(\ell)}a^{(\ell-1)}+b^{(\ell)}$, $a^{(\ell)}=\sigma(z^{(\ell)})$, with $\delta^{(\ell)}=\nabla_{z^{(\ell)}}L$:
$$\begin{aligned} \delta^{(L)} &= \nabla_{a^{(L)}}L \odot \sigma'(z^{(L)}) \\ \delta^{(\ell)} &= (W^{(\ell+1)})^\top \delta^{(\ell+1)} \odot \sigma'(z^{(\ell)}) \\ \nabla_{W^{(\ell)}}L &= \delta^{(\ell)}(a^{(\ell-1)})^\top \\ \nabla_{b^{(\ell)}}L &= \delta^{(\ell)}. \end{aligned}$$10.3 Computation-graph walkthrough
Trace forward and backward passes through a tiny three-operation graph. Edit $x$ and watch both values and gradients propagate. The "local grad" column is the derivative of each node with respect to its input; backprop multiplies them right-to-left.
Interactive · trace the chain rule through a small graph
| Node | Op | Value | Local grad | Upstream $\bar v$ | Gradient at node |
|---|
11. Pathologies in Deep Learning
Introduction
Multiplying many local derivatives can erase or amplify a learning signal. With sigmoid derivatives bounded by one quarter, an eight-layer network chain can shrink a unit gradient below two hundred-thousandths.
- Learning goal
Recognize vanishing gradients, exploding gradients, saddle points, and sharp-minimum behavior and connect each to practical remedies.
- Before you start
Backpropagation through layers, repeated multiplication, activation functions, gradient vectors, and the idea of curvature.
Lesson plan
- Calculate gradient decay through depth and inspect it with the interactive control.
- Contrast vanishing and exploding gradient signals and review practical stabilization methods.
- Distinguish saddle points from flat and sharp minima using local geometry.
Predict the symptom before choosing a remedy. Vanishing gradients produce tiny early-layer updates. Exploding gradients produce very large values or nan. Noisy gradients vary across batches. These failures can look similar if you inspect only the final loss.
11.1 Vanishing gradients
When each Jacobian $J_\ell$ has spectral radius $\rho(J_\ell)<1$, the chain-rule product $J_K^\top\cdots J_1^\top$ decays exponentially with depth. Early layers receive near-zero gradients. Fixes: ReLU activations, residual connections, careful initialisation (He, Xavier).
11.1.1 Interactive · gradient decay with depth
A deep chain of sigmoid units $a_{\ell+1}=\sigma(w\,a_\ell)$, with $L=a_N$. Drag the depth $N$ and weight $w$ to watch $|\partial L/\partial a_0|$ collapse. For $\sigma'(z)=\sigma(z)(1-\sigma(z))\le 1/4$, the gradient magnitude is bounded by $(|w|/4)^N$.
Interactive · $a_{\ell+1}=\sigma(w\,a_\ell)$, $L=a_N$
11.2 Exploding gradients
The dual problem ($\rho(J_\ell)>1$). Common in RNNs. Fix: gradient clipping $g \leftarrow g\cdot\min(1,\, c/\|g\|)$, typically $c=1$.
11.3 Saddle points
In high dimensions, most critical points are saddles, not minima. The loss is flat, gradients are tiny, SGD crawls. Momentum and stochasticity help escape.
11.4 Flat vs. sharp minima
Flat minima generalise better (Hochreiter & Schmidhuber, 1997). SGD's implicit bias toward them is one of the deep-learning regularisation effects.
12. Modern Optimisers
Introduction
Two optimizers can receive the same current gradient yet take different steps because they remember different history. SGD uses the present value, while momentum, RMSProp, and AdamW track running first or second moments.
- Learning goal
Compare major gradient optimizers by their stored state, update behavior, assumptions, and appropriate diagnostic questions.
- Before you start
Gradient descent, learning rates, moving averages, squared values, and parameter updates.
Lesson plan
- Start from plain SGD and identify what information one update uses.
- Add first-moment and second-moment histories to understand momentum and adaptive scaling.
- Compare AdamW and newer methods without treating any optimizer as universally best.
Optimizers change how gradients become parameter steps. They do not replace the gradient calculation. Compare methods under the same initialization, batches, and evaluation rule so a changed result has one plausible cause.
| Optimiser | Update | Notes |
|---|---|---|
| SGD | $\theta\leftarrow\theta-\eta g$ | Baseline. |
| SGD + momentum | $v\leftarrow\mu v-\eta g;\;\theta\leftarrow\theta+v$ | Damps oscillation. |
| Nesterov | Evaluate $g$ at $\theta+\mu v$. | Look-ahead momentum. |
| AdaGrad | $\theta\leftarrow\theta - \frac{\eta}{\sqrt{G+\varepsilon}}g,\; G\mathrel{+}=g^2$ | Per-parameter rate, decays. |
| RMSProp | EMA of $g^2$. | Non-stationary AdaGrad. |
| Adam | Momentum + RMSProp + bias correction. | Default for most DL. |
| AdamW | Decoupled weight decay. | LLM pre-training standard. |
| LAMB / LARS | Layer-wise scaling. | Large-batch distributed. |
| Shampoo | Precondition by $H^{-1/(2d)}$. | Approx 2nd-order at scale. |
| Muon | Polar decomposition of update. | Recent SOTA for LLMs. |
In Adam, naive $L_2$ regularisation couples into the adaptive learning rate and is not equivalent to AdamW. Use AdamW for real weight decay.
13. Gradients Beyond Supervised Training
Introduction
Gradients are not limited to fitting labels. They can change an input for an adversarial example, follow a diffusion score, improve a policy from reward, or differentiate through another learning step.
- Learning goal
Identify and explain what quantity is differentiated in four learning settings beyond ordinary supervised model training.
- Before you start
Gradients, loss functions, probability as a concept, and the basic supervised-training loop.
Lesson plan
- Follow an input gradient used to construct a fast adversarial perturbation.
- Compare score and reward gradients in diffusion and policy optimization.
- See why meta-learning may require a gradient through an earlier gradient update.
The supervised label is not required. What matters is a differentiable scalar objective. Language-model loss, reconstruction loss, and policy objectives define different goals, but each still supplies a local signal for parameters.
- Adversarial examples. FGSM perturbs inputs by $\varepsilon\cdot\text{sign}(\nabla_x L)$.
- Saliency and attribution. $\|\nabla_x L\|$ (or Integrated Gradients) identifies influential inputs.
- Diffusion models. A score network approximates $\nabla_x\log p(x)$; samples are drawn by Langevin dynamics.
- Reinforcement learning. The policy-gradient theorem: $\nabla_\theta J=\mathbb{E}[\nabla_\theta\log\pi_\theta(a|s)\,R]$.
- Meta-learning (MAML). Gradients of gradients through an inner training step.
- Natural gradient. Replace the Euclidean metric with the Fisher information: $\theta\leftarrow\theta-\eta F^{-1}\nabla L$. Basis of K-FAC.
14. References
Introduction
This reading list supports different next steps rather than one linear lesson. It groups sources for mathematical foundations, neural-network backpropagation, convex optimization, and the design and behavior of modern optimizers.
- Learning goal
Choose an appropriate source for a specific gap and understand what each reference category contributes.
- Before you start
Familiarity with the main gradient topics in this guide and a question to investigate.
Lesson plan
- Use foundation texts to strengthen derivatives, gradients, and deep-learning notation.
- Choose neural-network or convex-optimization sources for proofs and broader context.
- Read optimizer surveys and papers when comparing update rules and practical assumptions.
- Goodfellow, Bengio, Courville. Deep Learning, §4.3–4.4.
- Nielsen. Neural Networks and Deep Learning, Ch. 2.
- Boyd & Vandenberghe. Convex Optimization.
- Ruder. "An overview of gradient descent optimization algorithms." arXiv:1609.04747.
- Kingma & Ba. "Adam." arXiv:1412.6980.
- Loshchilov & Hutter. "Decoupled Weight Decay Regularization." arXiv:1711.05101.
- Jordan. "Dynamical, Symplectic and Stochastic Perspectives on Gradient-Based Optimization." ICM 2018.