14  Lesson 4: Feed-forward Networks and Backpropagation

Composition, nonlinear representations, and computation graphs

Author

Noel Danz

TipWeekly workflow
Phase Student work
Before Session 1 Read the provided material and work through the example tasks in the beginning.
Session 1 Hidden representations, nonlinearities, computation graphs, chain rule, and manual backpropagation.
Between sessions Implement one manual backward pass and compare it with automatic differentiation.
Session 2 Paired MLP implementation, gradient checking, and debugging of broken derivative code.
After Session 2 Complete the MLP and explore architectural changes and activations.

14.1 Learning outcomes

  • W04-01: Explain why stacked affine maps require nonlinear activations.
  • W04-02: Trace forward and backward values through a small computation graph.
  • W04-03: Implement and gradient-check a two-layer MLP.
  • W04-04: Relate width, activation choice, and representation capacity.

14.2 Prerequisites

Weeks 1–3: linear prediction, cross-entropy, gradients, and optimization.

14.3 Introduction

In this lesson we will extend linear regression to multivalued output functions, explore their limits of expressivity, and get to know a new model type that has a greater expressivity. At the end we will see that this new model type can approximate any continuous function to arbitrary precision, at least on a compact interval.

14.4 Linear Layers (Dense, Linear)

In weeks one and two, you modelled data using linear and logistic regression. Both begin with an affine map \(y=w^Tx+b\).

\[ z=Wx+b,\qquad W\in\mathbb R^{m\times d},\;b\in\mathbb R^m. \tag{14.1}\]

A linear layer extends linear regression by placing several linear predictors side by side: each receives the same input but has its own weights and bias, producing one component of an output vector. You can think of this as “horizontal stacking” or the “width”, which captures this parallel structure well. Together, these predictors compute Equation 14.1, where each row of (W) contains the weights for one output. Despite the common name linear layer, the bias makes this map affine rather than strictly linear. Each row of \(W\) computes a weighted projection of the input; \(b\) shifts it. A layer with \(m\) outputs therefore produces \(m\) learned features.

Figure 14.1 illustrates an affine layer with four inputs and five outputs. When these outputs are class scores, we call them logits \(z_k\), using the zero-based class indices from the softmax chapter.

from dlbook.network_diagrams import draw_network_diagram

fig = draw_network_diagram("singlelayer")
show_plot(fig)

Four input nodes x_1 through x_4 connect to five output logits z_0 through z_4. Every input connects to every output; biases and softmax are not drawn.

Four input nodes x_1 through x_4 connect to five output logits z_0 through z_4. Every input connects to every output; biases and softmax are not drawn.

Figure 14.1: An affine layer \(z=Wx+b\), with \(W\in\mathbb R^{5\times4}\) and \(b\in\mathbb R^5\). Each arrow represents a weight. The five logits become probabilities only after applying \(p=\operatorname{softmax}(z)\); biases and softmax are omitted from the diagram. Adapted from Dive into Deep Learning (Zhang et al. 2023), CC BY-SA 4.0, with notation updated for this book.

Linear Regression is the special case where \(m=1\), and binary classification, similar to logistic regression, can be done by applying a Sigmoid \(\sigma(\cdot)\) to one such feature; thresholding at \(1/2\) gives a hyperplane decision boundary \(w^\top x+b=0\).

Multi-label multiclass classification works similar to binary classification but makes use of the multiple horizontally stacked linear regressions (when \(m>1\)) using a Sigmoid activation. Single-label multiclass classification can be done by applying the \(\operatorname{softmax}\) function to the output of the map.

You can think of the hyperplane represented by each output of a linear layer as a boundary splitting the domain into two halfspaces, where the halfspace in the direction of the normal vector of the hyperplane is the postive side aligned with the definition of the inner product (dotproduct).

14.4.1 What can a linear layer learn?

TipTry it yourself

Lets consider this very simple 4-datum dataset: \[ \mathcal{D} = \{((0, 0),0),((1, 1),0),((0, 1),1),((1, 0),1)\} \] Can you argue why the above dataset can not be faithfully represented by a linear model?
Draw out the dataset with pen and paper and try to formulate an argument for the above question.
This dataset is referred to as the XOR dataset, as it is derived from applying the XOR operation.

We have seen that Linear models can be remarkably effective when the chosen input features already contain the information needed for the task. But their decision boundaries cannot bend around a class or divide the plane into multiple disconnected regions.

NoteDefinition: Linearly Separable

Data are linearly separable if a hyperplane exists that places all observations of one class strictly on one side and all observations of the other class strictly on the other side.

For the XOR dataset we have already seen that this is impossible, but many other datasets exist that are not linearly separable without further consideration (see Figure 14.2 for common examples).

The same observation can be made for regression problems, where simple functions like \(y=x^2\) already fall outside of what linear regression can faithfully represent. Again: convince yourself using pen and paper that the function can not be represented faithfully as is.

Figure 14.2: Three common examples for datasets that are not linearly separable: XOR, two moons, and two spirals.
NoteCan we make XOR linearly separable?

Can we transform the inputs of \(\mathcal{D}\) using a function \(\phi(x): \mathbb{R}^n \mapsto \mathbb{R}\) such that XOR becomes linearly separable? Try to come up with such a transform on paper.

One possible solution: \(\phi(x)=(x_1-x_2)^2\). Convince yourself that this would make the data linearly separable.

The effort of designing such transformations \(\phi\) is referred to as feature engineering and used to be a central task within machine learning done by researchers.

14.4.2 Does Stacking Layers help?

Ideally we would like our model to be expressive enough to be able to represent data like XOR by itself, such that our optimization procedures automatically adapt the model to perform the necessary (automatically discovered) transformations \(\phi\) to the data.

One could reasonably ask first: Could we stack multiple linear layers to improve expressiveness?

Consider these two stacked affine layers: \[ \begin{aligned} h &= W_1x + b_1 \\ y &= W_2h + b_2 \end{aligned} \]

Substitution gives \[ \begin{aligned} y &= W_2(W_1x+b_1)+b_2\\ &= W_2W_1x + W_2b_1 + b_2 \end{aligned} \]

With \(W'=W_2W_1\) and \(b'=W_2b_1 + b_2\), we obtain \(y=W'x+b'\), which itself is an affine transform. Therefore any finite stack of affine maps is itself affine. More layers alone can not make the decision boundary non-linear. What we need is some way to introduce non-linearities between the layers.

14.5 Activation Functions & Non-Linearities

A (non-linear) activation function \(\phi\) transforms the result of the affine map \(z=Wx+b\) into \(a=\phi(z)\), where we refer to \(a\) as the activation, motivated by the notion of an activation potential in biological neurons. \(\phi\) is usually applied elementwise and for neural networks we require it to be a function that is differentiable (at least almost everywhere, e.g., by having only finite non-differentiable inputs).
For example, the commonly used activation function \(\operatorname{ReLU}(x)=\max(0,x)\) can switch individual learned features on or off depending on the input. A subsequent linear layer combines these input-dependent features into a nonlinear function.

14.5.1 Common Activation Functions

Common activation functions include but are not limited to the ones shown in Table 14.1.

Table 14.1: Common activation functions, their definition, and their typical use.
Formula Name Typical use / consideration
\(\max(0,x)\) ReLU Common hidden-layer baseline; zero slope for negative inputs
\(\frac{1}{1+e^{-x}}\) Sigmoid Binary output probabilities and gates; saturates
\(\tanh(x)\) Tanh Bounded and zero-centred; saturates
\(\max(\alpha x,x)\) Leaky ReLU Nonzero negative-side slope, usually \(0<\alpha<1\)
\(\alpha(e^x-1)\) for \(x<0\), \(x\) otherwise ELU Smooth negative branch away from zero; parameter \(\alpha>0\)
\(x\Phi(x)\) GELU Smooth activation popular in Transformers
\(x\sigma(x)\) Swish / SiLU Smooth, non-monotone activation
\(x\) Identity Often used for unrestricted regression outputs
\(\operatorname{softmax}(\mathbf z)_i=\frac{e^{z_i}}{\sum_j e^{z_j}}\) Softmax Vector-valued multiclass output transform

In Table 14.1, \(\Phi\) denotes the standard normal cumulative distribution function, and \(\sigma\) denotes the sigmoid function. Most of the listed activation functions operate elementwise. Softmax is an exception: it is a vector-valued activation function whose output components depend on all input components. The identity function is also commonly treated as an activation, although it introduces no nonlinearity and is therefore primarily useful for output layers.

In Figure 14.3, we can see both the activation functions and their respective derivatives visualized. Notice: When looking at ReLU one can see that the derivative is only non-zero if the input to the activation function was positive. This both: allows a later optimization procedure to disregard certain parameters, as well as allows the optimization of parameters for piecewise functions.

Figure 14.3: Common activation functions and their derivatives.
TipActivation Choice

Consider the following questions:

  1. What happens to gradient-based learning when the sigmoid activation is evaluated at a very large positive or negative input?
  2. Why can ReLU behave differently, why does it not run into these same issues?

Activation choice affects both what the model can represent and how easily it can be optimized (Glorot and Bengio 2010).

14.5.2 Subderivatives

When characterizing activation functions we required them to be differentiable (at least almost everywhere). For many of these functions that have only a finite number of non-differentiable inputs, we can come up with a “sensible”, canonical values for the derivatives at these points. When doing so we will make use of what is referred to as a subderivative of a function at input \(x\). As an example consider ReLU: its derivative at \(x=0\) is not well defined, as the LHS and RHS limit for the derivative are unequal. Its piecewise derivatives are well defined, with values \(x<0\) having derivative \(relu'(x)=0\) and values \(x>0\) having derivative \(relu'(x)=1\). For training our models, we need to decide how to handle the derivative at such nondifferentiable points. Although we cannot make ReLU differentiable at \(x=0\) by assigning a value to its derivative, we can choose a suitable subgradient for use during backpropagation. In practice, most deep learning frameworks conventionally use \(0\) at this point.

For a convex function \(f\), a number \(g\) is a subgradient at \(x_0\) when: \[ f(x)\ge f(x_0)+g(x-x_0)\qquad\text{for every }x \] The collection of all such \(g\) is its subdifferential \(\partial f(x_0)\). For ReLU, \(\partial\operatorname{ReLU}(0)=[0,1]\): every slope in that interval defines a supporting line (see Figure 14.4). Note that the convex subgradient definition does not automatically extend to arbitrary nonconvex activation functions; generalized gradients require additional definitions.

Figure 14.4: Subgradients and the subdifferential of ReLU at the origin. Each supporting line on the left corresponds to a valid subgradient in [0, 1], shown on the right.

14.6 The Multilayer Perceptron

A multilayer perceptron (MLP) is a feed-forward composition of affine transformations and nonlinearities. Its hidden layers learn representations useful for a final prediction. Their origins trace back to the perceptron, introduced by Frank Rosenblatt in 1958 (Rosenblatt 1958), which can be thought of as a linear layer (or a stack thereof) followed by an threshold activation. Inspired by biological neurons, it was designed as a simple computational model capable of learning linear decision boundaries. The inability to solve nonlinearly separable problems that we already saw, was famously highlighted by Marvin Minsky and Seymour Papert in 1969 (Minsky and Papert 2017). The natural extension was to combine layers of these artificial neurons with nonlinear activation functions, which allowed networks to learn increasingly complex representations. Their practical training and usefulness became much more feasible with the popularization of the backpropagation algorithm popularized by Rumelhart, Hinton, and Williams in 1986 (Rumelhart et al. 1986), which we will introduce in Section 14.8. MLPs subsequently became a foundational architecture in machine learning, establishing many of the principles underlying modern deep learning.

A MLP with \(n\) affine layers is defined as: \[ \begin{aligned} h_1 &= W_1x+b_1 \\ a_1 &= \phi_1(h_1) \\ h_2 &= W_2a_1 + b_2 \\ &\vdots \\ \hat{y} &= W_n a_{n-1} + b_n \end{aligned} \tag{14.2}\]

The final output may itself pass through a task-specific transformation (e.g., sigmoid or softmax). Depth is the number of learnable layers; width is the number of units in a layer. A network with two affine layers and one nonlinear hidden layer is often called a two-layer MLP, and is the simplest neural network architecture. It will be the focus for our ongoing exploration from here on.

Figure 14.5 shows a classification example with four inputs, five hidden units, and three logits. Here \(a_{1,j}\) denotes component \(j\) of the hidden activation vector \(a_1\). The first index identifies the layer, and the second identifies the unit. In particular, these nodes show activations after the nonlinearity, rather than the pre-activations \(h_1\).

fig = draw_network_diagram("mlp")
show_plot(fig)

Four inputs x_1 through x_4 connect to five hidden activations a_{1,1} through a_{1,5}, which connect to three logits z_0 through z_2. Adjacent layers are fully connected.

Four inputs x_1 through x_4 connect to five hidden activations a_{1,1} through a_{1,5}, which connect to three logits z_0 through z_2. Adjacent layers are fully connected.

Figure 14.5: A two-layer MLP: \(h_1=W_1x+b_1\), \(a_1=\phi_1(h_1)\), and \(z=W_2a_1+b_2\), with \(W_1\in\mathbb R^{5\times4}\) and \(W_2\in\mathbb R^{3\times5}\). For classification, \(p=\operatorname{softmax}(z)\) gives the probabilities. For regression, the final affine output is \(\hat y\), as in Equation 14.2. Biases and the task-specific output transformation are omitted. Adapted from Dive into Deep Learning (Zhang et al. 2023), CC BY-SA 4.0, with hidden and output notation updated for this book.

14.6.1 Training a simple MLP

In the following we introduce a high-level description on how to train (read: adapt) a MLPs parameters to a dataset \(\mathcal{D}\). Some of the terms will be unfamiliar but properly introduced in the next sections as needed. Note that the training code in Listing 14.1 and Listing 14.2 is meant to be pseudo-code like and therefore follows no specific frameworks convention, even though it is functional and is used by the training in Section 14.10.

The goal in this section for the reader should be to understand the general “flow” of information and activities when training a neural network.

The central step in training (Listing 14.1) is when we observe a input-output pair and need to adapt the parameters to improve the prediction.

Listing 14.1: One training step: forward pass, backpropagation, and parameter update
def train_step(model, loss, optimizer, x, y):
    optimizer.zero_grad()
    prediction = model.forward(x)
    error = loss.forward(prediction, y)
    grad = loss.backward()
    model.backward(grad)
    optimizer.step()
    return error
0
Reset the gradient to zero, so that we can accumulate the new ones.
1
Apply the models transform. This step is also referred to as “prediction”
2
Calculate the error, between prediction and the true output.
3
Backpropagate the error to obtain the gradient.
4
Adjust the parameters according to the optimizer and gradients. This is “classic” gradient descent as we have seen before.

Outside of this core step, as illustrated in Listing 14.2, we have to setup the training environment consisting (at least) of: the model and its parameters; the optimizer and its hyperparameters; the data as input-output pairs; and the repeated calling of train_step. There we encounter another common technique, that is so immediate, most practitioners would not even notice it as a technique: the usage of epochs in training.

An epoch describes one complete pass through the training dataset. When training with stochastic gradient descent, the order in which observations are presented influences the sequence of parameter updates, since each update changes the model before the next observation is processed.

To reduce systematic effects caused by a fixed observation order, we commonly shuffle the training data at the beginning of each epoch. This helps prevent the model from repeatedly encountering observations in the same potentially biased sequence. Shuffling does not eliminate the stochasticity of SGD or guarantee convergence, but it generally makes training less dependent on the original ordering of the dataset.

Listing 14.2: Training a model over multiple epochs
def train(model, loss, optimizer, Xs, ys, cfg):
    ps = model.parameters()
    opt = optimizer(ps, lr=cfg["lr"])
    loss_fn = loss()
    history = [] 
    for e in range(cfg["epochs"]):
        # optional: reshuffle indices
        for (x,y) in zip(Xs,ys):
            err = train_step(model,loss_fn,opt,x,y)
            history.append(err)
    return history
1
Collect the parameters for the model, so the optimizer can adjust them later.
2
Set up the optimizer, setting the learning rate \(\eta\).
3
Then for a number of rounds (called epochs),
4
and for each observation pair \((x,y)\),
5
perform one training step.

While the example above updates the model after every individual observation, neural networks are commonly trained using mini-batches: small groups of observations processed together. The loss is typically averaged across the batch, and the resulting gradient is used for one parameter update. Mini-batches allow more efficient computation and provide a compromise between the noisy gradients of individual samples and the computational demands of processing the entire dataset at once (also called, batch training). As in previous lessons, we should also monitor performance on a separate validation set to assess whether improvements on the training data translate to unseen observations

14.7 Multivariate Calculus, its Chain Rule & Gradient Descent

In machine learning, we rarely work with functions of just a single variable. Instead, functions typically take multiple inputs, often represented as a column vector \(\mathbf{x}\in\mathbb{R}^n\), and produce either a scalar or another vector. Multivariate calculus extends familiar concepts such as derivatives to these functions. A partial derivative measures how a function changes with respect to one input variable while holding all others constant. For a scalar-valued function \(f:\mathbb{R}^n\to\mathbb{R}\), we collect these partial derivatives into the gradient \(\nabla_{\mathbf{x}}f\), a column vector pointing in the direction of steepest increase of the function.

When a function produces multiple outputs, \(f:\mathbb{R}^n\to\mathbb{R}^m\), we instead collect its partial derivatives into a matrix called the Jacobian. Each row describes how one output changes with respect to all inputs, while each column describes how all outputs respond to changes in one input. The Jacobian therefore generalizes the derivative to vector-valued functions. Both gradients and Jacobians describe local changes, making them essential for understanding how information and derivatives propagate through neural networks.

Concept Function Derivative Shape
Ordinary derivative \(f:\mathbb{R}\to\mathbb{R}\) \(\frac{df}{dx}\) Scalar
Partial derivative \(f:\mathbb{R}^n\to\mathbb{R}\) \(\frac{\partial f}{\partial x_i}\) Scalar
Gradient \(f:\mathbb{R}^n\to\mathbb{R}\) \(\nabla_{\mathbf{x}}f\) \(n\times 1\)
Jacobian \(f:\mathbb{R}^n\to\mathbb{R}^m\) \(J_f\) \(m\times n\)

The key distinction is that the gradient describes how a single output changes with all inputs, whereas the Jacobian describes how multiple outputs change with all inputs. In fact, for a scalar-valued function, the Jacobian is simply the transpose of its gradient: \(J_f=(\nabla_{\mathbf{x}}f)^\top\).

14.7.1 Multivariate Chain Rule

The chain rule allows us to compute derivatives of composed functions, where the output of one function becomes the input of another. In the familiar scalar case, for \(y=f(g(x))\), the derivative is \(\frac{dy}{dx}=f'(g(x))g'(x)\). For vector-valued functions, we generalize the derivative to the Jacobian matrix, which collects all partial derivatives of a function’s outputs with respect to its inputs:

\[ \mathbf{z}=g(\mathbf{x}),\qquad J_g(\mathbf{x})= \begin{bmatrix} \frac{\partial z_1}{\partial x_1}&\cdots&\frac{\partial z_1}{\partial x_n}\\\ \vdots&\ddots&\vdots\\\ \frac{\partial z_m}{\partial x_1}&\cdots&\frac{\partial z_m}{\partial x_n} \end{bmatrix}. \]

For a scalar loss \(L=f(\mathbf{z})\), the multivariate chain rule becomes

\[ \boxed{ \nabla_{\mathbf{x}}L = J_g(\mathbf{x})^\top \nabla_{\mathbf{z}}L } \]

where gradients are column vectors. This is simply the scalar chain rule applied to every possible path through the intermediate variables: \(\frac{\partial L}{\partial x_i}=\sum_{j=1}^{m}\frac{\partial L}{\partial z_j}\frac{\partial z_j}{\partial x_i}\).

In neural networks, this is the mathematical foundation of backpropagation. Starting from the loss, we repeatedly apply the chain rule backwards through the network, multiplying the gradient by the transpose of each layer’s Jacobian. For example, for a linear layer \(\mathbf{z}=W\mathbf{x}+\mathbf{b}\), the Jacobian is simply \(W\), giving \(\nabla_{\mathbf{x}}L=W^\top\nabla_{\mathbf{z}}L\). This allows us to propagate information about how the loss changes from the output of a network back toward its inputs and parameters, enabling gradient-based optimization.

14.7.2 Deriving a Gradient for a 2-layer MLP

We have already seen how the multivariate chain rule allows us to propagate gradients through composed functions. Let us now apply this to a simple two-layer MLP, consisting of one hidden layer with a nonlinear activation function and one output layer. Our goal is to calculate the gradient of a scalar loss \(L\) with respect to all trainable parameters of the network.

For simplicity, we consider a single observation \((x,y)\), use ReLU as our hidden activation function, and leave the output layer without an additional activation function. We define the loss as \(L=\frac12(\hat y-y)^2\), where the factor \(\frac12\) simplifies its derivative. The same principles apply to other activation and loss functions.

14.7.2.1 Forward Pass

Let \(x\in\mathbb R^d\) be our input, \(m\) the number of hidden neurons, and \(\hat y\in\mathbb R\) our scalar prediction. The forward pass consists of three steps:

\[ \begin{aligned} h_1 &= W_1x+b_1 &&\text{(hidden affine layer)}\\ a_1 &= \phi(h_1) &&\text{(hidden activation)}\\ \hat y &= W_2a_1+b_2 &&\text{(output layer)} \end{aligned} \]

Here, \(W_1\in\mathbb R^{m\times d}\), \(b_1\in\mathbb R^m\), \(W_2\in\mathbb R^{1\times m}\), and \(b_2\in\mathbb R\). The activation \(\phi\) is applied elementwise.

Figure 14.6 shows these transformations together with the parameters and target that each operation needs. Each boxed node is a value in the computation; a vector-valued node represents the whole vector, not a single neuron.

from dlbook.backprop_diagrams import draw_backprop_graph

fig = draw_backprop_graph()
show_plot(fig)

The forward computation runs down x, h_1, a_1, yhat, and L. W_1 and b_1 also feed h_1; W_2 and b_2 feed yhat; the observed target y feeds L. The h_1 to a_1 edge applies phi.

The forward computation runs down x, h_1, a_1, yhat, and L. W_1 and b_1 also feed h_1; W_2 and b_2 feed yhat; the observed target y feeds L. The h_1 to a_1 edge applies phi.

Figure 14.6: Computation graph for one regression example: \(h_1=W_1x+b_1\), \(a_1=\phi(h_1)\), \(\hat y=W_2a_1+b_2\), and \(L=\frac12(\hat y-y)^2\). Follow the arrows to compute values in the forward pass; traverse the dependencies in reverse to compute gradients. Both biases are explicit.

Reuse this graph: TikZ source or SVG.

During the forward pass, we retain the intermediate values \(x\), \(h_1\), \(a_1\), and \(\hat y\), as they will be needed to calculate the gradients.

14.7.2.2 Backward Pass

We now work backwards through Figure 14.6, starting at the loss. Rather than differentiating the entire composed function at once, we calculate the gradient of each operation and reuse the results for the preceding operation. For example, the two parameter inputs to \(\hat y\) give \(\nabla_{W_2}L\) and \(\nabla_{b_2}L\), while the path back to \(a_1\) carries \(W_2^\top\nabla_{\hat y}L\). The input \(x\) and target \(y\) are fixed observations, not parameters to update.

Step 1: Gradient of the loss

For our squared-error loss,

\[ L=\frac12(\hat y-y)^2, \]

the derivative with respect to the prediction is

\[ \boxed{\frac{\partial L}{\partial \hat y}=\hat y-y.} \]

This tells us how changing the prediction would locally affect the loss.

Step 2: Gradients of the output layer

Recall that \(\hat y=W_2a_1+b_2\). Applying the chain rule gives

\[ \boxed{ \begin{aligned} \nabla_{W_2}L &= (\hat y-y)a_1^\top,\\ \frac{\partial L}{\partial b_2} &= \hat y-y. \end{aligned} } \]

To propagate the gradient further backwards, we also need the gradient with respect to the input of this layer:

\[ \nabla_{a_1}L=W_2^\top(\hat y-y). \]

Notice that this is exactly the multivariate chain rule introduced earlier: the gradient is multiplied by the transpose of the layer’s Jacobian.

Step 3: Gradient through the activation

The hidden activation is \(a_1=\phi(h_1)\). Since \(\phi\) is applied elementwise, we obtain

\[ \boxed{ \nabla_{h_1}L= \nabla_{a_1}L\odot\phi'(h_1), } \]

where \(\odot\) denotes elementwise multiplication.

For ReLU, \(\phi'(h)=1\) when \(h>0\) and \(0\) when \(h<0\). We conventionally choose \(0\) at \(h=0\). Consequently, neurons that were inactive during the forward pass do not contribute to the parameter gradients for this observation.

Step 4: Gradients of the first layer

Finally, since \(h_1=W_1x+b_1\), we obtain

\[ \boxed{ \begin{aligned} \nabla_{W_1}L &= (\nabla_{h_1}L)x^\top,\\ \nabla_{b_1}L &= \nabla_{h_1}L. \end{aligned} } \]

The matrix product \((\nabla_{h_1}L)x^\top\) is an outer product. Its result has the same shape as \(W_1\), namely \(m\times d\). Each entry tells us how changing one particular weight affects the loss.

We have now calculated the gradients for all four trainable parameter groups: \(W_1\), \(b_1\), \(W_2\), and \(b_2\).

14.7.2.3 Worked Numerical Example

Consider a small network with two input features, two hidden neurons, and one output. We choose the following input, target, and parameters:

\[ x=\begin{bmatrix}1\\2\end{bmatrix}, \qquad y=1, \]

\[ W_1= \begin{bmatrix} 1&-1\\ 2&1 \end{bmatrix}, \quad b_1=\begin{bmatrix}0\\-1\end{bmatrix}, \]

\[ W_2=\begin{bmatrix}0.5&-0.5\end{bmatrix}, \qquad b_2=0. \]

Forward pass. We first calculate the hidden layer:

\[ h_1= \begin{bmatrix} 1&-1\\ 2&1 \end{bmatrix} \begin{bmatrix}1\\2\end{bmatrix} + \begin{bmatrix}0\\-1\end{bmatrix} = \begin{bmatrix}-1\\3\end{bmatrix}. \]

Applying ReLU gives

\[ a_1=\operatorname{ReLU}(h_1) =\begin{bmatrix}0\\3\end{bmatrix}. \]

The output and loss are therefore

\[ \begin{aligned} \hat y &= \begin{bmatrix}0.5&-0.5\end{bmatrix} \begin{bmatrix}0\\3\end{bmatrix}=-1.5,\\ L &= \frac12(-1.5-1)^2=3.125. \end{aligned} \]

Backward pass. Starting with the loss, we obtain

\[ \frac{\partial L}{\partial\hat y} =\hat y-y=-2.5. \]

For the output layer, this gives

\[ \begin{aligned} \nabla_{W_2}L &=-2.5\begin{bmatrix}0&3\end{bmatrix} =\begin{bmatrix}0&-7.5\end{bmatrix},\\ \frac{\partial L}{\partial b_2}&=-2.5. \end{aligned} \]

Propagating the gradient to the hidden activations:

\[ \nabla_{a_1}L = \begin{bmatrix}0.5\\-0.5\end{bmatrix}(-2.5) = \begin{bmatrix}-1.25\\1.25\end{bmatrix}. \]

Since \(h_1=(-1,3)^\top\), the first ReLU neuron was inactive and the second was active. Thus,

\[ \nabla_{h_1}L = \begin{bmatrix}-1.25\\1.25\end{bmatrix} \odot \begin{bmatrix}0\\1\end{bmatrix} = \begin{bmatrix}0\\1.25\end{bmatrix}. \]

Finally, the first-layer parameter gradients are

\[ \begin{aligned} \nabla_{W_1}L &= \begin{bmatrix}0\\1.25\end{bmatrix} \begin{bmatrix}1&2\end{bmatrix} = \begin{bmatrix} 0&0\\ 1.25&2.5 \end{bmatrix},\\[6pt] \nabla_{b_1}L &=\begin{bmatrix}0\\1.25\end{bmatrix}. \end{aligned} \]

Notice that the entire first row of \(\nabla_{W_1}L\) is zero. This is a direct consequence of the first hidden neuron being inactive: for this observation, small changes to its weights do not affect the prediction.

We can now perform a gradient descent update, for example with learning rate \(\eta=0.1\):

\[ W_1^{\text{new}} =W_1-\eta\nabla_{W_1}L = \begin{bmatrix} 1&-1\\ 1.875&0.75 \end{bmatrix}. \]

The same update rule is applied to \(b_1\), \(W_2\), and \(b_2\). Updating all four parameter groups simultaneously gives a new prediction of \(\hat y=0.8125\) and a reduced loss of approximately \(0.0176\) for this observation. Notice that this substantial improvement is specific to our chosen example and learning rate; a single gradient descent step does not generally guarantee a decrease in the loss.

14.7.2.4 Generalization

The procedure above can be summarized by introducing the intermediate gradients \(\delta_2=\nabla_{\hat y}L\) and \(\delta_1=\nabla_{h_1}L\):

\[ \begin{aligned} \delta_2 &= \hat y-y,\\ \nabla_{W_2}L &= \delta_2a_1^\top,\\ \nabla_{b_2}L &= \delta_2,\\ \delta_1 &= (W_2^\top\delta_2)\odot\phi'(h_1),\\ \nabla_{W_1}L &= \delta_1x^\top,\\ \nabla_{b_1}L &= \delta_1. \end{aligned} \]

These equations are the essential building blocks of backpropagation. For deeper networks, we simply repeat the same procedure, propagating gradients from one layer to the preceding one. For vector-valued outputs, \(\delta_2\) becomes a vector determined by the chosen output transformation and loss function.

Importantly, the gradients tell us how to change the parameters, but do not change them themselves. Updating parameters remains the responsibility of an optimization algorithm, such as gradient descent.

In the accompanying lab, you will implement these operations for a small MLP yourself and compare the resulting gradients against those obtained using automatic differentiation.

14.7.2.5 Adding a regularizer: gradients from two paths

How does the graph change when we add the weight penalty from Chapter 3? Keep the data loss \(L=\frac12(\hat y-y)^2\), and define

\[ R=\|W_1\|_F^2+\|W_2\|_F^2,\qquad J=L+\lambda R,\qquad \lambda\ge0. \]

Here \(\|W_l\|_F^2\) is the sum of squared matrix entries. We leave biases unpenalized. The penalty uses Chapter 3’s convention without a factor \(\frac12\), so its weight gradient is \(2\lambda W_l\).

fig = draw_backprop_graph(regularized=True)
show_plot(fig)

The forward graph x to h_1 to a_1 to yhat to L is extended by a regularizer R that depends on W_1 and W_2. L and lambda times R feed the objective J. Each weight matrix reaches J through both the data-loss path and the regularizer path. Biases feed only the affine layers.

The forward graph x to h_1 to a_1 to yhat to L is extended by a regularizer R that depends on W_1 and W_2. L and lambda times R feed the objective J. Each weight matrix reaches J through both the data-loss path and the regularizer path. Biases feed only the affine layers.

Figure 14.7: The regularized computation graph. Each weight matrix contributes to \(J\) through the prediction and through \(R\); backpropagation adds the gradient contributions from both paths. The edge labelled \(\lambda\) represents multiplication by the fixed regularization strength before adding to \(L\).

Reuse this graph: TikZ source or SVG.

Starting from \(J\), we have \(\partial J/\partial L=1\) and \(\partial J/\partial R=\lambda\). The hidden error signals \(\delta_2\) and \(\delta_1\) are unchanged because \(R\) does not depend on the activations. At the weights, add the two contributions:

\[ \begin{aligned} \nabla_{W_2}J &= \delta_2a_1^\top+2\lambda W_2, &\nabla_{b_2}J &= \delta_2,\\ \nabla_{W_1}J &= \delta_1x^\top+2\lambda W_1, &\nabla_{b_1}J &= \delta_1. \end{aligned} \]

For a mini-batch, average the data-loss gradients and add the penalty gradient once. Do not divide \(2\lambda W_l\) by the batch size. This is one example of gradient accumulation at a shared parameter, the same rule used by automatic differentiation when a value feeds several operations.

14.7.3 A Short Introduction to Autodifferentiation

So far, we have calculated derivatives by hand and used the chain rule to propagate gradients through a neural network. While this is useful for understanding how learning works, manually deriving and implementing gradients becomes increasingly impractical as models grow in complexity. Automatic differentiation (autodiff) solves this problem by automatically computing derivatives of functions implemented as computer programs. Unlike numerical differentiation, which approximates derivatives using small perturbations, autodiff applies the chain rule to elementary operations, producing derivatives that are accurate up to floating-point precision.

Modern deep learning frameworks such as PyTorch provide built-in automatic differentiation. When performing operations on tensors with requires_grad=True, PyTorch records the operations in a computation graph. Calling .backward() on a scalar result then traverses this graph in reverse, applying the chain rule to calculate gradients with respect to the relevant tensors. This process is known as reverse-mode automatic differentiation, and it is particularly efficient for neural networks, where a single scalar loss depends on potentially millions of parameters.

For example, consider the function \(f(x) = x^2 + 2x\). We can calculate its derivative at \(x=3\) using PyTorch:

import torch

x = torch.tensor(3.0, requires_grad=True)
y = x**2 + 2*x

y.backward()

print(f"Gradient (x={x}, f(x)=x²+2x): {x.grad}") # Note: x.grad is also of type Tensor
Gradient (x=3.0, f(x)=x²+2x): 8.0

Here, PyTorch constructs the computation graph while evaluating y and calculates \(\frac{dy}{dx} = 2x + 2 = 8\) when we call backward(). The resulting gradient is stored in x.grad. Importantly, PyTorch accumulates gradients by default, meaning that repeated calls to backward() add to existing gradients rather than replacing them. During neural network training, we therefore typically reset gradients using optimizer.zero_grad() before each backward pass (as we did in Listing 14.1). The optimizer can then use the newly computed gradients to update the model parameters.

Although we can use autodiff without implementing it ourselves, understanding its basic principles helps us reason about computational cost, memory usage, and common errors during training. In particular, it is useful to distinguish between the forward pass, which evaluates the function and records the necessary operations, and the backward pass, which propagates derivatives through the computation graph. For a more detailed explanation of computation graphs, forward- and reverse-mode differentiation, and how an automatic differentiation engine can be implemented, refer to the additional material on automatic differentiation.

14.8 Backpropagation

We have already seen how to calculate the gradients of a two-layer MLP by repeatedly applying the multivariate chain rule. However, for larger networks, calculating each parameter derivative independently would require us to repeatedly evaluate many of the same intermediate derivatives. This quickly becomes computationally expensive.

Backpropagation is an efficient algorithm for calculating the gradients of a scalar loss with respect to all parameters of a neural network. It works by traversing the network in reverse order, propagating gradients from the output towards the input while reusing previously calculated intermediate results.(Rumelhart et al. 1986)

Importantly, backpropagation does not update the parameters itself. It only calculates the gradients, which are subsequently used by an optimization algorithm such as gradient descent.

14.8.1 Algorithm

The algorithm consists of two passes through the network:

  1. Forward pass: Evaluate the network and store intermediate values required for differentiation.
  2. Backward pass: Starting with the derivative of the loss, propagate gradients backwards through the network, calculating parameter gradients along the way.

For a network with \(n\) layers, we can describe each layer using

\[ \begin{aligned} h_l &= W_la_{l-1}+b_l,\\ a_l &= \phi_l(h_l), \end{aligned} \]

where \(a_0=x\) is the network input, \(W_l\) and \(b_l\) are the parameters of layer \(l\), and \(\phi_l\) is its activation function. We assume that the final activation, if present, is included in \(\phi_n\).

During the forward pass, we retain the activations \(a_l\) and pre-activation values \(h_l\). These are needed when evaluating the derivatives during the backward pass.

For the backward pass, we introduce the error signal

\[ \delta_l=\nabla_{h_l}L, \]

which represents the gradient of the loss with respect to the pre-activation values of layer \(l\).

Starting at the final layer, we calculate

\[ \delta_n=J_{\phi_n}(h_n)^\top\nabla_{a_n}L. \]

For each preceding layer, the error signal is then calculated recursively:

\[ \boxed{ \delta_l=J_{\phi_l}(h_l)^\top W_{l+1}^\top\delta_{l+1}. } \]

Here, \(J_{\phi_l}(h_l)\) is the Jacobian of the activation. For elementwise activations such as ReLU, sigmoid, and tanh, this Jacobian is diagonal, so the recursion simplifies to

\[ \delta_l=(W_{l+1}^\top\delta_{l+1})\odot\phi_l'(h_l). \]

Softmax is not elementwise. For \(a=\operatorname{softmax}(h)\), its Jacobian is \(J_{\mathrm{softmax}}(h)=\operatorname{diag}(a)-aa^\top\).

Once \(\delta_l\) is known, the parameter gradients follow directly:

\[ \boxed{ \begin{aligned} \nabla_{W_l}L &= \delta_l a_{l-1}^{\top},\\ \nabla_{b_l}L &= \delta_l. \end{aligned} } \]

Notice that we do not need to construct the complete Jacobian of the network. Instead, we repeatedly multiply the incoming gradient by the transpose of the relevant weight matrix and apply the local activation derivative. This is one of the reasons why backpropagation is computationally efficient.

The following pseudocode illustrates the algorithm for a sequence of layers:

def backward(layers, loss_gradient):
    grad = loss_gradient

    for layer in reversed(layers):
        grad = layer.backward(grad)

Here, each layer’s backward method is responsible for two things: calculating and storing its own parameter gradients, and returning the gradient with respect to its input. For an affine layer, this can be implemented as:

def backward(self, grad):
    # grad = dL/dh
    self.dW = np.outer(grad, self.x)
    self.db = grad.copy()

    return self.W.T @ grad

The affine layer must have stored its input self.x during the forward pass. Similarly, an elementwise activation layer needs to retain its pre-activation values to evaluate the local derivative:

def backward(self, grad):
    return grad * self.activation_derivative(self.x)

For a complete MLP, these operations alternate as we traverse the network backwards: an activation layer transforms the incoming gradient, and an affine layer calculates parameter gradients and propagates the result further.

NoteWhy propagate backwards?

The gradient of an early layer depends on all subsequent transformations. We therefore cannot calculate its gradient without first knowing how the loss responds to the output of that layer.

By starting at the loss and working backwards, each intermediate gradient is calculated only once and can be reused immediately by the preceding layer.

This is also why reverse-mode automatic differentiation is particularly well suited to neural networks: we typically have a single scalar loss but potentially millions of trainable parameters.

14.8.2 Application

Having derived the gradients for a small MLP, we can now implement the backward pass ourselves. The implementation follows exactly the same steps as our mathematical derivation, but separates the calculations into reusable components.

In the accompanying lab, you will implement the forward and backward operations of affine layers and activation functions, combine them into a two-layer MLP, and train the resulting network using gradient descent.

To verify that your implementation is correct, you will compare the calculated gradients against those produced by an automatic differentiation framework (Gradcheck Mechanics &#X2014; PyTorch 2.14 Documentation — Docs.pytorch.org). You can additionally use finite differences to approximate individual derivatives numerically:

\[ \frac{\partial L}{\partial\theta_i} \approx \frac{L(\theta_i+\epsilon)-L(\theta_i-\epsilon)}{2\epsilon}, \]

where \(\theta_i\) denotes one model parameter and \(\epsilon\) is a small perturbation. This technique is known as gradient checking and is particularly useful for identifying mistakes in manually implemented backward passes.

Once your implementation is working, we can apply it to the XOR dataset introduced earlier. Unlike a linear classifier, our two-layer MLP can learn a nonlinear decision boundary without requiring us to manually construct suitable input features.

14.9 Universal Approximation Theorem

The universal approximation theorem (UAT) states the following:

Tip

A one hidden layer MLP, with a sufficient number of neurons, and a suitable nonlinear activation function can approximate any continuous function on a compact subset of \(\mathbb{R}^n\) to arbitrary accuracy Hornik (1991).

\[ \begin{aligned} f(x)&\approx \sum_{i=1}^{N(\epsilon)}{a_i\sigma(w_i\cdot x + b)}\\ &\text{where }\sigma\text{ is a suitable activation function}. \end{aligned} \tag{14.3}\]

The Universal Approximation Theorem (illustrated in Equation 14.3) tells us that a sufficiently large multilayer perceptron (MLP) can approximate a remarkably broad class of functions. Therefore (at least in theory), we do not need arbitrarily deep networks to represent complicated nonlinear relationships. Even a relatively simple MLP architecture can represent highly complex functions, provided we allow enough neurons in its hidden layer.

However, the theorem makes an important distinction between representing a function and learning it. It only guarantees that suitable network parameters exist, but it does not tell us how to find them. In particular, it does not guarantee that gradient descent will converge to these parameters, how many neurons we will need, or how much training data is required. Furthermore, the theorem concerns approximation on a bounded domain and does not guarantee that the learned function will generalize well to unseen data. A network might theoretically be capable of representing the desired function while still being extremely difficult to train in practice.

For us, the Universal Approximation Theorem provides an important theoretical justification for using MLPs as general-purpose function approximators. Rather than manually designing increasingly complicated mathematical models, we can construct a neural network and let its parameters adapt to the relationships present in our data. Nonetheless: expressive power alone does not make a good model.

Network architecture, depth, width, activation functions, optimization, and the available training data all influence how effectively a function can be learned. In practice, deeper networks can often represent certain functions much more efficiently than very wide, shallow networks, which helps explain why modern neural networks frequently use many hidden layers.

14.9.1 Tangent: Kolmogorov-Arnold Representation Theorem

We also want to mention the Kolmogorov–Arnold Representation Theorem (KART)(Kolmogorov 1957) as another fascinating perspective on function approximation. It states that any continuous multivariate function on a compact hypercube can be represented exactly as a finite composition and sum of continuous univariate functions (see Equation 14.4). \[ f(x) = \sum^{2n+1}_{q=1}{\Phi_q (\sum^{n}_{p=1}{\phi_{q,p}(x_p)})} \tag{14.4}\]

Unlike the Universal Approximation Theorem, which establishes that neural networks can approximate functions arbitrarily well, KART provides an exact representation using functions of only one variable. This suggests an alternative approach to neural network design: rather than learning weights between neurons with fixed (univariate) activation functions, we could learn the univariate functions themselves. This idea motivates Kolmogorov–Arnold Networks (KANs)(Liu et al. 2025), a relatively recent alternative to conventional MLPs. However, the theorem alone does not guarantee that such networks are easier to train or more efficient in practice. For a deeper exploration of the theorem, its implications, and the architecture of KANs, refer to the additional material on Kolmogorov–Arnold representations.

14.10 Applying our own MLP to XOR

After the above theoretical and practical considerations we finally have all building blocks at hand to be able to train our first (small) MLP. To show the expanded capabilities of our model compared to linear regressions and the perceptron, we again use the XOR dataset. This dataset, which we could not represent before (at least not without explicit feature engineering), can now be easily learned as demonstrated in Listing 14.3.

One thing to note for this implementation: as the gradients of the model are easily obtained, the implementation makes use of a very small handcrafted “neural network library” including an implementation of backpropagation. To recreate this will be one of the tasks in the lab for this chapter.

Listing 14.3: Training a two-layer MLP on XOR
from dlbook.autodiff import SGD, MSE, Sequential, Dense, Tanh, Sigmoid

X = np.array([
    [0., 0.],
    [0., 1.],
    [1., 0.],
    [1., 1.],
])

Y = np.array([
    [0.],
    [1.],
    [1.],
    [0.],
])

model = Sequential(
    Dense(2, 8),
    Tanh(),
    Dense(8, 1),
    Sigmoid(),
)

loss = MSE
optimizer = SGD
history = train(
    model, loss, optimizer,
    X, Y,
    {"epochs":3000, "lr":0.1},
)

for x, y in zip(X, Y):
    prediction = model.forward(x)
    print(f"{x} -> {prediction[0]:.3f} (target: {y[0]})")
[0. 0.] -> 0.012 (target: 0.0)
[0. 1.] -> 0.978 (target: 1.0)
[1. 0.] -> 0.974 (target: 1.0)
[1. 1.] -> 0.028 (target: 0.0)

(a) The learned decision boundary of the 2-layer MLP.

(b) Loss history over training duration.
Figure 14.8: Results of our 2-layer MLP training example.

14.11 Knowledge check

Go through the following questions, one by one, and write down an answer on a piece of paper, and importantly do so without looking at above material again while answering. If there is something you are missing for your answer, make a note on the page of what is missing (this will help you in reviewing the material afterwards). Strive for a level of writing where another student would be able to understand the material from your writing.

Important: We know the act of writing it on paper might feel redundant, but it enforces accountability and prevents handwaveiness in the answers. Seriously – do it in writing.

  1. Why does stacking affine layers without nonlinear activations not increase the class of representable functions?
  2. What distinguishes a gradient from a Jacobian?
  3. Why does backpropagation process layers in reverse order?
  4. What is the difference between backpropagation and gradient descent?
  5. What does the Universal Approximation Theorem guarantee, and what does it not guarantee?

14.12 Summary

In this lesson, we extended linear models into multilayer perceptrons by composing affine transformations with nonlinear activation functions. These nonlinearities allow networks to represent relationships that linear models cannot capture, like XOR. We introduced backpropagation as an efficient application of the multivariate chain rule and explored how automatic differentiation makes gradient calculation practical. Finally, the Universal Approximation Theorem provided a theoretical perspective on the expressive power of MLPs, while reminding us that the ability to represent a function does not guarantee that we can successfully learn a useful representation.