Level 3 In-Depth AI · Math Foundations
Gradient Descent
The algorithm that trains almost every AI model. Measure which way is downhill on the error, take a small step that way, and repeat millions of times.
- Level
- ●●●●● Easy
- Reading
- 13 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 3 concepts →
- Quiz
- 5 questions ↓
Read first
Partial Derivatives and GradientsThe full path from zero — 3 concepts before this one
- Derivatives and Slopes
- Vectors
- Partial Derivatives and Gradients
- Gradient Descent
Read them roughly in this order. See it on the concept map →
Why it matters
Every model in this guide has parameters: adjustable numbers, sometimes a handful and sometimes hundreds of billions. Training a model means finding the values of those numbers that make its predictions as good as possible. "As good as possible" is measured by a loss, a single number that says how wrong the model currently is. Higher loss means worse predictions.
So training is a search problem: find the parameters that make the loss smallest. For a model with a billion parameters you cannot try every combination. There are more combinations than atoms in the universe. You need a method that improves the parameters a little at a time, using only local information about where you are now.
That method is gradient descent. It fits a straight line through data points, and in essentially the same way it trains the neural networks behind image recognition, speech recognition and ChatGPT-style language models. Its improved forms, such as Adam, are still gradient descent at heart. If you understand this chapter you understand the engine of modern AI. Everything after it is about choosing what to optimise and computing the slopes efficiently (Backpropagation).
The intuition
Imagine you are standing on a hillside in thick fog. You want to reach the bottom of the valley, but you can only see the ground right around your feet. What do you do?
You feel the slope under your feet, find which direction goes down most steeply, and take a step that way. Then you feel the slope again and take another step. Step by step you walk downhill, and eventually you reach a point where the ground is flat in every direction. That is the bottom of a valley.
That is the whole algorithm. In machine learning:
- Your position is the current values of the model's parameters.
- Your height is the loss: how wrong the model is with those parameters.
- The landscape — every possible position and its height — is called the loss landscape.
- The slope under your feet is the gradient. The gradient points uphill, so you step the opposite way.
- The length of each step is the learning rate.
Notice something useful in the picture. You take big steps where the slope is steep and small steps where it is gentle, even though the learning rate never changes. That happens because each step is the learning rate times the slope. As you approach the bottom the slope shrinks towards zero, and so do your steps. You settle in without overshooting, provided the learning rate is sensible.
Key idea Gradient descent repeats one move: compute the slope of the loss, take a small step downhill, repeat. Training a neural network means doing this millions of times on billions of parameters.
How it works
One parameter
Start with the simplest case: a model with a single parameter and a loss that depends on it. The derivative tells you the slope at the current :
- If the slope is positive, the loss goes up as increases, so decrease .
- If the slope is negative, the loss goes down as increases, so increase .
In both cases you move in the direction opposite to the sign of the slope. The update rule is:
Read it as: new value = old value minus (learning rate × slope). The Greek letter ("eta") is the learning rate, a small positive number such as 0.1 or 0.001 that you choose.
A worked example by hand
Take the loss . It is a bowl with its bottom at , where the loss is 0. Its derivative is . Start at with learning rate .
| Step | Slope | Update slope | Loss | |
|---|---|---|---|---|
| 0 | 0.000 | −6.000 | +0.600 | 9.000 |
| 1 | 0.600 | −4.800 | +0.480 | 5.760 |
| 2 | 1.080 | −3.840 | +0.384 | 3.686 |
| 3 | 1.464 | −3.072 | +0.307 | 2.359 |
| 10 | 2.678 | −0.644 | +0.064 | 0.104 |
| 30 | 2.996 | −0.007 | +0.001 | 0.00001 |
Each step closes 20% of the remaining distance to 3, so the loss shrinks fast at first and then ever more slowly. You never land exactly on 3, but after 30 steps you are within 0.004. That is close enough. In practice you stop when the loss stops improving. This is called convergence.
Many parameters: the gradient
Real models have many parameters, collected into a vector . The loss now depends on all of them, and the slope has a direction as well as a size. The gradient collects the partial derivative with respect to each parameter:
The symbol ("nabla" or "del") means "the gradient of". Each component says how much the loss would change if you nudged that one parameter. Together they point in the direction of steepest ascent. So the update for every parameter at once is the same rule as before, written for vectors:
The arrow means "replace with". Each parameter moves by minus the learning rate times its own partial derivative. Parameters that strongly affect the loss move a lot, and parameters that barely matter hardly move.
The learning rate is the most important knob
The learning rate decides whether training works at all.
- Too small (e.g. in our example): every step is tiny. After 30 steps has only moved from 0 to about 0.18. Training takes forever.
- About right (): the steady descent in the table above.
- Too large (): the first step jumps from 0 to 6.6, right past the bottom at 3 and higher up the other side (loss 12.96, up from 9). The next step jumps back to −1.32, even further out. The loss grows without limit. This is divergence. In real training it shows up as a loss that suddenly shoots up or becomes
NaN(not a number).
For our bowl, any between 0 and 1 converges, and anything above 1 diverges. Real loss landscapes have no such tidy formula, so practitioners try a few values spaced by factors of about 3 or 10 (0.1, 0.03, 0.01, 0.003…) and keep the largest one that trains stably. Many training runs also change the learning rate over time. Learning Rate Schedules covers that.
Stochastic and mini-batch gradient descent
In machine learning the loss is an average over the training examples. If is the error on example and there are examples:
The ("sigma") means "add up". Computing the exact gradient means running the model on every training example before taking a single step. With a million images, or a trillion words of text, that is far too slow.
The fix is simple and surprisingly powerful: estimate the gradient from a small random sample.
- Stochastic gradient descent (SGD) uses one random example per step. Each step is cheap but noisy.
- Mini-batch gradient descent uses a small random batch, typically 32 to a few thousand examples. This is what everyone actually does. The word "SGD" is used loosely for it too.
One full pass through the training data is called an epoch. Each update is one iteration or step.
The noisy gradient points roughly downhill rather than exactly downhill, so the path zig-zags. The noise turns out to be useful as well as cheap. It helps the parameters jiggle out of shallow dips and flat regions, and it seems to steer training towards solutions that generalise better to new data.
Valleys, plateaus and saddle points
A bowl has one bottom. Real loss landscapes, especially for neural networks, are rugged, with many dips, ridges and flat stretches.
- A local minimum is a dip that is lower than everything nearby but not the lowest point overall (the global minimum). Gradient descent can get stuck in one, because the slope there is zero.
- A saddle point is flat but curves up in some directions and down in others, like the middle of a horse's saddle. In high dimensions these are far more common than true local minima.
- A plateau is a large, nearly flat region where the gradient is tiny and progress crawls.
It might seem that local minima would make training hopeless. In practice, for large neural networks, they rarely matter. With millions of dimensions there is almost always some direction that still leads down, and the many low points that training finds tend to be about equally good. Saddle points and plateaus cause more trouble, and the momentum-based optimizers are designed partly to roll through them.
In code
Here is gradient descent from scratch, fitting a straight line to data. The loss is the mean squared error, and we work out its gradient by hand (the Linear Regression chapter derives it).
import numpy as np
# Data: y = 2x + 1, plus noise
rng = np.random.default_rng(0)
x = rng.uniform(-1, 1, size=100)
y = 2 * x + 1 + rng.normal(0, 0.1, size=100)
w, b = 0.0, 0.0 # parameters, start anywhere
lr = 0.1 # learning rate (eta)
for step in range(201):
pred = w * x + b
error = pred - y
loss = np.mean(error ** 2) # mean squared error
dw = 2 * np.mean(error * x) # dL/dw
db = 2 * np.mean(error) # dL/db
w -= lr * dw # step downhill
b -= lr * db
if step % 50 == 0:
print(f"step {step:3d} loss {loss:.4f} w {w:.3f} b {b:.3f}")
# step 0 loss 2.8745 w 0.169 b 0.237
# step 50 loss 0.0101 w 1.955 b 0.999
# ...
# step 200 loss 0.0094 w 1.993 b 0.993 <- close to the true 2 and 1
In PyTorch you don't derive gradients by hand. The library computes them for you with Backpropagation, and an optimizer object applies the update rule:
import torch
x = torch.rand(100) * 2 - 1
y = 2 * x + 1 + 0.1 * torch.randn(100)
w = torch.zeros(1, requires_grad=True)
b = torch.zeros(1, requires_grad=True)
opt = torch.optim.SGD([w, b], lr=0.1)
for step in range(200):
loss = ((w * x + b - y) ** 2).mean()
opt.zero_grad() # clear old gradients
loss.backward() # compute dL/dw and dL/db
opt.step() # w -= lr * w.grad, b -= lr * b.grad
print(w.item(), b.item()) # about 2.0 and 1.0
Those last four lines — compute loss, zero gradients, backward, step — are the heart of every PyTorch training loop you will ever see, including the ones that train large language models.
Common pitfalls
- Loss goes up or becomes NaN. The learning rate is almost always too high. Divide it by 10 and try again.
- Loss decreases painfully slowly. The learning rate may be too low, or your inputs may be on very different scales. A feature measured in millions next to one measured in fractions makes the landscape a long, thin ravine, and gradient descent zig-zags across it instead of travelling along it. Standardise your inputs (subtract the mean, divide by the standard deviation).
- Forgetting to reset gradients. In PyTorch, gradients accumulate by default. Without
opt.zero_grad()each step uses the sum of all previous gradients, and training goes haywire. - Judging progress from one noisy batch. Mini-batch losses jump around. Look at a smoothed average, or at the loss on a fixed validation set.
- Expecting the global minimum. For anything beyond simple convex problems, gradient descent finds a good solution, not the best one. That is usually fine.
Watch out A low training loss doesn't mean a good model. Gradient descent will happily drive the loss to almost zero by memorising the training data. Always check performance on data the model never trained on. See Overfitting and the Bias–Variance Tradeoff.
Where it leads
Plain gradient descent is the foundation, and many improvements are built on it:
- Momentum keeps a running average of past gradients, like a heavy ball rolling downhill. It speeds through ravines and past small bumps.
- Adam and AdamW also give each parameter its own adaptive step size. Adam is the default optimizer for most neural networks today. See Optimizers: SGD, Momentum and Adam.
- Learning-rate schedules warm up gently and then decay the learning rate. See Learning Rate Schedules.
- Backpropagation is the efficient way to compute the gradient of a neural network's loss with respect to every weight in one backward pass. It is what makes gradient descent practical for deep networks. See Backpropagation.
Gradient descent is used directly in Linear Regression, Logistic Regression, Neural Networks and Gradient Boosting: XGBoost and LightGBM (which does gradient descent in a cleverer space), and indirectly in nearly everything else.
A bit of history
The idea goes back to the French mathematician Augustin-Louis Cauchy, who described the method of steepest descent in 1847 for solving systems of equations in astronomy. Stochastic approximation, the idea behind SGD, was introduced by Herbert Robbins and Sutton Monro in 1951. In the late 1950s, Frank Rosenblatt's The Perceptron learned with a closely related error-correction rule.
The method became central to AI in 1986, when Rumelhart, Hinton and Williams popularised Backpropagation for computing gradients in multi-layer networks. After that, training a neural network simply meant running gradient descent. In 2014, Kingma and Ba published Adam, which became the standard optimizer for deep learning. Today's largest language models are trained with variants of Adam running mini-batch gradient descent on thousands of GPUs for months. The core is still an idea nearly 180 years old: feel the slope, step downhill.
Try it
- In the from-scratch code, set
lr = 1.5and run it. What happens to the loss? Then trylr = 0.01. How many steps does it now need to reach a loss below 0.02?- Change the data to
y = -3x + 5and confirm that gradient descent finds the new values.- Harder: modify the loop to use mini-batches of 10 random examples per step instead of all 100. Plot the loss per step. Why is the curve noisier?
Hint for 1: compare the size of
wafter each step. Withlr = 1.5the updates overshoot and grow.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Neural Networks (video series)
Gorgeous animated explanations of neural nets, gradient descent, backprop, Transformers and attention.
Machine Learning Crash Course
Short, practical lessons with interactive visualisations covering regression, classification, embeddings and neural nets.
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
Understanding Deep Learning
A modern, beautifully illustrated textbook covering everything from basics to Transformers and diffusion, with notebooks.
Mathematics for Machine Learning
The linear algebra, calculus, probability and optimisation that ML uses, in one free book.
Adam: A Method for Stochastic Optimization
The Adam optimiser, still the default for training most neural networks.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/math/gradient-descent.md