1.3 Gradient Descent
Forward, loss, backward, update, and one ReLU unit’s chain rule. That loop is pretraining.
These notes match the lecture slides. Use (slides) on the course hub for the deck.
Training a net is an optimization problem: pick weights so a loss is small on training batches, then check a held-out set. Gradient descent is the default way to move the weights. By the end you should be able to write the update, take two numeric steps on a parabola, and chain-rule one ReLU unit by hand.
1. What gradient descent is
Collect all weights and biases into one vector . A loss is a scalar. Gradient descent repeatedly walks downhill on that surface: each step subtracts a scaled gradient. Stochastic gradient descent (SGD) estimates on a minibatch, not the full dataset. That is how nets learn, including the pretraining loop of a language model.
For classification the loss is often cross-entropy; for a regression toy it is squared error. In two dimensions you can draw the contours. Gradient descent follows .

The picture is a cartoon. Real nets live in millions of dimensions. The geometry is still the same idea: the gradient is the direction of steepest increase, so you walk the other way.
Nielsen calls this the cost; the usual name here is loss; a statistician calls it empirical risk. Same object. You need one scalar, then one vector of derivatives.
2. Why we use it
You cannot solve in closed form for a deep net. The training loop of pretraining is this walk, at huge batch and data scale. Fine-tuning (Week 8) is the same loop on a smaller, more specific dataset. RLHF (Week 9) changes what is, not the fact that you are differentiating a scalar with respect to weights.
Cross-entropy on a next-token distribution is the LLM default. For one token with predicted probability on the correct class,
If the gradient is noise, or is wrong, or the net is linear, no amount of later “prompt engineering” will save the representation. Get this loop right on a tiny problem in Lab 1 before you touch Hugging Face.
A noisy minibatch gradient is not a bug. It is the only gradient you can afford, and the noise can help you leave sharp spikes. The price is that one step is not guaranteed to decrease .
3. Architecture
One training iteration is four moves, in that order.
- Forward. Compute activations layer by layer. Keep them; the backward pass needs them.
- Loss. Compare to the target .
- Backward. Chain rule from the loss to every weight (backpropagation).
- Update. Take a descent step on .

PyTorch does (3) for you if the forward pass used nn.Module and a differentiable loss. Your job is to write (1), pick , and call optimizer.step().
If you forget zero_grad(), gradients accumulate across steps. That is a silent disaster, not a new algorithm.
Adam and related methods rescale coordinates using a running average of gradients; you will use them in PyTorch without deriving them today. The architecture of the loop does not change: forward, loss, backward, update.
4. How it works, step by step
One step is
is the learning rate. Too small: you crawl. Too large: you jump over the valley or diverge.

Treat each operation as a gate with a local derivative. Autograd is that picture. For squared error on one ReLU neuron,
Chain rule, using from note 1.2:
Same pattern for , with replaced by . If , the local derivative is 0 and that example does not move . That is a dead ReLU on this point, not a PyTorch bug.

Lab 1 uses binary cross-entropy on logits , not on . PyTorch’s BCEWithLogitsLoss is
which is numerically stable BCE. The extra line you need: pass , never sigmoid(z), into that loss. If you sigmoid first, you squash twice.
SGD uses a minibatch, not the full dataset. That is how you train on Wikipedia-scale text. We do not need Adam’s derivation this week.
5. Mathematical formulas
The descent step:
Next-token cross-entropy on the correct-class probability :
Chain rule on one ReLU unit with squared error :
The softmax/cross-entropy cousin is . Same “upstream error times input” shape.
Stable binary cross-entropy on a logit (what BCEWithLogitsLoss computes):
6. Positive points and negative points
Positive.
- The update is simple and scales to millions of steps on huge corpora.
- Minibatch SGD is the gradient you can actually afford; the noise can help leave sharp spikes.
- Autograd turns a forward graph of gates into the backward pass, so you write the net once.
- The same loop is pretraining, fine-tuning, and (with a different ) RLHF.
Negative.
- Local minima and saddles exist; a step is not guaranteed to decrease under minibatch noise.
- is a choice: too small crawls, too large overshoots or diverges.
- Forgetting
zero_grad()silently accumulates gradients and wrecks the effective step size. - Passing
sigmoid(z)intoBCEWithLogitsLossdouble-squashes and is a common Lab 1 bug. - If on a ReLU unit, that example does not move ; dead units stay dead.
When not to. If you can solve in closed form (a linear least-squares toy), do that. Deep nets are not that toy.
7. Teaching this note
~18 minutes. Draw a 1-D parabola, write the update, do two numeric steps plus the overshoot, then the four-box loop and zero_grad. Spend four minutes on the one-ReLU chain rule and the BCEWithLogitsLoss warning. 3Blue1Brown gradient descent (0:00–12:00) and the backprop follow-up are homework. Do not derive a softmax Jacobian in this block.
8. Worked example
Let , start at , take . Then .
Step 1:
Step 2:
The minimum is at . You moved . If you instead take , step 1 is , which overshoots. Draw both arrows on the same parabola.
One-unit check: , , , . Then , , , so . Change to : , , . One SGD step with sends .
9. Where students get stuck
- Walking up the gradient (forgetting the minus sign).
- Thinking SGD is “wrong GD” rather than the scalable estimator of .
- Dropping activations after the forward pass, then being surprised that backward needs them.
- Passing
sigmoid(z)intoBCEWithLogitsLoss(the loss already includes the sigmoid).
10. Video
Watch 3Blue1Brown: Gradient descent, how neural networks learn.
Pause when the ball follows , and when a large step jumps the valley. Optional: 3Blue1Brown: What is backpropagation really doing? after class (~14 min); pause on the chain-rule diagram, not the code.
11. Practice
-
You double and the loss oscillates. What happened geometrically?
-
Why keep after you already have ?
-
SGD uses a minibatch. Name one reason that is not “the full gradient is too slow.”
-
For , , , write and . (Use .)
-
Same and , but . Compute . Did the step move closer to or farther?
-
For the one-ReLU unit with , , , , write . Then take and the new .