Deep Neural Networks, Backpropagation and Optimization
Deep Neural Networks (also known as Multi-Layer Perceptrons) are universal approximators: with enough neurons, they approximate any continuous function on a closed and bounded domain. This post presents their layers and activation functions, backpropagation in matrix form, and their training with stochastic gradient descent, each with its NumPy code.
Feedforward Networks and Activation Functions
A feedforward network has an input layer of size \(D\), \(L\) hidden layers of size \(K\) and an output layer, and its computation flows from the input to the output, with no feedback loop. In a fully connected network, each neuron is connected to every neuron of the next layer.
Each layer computes the weighted sums of its inputs, adds the biases and applies an activation function \(\phi\) to each entry. For a mini-batch of \(B\) samples, one per row (batch first, as in PyTorch), the layer \(l\) is computed with one matrix multiplication as:
\[\begin{align*} Z^{(l)} & = X^{(l-1)} W^{(l)} + \mathbf{1} b^{(l)} \\ X^{(l)} & = \phi(Z^{(l)}) \end{align*}\]where \(X^{(l-1)}\) is the \(B \times n_{\text{in}}\) input of the layer, \(W^{(l)}\) the \(n_{\text{in}} \times n_{\text{out}}\) matrix of its weights, with one column per neuron, \(b^{(l)}\) the row vector of its biases, and \(\mathbf{1}\) a column of \(B\) ones, so that \(\mathbf{1} b^{(l)}\) adds the biases to every row. Each row of the input \(X^{(0)}\) holds the \(D\) inputs of one sample, and the output of the network is \(\hat{Y} = X^{(L+1)}\), whose layer usually has no activation function for regression, and a softmax for classification.
Note that \(\phi\) must be non-linear, as a stack of linear layers is a single linear layer. The most common activation functions are:
- sigmoid: \(\phi(x) = \frac{1}{1+e^{-x}}\), positive and bounded;
- tanh: \(\phi(x) = \frac{e^x - e^{-x}}{e^x+e^{-x}}\), positive and negative, and bounded;
- ReLU (Rectified Linear Unit): \(\phi(x) = \max\{0,x\}\), cheap, and its derivative is 1 for every positive input, which helps fight vanishing gradients;
- Leaky ReLU: \(\phi(x) = \max \{\alpha x,x\}\), with \(0 < \alpha < 1\), whose derivative is never 0. It fixes the dying ReLU: a ReLU whose input is negative for every sample has a zero derivative, so its weights stop learning;
- GELU (Gaussian Error Linear Unit): \(\phi(x) = x \, \Phi(x)\), where \(\Phi\) is the cumulative distribution function of the standard Gaussian. It is a smooth ReLU, used in many Transformers;
- Swish (or SiLU): \(\phi(x) = x \, \sigma(x) = \frac{x}{1+e^{-x}}\), where \(\sigma\) is the sigmoid. It is also a smooth ReLU, very close to GELU.
The following picture shows these functions and their derivatives:
ReLU and its variants are the default for hidden layers, and the sigmoid and tanh are used where a bounded output is needed, e.g. a probability. The Transformers of recent LLMs use a SwiGLU instead: a gated linear unit that multiplies the Swish of one linear layer by a second linear layer, entry by entry:
\[\text{SwiGLU}(X) = \text{Swish}(X W) \odot (X V)\]where \(W\) and \(V\) are two weight matrices, and \(\odot\) is the element-wise (Hadamard) product. The second layer acts as a gate that scales each output of the first one. For the same compute, it gives a lower loss than a ReLU or a GELU.
Backpropagation
Training minimizes the loss \(\mathcal{L}\), the error of the outputs of the network, with gradient descent, which needs \(\partial \mathcal{L} / \partial W^{(l)}\) and \(\partial \mathcal{L} / \partial b^{(l)}\) for every layer, matrices of the shapes of \(W^{(l)}\) and \(b^{(l)}\). The backpropagation algorithm computes them all with one forward and one backward pass. The chain rule gives one rule per operation: each operation receives the derivative of the loss with respect to its output and returns the derivative with respect to its input, from the loss back to the first layer. The derivative of the loss with respect to \(Z^{(l)}\), the input of the activation function, is the error of the layer:
\[\delta^{(l)} = \frac{\partial \mathcal{L}}{\partial Z^{(l)}}\]a matrix of the shape of \(Z^{(l)}\), with one row per sample.
The following picture illustrates a training step, for three linear layers without biases and activation functions:
The forward pass (blue) keeps the input \(X^{(l-1)}\) of each layer, and computes the loss \(\ell\) of each sample and their mean \(\mathcal{L}\). The backward pass (green) runs from the error \(\delta^{(3)}\) of the output layer to the first layer. Each layer \(l\) reuses \(X^{(l-1)}\) and \(W^{(l)}\) to compute \(\partial \mathcal{L} / \partial W^{(l)}\) and the error \(\delta^{(l-1)}\) of the previous layer. The optimizer update then subtracts a small multiple of \(\partial \mathcal{L} / \partial W^{(l)}\) from each \(W^{(l)}\).
The rules follow from the loss written out. Consider the output layer of a network with one output and no activation function, trained with the mean squared error (MSE) of least squares:
\[\mathcal{L} = \frac{1}{B} \lVert y - \hat{y} \rVert^2, \quad \hat{y} = X w + \mathbf{1} b\]where \(y\) and \(\hat{y}\) are the column vectors of the \(B\) targets and outputs, \({X = X^{(L)}}\) is the input of the layer, \({w = W^{(L+1)}}\) a column vector and \({b = b^{(L+1)}}\) a scalar. Four identities of matrix calculus are enough (The Matrix Cookbook, eqs. 69, 81, 70 and 77):
\[\begin{align*} \frac{\partial a^T w}{\partial w} & = a, & \frac{\partial w^T A w}{\partial w} & = 2 A w \;\; (A = A^T), \\ \frac{\partial a^T X c}{\partial X} & = a c^T, & \frac{\partial c^T X^T X c}{\partial X} & = 2 X c c^T \end{align*}\]First, the error of the output layer, whose output is \(\hat{y} = Z^{(L+1)}\), is given by:
\[\delta^{(L+1)} = \frac{\partial}{\partial \hat{y}} \frac{1}{B} (y - \hat{y})^T (y - \hat{y}) = -\frac{2}{B} (y - \hat{y})\]Then, with \(e = y - \mathbf{1} b\), the loss expands to \(\frac{1}{B} (e^T e - 2 e^T X w + w^T X^T X w)\), and the identities give its derivatives with respect to the weights, the bias and the input of the layer:
\[\begin{align*} \frac{\partial}{\partial w} \frac{1}{B} \lVert y - X w - \mathbf{1} b \rVert^2 & = \frac{1}{B} (-2 X^T e + 2 X^T X w) = -\frac{2}{B} X^T (y - \hat{y}) = X^T \delta^{(L+1)} \\ \frac{\partial}{\partial b} \frac{1}{B} \lVert y - X w - \mathbf{1} b \rVert^2 & = -\frac{2}{B} \mathbf{1}^T (y - \hat{y}) = \mathbf{1}^T \delta^{(L+1)} \\ \frac{\partial}{\partial X} \frac{1}{B} \lVert y - X w - \mathbf{1} b \rVert^2 & = \frac{1}{B} (-2 e w^T + 2 X w w^T) = -\frac{2}{B} (y - \hat{y}) w^T = \delta^{(L+1)} w^T \end{align*}\]Finally, \(X = \phi(Z^{(L)})\), with \(\phi\) applied to each entry, so the derivative with respect to \(Z^{(L)}\) is the derivative with respect to \(X\) times \(\phi'(Z^{(L)})\), entry by entry:
\[\delta^{(L)} = \frac{\partial}{\partial Z^{(L)}} \frac{1}{B} \lVert y - \phi(Z^{(L)}) w - \mathbf{1} b \rVert^2 = \left( \delta^{(L+1)} w^T \right) \odot \phi'(Z^{(L)})\]With several outputs, each column of \(W^{(L+1)}\) is one such \(w\): the derivatives with respect to the columns stack into \(X^T \delta^{(L+1)}\), and the derivatives with respect to \(X\) add up to \(\delta^{(L+1)} (W^{(L+1)})^T\). These results depend on the loss only through \(\delta^{(L+1)}\), so every layer follows the same rules, with its own error, and other losses only change \(\delta^{(L+1)}\).
The following table sums up the rules of each operation:
| Operation | Forward | Backward |
|---|---|---|
| Linear layer | \({Z = X W + \mathbf{1} b}\) | \({\partial \mathcal{L} / \partial W = X^T \delta}\) \({\partial \mathcal{L} / \partial b = \mathbf{1}^T \delta}\) \({\partial \mathcal{L} / \partial X = \delta W^T}\) |
| Activation | \({X = \phi(Z)}\) | \({\delta = (\partial \mathcal{L} / \partial X) \odot \phi'(Z)}\) |
| MSE | \({\mathcal{L} = \frac{1}{B} \lVert y - \hat{y} \rVert^2}\) | \({\delta = -\frac{2}{B} (y - \hat{y})}\) |
Chaining the rules gives the errors and the derivatives of all layers, from the output layer to the first one:
\[\begin{align*} \delta^{(l)} & = \left( \delta^{(l+1)} (W^{(l+1)})^T \right) \odot \phi'(Z^{(l)}) \\ \frac{\partial \mathcal{L}}{\partial W^{(l)}} & = (X^{(l-1)})^T \delta^{(l)} \\ \frac{\partial \mathcal{L}}{\partial b^{(l)}} & = \mathbf{1}^T \delta^{(l)} \end{align*}\]The following picture illustrates both passes for a network with one hidden layer, as the NumPy code below computes them:
The forward pass (left, up from the input) and the backward pass (right, down from the loss) of a network with one hidden layer, trained with the MSE. Each blue box is a forward method of the code, each green box the matching backward method, and the dashed arrows are the tensors that the forward pass saves for the backward pass.
Each layer runs one matrix product in the forward pass, \(X^{(l-1)} W^{(l)}\), and two of the same size in the backward pass, \(\delta^{(l)} (W^{(l)})^T\) and \((X^{(l-1)})^T \delta^{(l)}\), so a training step costs about three forward passes. The backward pass also needs the \(X^{(l-1)}\) and \(Z^{(l)}\) of every layer (the dashed arrows), so training keeps them in memory from the forward pass.
In NumPy, each parameter holds its values (data) and the derivative of the loss with respect to them (grad), as a PyTorch tensor does. The forward method of a linear layer computes \(Z^{(l)}\). Its backward method receives \(\delta^{(l)}\), adds \((X^{(l-1)})^T \delta^{(l)}\) and \(\mathbf{1}^T \delta^{(l)}\) to the grad of the parameters, and returns \(\delta^{(l)} (W^{(l)})^T\) to the layer below. The weights start as values drawn from a standard Gaussian, and the biases start at zero. Deeper networks scale the weights by \(\sqrt{2 / n_{\text{in}}}\) (He initialization), so that the activations keep the same scale across layers, where the factor 2 makes up for the half of its inputs that a ReLU sets to zero:
import numpy as np
class Parameter:
def __init__(self, data):
self.data, self.grad = data, np.zeros_like(data)
class Linear:
def __init__(self, n_in, n_out):
self.W = Parameter(np.random.randn(n_in, n_out)) # standard Gaussian
self.b = Parameter(np.zeros((1, n_out)))
def forward(self, x):
self.x = x # saved for the backward pass
return x @ self.W.data + self.b.data
def backward(self, delta):
self.W.grad += self.x.T @ delta
self.b.grad += delta.sum(axis=0, keepdims=True)
return delta @ self.W.data.T
def parameters(self):
return [self.W, self.b]
Note that backward adds to grad, so that a parameter used more than once sums its derivatives. Then, the backward method of the ReLU multiplies the derivative of the loss with respect to its output by \(\phi'(Z^{(l)})\), which is 1 where \(Z^{(l)} > 0\) and 0 elsewhere:
class ReLU:
def forward(self, z):
self.z = z # saved for the backward pass
return np.maximum(0, z)
def backward(self, dx):
return dx * (self.z > 0)
def parameters(self):
return []
Automatic Differentiation
Backpropagation is a special case of automatic differentiation (autodiff), which evaluates the derivatives of a function written as a program by applying the chain rule to its elementary operations. For a function made of \(L\) operations, \(x_l = f_l(x_{l-1})\), from the input \(x_0\) to the output \(x_L\), the chain rule gives:
\[\frac{\partial x_L}{\partial x_0} = \frac{\partial x_L}{\partial x_{L-1}} \, \frac{\partial x_{L-1}}{\partial x_{L-2}} \cdots \frac{\partial x_1}{\partial x_0}\]The reverse mode of autodiff computes this product from the output back to the input. Starting from \(\partial x_L / \partial x_L = 1\), each operation multiplies the derivative of the output with respect to its own output by its local derivative:
\[\frac{\partial x_L}{\partial x_{l-1}} = \frac{\partial x_L}{\partial x_l} \, \frac{\partial x_l}{\partial x_{l-1}}\]which is the backward pass above, with the loss as the output. One backward pass gives the derivatives of the output with respect to all the variables, while the forward mode, which computes the product from the input, needs one pass per input variable. So a network, with millions of parameters and one scalar loss, is trained in reverse mode.
The two layers above are enough for a minimal reverse-mode autodiff. A multi-layer perceptron (MLP) stores its layers in a list, in the order of the forward pass, which plays the role of the computational graph. Its backward method runs the layers in reverse order, from the error \(\delta^{(L+1)}\) of the output layer to the first layer:
class MLP:
def __init__(self, sizes):
self.layers = []
for n_in, n_out in zip(sizes[:-1], sizes[1:]):
self.layers += [Linear(n_in, n_out), ReLU()]
self.layers.pop() # no activation after the output layer
def forward(self, x):
for layer in self.layers:
x = layer.forward(x)
return x
def backward(self, delta):
for layer in reversed(self.layers):
delta = layer.backward(delta)
return delta # the derivative of the loss with respect to the input
def parameters(self):
return [theta for layer in self.layers for theta in layer.parameters()]
Stochastic Gradient Descent
Backpropagation gives the gradient \(g_t\) of the loss with respect to the parameters \(\theta\) of the network (all its weights and biases) at the step \(t\) of the training, and an optimizer uses it to update them. Gradient descent (GD) takes a step against the gradient, of a size set by the learning rate \(\eta\):
\[\theta_t = \theta_{t-1} - \eta \, g_t\]GD computes \(g_t\) over all \(N\) training samples. Stochastic gradient descent (SGD) computes it on a random mini-batch of \(B\) samples instead: a noisy but unbiased estimate of the gradient, \(N/B\) times cheaper.
In code, the optimizer holds the parameters of a model. Its zero_grad method resets their derivatives, which the backward pass accumulates, and its step method updates them, with a default learning rate of \(10^{-3}\):
class SGD:
def __init__(self, parameters, eta=1e-3):
self.parameters, self.eta = parameters, eta
def zero_grad(self):
for theta in self.parameters:
theta.grad.fill(0)
def step(self):
for theta in self.parameters:
theta.data -= self.eta * theta.grad
Training Loop
Last, the loss: MSELoss computes the MSE in forward, and returns the error \(\delta^{(L+1)} = -\frac{2}{B} (y - \hat{y})\) in backward:
class MSELoss:
def forward(self, y_hat, y):
self.y_hat, self.y = y_hat, y # saved for the backward pass
return np.mean((y - y_hat)**2)
def backward(self):
B = self.y.size # samples in the mini-batch, with one output each
return -2 * (self.y - self.y_hat) / B
The following loop trains an MLP on a continuous XOR: points drawn uniformly in \([-1, 1]^2\), with the target 1 when their two coordinates have different signs and 0 otherwise. Each step draws a random mini-batch of \(B = 32\) samples, resets the derivatives, and runs the forward pass, the loss, the backward pass and the optimizer step, as a PyTorch training loop does:
def xor_data(N):
x = np.random.uniform(-1, 1, (N, 2))
y = (x[:, 0] * x[:, 1] < 0).astype(float).reshape(N, 1) # 1 if the signs differ
return x, y
np.random.seed(0)
N, B = 1024, 32 # training samples, mini-batch size
x, y = xor_data(N)
x_test, y_test = xor_data(256)
model = MLP([2, 16, 16, 1])
loss_fn = MSELoss()
optimizer = SGD(model.parameters())
for step in range(20000):
n = np.random.choice(N, B, replace=False) # samples of a random mini-batch
optimizer.zero_grad()
loss = loss_fn.forward(model.forward(x[n]), y[n])
model.backward(loss_fn.backward())
optimizer.step()
if step % 5000 == 0:
print(f"step {step}: loss {loss:.4f}")
print("test accuracy:", np.mean((model.forward(x_test) > 0.5) == y_test))