Open the WaytoAGI knowledge base on Feishu · 100M+ visits, open to everyone →
WaytoAGI

Knowledge Base · Learning paths

Yes, You Should Understand Backpropagation

Backpropagation is the core of neural network training, yet it remains full of abstract pitfalls. Through real-world examples like vanishing gradients with Sigmoid, Dead ReLU, and exploding gradients in RNNs, this article shows why truly understanding backpropagation is essential for diagnosing training issues, initializing models correctly, and choosing the right activation functions.

backpropagationneural networksvanishing gradientexploding gradientdead relu

Translated from Chinese by AI. Spotted an issue? Use the feedback button.

Original link: https://karpathy.medium.com/yes-you-should-understand-backprop-e2f06eab496b

Author: Andrej Karpathy (Co-founder of OpenAI)

Published: December 2016

Translator: Dorothy. During translation, this version was used as a reference.

When we taught CS231n at Stanford (CS231n: Convolutional Neural Networks for Visual Recognition, a top-tier university course on deep learning and computer vision), we deliberately designed the programming assignments in the introductory backpropagation module to require explicit computation. Students had to implement both the forward and backward passes for every layer using raw NumPy (a Python library for scientific computing). It was common for students to complain on the class forum: “Why do we have to manually write backpropagation when, in the real world, frameworks like TensorFlow compute it automatically?”

This seems like a perfectly reasonable objection — after all, once the course is over, you’ll never write backpropagation again, so why practice it? Are we just torturing students for our own amusement? Simple answers like “it’s good to be curious about how things work” or “in case you ever want to improve the core algorithms” might suffice, but I wanted to write a dedicated article to present a much stronger, more practical argument.

The problem with backpropagation is that it is a leaky abstraction. (The Law of Leaky Abstractions is a principle in programming, first proposed by Joel Spolsky in his blog. It states that “all non-trivial abstractions are, to some degree, leaky.”)

In other words, it’s easy to fall into the trap of thinking that you can simply stack arbitrary layers together and that backpropagation will “magically” work on your data. But as the following clear examples show, that is often not the case — and the ways in which it fails are frequently highly unintuitive.

Something visually pleasing: the computational graph of a Batch Normalization layer, showing the forward pass (black) and backward pass (red). (Image from this article)

Vanishing Gradient in the Sigmoid Function

Let’s start with an easy one. There was a time when it was very popular to use nonlinear functions such as sigmoid (or tanh) in fully connected layers. It wasn’t until people started using backpropagation that they realized a tricky problem: if you carelessly set the initial values or perform data preprocessing, these nonlinear functions can “saturate” and completely stop learning — your training loss becomes flat or stops decreasing altogether. Here’s an example of a sigmoid computation inside a fully connected layer (using plain NumPy):

python
z = 1/(1 + np.exp(-np.dot(W, x))) # forward pass
dx = np.dot(W.T, z*(1-z)) # backward pass: local gradient for x
dW = np.outer(z*(1-z), x) # backward pass: local gradient for W

If your weight matrix W is initialized with excessively large values, the output of the matrix multiplication can have a very large range (e.g., numbers between -400 and 400). This will cause almost all values in vector z to become binary — either 1 or 0. In that case, z*(1-z) (the local gradient of the sigmoid nonlinearity) becomes zero in both cases (“vanishing gradient”), making the gradients for both x and W zero. Because of the “multiplication” in the chain rule, from this point onward all remaining backpropagated values will also be zero. (Since gradients are computed by multiplying the local gradients of each layer, if any layer’s local gradient is zero, the gradients of all layers before it will become zero. This is the effect of multiplication in the chain rule.)

Another less obvious but interesting fact about the sigmoid is that when z = 0.5, the maximum value of its local gradient z*(1-z) is only 0.25. This means that every time the gradient signal passes through a sigmoid gate, its magnitude is always reduced by at least a factor of four. If you are using basic SGD, the lower layers of the network will train much more slowly than the higher layers.

In summary: If you are using sigmoid or tanh nonlinearities in your network and you understand backpropagation, you should always be careful that your initialization does not cause them to saturate completely. See the detailed explanation in this CS231n lecture video.


Dying ReLU

Another interesting nonlinearity is ReLU, which thresholds neurons at zero. The core forward and backward pass for a fully connected layer using ReLU looks like this:

python
z = np.maximum(0, np.dot(W, x)) # forward pass
dW = np.outer(z > 0, x) # backward pass: local gradient for W

If you look closely, you’ll notice that if a neuron is clamped to zero during the forward pass (i.e., z = 0, it doesn’t “fire”), then its weights will receive zero gradient. This leads to the so-called “dead ReLU” problem: if a ReLU neuron is unfortunately initialized this way, it will never fire; or if during training its weights are updated aggressively into this region, the neuron will die permanently. It’s like permanent, irreversible brain damage. Sometimes you can run a forward pass over the entire training set and find that a large portion (e.g., 40%) of the neurons in your network are always zero.

In summary: If you understand backpropagation and your network uses ReLU, you should frequently worry about the dying ReLU problem. These neurons never activate for any sample in the entire training set and will remain dead forever. Neurons can also die during training, typically due to overly aggressive learning rates. See the detailed explanation in this CS231n lecture video.

Gradient Explosion in RNNs

Vanilla RNN (RNN stands for Recurrent Neural Network; Vanilla RNN is the most basic form of RNN) is another excellent example of the non-intuitive nature of backpropagation. I will copy and paste a slide from CS231n. This slide shows a simplified RNN that does not accept any input x and only computes the recursive hidden state (equivalently, the input x can always be zero):

This RNN is unrolled for T time steps. When you look closely at what backpropagation is doing, you will notice that the backward-in-time gradient signal passing through all the hidden states is always multiplied by the same matrix (the recurrent matrix Whh), interspersed with the backward pass of the nonlinearities.

What happens when you take a number a and keep multiplying it by another number b (i.e. abbbbbb...)? If |b| < 1, the sequence goes to zero; if |b| > 1, it explodes to infinity. The exact same thing happens during backpropagation in an RNN, except that b is a matrix rather than a scalar, so we must consider its largest eigenvalue.

In short: if you understand backpropagation and are using RNNs, you should probably worry about having to perform gradient clipping, or you would prefer to use LSTM instead. See the detailed explanation in this CS231n lecture video.

Practical Discovery: DQN Clipping

“DQN Clipping” refers to a clipping issue discovered in the practical application of DQN. DQN is short for Deep Q-Learning, a reinforcement learning algorithm. Clipping refers to limiting the gradient during training to prevent gradient explosion or vanishing.

Let’s look at another example — the one that actually inspired this article. Yesterday I was browsing practical implementations of Deep Q-Learning in TensorFlow (checking how others handle the NumPy equivalent of computing Q[:, a] where a is an integer vector — it turns out TF doesn’t support this trivial operation). Anyway, I searched for “dqn tensorflow”, clicked the first link, and found the core code. Here’s an excerpt:

If you are familiar with DQN, you can see that there is target_q_t, which is [reward * γ * argmax_a Q(s', a)], and then there is q_acted, which is the Q(s, a) of the action that was taken. The author subtracts the two to obtain the variable delta, and then wants to minimize it on line 295 using L2 loss and tf.reduce_mean(tf.square()). So far so good.

The problem lies in line 291. The author is trying to react to outliers, so if delta is too large, they clip it with tf.clip_by_value. This is done with good intention and looks reasonable from the forward pass perspective, but if you consider backpropagation, it introduces a significant error.

The clip_by_value function makes the local gradient zero outside the [min_delta, max_delta] range. Therefore, when delta exceeds the min/max thresholds, the gradient becomes exactly zero during backpropagation. While the author was trying to clip the gradient to add robustness, they were actually clipping the original Q delta. In this case, the correct approach is to replace tf.square with Huber loss:

python
def clipped_error(x):
    return tf.select(tf.abs(x) < 1.0,
                     0.5 * tf.square(x),
                     tf.abs(x) - 0.5)  # condition, true, false

This is a bit awkward in TensorFlow because what we really want is to clip the gradient when it exceeds a threshold. Since we cannot directly intervene in the gradient, we can only approximate it by defining a Huber loss. In Torch, this would be much simpler.

I opened an issue on the DQN repository, which was quickly fixed.

In Summary

Backpropagation is an abstract vulnerability — it is a credit assignment scheme with significant consequences. If you try to gloss over its underlying mechanics just because “TensorFlow automatically makes my network learn,” you will be ill-prepared to combat the dangers it introduces, and your efficiency in building and debugging neural networks will be greatly reduced.

The good news is that, when presented properly, backpropagation is not difficult to understand. I have relatively strong feelings about this topic because, in my view, 95% of the material on backpropagation is wrong — it is filled with mechanical mathematical formulas. Instead, I recommend the CS231n lecture on backpropagation, which emphasizes intuition (yes, please allow me to shamelessly plug my own work). If you have free time, as a bonus you can complete the CS231n assignments, which will have you implement backpropagation by hand and help solidify your understanding.

That’s it for now! I hope you remain curious about backpropagation and think carefully about what it is actually doing. Also, I know this article (unintentionally!) turned into several CS231n advertisements. My apologies :)