Skip to main content

Welcome to a Grasp lesson

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

Lesson 4

Understanding Vanishing and Exploding Gradients in RNNs

Recommended resources

Hello! Welcome to your fourth lesson in our journey into the world of Large Language Models.

In our last lesson, we explored the sequence-to-sequence (seq2seq) architecture, which uses an encoder and a decoder RNN to handle variable-length sequences. We identified a key limitation: the context vector bottleneck, where the entire meaning of a long input sequence must be compressed into a single, fixed-size vector.

Today, we'll investigate a more fundamental problem with the simple RNNs used in that architecture: the vanishing and exploding gradient problems. This issue is the primary reason why simple RNNs struggle to remember information over long sequences, making the context vector bottleneck even more severe. Understanding this is essential, as it directly motivated the creation of more sophisticated recurrent units like LSTMs and GRUs, which we'll cover next.

How Gradients Flow in RNNs: Backpropagation Through Time

To understand why gradients can misbehave, we first need to visualize how an RNN is trained. The process is called Backpropagation Through Time (BPTT). You can think of it as "unrolling" the recurrent network for each token in the sequence. An RNN processing a 10-word sentence can be visualized as a 10-layer feed-forward network, with the crucial difference that the weights are shared across all 10 layers (timesteps).

When we calculate the loss at the end of the sequence, the error signal must be propagated backward through this entire unrolled structure to update the weights.

Vanishing Gradient Intuition in RNNs
This diagram shows an RNN unrolled over four timesteps. To calculate the gradient of the loss at step 4 with respect to the hidden state at step 1 (`h(1)`), we must apply the chain rule, multiplying the local gradients at each intermediate step. This creates a long product chain, which is the root of our problem.

For an intuitive walkthrough of how this unrolling works and how information flows, the following video is an excellent starting point.

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

The video 'Recurrent Neural Networks (RNNs), Clearly Explained!!!' from StatQuest with Josh Starmer provides a great visual intuition for unrolling an RNN and how weights are shared across timesteps.

Watch the segment from 4:43 to 11:18. Focus on how the network with a feedback loop is 'unrolled' into a deep structure to process a sequence. Note how the weights (like W_1 and W_2) are the same at every timestep.


The Mathematical Origin of the Problem

Now, let's look at the mathematics behind BPTT. Your goal of deep mastery requires us to go beyond intuition and understand the mechanism precisely. The gradient signal propagating from a later timestep k to an earlier timestep k-1 depends on the derivative of the hidden state update function.

Recall the basic RNN recurrence equation:

Using the chain rule, the gradient of the loss L with respect to the weights W involves a sum of contributions from each timestep. The critical part of this calculation is how the hidden state at a late timestep T is affected by a hidden state at an early timestep t. This is expressed as a product of Jacobian matrices:

Each Jacobian matrix in this product breaks down into two key components:

Where:

  • W_hh is the recurrent weight matrix.
  • tanh' is the derivative of the tanh activation function, which is always between 0 and 1.
  • diag(...) creates a diagonal matrix from the vector of tanh derivatives.

This product of matrices is the heart of the problem. We are repeatedly multiplying the same kind of transformation over and over. Linear algebra tells us that the behavior of repeated matrix multiplication is dominated by the matrix's eigenvalues.

The following article provides a clear and detailed mathematical derivation of this process.

Vanishing Gradients in RNNs: Why Neural Networks Forget Long Sequences

The article 'Vanishing Gradients in RNNs' offers an excellent, in-depth explanation of the gradient product chain. It mathematically derives why gradients decay or explode.

Please read the first two major sections: 'The Gradient Product Chain' and 'Why Gradients Vanish'. Focus on understanding how the chain rule leads to a long product of Jacobians and how each Jacobian is composed of the recurrent weights and the activation derivative.


The Vanishing Gradient Problem

As the article explains, the tanh derivative is always ≤ 1. This means the diag(tanh'(z_k)) matrix always shrinks the gradient. If the largest eigenvalue (in magnitude), known as the spectral radius ρ(W_hh), of the recurrent weight matrix is also less than 1, the overall effect of each multiplication is to shrink the gradient vector.

When you multiply many numbers that are less than 1 together, the result gets exponentially smaller.

  • 0.9 * 0.9 = 0.81
  • 0.9^10 ≈ 0.35
  • 0.9^50 ≈ 0.005

The Consequence: The gradient signal from the end of a long sequence becomes virtually zero by the time it propagates back to the beginning. The model gets no information about how to adjust the weights that processed the early inputs to reduce the final error. This makes it impossible for the network to learn long-range dependencies, such as connecting a pronoun at the end of a long paragraph to the noun it refers to at the beginning.


The Exploding Gradient Problem

Now consider the opposite case. What if the spectral radius of W_hh is greater than 1?

Even if the tanh derivative shrinks the gradient slightly, the expansion from W_hh can dominate. When you multiply many numbers greater than 1 together, the result grows exponentially.

  • 1.1 * 1.1 = 1.21
  • 1.1^10 ≈ 2.6
  • 1.1^50 ≈ 117

The Consequence: The gradient values can become astronomically large (Inf or NaN), leading to huge, unstable updates to the weights. This causes the training loss to diverge, and the model fails to learn anything.

The following video provides a more rigorous look at both scenarios from a linear algebra perspective, which will be valuable for your goal of deep mastery.

Vanishing Gradients: Why Training RNNs is Hard

The video 'Vanishing Gradients: Why Training RNNs is Hard' by DeepBean offers a concise and mathematically rigorous explanation of both gradient problems, linking them directly to the eigenvalues of the weight matrix.

Watch from 6:37 to 12:14. This section first explains the core intuition behind vanishing and exploding gradients (6:37 - 7:38) and then provides a more rigorous analysis using eigenvalues and the spectral radius (7:38 - 12:14). Pay close attention to how the properties of the weight matrix W and the activation's derivative gamma determine the outcome.

Test your understanding!

Suppose in a simplified RNN, the recurrent weight W_hh is just a scalar with value 1.2, and the tanh derivative at every step is approximately 0.8.

  1. What is the effective multiplication factor for the gradient at each backward step?
  2. After propagating backward 20 steps, by roughly what factor will the original gradient have been scaled? Is this a vanishing or exploding gradient scenario?
Show answer
  1. The effective factor is 1.2 * 0.8 = 0.96.
  2. After 20 steps, the gradient will be scaled by 0.96^20 ≈ 0.44. Since the factor is less than 1, this is a vanishing gradient scenario, even though the weight itself was greater than 1. This highlights the crucial role of the activation function's derivative.

An Asymmetric Problem with a Partial Solution

At first glance, these two problems seem like two sides of the same coin. However, there's a critical asymmetry in how we can deal with them.

For exploding gradients, we have a simple and effective solution: gradient clipping. If the norm (magnitude) of the gradient vector exceeds a certain threshold, we simply scale it down to that threshold. This acts like a safety valve, preventing the huge weight updates that destabilize training. It's a standard and essential technique when training RNNs.

For vanishing gradients, there is no such easy fix. Once a gradient has decayed to near-zero, you cannot "amplify" it because the directional information is already lost. You can't make a vector longer if you don't know which way it's supposed to point. This makes vanishing gradients the more fundamental and difficult problem to solve.


Conclusion

Today we've dissected one of the most significant historical challenges in training neural networks for sequences.

Key Takeaways:

  • Training RNNs involves Backpropagation Through Time (BPTT), which unrolls the network and creates a long chain of gradient calculations.
  • This process involves the repeated multiplication of a Jacobian matrix that contains the recurrent weights (W_hh) and the derivative of the activation function (tanh').
  • Vanishing Gradients: If the effective transformation factor is less than 1, the gradient signal shrinks exponentially as it travels back in time, preventing the model from learning long-range dependencies.
  • Exploding Gradients: If the factor is greater than 1, the gradient grows exponentially, leading to unstable training.
  • Exploding gradients can be managed with gradient clipping, but vanishing gradients require a more fundamental, architectural solution.

What's Next?

The inability of simple RNNs to overcome the vanishing gradient problem was a major roadblock. To solve it, researchers had to rethink the core RNN unit itself. This led to the development of gated architectures.

In our next lesson, we will explore Long Short-Term Memory (LSTM) and Gated Recurrent Units (GRU). You will see how they introduce explicit "gates" and a "cell state" to create an express lane for gradients, allowing learning signals to flow across hundreds of timesteps without vanishing. This was the key innovation that made RNNs truly effective for a wide range of complex sequence tasks.