Mariano Crosetti
  • Deep Learning
  • Neural Networks
  • Chain Rule
  • Pytorch
  • Calculus

Backpropagation is not the Chain Rule; Read why in this easy-to-understand Deep Learning and backpropagation introduction! (+books recommended)

Backpropagation was always a mind-blowing concept, as many others taught at university (others that I consider to have the same effect on the students are induction, recursion, etc.). I like to understand why students struggle to understand it so that I can develop more effective ways of introducing the concept and avoiding common misconceptions.

This is not 100% true and we will see why.

If you don’t know anything about neural networks, don’t worry: I will briefly introduce the necessary concepts.
If you already know Deep Learning concepts, skip to section 6.

0. What is a Neural Network?

A significant simplification: a formula that takes an ℝⁿ vector and returns a prediction, for instance, a probability between [0,1] if it’s a binary classifier.

This function is made by composing many functions that successively transform the input ℝⁿ vector to other ℝᵏ vectors:

Typically, each step consists of a linear transformation (for transforming ℝᵃ to ℝᵇ) and a non-linear function applied coordinate by coordinate at each step:

g(x) popularly is the function max(x,0) named ReLU

The entries of _W_ₜ and _b_ₜ are parameters: they start in a random value, and we change them to improve the prediction by an optimization algorithm. Generally, we call θ to the set of all the parameters θ = { _W_ₜ _b_ₜ | t }

1. 101 Machine Learning Concepts

To know if we are improving the prediction, we need to have a set of inputs for which we know the desired output: { (x, y) | x ∈ℝⁱⁿ y ∈ ℝᵒᵘᵗ_}._ We call it labeled data. Generally, we split the data into two sets, one used for adjusting the parameters called training data and the other to ensure how good the predictions in samples not used by the optimization algorithm called validation data: after all, the purpose of the model is always using it in future data, not seen by the optimization algorithm. Improving the prediction for the training data where we know the desired output is also called supervised learning. We also call training for the execution of the optimization algorithm.

These concepts are not specifically related to Deep Learning but are used for all the machine learning algorithms. Machine Learning is just the study of the algorithms that use data for making predictions (they “learn” from the data).

2. How do we optimize the parameters θ?

Optimizing the models is finding values of the parameters (W, b matrices we’ve seen) that improve the prediction. To measure how good a prediction is, we use a loss function. The loss function depends on the problem we want to solve. For instance, for binary classification, we use the binary cross entropy:

Notice that yᵢ is 1 or 0 (same for (1-yᵢ)). So multiplying for yᵢ and (1-yᵢ) just acts like an "if" statement.

Why not optimize the “error rate” directly? First, it’s not a continuous function, and the method we will use requires it. If you thoughtfully see Binary Cross Entropy, it’s a kind of “continuous error rate” (that considers the probability instead of the prediction). However, considering the log, which we intuitively want because of the difference between 0.1 error rate and 0.01, it’s relatively the same as 0.01 and 0.001 (10x less error). I struggled to fully understand a more formal explanation (based on max likelihood estimators) until I read this book and did this course about information theory, which I 100% recommend. Still, knowing Information Theory is unnecessary in understanding deep learning.

3. Why do we need the gradient?

Then, to find optimal values of W and b, we make gradient descent, which consists of calculating the derivative of the loss function with respect to each parameter and updating the parameter, “moving” it in the opposite direction: subtracting to the parameter the gradient multiplied by a small constant (something like 1e-3).

The vector of the derivatives to each variable is called the gradient:

Behind the fancy notation, the gradient it just a list of derivatives.

If we see this vector as a direction (in the space of all the parameters), it’s the local direction that maximizes the loss. So, the opposite direction is the direction that locally minimizes the loss. (by local, we refer to when the step is very, very small)
Intuitively, it can be seen as we are climbing down a hill, always taking steps in the direction of the slope down:

Notice that the input variables of loss (usually noted by the letter J) are the parameters to optimize: the values at W and b that are initially random.

We will note the loss function by the letter J, which is the typical notation in Deep Learning literature.

Notice that although the input of a neural network during training is the training data samples, the input variables of J are the weights. Of course, J depends on the training data, but when optimizing the model (during training), we consider the data fixed: we can’t change the data; we must change the parameters to predict the samples correctly.

The results of J will be different if the calculation considers another dataset or a different dataset split (for instance, if we evaluate the loss in the validation set). We say that the model generalizes well if J is minimized for the training data; we also observe a reduction in J for data not used for training. That’s why the validation data is essential: to check if the obtained model generalizes properly.

4. Just let’s focus on the gradients.

At the beginning of the Deep Learning era, practitioners had to write down the formula of the neural network (we saw a neural network is just a formula) and then derive it and calculate other formulas for the gradients.

This can be cumbersome, but it’s mechanical; we have a set of rules of how to calculate the derivative of a formula concerning their sub-formulas:

If the formula we have is a product of sub-formulas, we can apply the "Product Rule" (like f(x) = sin(x).log(x))
If the formula we have is a composition of function we can apply the "Chain Rule" (like f(x) = sin(log(x))).

Let’s forget we have a neural network. Let’s think we have a formula whose input variables are a,b,c and which output is l:

We could have written = ((a+b).max(b,c))², but we decided to name the intermediate results to refer to them later.

Our final goal is to calculate the gradient of the output l with respect to their inputs a,b,c:

The three derivatives that consist our gradient ▽l

Let’s focus on the first derivative; by the chain rule, we have:

This is just the chain rule

Now, we have a formula where one of the factors we know:

The other factor is the derivative of p with respect to a. Notice the problem is similar to the one we had initially (which was the derivative of l with respect to a). But now, p is a variable that is “closer” to an in the dependency graph:

Nodes represent variables of the given formula, and there is an arrow x→y if for calculating y, we need the value of x (y "depends on" x, or in other words, x "is necessary for" y).

We can apply successively an analogous reasoning to calculate what we want:

All this example belong to a course I dictated for LLMs from Zero (in Spanish) at Austral University.

Note: In math, the word derivative (of a function) is indistinguishably used for the function (the abstract formula) to calculate the derivative at any input or the value of the derivative at a specific input. In our particular case, on the i-th step of gradient descent, we have one specific weight assignation θᵢ, and to calculate the update, we need to calculate the gradient for that specific input of J. So, we need the value of the derivative at a certain point. We don’t need the abstract derivative formula.

During this process, we calculate the derivative of l with respect to each variable. And we do so from closer to l variables, to the ones that are furthermost. We can apply the chain rule to go “one step further.” If we have the derivative (of l) with respect to p, we can calculate the derivative (of l) with respect to m (knowing the relationship between m and p). With the derivative (of l) with respect to m, we can calculate the derivative (of l) with respect to a (knowing the relationship between a and m):

So, the backpropagation algorithm is essentially:

  1. We will calculate gradient(x) = the derivative of l with respect to x.
  2. The basic case is when x = l. Then gradient(x) = 1.
  3. Then, we visit the variables in the inverse topological sort of the dependency graph of the formula.
  4. When we visit the node x that points to node y (x → y in the graph), gradient(x) = gradient(y) . “derivate of y with respect to x”.
    The “derivate of y with respect to x” will depend on the formula that the dependency x → y represents.

What happens if you have two children in the dependency graph? (x → y₁, x → y₂). We will see in section 7 how to deal with that case and why this is, in my opinion, a main source of misunderstandings.

5. Now let’s go back to neural network

Neural networks are essentially formulas but more complex. For instance, let’s think about a neural network with 4 inputs and a hidden layer of size 6 can be represented as follows:

Each input sample consists of 5 numbers: x₁ to x₅, so the input is a ℝ⁵ vector. As we said, the hidden layer is a ℝ⁶ vector h, which is obtained as a linear transformation plus a non-linear applied on each coordinate, so we have h = ReLU(x.W + b). W and b contain parameters that are initially random and then optimized for the predictions that fit the sample data.

The last diagram represents the inputs, outputs, and intermediate results (we call them activations). However, the outcome depends not only on the input data but also on the parameters. Where are the parameters represented? The parameters at W indicate how x are combined for each h. Each matrix entry Wᵢⱼ is the weighting of xᵢ in the equation of hⱼ. b is not represented explicitly, but for each hⱼ, a bⱼ exists that will be added to the linear combination of x (before applying ReLU).

But again, where are the parameters represented? The diagram is the most popular representation of a neural network computation but doesn’t explicitly represent the parameters!?

In my experience as a teacher, this is one of the two significant sources of confusion for people who start a journey in Deep Learning: they see the diagram and think that backpropagation calculates the gradient with respect to x, which is incorrect. Again, remember that the gradient is with respect to the parameters (the numbers that are in W and b matrices).

Probably a more fair representation of all the numbers (inputs and parameters) that are involved in the calculation is this other way of representing it (notice that this is a different network) :

This network has two inputs x1 x2 and a hidden layer with size 1—notice also that for computing the loss, the labels y are involved. In red, are all the numbers that are part of the sample training data (what we can't change). In green are all the parameters. We need to calculate the derivative of the output concerning green nodes. The image was taken from this other post, which is great because it also includes Pytorch code with the example.

Most of my students make two main mistakes when introducing to Deep Learning:

  1. They confuse input with weights: while a neural network is calculating a function over the inputs (for instance, we provide an image and we get a classification probability), backpropagation minimizes the cost function (whose inputs are the weights) and calculates the cost of misclassifications over all the training data. The input samples that comprise the training data are considered fixed for the shake of the cost function.
    This error is especially common in novices and was covered deeply in the last section.
  2. The second big mistake is what we saw at the end of section 4: how gradients are calculated when weights appear in two sub-formulas (this happens in all the neural networks with more than one hidden layer, so it’s more common than you may think).
    The answer is that backpropagation does not use the Chain Rule but the Multivariate Chain Rule. So the meme of the beginning of the post, corrected will be:

7. Backpropagation is not the Chain Rule; it’s the Multivariate Chain Rule!

Let’s go back to our toy equation example:

The analysis of the derivative of l with respect to a was covered in section 3.

But now let’s focus on the derivative of l with respect to b: so remembering our method, we will first calculate the derivatives of l with respect to the variables that are “closer” to l, so seeing the diagram:

We calculate the derivative of l with respect to p, m, n:

Now, calculating the derivative of l with respect to b is not as easy because we can’t apply the Chain Rule we saw:

For applying this, it must be h(x) = f(g(x)). But int this case we have l(b) = p(m(b), n(b)).

How do we calculate the derivative of l(b) = p(m(b), n(b))?

For that, we need to use the multivariate chain rule:

Dᵢ f is the derivative of f with respect to gᵢ.

So, in the case of the formula that we presented at the beginning of the section, we have:

In the backpropagation algorithm (section 4), we must modify the step 4:
When we visit a node x, we iterate through all the others node yᵢ such x→ yᵢ and gradient(x) = sum( gradient(yᵢ). “derivate of yᵢ with respect to x” | ∀ i )

Note: Most of the implementations of the backpropagation algorithm are slightly different: as the node yᵢ is the one that “uses” the value of x, it’s probably the one that knows which operation performs yᵢ(x), so it’s the one that knows how to calculate “derivate of yᵢ with respect to x.” So usually, in most implementations of backpropagation, when we visit certain node a, we assume that gradient(a) is already calculated (which is true for the initial node as we can set gradient(l) = 1), and iterate through b, the parents node of a (b → a). As we are in node a, we know how to calculate the “derivate of a with respect to b” so we add to gradient(b) the respective contribution of b → a

gradient(b) += gradient(a) . “derivate of a with respect to b”

Then, when we reach b with the inverse topological sort, it means that we had visited all their children, and gradient(b) is calculated properly (assuming it started at 0).

The backpropagation algorithm relies on visiting all the edges of the calculation dependency graph. The described alternative implementation is just another way of visiting all the edges of the graph: we can visit them either from the nodes they come from or from the nodes they come in.

Finally, I only really understood backpropagation once I imagined the code, but you can see a toy implementation that Andrej Karpathy did for educational purposes.

This is one example of how even geniuses struggle with the difference between chain rule and multivariate chain rule and its implementation implications.

8. Personal opinion about multivariate chain rule (optional section)

From my perspective, the univariate chain rule is intuitive: to obtain the change ratio of a composition of function, you multiply the chain ratios of the variables. A very illustrative way of seeing how gear works:

The chain ratio between x and y is obtained by multiplying the chain ratios between x and y and between u and y.

However, the multivariate version is not trivial for me. It’s not intuitive that you “add” the gradients independently (without considering some interaction between them). If you look at the demonstration, it’s clear why it’s like that, though (that’s why I think demonstrations are fantastic, as we gain intuition). You can read the deeper explanation of the multivariate chain rule in this book (which is the best Deep Learning book at the moment I wrote the article, in my opinion).

Note: notice that luckily for us, it’s like that, and we don’t need to consider any interaction between the gradient, as this would modify the complexity of the backpropagation algorithm, which with this formulation is still O(N+M) (being N and M respectively the vertex and edges of the calculation dependency graph).

9. Why does this thing matter?

Most people explain the backpropagation algorithm with examples of formulas where the multivariate chain rule is unnecessary. And as I explained, the multivariate chain rule is not a trivial or intuitive concept. So then it causes much confusion because:

  • It’s not clear why the gradients get accumulated.
  • And even worse, it’s not clear that this tweak in the algorithm is just enough for a weight to be re-used in many places in the formula. So, students have many problems understanding how “weight tying” works.

I evidence this by teaching RNN, where understanding that “weight tying” works appropriately is essential. But there is weight sharing everywhere:

  • In CNN, the same convolutional kernel (set of weights) is applied across different parts of the input image.
  • In auto-regressive language model transformers, the token embeddings (which go from vocab to embedding dimension) are usually tied to the classification head (which goes from embedding dimension to vocab).

10. Why do the most advanced students struggle with it?

This fact affected only the most advanced students because they are the ones who ask themselves:

  • If neural networks are just formulas, what prevents me from reusing the same parameters in multiple layers? Is it possible? Does it break the backpropagation algorithm?
  • Is it possible to make more subtle formulas, like calculating the distance between two activations? Is it possible to have cycles in the formula (like an iteration)?

The short answer is that re-using weights will ultimately work because the backpropagation algorithm uses the multi-variate chain rule. Regarding the cycles, notice that the graph nodes are created at runtime (while we execute the formula). Even if we have a loop, the intermediate results calculated at the first iteration will be different from those in the second iteration, so they will have different values and be different nodes in the graph. The graph will still be a Directed Acyclic Graph considering the execution time where each expression is calculated.

Also, even in 2 hidden layers of a neural network, is important the multivariate chain rule (but it’s almost always hidden from the analysis by the matrix multiplication and matrices’ gradient algebra). Let’s see an example:

Let’s call h₁ h₂ h₃ h₄ the first hidden layer, g₁ g₂ g₃ g₄ the second one, and output₁ output₂ the final outputs. Let’s analyze the gradient of output₁ with respect to the single weight w₁₁. If we expand the formula of output₁:

output₁ = c₁ g₁(h₁) + c₂ g₂(h₁) + c₃ g₃(h₁) + c₄ g₄(h₁)

But h₁ h₂ h₃ h₄ are function of w₁₁ so we have

output₁ = c₁ g₁(h₁(w₁₁)) + c₂ g₂(h₁(w₁₁)) + c₃ g₃(h₁(w₁₁)) + c₄ g₄(h₁(w₁₁))

So then, for calculating the ∂output₁ / ∂w₁₁, we are applying the multivariate chain rule somewhere!

Recap & About Me

Material referenced in the post:

If you liked this post / my style, you can connect with me on other social networks.

At ICPC World Finals (Astana 2024) as coach.

I will try to keep on posting regularly about SE, Deep Learning, and NLP, always with these objectives in mind:

  • being didactic
  • being meaningful
  • explain with examples