1.5Loss functions & gradient descent
How a model measures its own mistakes, and the deceptively simple rule — "walk downhill" — that trains every modern neural network.
Turning “wrong” into a number
In the previous lessons, a modelModelA function with adjustable parameters that maps inputs to outputs. Training sets the parameters so the outputs are useful. was a function with knobs: its parametersParameter (weight)A number inside a model that is adjusted during training. Modern LLMs have billions to trillions of them.. Training means finding knob settings that make the model’s outputs match the data. To do that automatically, the computer needs a precise answer to one question: how bad is the current setting?
That answer is the loss functionLoss functionA number measuring how wrong a model's predictions are. Training tries to make it small.. It takes the model’s predictions and the correct answers and returns one number: 0 means perfect, bigger means worse. Two classic examples:
- Mean squared error for predicting numbers (house prices, temperatures). Average the squared differences between prediction and truth. Squaring makes big misses hurt a lot more than small ones.
- Cross-entropy for predicting categories, including the next word. It is the negative log of the probability the model gave to the right answer. Language models are trained with this loss; see cross-entropyCross-entropy lossThe negative log-probability the model assigned to the correct answer. It is low when the model is confidently right. in the previous lesson.
Once you have a loss, training becomes an optimization problem: find the parameters that make the loss as small as possible.
You’re on a hillside in thick fog and want to reach the valley floor. You can’t see the valley, only the ground right at your feet. So you feel which way the ground slopes most steeply downward, take one step that way, and repeat.
The altitude is the loss. Your position is the model’s parameters. The slope under your feet is the gradient, and the length of your stride is the learning rate. You never see the whole landscape, and neither does the computer. It only ever measures the local slope.
The loss landscape
Picture every possible parameter setting as a location on a map, with the loss at that setting as the height of the ground. The result is the loss landscape. Our toy model below has just two parameters, and , so the landscape is a surface you can look at. Real LLMs have billions of parameters, so their landscape lives in a billion-dimensional space that nobody can picture, but the rule for moving through it is exactly the same.
Drag to orbit · scroll to zoom · click the surface to drop the ball anywhere. Blue valleys = low loss.
Things to try in the demo:
- Learning rate ≈ 0.05. The ball creeps; it will get there, eventually.
- Learning rate ≈ 1.4. The ball overshoots the valley floor and zig-zags, or even flies off to the edge. Too big a step and you leap over the valley.
- Start B. The ball settles in the smaller valley at the lower left. That is a local minimum: every direction from there goes up, even though a deeper valley exists elsewhere.
- Momentum. The ball now keeps some of its previous velocity, like a heavy ball rather than a cautious hiker. It can roll across small bumps and often converges faster.
The gradient: which way is downhill?
The gradientGradientThe vector of partial derivatives of the loss with respect to each parameter. It points in the direction of steepest increase., written , is a vector with one entry per parameter. Each entry answers: if I increase this parameter a tiny bit, how fast does the loss change? Together, the entries point in the direction of steepest increase. So we step the opposite way:
Here (theta) is all the parameters bundled into one vector, and (eta) is the learning rateLearning rateThe step size in gradient descent. Too small is slow; too large overshoots or diverges.. That’s the entire algorithm. Everything else (Adam, learning-rate schedules, momentum) refines this one line.
Stochastic gradient descent: estimating the slope cheaply
The “true” loss is an average over the entire training set, which for an LLM is trillions of tokens. Computing the exact gradient before every single step would take forever. Instead, we estimate it from a small random mini-batch of examples (say, a few million tokens), take a step, then grab a fresh batch. This is stochastic gradient descentStochastic gradient descent (SGD)Gradient descent that estimates the gradient on a small random batch of examples instead of the full dataset. (SGD).
Each step’s direction is a little noisy, like a hiker who misjudges the slope now and then. In practice that noise is fine and even helpful: it jostles the parameters out of sharp, narrow dips that tend not to generalize. Real training runs take hundreds of thousands of these noisy steps.
Choosing the learning rate
The learning rate is the most important single knob in training:
- Too small: progress is glacial, and you burn compute standing still.
- Too large: updates overshoot, the loss oscillates or explodes (you’ll see
NaNin your logs). - Just right: usually found by experiment. Modern LLM training uses a schedule: a short warm-up from near zero, then a slow decay (cosine or linear) so the final steps are small and precise.
MATH CORNER · optionalDeriving the update rule, with a worked example
Why minus the gradient? For a small step , a first-order Taylor expansion says
We want the second term as negative as possible for a step of fixed length. The dot product is most negative when points exactly opposite to . Hence .
Worked example (one parameter). Let , minimized at . Its derivative is . Start at with :
| step | update | ||
|---|---|---|---|
| 0 | 0.000 | −6.000 | +1.500 |
| 1 | 1.500 | −3.000 | +0.750 |
| 2 | 2.250 | −1.500 | +0.375 |
| 3 | 2.625 | −0.750 | +0.188 |
Each step halves the remaining distance to 3, because . Notice what happens if : the factor becomes , so bounces forever between 0 and 6. And with the factor’s magnitude exceeds 1, so it diverges. For a quadratic with curvature , gradient descent is stable only when . That is the precise version of “too large a learning rate overshoots”.
Momentum keeps a running velocity:
with . Consistent gradients accumulate into speed; gradients that flip sign cancel out, damping zig-zags.
In code
Here is gradient descent on the toy loss above, first by hand and then the way PyTorch does it for any model:
# By hand: minimize L(w) = (w - 3)^2
w, lr = 0.0, 0.25
for step in range(10):
grad = 2 * (w - 3) # dL/dw
w = w - lr * grad # the gradient descent update
print(w) # ≈ 2.997
# PyTorch: identical idea, gradients computed automatically
import torch
model = torch.nn.Linear(10, 1)
opt = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
for x, y in data_loader: # mini-batches → "stochastic"
loss = torch.nn.functional.mse_loss(model(x), y)
opt.zero_grad()
loss.backward() # backpropagation fills .grad
opt.step() # θ ← θ − η·∇L (plus momentum)
Isn’t getting stuck a disaster?
The demo makes local minima look scary. In very high-dimensional spaces they turn out to be less of a problem than intuition suggests. For a point to be a true local minimum, the surface must curve upward in every one of millions of directions at once. Most flat spots are instead saddle points: uphill in some directions, downhill in others, so noisy SGD eventually slides off. Large networks also tend to have many different low-loss solutions that perform about equally well. The 2D picture is a great intuition pump, but don’t over-trust it.
- “Gradient descent finds the best possible parameters.” It finds a low point near where it started, guided only by local slope. For neural networks there is no guarantee of the global minimum. In practice we just need a good-enough one.
- “A bigger learning rate always trains faster.” Only up to a threshold. Beyond roughly the updates overshoot and the loss goes up, sometimes to infinity.
- “The gradient points to the minimum.” It points in the steepest local uphill direction. On a long, narrow valley the steepest-descent direction points mostly across the valley, not along it, which causes zig-zagging. Momentum and Adam help with exactly this.
- “Lower training loss always means a better model.” A model can drive training loss to zero by memorizing. What matters is loss on data it hasn’t seen (see the lesson on overfitting).
Check your understanding
Q1.In the update rule θ ← θ − η∇L, why do we subtract the gradient?
Q2.You train with L(w) = (w−3)² and learning rate η = 1.2. What happens?
Q3.What makes stochastic gradient descent 'stochastic'?
Q4.Your ball settles in a valley where every nearby direction goes uphill, but a deeper valley exists elsewhere. This is…
Q5.Which statement about momentum is most accurate?
Further reading
- paperAn overview of gradient descent optimization algorithms — Sebastian Ruder's classic survey of SGD, momentum, Adam and friends.
- blogWhy Momentum Really Works — Gabriel Goh's beautiful interactive Distill article.
- videoGradient descent, how neural networks learn — 3Blue1Brown's visual introduction.
- bookDeep Learning (Goodfellow, Bengio, Courville), Chapter 8: Optimization