Skip to main content

Welcome to a Grasp lesson

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

Lesson 82

Understanding Vanishing and Exploding Gradients in RNNs

Recommended resources

Hello! Welcome back.

In our previous lesson, we established the fundamental architecture of a Recurrent Neural Network (RNN). We saw how its recurrent loop and shared weights allow it to process sequential data by maintaining a hidden state, or "memory," that carries information from one time step to the next.

However, as I hinted at the end of that lesson, this simple and elegant architecture has a critical flaw that severely limits its practical use. Today, we will explore this weakness.

Your learning outcome for this lesson is to explain the vanishing and exploding gradient problems that affect simple RNNs. Understanding this is crucial, as it provides the motivation for the more complex and powerful recurrent architectures like LSTMs, which we will cover next.

1. The Root of the Problem: Backpropagation Through Time (BPTT)

To understand where things go wrong, we first need to recall how a neural network learns. It uses backpropagation to calculate the gradient of the loss function with respect to each weight. This gradient tells the optimizer how to adjust the weights to reduce the error.

In an RNN, the output at a given time step (e.g., the 10th word in a sequence) depends on computations from all previous time steps. Therefore, to calculate the gradient for a weight that was used in an early time step, the error signal must be propagated backward from the end of the sequence all the way to the beginning. This process is called Backpropagation Through Time (BPTT).

Let's read a short introduction to this concept.

The Vanishing Gradient Problem in RNNs

The article 'The Vanishing Gradient Problem in RNNs' from ApX Machine Learning provides a concise explanation of BPTT. Focus on understanding why training an RNN involves propagating gradients not just through layers, but 'through time'.

Read the first three paragraphs of the article, starting from the top down to the sentence that ends with '...the chain rule requires us to multiply many gradient terms together, one for each time step we propagate back through.'

As the article states, the key takeaway is that BPTT uses the chain rule to calculate gradients. This means the gradient at an early time step is the result of multiplying many smaller gradient terms together, one for each step back in time.

This chain of multiplications is the source of our problems.

Vanishing Gradient Intuition in RNNs
This diagram illustrates the chain rule in BPTT. To find how the loss at step 4, J(4), is affected by the hidden state at step 1, h(1), we must multiply the partial derivatives from each intermediate step. This repeated multiplication is where gradients can either vanish or explode.

2. Exploding and Vanishing Gradients: A Visual Intuition

Depending on the values of the terms we are repeatedly multiplying, the final gradient signal can either grow exponentially until it's uselessly large (exploding gradients) or shrink exponentially until it's uselessly small (vanishing gradients).

The StatQuest video below gives a brilliant and simple visual intuition for both of these scenarios.

Recurrent Neural Networks (RNNs), Clearly Explained!!!

This video uses a simple RNN with a single recurrent weight to demonstrate how repeated multiplication leads to either exploding or vanishing gradients.

Watch from 11:18 to 15:36. This section covers the 'Vanishing/Exploding Gradient Problem'. Notice how the outcome depends entirely on whether the recurrent weight being multiplied is greater than 1 (exploding) or less than 1 (vanishing).

Let's formalize what you just saw:

  • Exploding Gradients: Occurs when the gradients are repeatedly multiplied by numbers greater than 1. The gradient signal grows exponentially, resulting in huge weight updates. This makes the training process unstable, and you'll often see the loss function result in NaN (Not a Number) or Inf (Infinity) values.
  • Vanishing Gradients: Occurs when the gradients are repeatedly multiplied by numbers less than 1. The gradient signal shrinks exponentially, becoming close to zero for early time steps. The network effectively stops learning from information seen long ago.

3. The Practical Consequence: Short-Term Memory

The exploding gradient problem is frustrating but easy to spot. The vanishing gradient problem is more insidious. The network might appear to be training fine, but it becomes incapable of learning long-range dependencies.

Imagine trying to predict the last word of this sentence:

"I grew up in France and I love the culture, the food, the art... I speak fluent _____."

To predict "French," the model needs to "remember" the word "France" from the beginning of the sentence. If the gradient signal from the end of the sentence has vanished by the time it gets back to the beginning, the weights that process "France" will not be updated properly to help with the prediction. The RNN effectively has short-term memory.

The following video provides an excellent walkthrough of this exact issue in a Natural Language Processing (NLP) context.

Vanishing and exploding gradients | Deep Learning Tutorial 35 (Tensorflow, Keras & Python)

This clip from the codebasics channel demonstrates why the vanishing gradient problem gives RNNs a 'short-term memory,' making them struggle with long-range dependencies in text.

Watch the segment from 05:31 to 09:33. Focus on the example provided. Understand why the network's ability to use the word 'today' to predict a word later in the sentence diminishes as the sequence gets longer.


4. A Formal Look and a Simple Solution

So far, we have built a strong intuition. The core mathematical mechanism involves the repeated multiplication of the Jacobian matrix , which is heavily influenced by the recurrent weight matrix from our previous lesson.

The gradient of the loss at a late time step with respect to a hidden state at an early time step is a product:

If the norm of the terms in the product is consistently > 1, the overall gradient explodes. If it's consistently < 1, it vanishes.

The Vanishing Gradient Problem in RNNs
This image ties everything together. The unrolled RNN at the top shows the recurrent weight `Wrec`. The equations on the right show how the gradient with respect to a past state involves a product of `Wrec` terms. The key at the bottom explicitly states: small `Wrec` leads to vanishing gradients, large `Wrec` leads to exploding gradients.

While the vanishing gradient problem is harder to solve, there is a very common and effective technique for the exploding gradient problem.

The Vanishing Gradient Problem in RNNs

Let's read a final summary that formally defines both problems and introduces a key technique for mitigating exploding gradients.

Please read from the paragraph starting 'The problem arises when these terms are consistently smaller than 1...' to the end of the section on exploding gradients, which mentions the solution 'gradient clipping'.

As the article mentioned, gradient clipping is a simple and practical solution for exploding gradients. It works by setting a predefined threshold for the gradient's magnitude. If a gradient exceeds this threshold during backpropagation, it's "clipped" or scaled down to the maximum value. This prevents the massive, destabilizing weight updates.

Test your understanding!

A data scientist is training two different RNN models.

  1. Model A: The training loss suddenly becomes NaN after just a few epochs.
  2. Model B: The model trains without any errors for many epochs, but its accuracy on a task requiring long-term context is no better than random chance.

Which gradient problem is likely affecting each model, and why?

Show answer
  • Model A is suffering from the exploding gradient problem. The gradients are growing exponentially, leading to numerical overflow (Inf or NaN), which causes the training process to crash.
  • Model B is suffering from the vanishing gradient problem. The gradients are shrinking to near-zero for early time steps, meaning the model is unable to learn dependencies between distant parts of the sequence. It trains without error but simply cannot learn the necessary long-range patterns.

Conclusion

In this lesson, we dissected a fundamental weakness of simple Recurrent Neural Networks. While powerful in theory, their reliance on backpropagation through time makes them susceptible to unstable gradients.

Key Takeaways:

  • Backpropagation Through Time (BPTT): The process of training RNNs involves unrolling the network and propagating gradients through the entire sequence, which requires repeated multiplication via the chain rule.
  • Vanishing Gradients: If recurrent weight matrices and activation function derivatives are small (norm < 1), the gradient signal shrinks exponentially, preventing the network from learning long-range dependencies. This results in a model with only "short-term memory."
  • Exploding Gradients: If recurrent weight matrices are large (norm > 1), the gradient signal grows exponentially, leading to numerical instability (NaN values) and divergent training.
  • Mitigation: Exploding gradients can be effectively handled using gradient clipping. The vanishing gradient problem is more difficult and required a fundamental change in the network's architecture.

Preview of the Next Lesson:

The vanishing gradient problem was a major obstacle in the history of deep learning. To solve it, researchers developed more sophisticated recurrent units. In our next lesson, we will explore the Long Short-Term Memory (LSTM) cell, an ingenious architecture that uses a system of "gates" to explicitly control the flow of information, allowing it to remember or forget information over long sequences and finally overcome the challenge of vanishing gradients.