Say you're building the arrival estimate for a delivery app. You have three past orders: 1 km took 12 minutes, 2 km took 15, and 3 km took 20. You guess a rule, minutes = 3 × km + 5, which predicts 8, 11 and 14 minutes. Every one of those is too short, so the rule needs fixing.
That rule is a model, a formula that turns an input (kilometres) into a prediction (minutes). It has two numbers in it, the 3 and the 5, which are called its parameters. Read as a line, the 3 is how many minutes each extra kilometre adds (the slope) and the 5 is what a zero-kilometre trip would take (the intercept). Fixing the model means changing those two numbers, and that raises three questions in a fixed order. First, how wrong is the rule, as one number? You can't tell whether a change helped unless you can score it. Second, which way should the 3 and the 5 move? You could nudge each one and watch the score, but a model with a billion parameters would need a billion extra tries for every step. Third, how far should they move? Too little and learning crawls, and too far makes the next guess worse.
A quieter question hides behind the first one. We'll start by squaring each miss and averaging the squares, but why square? If the target were yes or no ("will this order be late?"), would squaring still be a good score? It wouldn't, and seeing why takes probability.
Each question belongs to a branch of math you may have met separately. Linear algebra computes all the predictions at once, calculus finds the direction, probability and information theory decide what "wrong" should mean and turn it into a score, and optimization chooses the step. Section 01 lays out the loop these pieces form, sections 02 to 06 build the pieces on the delivery model with numbers you can check on paper, and section 07 follows the model onto a fourth order it hasn't seen. Those same stages train a linear regression in scikit-learn and a GPT-style language model, so the rest of the site stands on this chapter.
01The loop on three orders
Let's run the guess once, slowly, before any theory. Our model says minutes = 3 × km + 5, so for the three orders it predicts 3·1 + 5 = 8, 3·2 + 5 = 11 and 3·3 + 5 = 14 minutes. Against true times of 12, 15 and 20, the predictions miss by −4, −4 and −6, where a negative miss means the prediction was too short.
Three separate misses are awkward to judge, because a change that helps one order can hurt another. We want one number. Squaring each miss makes them all positive and makes big misses count for more than small ones, and averaging the squares gives (16 + 16 + 36) / 3 ≈ 22.67. That number is the loss, a score for how wrong the model is, and lower is better. We chose squaring out of habit, and section 04 explains when it's the right choice and what to use when it isn't.
Why does the score have to be a single number?
Because "downhill" needs one hill. Score a model on accuracy and speed at once and a change can help one while hurting the other, which leaves no single direction to move in. So training collapses its goals into one number. If you care about two things, you add them together with a weight, and picking that weight is your call.
With a loss in hand, fixing the model turns into a routine we repeat. We predict with the current parameters, score the predictions with the loss, work out which way each parameter should move to lower the loss, and take a small step that way. Repeating this until the loss stops falling is called training, and one pass through it is a training step. On our orders, a single step moves the 3 to 4.0 and the 5 to about 5.47, which drops the loss from 22.67 to 5.06. After 300 steps the loss is 0.223, against a best possible 0.222 for any straight line. We'll derive every one of those numbers over the next five sections.
A language model trains with the same loop. Its model is far bigger and its score is different, but each step still predicts, scores, finds a direction and moves. Each part of the loop leans on a different branch of math, and none of them was invented for deep learning. Bayes' theorem, which updates a belief when evidence arrives, was published in 1763 after Thomas Bayes' death, communicated to the Royal Society by Richard Price, and it's where the idea of priors acting as regularizers comes from. Cauchy described steepest descent in 1847 for solving systems of equations, and it's the ancestor of gradient descent. In 1948 Shannon's "A Mathematical Theory of Communication" defined entropy, and cross-entropy and mutual information grew out of it. Rumelhart, Hinton and Williams popularized backpropagation in 1986, although the chain rule it rests on is centuries older, and it gets every gradient in a network from one backward pass. Kingma and Ba published Adam in 2014, and together with a variant called AdamW it's the optimizer behind most large models. Each of those names gets explained in its own section.
Every loop starts with a prediction, and a million orders won't fit in your head the way three do. So we begin with how to hold the data and compute every prediction at once.
02Linear algebra: all the predictions at once
A GPU (the graphics chip that trains most models) is only fast on numbers laid out in regular arrays, and linear algebra is the bookkeeping for those arrays, plus a few facts about them that turn out to control how training behaves. We'll meet the bookkeeping first, on the three orders.
2.1 Vectors, matrices, and one product
A vector is a list of numbers, a matrix is a table of them, and a tensor is the same idea with any number of axes. A batch of colour images, for instance, is a 4-D tensor of shape (batch, height, width, channels). For the delivery model we put the orders in a matrix with one row per order, holding the distance and a 1. Likewise the two parameters become a vector (theta) holding the slope and the intercept. Multiplying by gives every prediction in one go:
Look at the first row, 1·3 + 1·5 = 8. Each prediction is a dot product of one row of with , which means multiplying the two lists entry by entry and adding up the products. The column of ones is there so the intercept becomes one more weight in that dot product, and then every formula below treats the two parameters alike. Nothing about the recipe changes when there are a billion rows instead of three. Next we need a way to turn the three misses into one number.
2.2 Norms: the size of a miss
Predictions minus targets gives the error vector . A norm measures how big a vector is, and two of them come up constantly. First comes the L2 norm, , the ordinary length you'd measure with a ruler, so here it's . Then there's the L1 norm, , which adds up the absolute values and gives 14.
Now look back at the loss from section 01. Mean squared error is the squared L2 norm divided by the number of examples, , so the score we've been using is a norm in disguise. Put the parameters inside the same norms and you get L2 and L1 regularization, penalties that discourage large parameters, and section 04 shows where each comes from.
Dot products also measure alignment. Divide one by both vectors' lengths, , and you get the cosine similarity, a number from −1 to 1 that says how closely the two point the same way. A projection uses the same quantity to ask how much of one vector lies along another. Attention (08) is built on this: a large dot product between a query and a key means "this token is relevant to me".
2.3 Eigenvectors, SVD and PCA
One more fact about the data matrix will matter in section 06, when we ask how far to step. Most matrices rotate and stretch whatever they multiply. An eigenvector of a matrix is a direction that the matrix only stretches without turning it, written , and the stretch factor is its eigenvalue. For the delivery data, the matrix that matters later is , the transpose of (rows and columns swapped, written ) multiplied by :
The eigenvalues of a 2×2 matrix come from its trace, the sum of the diagonal, 17, and its determinant, . They work out to about 16.64 and 0.36, so one direction is stretched 46 times more than the other. Section 06 shows that this ratio is why even this tiny model needs hundreds of steps.
SVD (singular value decomposition) extends the idea to any matrix, writing it as , a rotation, a scaling and another rotation. PCA (principal component analysis) is SVD applied to data after subtracting each feature's mean. The directions the data varies along most are the top eigenvectors of its covariance matrix (section 04 defines that), so projecting onto the first few gives the best linear summary of the data in fewer dimensions.
A ratio of 46 looks like something we should be able to fix. If we subtract the mean distance, 2 km, from every input, becomes , a ratio of 1.5 instead of 46. That one preprocessing line is why pipelines routinely centre or standardize their inputs, and section 06 shows it cutting convergence from 48 steps to 3.
We can now compute predictions and a loss for any pair of parameters. What we still lack is a direction, since the loss tells us we're wrong without saying whether to raise the 3 or lower it. Finding that direction is the job of calculus.
03Calculus: which way to move
We have a score and two knobs. Calculus tells us how the score changes when we turn each knob slightly, without trying every setting.
3.1 Derivatives and the gradient
A derivative is a local slope, and you can measure one directly. Raise the slope parameter from 3 to 3.001 and the loss goes from 22.66667 to 22.64667. That's −0.02 for a change of 0.001, so the loss falls by about 20 for each unit of . Calculus gives the exact answer without any trial. With the miss on order written (prediction minus target, where is the distance and the intercept) and the loss , the slope of the loss with respect to is below, and the intercept's version follows the same pattern.
The first line says each miss is weighted by its distance, which makes sense: a miss on a long trip is more sensitive to the slope. A partial derivative is a derivative that holds every other input fixed (that's what the symbol signals). Stacking the partial derivatives for all the parameters gives the gradient, here . In matrix form it's , and gives the same numbers.
Why walk against the gradient?
Since the gradient points where the loss rises fastest, its negative points where the loss falls fastest, at least for a small step. Both components are negative here, so both parameters should go up, and that fits what we saw: every prediction was too short.
3.2 One gradient step by hand
The update subtracts the gradient times a learning rate (eta), a small number we choose that sets the step size. With :
The predictions become 9.47, 13.47 and 17.47, and the loss falls from 22.67 to 5.06, so one step removed 78% of the error. That pace doesn't last, as the table shows for the first 300 steps.
| Step | Slope w | Intercept b | Loss |
|---|---|---|---|
| 0 | 3.00 | 5.00 | 22.67 |
| 1 | 4.00 | 5.47 | 5.06 |
| 5 | 4.74 | 5.90 | 0.67 |
| 50 | 4.45 | 6.65 | 0.37 |
| 300 | 4.02 | 7.62 | 0.223 |
| best fit | 4.00 | 7.67 | 0.222 |
Watch the slope. It reaches the best-fit value, 4.0 (last row), after one step, overshoots to 4.74, and takes hundreds of steps to come back. Those two parameters are coupled: while the intercept is too low, a steeper slope is the fastest way to lengthen the predictions, so the slope runs ahead of where it belongs and has to be pulled back as the intercept slowly catches up. Section 06 explains the slow tail.
Here's code that repeats the update 300 times and prints the rows of that table, plus the gradient at each of them. X.T @ e is the matrix form of the gradient from the last subsection, and the final line of the loop is the update itself.
Try it Gradient descent on the delivery model, 300 steps
import numpy as np
km = np.array([1.0, 2.0, 3.0])
minutes = np.array([12.0, 15.0, 20.0])
X = np.column_stack([km, np.ones(3)]) # second column of ones: intercept
theta = np.array([3.0, 5.0]) # slope, intercept
eta = 0.05 # learning rate
for step in range(301):
e = X @ theta - minutes # error vector
loss = (e ** 2).mean()
grad = (2 / 3) * X.T @ e # (2/n) X^T e, with n = 3
if step in (0, 1, 5, 50, 300):
print(f"step {step:3d} w={theta[0]:.2f} b={theta[1]:.2f}"
f" loss={loss:.3f} grad={np.round(grad, 2)}")
theta = theta - eta * grad # step against the gradient
22.667, 5.062, 0.671, 0.371 and 0.223. The gradient column is new. It starts at [-20, -9.33], the slope's entry is positive (0.11) at step 50, and by step 300 both are about 0.01 in size.Look at the gradient column. It starts at -20 for the slope and shrinks as the loss falls, so the steps get smaller on their own. By step 50 the slope's gradient has turned positive, 0.11, which says the slope is now too high and is being pulled back. That's the overshoot from the table. At step 300 both gradients are about zero, so the updates have almost stopped, and the loss of 0.223 sits just above the best possible 0.222.
3.3 The chain rule is backpropagation
Our model is one line, so we could differentiate it on paper. A neural network is a model built from layers, where each layer takes a weighted sum of its inputs, passes it through a fixed nonlinear function called an activation, and hands the result to the next layer. That makes it formulas nested inside formulas. To differentiate through the nesting we use the chain rule, . For one weight, through whatever sits between it and the loss, the derivative is a product of local derivatives:
Here ("y-hat") is the model's output and is the layer's weighted sum before the activation is applied, called the pre-activation. Each layer in between adds one more factor to the product. In the diagram below we follow the slope of the delivery model, going forward to compute and keep each value and then backward to multiply the local derivatives.
- ForwardCompute and keep each value. Order 1:
ŷ = 3·1 + 5 = 8, errore = −4. - ForwardLoss from all three errors:
(16 + 16 + 36) / 3 = 22.67. - Backward · loss → errorThe derivative of
e²/3is2e/3: −2.67 for order 1. - Backward · error → prediction
e = ŷ − y, so this link is 1. - Backward · prediction → weight
ŷ = wx + b, so this link isx = 1. Order 1 contributes −2.67. - Sum over examplesOrders 2 and 3 add
−2.67 × 2and−4 × 3. Total: −20, matching the direct formula.
Doing that for every weight at once, layer by layer, and reusing what the forward pass computed, is backpropagation. Those forward values have to be kept because every local derivative needs them: the first backward step needs , and an activation's derivative needs the activation's own output. Caching them keeps the backward pass cheap. It's also why training needs far more memory than inference, since every layer's activations must survive until the backward pass reaches them.
3.4 Jacobians, Hessians and curvature
When a function outputs a vector, its derivative is a matrix of partial derivatives, the Jacobian. Differentiate once more and the matrix of second derivatives is the Hessian, which describes curvature. If all its eigenvalues are positive the surface is a bowl, mixed signs make a saddle, and all negative makes a peak.
Our delivery loss has a constant Hessian, , with eigenvalues of about 11.09 and 0.24. Both are positive, so the loss is one bowl, but a long, narrow one. Section 06 turns those two eigenvalues into a speed limit.
3.5 Why deep chains vanish or explode
The chain rule multiplies one factor per layer. Factors a bit below 1 shrink the product toward zero on its way back to the first layers, and factors above 1 blow it up. A sigmoid, the S-shaped function that squashes any number into the range 0 to 1, has a derivative that is never larger than 0.25. So across ten sigmoid layers, the activation derivatives alone multiply a gradient by at most . A factor of 1.5 per layer gives instead. That's why plain deep networks and long unrolled RNNs (recurrent networks, which reuse one layer over a sequence) were hard to train. Residual connections, careful initialization and normalization are the fixes, covered in 04 · Neural Network Fundamentals.
Everything in this section differentiated squared error. We picked squared error by habit. Whether it's the right score depends on what the data looks like, and that's a question for probability.
04Probability: what "wrong" should mean
Squaring the misses was a guess, though a reasonable one. Probability tells us when it's the right guess, what to use when it isn't, and how to reason about a model's outputs once it exists.
4.1 A loss is a likelihood in disguise
Suppose the real delivery time is our line plus random noise, and the noise follows a Gaussian distribution, the familiar bell curve, where small deviations are common and large ones are rare, with a spread we'll call (sigma). Under that assumption, any choice of parameters makes the observed delivery times more or less probable. Call that probability the likelihood: how probable the observed times are under a given . Maximum likelihood estimation (MLE) picks the that makes them most probable. To compare candidates it's easier to take the negative log of the probability, and for one Gaussian observation that is:
The first term is the squared miss, scaled by the noise spread. That second term has no in it, so it can't change which wins. What's left is squared error: mean squared error is maximum likelihood under Gaussian noise, and that's the assumption you make whenever you use it.
Why take the log?
A dataset's likelihood is a product, one probability per example. A thousand examples at 0.5 each give , near the bottom of what a 64-bit float can hold, and two thousand underflow to zero. Taking the log turns the product into a sum, , which differentiates term by term. A log only ever increases, so the maximum stays where it was.
4.2 Yes-or-no targets
Now ask "will this order be late?". Here the label is 0 or 1, and Gaussian noise around a 0/1 label makes no sense, because the label can't be 0.4. So the model computes a raw score , called a logit, and passes it through a sigmoid to get a probability, . For a yes/no outcome the natural choice is the Bernoulli distribution, one trial with probability of yes, and its negative log-likelihood is:
Only one of the two terms survives for any given label, so the loss is the negative log of the probability the model gave to the right answer. This is binary cross-entropy, and it falls out of maximum likelihood once the target is binary. With more than two classes the sigmoid generalizes to a softmax, which exponentiates each class's score and divides by the total so the outputs are positive and sum to 1. Section 05 shows how differently cross-entropy behaves from squared error when the model is confidently wrong. We've now used two named distributions, the Gaussian and the Bernoulli, and it helps to see the family they belong to before moving on.
4.3 The distributions you'll meet
A random variable is a quantity whose value depends on chance, like the delivery time of the next order, and its distribution says how likely each value is. Six of them are in the table below, with where each one shows up.
| Distribution | Describes | Where you meet it |
|---|---|---|
| Bernoulli | One yes/no trial | A binary label; a sigmoid output |
| Categorical | One trial, K outcomes | A softmax output; next-token prediction |
| Multinomial | Counts over many categorical trials | Bag-of-words counts |
| Gaussian | A continuous value around a mean | The default continuous assumption (Central Limit Theorem), and the one behind MSE |
| Poisson | Counts of rare, independent events per interval | Requests per second on a server |
| Exponential | Waiting time between those events | Memoryless: waiting five more minutes doesn't depend on how long you've waited |
4.4 Expectation, variance, covariance
Three numbers summarize a distribution or a dataset. Expectation is a probability-weighted average. Variance, , is the spread around that average, measured as the average squared distance from it. Covariance is positive when two variables move together and negative when they move apart.
On the delivery data, distance has variance , and its covariance with time is . Divide one by the other, , and you get the best-fit slope. Least-squares regression, in other words, is covariance over variance. Correlation divides covariance by both standard deviations (the square root of the variance) to remove the units, and here it comes to about 0.99.
4.5 Bayes' theorem and the base rate
Conditional probability, , is how likely A is once you know B happened. Bayes' theorem turns one conditional into its reverse, and it's the place where intuition fails most often. Try one example before we write the formula.
Suppose 1% of card transactions are fraud, and your model flags 90% of fraudulent ones and wrongly flags 5% of legitimate ones. A transaction gets flagged. Roughly how likely is it to be fraud?
- About 90%
- About 50%
- About 15%
- About 5%
Show the answer
C, about 15%. Count 10,000 transactions: 100 are fraud and 90 of those get flagged, while 9,900 are legitimate and 5% of those, 495, get flagged too. Of 585 flags, 90 are fraud: .
Bayes' theorem is the count in that answer, written as a formula. Its numerator is , the fraud that gets flagged, and the extra term in the denominator is , the false alarms.
Each piece of the formula has a name:
- P(θ) the prior, the belief before the evidence: 1% fraud.
- P(D|θ) the likelihood of the evidence if the hypothesis holds: a 90% flag rate.
- P(θ|D) the posterior, the updated belief you want.
- P(D) the evidence, summed over every hypothesis: 5.85% of transactions get flagged. Over a model's parameters it's usually intractable, so approximate Bayesian inference exists.
Why so low, when the model catches 90%?
Legitimate transactions outnumber fraud 99 to 1, and 5% of a large pile beats 90% of a small one. A flag is 18 times likelier on fraud (0.9 against 0.05), which turns prior odds of 1 to 99 into 18 to 99. Raise the prior to 10% fraud and the same flag means 67%. Nothing about the model changed, only the population.
That has a practical consequence. Precision, the share of flags that are fraud, depends on the base rate, while recall, the share of fraud that gets flagged, doesn't. A fraud model tested on a balanced set will report far higher precision than it gets in production, so evaluate at the class balance you'll deploy into.
4.6 MLE, MAP, and where regularization comes from
Bayes' theorem lets us put a belief about the parameters into the loss, and what people call "training" uses it in one of three amounts. MLE ignores the prior and maximizes , so unregularized loss minimization is MLE. MAP (maximum a posteriori) maximizes , and a Gaussian prior on the weights gives L2 regularization while a Laplace prior (a distribution with a sharper peak at zero) gives L1. Full Bayesian inference keeps the whole posterior, so predictions carry uncertainty, at a much higher computing cost.
Showing the L2 link takes two lines. A zero-mean Gaussian prior with spread has . Add it to the negative log-likelihood from 4.1 and multiply through by :
That's weight decay with , a penalty on the size of the weights. A narrower prior, meaning a stronger belief that weights are small, gives a bigger penalty.
4.7 Intervals and tests
A confidence interval is a range of plausible values built from data at a chosen confidence level, and hypothesis testing asks whether an effect is surprising enough to reject a "nothing's going on" baseline. A common mistake is to read a 95% interval as "a 95% probability the true value is in this range". That 95% describes the procedure: repeat the experiment many times and about 95% of the intervals would contain the true value. Any single interval either does or doesn't.
We've now argued that the loss for a yes/no label should be the negative log of the probability the model gave to the right answer. Information theory explains why that quantity is a natural price for being wrong, and how to compare two whole distributions.
05Information theory: entropy, cross-entropy and KL
Section 04 ended with a loss of for the right answer. To see why that's natural, we first need a way to put a number on how surprised a model should be.
5.1 Entropy: average surprise
Shannon measured the surprise of an outcome with probability as . A certain outcome has no surprise, and a one-in-a-hundred outcome costs about 6.6 bits. Entropy is the average surprise over all the outcomes of a distribution, . A coin that always lands heads has an entropy of 0 bits. A 90/10 coin has 0.47 bits, and a fair coin has 1 bit, the maximum for two outcomes.
With the unit is the bit. Deep learning libraries use the natural log, so their losses are in nats (one nat is about 1.44 bits), and the minimum sits in the same place either way.
5.2 Cross-entropy and KL divergence
Entropy assumes we score each outcome with its true probability. A model doesn't know the true probabilities, so it scores outcomes with its own guess . We define that average as the cross-entropy and compare it with the entropy:
Cross-entropy is the average surprise when outcomes come from but you score them with your model's . Whatever it costs beyond is the KL divergence. Take the 90/10 coin with a model that believes 80/20: bits against , so the model's mistake costs 0.053 bits per flip.
is a property of the data that no model changes, so minimizing cross-entropy and minimizing KL are the same optimization problem. That's the case for cross-entropy as a loss. Two derivations below make that precise: the first shows that maximum likelihood turns into cross-entropy, and the second shows why KL can never be negative.
Derivation Where cross-entropy comes from, and why it equals KL
Cross-entropy is what maximum likelihood turns into once your model outputs a distribution over classes.
-
Where we start: maximum likelihood. Two things are assumed, not derived: that MLE is the right principle, and that examples are independent, which licenses writing the joint probability as a product.
-
Why this is legal: is strictly increasing, so it can't move a maximum. The product becomes a sum, which doesn't underflow and differentiates term by term. That's what makes mini-batch gradients possible.
-
Why: negating turns a maximisation into a minimisation, because optimisers descend. The is convention; it makes the number comparable across batch sizes and doesn't move the argmin.
-
Why this changes nothing numerically: is the one-hot label. Every term but the true class is multiplied by zero, so the right side collapses to the left. The point is to rewrite it in a shape you recognise.
-
Why: that's the definition of . Cross-entropy was never chosen as a loss. It's what maximum likelihood already was, written out.
-
Why: expand KL. . Rearrange.
-
Why: contains no . Adding a constant to an objective shifts its value but never its argmin.
Derivation Why KL divergence can never be negative
Everything above leans on . The same fact makes the ELBO on 12 a true lower bound and not just an approximation.
-
Why: , and a sum weighted by is an expectation under .
-
Why: Jensen's inequality. is concave (its second derivative, , is negative), and for a concave function the expectation of the function is at most the function of the expectation.
-
Why: the cancel, leaving the total mass of . This is the one step that needs to be a normalised distribution.
-
Why: steps 1 to 3 say the negative of the divergence is at most zero. Multiply by and the inequality flips.
-
Why: Jensen is tight only when the quantity inside is constant. Here that forces to be the same for every , and since both sum to one, the constant is one.
KL is asymmetric. On the same coins, bits, where the other direction gave 0.053. So it isn't a true distance, and which side you call "true" changes what gets penalized. Section 09's project makes that visible. Both quantities run through modern ML. GPT-style pretraining is cross-entropy on the next token. KL is the VAE's pull toward its prior (12), the penalty that keeps an RLHF policy near its reference model (15), and the target in knowledge distillation.
5.3 Cross-entropy against squared error at p = 0.01
Back to the late-delivery classifier. An order was late () and the model said . Our model is confidently wrong, so which loss pushes harder to fix it? To find out, differentiate each with respect to the logit , using the sigmoid's derivative . Cross-entropy comes first, then squared error:
Compare the two lines. Notice that the sigmoid's derivative is nearly zero when is near 0 or 1, and squared error keeps that factor, so its gradient vanishes exactly when the model is confidently wrong. In cross-entropy, the that comes from the log cancels the factor, and only the miss is left. At , cross-entropy gives , while squared error gives . Cross-entropy pushes roughly 50 times harder, at the moment the model most needs it.
| p on the true class | Cross-entropy | Its gradient | Squared error | Its gradient |
|---|---|---|---|---|
| 0.01 (confidently wrong) | 4.61 | −0.99 | 0.98 | −0.020 |
| 0.1 | 2.30 | −0.90 | 0.81 | −0.162 |
| 0.5 (unsure) | 0.69 | −0.50 | 0.25 | −0.250 |
| 0.9 | 0.105 | −0.10 | 0.010 | −0.018 |
| 0.99 (confidently right) | 0.010 | −0.01 | 0.0001 | −0.0002 |
Squared error's gradient is largest at (about −0.30) and fades toward both ends. Cross-entropy's gradient is the size of the miss, and with a softmax over many classes it has the same form, , the predicted probabilities minus the one-hot target. Below, the curve plots the cross-entropy loss itself, and you can see it climb without limit as the probability on the true class falls toward 0.
5.4 Computing it without overflowing
Softmax, , uses exponentials, and exponentials get large fast. Feed it scores of 1000 and 999 and overflows, since a 64-bit float tops out near and a 32-bit float near .
Shifting every score by the same amount doesn't change a softmax, so we subtract the largest score first. (1000, 999) becomes (0, −1), giving probabilities of 0.731 and 0.269. Log-softmax does this and takes the log in one fused step, returning −0.313 and −1.313 directly, so it never computes . This leads to a common mistake: passing probabilities to a loss that expects scores. PyTorch's F.cross_entropy takes raw logits and applies log-softmax itself, so if you put a softmax layer in front of it you apply softmax twice. It still trains, but its gradients are squashed and the reported loss is wrong.
5.5 Mutual information
Mutual information, , is how much observing reduces your uncertainty about , and it's zero for independent variables. A good representation, roughly speaking, keeps high mutual information with what you care about and drops nuisance variation. Self-supervised objectives (03) are different ways of chasing that.
That settles what to score with. What's left is the step itself: how far to walk along the gradient, and what to do when the direction keeps changing.
06Optimization: how far to move
Calculus gave us a direction but not a distance, and the direction itself changes as we move. Our delivery model already shows both problems, and we'll take them in turn.
6.1 How big a step?
Section 03's update rule gets repeated at every step, with the parameters at step and the gradient of the loss with respect to them:
So far we've used a learning rate of 0.05 and made steady progress. Before we derive what limits it, try guessing what happens when it's larger.
Section 3.2 used η = 0.05. Run the delivery model again with η = 0.17, then with η = 0.19. What happens to the loss?
- Both converge, and 0.19 converges faster
- 0.17 converges; 0.19 bounces forever at the same height
- 0.17 converges after zigzagging; 0.19 grows without limit
- Both diverge
Show the answer
C. At η = 0.17 the slope bounces 6.4, 3.3, 6.0, 3.6 while the loss falls from 22.7 to 7.1 in five steps, and reaches 0.23 by step 50. At η = 0.19 the loss goes 27.6, 33.7, 41.1 and passes 600,000 by step 50. The cut-off is 0.180.
To see why the answer is C, picture a loss shaped like a bowl. Along each eigenvector of the Hessian, the error is multiplied by at every step, where is that eigenvector's eigenvalue. If the size of that factor is below 1 the error shrinks, and if it's above 1 the error grows.
Along the steep direction of the delivery loss, . At the factor is about −0.89, so the sign flips every step (the zigzag) but the size shrinks. At it's about −1.11, and the error grows 11% per step. Divergence starts at , where is the largest eigenvalue.
Why not pick a tiny learning rate and wait?
Because the flattest direction sets the wait. Its eigenvalue is 0.24, so at the error there shrinks by only per step, roughly 83 steps per factor of e. So the steepest direction caps the learning rate, and the flattest one sets the pace. How lopsided those two curvatures are has a name, and it's the subject of the next subsection.
6.2 Why the valley zigzags
The ratio of the largest to the smallest curvature is the condition number: , the same 46 as in . A large one means a long, narrow valley, and 46 is already a bit of one. Gradients there point mostly across the valley toward the steep walls, so each step overshoots sideways and barely moves forward. In the diagram below, the contours are curves of equal loss, and the pink path is plain gradient descent bouncing between the walls.
Here's what that costs on the delivery model, counting steps until the loss is within 0.01 of its best. In the second row it's the same data with the distance centred, the preprocessing line from section 02.
| Inputs | Condition number | Steps at η = 0.05 | Steps at the best fixed η |
|---|---|---|---|
| Raw distance | 46 | 162 | 48 (η ≈ 0.167) |
| Distance minus its mean | 1.5 | 39 | 3 (η = 0.6) |
Same data, same final predictions. Centring the input changed only the shape of the bowl. Normalization layers apply a similar rescaling to activations inside a network (04). Rescaling the inputs fixes this tiny model, but a big network can't always be fixed by preprocessing, so the optimizer itself has to cope with the zigzag.
6.3 Stochastic gradients and momentum
With a billion examples, computing one exact gradient per step is far too slow. Stochastic gradient descent (SGD) estimates it from a random minibatch, a small sample of the examples. Each estimate is noisy, much cheaper, and right on average. That noise seems to help a bit too, by jostling parameters out of shallow irregularities.
Plain SGD treats each step independently, and that's what makes the zigzag. Momentum instead steps along a running sum of past gradients, so a direction that keeps repeating builds up speed:
With the usual , velocity along the valley floor, where the gradient keeps its sign, builds toward gradients' worth. Across the valley the sign flips each step and the terms cancel. Momentum, in other words, works as a low-pass filter on the gradient: it lets the steady part through and damps the part that flips back and forth.
6.4 Adam and AdamW
Momentum smooths the direction. A separate problem is that different parameters can have gradients of very different sizes, as the −20 and −9.33 on our delivery model do. Adam keeps a running average of the gradient and of its square, and uses the second to scale each parameter's step:
Here is the gradient at step , and set how quickly the averages forget old values, and is a tiny constant that keeps the division safe. is the momentum term. tracks how large each parameter's gradient has been lately, so dividing by its root gives large gradients smaller steps. Both averages start at zero, and the hats correct for that early bias.
Take the first step on the delivery model with and . After one gradient, and , so the step is , exactly per parameter whatever the gradient's size. At , Adam raises both slope and intercept by 0.1, while plain gradient descent would move them by 2.0 and 0.93. Adam has discarded the scale difference between parameters, and that's much of why it's forgiving on badly scaled problems.
AdamW changes one thing. Standard L2 regularization adds to the gradient before the adaptive division, which warps the regularization strength per parameter. AdamW subtracts from the weights directly, and it's the default in most modern recipes.
Why not always use Adam? It tolerates a poorly tuned learning rate, which matters when a model is too big for much hyperparameter search, and that's why transformers and LLMs default to it. But well-tuned SGD with momentum often matches or beats it on final accuracy for some vision architectures, and why that happens is still argued about. In practice the trade is that Adam gets a working model faster, while tuned SGD sometimes gets a slightly better one. Here are the four optimizers side by side.
| SGD | Momentum | Adam | AdamW | |
|---|---|---|---|---|
| Core idea | Step against the raw minibatch gradient | Step against a running average, damping the zigzag | Momentum plus a per-parameter step size from squared gradients | Adam, with weight decay applied to the weights directly |
| Per-parameter step | No | No | Yes | Yes |
| Learning-rate sensitivity | High; needs a schedule | Lower | Low | Low |
| Typical home | Convex problems, tuned CNN recipes | The standard upgrade in vision | Transformers, sparse or noisy gradients | Most large-model training |
6.5 Local minima and saddle points
The delivery loss is convex, a single bowl, so going downhill always finds the global minimum. Neural network losses are non-convex, with no such guarantee, but that matters less than it seems. A true local minimum needs every Hessian eigenvalue positive, and across millions of directions that's rare. Saddle points, which curve up in some directions and down in others, are far more common.
So when someone says training "got stuck in a bad local minimum", be skeptical. Slow progress across saddles and plateaus is the likelier cause of a flat loss curve. Experiments on overparameterized networks (ones with more parameters than training examples) also find that the minima SGD reaches have similar loss and generalize comparably. Why SGD lands in minima that generalize well is still an open question.
6.6 The whole loop, named
Every piece now has a name, so here's the loop from section 01 once more, with each stage labelled by the field that supplies it. It starts from slope 3 and intercept 5 and ends where the table in 3.2 ended.
- Linear algebra · predictOne matrix product gives all three predictions: 8, 11 and 14 minutes.
- Probability · choose the scoreAssume Gaussian noise on the minutes. That assumption turns into squared error.
- ScoreThe loss is 22.67. For a yes/no target the same reasoning gives cross-entropy, information theory's price for surprise.
- Calculus · differentiateThe gradient is −20 for the slope, −9.33 for the intercept. Both negative, so both should rise.
- Optimization · stepWith a learning rate of 0.05, the slope becomes 4.0, the intercept 5.47, and the loss drops to 5.06.
- RepeatAfter 300 steps the loss is 0.223. The best possible is 0.222.
All of this fitted three orders, and fitted them well. It's the fourth order that matters, and a good fit on the first three is no guarantee about it.
07Generalization, and what breaks
A model can fit the first three orders perfectly and still miss the fourth badly. Our delivery data shows how.
7.1 A perfect fit is the wrong goal
The best line has a loss of 0.222. The curve passes through all three orders exactly (12, 15, 20), so its loss is zero. Ask both about a 10 km order: the line says minutes, and the curve says 111. Three points can't say which is right, though the line is probably the safer bet. That curve has enough freedom to fit whatever those points happened to be, noise included, and the next equation calls that freedom variance.
7.2 The bias-variance decomposition
Take a model trained on a random sample of data and ask for its expected squared error at a new point. That error splits into three parts:
Each part has its own cause and its own look:
- Bias is error from a model too simple for the pattern, wrong the same way even with infinite data, and it looks like underfitting.
- Variance is error from a model too sensitive to its training sample, so predictions swing when you retrain on fresh data, and it looks like overfitting.
- σ² the noise in the data itself. No model gets below it.
Below, the derivation shows where the split comes from and what it assumes.
Derivation Splitting squared error into bias, variance, and noise
Assume , with and . The estimator is random too, because it depends on which training sample you drew. Every expectation runs over both sources of randomness.
-
Where we start: expected squared error at one point . Keeping the two kinds of randomness apart (noise in the label, noise in the training set) is most of the difficulty.
-
Why this is legal: substitute , then add and subtract . Choosing that quantity is the pivot: it separates how far the average prediction is from the truth, from how far this prediction is from the average.
-
Why: expand the squared trinomial and use linearity of expectation.
-
Why, each for its own reason: isn't random, since and are fixed numbers. So and . The third differs in kind: is noise on the test label and depends only on the training sample, so they're independent with mean zero.
-
Why: because is deterministic. is the definition of the variance of . And , since .
7.3 Regularization is one trade
Weight decay, dropout (randomly switching off units while training), early stopping (halting before training loss bottoms out), augmentation (training on altered copies of the data) and a smaller architecture all make the same bet: a little more bias for a larger cut in variance. So training loss usually gets slightly worse while validation loss, the loss on held-out data the model didn't train on, improves. An interviewer is usually checking whether you see that trade, and no single technique matters as much.
7.4 Calibration
A model can be accurate and still overconfident, and modern deep nets usually are, straight out of training. If its "90% confident" predictions are right 70% of the time, those scores can't drive a threshold or a hand-off to a human. That's miscalibration, and accuracy can't see it.
Temperature scaling is the cheap fix: divide the logits by one scalar, fitted on held-out data, before the softmax. It doesn't change which class ranks first, only how confident the model sounds. 25 · Evaluation, Reliability & Safety goes further.
7.5 Symptom, cause, fix
Most training failures show up first in the loss curve, and each row of the table traces back to a section you've already read.
| Symptom | Likely cause | Fix |
|---|---|---|
| Loss grows or turns NaN within a few steps | η above (6.1), or overflow and in a hand-written softmax (5.4) | Lower η or add warmup; clip gradients; use the fused log-softmax loss |
| Loss drops fast, then crawls | Poor conditioning (6.2) | Standardize inputs; momentum or Adam; normalization layers |
| Early layers barely change | Vanishing gradients (3.5) | ReLU-family activations, residual connections, careful init |
| Classifier learns slowly from its worst mistakes | Squared error on a sigmoid (5.3) | Cross-entropy on logits |
| Training and validation error both high | High bias (7.2) | Bigger model, better features, less regularization |
| Training error low, validation much higher | High variance (7.1) | More data, augmentation, weight decay, dropout, early stopping |
| Confidence scores don't match hit rates | Miscalibration (7.4) | Temperature scaling on a held-out set |
| 99% accuracy, rare class never caught | Imbalanced data; base rates (4.5) | Precision and recall on the rare class, at the production base rate |
Every row of that table is one stage of the loop going wrong, which gives you a way to hold the whole chapter in your head.
08Summary
- Training is one loop. Predict with a matrix product, score with a loss, differentiate with the chain rule, and step against the gradient, as we did on three delivery orders.
- One number scores the model because "downhill" needs one direction. Weighing two goals is your decision.
- Gradients are cheap. For squared error the gradient is , and in a network, backprop multiplies local derivatives and reuses the forward pass.
- A loss is a noise assumption. Squared error is maximum likelihood under Gaussian noise, and binary cross-entropy is maximum likelihood for a yes/no label.
- Cross-entropy keeps its gradient when the model is confidently wrong, about 50 times squared error's at .
- Base rates dominate Bayes. A detector that catches 90% of fraud at a 5% false-alarm rate is right 15% of the time it fires when fraud is 1%.
- Regularization is a prior. L2 is MAP with a Gaussian prior, and L1 is a Laplace prior.
- Curvature sets the learning rate. Gradient descent diverges above , and the flattest direction sets the pace.
- Conditioning is often a preprocessing problem. Centring one input took the delivery model from 48 steps to 3.
- A perfect training fit proves little. Test error is bias, variance and noise, and every regularizer trades the first for the second.
09Build this
Section 05 says KL is asymmetric and that the direction you pick changes what gets penalized, which is easy to nod at and hard to believe. Two plots settle it.
Build a target with two separated bumps. Fit a single Gaussian to it twice: once minimizing , once minimizing . Same target, optimizer and initialization; only the argument order changes. Stay in one dimension, where the fitted Gaussian has nowhere to hide.
- Lay a grid of a few hundred points across the real line. Define on it as a mixture of two well-separated Gaussians, normalized to sum to 1.
- Parameterize by a mean and a log standard deviation, evaluated on the same grid and normalized the same way.
- Write the KL sum by hand from section 05, . No
kl_div, no distribution class. Add a small floor inside the log, since the derivation needs wherever . - Minimize with Adam and plot the fitted on top of .
- Swap to , refit from the same initialization, and plot it on the same axes. Then refit starting near the other bump.
- Replace the two-bump target with a single Gaussian and fit both directions again.
10Interview questions
BeginnerWalk me through gradient descent, step by step.
Start from some parameters, usually random. Compute the loss on a batch. Use the chain rule to get the gradient of the loss with respect to every parameter; it points toward steepest increase. Step the other way, scaled by the learning rate, and repeat until the loss stops improving. Stochastic gradient descent is the same loop with the gradient estimated from a random minibatch.
BeginnerWhat's the difference between a derivative, a gradient, and a Jacobian?
A derivative is the slope of a scalar function of one variable. A gradient is the vector of partial derivatives of a scalar function of several variables, one slope per input. A Jacobian is the matrix of partial derivatives of a function that outputs a vector: every output's sensitivity to every input.
BeginnerState Bayes' theorem and explain each term.
. is the prior, the belief before the data. is the likelihood of the data under that hypothesis. is the posterior, the updated belief. is the evidence, the data's probability summed over every hypothesis, and usually the hardest term to compute. The classic trap is the base rate: at 1% prevalence, a test that fires on 90% of positives and 5% of negatives is right only about 15% of the time it fires.
BeginnerWhy do we use cross-entropy loss for classification instead of mean squared error?
Cross-entropy is the maximum-likelihood loss for a categorical target, so minimizing it maximizes the probability of the correct class. MSE is maximum likelihood under Gaussian noise, the wrong assumption for a discrete label. It also keeps a strong gradient when the model is confidently wrong: at 0.01 on the true class, its gradient on the logit is −0.99, against about −0.02 for squared error through a sigmoid.
IntermediateExplain the bias-variance tradeoff and how regularization affects each term.
Expected squared test error splits into bias squared, variance and irreducible noise. Bias is systematic error from a model too simple for the pattern (underfitting). Variance is error from a model too sensitive to its training sample (overfitting). Regularization, such as weight decay, dropout, early stopping or a smaller architecture, accepts a little more bias for a larger drop in variance. That's why it usually makes training loss slightly worse and validation loss better.
IntermediateWhat problem does Adam solve that plain SGD doesn't? What does each of Adam's moving averages track?
Plain SGD uses one global learning rate and treats steps independently, so it zigzags on badly conditioned surfaces and needs careful tuning. Adam keeps two moving averages per parameter: of the gradient, like momentum, and of the squared gradient. Dividing the first by the square root of the second gives each parameter its own step size, larger for small steady gradients and smaller for large or noisy ones. On the first step every parameter moves by the learning rate, whatever its gradient's size.
IntermediateWhat's the difference between MLE, MAP, and full Bayesian inference?
MLE maximizes the likelihood alone: unregularized loss minimization. MAP maximizes likelihood times prior, ; L2 regularization is MAP with a Gaussian prior on the weights, and L1 with a Laplace prior. Full Bayesian inference keeps the whole posterior over instead of one point, so predictions carry uncertainty, at a much higher computing cost.
IntermediateWhat's the relationship between cross-entropy and KL divergence? Why does minimizing one minimize the other?
. The entropy of the data, , doesn't depend on the model and doesn't change during training. So minimizing over the parameters and minimizing are the same problem, differing by a constant. With one-hot labels and they're equal.
DeepWhy do saddle points matter more than local minima in high-dimensional non-convex optimization?
At a critical point, the Hessian's eigenvalues decide its type. A true local minimum needs every eigenvalue positive, curving up in each of possibly millions of directions. As dimension grows that gets unlikely, and a mixed-sign Hessian, a saddle, becomes the common case. So in high dimensions training mostly slows on saddles and the plateaus around them while it searches for a direction that still curves down. A bad basin is the rarer explanation.
DeepDerive the gradient of softmax plus cross-entropy with respect to the logits, and explain why the result matters.
With logits , , one-hot target and : the softmax Jacobian is . Multiply by and sum over . The cancel and, since , . The gradient is the size of the miss. It doesn't saturate the way squared error on a sigmoid does, so the model gets its strongest correction when it's most wrong.
DeepYour model has 99% accuracy on a fraud dataset but is badly miscalibrated. How would you diagnose and fix that, and why didn't accuracy catch it?
Accuracy only checks the top prediction and ignores confidence; when 99% of examples are legitimate, a model can score 99% by ignoring the input. Diagnose calibration with a reliability diagram (confidence against actual accuracy per bucket) or expected calibration error; overconfidence bows below the diagonal. Fix it with temperature scaling on a held-out set, which keeps the ranking, or with label smoothing or focal loss in training. Evaluate with precision, recall or PR-AUC on the minority class, at the production base rate.
DeepWhat does it mean, information-theoretically, for a learned representation to be "good"? Connect this to mutual information.
A representation of input is good for predicting if it keeps high mutual information , so knowing cuts your uncertainty about , while discarding what in is irrelevant to . It can never hold more information about than did (the data processing inequality). Contrastive objectives, masked prediction and next-token prediction can all be read as ways to raise the mutual information between a representation and some signal (another view, a masked patch, the next token) without hand-labelled targets.
11Go deeper
●Now write it yourself
Reading the derivation and being able to produce it are different skills. These are Deep-ML problems that exercise what this page covers — each one is checked against real test cases, not multiple choice.
Matched to this page from Deep-ML's catalogue of 1,380 problems. More at deep-ml.com, and Where to practise covers the other platforms and what each one trains.