Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsOptimization

Gradient descent

P1.F325 min●○○ BeginnerReviewed Nov 30, 2026

Why this matters for machine learning

Gradient descent is how neural networks learn. Training a model, from a tiny classifier to a large language model, means running this algorithm (or a close relative) millions of times.

  • Every training loop you will write takes an optimizer step, gradient descent or a variant of it, after each batch of data. (P2.7: The PyTorch training loop, coming soon)
  • Backpropagation exists to compute the gradients that gradient descent needs. (P4.8: Backpropagation: step by step with numbers)
  • Adam and its variants such as AdamW, the optimizers used to train most modern networks, are gradient descent plus momentum and a separate step size for each parameter. (P4.13: Optimizers, coming soon)
  • Choosing the learning rate, the topic of this lesson, is one of the most important decisions when training any model, including LLMs. (P4.14: Learning-rate schedules, coming soon)

Before this: Rates of change and the derivative, What is optimization?

After this lesson you can

  • State the gradient-descent update rule and explain the minus sign
  • Run a few steps of gradient descent by hand
  • Predict what happens when the learning rate is too small, about right, or too big
  • Explain why gradient descent can end up in a valley that isn't the lowest one
  • Say what the loss is a function of, and what one step does to every parameter
  • Pick a learning rate by trying values about 10 times apart and reading the loss curve

Imagine you’re on a mountainside at night in thick fog, and you want to get down to the valley. You can’t see the valley. All you can feel is the slope of the ground under your feet.

A sensible plan: feel which way is downhill, take a step that way, and repeat. That’s gradient descent. It’s the algorithm that trains nearly every neural network, and it fits in one line.

The rule

We want to find the input xx that makes a function f(x)f(x) as small as possible. In machine learning, ff is the loss: a number that says how wrong the model is. Start anywhere, then repeat:

xnew=x−η⋅f′(x)x_{\text{new}} = x - \eta \cdot f'(x)
  • f′(x)f'(x) is the slope at the current point (its derivative).
  • η\eta (the Greek letter “eta”) is the learning rate: it scales the step. The step itself is η×\eta \times slope, so steep ground gives a long step and flat ground gives a short one.
  • The minus sign makes you go downhill. If the slope is positive, the function rises to the right, so you move left. If it’s negative, you move right.

What is xx here?

In the widget below, xx is a parameter: a number the model can change, such as a weight. The loss is a function of the parameters. The data is fixed. Training does not change the data; it searches for the parameter values that make the loss small on that data. With one parameter the loss is a curve, like the one in the widget. A real model has millions of parameters, but the idea is the same. You’ll see a concrete example with real data further down.

Worked example

Take f(x)=x2f(x) = x^2, whose lowest point is at x=0x = 0. Its slope is f′(x)=2xf'(x) = 2x. Start at x=3x = 3 with η=0.1\eta = 0.1:

stepxxslope f′(x)=2xf'(x) = 2xchange =−0.1×= -0.1 \times slopenew xx
136−0.62.4
22.44.8−0.481.92
31.923.84−0.3841.536

Each step moves closer to 0, and the steps get smaller on their own, because the slope shrinks as you approach the bottom. Nobody has to tell the algorithm to slow down. (Here each step multiplies xx by 0.8.)

−3−2−101230246810xf(x)

Press Step to take one gradient-descent step, or Play to keep going.

Try:
step 0
x = 3
f(x) = 9
slope f′(x) = 6
next step = −η·f′(x) = −0.1 × 6 = −0.6

Loss curve: f(x) after each step

024681005step

Drag the ball to choose a different starting point.

The orange line is the slope at the ball's position; the orange arrow along the bottom is the step that will be taken next. Press Step a few times, then change the learning rate.
Go deeper Why is the negative gradient the best direction to move?

Near a point, a smooth function looks like a straight line: f(x+δ)≈f(x)+f′(x) δf(x + \delta) \approx f(x) + f'(x)\,\delta. Choose δ=−ηf′(x)\delta = -\eta f'(x) and the change in ff is about −η f′(x)2-\eta\,f'(x)^2. That is never positive, so for a small enough η\eta the function goes down (unless the slope is exactly zero).

With many parameters, the change in LL for a small move in a unit direction u\mathbf{u} is ∇L⋅u=∥∇L∥cos⁡θ\nabla L \cdot \mathbf{u} = \lVert\nabla L\rVert \cos\theta, where θ\theta is the angle between u\mathbf{u} and the gradient. This is smallest (most negative) when θ=180∘\theta = 180^\circ, so −∇L-\nabla L is the direction of steepest descent. Example: at a point where the gradient is (2,20)(2, 20), moving along −∇L-\nabla L lowers LL at a rate of about 20.1 per unit distance. Moving straight left, (−1,0)(-1, 0), lowers it at only 2. This is the “gradient points uphill” fact, and P1.C5 gives the angle argument behind it; P1.C6 looks at the slope in any direction.

“Steepest” is measured for a tiny move. It does not promise the best big step.

The learning rate decides everything

Try the three learning-rate buttons in the widget on the bowl f(x)=x2f(x) = x^2, starting at x=3x = 3. Each row below was checked against the widget’s own rules: it declares “converged” when the next step is smaller than 0.00010.0001, “diverged” when ∣x∣|x| passes 50, and it stops after 60 steps.

learning rate η\etawhat happens
0.02 (too small)Creeps toward the bottom. After 60 steps it is still at x≈0.26x \approx 0.26.
0.1 (about right)Glides smoothly down and converges (39 steps).
0.3Faster: converges in 11 steps, still without changing sign.
exactly 0.5Lands exactly on the bottom in one step. This is a coincidence of this function, not a general rule.
0.6Overshoots to the other side every step (zig-zag), but settles in 7 steps.
0.9Zig-zags and settles slowly (49 steps).
0.95 to just below 1Zig-zags and shrinks so slowly that the widget’s 60 steps aren’t enough. At 0.99 the ball is still at x≈0.9x \approx 0.9 after 60 steps.
exactly 1Bounces between 3 and −3 forever.
above 1 (too big)Each jump lands higher than the last. It diverges. At 1.05 the widget gives up after 30 steps.

Diverging is the dramatic failure, but too-small is just as real a problem in practice: training that takes weeks instead of hours.

Go deeper Why exactly do 0.5 and 1 matter for f(x) = x²?

For f(x)=x2f(x) = x^2 the update is xnew=x−η⋅2x=(1−2η) xx_{\text{new}} = x - \eta \cdot 2x = (1 - 2\eta)\,x. So every step multiplies xx by the same factor r=1−2ηr = 1 - 2\eta:

  • 0<η<0.50 < \eta < 0.5: 0<r<10 < r < 1, so xx shrinks toward 0 without changing sign (smooth).
  • η=0.5\eta = 0.5: r=0r = 0, so the first step lands exactly on 0.
  • 0.5<η<10.5 < \eta < 1: −1<r<0-1 < r < 0, so xx flips sign every step but still shrinks (zig-zag). Near η=1\eta = 1, rr is close to −1-1, so the shrinking is very slow.
  • η=1\eta = 1: r=−1r = -1, so xx flips between 33 and −3-3 forever.
  • η>1\eta > 1: ∣r∣>1|r| > 1, so ∣x∣|x| grows every step (divergence).

For a general function the safe range depends on how sharply it curves (its second derivative). For x2x^2 the curvature is 2, and the safe range is η<2/2=1\eta < 2/2 = 1. A more sharply curved bowl needs a smaller η\eta. That idea returns in P1.F6 and P4.14.

Choosing a learning rate in practice

Real losses have no formula you can analyze, so people try values and watch the loss curve (below). A common habit is to try values about a factor of 10 apart, such as 1, 0.1, 0.01 and 0.001, for a short run each. Throw out any that make the loss blow up. Among the rest, pick one of the larger ones that still falls steadily. If a value works but is slow, try about 3 times larger. This is a rule of thumb from experience, not a theorem. Changing the rate during training (schedules) is the topic of P4.14.

More than one valley

Now switch the widget to Two valleys. This function has a shallow valley on the right and a deeper one on the left.

Start the ball at x=2x = 2 with the learning rate at 0.1. It settles in the right valley, at x≈1.30x \approx 1.30 and a height of about −0.46, even though the left valley goes down to about −1.58 (at x≈−1.51x \approx -1.51). Drag the ball to x=−2x = -2 and it finds the deeper one. The two valleys are separated by a hilltop at x≈0.20x \approx 0.20, where the slope is zero. With η=0.1\eta = 0.1, starts on the left of the hilltop end in the left valley, and starts on the right of it end in the right valley.

Gradient descent only ever looks at the slope where it’s standing. So it is a local method: it finds a valley (a local minimum), not necessarily the lowest one (the global minimum). Where you start matters.

With a learning rate of 0.45, the first step from x=2x = 2 lands near the hilltop (at x≈0.02x \approx 0.02), and the ball then ends up bouncing around in the left valley, because that valley is steep and needs η\eta below about 0.42. Big steps can hop over hills, but erratically: that’s not a reliable way to find the best valley.

Many parameters: the loss, averaged over data

Let’s see a loss that really comes from data. The model has one parameter ww and predicts y^=w x\hat{y} = w\,x. (Careful: here xx is the input data and ww is the parameter we adjust. In the widget above, the thing being adjusted was called xx.) We have two examples, (x,y)=(1,2)(x, y) = (1, 2) and (2,6)(2, 6). The loss on one example is the squared error (wx−y)2(w x - y)^2. The loss on the whole dataset is the average over the examples:

L(w)=12[(w⋅1−2)2+(w⋅2−6)2]\begin{gathered} \mathcal{L}(w) \\ \quad= \frac{1}{2}\Big[(w\cdot 1 - 2)^2 + (w\cdot 2 - 6)^2\Big] \end{gathered}

This is a curve in ww, a bowl. The data (the numbers 1, 2, 2, 6) are fixed constants inside it. Its slope is L′(w)=5w−14\mathcal{L}'(w) = 5w - 14, which is zero at w=2.8w = 2.8. Gradient descent from w=0w = 0 with η=0.1\eta = 0.1:

stepwwgradientloss L(w)\mathcal{L}(w)
start0−1420
11.4−75.3
22.1−3.51.625
32.45−1.750.706

The gradient −14 at the start is the average of the two examples’ own gradients, −4 and −24. Using every example for every step, as here, is called full-batch gradient descent. The gradient of an average is the average of the gradients, so every step has to compute a gradient for every example: the cost of one step grows with the number of examples. With millions of examples this is slow, and the fix (estimating the gradient from a small batch) is stochastic gradient descent, the next lesson (P1.F4).

With more parameters, the loss is a surface over (w1,w2,… )(w_1, w_2, \dots). The slope becomes a list of partial derivatives, one per parameter: the gradient ∇L\nabla L. One step moves every parameter at once, each against its own partial derivative. A neural network can have millions of parameters, so the gradient has millions of entries. Backpropagation (P4.8) is how they’re computed efficiently.

Bowls that are stretched

The animation shows gradient descent on f(x,y)=x2+10y2f(x, y) = x^2 + 10y^2, seen from above as contour lines (each oval is a set of points with the same loss). The bowl is ten times steeper in the yy direction than in the xx direction.

Gradient descent seen from above on the oval bowl f = x² + 10y², with learning rate 0.095, 20 steps from the point (−3.5, 1). Each orange arrow points downhill (the arrows have a fixed length: they show direction, not step size) and the ball steps that way, leaving a blue path. Every step multiplies y by −0.9, so the ball jumps back and forth across the narrow direction while the zig-zag slowly shrinks. Every step multiplies x by 0.81, so the ball moves steadily toward the centre along the wide direction. After 20 steps it is near (−0.05, 0.12).

The numbers here are exact. The gradient is (2x,20y)(2x, 20y), so with η=0.095\eta = 0.095 each step does this:

  • x←(1−2η) x=0.81 xx \leftarrow (1 - 2\eta)\,x = 0.81\,x. The shallow direction shrinks smoothly, but only by 19% per step.
  • y←(1−20η) y=−0.9 yy \leftarrow (1 - 20\eta)\,y = -0.9\,y. The steep direction overshoots the valley floor every step (the sign flips), and shrinks by only 10% per step.

We can’t fix this by raising η\eta: at η=0.1\eta = 0.1 the yy factor is exactly −1-1 (bouncing forever), and above that yy diverges. So the steep direction caps the learning rate, and the shallow direction then makes slow progress. After 20 steps the ball has gone from (−3.5,1)(-3.5, 1) to about (−0.05,0.12)(-0.05, 0.12), and the loss from 22.25 to 0.15. On a perfectly round bowl x2+y2x^2 + y^2, one step with η=0.5\eta = 0.5 lands exactly on the bottom.

The ratio of steepest to shallowest curvature (here 10) is the bowl’s ill-conditioning. The bigger it is, the slower and more zig-zaggy plain gradient descent gets. Momentum (P1.F5) and Adam (P4.13) help with this kind of problem: momentum smooths out the zig-zag, and Adam gives each parameter its own step size.

Why feature scaling helps

Where do stretched bowls come from? One common source is features on very different scales. Suppose a model uses two features, and one is 10 times bigger than the other (say, income in thousands and age in decades). The loss changes about 102=10010^2 = 100 times faster when you wiggle the weight of the big feature. For example, take a linear model with squared-error loss and two features whose standard deviations are about 1 and about 10. On random data like that, the curvature along the weight of the smaller feature is about 2, and along the other about 209. The largest safe learning rate is then about 0.0096 on the raw features, and about 0.94 after standardizing each feature (subtracting its mean and dividing by its standard deviation). Rescaling features makes the bowl rounder, so a much bigger learning rate is safe. This is covered in P3.A11. Scaling only fixes the part of the stretching that comes from feature scale; it does not remove all of it.

Flat regions and saddle points

The step is η×\eta \times slope, so where the ground is nearly flat, the step is tiny, even if you’re far from any minimum. Compare two bowls from x=1x = 1 with η=0.1\eta = 0.1:

  • f(x)=x2f(x) = x^2: after 100 steps, x≈2×10−10x \approx 2 \times 10^{-10}. Done.
  • f(x)=x4f(x) = x^4 (very flat near 0): after 100 steps, x≈0.11x \approx 0.11, and after 1000 steps, still ≈0.035\approx 0.035.

A plateau like this makes the loss curve look stuck. It may not be stuck at a minimum, just crawling. Watch out: the widget’s “converged” rule only checks that the step is small. A small step means flat ground, which could be a minimum or just a plateau. (With x4x^4 and the same rule, the step falls below 0.0001 after 310 steps, while x≈0.063x \approx 0.063 is not yet the minimum.)

A saddle point is a point where the gradient is zero but the surface curves up in some directions and down in others, like the middle of a horse saddle. Example: f(x,y)=x2−y2f(x, y) = x^2 - y^2 with the saddle at (0,0)(0, 0). Start at (1,0)(1, 0) and gradient descent walks straight into the saddle and sits there, because the yy part of the gradient is exactly zero. But start at (1,0.001)(1, 0.001) and yy grows by a factor 1.2 every step, so after about 38 steps the ball slides away downhill. P1.F2 has the full story.

The recipe in one place

Intuition

You’re in the fog again. The gradient is the direction that goes uphill most steeply. You step the opposite way. The learning rate is how much you scale the step: tiny strides are safe but slow; giant strides can carry you right across the valley and up the other side.

You stop when you’ve walked as long as you planned, or the ground feels flat, or you stop getting lower. Flat ground does not prove you’re at the very bottom.

Math

With many parameters θ=(θ1,…,θn)\boldsymbol{\theta} = (\theta_1, \dots, \theta_n), the slope becomes the gradient ∇L(θ)\nabla L(\boldsymbol{\theta}), the vector of partial derivatives, and the update is the same idea in every coordinate at once:

θt+1=θt−η ∇L(θt)\boldsymbol{\theta}_{t+1} = \boldsymbol{\theta}_t - \eta\, \nabla L(\boldsymbol{\theta}_t)

The gradient points in the direction of steepest increase, so subtracting it moves in the direction of steepest decrease. If LL is an average of per-example losses, L=1N∑i=1NLi\mathcal{L} = \frac{1}{N}\sum_{i=1}^{N} L_i, then ∇L=1N∑i∇Li\nabla\mathcal{L} = \frac{1}{N}\sum_{i} \nabla L_i.

Common ways to decide when to stop:

  • the gradient’s size ∥∇L∥\lVert\nabla L\rVert falls below a small threshold;
  • the loss stops improving (or the step becomes tiny);
  • a fixed number of steps runs out (the usual choice when training neural networks, often together with a check on held-out data).

Code

def gradient_descent(df, x, lr, steps):
    for _ in range(steps):
        x = x - lr * df(x)
    return x

# Minimize f(x) = x**2, whose slope is 2x
print(gradient_descent(lambda x: 2 * x, x=3.0, lr=0.1, steps=50))  # ≈ 0

In PyTorch, torch.optim.SGD(params, lr=0.1) does exactly this update for every parameter of a model.

The loss curve

The small chart under the widget plots the loss after every step. This loss curve is the first thing anyone looks at when training a model:

  • steadily falling: it’s learning;
  • falling, but very slowly: try a bigger learning rate (or you’re on a plateau);
  • jumping up, or growing: the learning rate is too big;
  • bouncing up and down: also a sign the rate is a bit too big.

You’ll read many of these in P4.22.

Try it: gradient descent in plain Python

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

Now a version where the loss comes from data and the parameter is ww. It also checks the gradient formula numerically.

Try it: full-batch gradient descent on data

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

Go deeper Checking a gradient with finite differences

If you compute a gradient by hand (or write backpropagation code), how do you know it’s right? Compare it with a numerical estimate: nudge the parameter a tiny bit each way and see how the loss changes.

f′(x)≈f(x+h)−f(x−h)2hf'(x) \approx \frac{f(x + h) - f(x - h)}{2h}

This is the central difference. Example: for f(x)=x3f(x) = x^3 at x=1x = 1 (true slope 3), h=0.1h = 0.1 gives an error of 0.01, and h=10−5h = 10^{-5} gives an error of about 10−1010^{-10}. Making hh much smaller does not help: with h=10−12h = 10^{-12} the error grows back to about 10−410^{-4}, because the computer’s rounding errors get divided by a tiny number. A value like 10−510^{-5} is a common choice.

Finite differences need two loss evaluations per parameter, so they are far too slow for training a large model. They are a debugging check only. P4.9 builds an autograd engine and uses this idea to test it.

Check your understanding

  1. At the current point the slope is f′(x)=−4f\prime(x) = -4 and the learning rate is 0.50.5. Which way does xx move, and by how much?

  2. Why do the steps get smaller as gradient descent approaches a minimum, even with a fixed learning rate?

  3. Training loss goes down for a few steps, then starts climbing higher and higher. What is the most likely fix?

  4. Gradient descent stopped at a point where the slope is zero. What can you be sure of?

  5. The loss falls smoothly but very slowly, never rising. After many steps it is still dropping at about the same slow rate. What is a sensible first thing to try?

Exercises

  1. By hand: run two steps of gradient descent on f(x)=x2f(x) = x^2 from x=−2x = -2 with η=0.25\eta = 0.25.
    Show answer−1, then −0.5.
  2. For f(x)=x2f(x) = x^2 the update multiplies xx by 1−2η1 - 2\eta. For which η\eta does xx flip sign on every step, and what happens at exactly η=0.5\eta = 0.5? Use the Go deeper box.
    Show answersign flips for every η\eta above 0.5, because the factor is then negative. There is no smallest such value: any η\eta just above 0.5 works. At exactly 0.5 the factor is 0 and the first step lands on 0.
  3. In the widget’s two-valley mode with η=0.1\eta = 0.1, find the starting point that separates “ends in the left valley” from “ends in the right valley”. What is special about the curve there?
    Show answerthe hilltop near x≈0.20x \approx 0.20, where the slope is zero. Starts at 0.20 or below end in the left valley; 0.21 or above end in the right valley.
  4. For the data example, compute the gradient of the average loss at w=0w = 0 from the two per-example gradients.
    Show answerthe per-example gradients are 2x(wx−y)=−42x(wx - y) = -4 and −24-24; their average is −14-14.
  5. Check the slope of f(x)=x3f(x) = x^3 at x=2x = 2 using a central difference with h=0.1h = 0.1.
    Show answer(2.13−1.93)/0.2=12.01(2.1^3 - 1.9^3)/0.2 = 12.01, close to the true slope 3⋅22=123 \cdot 2^2 = 12.

Next: in real training the loss is an average over millions of examples, which is far too slow to compute for every step. Stochastic gradient descent (P1.F4) fixes that by estimating the slope from a small batch.

Key takeaways

  • Gradient descent repeats one step: x ← x − η · f′(x). Move against the slope, by an amount set by the learning rate η.
  • The minus sign sends you downhill: a positive slope means go left, a negative slope means go right.
  • Steps shrink automatically near the bottom, because the slope there is close to zero.
  • Learning rate too small: painfully slow. Too big: zig-zags, or diverges entirely.
  • The loss is a function of the parameters, not of the data. Gradient descent changes the parameters; the data stays fixed.
  • With many parameters the gradient is a vector, and one step updates every parameter at once: θ ← θ − η∇L.
  • Flat regions give tiny gradients, so training can look stuck; a very elongated bowl makes the path zig-zag, and scaling features helps.
  • Pick the learning rate by trying values about 10 times apart and watching the loss curve.
  • Gradient descent only finds a nearby valley. Where you start can decide which valley you end up in.
Found a mistake? Tell us