Math & Machine Learning Foundations
Calculus and Optimization: Derivatives, Gradients, the Chain Rule and Gradient Descent
Intermediate 35 min For: Beginners / Researchers
Key takeaways
- ▸The gradient is the vector of partial derivatives and points in the direction of steepest increase; gradient descent updates parameters along the negative gradient, w ← w − α∇f(w), where α is the learning rate.
- ▸The chain rule writes the derivative of a composite function as a product of local derivatives. Backpropagation (Rumelhart, Hinton and Williams, 1986) uses it to compute every parameter's gradient layer by layer from the output backwards; Baydin et al. (2015) note that it is a special case of reverse-mode automatic differentiation.
- ▸On a quadratic, gradient descent converges at rate max|1−αλᵢ|, governed by the ratio of the Hessian's largest and smallest eigenvalues (the condition number κ); any learning rate above 2/λ_max diverges. Momentum improves the dependence on the same problem from κ to roughly √κ.
- ▸Stochastic gradient descent replaces the full gradient with a mini-batch gradient; it goes back to the stochastic approximation method of Robbins and Monro (1951), and Bottou et al. (2016) review its central role in large-scale machine learning.
- ▸Adam adapts each parameter's step using exponential moving averages of the gradient's first and second moments; AdamW decouples weight decay from the gradient update, and Loshchilov and Hutter (2017) show that for Adam, L2 regularisation and weight decay are not equivalent.
Overview: Training a neural network means solving an optimisation problem: finding the parameters that minimise a loss function. This lesson starts from derivatives, partial derivatives and gradients, shows how the chain rule becomes backpropagation and automatic differentiation, then analyses the learning rate and condition number of gradient descent, momentum, stochastic gradient descent, and the two mainstream optimisers Adam and AdamW. Every numerical claim comes with a runnable check.
This lesson belongs to the Calculus and Optimization unit; the prerequisite is Python and NumPy setup, and the eigenvalue section of Linear Algebra is recommended first. Continue with PyTorch autograd and the training loop and Neural Network Basics. Related algorithm cards: SGD, Backpropagation, Adam, AdamW, Weight initialisation.
Derivatives, partial derivatives and gradients
The derivative of a one-variable function, f′(x) = lim(h→0) [f(x+h) − f(x)]/h, is its rate of change at x. For a multivariable function f(x₁, …, xₙ), differentiating with respect to each variable gives the partial derivatives ∂f/∂xᵢ; stacking them gives the gradient:
∇f(x) = ( ∂f/∂x₁, …, ∂f/∂xₙ )ᵀ
The directional derivative along a unit vector u is ∇f·u = ‖∇f‖cos θ. The gradient is therefore the direction of steepest increase, and the negative gradient the direction of steepest decrease.
For example, f(x, y) = x²y + sin y has ∂f/∂x = 2xy and ∂f/∂y = x² + cos y. At (1.5, −0.7) the analytic gradient is (−2.1, 3.014842), which matches the central difference [f(x+h) − f(x−h)]/2h (see the example below). Central differences are routinely used for gradient checking of hand-written or custom derivative code.
The matrix of second derivatives, the Hessian Hᵢⱼ = ∂²f/∂xᵢ∂xⱼ, describes curvature. It is real and symmetric, and its eigenvalues determine how gradient descent converges; see the section on the condition number.
The chain rule, backpropagation and automatic differentiation
If L = g(h(w)), then dL/dw = g′(h(w))·h′(w). A neural network is a composition of many functions, and the chain rule writes the derivative of the loss with respect to any parameter as a product of local derivatives along the path.
For a single neuron L = (σ(wx+b) − t)², with z = wx + b and s = σ(z):
∂L/∂w = 2(s − t) · s(1 − s) · x
The three factors are ∂L/∂s, ∂s/∂z and ∂z/∂w respectively.
With x = 2, t = 1, w = 0.3, b = −0.1, the chain rule gives −0.354894, the same value as numerical differentiation and PyTorch autograd.
- Backpropagation: the algorithm published by Rumelhart, Hinton and Williams (1986) in Nature repeatedly adjusts connection weights to minimise the difference between the network's actual and desired outputs, and in the process hidden units come to represent important features of the task (Rumelhart et al., 1986).
- Automatic differentiation: the survey by Baydin et al. (2015) defines automatic differentiation as a family of techniques for computing derivatives of programs exactly, more general than backpropagation, which is a special case of reverse-mode AD (Baydin et al., 2015). Reverse mode's advantage is that, for a scalar loss, one backward sweep yields the gradient with respect to all parameters, at a cost of the same order as one forward evaluation.
- PyTorch autograd: the official tutorial explains that autograd records tensors and executed operations in a directed acyclic graph (DAG) of Function objects, with input tensors as leaves and outputs as roots; calling
.backward()computes gradients by the chain rule and accumulates them into each leaf tensor's.gradattribute (PyTorch tutorial). This is why training loops callzero_grad()every step.
To see the mechanism in source code, read micrograd, a scalar reverse-mode autodiff engine in about a hundred lines of Python.
Gradient descent and the learning rate
Gradient descent updates
w_{t+1} = w_t − α ∇f(w_t)
where the learning rate α sets the step size. Fitting y = 3x + 0.5 (plus a little noise) on 200 examples with mean squared error, 50 steps each, this lesson's demo measured:
| Learning rate | a after 50 steps | b after 50 steps | MSE | Behaviour |
|---|---|---|---|---|
| 0.05 | 2.5253 | 0.5451 | 0.08824 | Converging, not yet there |
| 0.5 | 2.9873 | 0.4921 | 0.01042 | Close to the true values |
| 1.2 | about −4.9×10⁶ | about −4.0×10⁷ | about 1.6×10¹⁵ | Diverges |
A learning rate that is too small converges slowly; one that is too large makes the parameters bounce across the valley with growing amplitude. The next section explains this quantitatively.
Condition number and convergence speed
Consider the quadratic f(w) = ½wᵀAw with symmetric positive definite A and eigenvalues λ₁ ≤ … ≤ λₙ. In eigenvector coordinates, gradient descent shrinks each direction independently by a factor 1 − αλᵢ, so the overall rate is
rate(α) = max{ |1 − αλ₁|, |1 − αλₙ| }
Goh (2017) derives the following in Distill (Goh, 2017):
- The optimal learning rate is α* = 2/(λ₁ + λₙ), giving rate (κ − 1)/(κ + 1), where the condition number is κ = λₙ/λ₁;
- the larger κ, the slower gradient descent; with κ = 1 it converges in one step;
- as soon as some direction has |1 − αλᵢ| > 1, i.e. α > 2/λₙ, the iteration diverges.
With λ = (1, 100), κ = 100, and 100 iterations, the demo measured:
| Learning rate α | Rate | ‖w‖ after 100 steps |
|---|---|---|
| 0.005 | 0.9950 | 0.6058 |
| 2/101 ≈ 0.0198 (optimal) | 0.9802 | 0.1914 |
| 0.0201 (just above 2/100) | 1.0100 | 2.708 (diverging) |
Even with the optimal learning rate, gradient descent is slow on an ill-conditioned problem, and a learning rate only slightly above 2/λₘₐₓ diverges.
Momentum
Momentum (the heavy-ball method, Polyak 1964) adds a "velocity" term to the update (Polyak, 1964):
z_{t+1} = β z_t + ∇f(w_t)
w_{t+1} = w_t − α z_{t+1}
Goh (2017) gives the optimal parameters on a quadratic, α = [2/(√λ₁ + √λₙ)]² and β = [(√κ − 1)/(√κ + 1)]², which improve the rate from (κ − 1)/(κ + 1) to (√κ − 1)/(√κ + 1) — described in the article as up to a quadratic speed-up. On the κ = 100 problem above, after 100 steps the demo measured ‖w‖ = 0.1914 for optimal gradient descent and 3.5×10⁻⁷ for optimal momentum.
Stochastic gradient descent
Machine-learning losses are usually averages over many examples, f(w) = (1/N)Σᵢ ℓᵢ(w). Computing the full gradient every step is too expensive, so stochastic gradient descent (SGD) uses the gradient on a mini-batch as an unbiased estimate.
Its theoretical origin is the stochastic approximation method of Robbins and Monro (1951), which iteratively finds a root when only noisy function values can be observed (Robbins & Monro, 1951). The classical convergence conditions require step sizes with Σₜ αₜ = ∞ and Σₜ αₜ² < ∞, the theoretical basis for decaying learning rates. The review by Bottou, Curtis and Nocedal (2016) argues that large-scale machine learning is a setting where the stochastic gradient method plays a central role while conventional gradient-based nonlinear optimisation techniques typically falter, and discusses two lines of improvement: reducing noise in stochastic directions and using second-order information (Bottou et al., 2016).
Adam and AdamW
Adam (Kingma and Ba, 2014) keeps, for each parameter, exponential moving averages of the gradient's first moment m and second moment v, with bias correction (Kingma & Ba, 2014):
m_t = β₁ m_{t−1} + (1 − β₁) g_t
v_t = β₂ v_{t−1} + (1 − β₂) g_t²
m̂_t = m_t / (1 − β₁ᵗ)
v̂_t = v_t / (1 − β₂ᵗ)
w_t = w_{t−1} − α · m̂_t / (√v̂_t + ε)
The paper's default hyperparameters are α = 0.001, β₁ = 0.9, β₂ = 0.999, ε = 10⁻⁸, and the abstract notes that the method is invariant to diagonal rescaling of the gradients. In this lesson's demo the two gradient components differ by a factor of 100 (0.1 and −10), yet Adam's first update is 0.001 in magnitude for both, opposite to the gradient — the step size is set by α, not by the gradient's absolute scale.
AdamW (Loshchilov and Hutter, 2017) points out that L2 regularisation and weight decay are equivalent for standard SGD (after rescaling by the learning rate) but not for adaptive methods such as Adam. They decouple weight decay from the loss-based gradient step, which makes the optimal weight-decay factor independent of the learning rate and substantially improves Adam's generalisation (Loshchilov & Hutter, 2017). PyTorch provides both Adam and AdamW in torch.optim (PyTorch documentation).
| Method | State per parameter | Main effect | Source |
|---|---|---|---|
| SGD | None | Mini-batch estimate of the full gradient | Robbins & Monro, 1951 |
| Momentum | One velocity | Counters ill-conditioning, speeds convergence | Polyak, 1964 |
| Adam | First and second moments | Per-parameter adaptive steps | Kingma & Ba, 2014 |
| AdamW | Same as Adam | Decoupled weight decay | Loshchilov & Hutter, 2017 |
Convex and non-convex losses
For a convex function every local minimum is global, and gradient descent with a suitable learning rate is guaranteed to converge; the losses of linear and logistic regression are convex. Neural-network losses are non-convex, with many local minima and saddle points. Li et al. (2017) introduce "filter normalisation" to visualise loss surfaces and compare how architectures and training parameters shape the surface and its minimisers — for instance, skip connections produce losses that are easier to train (Li et al., 2017). These are empirical findings; why non-convex optimisation works so well in deep learning remains an open research question.
Runnable example
The NumPy script below reproduces every numerical claim in this lesson (run under Python 3.13 and NumPy 2.5 with a fixed seed):
import numpy as np
rng = np.random.default_rng(0)
# 1) Partial derivatives and gradient check: f(x, y) = x^2 * y + sin(y)
f = lambda p: p[0] ** 2 * p[1] + np.sin(p[1])
grad_f = lambda p: np.array([2 * p[0] * p[1], p[0] ** 2 + np.cos(p[1])])
p, h = np.array([1.5, -0.7]), 1e-5
num = np.array([(f(p + h * e) - f(p - h * e)) / (2 * h) for e in np.eye(2)])
print("analytic =", np.round(grad_f(p), 6), " numeric =", np.round(num, 6))
# 2) Chain rule: L = (sigmoid(w*x + b) - t)^2
x, t, w, b = 2.0, 1.0, 0.3, -0.1
s = 1 / (1 + np.exp(-(w * x + b)))
print("dL/dw =", round(2 * (s - t) * s * (1 - s) * x, 6))
# 3) Gradient descent for y = a x + b with three learning rates
X = rng.uniform(-1, 1, 200); Y = 3.0 * X + 0.5 + 0.1 * rng.standard_normal(200)
for lr in (0.05, 0.5, 1.2):
a = bb = 0.0
for _ in range(50):
r = a * X + bb - Y
a, bb = a - lr * 2 * (r * X).mean(), bb - lr * 2 * r.mean()
print(f"lr={lr} a={a:.4f} b={bb:.4f} mse={((a * X + bb - Y) ** 2).mean():.4g}")
# 4) Condition number: f = 0.5 * (1 * x1^2 + 100 * x2^2)
lam = np.array([1.0, 100.0]); kappa = lam.max() / lam.min()
def run(alpha, beta=0.0, steps=100):
w_, z = np.array([1.0, 1.0]), np.zeros(2)
for _ in range(steps):
z = beta * z + lam * w_
w_ = w_ - alpha * z
return np.linalg.norm(w_)
for alpha in (0.005, 2 / (lam.min() + lam.max()), 0.0201):
print(f"alpha={alpha:.5f} rate={np.abs(1 - alpha * lam).max():.4f} |w|={run(alpha):.3e}")
# 5) Momentum with the optimal parameters from Goh (2017)
a_m = (2 / (np.sqrt(lam.min()) + np.sqrt(lam.max()))) ** 2
b_m = ((np.sqrt(kappa) - 1) / (np.sqrt(kappa) + 1)) ** 2
print(f"momentum alpha={a_m:.4f} beta={b_m:.4f} |w|={run(a_m, b_m):.3e}")
# 6) First Adam step (Kingma & Ba default hyperparameters)
g = np.array([0.1, -10.0]); b1, b2, lr, eps = 0.9, 0.999, 1e-3, 1e-8
m, v = (1 - b1) * g, (1 - b2) * g ** 2
print("Adam step =", lr * (m / (1 - b1)) / (np.sqrt(v / (1 - b2)) + eps))
Key points from the measured output: analytic and numerical gradients are both [-2.1, 3.014842]; the chain rule gives dL/dw = -0.354894; the learning-rate results are in the table above; the condition-number and momentum figures are in those two sections (optimal momentum parameters α = 0.0331, β = 0.6694); the first Adam step is [0.001, -0.001].
Checking the same chain rule with PyTorch autograd, and observing gradient accumulation (measured on PyTorch 2.x CPU):
import torch
x, t = torch.tensor(2.0), torch.tensor(1.0)
w = torch.tensor(0.3, requires_grad=True)
b = torch.tensor(-0.1, requires_grad=True)
L = (torch.sigmoid(w * x + b) - t) ** 2
L.backward()
print(w.grad.item(), b.grad.item()) # -0.354894, -0.177447
L = (torch.sigmoid(w * x + b) - t) ** 2
L.backward() # not zeroed, so gradients accumulate
print(w.grad.item()) # -0.709788
Exercises
- Unit project: write gradient descent by hand to fit y = ax + b, try at least three learning rates and plot the loss curves; use the condition-number section to explain which one diverges and why. Then standardise the input feature, rerun, and compare convergence speed.
- Read and retype micrograd, train a small multilayer perceptron with it, and check its gradients with central differences.
- In the interactive figures of Distill: Why Momentum Really Works, adjust the step size and momentum and observe when gradient descent oscillates or diverges.
- In PyTorch, train the same model with
torch.optim.SGD(with momentum),AdamandAdamW, record training and validation loss, and compare the effect of weight decay.
Suggested order of study
Start with 3Blue1Brown's Essence of Calculus for intuition about derivatives and the chain rule, and practise partial derivatives and gradients in Khan Academy Multivariable Calculus. Then read D2L sections 2.4–2.5 to put the ideas into code; for systematic study use chapters 5 (vector calculus) and 7 (continuous optimisation) of Mathematics for Machine Learning, and see D2L chapter 12 for optimiser details. Then continue with PyTorch autograd and the training loop.
FAQ
Why does the gradient point in the direction of steepest increase?
The directional derivative along a unit vector u is ∇f·u = ‖∇f‖cosθ, where θ is the angle between u and the gradient. It is largest, ‖∇f‖, at θ = 0 — along the gradient — and most negative at θ = π, which is why gradient descent steps along the negative gradient.
How should I choose the learning rate?
In theory, under a quadratic approximation the learning rate must be below 2/λ_max (λ_max being the Hessian's largest eigenvalue), and the optimum is 2/(λ_min+λ_max). In practice the Hessian is unknown, so you run a learning-rate sweep on a log scale (1e-4, 3e-4, 1e-3, …), train briefly with each, pick the value whose loss falls fastest without diverging, and combine it with warm-up and decay schedules.
Neural-network losses are non-convex. Why does gradient descent still work?
Non-convex functions can have many local minima and saddle points, and gradient descent does not guarantee a global optimum. In practice, gradient methods usually find well-generalising solutions for large networks; the visualisations of Li et al. (2017) show that architectural choices such as skip connections make the loss surface smoother and easier to train. This is an empirical observation, not a general theorem.
How does automatic differentiation differ from numerical differentiation?
Numerical differentiation approximates derivatives with (f(x+h)−f(x−h))/2h, needs two extra function evaluations per parameter and suffers from truncation and round-off error, so it is only suitable for gradient checking. Automatic differentiation records operations as the program runs and applies the chain rule exactly; in reverse mode, one backward pass yields the gradient of a scalar loss with respect to all parameters.
Why does a PyTorch training loop call zero_grad every step?
The official PyTorch tutorial explains that backward accumulates gradients into the .grad attribute of leaf tensors. Without zeroing, this step's gradient is added to the previous one. In this lesson's example, calling backward twice on the same loss changes w.grad from −0.354894 to −0.709788 — exactly doubled.