Semester 1 · Week 03
Calculus and optimisation
- Ch 4 Maths Foundations: Calculus & Optimisation
Chapter 4: Calculus and optimisation
Training a model is a search for the bottom of a valley.
Notes · slide 2
Time: 50 minutes for one chapter. About 20 on gradients and the update rule, 15 on loss functions and optimisers, 10 on the worked example, and 5 to check understanding.
Say: Last week, linear regression had an exact formula. Almost nothing else does. Logistic regression and neural networks are found by search. Start from a guess and improve it.
Key line: training a model is a search for the bottom of a valley. Tonight is how that search works.
GenAI link: Every LLM was trained this way. GPT-3's 175 billion weights were all found by the search covered tonight.
Next: training as optimisation.
Training is optimisation
- A loss function measures how wrong the predictions are.
- Over all parameter values, the loss forms a surface. With two weights, picture terrain.
- Training searches for the lowest point.
- Gradient descent does the search: find the steepest way down, step, repeat.
It scales from one parameter to hundreds of billions.
Notes · slide 3
Say: A loss function scores how wrong the predictions are. Every setting of the weights gives a loss. Over all settings, that's a surface. With two weights, picture terrain where height is loss.
Say: Training looks for the lowest point. Gradient descent does it with local information only: which way is down from here. Step, then repeat.
Key line: it never needs the whole landscape. That's why it scales from one parameter to hundreds of billions.
Ask: "Why not try every combination of weights?" Listen for: far too many, even for a small model.
GenAI link: The same loop trains an LLM. The loss is cross-entropy on the next token. Pretraining a large model is one long gradient descent run over trillions of tokens.
Next: how we find "down".
Derivatives and gradients
- A derivative is a rate of change. Velocity is the derivative of position.
- With many parameters, the gradient collects every partial derivative:
∇f(w)=[∂w1∂f,∂w2∂f,…,∂wn∂f]
- It points uphill, in the direction of steepest ascent. So we step the other way.
Notes · slide 4
Say: A derivative is a rate of change. Your speedometer shows one: the derivative of position. For a loss, it says how much the loss moves if you nudge a weight, and in which direction. The sign is what matters.
Say: With many weights, the gradient lists one partial derivative per weight. Each says how the loss responds to that weight alone. Together they point uphill, the steepest way up. So we step the opposite way.
Three ways to get a derivative. Take f(x)=3x2−4x+5 at x=3, where f=20.
- Symbolic: apply the calculus rules on paper. f′(x)=6x−4, so the slope at 3 is 14. Nobody does this for a neural network. Written out, the formula would run to tens of thousands of terms.
- Numerical, rise over run: nudge x by a small h and measure the change. With h=0.001, f rises by about 0.050, and 0.050/0.001≈14. It's the definition of the derivative, so it builds intuition. But it's an estimate, and if h gets too small, floating-point rounding gives wrong answers. It also needs one extra run of the model per weight.
- Automatic, backpropagation: each small operation knows its own local derivative, and the chain rule combines them. Exact, with no formula written out. This is what PyTorch does, and it's the next slide.
Andrej Karpathy's micrograd video walks this path: rise over run for intuition, then backpropagation built from scratch. It's on the reading list.
Ask: "The derivative is positive. Do you increase or decrease the weight?" Listen for: decrease.
GenAI link: In an LLM, the gradient has one entry per weight: billions of numbers every step. Holding the gradients and the optimiser's running averages is why training needs several times the GPU memory of running the model.
Next: the update rule.
The update rule
w←w−α∇f(w)
- α is the learning rate: the step size.
- Repeat until the loss stops falling.
Notes · slide 5
Say: One line. New weights equal old weights minus learning rate times gradient. Recompute the gradient, take another step, and repeat until the loss stops falling or you hit an iteration limit.
Key line: every model trained by gradient descent in this course, and the next three, runs this line.
Do: if the room is unsure, act it out on a 1D parabola on the board: slope positive, move left. Slope negative, move right.
GenAI link: Fine-tuning is this same line, started from pretrained weights instead of random ones, usually with a much smaller learning rate. LoRA runs it on the small low-rank matrices only, from week 2.
Next: choosing the step size.
The learning rate trade-off
| α | What happens |
|---|---|
| Too large | Overshoots. The loss oscillates or diverges |
| Too small | Converges, eventually. Wastes compute |
| Just right | Falls fast, then settles |
There's no universal right value. Read the loss curve.
Notes · slide 6
Say: Too large and you overshoot the bottom, land higher on the other side, and the loss bounces or blows up. Too small and you get there eventually, after far more steps. Just right falls fast, then levels off.
Say: The right value depends on the problem, the model, and the scale of the inputs. That's why schedules shrink it during training.
Key line: read the loss curve. It tells you which of the three you're in.
Ask: "Your loss goes up every epoch. What's your first fix?" Listen for: lower the learning rate.
GenAI link: LLM training uses a schedule. Warm-up raises the learning rate from near zero over the first steps. Then it decays slowly, often along a cosine curve. Large runs sometimes hit sudden loss spikes. The team behind Google's PaLM handled them by restarting from an earlier checkpoint and skipping the batches around the spike.
Next: what the loss measures.
Loss functions define "good"
| Loss | Formula | Use for |
|---|---|---|
| MSE | N1∑(y^−y)2 | Regression |
| MAE | N1∑∣y^−y∣ | Regression with outliers |
| Binary cross-entropy | −[ylogy^+(1−y)log(1−y^)] | Binary classification |
Choosing the loss is a modelling decision, made when you design the solution.
Notes · slide 7
Definitions: Mean Absolute Error (MAE) averages the absolute differences between actual and predicted values. Mean Squared Error (MSE) averages the squared differences. An error of 2 adds 2 to MAE's total but 4 to MSE's. An error of 10 adds 10 to MAE's but 100 to MSE's.
Say: The loss defines what "good" means. MSE squares errors, so big ones dominate, and it's smooth everywhere. MAE treats every error linearly, so a few outliers can't dominate. Binary cross-entropy is for classification. It comes from the Bernoulli likelihood in Chapter 3. It's zero for a perfect prediction and grows without limit for a confident wrong one.
Key line: choosing the loss is a modelling decision, made when you design the solution. Not a default to accept.
Ask: "Delivery times with a few lost parcels in the data. MSE or MAE?" Listen for: MAE, because the outliers would swamp MSE.
GenAI link: An LLM's pretraining loss is cross-entropy over the next token: the many-class version of the binary loss here. Perplexity, a number in many LLM papers, is the exponential of that average loss. A perplexity of 10 means the model is as unsure, on average, as picking between 10 equally likely tokens. Fine-tuning with RLHF or DPO changes the loss, and so changes what "good" means: from likely text to text people prefer.
Next: gradients through many layers.
The chain rule and backpropagation
dxd[f(g(x))]=f′(g(x))⋅g′(x)
- A neural network is functions inside functions.
- The chain rule, applied layer by layer, gives the gradient for every weight.
- That's backpropagation.
Notes · slide 8
Definition: the chain rule gives the rate of change of a function inside another function. Multiply the outer function's rate of change, taken at the inner value, by the inner function's rate of change.
Example: y=(3x+1)2. Two stages. The inner stage is u=3x+1, which changes 3 times as fast as x. The outer stage is y=u2, which changes 2u times as fast as u. Chain them: dy/dx=2u×3=6(3x+1). At x=1, u=4, so the outer stage gives 8, the inner gives 3, and dy/dx=24. Check it: nudge x from 1 to 1.001, and y moves from 16 to about 16.024. That's 24 times the nudge.
Say: A neural network is functions inside functions. The loss depends on the last layer, which depends on the one before, back to the first weight.
Say: Think of gears. Turn the first and the last turns at the product of every ratio in between. Derivatives chain the same way: multiply each layer's local rate of change.
Key line: backpropagation is the chain rule applied from the loss back to every weight. PyTorch automates it, but this is what it automates.
Common question: "Do real models estimate the gradient with rise over run?" No. Rise over run would need one extra run of the model per weight: 70 billion runs per step for a 70-billion-weight model. Backpropagation runs the model forward once and keeps each layer's results. Then it runs the chain rule backwards from the loss. That gives the exact gradient for every weight in roughly two to three times the work of one forward pass, however many weights there are. Rise over run appears only as a check: the lab's numerical gradient check compares the two on a small model. The approximation in real training is elsewhere. Each gradient is exact for its mini-batch, but only an estimate for the whole dataset.
GenAI link: Backpropagation through a transformer is the chain rule through dozens of layers. Multiplying many small factors can shrink the gradient to almost nothing before it reaches the early layers: the vanishing gradient problem. Residual connections add each layer's input to its output, which gives the gradient a direct path back. Every transformer uses them.
Next: how much data each step uses.
How much data per step?
| Variant | Batch | Trade-off |
|---|---|---|
| Batch GD | All N rows | Exact gradient, slow for large N |
| Stochastic GD | 1 row | Fast and noisy |
| Mini-batch GD | 32–256 rows | The standard in practice |
Notes · slide 9
Say: Batch gradient descent uses every row for each step. An exact gradient, but slow on large data. Stochastic uses one row. Fast and noisy, and the noise can help it escape shallow dips. Mini-batch uses 32 to 256 rows: noise mostly averaged out, fast steps, and a good fit for GPUs.
Key line: mini-batch is the standard in practice.
Ask: "Your data doesn't fit in memory. Which variant?" Listen for: mini-batch or stochastic.
GenAI link: LLMs train with very large batches, often millions of tokens per step, spread across thousands of GPUs. Each GPU computes a gradient on its own slice, then the gradients are averaged. It's mini-batch gradient descent at scale.
Next: giving the search a memory.
Momentum and Adam
- Plain gradient descent has no memory. It crawls across flat areas and zig-zags in narrow valleys.
- Momentum keeps a running velocity:
v←βv+(1−β)∇f(w),w←w−αv
- Adam also scales each parameter's step by how steep that direction has been. It's the default for neural networks.
Notes · slide 10
Say: Plain gradient descent forgets each step. It crawls across flat ground and zig-zags in narrow valleys. Momentum keeps a running velocity, like a ball rolling downhill. Consistent directions build speed. Oscillations cancel out.
Say: Adam adds a step size per parameter. Weights with big recent gradients take smaller steps. Weights with small ones take bigger steps. That makes it less sensitive to the starting learning rate.
Key line: Adam is the default for neural networks.
GenAI link: Adam, and its variant AdamW, train almost every LLM. AdamW applies weight decay separately from the gradient step. Adam keeps two running averages per weight, so its state is twice the size of the model. That's a large part of the training memory.
Next: when not to write the loop yourself.
When to use scipy instead
- For small, smooth problems on the full dataset,
scipy.optimize.minimizeis faster and more reliable than a hand-written loop. - Its L-BFGS-B solver uses curvature, not only slope.
- It doesn't replace mini-batch gradient descent for neural networks. It needs exact, low-noise gradients.
Notes · slide 11
Background, the problem: every training problem tonight has the same shape. Find the parameter values that make one number, the loss, as small as possible. In the worked example later, the parameters are a regression's two weights. The loss is the mean squared error of the predictions against the data.
Background, what minimize does: you give it three things. A Python function that takes the parameters and returns the loss. A starting guess. And, ideally, a function that returns the gradient. If you leave the gradient out, it estimates one by nudging each parameter in turn, which is slower. It searches for the lowest loss and returns the best parameters it found, the loss there, the number of iterations, and whether it succeeded.
Background, L-BFGS-B: plain gradient descent only knows the slope, so you must choose a step size. L-BFGS-B also estimates the curvature, how fast the slope is changing, from its last few gradients. Curvature tells it how far away the bottom is, so it chooses its own step sizes. There's no learning rate to tune. "Limited memory" means it keeps only those last few gradients, so it works with thousands of parameters. The "B" means it accepts bounds, such as a weight that must stay positive. On the worked example's bowl-shaped loss, it reaches the bottom in 2 iterations.
Say: For small, smooth problems on the full dataset, use scipy.optimize.minimize. Its L-BFGS-B solver uses curvature as well as slope, so it takes far fewer steps. Curve fitting, statistical models, a handful of parameters.
Say: It doesn't replace mini-batch descent for neural networks. It needs exact gradients, and mini-batch gradients are noisy. The noise also helps neural networks escape saddle points. And the data rarely fits in memory.
Ask: "A colleague wants L-BFGS-B for a 50-million-parameter network because it was fast on a toy. What do you say?"
Next: when gradient descent finds the right answer.
Convex and non-convex
- Convex: one bowl, one lowest point. Gradient descent with a small enough step reaches it. Logistic regression is convex.
- Non-convex: several valleys. Gradient descent can stop in a shallow one and think it's done.
- For large neural networks, the minima found this way tend to generalise well anyway. That's an observation, not a guarantee.
Notes · slide 12
Say: A convex loss is a single bowl. With a small enough step, gradient descent reaches the bottom. Logistic regression and MSE regression are convex. Too large a step still diverges.
Say: Neural network losses aren't convex. There are many valleys and saddle points. Gradient descent finds a good minimum, not provably the best.
Key line: for large networks, the minima found tend to generalise well. That's an observation, not a theorem.
Common question: "Why is a bowl called convex, not concave?" The intuition is right about the shape. The name comes from a different viewpoint.
- Everyday "concave" describes a surface from where you look. The inside of a bowl curves away from you, so it's concave from above. A concave lens is the same idea.
- Mathematical "convex" describes a set: the region on or above the graph. A set is convex if the straight line between any two points in it stays inside it. Fill a bowl with water and that region has no dents: any two points in the water join by a line through the water. So the function whose graph is the bowl is called convex.
- An equivalent test on the curve itself. Pick any two points on the graph and draw the straight line between them. For a convex function, the line always sits on or above the curve. For x2, the line from (−1,1) to (1,1) sits at height 1, above the curve's bottom at 0.
- Concave is the upside-down version. It's a hill, like −x2, and the region below the graph is the convex set. Maximising a concave function is the same problem as minimising a convex one. That's why optimisation books mostly talk about convex losses.
- School calculus adds to the confusion. It calls a bowl "concave up" and a hill "concave down". Concave up is the same as convex.
A memory aid: convex has a v in it, and a v is a bowl shape. Some teachers use "concave down looks like a cave" for the hill.
GenAI link: An LLM's loss surface is non-convex, with billions of dimensions. Research suggests a surprise: in very high dimensions, most points where the gradient is zero are saddle points, not poor local minima. Some direction almost always still goes down. That's part of why gradient descent works on such large models at all.
Next: what that looks like.
A loss surface with two dips

Gradient descent rolls into the dip nearest its start. On a non-convex surface, the start decides the answer.
Notes · slide 13
Say: Two valleys. The deep one on the left is the global minimum. Start on the right and gradient descent rolls into the shallow dip. Every direction from its floor goes up, so it stops, sure it's done.
Key line: on a non-convex surface, the starting point decides the answer.
Ask: "How would you guard against this?" Listen for: random restarts from several starting points, and momentum to roll through small bumps.
GenAI link: Random restarts don't scale to LLMs. One training run can take months. Careful starting weights, momentum, and mini-batch noise keep the search moving instead. Runs with different random seeds still end at different weights, with slightly different behaviour.
Next: the worked example.
Worked example, stage 1: a parabola
f(x)=x2, starting at x=3, with α=0.2.
| Step | x | f(x) |
|---|---|---|
| 0 | 3.000 | 9.0 |
| 3 | 0.648 | 0.42 |
| 7 | 0.084 | 0.0071 |
| 20 | 0.00011 | 1.2×10−8 |
Each step multiplies the distance to the minimum by 1−2α=0.6.
Notes · slide 14
Say: The simplest case. f(x) = x², starting at 3, learning rate 0.2. The derivative is 2x. Each step multiplies x by 1 − 2α, which is 0.6. So 3, then 1.8, then 1.08. By step 20, x is about 0.0001.
Ask: "What happens with α = 1.1?" Listen for: the factor is −1.2. x flips sign and grows each step. It diverges. That's Exercise 4.3.
Key line: the learning rate sets the shrink factor. Push it past the limit and the shrink becomes growth.
Next: a real regression.
Worked example, stage 2: real regression
- 200 rows, one feature, full-batch gradient descent at α=0.1.
- The loss falls from 6934.10 to 406.52 by epoch 40, then stops.
- Gradient descent, the normal equations, and sklearn all give w=[−0.690,80.790]. Convexity guarantees they agree.
- Why not 0? The data was made with noise of standard deviation 20, and 202=400.
The lowest loss is the noise floor, not zero.
Notes · slide 15
Say: 200 rows, one feature, standardised, with a bias column. Full-batch gradient descent at 0.1. The loss falls from 6934.10 to 406.52 by epoch 40, and stays there.
Say: Then the check. The normal equations from last week and sklearn give the same weights to six decimal places.
Key line: iterative search and exact algebra find the same optimum. Convexity guarantees it.
Say: Now the question most people skip. Why does the loss stop at 406.52 and not 0? The dataset was generated with random noise of standard deviation 20. Squared, that's 400. Take the square root of 406.52 and you get about 20.2. The model's typical error is the noise. No straight line through this feature can predict the noise, so no line can do better.
Key line: every problem has a floor set by what the features can't explain. Knowing roughly where it is tells you when to stop improving the model.
Ask: "A more flexible model gets the training loss down to 150 on this data. Good news?" Listen for: no. It's fitting the noise, so it will do worse on new data. That's overfitting, later in the course.
Say: One more detail made this run smooth: the feature was standardised. That makes the loss bowl round, so one learning rate suits every direction. The lab shows what happens without it.
GenAI link: Convexity is why the three methods agree here. An LLM has no such guarantee. Two runs with different seeds end at different weights, though they often reach a similar loss. LLMs have a loss floor too. The scaling-law fits in DeepMind's 2022 Chinchilla paper include a fixed term that no amount of model size or data removes: the uncertainty in text itself. A next word is often not predictable, even in principle.
Next: what the learning rate does.
Worked example, stage 3: three learning rates
| α | After 100 epochs |
|---|---|
| 0.001 | 4797.88. Nowhere near 406.52 |
| 0.1 | 406.53 by epoch 30 |
| 1.5 | Past 108 by epoch 10. Diverged |
scipy's L-BFGS-B reaches the same answer in 2 iterations: 5 gradient evaluations against gradient descent's 30, and about 0.16 ms against 0.3 ms.
Notes · slide 16
Say: Same problem, three learning rates, 100 epochs. At 0.001 the loss has only crawled to 4797.88. Too small isn't safe. It's slow. At 0.1 it's converged by epoch 30. At 1.5 it's past 10⁸ by epoch 10. Divergence, not a bug.
Say: scipy's L-BFGS-B gets the same answer in 2 iterations. For a 2-parameter smooth problem, use the curvature-aware solver. Those 2 iterations used 5 gradient evaluations. Gradient descent used about 30 to get within 0.01 of the lowest loss.
Say: On the clock, both finish in under a millisecond: about 0.16 ms for scipy and 0.3 ms for 30 epochs, measured on one desktop CPU. Times vary by machine. The gradient count doesn't. The clock gap, about 2 times, is smaller than the gradient gap, 6 times, because scipy has a fixed setup time per call. On data this small, neither matters. When one gradient takes minutes over a large dataset, 5 against 30 is the difference that counts.
Lab: check your gradient numerically before training. A sign error otherwise costs an hour. Also watch what happens without feature scaling.
GenAI link: At LLM scale, you can't try three learning rates on the full model. One run is too slow to repeat. Teams tune the learning rate on small models and carry it over to the large one, using methods designed so the best value transfers across sizes.
Next: the chapter in one idea.
Mental model
Training is hiking downhill in the dark.
- You only know which way is down from where you stand.
- Gradient descent takes a step that way.
- The learning rate is the step size.
- Adam adapts each direction's step to how steep it has been.
- The chain rule works out "which way is down" through many layers.
Notes · slide 17
Say: Training is hiking downhill in the dark. You only know which way is down from where you stand. Gradient descent takes a step that way. The learning rate is the step size. Adam adjusts each direction's step to how steep it has been. The chain rule works out which way is down through many layers.
Key line: gradient descent is how we minimise. The loss is what we minimise. Don't mix them up.
GenAI link: Training an LLM is the same hike, in billions of directions at once, for months.
Next: check yourself.
Check yourself
- Your loss goes up every epoch. What do you change first?
- Why is MSE a poor loss for classification?
- What does backpropagation compute?
- When would you use
scipy.optimizeover gradient descent?
Notes · slide 18
Do: pairs, three minutes, then take answers.
Answers: 1. Lower the learning rate. 2. Cross-entropy matches the Bernoulli likelihood and punishes confident mistakes hard. MSE doesn't (more next week). 3. The gradient of the loss for every weight, using the chain rule. 4. Small, smooth problems that fit in memory.
Lab: make the numerical gradient check the first checkpoint. Learners who skip it lose an hour to a sign error. Let them see unscaled features make gradient descent diverge before you explain why.
GenAI link: a bonus question. "Your fine-tuning loss suddenly jumps. What do you check first?" Listen for: the learning rate. Lower it, or add a warm-up.
This week
- Read Chapter 4: Maths Foundations: Calculus & Optimisation.
- Take the Chapter 4 quiz.
- Run the notebooks: Chapter 4 (opens in a new tab).
- Optional: the further reading for week 3.
Slide 1 of 19: Calculus and optimisation
Keys: → or Space next · ← back · Home/End · F full screen · N notes. Swipe on touch screens. "Save as PDF" opens the print dialog with one slide per page: choose "Save as PDF" as the printer. "Print handout" adds the speaker notes, in black on white.