Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 4

Backpropagation and Gradient Descent in Neural Networks

Recommended resources

Hello! Welcome to the fourth and final lesson of our foundational module.

So far, we have constructed a complete forward path for a neural network. We've seen how it takes an input, processes it through layers of matrix multiplications and activation functions (the forward pass), and produces an output. In our last lesson, we introduced the loss function (specifically, cross-entropy), which compares the network's output to the true answer and calculates a single scalar value representing the model's error.

Our entire network, from input to loss, is one giant, complex, but ultimately differentiable function. The question now is: how do we use this loss value to tune the millions of weights and biases inside the network to make it better?

Today, we will answer that question by exploring the engine of deep learning: the combination of gradient descent and backpropagation. Our goal is to understand how these two concepts work together to systematically update a network's parameters to minimize its loss, enabling it to learn from data.

1. The Optimization Problem: Gradient Descent

The process of training a neural network is an optimization problem. We have a loss function, , which depends on all the parameters (weights and biases) of the network. We want to find the set of parameters that makes the loss as small as possible.

The most common algorithm used to solve this is gradient descent. The core idea is simple and intuitive:

  1. Calculate the gradient of the loss function with respect to each parameter, . The gradient is a vector that points in the direction of the steepest ascent of the loss function.
  2. To decrease the loss, we take a small step in the opposite direction of the gradient.

This is expressed in the famous update rule, applied to every parameter in the network:

Here, (eta) is the learning rate, a small positive number that controls the size of our step.

Feed-Forward and Backpropagation Diagram
This diagram illustrates the two phases of training. The forward pass (left to right) computes the output and error. The backward pass, or backpropagation (right to left), calculates the gradients needed for the parameter update step shown at the bottom.

The main challenge, then, is to compute the gradient , which consists of the partial derivative of the loss with respect to every single weight and bias in the network. For a model with millions of parameters, this is a monumental task. A naive approach, like estimating the derivative for each parameter by slightly perturbing it (finite differences), would be computationally impossible. We need a more efficient way.


2. Backpropagation and Computational Graphs

This is where backpropagation comes in. Backpropagation is a highly efficient algorithm for computing the exact gradient of the loss function with respect to all network parameters. At its core, it is a clever, systematic application of the multivariate chain rule from calculus.

To understand how it works, it's incredibly helpful to visualize the network's calculations as a computational graph. In this graph, nodes represent values (inputs, parameters, intermediate results, the final loss), and edges represent the functions that compute them.

Lecture 6: Backpropagation

The video 'Lecture 6: Backpropagation' from Michigan Online provides an excellent conceptual introduction to computational graphs and the backpropagation algorithm. We'll start with the high-level intuition.

Please watch from 01:09 to 14:28. Why Computational Graphs? (01:09 - 07:57): This part explains why deriving gradients on paper is not scalable and introduces the computational graph as a modular data structure to represent complex functions. The Backward Pass (07:57 - 14:28): This is the key part. It walks through a simple scalar example, introducing the concepts of the forward pass, backward pass, upstream gradient, and local gradient. Focus on the core idea that the gradient at a node (the 'downstream gradient') is calculated by multiplying the gradient from the next node ('upstream') by the node's own local derivative.

As the video explains, the core operation of backpropagation at any node in the graph is:

We start at the very end of the graph, where the final loss is computed. The "gradient of the loss with respect to itself", , is trivially 1. This is our initial "upstream gradient". We then work our way backward through the graph, applying this rule at every node, until we have the gradient of the loss with respect to the network's original inputs and parameters.


3. The Mathematics of Backpropagation: Vector-Jacobian Products

The intuitive formula above works for scalar values. Since you're interested in the mathematical foundations, let's formalize this for the vector and matrix operations that dominate neural networks.

When a function takes a vector and produces a vector , its "local derivative" is the Jacobian matrix, , an matrix of all possible partial derivatives .

The backpropagation rule is then expressed as a Vector-Jacobian Product (VJP).

Everything You Need to Know About Backpropagation

The blog post 'Everything You Need to Know About Backpropagation' gives a concise, math-focused definition of the VJP and its role. This section formalizes the concept we just saw in the video.

Read the section 'The Chain Rule with Vector-Jacobian Products (VJP)'. Focus on Definition 1. Notice how the VJP formula ( J_f(x)^T abla_y \mathcal{L} ) is a direct mathematical translation of 'local gradient' (J_f(x)^T) times 'upstream gradient' (( abla_y \mathcal{L})).

The key formula is:

This states that the gradient of the loss with respect to the function's input (the downstream gradient) is the transpose of the local Jacobian matrix multiplied by the gradient of the loss with respect to the function's output (the upstream gradient).

Backpropagation is simply a chain of these VJP calculations, starting from the loss and moving backward. This method is also called reverse-mode automatic differentiation. Its efficiency comes from the fact that we always perform matrix-vector products, which is significantly cheaper than the matrix-matrix products required by the alternative, forward-mode differentiation. For a typical neural network, where the final output (loss) is a scalar and the parameters are numerous, reverse-mode is vastly more efficient.


4. Backpropagation in Practice: A 2-Layer MLP

Let's apply this to the 2-layer MLP we've been working with. The forward pass is:

  1. (Cross-Entropy Loss)

To perform backpropagation, we go in reverse.

Step 1: Gradient of the Loss w.r.t Softmax input ()

This is our starting point. We need the derivative of the combined Softmax and Cross-Entropy loss functions. As it turns out, this has a remarkably simple form.

Everything You Need to Know About Backpropagation

Let's return to the article on backpropagation to see a very important derivation. This shows that the gradient of the cross-entropy loss with respect to the logits (the input to the softmax) is simply the difference between the predicted probabilities and the true labels.

Read the section 'Deriving the Softmax Cross-Entropy Gradient'. The final result, ( abla_z \mathcal{L} = p - y), is a cornerstone of training classifiers.

So, our initial upstream gradient is:

where is the vector of predicted probabilities and is the one-hot encoded true label vector. This vector tells us how much the loss would change for a small change in each logit.

Step 2: Gradients for the Output Layer ()

Now we backpropagate through the function . Our upstream gradient is . We need to calculate the gradients for the parameters and , and the new upstream gradient to pass back to .

For this, we use the "VJP trick": we never explicitly form the giant Jacobian matrices. Instead, we use a pre-derived, efficient expression for the VJP of a linear layer.

Everything You Need to Know About Backpropagation

The same article provides a clear derivation for the gradient of a linear layer. This shows how the mathematically complex VJP simplifies to a simple and efficient outer product.

Read the section 'Deriving the Gradient for a Linear Layer'. The key takeaway is the final boxed formula: the gradient with respect to the weight matrix is the outer product of the upstream gradient and the layer's input vector.

Using these rules, we get:

  • Gradient for weights : (Upstream gradient layer input transposed)
  • Gradient for bias : (This is just the upstream gradient, as the bias's local derivative is 1)
  • New upstream gradient for : (Jacobian w.r.t is , so the VJP is upstream gradient)

Step 3: Gradients for the Hidden Layer ()

We continue backward.

  • First, we backpropagate through the activation function . The local derivative is . Since this is an element-wise operation, the VJP is simply an element-wise product (Hadamard product ).
  • Now we have the upstream gradient for . We are back at another linear layer, , and we apply the exact same rules as in Step 2:

We have now computed the partial derivative of the loss with respect to every parameter in the network!

Test your understanding!

Look at the formula for . The term is a column vector representing the error in the output probabilities. is a row vector representing the activations of the hidden layer.

What are the dimensions of the resulting gradient matrix ? Does this match the dimensions of the weight matrix ? Why is this critically important?

Show answer

Let's say the hidden layer has neurons and the output layer has neurons (for classes).

  • The dimensions of are .
  • The dimensions of are .
  • The outer product of a vector and a vector results in a matrix of size .

The dimensions of the weight matrix are also , as it transforms the -dimensional hidden layer output to the -dimensional logit vector.

This is critically important because the gradient matrix must have the exact same shape as the parameter matrix . Each element in the gradient matrix tells us how to update the corresponding element in the weight matrix. If the shapes didn't match, the gradient descent update rule would be mathematically impossible. This "shape matching" is a powerful sanity check when implementing backpropagation.


5. The Complete Training Algorithm

We can now put everything together into the full training procedure for a neural network. This is the fundamental loop of deep learning.

Backpropagation Algorithm | Neural Networks

This final video, from First Principles of Computer Vision, provides a concise summary of the complete training algorithm, tying together the forward pass, backpropagation, and the gradient descent update step.

Watch from 09:55 to 11:38. This clip outlines the complete training algorithm. Notice how it integrates the steps we've discussed: forward pass, computing deltas (gradients) via backpropagation, and updating the weights and biases.

The algorithm is as follows:

  1. Initialize all weights and biases with small random values.
  2. Repeat for a set number of iterations (epochs):
    a. Select a batch of training examples ().
    b. Forward Pass: Feed the batch through the network to compute the predicted outputs and the average loss for the batch.
    c. Backward Pass (Backpropagation): Compute the gradient of the loss with respect to every parameter in the network (, ).
    d. Parameter Update: Adjust each parameter using the gradient descent update rule:

This cycle of forward pass -> loss calculation -> backward pass -> parameter update is repeated thousands or millions of times, gradually nudging the network's parameters towards values that minimize the loss and produce more accurate predictions.


Conclusion

This lesson completes our journey through the fundamental mechanics of a neural network. We have closed the learning loop.

Key Takeaways:

  • Gradient Descent is an iterative optimization algorithm that minimizes the loss function by taking small steps in the direction opposite to the gradient.
  • Backpropagation is an efficient algorithm that computes the exact gradient of the loss with respect to all network parameters. It does this by applying the chain rule backward through the network's computational graph.
  • Mathematically, backpropagation is a sequence of Vector-Jacobian Product (VJP) calculations, which are implemented efficiently without ever materializing the full Jacobian matrices.
  • The full training process involves repeatedly executing a loop: a forward pass to get the loss, a backward pass to get the gradients, and an update step to improve the parameters.

You now understand the complete process for training a basic Multi-Layer Perceptron. We have built the essential toolkit that underpins all modern deep learning, including the large language models that are our ultimate goal.

In the next module, we will transition from these general principles to the specific components of the Transformer architecture. We will begin by tackling the first challenge in any language model: how to represent words and their positions in a sequence as numerical vectors that a neural network can process. We will explore embedding layers and positional encodings.