From the free course Backpropagation on Lykke
The Core Backpropagation Algorithm
Key concepts: Chain Rule · Gradient Computation · Hidden Units · Representation Learning · Stochastic Gradient Descent (SGD)
Detailed breakdown of the standard backpropagation algorithm, the chain rule, and its role in representation learning.
The Core Backpropagation Algorithm
Backpropagation, short for "backward propagation of errors," is the fundamental algorithm that enables the training of deep neural networks. While often conflated with the entire learning process, backpropagation is specifically the method used to calculate the gradient of a loss function with respect to the weights of the network. It is an application of Reverse Mode Automatic Differentiation, leveraging the chain rule from calculus to efficiently assign "credit" (or blame) to each parameter for the final output error.
AI_SVGI_SVG## The Mathematical Foundation: The Chain Rule
At its heart, backpropagation is an exercise in the Chain Rule. In a multi-layer neural network, the output is a nested function of the inputs. If we have a composition of functions $y = f(g(h(x)))$, the derivative of $y$ with respect to $x$ is the product of the derivatives of each component function.
Definition: The Chain Rule If a variable $z$ depends on $y$, which in turn depends on $x$ (i.e., $y = g(x)$ and $z = f(y)$), then $z$ depends on $x$ as well, and the derivative of $z$ with respect to $x$ is given by: $$\frac{dz}{dx} = \frac{dz}{dy} \cdot \frac{dy}{dx}$$
In the context of a neural network, we are interested in $\frac{\partial \mathcal{L}}{\partial w_{ij}^{(l)}}$, where $\mathcal{L}$ is the loss function and $w_{ij}^{(l)}$ is the weight connecting the $i$-th neuron in layer $l-1$ to the $j$-th neuron in layer $l$.
The Local Gradient
Backpropagation works by computing a local gradient at each node. For any given neuron, we calculate how the loss changes with respect to the neuron's output, and then use that to find how the loss changes with respect to the neuron's inputs and parameters.
| Component | Symbol | Description |
|---|---|---|
| Input | $x$ | The raw data or output from the previous layer. |
| Weight | $w$ | The learnable parameter scaling the input. |
| Bias | $b$ | The learnable additive constant. |
| Pre-activation | $z$ | The weighted sum: $z = \sum (w \cdot x) + b$. |
| Activation | $a$ | The non-linear transformation: $a = \sigma(z)$. |
| Loss | $\mathcal{L}$ | The scalar value representing the error. |
The Mechanics of the Backward Pass
The training of a neural network consists of two distinct phases: the Forward Pass and the Backward Pass.
1. The Forward Pass
During the forward pass, data flows from the input layer through the hidden layers to the output layer. Each layer performs a linear transformation followed by a non-linear activation.
- Compute the weighted sum: $z^{(l)} = W^{(l)} a^{(l-1)} + b^{(l)}$
- Apply activation: $a^{(l)} = \sigma(z^{(l)})$
- Store intermediate values ($a$ and $z$) for use during the backward pass.
2. The Backward Pass
The backward pass begins at the output layer. We calculate the error gradient and propagate it backward through the network.
- Compute Output Error: Calculate $\delta^{(L)}$, the gradient of the loss with respect to the pre-activation of the output layer.
- Propagate Error: For each preceding layer $l = L-1, \dots, 1$, calculate $\delta^{(l)}$ based on $\delta^{(l+1)}$.
- Compute Parameter Gradients: Use $\delta^{(l)}$ to find the gradients for $W^{(l)}$ and $b^{(l)}$.
Theorem: The Backpropagation Equations For a layer $l$, the error $\delta^{(l)}$ is defined as $\frac{\partial \mathcal{L}}{\partial z^{(l)}}$. The four fundamental equations are:
- $\delta^{(L)} = \nabla_a \mathcal{L} \odot \sigma'(z^{(L)})$
- $\delta^{(l)} = ((W^{(l+1)})^T \delta^{(l+1)}) \odot \sigma'(z^{(l)})$
- $\frac{\partial \mathcal{L}}{\partial b^{(l)}} = \delta^{(l)}$
- $\frac{\partial \mathcal{L}}{\partial W^{(l)}} = \delta^{(l)} (a^{(l-1)})^T$
Dynamic Programming and Efficiency
One might wonder why we don't simply use symbolic differentiation or finite differences to calculate gradients. The answer lies in computational complexity.
If a network has $N$ parameters, calculating the gradient via finite differences (perturbing each weight slightly and re-running the forward pass) would require $O(N)$ forward passes. For modern models with billions of parameters, this is impossible.
Backpropagation is a Dynamic Programming algorithm. It avoids redundant calculations by caching the intermediate activations during the forward pass and the intermediate gradients during the backward pass. This allows us to compute the gradients for all parameters in a single backward pass, which has a computational cost roughly equivalent to two forward passes.
| Method | Complexity | Pros | Cons |
|---|---|---|---|
| Finite Differences | $O(N^2)$ | Simple to implement | Extremely slow for large $N$ |
| Symbolic Diff. | Variable | Exact expressions | Can lead to "expression swell" |
| Backpropagation | $O(N)$ | Highly efficient, scales to billions | Requires storing activations (memory intensive) |
Implementation: Matrix Calculus and Tensors
In practice, we do not iterate over individual neurons. Instead, we use Matrix Multiplication to process entire layers and batches of data simultaneously. This leverages the highly optimized BLAS (Basic Linear Algebra Subprograms) libraries and GPU architectures.
Python Implementation (NumPy)
The following code demonstrates a single update step for a simple 2-layer MLP.
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
return sigmoid(x) * (1 - sigmoid(x))
# Hyperparameters and Data
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) # Input
y = np.array([[0], [1], [1], [0]]) # Target (XOR)
learning_rate = 0.1
# Initialize weights
W1 = np.random.randn(2, 4)
b1 = np.zeros((1, 4))
W2 = np.random.randn(4, 1)
b2 = np.zeros((1, 1))
# --- Forward Pass ---
z1 = np.dot(X, W1) + b1
a1 = sigmoid(z1)
z2 = np.dot(a1, W2) + b2
a2 = sigmoid(z2)
# --- Backward Pass ---
# 1. Output layer error
loss_grad = a2 - y # Derivative of MSE loss: (a2 - y)^2
d_z2 = loss_grad * sigmoid_derivative(z2)
# 2. Gradients for W2 and b2
d_W2 = np.dot(a1.T, d_z2)
d_b2 = np.sum(d_z2, axis=0, keepdims=True)
# 3. Hidden layer error
d_a1 = np.dot(d_z2, W2.T)
d_z1 = d_a1 * sigmoid_derivative(z1)
# 4. Gradients for W1 and b1
d_W1 = np.dot(X.T, d_z1)
d_b1 = np.sum(d_z1, axis=0, keepdims=True)
# --- Update Weights ---
W2 -= learning_rate * d_W2
b2 -= learning_rate * d_b2
W1 -= learning_rate * d_W1
b1 -= learning_rate * d_b1
Backpropagation Through Time (BPTT)
Standard backpropagation is designed for feedforward networks. However, Recurrent Neural Networks (RNNs) process sequences by maintaining a hidden state that persists across time steps. To train these, we use Backpropagation Through Time (BPTT).
The Unfolding Concept
BPTT works by "unfolding" the RNN into a deep feedforward network where each layer represents a time step. The critical distinction is that the weights are shared across all time steps.
- Unfold: Create a copy of the network for each time step in the sequence.
- Forward Pass: Compute the hidden states and outputs for the entire sequence.
- Backward Pass: Accumulate gradients for the shared weights across all time steps.
- Update: Apply the accumulated gradient to the weights.
Truncated BPTT
For very long sequences, standard BPTT suffers from the Vanishing Gradient Problem and high memory usage. Truncated BPTT processes the sequence in smaller chunks (e.g., 20 time steps), stopping the gradient flow after a certain point to maintain stability and efficiency.
Backpropagation Through Structure (BPTS)
While BPTT handles sequences, Backpropagation Through Structure (BPTS) is used for Recursive Neural Networks, which operate on tree-structured data (like parse trees in linguistics or molecular graphs in chemistry).
In BPTS, the topology of the network is determined by the structure of the input data. The gradient is propagated from the root of the tree down to the leaves. This allows the model to learn distributed representations of hierarchical structures.
| Algorithm | Network Type | Data Structure | Key Characteristic |
|---|---|---|---|
| Standard Backprop | Feedforward (MLP, CNN) | Fixed-size vectors/images | Direct DAG flow |
| BPTT | Recurrent (RNN, LSTM) | Sequences (Time) | Weight sharing across time |
| BPTS | Recursive | Trees/Graphs | Dynamic topology per input |
Common Pitfalls and Challenges
Even with a perfect implementation, backpropagation can fail due to the mathematical properties of the network.
1. The Vanishing Gradient Problem
When using activation functions like Sigmoid or Tanh, the derivative is very small for large positive or negative inputs. As we multiply these small derivatives across many layers (via the chain rule), the gradient effectively "vanishes" by the time it reaches the early layers.
- Solution: Use ReLU (Rectified Linear Unit) activations or Batch Normalization.
2. The Exploding Gradient Problem
Conversely, if weights are initialized too large, the gradients can grow exponentially, leading to numerical instability (NaN values).
- Solution: Use Gradient Clipping or careful weight initialization (e.g., Xavier/Glorot or He initialization).
3. Local Optima and Saddle Points
In high-dimensional spaces, the loss surface is complex. While true local minima are rare in deep learning, saddle points (where the gradient is zero but it's not a minimum) are common and can slow down training.
- Solution: Use momentum-based optimizers like Adam or RMSProp.
4. The Dying ReLU
If a ReLU neuron's input is always negative, its gradient becomes zero, and it will never update again—it "dies."
- Solution: Use Leaky ReLU or lower learning rates.
Activation Functions and Their Derivatives
The choice of activation function $\sigma$ is critical because its derivative $\sigma'$ is a direct multiplier in the backpropagation formula.
| Activation | Formula $\sigma(x)$ | Derivative $\sigma'(x)$ | Notes |
|---|---|---|---|
| Sigmoid | $\frac{1}{1+e^{-x}}$ | $\sigma(x)(1-\sigma(x))$ | Vanishing gradient risk; output not zero-centered. |
| Tanh | $\frac{e^x - e^{-x}}{e^x + e^{-x}}$ | $1 - \sigma(x)^2$ | Zero-centered; still prone to vanishing gradients. |
| ReLU | $\max(0, x)$ | $1$ if $x>0$, else $0$ | Efficient; solves vanishing gradient; "dying" risk. |
| Leaky ReLU | $\max(\alpha x, x)$ | $1$ if $x>0$, else $\alpha$ | Prevents dying neurons by allowing small gradient. |
Summary of the Backpropagation Workflow
To summarize the entire process for a single training iteration:
- Input: Provide a batch of training data $X$.
- Forward Pass: Compute activations $a^{(l)}$ for every layer.
- Loss Calculation: Compute the scalar error $\mathcal{L}$ using a loss function (e.g., Cross-Entropy).
- Output Gradient: Calculate the error signal $\delta^{(L)}$ for the final layer.
- Backpropagation: Iterate backward from $L-1$ to $1$ to compute $\delta^{(l)}$ for all hidden layers.
- Weight Gradients: Calculate $\frac{\partial \mathcal{L}}{\partial W}$ and $\frac{\partial \mathcal{L}}{\partial b}$ using the stored activations and error signals.
- Optimization: Update the weights using an optimizer (SGD, Adam, etc.): $W = W - \eta \nabla_W \mathcal{L}$.
Backpropagation remains the most successful algorithm in the history of AI, providing the mathematical bridge between high-level objectives (the loss function) and low-level parameter adjustments.
AI_STUDY_GUIDEI_STUDY_GUIDE### Flashcards: Backpropagation Essentials
- Q: What is the primary mathematical tool used in backpropagation?
- A: The Chain Rule.
- Q: Why is backpropagation considered a dynamic programming algorithm?
- A: Because it stores (caches) intermediate results (activations and gradients) to avoid redundant calculations.
- Q: What is the "error signal" $\delta$ in backpropagation?
- A: The partial derivative of the loss function with respect to the pre-activation $z$ of a neuron ($\partial \mathcal{L} / \partial z$).
- Q: How does BPTT differ from standard backpropagation?
- A: BPTT unfolds the network across time steps and accumulates gradients for shared weights.
- Q: What is the main advantage of ReLU over Sigmoid for backpropagation?
- A: ReLU has a constant gradient of 1 for positive inputs, which helps prevent the vanishing gradient problem.
Quiz: Conceptual Understanding
- True or False: Backpropagation is an optimization algorithm like Gradient Descent.
- Answer: False. Backpropagation is a method for calculating gradients; Gradient Descent is an optimization algorithm that uses those gradients.
- In a network with 10 layers, if the gradient at layer 10 is 0.5 and the derivative of the activation at layer 9 is 0.1, what happens to the error signal as it moves backward?
- Answer: It is scaled (multiplied) by the activation derivative and the weights, typically becoming smaller (vanishing).
- Which pass (Forward or Backward) requires more memory, and why?
- Answer: The Backward pass indirectly requires more memory because it needs the activations stored during the Forward pass to compute gradients.
- What happens to the weight update if the activation of a neuron is zero?
- Answer: According to the equation $\frac{\partial \mathcal{L}}{\partial W} = \delta \cdot a^T$, if the activation $a$ is zero, the gradient for the weight $W$ will be zero, and the weight will not update.
Study Guide: Mastering Backpropagation
- Derive the Chain Rule: Practice deriving the gradient for a single-neuron "network" ($y = \sigma(wx+b)$).
- Matrix Dimensions: Ensure you can trace the shapes of matrices through the forward and backward pass. If $W$ is $(m, n)$, then $\nabla_W$ must also be $(m, n)$.
- Activation Derivatives: Memorize the derivatives of Sigmoid, Tanh, and ReLU. They are the "gates" through which the gradient flows.
- Implementation: Write a backpropagation script from scratch using only NumPy. Do not use PyTorch or TensorFlow until you can do it in raw math.
- Vanishing Gradient: Visualize the Sigmoid curve and its derivative. Note how the derivative approaches zero at the tails—this is the visual explanation of the vanishing gradient.
Source Materials
Study Backpropagation on Lykke
This course page is free to open: signed out, you can read its first two sections, and signing in, on any plan, opens the rest. The free Lykke Chrome extension syncs your own Canvas courses, so ChatGPT, Claude and Muse can answer from your classes and deadlines. It only reads Canvas.
Add the free extensionSign in to open every section