AI from scratch · Chapter 2
Gradients: which way is downhill
Last chapter ended with a promise: training a network means finding the right numbers for its matrices. There are millions of them, so nobody tries them one by one. Instead, the network measures how wrong it is and asks a simple question: if I nudge this number a little, does it get better or worse? That question has a name, the derivative, and the whole of deep learning is built on asking it very fast. (This chapter is the intuition; for the full toolkit, the rules, many variables and curvature, continue with Calculus 1 afterwards.)
1. A slope is "how much does it change?"
Here's a bumpy curve. The yellow line joins your point to another point a step h to the right: it rises some amount over a run of h. Drag the blue point along the curve, and shrink h.
As h shrinks, the line stops cutting the curve and just touches it: that's the tangent, and its slope is the derivative. Zoom in on any smooth curve far enough and it looks straight; the derivative is the slope of that straight bit. Positive means "going up to the right", negative means "going down", zero means you're at a flat spot: the top of a hill or the bottom of a valley.
For simple functions the limit can be worked out once, by hand, and gives rules you can reuse. Take \(f(x) = x^2\). The one algebra step: \((x+h)^2\) is \((x+h)\) times \((x+h)\), and multiplying every part by every part gives \(x \cdot x + x \cdot h + h \cdot x + h \cdot h = x^2 + 2xh + h^2\). (Check with numbers: \((3+1)^2 = 16 = 9 + 6 + 1\).) Then the \(x^2\)s cancel and the \(h\) divides out:
\[ \frac{(x+h)^2 - x^2}{h} = \frac{x^2 + 2xh + h^2 - x^2}{h} = 2x + h \;\xrightarrow{\;h \to 0\;}\; 2x \]
So the slope of \(x^2\) at any \(x\) is \(2x\). The same algebra gives the rules every library uses: \((x^n)' = n x^{n-1}\), \((e^x)' = e^x\), \((\ln x)' = 1/x\), and slopes of sums add up. A computer can also skip the algebra and just try a small \(h\), which is what the code below does. Watch what happens when \(h\) gets too small.
\(f(x) = x^2\) at \(x = 3\), with a step \(h = 1\). What's the slope of the yellow line (the secant), \(\frac{f(4) - f(3)}{1}\)?
2. Rolling downhill
Say the curve measures how wrong we are, and we want the lowest point. We can't see the whole curve (in a real network it lives in a million dimensions), but we can always measure the slope where we stand. So: take a step against the slope. If the ground tilts up to the right, step left. Repeat.
x ← x − (learning rate) × slope
Play with the learning rate. Small, and the ball crawls. Big, and it overshoots, bouncing from wall to wall, or flies off entirely. Drop it on the right and it settles in the shallow valley, never finding the deeper one: gradient descent only knows the ground under its feet. Choosing the step size, and getting out of shallow valleys, is half the craft of training networks.
Gradient descent only feels the ground under its feet: step against the slope, with steps small enough for how sharply the valley curves.
Where it breaks: when "go downhill" isn't enough
- Shallow valleys. The ball stops in the first valley it rolls into, as you saw. Real networks have millions of directions, and it turns out most of their valleys are about equally good, so this hurts less than you'd fear; restarts from different random points are the classic remedy.
- Flat ground and saddles. The slope is near zero on a plateau, and at a saddle (downhill one way, uphill another, like a mountain pass), without being a valley at all. In many dimensions saddles are far more common than valleys. Steps there are tiny, and training seems stuck before it starts moving again. Momentum (keep some of the last step's speed) rolls through them.
- Narrow, steep valleys. When one direction curves sharply and another gently, a step size safe for the steep one crawls along the gentle one, and the path zigzags. Adam's per-number step sizes are the usual fix (training in PyTorch).
- Noisy slopes. Real training measures the slope on a small batch of examples, so each step's direction is a little wrong. That noise is mostly harmless, sometimes even helpful, but it's why the loss curve wobbles.
The math, step by step
The update rule, with \(\eta\) (eta) for the learning rate:
\[ x_{k+1} = x_k - \eta\, f'(x_k) \]
Try it on the simplest valley, \(f(x) = x^2\), whose slope is \(2x\). Then \(x_{k+1} = x_k - \eta \cdot 2x_k = (1 - 2\eta)\,x_k\). Every step multiplies \(x\) by the same factor \((1 - 2\eta)\), and that factor tells the whole story:
- \(\eta = 0.1\): factor 0.8. From \(x = 5\): 4, 3.2, 2.56, … shrinking smoothly to 0.
- \(\eta = 0.5\): factor 0. Lands at the bottom in one step (lucky: only works because we know the curve exactly).
- \(\eta = 0.9\): factor −0.8. Overshoots to the other side each time, but still shrinks: the bouncing you saw above.
- \(\eta = 1\): factor −1. Bounces 5, −5, 5, −5 forever.
- \(\eta > 1\): \(|1 - 2\eta| > 1\), each bounce is bigger than the last, and \(x\) flies off.
The steeper the valley's walls curve (the bigger the second derivative), the smaller \(\eta\) must be. Real loss landscapes curve differently in different directions, which is why methods like Adam adapt the step size per parameter.
\(f(x) = x^2\), learning rate 0.1, and you're at \(x = 5\). Where is the ball after one step?
Same valley, \(f(x) = x^2\). Which learning rate makes the ball bounce between 5 and −5 forever?
- 0.1
- 0.5
- 1
- 2
3. Two inputs: the gradient is an arrow
Now the "wrongness" depends on two numbers, so it's a landscape, drawn here like a map: dark is low, bright is high, and the lines are contours of equal height. At any spot you can ask two questions: how steep is it going right, and how steep going up? Those two slopes together make an arrow, the gradient. Drag the point.
The red arrow (the gradient) always points straight uphill, the steepest way up, and it's always perpendicular to the contour line you're standing on. Its length says how steep. The green arrow is the opposite: steepest downhill. That's the direction gradient descent walks.
The math, step by step
With two inputs, take the slope in each direction while holding the other one fixed. These are partial derivatives, written with a curly \(\partial\). Stacked together they're the gradient:
\[ \nabla f(x, y) = \left( \frac{\partial f}{\partial x},\ \frac{\partial f}{\partial y} \right) \]
Example: \(f(x, y) = x^2 + 3y^2\). Treat \(y\) as a constant and differentiate in \(x\): \(\partial f/\partial x = 2x\). Treat \(x\) as constant: \(\partial f/\partial y = 6y\). At the point (1, 1) the gradient is (2, 6): the ground rises three times faster going north than going east.
Why the gradient points steepest uphill (this is chapter 1's dot product paying off). Walk a tiny step in a direction \(u\) of length 1. The height changes by about \(\nabla f \cdot u = \lVert \nabla f \rVert \cos\theta\). That's largest when \(\theta = 0\), walking straight along the gradient; zero when you walk at right angles to it, which is along the contour line, where the height doesn't change; and most negative straight against it.
The gradient is an arrow that points the steepest way uphill, and its length says how steep. Walking against it is the fastest way down, for a small enough step.
Why does a small step against the gradient always go down?
- Near where you stand, the landscape is almost flat-tilted: a step \(s\) changes the height by about \(\nabla f \cdot s\) (the dot product from the box above).
- Step against the gradient, \(s = -\eta\, \nabla f\): the change is about \(-\eta\, \nabla f \cdot \nabla f = -\eta \lVert \nabla f \rVert^2\).
- A squared length is never negative, so this is below zero whenever the gradient isn't zero: the height goes down.
- The catch is "about". The tilted-plane picture only holds near where you stand; a big \(\eta\) walks off into ground that curves away from it, which is the bouncing and flying off you saw in section 2. Calculus 3 measures exactly how far is too far.
\(f(x, y) = x^2 + 3y^2\). What is the gradient at the point (2, −1)?
- (4, 3)
- (4, −6)
- (4, 6)
- (4, −2)
Why is the gradient always at right angles to the contour line you're standing on?
- Along the contour the height doesn't change, so \(\nabla f \cdot u = 0\) for that direction, and a zero dot product means a right angle
- It's a convention of how contour maps are drawn
- Only because these valleys are round
4. Learning is walking downhill
Here's the whole idea of training, in miniature. On the left: some points, and a line y = w·x + b that should fit them. How wrong the line is (the average squared vertical miss, called the loss) depends on two numbers, w and b. On the right: that loss as a landscape over every possible (w, b). Each training step is one step downhill on the right, and the line on the left gets better.
Drag the points on the left and the landscape on the right reshapes itself: the loss depends on the data. Drag the yellow dot on the right to start the line somewhere else. A real network is this exact loop with millions of numbers instead of two: measure the loss, compute its gradient, step downhill, repeat. The only hard part left is computing the gradient for millions of numbers at once, efficiently. That's backpropagation, and it's coming up right after we build a single neuron.
The math, step by step
With \(N\) points \((x_i, y_i)\), the line predicts \(\hat y_i = w x_i + b\) and misses by \(r_i = \hat y_i - y_i\) (the residual). The loss is the mean squared error:
\[ L(w, b) = \frac{1}{N} \sum_{i=1}^{N} (w x_i + b - y_i)^2 \]
Differentiate one term at a time. The outside is "something squared", with slope 2·(something); the inside \(w x_i + b - y_i\) has slope \(x_i\) in \(w\) and 1 in \(b\). Multiply the two (the chain rule, chapter 4's main character):
\[ \frac{\partial L}{\partial w} = \frac{2}{N} \sum_i r_i\, x_i \qquad \frac{\partial L}{\partial b} = \frac{2}{N} \sum_i r_i \]
Read them in plain words. If the line sits too high on average (residuals positive), \(\partial L/\partial b > 0\), so a step downhill lowers \(b\). If it's too high mostly where \(x\) is large, \(\partial L / \partial w > 0\) and the slope \(w\) comes down. Each point pulls the line toward itself, weighted by how badly it's missed.
Training is this loop: measure the loss, find its gradient with respect to every knob, take a step downhill, repeat.
The line sits above every point. One gradient step later, what happens to the bias \(b\)?
- It goes up
- It goes down
- It stays the same
Inspired by 3Blue1Brown's gradient descent and Essence of Calculus. All lessons: AI from scratch.
Last updated