Backpropagation: every gradient in one backward pass
The chain rule in matrix form, its cost in operations and memory, and what it says about initialization.
On this page
Gradient descent needs the derivative of the loss with respect to every parameter (article 5). Article 5 computed these derivatives by hand for a network with one hidden unit, and article 7 introduced deep networks whose parameters number in the hundreds of thousands. This article derives the algorithm that computes all of these derivatives at once, backpropagation, in full. We first run it on a chain of scalar functions with actual numbers, then state the general rule for any computation, then derive the matrix form for a deep network and work through an example. We then count its cost in operations and memory, show how the backward pass starts from the loss, place it within automatic differentiation, and finally use the backward equations to explain why the scale of the initial weights decides whether a deep network trains at all.
1. Why we need an algorithm
The simplest way to estimate a derivative is to nudge a parameter and measure the change in the loss. The central difference
needs two evaluations of the loss for each parameter, each a full forward pass through the network. For the classifier of article 7, with 269,322 parameters, one gradient would cost 538,644 forward passes. Gradient descent takes thousands of steps, so this is hopeless.
Two observations point to a better method. First, a weight multiplies an activation, so its effect on the loss is proportional to that activation: if the activation is zero, changing the weight does nothing, and if it is large, a small change in the weight has a large effect. Second, a parameter in an early layer affects the loss only through all the layers after it. Every early parameter shares the same downstream path, so the derivatives along that path can be computed once and reused. Backpropagation exploits both: it computes the derivatives with respect to the intermediate values, starting at the loss and working backwards, and then reads off each parameter's derivative from the intermediate value it feeds and the activation it multiplies.
2. A chain of functions
We start with a model that is a chain of scalar operations, the smallest case that has all of backpropagation's steps. We defer the network version until section 4. With one input , the model computes:
It has the structure of a deep network with one unit per layer. Each is an affine function with a bias and a weight ("omega"), and each applies a nonlinear function to it. We use three different nonlinear functions instead of ReLU so that every step of the derivation looks different. The last line is the squared error for one training example . The model has eight parameters.
We take , and the parameter values , , , , , , , .
The forward pass evaluates equation 8.2 from top to bottom and stores every intermediate value: , , , , , , and finally .
The backward pass computes the derivative of the loss with respect to each intermediate value, in the opposite order. We start at the end:
The value affects the loss only through , which grows by for every unit of . By the chain rule:
Next, affects the loss only through , whose derivative is :
The pattern repeats down the chain. Each step multiplies the derivative computed in the previous step by one local derivative, the derivative of a single operation with respect to its input:
where is the nonlinear function of step (sin, exp or cos here). In words: to move back past an affine step, multiply by its weight; to move back past a nonlinear step, multiply by the slope of the function at the value it received in the forward pass. The second rule is why the forward pass stored the . Continuing gives , , and . Figure 8.1 shows all the values.
Figure 8.1 Forward and backward passes through a chain. The model of equation 8.2 with and . The forward pass (dark arrows) applies each operation, shown above its arrow, and stores the result (dark numbers). The backward pass (orange arrows) starts from and multiplies by one local derivative per step (equation 8.3), giving the derivative of the loss with respect to every intermediate value (orange numbers).
The parameter derivatives now come almost for free. The bias enters only through , with local derivative 1, and the weight enters through multiplied by (with ):
These are the two observations of section 1 in equation form. The weight's derivative is the derivative at the point where it acts, scaled by the activation it multiplies. For our values:
| 0 | ||
| 1 | ||
| 2 | ||
| 3 |
Each of the eight values agrees with the central difference of equation 8.1, with , to at least six decimal places. The backward pass needed about a dozen multiplications, roughly the work of one forward pass. The central differences needed sixteen forward passes.
3. The general rule: computational graphs
The chain had a single path from each value to the loss. Real networks branch: a hidden unit feeds every unit of the next layer, and a value can be used several times. The general rule handles this.
Any computation can be drawn as a computational graph: each node is a value, and an arrow from node to node means that is computed directly from (among other inputs). If is used by several nodes , a small change in changes all of them, and the effects on the loss add up. The multivariable chain rule gives:
We can break this down into two parts. The derivatives belong to nodes later in the graph and are already known if we process nodes from the loss backwards. The factors are local: each depends only on the single operation that computes , evaluated at the stored forward values. In words: the derivative of the loss with respect to a value is the sum, over everything that uses the value, of that user's derivative times the local derivative.
A tiny example shows the summation. Let feed two operations, and , and let . Then , and equation 8.5 gives . Writing the loss directly as gives the same derivative, . Forgetting one of the paths, a common bug in hand-written gradients, would give 2 or 6.
The algorithm is then: run the forward pass, storing every node's value; set ; visit the nodes in reverse order of computation, and for each node apply equation 8.5. Every arrow of the graph is used once in each direction, so the backward pass costs a small constant multiple of the forward pass, however many parameters there are. That is the whole of backpropagation. The rest of this article specializes it to deep networks and examines its consequences.
4. Backpropagation in matrix form
We now apply the general rule to the deep network of article 7 (equation 7.4). It is convenient to name the pre-activations. With , the forward pass computes, for :
and the output is . We define the error signal of layer as the derivative of the loss with respect to that layer's pre-activations, , a vector with elements.
Parameters. Element of is . The weight appears only in this element, multiplied by , so , exactly as in equation 8.4. Collecting all and :
The weight gradient is an outer product: a column vector with elements times a row vector with elements, which gives a matrix, the same shape as . In words: the gradient for the weight from unit to unit is unit 's error signal times unit 's activation.
Moving back past a weight matrix. Unit of is used by every element of , with local derivative . Equation 8.5 sums over these uses: . The sum runs down column of , so in matrix form it is a product with the transpose:
The shapes check: times elements gives elements, one per unit of . The forward pass multiplies by ; the backward pass multiplies by and sends each error signal back along the same connections.
Moving back past the activation. Element of depends only on element of , so the local derivative is the slope of the activation function there:
where multiplies two vectors element by element. For ReLU, the slope is 1 where the pre-activation is positive and 0 where it is negative, so equation 8.9 zeroes the error signal of every inactive unit. (At exactly zero the derivative is undefined; libraries use 0.)
Together, equations 8.7–8.9 are the backward pass for a deep network:
- Run the forward pass (equation 8.6), storing every and (for ReLU, the signs of are enough).
- Compute from the loss (section 6).
- For : compute the parameter gradients of layer with equation 8.7; if , compute with equations 8.8 and 8.9.
We work through a network with sizes , which has 15 parameters, ReLU activations and squared error. The input is , the target is , and the parameters are:
The forward pass gives , so : the first unit of layer 1 is inactive. Then and : the second unit of layer 2 is inactive. The output is and the loss is .
The backward pass starts with . Equation 8.7 gives . Equation 8.8 gives , and equation 8.9 zeroes the inactive second element: . One layer further back:
and zeroing the inactive first unit gives , so has rows and . All 15 derivatives agree with central differences. Figure 8.2 shows the values on the network.
Figure 8.2 Backpropagation through a small ReLU network. Sizes , input , target , parameters as in section 4. Each unit shows its pre-activation and activation from the forward pass (dark) and its error signal from the backward pass (orange). The gray units are inactive (): they pass nothing forward, their error signal is zero, and every weight into or out of them gets a zero gradient for this example (dashed lines).
The example shows two properties that hold in general. First, an inactive ReLU unit blocks the gradient for this example in both directions: its incoming weights get and its outgoing weights multiply . A unit that is inactive for every training example never changes, which is called a dead ReLU. Second, each example's weight gradient has rank one. The gradient over a batch, a sum of such outer products, usually has higher rank, but at most the batch size.
5. Batches, cost and memory
Training uses a batch of examples and the mean loss (article 5). Each example has its own forward and backward pass, and the gradient of is the mean of the per-example gradients. With the activations of the batch as columns, as in article 7, and the error signals as columns of , the sum over examples of the outer products in equation 8.7 is one matrix product:
The shapes are : the product sums over the batch dimension. Equation 8.8 becomes , one product for the whole batch.
Operations. Per layer, the forward pass does one matrix product, , with multiply-adds. The backward pass does two of the same size: for the weight gradient and to continue backwards. The first layer can skip the second product, because nothing needs . So the backward pass costs about twice the forward pass, and a training step about three times. For the classifier, the forward pass needs 268,800 multiply-adds per example and the backward pass 336,896; the ratio is only 1.25 because the large first layer skips its second product.
Memory. Equation 8.10 needs , and equation 8.9 needs the signs of , both from the forward pass. Training must therefore keep every layer's activations for the whole batch until the backward pass reaches that layer, which costs memory proportional to . At prediction time there is no backward pass, and each layer's activations can be discarded once the next layer is computed. This is why training needs much more memory than prediction, and why the batch size is often limited by memory. Gradient checkpointing [7] trades computation for memory: it stores the activations of only some layers and recomputes the others during the backward pass, which for a chain of layers reduces activation memory to about layers' worth at the cost of roughly one extra forward pass.
6. Starting the backward pass: the loss
The backward pass starts from , which depends on the loss.
Squared error. For , the derivative is : the error itself, doubled. If the loss is a mean over examples, each example's signal is divided by .
Softmax and cross-entropy. For classification, the network outputs scores , softmax turns them into probabilities , and the loss is for the correct class (article 4). Substituting the softmax and using :
where runs over all classes. The first term depends only on , with derivative for and 0 otherwise. The derivative of the second term with respect to is . Together:
where is 1 for the correct class and 0 otherwise. In words: the error signal is the predicted probability minus the target probability. For the scores of article 4, with probabilities , and the photograph showing a cat, the error signal is . Gradient descent moves against it: it raises the cat score and lowers the other two, each in proportion to how wrong its probability is. The elements always sum to zero, because the probabilities sum to 1.
Equation 8.11 is simpler and better behaved than the two steps taken separately. Computing first and then fails when underflows to zero in floating point, and the derivative of alone, , is huge exactly where the softmax's own derivative is tiny. Libraries therefore provide a fused "cross-entropy from scores" that computes as with , so no exponential overflows, and uses equation 8.11 for the backward pass.
7. Automatic differentiation
Nothing in sections 3–6 is specific to neural networks. Any program built from operations whose local derivatives are known (additions, products, matrix products, exponentials, ReLU and so on) defines a computational graph, and the backward pass of section 3 computes the derivative of its output with respect to all of its inputs. This is reverse-mode automatic differentiation, and backpropagation is its special case for neural networks. Libraries such as PyTorch and JAX record the operations as the forward pass runs (or trace the program in advance) and provide, for each primitive operation, a rule that maps the derivative with respect to its output to the derivatives with respect to its inputs. Users write only the forward computation.
It helps to see why the reverse direction is the right one. For a chain of layers, the chain rule writes the gradient as a product of Jacobian matrices, , where is the matrix of derivatives of layer 's outputs with respect to its inputs. The leftmost factor is a row vector, because the loss is a single number. Multiplying from the left keeps every intermediate result a vector, and each step costs a vector-matrix product. Multiplying from the right instead carries full matrices through the chain. Forward-mode automatic differentiation does the latter one column at a time: it pushes the derivative with respect to one input forward alongside the values, which needs one pass per input or parameter. For a scalar loss and many parameters, reverse mode costs a small constant multiple of one forward pass, independent of the number of parameters [5]; forward mode costs a multiple of the number of parameters. Forward mode wins in the opposite situation, few inputs and many outputs.
Hand-written or custom gradients should be checked against central differences (equation 8.1). The central difference has error proportional to , against for the one-sided version. In 64-bit arithmetic, around and a relative error below about between the two gradients are typical; 32-bit arithmetic is too imprecise for a reliable check. Points within of a ReLU kink can disagree for a legitimate reason, because the two evaluations land on different linear pieces.
8. What the backward pass says about training deep networks
Unrolling equations 8.8 and 8.9 from the output to the first layer shows the structure of the error signal:
The signal that reaches an early layer has been multiplied by one weight matrix and one activation slope per layer. Products of many factors tend to grow or shrink exponentially with their length, and the same is true of the forward pass, which multiplies by one weight matrix and one activation per layer. The size of the weights decides which happens. This is the reason behind the initialization rule that article 5 stated without proof, and we can now derive it.
Forward. Suppose the weights of layer are drawn independently with mean 0 and variance , the biases are 0, and the pre-activations of the previous layer are symmetric around zero. Element of is a sum of independent terms , each with mean 0 and variance . A ReLU of a symmetric variable keeps exactly half of its squared mass, so . Hence:
Backward. Element of equation 8.8 is a sum of terms , and equation 8.9 keeps about half of the results. Treating the weights, error signals and activation pattern as independent (an approximation, but a good one at initialization), the same argument gives:
In words: each layer multiplies the variance of the forward signal by and the variance of the backward signal by . If these factors are smaller than 1, both signals vanish exponentially with depth; if they are larger, both explode. They equal 1 when (forward) or (backward), which is He initialization [6]. When all hidden layers have the same width , both conditions say .
Figure 8.3 checks this with a simulation: 50 ReLU layers of width 100, no biases, a batch of 256 random inputs, weights with variance for , and a random error signal at the top. With , the pre-activations and error signals keep roughly the same size through all 50 layers. With , each layer multiplies the standard deviation by about : after 50 layers the pre-activations have shrunk to of their size, and the error signal at the first layer to . With , both grow by about per layer, to and .
Figure 8.3 The scale of the initial weights decides whether signals survive 50 layers. A ReLU network with 50 layers of width 100, weights drawn with variance , a batch of 256 random inputs and a random error signal at the last layer. a) The root-mean-square size of the pre-activations in the forward pass. b) The size of the error signals in the backward pass, which runs from layer 50 down to layer 1. With (green, He initialization) both stay near 1, as equations 8.13 and 8.14 predict. With (blue) both shrink by a factor of about per layer, and with (orange) both grow by about per layer.
A subtlety appears when we look at the weight gradients themselves. By equation 8.7, the gradient of layer is . With , the activations are small in late layers and the error signals are small in early layers, and the product is small in every layer by about the same overall factor, ; the simulation measures weight-gradient norms between and at layers 1, 25 and 50 alike. So in a plain ReLU network with equal widths, a bad scale does not make early layers learn more slowly than late ones. It makes the whole network's outputs and gradients useless, and no single learning rate fixes outputs that are times the size they should be. In other settings the imbalance between layers is real. With sigmoid or tanh units, whose slopes are below 1 almost everywhere, and in recurrent networks, which multiply by the same matrix at every time step, the error signals shrink on the way back while the activations do not, so early layers or early time steps receive tiny gradients. This is the vanishing gradient problem in its classic form [8].
Initialization keeps the signals the right size at the start of training. It does not keep them there as the weights change, and it does not help with a different difficulty: the deep plain network that trains worse than a shallow one (article 7, section 5). Article 11 introduces residual connections, which add an identity path to every layer so that equation 8.12 no longer consists only of products, and normalization layers, which reset the scale of the activations at every layer.
Summary
Backpropagation computes the derivative of the loss with respect to every parameter in one backward pass whose cost is a small multiple of the forward pass. The forward pass stores the intermediate values. The backward pass starts from the derivative of the loss and visits the values in reverse order, multiplying by one local derivative per operation and summing over every use of a value (equation 8.5). For a deep network this gives three equations: the weight gradient is the error signal times the activation it multiplies, an outer product; the error signal moves back past a weight matrix by multiplying with its transpose; and it moves back past ReLU by zeroing inactive units. The backward pass costs about twice the forward pass, and training must keep every layer's activations, which is why it needs much more memory than prediction. For softmax with cross-entropy, the backward pass starts from the predicted probabilities minus the targets. The same algorithm, applied to any program, is reverse-mode automatic differentiation. Finally, the backward pass is a product of one factor per layer, and analysing its variance gives He initialization; the remaining difficulties of training very deep networks are taken up in article 11. Article 9 now turns from fitting the training data to generalizing beyond it.
Notes
History. Reverse-mode differentiation was described by Linnainmaa in 1970 [3] as a way to compute the rounding errors of long computations, and Werbos proposed applying it to neural networks in his 1974 thesis [4]. Rumelhart, Hinton and Williams [2] showed in 1986 that it lets multilayer networks learn useful internal representations, and that paper brought it into wide use. Baydin and colleagues [9] survey automatic differentiation for machine learning.
Second derivatives. Backpropagation gives the gradient. Second derivatives, the Hessian matrix, have entries and are rarely formed for neural networks. Products of the Hessian with a vector can be computed at the cost of a few gradient evaluations by applying forward mode to the backward pass, which is how many analyses of the loss curvature work.
Other initializations. For activations that are linear near zero, such as tanh, equation 8.13 without the factor suggests . Glorot and Bengio [10] compromised between the forward and backward conditions with , often called Xavier initialization. The derivations assume independent weights; orthogonal initialization, which draws each weight matrix as a random rotation, preserves the length of every vector exactly in a linear network.
Non-differentiable points. ReLU has no derivative at 0, and maximum and absolute-value operations have similar kinks. Automatic differentiation picks one value of the derivative there (for ReLU, 0). Because pre-activations are exactly zero with negligible probability, this choice rarely matters in practice.
Reading further. Chapter 7 of Understanding Deep Learning [1] derives backpropagation for the same toy model and for deep networks, and covers initialization. Griewank and Walther [5] is the standard reference on automatic differentiation.
Problems
Problem 8.1 For the chain of section 2, compute . Why does training never need it? (Answer: . The input is data, not a parameter, so gradient descent never updates it.)
Problem 8.2 In the network of section 4, change the target to and leave everything else unchanged. What are the new gradients? (Answer: the forward pass is unchanged and . Every gradient is linear in , so all of them are multiplied by : for example and has rows and .)
Problem 8.3 For the scores , compute the error signal of equation 8.11 when the correct class is the second one. Show that the elements of equation 8.11 always sum to zero. (Answer: . The sum is .)
Problem 8.4 Let , , and . Compute with equation 8.5 and check it by writing as a function of . (Answer: and , so . Directly, and its derivative is .)
Problem 8.5 How many multiply-adds does one training step of the classifier need for a batch of 256, forward and backward together? (Answer: , about 155 million.)
Problem 8.6 Repeat the forward-variance derivation of section 8 for an activation function that is the identity, . Which weight variance keeps the pre-activations the same size? (Answer: without the ReLU, , so and .)
Problem 8.7 In the simulation of figure 8.3 with , by roughly what factor should the size of the pre-activations shrink between layer 1 and layer 50, according to equation 8.13? Compare with the measured and . (Answer: ; the measured ratio is , the same order of magnitude. The difference comes from random fluctuations that compound over 49 layers.)
References
- 1: Simon J.D. Prince (2023). Understanding Deep Learning. MIT Press.
- 2: David Rumelhart, Geoffrey Hinton and Ronald Williams (1986). Learning representations by back-propagating errors. Nature 323, 533–536.
- 3: Seppo Linnainmaa (1970). The representation of the cumulative rounding error of an algorithm as a Taylor expansion of the local rounding errors. Master's thesis, University of Helsinki.
- 4: Paul Werbos (1974). Beyond regression: new tools for prediction and analysis in the behavioral sciences. PhD thesis, Harvard University.
- 5: Andreas Griewank and Andrea Walther (2008). Evaluating Derivatives: Principles and Techniques of Algorithmic Differentiation, 2nd edition. SIAM.
- 6: Kaiming He, Xiangyu Zhang, Shaoqing Ren and Jian Sun (2015). Delving deep into rectifiers: surpassing human-level performance on ImageNet classification. International Conference on Computer Vision.
- 7: Tianqi Chen, Bing Xu, Chiyuan Zhang and Carlos Guestrin (2016). Training deep nets with sublinear memory cost. arXiv:1604.06174.
- 8: Yoshua Bengio, Patrice Simard and Paolo Frasconi (1994). Learning long-term dependencies with gradient descent is difficult. IEEE Transactions on Neural Networks 5(2), 157–166.
- 9: Atılım Güneş Baydin, Barak Pearlmutter, Alexey Radul and Jeffrey Siskind (2018). Automatic differentiation in machine learning: a survey. Journal of Machine Learning Research 18(153), 1–43.
- 10: Xavier Glorot and Yoshua Bengio (2010). Understanding the difficulty of training deep feedforward neural networks. International Conference on Artificial Intelligence and Statistics.