Part II ยท Ch. 6 โ€” Teaching the Network

Part II ยท Chapter 6 of 13

Teaching the Network

Backprop, optimizers, and the art of not memorizing


The two problems we left open

Last chapter we built a network of plain straight-line neurons that, stacked a few layers deep, can bend into any shape, and we watched gradient descent nudge one toward a good boundary. But we cheated twice, and both cheats have to be paid off before anything real can be trained. This chapter pays them.

The first debt is mechanical. A real network has thousands, millions, sometimes billions of weights buried inside its hidden layers, and when it gets a training point wrong, every one of them needs to know which way to turn. Gradient descent from fitting a line runs on the gradient โ€” one slope per weight โ€” and we never said how to get all those slopes without re-running the whole network once per weight, which at real scale is impossible. The second debt is subtler and more important: a network powerful enough to fit any shape is powerful enough to fit the wrong shape โ€” to trace every training point exactly, noise and all, and then fail on everything it has never seen.

So the chapter has two halves. First the mechanics: backpropagation, which grades every buried weight for the price of two passes, then better ways to take the downhill step โ€” momentum and Adam. Then the wisdom: overfitting, the train/validation/test split, and the regularizers that keep a network honest. The first half is arithmetic; the second is judgement โ€” and it is where most of the real craft of machine learning lives.

How blame reaches a buried weight

The engine is the chain rule, built in full โ€” slowly, with a nudge-check โ€” on the sister site; for the patient version, read the LLM site's backpropagation chapter. In one sentence: when machines feed machines, a small wiggle in an early weight reaches the output multiplied by the slope of every stage in between. So to find how the loss responds to a buried weight, multiply the local slopes along the path from that weight down to the loss.

Work it on the smallest honest network there is, using the exact numbers the sister site uses โ€” so a reader crossing between the two sites meets one consistent example. Two weights in series: an input $x = 2$ flows into a first weight $w_1$, giving a middle value $h = w_1 x$; that $h$ flows into a second weight $w_2$, giving the prediction $\hat{y} = w_2 h$ โ€” "y-hat, the model's guess". The target is $y = 3$. Set $w_1 = 1$ and $w_2 = 2$.

A left-to-right pipeline. Forward, along the middle: a mint chip x = 2 feeds a violet dial w1 = 1, giving a white chip h = 2, which feeds a violet dial w2 = 2, giving a chip y-hat = 4, which feeds a red-outlined box reading target y = 3 and L = (4 minus 3) squared = 1. Above the pipeline the backward story runs right to left in red: a red arrow spanning the width, blame value 2 over y-hat tagged dL/dy-hat = 2 times miss, blame value 4 over h, and two red drop-arrows descending into the two dials carrying boxed formulas partial-L/partial-w1 = 4 times 2 = 8 and partial-L/partial-w2 = 2 times 2 = 4. A bottom strip reads: step eta = 0.05, w1 goes 1 to 0.6, w2 goes 2 to 1.8, re-run, L goes 1 to 0.71.
One heartbeat of training, by hand. Forward (middle): $x = 2$ becomes $h = 2$, becomes $\hat{y} = 4$ โ€” one too high, so the squared-miss loss is $1$. Backward (top): blame starts as $2$ at the prediction and is multiplied by each local slope, dropping every weight's share ($4$ for $w_2$, $8$ for $w_1$). One small step against those slopes, re-run, and the loss falls from $1$ to $0.71$. Two passes graded both weights โ€” the same trick grades two billion.

Worked example โ€” one heartbeat of training

The forward pass. Push the number through and grade with the squared miss โ€” a plain-number prediction wants a plain-number ruler, and squaring makes every miss positive and punishes big ones hardest:

$$h = w_1 x = 2, \quad \hat{y} = w_2 h = 4, \quad L = (\hat{y} - y)^2 = 1$$

In words: the input doubles into $h = 2$, doubles again into $\hat{y} = 4$, and since the target was $3$ the prediction is one too high โ€” a squared loss of $1$.

One symbol before we start, so it does not ambush you: from here the slopes are written with a curly $\partial$ rather than the straight $d$ of $\frac{df}{dx}$. It is read "partial", and it means the same slope-of-the-loss idea with a reminder attached โ€” we are wiggling one weight while holding the others still.

The backward pass, one hop at a time, right to left โ€” this is the whole idea. Blame starts at the loss: how much does $L$ change if $\hat{y}$ nudges? For the squared miss that slope is $2 \times (\text{miss}) = 2$ (the $x^2 \to 2x$ pattern from the math toolkit). Hop into $w_2$: since $\hat{y} = w_2 h$ is a straight line in $w_2$ with slope $h = 2$, the loss's sensitivity to $w_2$ is $2 \times 2 = 4$. That same blame passes through $h$ (slope back $w_2 = 2$), arriving as $4$, and hops into $w_1$ (slope $x = 2$), giving $4 \times 2 = 8$:

$$\frac{\partial L}{\partial w_2} = 2(\hat{y}-y)\cdot h = 2\times 2 = 4 \qquad \frac{\partial L}{\partial w_1} = 4 \times 2 = 8 \qquad \nabla L = \begin{bmatrix} 8 \\ 4 \end{bmatrix}$$

In words: the loss is twice as sensitive to the inner weight as to the outer one, so the gradient โ€” the vector of both slopes โ€” is eight over four.

The step. Take one downhill step with the rule from fitting a line, now written $\theta \leftarrow \theta - \eta\,\nabla L$. The $\theta$ โ€” "theta" โ€” is the standing symbol for whatever dials the model has, which last chapter meant one weight and here means both of ours at once; $\eta$ โ€” "eta", the learning rate โ€” sets how big the step is. Use $\eta = 0.05$:

$$w_1 \leftarrow 1 - 0.05\times 8 = 0.6 \qquad w_2 \leftarrow 2 - 0.05\times 4 = 1.8 \;\Rightarrow\; L: 1 \to 0.71$$

In words: nudge each weight a little against its own blame, re-run the network, and the loss falls from $1$ to about $0.71$ in one measured step.

That last number is worth watching being made rather than taking on trust. Push the input through once more with the new dials: $2$ times $w_1 = 0.6$ gives $h = 1.2$; times $w_2 = 1.8$ gives $\hat{y} = 2.16$; the miss is $2.16 - 3 = -0.84$, and squared that is about $0.71$. Down from $1$, in one honest step.

Now the payoff, said with force: nobody re-ran the network to get those two slopes. One forward pass computed and stored every value; one backward pass, reusing exactly those stored values, computed every weight's blame โ€” everyone upstream reuses the blame that has already flowed to the value below them. Two passes grade all the weights. Two, or two billion. That reuse is the entire reason training a deep network is affordable; without it you would re-run the whole model once per weight, which at real scale is never. Forward, grade, backward, step โ€” that four-beat cycle, repeated a few million times, is training.

Better ways downhill

Plain gradient descent takes one step straight down the local slope, every step, with no memory of where it has been. On the smooth bowls of the math toolkit that is fine. On the crumpled loss landscapes of real deep networks it struggles in two ways this section fixes: it zigzags helplessly across long narrow valleys, and it crawls to a near-stop across vast flat plateaus.

First, an upgrade that changes what "the gradient" even means. Grading the loss over the full training set at every step is unaffordable, so each step grades a small random batch of examples instead. A batch's gradient is only a noisy estimate of the true one โ€” a compass that jitters around downhill rather than pointing at it exactly. That is stochastic gradient descent, or SGD, and it is what everyone actually runs. The jitter is not just tolerated but useful, rattling the walker out of shallow dead-ends the way a little shaking settles sand into a tighter pack.

Second โ€” momentum. Instead of stepping on the raw slope, keep a running average of recent gradients โ€” a velocity $\mathbf{v}$ โ€” and step on that:

$$\mathbf{v} \leftarrow \beta\,\mathbf{v} + \nabla L \qquad \theta \leftarrow \theta - \eta\,\mathbf{v}$$

In words: build up speed in directions the slope keeps pointing, and let disagreeing wiggles cancel out โ€” then step along that accumulated velocity, not the raw gradient.

The new symbol $\beta$ โ€” "beta" โ€” is the momentum coefficient, usually about $0.9$: how much of the old velocity carries into the next step. Why $0.9$ and not something else โ€” because keeping nine-tenths of your speed each step means it takes about ten steps of steady pushing to turn the walk around, which is long enough to smooth out random wobble and short enough to still respond when the ground genuinely changes. Picture a ball rolling downhill instead of a hiker re-deciding at every footstep. It powers through plateaus because it arrives carrying speed, and it stops zigzagging across a narrow valley because the sideways slaps alternate and cancel while the gentle downhill push points the same way every step and accumulates.

Third โ€” Adam, the one you will actually meet in code. Its idea in a sentence: give every weight its own learning rate, automatically. A weight whose gradient has been consistently large gets smaller, calmer steps; one whose gradient has been tiny and rare gets larger, bolder ones โ€” so no single global $\eta$ has to suit every weight at once. It does this by tracking, per weight, both a running average of the gradient (that is momentum again) and a running average of its square โ€” a measure of how jumpy that weight has been โ€” and dividing each step by the square root of the latter:

step $\;\propto\;$ (average gradient) $/\;\sqrt{\text{average squared gradient}}$

That is Adam. A thrashing weight has a large average square, so it gets divided down into small steps; a barely-moving weight is divided by almost nothing and is free to take a big one. It usually "just works" with very little tuning, which is exactly why it dominates.

A bird's-eye contour map of a long narrow elliptical valley, its floor running left to right toward a violet star at the origin. Three descent paths start from the same white dot at upper right labeled start. A blue SGD path zigzags violently up and down across the narrow direction while creeping along the floor. A mint momentum path makes one gentle damped wave and settles at the star. An amber Adam path descends almost straight down the diagonal to the star. Labels: SGD zigzags, momentum smoother, Adam adaptive, and a note reading a long narrow valley: plain steps zigzag across it.
Three ways down the same valley. Plain SGD (blue) zigzags across a long narrow ravine, wasting steps. Momentum (mint) averages recent gradients, so the sideways slaps cancel and it powers down the floor. Adam (amber) gives each direction its own step size and descends almost straight. They differ in path and effort, not in where they are headed โ€” the same minimum, reached with more or less fuss.

Land it with a fair summary, no hype. SGD is the honest baseline; momentum smooths and accelerates it; Adam adapts per weight and is the sensible default for most deep networks โ€” yet plain SGD with momentum still wins some of the largest, most carefully tuned training runs on Earth. The optimizer is a knob, not a magic wand. Every one of them is still just walking downhill on the same loss.

The real enemy: memorizing

Now the harder half, and it opens with a scene. Imagine seven scattered data points that clearly come from a gentle underlying trend plus a little measurement noise. A straight line through them misses the bend entirely โ€” too simple to capture the real pattern, with high error even on the data it trained on. We say it underfits. A gentle degree-3 curve โ€” degree being the dial for how much a curve is allowed to bend, a degree-3 curve getting up to two bends โ€” follows the trend and shrugs off the scatter, a good fit. But a wild degree-9 curve, allowed eight bends' worth of freedom, can be forced through all seven points exactly, wiggling violently between them and shooting off near the edges. It overfits: perfect on the training points, nonsense on any new one.

Three panels sharing the same seven blue scatter points that follow a gentle bend with noise. Left panel, labeled underfit a straight line: a mint straight line that misses the bend, noted misses the pattern. Middle panel, labeled good fit a gentle curve: a mint degree-3 curve tracking the trend, noted follows the trend ignores the noise. Right panel, labeled overfit a wild curve: a mint degree-9 curve threading every point exactly and oscillating wildly, noted hits every point learns nothing.
The whole story in three curves. Too simple (left), a straight line misses the real bend. Just right (middle), a gentle curve follows the trend and shrugs off the scatter. Too powerful (right), a wild curve threads every single point exactly โ€” perfect on the training data, useless everywhere between. A network with enough neurons is the curve on the right unless you stop it.

Here is the distinction the whole rest of machine learning turns on. Getting the training data right is not the goal. Generalization โ€” doing well on data it has never seen โ€” is. A model can have near-zero training error and be worthless, because it memorized the exam instead of learning the subject. And here is the trap specific to neural networks: last chapter's universal-approximation power cuts both ways. A big enough network can memorize its entire training set perfectly, noise and all โ€” it is the degree-9 curve with a million dials instead of nine.

To manage this you first have to see it, so make memorizing measurable. Split your data: train on one part, and keep a held-out part the model never learns from, used only to check how it does on the unseen. Now plot both losses as training proceeds, measured in epochs โ€” one epoch is one complete pass over the training set. The training loss falls and keeps falling โ€” the model gets better and better at the questions it can see. The held-out loss falls too at first โ€” real pattern being learned โ€” then bottoms out and starts rising, as the model begins memorizing training noise that does not transfer. That rising curve is overfitting made visible, and the growing gap between the two curves is exactly the memorization.

A loss-versus-epochs plot. A mint training-loss curve falls smoothly and keeps falling toward about 0.05. An amber validation-loss curve falls with it at first, reaches a minimum near epoch 27 at about 0.30, then rises steadily to about 0.56. A violet dashed vertical line and dot mark the minimum, labeled early stop best generalization. The region to the right is faintly shaded red and labeled overfitting: training keeps improving, validation gets worse. A double arrow on the right marks the vertical gap between the curves, labeled this gap = memorization.
Overfitting made visible. Both losses fall together while the network learns the real pattern โ€” then the validation curve (amber) bottoms out and turns up as the network starts memorizing training noise, even as the training curve (mint) keeps happily dropping. The best model is at the validation minimum; the widening gap past it is pure memorization. Early stopping just means quitting at the violet line.

That gives us the sweet spot and the cheapest fix. The moment the held-out loss stops falling is the best this model will ever generalize; training past it makes things strictly worse. So stop there. Early stopping is exactly that โ€” watch the held-out curve and quit at its minimum. It is the cheapest and most-used regularizer there is.

Three piles of data

Turn that honest-measurement habit into the discipline every practitioner follows: before doing anything else, split the data into three piles. The training set is what the model actually fits its weights to. The validation set is what you check during development โ€” to pick the learning rate, choose the network size, decide when to early-stop. And the test set is locked in a drawer and looked at exactly once, at the very end, for the true grade.

Why three and not two? The reason is subtle and almost universally botched. Every time you use the validation set to make a choice, you leak a little information about it into the model. Tune long enough against validation and you start overfitting to it โ€” your validation score becomes optimistic, a grade you have quietly studied for. The test set catches exactly that: because you never once used it to make a decision, its number is trustworthy. State the rule plainly, and tape it to the wall: the moment you make any choice based on the test set, it stops being a test set.

Two practical notes. A common split is something like 80/10/10, but the real constraint is not the ratio: all three piles must look like the world the model will actually face โ€” the same kinds of examples, with no training point sneaking into the test pile in disguise. And when data is genuinely scarce, cross-validation โ€” rotating which slice is held out and averaging the results โ€” squeezes more signal from the same points.

Keeping a network honest

Early stopping was our first regularizer. There is a whole family of them, and they share one idea: make memorizing harder, so the network is nudged toward simple, general patterns instead of intricate, memorized ones. A regularizer deliberately hobbles the model's ability to memorize, and that small handicap usually buys a large gain on new data.

First, weight decay, also called L2. Add a penalty to the loss for large weights: instead of minimizing $L$ alone, minimize $L$ plus a small multiple of the total squared size of the weights:

$$L_{\text{total}} = L + \lambda\,\lVert \mathbf{w} \rVert^2$$

In words: pay the usual loss, plus a fee that grows with how big the weights get โ€” so the network keeps them small unless a big weight really earns its keep. The double bars are the vector length from the toolkit, so $\lVert \mathbf{w} \rVert^2$ is that length squared: every weight squared and added up.

The new symbol $\lambda$ โ€” "lambda" โ€” is the strength dial: crank it up and the fee bites harder. Why does this help? Small weights make smooth, gentle functions โ€” the tame degree-3 curve. Big weights are what make the violent wiggles of overfitting possible. Weight decay is a thumb on the scale toward smoothness.

Second, dropout โ€” the one regularizer unique to neural networks, and delightfully strange. During training, at every step, randomly switch off a fraction of the neurons (say half), setting their outputs to zero for that step only. The network must still predict correctly with a random half of it missing, so it cannot lean on any single neuron as a memorized lookup โ€” it is forced to spread each pattern redundantly across many. At test time you switch every neuron back on. The effect is like cheaply training a huge ensemble of slightly different networks that share one set of weights โ€” robustness for almost no cost.

Two panels showing the same small network: two mint input dots, five hidden dots, one amber output dot, fully connected. Left panel, labeled training step dropout ON: two of the five hidden neurons are drawn as hollow gray circles with an X, and all their connection lines are removed, noted a random half switched off the network must still be right. Right panel, labeled test time all neurons ON: the full network with all five hidden dots violet and every line present, noted the whole network is used. A line spans the bottom: each pattern spread across many neurons no single one is a memorized shortcut.
Dropout, in two moments. During training (left), a random fraction of hidden neurons is switched off at every step, so the network can never lean on any single neuron as a memorized lookup โ€” it must spread each pattern redundantly across many. At test time (right), every neuron is back on and the full network predicts. It is like cheaply training a whole ensemble of networks that share one set of weights.

Third, gather the two you already met: early stopping (quit at the validation minimum) and, quietly the most powerful of all, more data. Here is the deepest, least glamorous truth in the chapter: the single most reliable cure for overfitting is a bigger, more varied training set. A model cannot memorize its way through a dataset too large to memorize โ€” it is forced to find the actual pattern. Every regularizer above is, in part, a substitute for data you did not have.

Close on the balance, with no false precision. Regularize too little and the network memorizes; regularize too much and you handcuff it into underfitting โ€” the straight line again, this time by choice. The right amount is found the way everything else here is: by watching the validation curve. There is no formula, only measurement.

Where you'll meet this

You now own the full training loop, and it is a ritual you can recite for any neural network in the rest of this site. Split the data three ways. Forward a batch through the network. Grade it with a loss. Backpropagate the blame to every weight in two passes. Step with an optimizer โ€” SGD, momentum, or Adam. Watch the validation curve. Regularize and early-stop so the network generalizes instead of memorizing. Every model in Part III โ€” the convolutional networks, the recurrent networks, the graph networks, and the transformers on the sister site โ€” is trained by this exact loop. Only the network's shape changes.

Follow the thread to the sister site: pretraining a large language model is this same loop run at industrial scale โ€” the same backprop, the same Adam-family optimizer, the same falling loss โ€” poured over trillions of tokens (the LLM site's training-run chapter shows it happening). The reader who understands overfitting on seven points understands, in miniature, why frontier models are trained on more data than any human could read in a thousand lifetimes: enough that memorizing it is not an option.

And name honestly what is still ahead. We now know how to train a network and keep it honest โ€” but we have been feeding it plain flat lists of numbers, every input treated as unrelated to its neighbors. Real data has shape: an image is a grid, a sentence is a sequence, a contact network is a graph. Pour any of those into a plain stack of neurons and you throw their structure away before the network ever sees it. The next part of the book matches the network's wiring to the data's shape โ€” and the gains are enormous.

Close warm. You have hand-graded a two-weight network ($\nabla L = [8, 4]$, loss $1 \to 0.71$), watched a wiggly curve memorize seven points, and learned the discipline โ€” three piles, one honest test โ€” that separates a model that works from one that only looks like it works. That discipline, more than any architecture, is what makes machine learning a science instead of a magic trick.

What you now know

  • Backpropagation grades every buried weight in two passes: one forward pass computes and stores each value, one backward pass multiplies local slopes (the chain rule) to hand each weight its share of blame โ€” on our two-weight network, $\nabla L = [8, 4]$, and one $\eta = 0.05$ step drops the loss from $1$ to $0.71$.
  • Real training uses random mini-batches (stochastic gradient descent), and better optimizers improve the walk: momentum averages recent gradients to power through plateaus and stop zigzagging, and Adam gives every weight its own adaptive step size and is the usual default โ€” but all of them still just descend the same loss.
  • A network powerful enough to fit any shape can fit the wrong one: it will memorize the training points, noise and all (the degree-9 wiggle), scoring perfectly on data it has seen and failing on data it hasn't.
  • Overfitting becomes visible when you hold data out: training loss keeps falling while validation loss bottoms out and rises โ€” and the goal is generalization (doing well on new data), not a low training number.
  • Split data into three piles โ€” train (to fit), validation (to make choices and early-stop), test (touched once, for an honest final grade) โ€” because any choice made against a set quietly overfits to it.
  • Regularizers make memorizing harder and generalization better: weight decay penalizes large weights toward smoothness, dropout forces patterns to spread across neurons, early stopping quits at the validation minimum โ€” and more data beats all of them.

Where we're headed. We can now train a network and keep it honest โ€” the full loop of forward, grade, backprop, step, validate, regularize. But notice what we have been feeding it: plain flat lists of numbers, every input treated as unrelated to its neighbors. Real data isn't flat. An image is a grid where nearby pixels belong together; a sentence is a sequence where order carries meaning; a contact network is a graph of nodes and links. Pour any of those into a plain stack of neurons and you throw their structure in the trash before the network ever sees it. The next part of the book does something smarter: it shapes the network's wiring to match the shape of the data โ€” and the payoff, starting with how a network learns to see, is one of the most beautiful ideas in the field.