Optimization & Backpropagation

A neural network learns by feeling which way is downhill and stepping that way. The size of the step decides whether it arrives, crawls or flies off the edge.

Pick a learning rate and take 12 steps down the bowl. Click the bowl to start somewhere else. Then we build, piece by piece, how a network finds the slope for millions of weights at once.

You need basic calculus (derivatives) and linear classification. We build the rest from zero.

Walk downhill

Ready

A toy bowl, L = w₁² + 2w₂², started at (2.4, 1.6). Every step uses the exact gradient (2w₁, 4w₂). The warm arrow shows the downhill direction. Nothing here comes from a paper: it is the idea of this lesson made playable.

Chapter 0

Why Optimization?

Picture the loss as a landscape, and see why we need a downhill direction

You've built a classifier. It has weights. It makes predictions. But right now those weights are random, and the predictions are garbage. How do you find good weights?

Your loss function tells you how badly the current weights perform, a single number. High loss means bad predictions. Low loss means good predictions. The question becomes: how do you change the weights to make the loss go down?

The core idea: Imagine the loss function as a landscape, hills and valleys across weight-space. You're standing somewhere on that landscape. You want to walk downhill to the lowest valley. Optimization is the art of finding the downhill direction and taking a step.

Walk down a loss landscape

A 2D slice of a loss landscape. Bright is high loss, dark is low loss. The teal dot is your current position in weight space. Click the landscape to place the dot, then press Step downhill to watch it roll toward a minimum.

Toy landscape: two smooth valleys, one deeper than the other, drawn from a made-up formula. Each step moves the dot 0.02 of the way along the negative gradient.

Every machine learning algorithm, linear classifiers, SVMs, neural networks, has this same structure: define a loss function, then minimize it by adjusting weights. The loss function is fixed (you chose it). The optimization strategy is how you navigate the landscape to find the bottom.

The naive approach? Try random weights, keep whichever set gives the lowest loss. This is like exploring a mountain range by parachuting to random spots and hoping to land in the deepest valley. It works terribly. We need something smarter: a way to figure out which direction is downhill from wherever we currently stand.

Here is where each part of the instrument at the top gets explained.

  1. Gradients: how to find the slope the arrow follows, by wiggling one weight at a time.
  2. Analytic gradients: an exact formula for the same slope, and the wiggle as a check.
  3. Gradient descent: the update rule, and the learning rate you chose with the buttons.
  4. Mini-batch SGD: a cheaper, noisier slope from a few examples.
  5. Backpropagation: how a network with millions of weights gets its slope.
  6. Local gradients: one worked example, by hand.
  7. A circuit: values forward, gradients backward, gate by gate.
  8. Gate patterns: how add, multiply and max pass a gradient.
  9. Beyond: Momentum, Adam and what comes next.
What does the loss function tell us?

Chapter 1

Gradients: The Direction of Steepest Ascent

Find the downhill direction by wiggling each weight and measuring the slope

Standing on our loss landscape, we need to find the downhill direction. The tool for this is the gradient, a vector of partial derivatives, one for each weight. The gradient points in the direction of steepest ascent. So we walk in the opposite direction.

But how do we actually compute a gradient? The simplest way is the numerical gradient: wiggle each weight by a tiny amount h, measure how the loss changes, and compute the slope.

∂L / ∂wi
The slope of the loss L along weight i alone, with all other weights held still.
L(wi + h)
The loss after nudging weight i up by a tiny amount h.
L(wi − h)
The loss after nudging weight i down by h.
2h
The total width of the wiggle. Dividing the loss change by it gives the slope.

This is the centered difference formula. You nudge the weight up by h, compute the loss. Nudge it down by h, compute the loss. The difference divided by 2h is the approximate slope. Do this for every weight and you have the full gradient vector.

Think of it this way: You're blindfolded on a hillside. To figure out which way is downhill, you take a tiny step forward and feel if you went up or down. Then step backward and feel again. The direction that goes most steeply down is the negative gradient.

Slide along a curve and read its slope

A simple loss curve L(w) = w². Drag the slider to move w. The warm tangent line shows the gradient (slope) at that point. Positive slope → move left. Negative slope → move right.

2.0

The curve is the toy loss w², whose true slope is 2w. The tangent shown is that exact slope.

The numerical gradient is simple but painfully slow. If you have a million weights, you need a million forward passes just to compute one gradient. Each wiggle requires re-evaluating the entire loss function. For a neural network with millions of parameters, this is completely impractical.

python
def numerical_gradient(f, w, h=1e-5):
    grad = np.zeros_like(w)
    for i in range(len(w)):
        old = w[i]
        w[i] = old + h
        loss_plus = f(w)
        w[i] = old - h
        loss_minus = f(w)
        grad[i] = (loss_plus - loss_minus) / (2 * h)
        w[i] = old  # restore
    return grad
Why is the numerical gradient impractical for neural networks?

Chapter 2

Analytic Gradients: Calculus to the Rescue

Swap the slow wiggle for an exact formula, and keep the wiggle as a test

The numerical gradient wiggles each weight and measures what happens. The analytic gradient uses calculus to derive an exact formula for the gradient. No wiggling, no approximation, just math.

For a simple loss L(w) = w², calculus gives us dL/dw = 2w. That's it. One formula, one evaluation, exact answer. Compare this to the numerical approach: two function evaluations per weight, and still just an approximation.

The tradeoff: Numerical gradients are easy to code but slow and approximate. Analytic gradients are exact and fast, but require you to derive the gradient formula by hand (or have a system do it for you). In practice, we always use analytic gradients for training. We use numerical gradients to check that our analytic gradient is correct, a technique called gradient checking.

Compare the formula to the wiggle

For L(w) = w², the analytic gradient is 2w (warm line). The numerical gradient (teal dots, computed with finite differences) closely matches. Smaller h = better approximation. Switch to the one-sided difference to see h matter.

0.01

Computed live in your browser with ordinary 64-bit numbers. The slider sets the exponent: h runs from 0.0001 to 1.

PropertyNumerical GradientAnalytic Gradient
SpeedO(N) forward passes per N weightsO(1) with backprop
AccuracyApproximate (depends on h)Exact
ImplementationSimple loopRequires derivation
Use caseDebugging / gradient checkingActual training

In practice, you derive the analytic gradient, implement it, and then verify it against the numerical gradient on a few random inputs. If they match (within floating-point tolerance), you can trust the analytic version and use it for fast training.

What is gradient checking?

Chapter 3

Gradient Descent: The Update Rule

Turn the gradient into one update rule, and see what the learning rate does to it

Now we have the gradient, it tells us the uphill direction. To go downhill, we walk in the opposite direction. This gives us the simplest optimization algorithm: gradient descent.

w
The weights. The arrow means “replace the old weights with the new value on the right”.
η
Eta, the learning rate: how big a step we take.
∇L(w)
The gradient of the loss with respect to the weights. It points uphill, so we subtract it.

That's the entire algorithm. η (eta) is the learning rate, how big a step we take. ∇L(w) is the gradient of the loss with respect to the weights. We subtract because the gradient points uphill and we want to go downhill.

The learning rate is the most important hyperparameter in deep learning. Too large, and you overshoot the minimum, the loss explodes. Too small, and training takes forever, possibly getting stuck in a shallow local minimum. Finding the right learning rate is an art.

Choose a learning rate

Gradient descent on L(w) = w². Adjust the learning rate and watch the trajectory. Too high = overshooting. Too low = barely moving. Just right = smooth convergence.

0.10

Starts at w = 2.5. Each step is w ← w − η · 2w, the exact gradient of w². A path that leaves the chart is clipped at 10.

In code, gradient descent is just a loop:

python
# Vanilla gradient descent
while True:
    grad = compute_gradient(loss_fn, weights, data)
    weights -= learning_rate * grad  # the update step

Each iteration, we compute the gradient over the entire training set, then update. This is called batch gradient descent, "batch" because we use the full batch of data. It gives the cleanest gradient estimate, but it's expensive: every single update requires a pass over all training examples.

What happens if the learning rate is too large?

Chapter 4

Mini-Batch SGD: Approximate Gradients, Real Speed

Estimate the gradient from a small random batch, and see why the noise helps

Batch gradient descent computes the gradient over the entire training set. With ImageNet (1.2 million images), that means processing every single image before updating the weights once. That's absurdly slow.

The insight: you don't need the exact gradient. An approximation is good enough, as long as it points roughly downhill. Stochastic Gradient Descent (SGD) estimates the gradient from a single random example. Mini-batch SGD uses a small random subset (typically 32-256 examples), the sweet spot between noise and speed.

∇L
The full gradient over the whole training set, which we want but cannot afford each step.
1/B
One over the batch size: the weight that turns a sum into an average.
∑i=1B
Add up the terms for example 1 through example B.
∇Li
The gradient from example i alone.

Where B is the batch size. The mini-batch gradient is a noisy estimate of the true gradient. But here's the beautiful part: that noise actually helps. It acts like a regularizer, preventing the optimizer from settling into sharp, narrow minima that generalize poorly.

Why noise helps: Imagine two valleys, one narrow and deep, one wide and shallow. Both have low loss on training data. But the wide valley is more likely to generalize to new data (small changes in weights don't change the loss much). SGD's noise makes it hard to stay in the narrow valley, random fluctuations bounce it out. The wide valley is more stable under noise, so SGD naturally prefers it.

Race three batch sizes

Three gradient descent trajectories on the same loss surface. Teal = full batch (smooth but slow). Orange = mini-batch (noisy but fast). Purple = SGD (very noisy, single example). All reach roughly the same region.

16

Toy bowl L = x² + 2y², rate 0.05, 40 steps from (2.5, 2). The noise is simulated: spread 0.05 for the full batch, 1.5 ÷ √B for a batch of B, and 1.5 for one example. Each run uses a new random seed.

python
# Mini-batch SGD
for epoch in range(num_epochs):
    for batch in get_mini_batches(data, batch_size=32):
        grad = compute_gradient(loss_fn, weights, batch)
        weights -= learning_rate * grad

Mini-batch SGD is the workhorse of deep learning. Virtually every neural network you've heard of, GPT, ResNet, DALL-E, was trained with some variant of SGD.

Why does mini-batch SGD use a subset of data instead of the full training set?

Chapter 5

Backpropagation: Chain Rule Through a Graph

Apply the chain rule through a graph of simple operations

We know what we need: the gradient of the loss with respect to every weight. And we know analytic gradients are the way to get them. But for a deep neural network with millions of weights arranged in dozens of layers, how do we actually compute all those derivatives efficiently?

The answer is backpropagation. It's not a separate algorithm, it's just the chain rule from calculus, applied systematically to a computation graph.

A computation graph is a directed graph where each node is an operation (add, multiply, max, etc.) and edges carry values. The forward pass flows inputs through the graph to produce the loss. The backward pass flows gradients back through the graph to produce derivatives with respect to every input.

Consider a simple example: f(x, y, z) = (x + y) · z. We can break this into two operations:

q = x + y
Add gate: combines x and y
↓
f = q · z
Multiply gate: combines q and z

The chain rule says: ∂f/∂x = (∂f/∂q) · (∂q/∂x). We compute ∂f/∂q at the multiply gate, and ∂q/∂x at the add gate, then multiply them together. That's backpropagation, each gate computes its local gradient, and gradients multiply as they flow backward.

Pass values forward and gradients back

A simple computation graph: f = (x + y) · z. Teal values flow forward. Warm gradients flow backward via the chain rule. Choose which pass to show.

Fixed inputs x = −2, y = 5, z = −4, the example worked by hand in the next chapter.

The key insight: each node only needs to know its local gradient (the derivative of its output with respect to its inputs) and the upstream gradient (the gradient flowing in from above). Multiply them together, and pass the result backward. No node needs to understand the rest of the graph.

What does each node in a computation graph compute during the backward pass?

Chapter 6

Local Gradients: Each Gate Knows Its Own Derivative

Work one example by hand, and check it against a small change

Backpropagation works because each gate only needs to know one thing: given its inputs, what is the derivative of its output with respect to each input? This is the local gradient.

Let's work through the concrete example from Chapter 5. Set x = −2, y = 5, z = −4.

Forward pass:

q = x + y = −2 + 5 = 3

f = q · z = 3 · (−4) = −12

Backward pass (starting from ∂f/∂f = 1):

At the multiply gate (f = q · z):

∂f/∂q = z = −4    ∂f/∂z = q = 3

At the add gate (q = x + y):

∂q/∂x = 1    ∂q/∂y = 1

Chain rule gives the final gradients:

∂f/∂x = (∂f/∂q) · (∂q/∂x) = −4 · 1 = −4

∂f/∂y = (∂f/∂q) · (∂q/∂y) = −4 · 1 = −4

∂f/∂z = 3

Sanity check: ∂f/∂x = −4 means that if we increase x by a tiny amount h, f decreases by 4h. Let's verify: f(−2 + 0.01, 5, −4) = (−1.99 + 5)(−4) = 3.01 × −4 = −12.04. The change is −0.04 = −4 × 0.01. It checks out.

Set the inputs, read the local gradients

Adjust x, y, z and watch the forward values and backward gradients update in real time. Each gate computes only its local derivative.

−2.0
5.0
−4.0

Every gradient shown is exact, computed from the gate rules in this chapter.

For the multiply gate f = a · b, what is the local gradient ∂f/∂a?

Chapter 7

Backprop Through a Circuit: The Showcase

Run values forward and gradients backward through a larger circuit

Now let's put it all together with a richer computation graph. Below is an interactive circuit that computes a more complex function. You set the inputs, watch values flow forward through the gates, then see gradients flow backward, gate by gate, via the chain rule.

What to watch for: During the forward pass, values flow left-to-right, each gate combining its inputs. During the backward pass, gradients flow right-to-left. At each gate, the incoming gradient is multiplied by the local gradient. By the time gradients reach the inputs, they encode how much each input affects the final output.

Run a circuit forward, then backward

Circuit: f = (x + y) · z + max(x, w). Set inputs, run the forward pass, then the backward pass. Watch gradients propagate through each gate.

2.0
1.0
−3.0
4.0

Every number is computed exactly by the rules in Chapters 5 and 6. At a tie between x and w the max gate sends the gradient to x.

Try these experiments:

Chapter 8

Gate Patterns: Add, Multiply, Max

Learn how add, multiply and max each hand a gradient along

Once you've seen backpropagation through a few gates, you notice patterns. Each common gate has a characteristic way it handles gradients. Memorizing these patterns lets you read computation graphs like a circuit diagram.

The add gate: gradient distributor. For f = x + y, we have ∂f/∂x = 1 and ∂f/∂y = 1. The upstream gradient is simply copied to both inputs, unchanged. The add gate distributes the gradient equally.

The multiply gate: gradient switcher. For f = x · y, we have ∂f/∂x = y and ∂f/∂y = x. The gradient for each input is scaled by the other input's value. If one input is large, the other's gradient is large. This is why multiplications can cause gradient explosion or vanishing.

The max gate: gradient router. For f = max(x, y), the gradient flows entirely to whichever input was larger. The other input gets zero gradient. It's like a switch, the max gate routes the gradient to the winner and blocks the loser.

Why this matters for neural networks: A ReLU activation is f = max(0, x). When x > 0, the gradient flows through. When x ≤ 0, the gradient is zero, the neuron is "dead" for this input. This is the dying ReLU problem, and it comes directly from the max gate pattern.

Compare the three gates

Three gates share one upstream gradient. Watch how each gate hands it out differently. Adjust the inputs to see the pattern. Set the upstream gradient to 2.0 and y to 5 to check the quiz.

3.0
2.0
1.0

The upstream gradient starts at 1.0, as at the end of a loss. Raise it to see every gradient scale with it.

GateForwardLocal GradientRole
Addx + y∂f/∂x = 1, ∂f/∂y = 1Distributor, copies gradient to all inputs
Multiplyx · y∂f/∂x = y, ∂f/∂y = xSwitcher, scales gradient by the other input
Maxmax(x, y)1 for winner, 0 for loserRouter, sends gradient only to the larger input
If f = x · y and the upstream gradient is 2.0, what gradient does x receive when y = 5?

Chapter 9

Beyond: From Gradients to Neural Networks

See how the same gradients feed Momentum and Adam, and what you can build next

You now understand the complete optimization pipeline: define a loss, compute its gradient with respect to the weights using backpropagation, and update the weights in the opposite direction of the gradient. Every neural network, from a single-layer perceptron to GPT-4, learns this way.

But the story doesn't end with vanilla SGD. Modern deep learning uses sophisticated optimizers that adapt the learning rate for each parameter individually:

What's next: SGD with Momentum adds velocity, the update accumulates past gradients like a ball rolling downhill, carrying momentum through flat regions. Adam adapts the learning rate per-parameter using running averages of the gradient and its square. These are the optimizers that power modern deep learning.
ConceptWhat We LearnedWhat Comes Next
GradientDirection of steepest ascentSecond-order methods (curvature)
Learning rateFixed step sizeAdaptive rates (Adam, AdaGrad)
SGDMini-batch gradient estimationMomentum, Nesterov, Adam
BackpropChain rule on a computation graphAutograd (automatic differentiation)
Gate patternsAdd, multiply, maxSigmoid, softmax, attention gates

The key lessons from this chapter:

The takeaway: “What I cannot create, I do not understand.” (Richard Feynman) You can now build the loop: a loss, a gradient from backpropagation, and a step the opposite way.

The whole lesson as one loop

Here is every idea above in a few lines. The loss and the gradient come from a computation graph, and the step goes the opposite way. This is a sketch: forward and backward stand for the two passes you ran in Chapter 7.

pythonfor epoch in range(num_epochs):                       # Ch 4: many passes over the data
    for batch in get_mini_batches(data, batch_size=32):  # Ch 4: a noisy but cheap slope
        loss  = forward(weights, batch)                 # Ch 5: values flow forward
        grad  = backward(loss)                          # Ch 5 to 8: gradients flow back, gate by gate
        weights -= learning_rate * grad                 # Ch 3: step the opposite way
What is the fundamental difference between SGD and Adam?

Now press Present or Teach and explain one training step out loud, from memory: what the loss is, how a gradient is found, how one gate hands a gradient back, and why the learning rate matters. Then go back to the bowl at the top, pick each learning rate in turn, and say what the gradient is doing at every step.

Optimization & Backpropagation: From Loss Landscapes to Learning
← Back to Gleams