◆ AI All-in-One

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
↗ Plan a path here

Read first

Partial Derivatives and Gradients

This leads to

BackpropagationGradient Boosting: XGBoost and LightGBMLinear RegressionPolicy GradientsAdversarial Examples
The full path from zero — 3 concepts before this one
  1. Derivatives and Slopes
  2. Vectors
  3. Partial Derivatives and Gradients
  4. 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.
parameter w loss L(w) Start: w = 0 loss 9, steep slope → big step Minimum: w = 3 slope 0, loss 0 red dashes: the slope at the starting point (−6) each step: w ← w − η · dL/dw with η = 0.1 the slope flattens near the bottom, so the steps shrink on their own
Fig. 1 Gradient descent on a one-parameter loss curve. Starting high on the left, each step moves against the slope. The steps get shorter on their own as the curve flattens near the bottom.

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 ww and a loss L(w)L(w) that depends on it. The derivative dLdw\frac{dL}{dw} tells you the slope at the current ww:

  • If the slope is positive, the loss goes up as ww increases, so decrease ww.
  • If the slope is negative, the loss goes down as ww increases, so increase ww.

In both cases you move ww in the direction opposite to the sign of the slope. The update rule is:

wnew=wold−η dLdww_{\text{new}} = w_{\text{old}} - \eta \, \frac{dL}{dw}

Read it as: new value = old value minus (learning rate × slope). The Greek letter η\eta ("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 L(w)=(w−3)2L(w) = (w - 3)^2. It is a bowl with its bottom at w=3w = 3, where the loss is 0. Its derivative is dLdw=2(w−3)\frac{dL}{dw} = 2(w - 3). Start at w=0w = 0 with learning rate η=0.1\eta = 0.1.

Step ww Slope 2(w−3)2(w-3) Update −η×-\eta \times slope Loss (w−3)2(w-3)^2
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 θ=(θ1,θ2,…,θn)\boldsymbol{\theta} = (\theta_1, \theta_2, \dots, \theta_n). 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:

∇L(θ)=(∂L∂θ1,∂L∂θ2,…,∂L∂θn)\nabla L(\boldsymbol{\theta}) = \left( \frac{\partial L}{\partial \theta_1}, \frac{\partial L}{\partial \theta_2}, \dots, \frac{\partial L}{\partial \theta_n} \right)

The symbol ∇\nabla ("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:

θ←θ−η ∇L(θ)\boldsymbol{\theta} \leftarrow \boldsymbol{\theta} - \eta \, \nabla L(\boldsymbol{\theta})

The arrow ←\leftarrow 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 η = 0.01 · 10 steps About right η = 0.1 · 10 steps Too large η = 1.1 · 3 steps barely moves: w ≈ 0.55 settles near the bottom: w ≈ 2.7 0 → 6.6 → −1.3 → … each jump lands higher
Fig. 2 Three learning rates on the same loss. Too small: progress is painfully slow. About right: a steady descent to the bottom. Too large: each step overshoots further than the last, and the loss explodes.
  • Too small (e.g. η=0.001\eta = 0.001 in our example): every step is tiny. After 30 steps ww has only moved from 0 to about 0.18. Training takes forever.
  • About right (η=0.1\eta = 0.1): the steady descent in the table above.
  • Too large (η=1.1\eta = 1.1): 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 η\eta 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 ℓi\ell_i is the error on example ii and there are NN examples:

L(θ)=1N∑i=1Nℓi(θ)L(\boldsymbol{\theta}) = \frac{1}{N} \sum_{i=1}^{N} \ell_i(\boldsymbol{\theta})

The ∑\sum ("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 y=wx+by = wx + b 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

  1. In the from-scratch code, set lr = 1.5 and run it. What happens to the loss? Then try lr = 0.01. How many steps does it now need to reach a loss below 0.02?
  2. Change the data to y = -3x + 5 and confirm that gradient descent finds the new values.
  3. 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 w after each step. With lr = 1.5 the updates overshoot and grow.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. You double the learning rate and the loss starts jumping up and down, then shoots up to NaN. What is the most likely reason?

  2. Loss L(w) = (w − 3)², start at w = 0, learning rate 0.1. What is w after one step?

  3. You have 10,000 training examples and a mini-batch size of 100. How many iterations make one epoch?

  4. Why does almost everyone train with mini-batches instead of computing the exact gradient over the whole dataset?

  5. Your training loss is close to zero after many epochs. What should you check before celebrating?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Video

Neural Networks (video series)

3Blue1Brown · Beginner · Free

Gorgeous animated explanations of neural nets, gradient descent, backprop, Transformers and attention.

Course

Machine Learning Crash Course

Google · Beginner · Free

Short, practical lessons with interactive visualisations covering regression, classification, embeddings and neural nets.

Book

Dive into Deep Learning

Zhang, Lipton, Li & Smola · Intermediate · Free

An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.

Book

Understanding Deep Learning

Simon J. D. Prince · 2023 · Intermediate · Free

A modern, beautifully illustrated textbook covering everything from basics to Transformers and diffusion, with notebooks.

Book

Mathematics for Machine Learning

Deisenroth, Faisal & Ong · 2020 · Intermediate · Free

The linear algebra, calculus, probability and optimisation that ML uses, in one free book.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/math/gradient-descent.md