KnowML

Neural Network Fundamentals

Follow one tiny network as it learns XOR, and see how the loss reaches every weight through backpropagation. Then make the network deep and learn what keeps it trainable: activations, initialisation, residual connections, normalisation and regularisation.

⏱ 30 min readAssumes: chain rule, gradient descent (01)
Start reading

Take two inputs, each either 0 or 1, and ask for an output that is 1 when exactly one of the inputs is 1 and 0 otherwise. That function is called XOR, short for "exclusive or", and you could write it as a one-line program. Suppose we want a machine to work it out from examples instead, the way a person learns a rule by seeing enough cases. We'll use a neural network: a chain of steps, each of which mixes a list of numbers using a set of adjustable numbers called weights. With the right weights the network computes XOR, and with any other weights it computes something else, so everything comes down to how the weights get chosen.

Training is a loop. We run an example through the network, measure how wrong the output is with one number called the loss, and then nudge every weight a little in whichever direction makes the loss smaller. That nudge is gradient descent, from chapter 01. Knowing the direction for each weight is the hard part, because a weight in the middle of the network only affects the output through everything that comes after it. Backpropagation solves this by applying the chain rule, also from chapter 01, once backward through the network, and it hands every weight its direction in a single sweep. It has been the training algorithm for neural networks since 1986, and it's still the one underneath every model on this site.

On a tiny network backprop is easy to follow, and we'll work through it by hand on our XOR network. Trouble starts when the network gets deep. Signals shrink as they pass through many layers, some units stop responding, and training stalls or blows up. A few design choices decide whether a deep network trains at all: the function applied to each layer's output, the numbers the weights start with, how the values flowing through the network are kept at a sensible size, and a shortcut that lets gradients skip past dozens of layers.

So we'll go in this order. First we build the XOR network by hand, then work out how the loss reaches each of its weights and write that down as equations we can run on real numbers. After that we count what a network costs, make it deeper, and meet each problem and its fix in turn, ending with how to stop a network from memorizing its training data. You'll need the chain rule and gradient descent from chapter 01, and we'll recall each one where we use it.

01A tiny network that computes XOR

Let's start with the smallest piece, a single artificial neuron. It takes some numbers in, multiplies each by its own weight, and adds the products together with one more adjustable number called the bias. A weighted sum plus a bias is a linear transformation. If that were all a neuron did, stacking neurons would get us nowhere, because a weighted sum of weighted sums is still a weighted sum. So the total goes through one more step, an activation function that bends it in a way no weighted sum can. Our first choice is ReLU, short for rectified linear unit. It computes max(0, z): negative totals become 0 and positive totals pass through unchanged. A neural network is these two steps alternating, a linear transformation and then a non-linear activation. Each such pair is a layer, and a network stacks them one after another.

Why does XOR need more than one neuron? Draw the four possible inputs, (0,0), (0,1), (1,0) and (1,1), as the corners of a square. Inputs that should give 1 are (0,1) and (1,0), on opposite corners, and the two that should give 0 sit on the other two. A single neuron decides by asking whether its weighted sum is above some level, and on our square that's a straight line, with the 1 answers on one side and the 0 answers on the other. No straight line puts two opposite corners together and the other two on the far side. Two neurons feeding a third can do it, though. The first two sit in a hidden layer, called hidden because its values are neither the input nor the output.

Here is a set of weights that works, picked by hand to show that the idea holds; training would find something equivalent. Both hidden neurons add the two inputs together. One passes that sum along unchanged. Its partner has a bias of −1, so after ReLU it's 0 unless the sum is above 1, and that happens only when both inputs are 1. Then the output neuron computes the first hidden value minus twice the second. Try (0,1) by hand: the sum is 1, the first neuron gives 1, the second gives max(0, 1 − 1) = 0, and the output is 1. For (1,1) the sum is 2, so the first neuron gives 2, the second gives 1, and the output is 2 − 2 = 0. In the code, the four inputs are the rows of X, so X @ W1 + b1 (@ is matrix multiplication) computes both hidden totals for all four inputs at once. Then comes the ReLU, and @ W2 produces the outputs.

Try it Compute XOR with a two-neuron hidden layer and hand-set weights
import numpy as np

def relu(z): return np.maximum(0, z)

X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float)
W1 = np.array([[1.0, 1.0], [1.0, 1.0]])   # both hidden units add inputs
b1 = np.array([0.0, -1.0])                # the second fires only above 1
W2 = np.array([1.0, -2.0])                # output = h1 - 2 * h2

out = relu(X @ W1 + b1) @ W2
for x, o in zip(X, out):
    print(f"inputs {x.astype(int)} -> {o:.0f}")
The network returns 0, 1, 1, 0 for the four inputs. That's XOR. Hidden neuron two switches on only when both inputs are 1, because their sum is then above 1. The output subtracts twice its value, and that cancels the first neuron's 2 down to 0.

Notice that the second hidden neuron does nothing for (0,1) and (1,0), and only the input (1,1) wakes it up. That one neuron is the bend a single straight line couldn't make, and it's the reason a hidden layer lets a model make a decision no single neuron can.

This failure of a single neuron has a history. Rosenblatt's perceptron (1958) was one neuron of this kind, and it could learn only patterns that a straight line separates. Minsky and Papert (1969) proved it could not learn XOR, and that helped cause the first AI winter, a long stretch when funding and interest dried up, because nobody knew how to train networks with hidden layers. Rumelhart, Hinton and Williams (1986) popularized backpropagation, a method that computes the gradient for every weight in a multi-layer network with one forward and one backward pass, and that made hidden layers trainable. Since then CNNs (LeCun, late 1980s to 1998), RNNs and LSTMs, and Transformers (2017) have changed the layers while the training algorithm stayed backprop, the chain rule and gradient descent.

We chose the XOR weights ourselves, which was possible because there are only a handful of them and four cases to check. A real network has millions of weights and no one to pick them. So we need a procedure that finds good weights from the data alone, and that starts with a way of saying how wrong the network currently is.

02Blame: how the loss reaches every weight

Training starts with weights that are random and almost certainly wrong. We feed an input through the network, layer by layer, and each layer computes its values from the ones before it. That left-to-right sweep is the forward pass, and it ends in a prediction. We compare the prediction to the true answer and get one number, the loss: the larger it is, the more wrong the prediction. In our XOR network, a sensible loss for one input is the squared difference between the output and the true answer.

Computing the loss was never the hard part. Deciding what to change is the hard part. If a weight three layers deep were a little larger, would the loss go up or down, and by how much? That question has a name, credit assignment, though here it's mostly blame we're assigning. For one weight the answer is the derivative of the loss with respect to it, meaning how fast the loss changes as that weight changes. Collect the derivatives for all the weights and you have the gradient. Gradient descent then moves every weight a small step against its derivative, and the loss goes down.

Why not nudge each weight and see what happens?

It's the obvious way to measure a derivative: add a tiny amount to one weight, rerun the forward pass, and see how much the loss moved. That works, and we'll use it to check our numbers in the next section. As a training method it's hopeless, because every weight needs its own forward pass, so a million parameters means a million forward passes for a single step. We need a calculation that gives every weight's answer for roughly the price of one pass.

Our saving comes from noticing how much work the weights share. Seen whole, the forward pass is a computational graph, a chain of simple operations, each one something we can take derivatives of, in which each node's output feeds the next node's input. Under the chain rule, the derivative of the loss with respect to any node is the product of local derivatives, one for each step on the path from that node to the loss. A weight in layer 1 changes the loss only through everything downstream of it, and that downstream work is the same for every weight in the layer. If we added up every path separately, the number of paths would multiply at each layer and the cost would grow exponentially with depth. But the paths share their tails, so we can compute each shared piece once, store it, and reuse it. One backward traversal then yields every weight's gradient.

Take the two-layer network we already have: the input goes through a linear step and an activation to give a hidden layer , then through a second linear step and activation to give the output , and the output goes into the loss . To find , the gradient for the first layer's weights, we don't analyze layer 1 on its own. We take the gradient signal that already reached the hidden layer, computed a moment ago while working on layer 2, and multiply it by one more local derivative. You can picture the gradient flowing backward like water through a pipe network, picking up a multiplicative factor at every junction. Keep that picture in mind, because a factor smaller than 1 shrinks the flow at every junction, and a factor larger than 1 swells it. Sections 05 and 08 are about what that does over many junctions.

In the diagram below, the blue lines carry values forward through a tiny network, and the pink lines run on the same wires in the opposite direction, carrying gradients from the loss back toward the inputs.

Forward pass (blue) and backward pass (pink) through the same tiny network
x1 x2 h1 h2 ŷ L → forward: values ← backward: ∂L/∂w, one local derivative at a time
Forward (blue): each node computes a value from the ones behind it, left to right, ending in the loss . Backward (pink, running on the same wires): starting from , each node receives a gradient from downstream and multiplies it by its own local derivative before passing it further back. Every weight on every wire gets the product of the local derivatives along the path from that weight to , summed over paths when there is more than one.

That tells us what to compute and in which order, and the next section turns it into equations we can run on actual numbers.

03Backpropagation in equations

A stack of layers, each a linear step followed by an activation, is called a multilayer perceptron (MLP), and our XOR network is a small one. We'll write out the two-layer case. In the forward pass, is the weighted sum entering the first layer, called its pre-activation, and is what comes out after the activation function is applied. Layer two does the same with its own activation and produces the output , and the loss compares with the true answer .

The backward pass computes a gradient at each layer's pre-activation, sends it back through one linear map, and stops. Here multiplies two vectors entry by entry, and the superscript is the transpose, the operation that turns a matrix's rows into columns. We start at the output layer:

Then the same pattern repeats one layer back, using the signal we just computed:

Each symbol has a job, and the list below says what it is.

  • δ is the error signal arriving at a layer's pre-activation: everything the loss cares about that flows through this point, collapsed into one vector.
  • f', g' are the local derivatives of each layer's activation function, evaluated at the value that layer saw on the forward pass. That's why the forward pass's intermediate values have to be cached, since the backward pass needs them.
  • (W^[2])ᵀδ^[2] is how the error signal at layer 2 travels back through layer 2's weights to become the blame felt by layer 1's output. This is the literal mechanism of credit assignment.
  • δ(a)ᵀ is an outer product (every entry of one vector times every entry of the other) that gives every weight the product of "how wrong was output " and "how active was input ". A weight is blamed in proportion to how much it was used.

Let's run these on our XOR network with one deliberate mistake. Set the output weights to in place of the we used, feed in the input (1,1) whose true answer is 0, and use squared error for the loss, so the output activation does nothing and . Running forward gives , so , and the output is . That makes the loss , and , so . The output is 1 and the right answer is 0, so the network is too high. Before reading on, can you guess which way the output weights should move?

Going backward, the gradient for the output weights is . To reach the first layer we multiply by the output weights to get , and then by the ReLU slope, which is 1 for both hidden neurons because both totals are positive. So , and the gradient for the first layer's weights is the outer product with , the matrix with rows and . These numbers match what the nudge test from section 02 gives. Add 0.001 to the first output weight and the output rises by 0.002, so the loss goes from 1 to about 1.004, a change of 0.004, which is 0.001 times the gradient of 4.

Read the signs against the hand-set solution. A gradient descent step with a learning rate of 0.1 (how big a step to take) moves the output weights from to . Its second weight became more negative, heading toward the we picked by hand, so the algorithm is pulling the mistake toward the working answer. Every number in that calculation came from one forward pass and one backward sweep, and the backward sweep gave all six weight gradients, where the nudge test would have needed a separate forward pass for each.

We stated the four equations without earning them. The box below shows where each one comes from, and the only tool it uses is the chain rule. You can skip it on a first read.

Derivation Deriving backpropagation from the chain rule alone

Those four equations were stated, not earned. Here is where each one comes from. Nothing below is more than the chain rule applied carefully, which is the point: backprop is not a separate algorithm you have to memorise.

  1. Why define this at all: we want , not . But every parameter in layer influences the loss only by changing . So if we know how sensitive is to , one more short step gives us every gradient in that layer. is the quantity worth computing.
  2. Why the Hadamard product: the output activation acts elementwise, so depends on and on no other component. The chain rule for a single index reads . Stack those independent scalar equations and you get an elementwise product, not a matrix multiply.
  3. Why a sum: this is the multivariable chain rule. Perturbing changes , which feeds into every unit of the next layer. The blame arriving at one hidden unit is the total collected over all the paths leaving it.
  4. Why: expand the single path. and . Differentiating the composition gives the weight on that edge times the local activation slope.
  5. Why the transpose appears, concretely: in that sum, is the row index of and is fixed as the column. Summing down a column of is the same as summing across a row of . The forward pass used row to build output from all inputs. The backward pass reads column to collect what input is answerable for. Same matrix, read the other way.
  6. Why the outer product: appears in exactly one place in the whole forward pass, the expression for , where it multiplies . So its derivative is that single term, with no sum. Every pairing of the two vectors is an outer product.
  7. Why it is just : . The bias enters additively, so the error signal passes through it unchanged.
There is no backpropagation algorithm in the sense of a clever new idea. There is the chain rule, plus one observation: is a shared subexpression. Every parameter in a layer needs it, and every layer below needs it too. Compute it once per layer, cache it, reuse it. The naive alternative recomputes that same downstream product separately for each parameter, so cost scales with the number of parameters instead of staying at roughly one extra pass. That reuse is the entire reason a billion-parameter network is trainable at all.

It ends on the point that matters for cost: is computed once per layer and reused. Notice also that the backward pass needs the forward pass's values, so everything the forward pass computed has to be kept in memory. With the algorithm in hand, we can ask how large a network needs to be and what training one costs.

04How deep to go, and what it costs

Our XOR network has one hidden layer. Is one hidden layer enough for any problem? A result called the universal approximation theorem (Cybenko, 1989; Hornik, 1991) says that a single hidden layer, given enough neurons and a non-linear activation, can approximate any continuous function on a compact input domain, meaning a closed and bounded region of inputs, to arbitrary precision. That sounds like the end of the story, but it only proves that suitable weights exist. It says nothing about how many neurons "enough" is, and the number can be exponentially large. It also doesn't say whether gradient descent will ever find those weights.

In practice depth helps, even though the theorem only asks for width. A deep network can represent the same function with far fewer neurons in total, because each layer builds on features the previous layer already made. In an image network, for example, the features go from edges to textures to parts to objects, where a shallow network would have to represent the whole function flat in a single layer. So we stack layers. To see what that costs, we'll count the network's numbers.

A linear layer maps a batch of inputs of shape (batch, in_features) to (batch, out_features), where batch is how many examples we push through together. It does that with a weight matrix of shape (in_features, out_features) plus a bias. Together the weights and biases are the network's parameters, and this layer has in_features × out_features + out_features of them, whatever the batch size.

For the cost of training, the scaling-law literature gives a useful rule of thumb. Total training compute is roughly , where is the parameter count and is the number of training tokens seen, a token being one piece of text for a language model. Compute is counted in FLOPs, floating-point operations such as one multiply or one add. A forward pass takes about FLOPs per token, one multiply and one add for each parameter. Backward takes roughly twice the forward pass again, because it does two products per layer, as the equations in section 03 showed: one for the gradient of the weights and one to pass the signal back (a gradient with respect to the activations). Two parts forward and four parts backward give the six in the rule.

Memory has two separate costs. Parameters set a floor, since the weights have to live somewhere. Then there are the activations, the values we have to keep from the forward pass for the backward pass to use. They set a second cost that grows with batch size and with depth, and it's often the larger of the two. This is why gradient accumulation (summing gradients over several small batches before one update) and activation checkpointing (recomputing activations in the backward pass instead of storing them) exist, and both come up again in section 11 and in chapter 23.

You might expect a deeper network to take proportionally longer per training step because backprop has more layers to work through. It doesn't, since the backward pass costs roughly twice the forward pass however the compute is spread across layers, so depth alone doesn't change that ratio. What depth does cost is memory. Every layer's activations have to be held until the backward pass needs them, so memory is usually the first thing to break as layers are added, ahead of the extra time per step. And memory isn't the only price of depth. Past a modest number of layers, plain stacking becomes hard to train at all, and the next three sections are about why.

05Activations: keeping the gradient alive

Go back to the water in the pipes. At every junction the gradient is multiplied by a local derivative, and one of those derivatives is the slope of the activation function, . So the choice of decides what happens to the gradient over many layers. Early networks used sigmoid and tanh, which squash their input into a bounded range. For large positive or negative inputs they go almost flat, so their derivative is close to zero. Chain a dozen of those together and the gradient reaching the early layers is a product of a dozen near-zero numbers. It becomes vanishingly small, a failure called the vanishing gradient, and the early layers almost stop learning.

Why did ReLU beat sigmoid and tanh?

ReLU, , has a derivative of exactly 1 for any positive input. It doesn't saturate or shrink gradients, so they pass through unchanged wherever the unit is active, and that's what unlocked deeper networks. It has a cost, though. For negative inputs ReLU's derivative is exactly 0, so a unit whose total is negative on every training example gets no gradient at all and never changes again. We say the unit dies. Two patches keep ReLU's advantage while fixing this. LeakyReLU gives negative inputs a small non-zero slope. GELU and SiLU are smooth and have a non-zero gradient almost everywhere.

GELU is , where is the standard normal distribution's cumulative distribution function, the probability that a standard normal variable falls below . SiLU, also called Swish, is , where is the sigmoid. Both multiply the input by a smooth gate that is close to 0 for very negative inputs and close to 1 for very positive ones. Unlike ReLU, the transition is smooth, and the function dips slightly negative just below zero and doesn't clamp hard at zero. That smoothness gives better-behaved gradients at the scale transformers are trained at, and empirically these activations outperform ReLU in that regime. Hence BERT, the GPT-family models and most modern transformer feed-forward blocks (chapter 08) default to GELU or to a gated SiLU variant called SwiGLU.

Activations shape the gradient, and the starting weights shape the forward signal. If the initial random weights are too small, the values shrink as they pass through the layers, and if they're too large, the values blow up before training has begun. Initialization schemes scale the random weights so that the variance of the activations, meaning how spread out they are, stays roughly constant from layer to layer. Xavier (or Glorot) initialization assumes a roughly linear, symmetric activation like tanh or sigmoid, and it scales the variance by , where fan is the number of connections going into or out of a unit and the subscript means the average of the two. He initialization accounts for ReLU zeroing out roughly half of all pre-activations, so it scales the variance by , with the number of inputs to a unit, to make up for the lost variance. Using the wrong one for your activation brings back the vanishing or exploding signal, starting at step zero instead of building up over training.

With ReLU or GELU and a matching initialization, a network of a dozen layers trains well. A network of fifty layers, built the same way, still doesn't, and the cause isn't something an activation can fix.

06Residual connections

He et al. (2015) found something that looks paradoxical. A plain 56-layer network had higher training error than an 18-layer one. That's a worse score on the very data it was trained on, so overfitting, where a model memorizes its training data and fails on new data, can't explain it.

If a deeper network can copy a shallow one, why does it train worse?

A deeper plain network is strictly more expressive than a shallow one, because it could reproduce the shallow network by setting the extra layers to the identity, a layer whose output equals its input. So the deep network has the capacity, and what fails is the search. Plain stochastic gradient descent (the version of gradient descent from chapter 01 that works on small random batches of data) struggles to find that identity mapping across many stacked non-linear layers. We have an optimization failure and not a capacity failure.

So we make the identity the easy answer. A residual block computes in place of : it adds the layer's output back onto its own input. Whenever contributes little, the block passes through, so the network starts at the identity and only has to learn a useful deviation from it. In the backward pass the addition contributes one extra term, the incoming gradient passed straight through, so gradients get a path that skips the layer's non-linearities. This is what unlocked networks past about 20 layers, and it's why 50-, 100- and even 1000-layer networks are trainable. A modern block normalizes, transforms, and adds the result onto a running residual stream instead of overwriting it, and the same stream runs through every Transformer block (08).

In the diagram below, follow the dashed line up the middle: that's the residual stream. Its box labelled Norm is a normalization step that rescales the numbers before the layer reads them, and the next section explains it. Putting it before each part is called pre-norm.

A generic pre-norm residual block — the residual stream flowing bottom to top
Input activations Norm (Batch / Layer / RMS) Linear + non-linearity (GELU/SiLU) + residual add Norm Linear (project back to width) + residual add ↑ to next block / output head
Each sub-layer reads the current value off the residual stream (the dashed line), computes an update, and adds it back instead of replacing the value. If the update is close to zero, say a not-yet-useful or poorly initialized transformation early in training, the identity path still carries the input straight through undamaged. The same direct additive path serves gradients flowing backward: they don't have to survive being multiplied through every transformation, and can flow along the stream. It's the same mechanism as the residual stream in a Transformer block (08).

That leaves the Norm boxes. What exactly do they compute, and why do some versions work for transformers while others don't?

07Normalization

Even with good initialization and residuals, the numbers flowing through a network can drift in size from layer to layer as the weights change during training. Normalization counters that by rescaling the values to a steady average and spread before each part uses them. BatchNorm was the first widely used version, and it computes statistics for each feature across the batch. Each example is a list of numbers, and each position in that list is a feature. For a feature with values over the examples, it finds their mean and variance , shifts and scales each value to , and then applies a learned scale and shift . A small constant keeps the division safe if the variance is zero.

LayerNorm uses the same formula, but and range over each example's own features and never touch the batch dimension. RMSNorm goes one step further and drops mean-centering entirely, normalizing only by the root-mean-square magnitude, where is the number of features:

RMSNorm needs no batch statistics and no running mean, the average BatchNorm keeps during training for use at inference. In the original formulation it has no bias term or mean subtraction either. It's cheaper to compute than LayerNorm and empirically about as effective, and that combination is why it's the default in most modern large language models (LLMs).

Why do transformers use LayerNorm or RMSNorm and not BatchNorm?

What you normalize over, whether the batch, a layer's features or a group of channels, is not a stylistic detail. It's the answer to a very common interview question. This table compares the four common choices. GroupNorm, the one we haven't described, normalizes over a group of channels within one example, and it's used where batches are small.

BatchNormLayerNormRMSNormGroupNorm
Normalizes overone feature/channel, across the batchall features, within one exampleall features, within one example (no centering)a group of channels, within one example
Depends on batch sizeYes — unstable/wrong at batch size 1NoNoNo
Needs running stats at inferenceYes (running mean/var — train/eval mismatch risk)NoNoNo
Typical homeCNNs / image classifiersTransformers, RNNs, sequence modelsModern LLMs (LLaMA-family and similar)Detection/segmentation — small per-GPU batch sizes

BatchNorm's statistics are computed across the examples in the batch, so the normalization applied to one example depends on which other examples happen to be sitting beside it. That's fine for image classifiers, where the batch size is typically large and fixed. It breaks badly for sequence models, for three reasons. Batch size varies between steps, sequences are padded with filler to different lengths, and, most seriously, text generation happens one token at a time with each new token fed back in (autoregressive generation), with an effective batch dimension that doesn't resemble training at all. LayerNorm and RMSNorm normalize within a single example's own feature vector. Their computation is identical whether the batch size is 512 or 1, and identical between training and inference. That independence from batch size and sequence length is why sequence models settled on per-example normalization.

Now the pieces fit together into a recipe. RMSNorm paired with a SwiGLU-style gated feed-forward block is now the default across most frontier open-weight LLM families, including LLaMA, Mistral and Qwen, and it has largely displaced the original 2017 Transformer's LayerNorm with a ReLU or GELU feed-forward design. Underneath all of it, training is still the backprop from section 03, largely unchanged since 1986, while the architecture keeps evolving. Even so, a network built from these parts can still fail in a handful of recognizable ways, and it helps to know how each one looks.

08When training goes wrong

The first failure we've already met. ReLU units can die, and the symptom is a growing fraction of activations reading exactly zero. A unit dies when its pre-activation is negative for every input in the training set, because it then receives zero gradient forever. A large learning-rate spike or an unlucky initialization can push a unit there, and it never recovers. To fix it, lower the learning rate, use He initialization, or use LeakyReLU, GELU or SiLU in place of plain ReLU.

Recurrent networks show the second failure. They read a sequence one step at a time (chapter 07). An RNN reuses the same weight matrix at every timestep, so the gradient flowing back through timesteps is roughly that matrix raised to the -th power. What that does depends on the matrix's dominant eigenvalue, the factor by which it stretches the direction it stretches most. If the dominant eigenvalue is below 1, the gradient shrinks toward zero over long sequences. If it's above 1, the gradient grows exponentially and can produce a NaN loss, meaning the numbers have overflowed, within a few hundred steps.

Gradient clipping handles the exploding side. It caps the global gradient norm, the overall length of the gradient vector, at a threshold before the optimizer applies the weight update. That limits the size of the update without changing its direction. It's cheap, standard (Pascanu et al., 2013), and still routinely used when training any recurrent or otherwise deep, unstable model.

A third failure sits at the very end of the network. Its logits, the raw scores before a softmax turns them into probabilities, can grow very large. Large logits push the cross-entropy loss (the loss that compares the predicted probabilities with the true answer) toward numerical overflow, and they make the loss landscape near that point extremely sharp. In practice this is handled with the log-sum-exp trick, a way of computing the softmax's logarithm without overflowing, and in some modern LLMs with an explicit logit soft-cap.

All three failures stop the network from fitting its training data. An opposite problem is just as real: a network with enough weights can fit its training data too well, memorizing it and failing on anything new.

09Regularization: dropout, early stopping, weight decay

Normalization stabilizes optimization. Regularization does the opposite job, deliberately making training harder so the network cannot memorize its way to a low loss. Chapter 01 frames the tradeoff, and here is what the three most common levers do to the network.

Dropout zeroes out each unit independently with probability during training, and then rescales the survivors by so the expected activation is unchanged. At evaluation time nothing is dropped. Its effect is that no unit can rely on any particular other unit being present, and that stops co-adaptation, where a group of units only works as a committee and none is individually meaningful.

Early stopping tracks the validation loss, the loss on held-out examples the network never trains on, after every epoch (one full pass through the training data). It keeps the weights from the best epoch and stops once the validation loss hasn't improved for a set number of epochs, called the patience. It costs nothing, and it's the only technique here that needs no hyperparameter (a setting we choose ourselves instead of learning it) tuning beyond the patience value.

Weight decay adds a penalty proportional to the squared magnitude of the weights, and that pulls them toward zero unless the data pushes back. This is regularization, and in a Bayesian reading it's a Gaussian prior centered on zero, a prior being what you believe about the weights before seeing any data.

One interaction trips people up, and it's a common interview follow-up: dropout and BatchNorm interact badly. Dropout changes the variance of the activations between training and evaluation, and BatchNorm's running statistics were estimated under training-time dropout, so the two disagree at inference. This is one reason modern transformer blocks use LayerNorm or RMSNorm with little or no dropout in the residual stream. It's also why model.eval() matters, since it switches both layers into inference behaviour, and forgetting it is a classic source of results that are quietly wrong.

A practical ordering is to always use early stopping, since it's free, and then to add weight decay, because it's one number and usually helps. Add dropout when the model still overfits after both, and expect to need less of it than older tutorials suggest: large models trained on large corpora are often regularized adequately by the data itself. That completes the toolkit, and the summary below recalls where each piece came from.

10Summary

  1. A network alternates linear steps and non-linear activations. A weighted sum and a bias, then ReLU or a similar function. The hidden layer is what let our XOR network do what a single neuron could not.
  2. Training needs the loss's derivative for every weight. Nudging weights one at a time costs a forward pass each, which is hopeless with millions of weights.
  3. Backpropagation is the chain rule over a computational graph. The work downstream of a layer is shared by every weight in it, so it's computed once, cached and reused, and one backward sweep gives every gradient.
  4. The two-layer case is a few lines. at the output, one layer back, and an outer product for each weight gradient. On our XOR example the output weights get the gradient .
  5. Backward costs about twice forward, and depth costs memory. Training takes roughly FLOPs, and the activations kept for the backward pass are often the larger memory bill.
  6. Sigmoid and tanh vanish, ReLU passes gradients but can die. LeakyReLU, GELU and SiLU keep a gradient almost everywhere, and GELU or SwiGLU is the default in modern transformers.
  7. Initialization sets the starting scale. Xavier suits tanh and sigmoid, He suits ReLU, and the wrong choice brings back vanishing or exploding signals at step zero.
  8. Residual connections make depth trainable. A block computes , so identity is the default and gradients get a direct path back, and that fixes the training error that made a plain 56-layer network worse than an 18-layer one.
  9. Normalize per example in sequence models. BatchNorm depends on the batch and needs running statistics, while LayerNorm and RMSNorm don't, and RMSNorm with SwiGLU is the 2026 default recipe.
  10. Training still fails in recognizable ways. Dead ReLUs, vanishing or exploding gradients in RNNs (cured on the exploding side by clipping) and exploding logits each have a known fix.
  11. Regularization fights memorizing. Early stopping is free, weight decay is one number, dropout comes last, and model.eval() turns dropout off at inference.

11Build this

Section 06 makes a claim that sounds wrong. A deep plain network can have higher training error than a shallow one, on the same data. The loss curve is more convincing than the sentence.

Project Stall a 40-layer MLP, then fix it with one addition ~4 hours · NumPy

Fit a smooth one-dimensional curve with a plain MLP, then keep making it deeper until it stops learning. Everything is hand-written from the four backprop equations in section 03, with no autograd. The aim is to watch the gradient shrink on its way back, and then change that by hand.

  1. Data: a few hundred points from a smooth curve with a couple of bends. One input, one output, no noise needed.
  2. Write forward and backward in NumPy from the section 03 equations. A at each pre-activation, an outer product for each weight gradient. Depth and width are arguments. Use tanh, and check the gradients once against finite differences before trusting anything.
  3. Train at depth 4, then at depth 40 with the same width, same learning rate, same number of steps. Plot both training-loss curves on one axis, plus each network's fitted curve over the target. If depth 40 still trains, keep adding layers until it stops. Where that happens is yours to find.
  4. Print the gradient norm for every layer of the deep net, output back to input, at the first step and again later in training.
  5. Add the residual: each block computes x + f(x) in place of f(x). In the backward pass that is one extra term, the incoming gradient passed straight through. Add hand-written RMSNorm from section 07 ahead of each block. Retrain at the same depth.
  6. Now ablate: remove the residual and keep the norm, then keep the residual and remove the norm, with the same depth, seed and steps, and plot all three curves together.
You'll know it worked when the deep plain net's training loss curve sits above the shallow one's. Its fitted curve stays close to flat while the shallow net traces the target. Nothing was overfitted and no capacity was missing: the deep net contains the shallow one as a special case (section 06). Step 4 shows the mechanism, with the per-layer gradient norms shrinking as they travel back toward the input. Add the residual and that decay flattens out.
What the ablation teaches. Depth was never the problem on its own. Section 06 has the framing worth keeping. A residual block starts from the identity and only learns a deviation from it. The network is never asked to discover the identity across forty stacked non-linearities. The norm and the residual do different jobs. Running each one alone, at a depth where plain stacking fails, is the cheapest way to feel that difference. Whichever turns out to be load-bearing for you, step 4's gradient-norm printout says why.

Where this runs in production

Two of the tradeoffs above compound into a real constraint. A 7B-parameter model's weights, gradients, and optimizer state already consume tens of gigabytes in FP32, before a single activation is stored.

Three levers, each attacking a different part of that:

  • Mixed precision. Store most of the forward and backward computation in FP16 or BF16. Half the memory, and much higher throughput on GPU tensor cores. Keep a master copy of the weights in FP32 so small updates are not lost to rounding, and add loss scaling to stop small gradients underflowing to zero. Loss scaling matters more for FP16's narrow exponent range than for BF16's.
  • Gradient accumulation. This handles the batch-size side. If the batch you want does not fit, run several smaller micro-batches forward and backward, sum their gradients, and take one optimizer step after enough have accumulated. Mathematically close to training at the larger batch size, paid for with extra passes and not extra memory.
  • Gradient clipping. Keeps the mixed-precision, accumulated updates numerically stable.

Together those are the standard recipe that lets a handful of memory-constrained GPUs train a model that would otherwise need far more hardware. The rest of the toolbox (sharding, offloading, activation checkpointing) gets a full treatment in 23.

12Interview questions

BeginnerWalk me through backpropagation for a simple 2-layer network.

Run the forward pass, caching every intermediate value: , , , , then the loss. Going backward, compute , use it to get , then propagate one layer further with to get . Each layer's gradient reuses the layer above it's already-computed signal, multiplied by one local derivative.

BeginnerWhy did ReLU replace sigmoid/tanh as the default activation?

Sigmoid and tanh saturate — for large-magnitude inputs their derivative approaches zero. Chained across many layers, that near-zero derivative gets multiplied together and the gradient reaching early layers vanishes, so those layers barely learn. ReLU's derivative is exactly 1 for any positive input, so gradients pass through unshrunk wherever the unit is active. The tradeoff is dead units: a unit stuck permanently negative gets exactly zero gradient and stops updating, which is what LeakyReLU/GELU/SiLU are designed to fix.

IntermediateWhat's the difference between BatchNorm and LayerNorm, and why do transformers use LayerNorm (or RMSNorm) instead of BatchNorm?

BatchNorm normalizes one feature's values across all examples in the batch; LayerNorm normalizes all of one example's features against each other, never touching the batch dimension. BatchNorm's statistics therefore depend on batch composition and size, need running estimates carried into inference, and break down at small or variable batch sizes. Sequence models have variable-length, often padded sequences and generate one token at a time at inference — batch statistics are unreliable or simply don't make sense there. LayerNorm and RMSNorm normalize per example, so they're identical regardless of batch size or between training and inference, which is why they're the standard for transformers and RNNs.

IntermediateWhy do residual connections make very deep networks trainable?

He et al. showed that plain (non-residual) deep networks can have higher training error than shallower ones — an optimization failure, since a deeper network could always represent the shallow function by learning identity in the extra layers, it just struggles to find that solution via SGD. A residual block computes instead of , so identity is the default whenever the learned branch contributes little, and gradients get a direct additive path backward through the residual stream instead of having to survive being multiplied through every intervening non-linear transformation.

IntermediateXavier/Glorot vs. He initialization — what's the actual difference, and why does it matter?

Both scale the initial random weights so that activation variance stays roughly constant from layer to layer instead of shrinking or blowing up as depth increases. Xavier/Glorot initialization assumes a roughly linear, symmetric activation like tanh/sigmoid and scales variance by . He initialization accounts for ReLU zeroing out roughly half of all pre-activations, so it scales variance by to compensate for that lost variance. Using the wrong one for your activation function reintroduces exactly the vanishing/exploding signal problem initialization is supposed to prevent, just starting at step zero instead of building up over training.

DeepYou're training a 7B-parameter model and keep running out of GPU memory. What levers do you pull, and why?

Mixed precision (FP16/BF16 compute with an FP32 master copy of weights) roughly halves memory and increases tensor-core throughput. Gradient accumulation lets you simulate a larger batch size than fits in memory by summing gradients over several forward/backward micro-batches before one optimizer step. Gradient clipping keeps the resulting updates numerically stable under mixed precision. If that's still not enough, the next lever is activation checkpointing (recompute activations during the backward pass instead of storing all of them) and optimizer/parameter sharding — both covered in depth in 23. None of these change what backprop computes, they change how much of it you have to hold in memory at once.

DeepYour RNN's training loss suddenly goes to NaN a few hundred steps in. What's happening, and what do you do?

Classic exploding gradient: an RNN reuses the same weight matrix at every timestep, so the backward gradient is roughly that matrix raised to the power of the sequence length. If its dominant eigenvalue is above 1, the gradient — and eventually the loss — grows exponentially with sequence length until it overflows to NaN. Fix: clip the global gradient norm to a fixed threshold before the optimizer step (this caps magnitude without changing direction), consider a lower learning rate, and if this keeps recurring, consider whether the architecture itself (e.g. gated recurrence, or dropping recurrence for attention) is fighting you rather than a tuning issue.

IntermediateWhat does dropout do differently at training time and at evaluation time?

During training it zeroes each unit independently with probability and rescales the survivors by , so the expected activation is unchanged. At evaluation nothing is dropped and no rescaling happens, which is why the scaling has to be applied during training rather than after. The mechanism prevents co-adaptation: no unit can depend on a particular other unit being present, so the network cannot rely on a committee where no member is individually meaningful. Forgetting model.eval() leaves dropout active at inference, which produces results that are noisy and slightly wrong rather than obviously broken.

DeepWhy do modern transformer blocks use little or no dropout in the residual stream?

Partly because dropout and normalization interact badly. Dropout changes activation variance between training and evaluation, and BatchNorm's running statistics were estimated under training-time dropout, so the two disagree at inference. Transformers avoid that by using LayerNorm or RMSNorm, which are per-example and need no running statistics. The larger reason is that regularization need scales with how much the model can memorise relative to the data. A large model trained on a very large corpus sees few repeats, so the data itself does much of the regularising and heavy dropout mostly slows convergence.

13Go 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.