3.5.3Sequence Models

Vanishing gradients in RNNs

3,015 words14 min readdifficulty · medium

Overview

The vanishing gradient problem occurs when gradients become exponentially small as they propagate backward through time in recurrent neural networks, making it impossible to learn long-term dependencies. This is the fundamental obstacle that prevented RNNs from being effective on real-world sequential tasks until LSTM and GRU architectures were developed.

Figure — Vanishing gradients in RNNs

The Mathematical Root Cause

To train via gradient descent, we need LWhh\frac{\partial L}{\partial W_{hh}} where LL is our loss. By the chain rule, gradients must flow backward through all time steps.

Derivation from First Principles

Let's derive why gradients vanish. Consider a simple RNN with loss LL at time step TT.

Step 1: Chain rule through time

To update parameters at time tt, we need: Lht=LhThTht\frac{\partial L}{\partial h_t} = \frac{\partial L}{\partial h_T} \cdot \frac{\partial h_T}{\partial h_t}

Why this step? The loss at time TT depends on hth_t only through the chain of hidden states htht+1hTh_t \to h_{t+1} \to \cdots \to h_T. We must accumulate gradients across this entire path.

Step 2: Expand the chain

hTht=hThT1hT1hT2ht+1ht\frac{\partial h_T}{\partial h_t} = \frac{\partial h_T}{\partial h_{T-1}} \cdot \frac{\partial h_{T-1}}{\partial h_{T-2}} \cdots \frac{\partial h_{t+1}}{\partial h_t}

=k=t+1Thkhk1= \prod_{k=t+1}^{T} \frac{\partial h_k}{\partial h_{k-1}}

Why this step? Each hidden state depends directly only on the previous one, so we chain all the local derivatives together.

Step 3: Compute the local derivative

From hk=tanh(Whhhk1+Wxhxk+bh)h_k = \tanh(W_{hh}h_{k-1} + W_{xh}x_k + b_h):

hkhk1=diag(tanh(zk))Whh\frac{\partial h_k}{\partial h_{k-1}} = \text{diag}(\tanh'(z_k)) \cdot W_{hh}

where zk=Whhhk1+Wxhxk+bhz_k = W_{hh}h_{k-1} + W_{xh}x_k + b_h and tanh(z)=1tanh2(z)\tanh'(z) = 1 - \tanh^2(z).

Why this step? The chain rule for the composition tanh()\tanh(\cdot) applied to a linear transformation gives us the derivative of the activation times the weight matrix.

Step 4: Bound the product

Since tanh(z)1\tanh'(z) \leq 1 for all zz, each diagonal entry is at most 1. Therefore:

hkhk1Whh\left\| \frac{\partial h_k}{\partial h_{k-1}} \right\| \leq \| W_{hh} \|

Why this step? The derivative of tanh is bounded (each diagonal entry 1\leq 1), and matrix norms satisfy ABAB\|AB\| \leq \|A\| \cdot \|B\|. So the tanh factor can only shrink the norm, leaving Whh\|W_{hh}\| as the effective per-step multiplier.

Step 5: The exponential decay

For a product of (Tt)(T-t) terms:

hThtWhhTt\left\| \frac{\partial h_T}{\partial h_t} \right\| \leq \| W_{hh} \|^{T-t}

If Whh<1\|W_{hh}\| < 1 (whether by default initialization or by weight decay driving the spectral norm below 1), then:

hThtγTt\left\| \frac{\partial h_T}{\partial h_t} \right\| \leq \gamma^{T-t}

where γ<1\gamma < 1. This decays exponentially in the time gap (Tt)(T-t).

Important distinction: The two mechanisms act on different factors. The spectral norm Whh\|W_{hh}\| is a property of the weight matrix and is what must be <1< 1 for this bound to produce decay. Tanh saturation does not change Whh\|W_{hh}\|—instead it shrinks the diag(tanh(zk))\text{diag}(\tanh'(z_k)) factor toward 00, which multiplies on top of the Whh\|W_{hh}\| term. Both push in the same (shrinking) direction, but they are separate contributions and must not be conflated.

Why this step? Multiplying a number less than 1 by itself many times gives exponential decay. After just 10 time steps with γ=0.9\gamma = 0.9, the gradient is 0.9100.350.9^{10} \approx 0.35. After 50 steps: 0.9500.0050.9^{50} \approx 0.005. The gradient effectively vanishes.

Setup: We have a sequence of length 50, and we want to see how a gradient at t=50t=50 affects parameter updates at t=0t=0.

Computation: h50h0=0.950=5.15×103\frac{\partial h_{50}}{\partial h_0} = 0.9^{50} = 5.15 \times 10^{-3}

Interpretation: A gradient of magnitude 1.0 at the output becomes 0.005 by the time it reaches the beginning. If our learning rate is 0.01, the parameter update is 0.01×0.005=0.000050.01 \times 0.005 = 0.00005—essentially zero. The network cannot learn dependencies that span 50 steps.

With typical RNN: Add tanh\tanh saturation on top. If inputs are large, tanh(z)0.1\tanh'(z) \approx 0.1 per step. Now the combined per-step multiplier (tanh factor ×\times weight factor) is: Effective multiplier per step=0.1×0.9=0.09\text{Effective multiplier per step} = 0.1 \times 0.9 = 0.09 0.09502×10530.09^{50} \approx 2 \times 10^{-53}

This is smaller than machine epsilon for float32. The gradient has numerically vanished. Note the 0.10.1 came from tanh's derivative and the 0.90.9 from the weight norm—separate factors that multiply.

Ct=ftCt1+itC~tC_t = f_t \odot C_{t-1} + i_t \odot \tilde{C}_t

Key difference: The gradient path through the cell state is: CtCt1=ft\frac{\partial C_t}{\partial C_{t-1}} = f_t

This is additive, not multiplicative through many layers. The forget gate ftf_t is learned and can be close to 1, creating an uninterrupted gradient highway.

Why this step? Instead of exponential decay from repeated multiplication by small numbers, we have a learned gate that controls how much of the old information (and its gradient) to preserve. When ft1f_t \approx 1, gradients flow nearly unchanged across many time steps.

When and Why It Happens

All three usually occur together in practice, but they act on different factors in the product.

Common Mistakes and Misconceptions

Why it's wrong: ReLU removes the shrinking tanh-derivative factor (making the local derivative either 00 or 11), but that does not guarantee explosion. Whether gradients explode still depends entirely on the spectral norm of WhhW_{hh}: if Whh>1\|W_{hh}\| > 1, the product diag(ReLU(zk))Whh\prod \text{diag}(\text{ReLU}'(z_k)) W_{hh} can now grow because the tanh damping is gone; if Whh<1\|W_{hh}\| < 1, gradients can still vanish. So ReLU removes one safety cushion (activation damping) without fixing the underlying credit-assignment problem—it does not inherently cause explosion, it just makes the weight spectral norm the sole controlling factor.

The fix: You typically need gradient clipping and careful (e.g., identity/orthogonal) initialization of WhhW_{hh} with ReLU RNNs, and even then the architecture doesn't solve the credit assignment problem. LSTMs/GRUs with carefully gated additions are the proper solution.

Why it's wrong: Gradients at different time steps decay at different rates. Early steps have vanished gradients (105010^{-50}) while recent steps have reasonable gradients (10210^{-2}). A single learning rate cannot fix both: large enough for early steps means exploding updates for recent steps.

The fix: Architectural solutions (LSTM/GRU) or adaptive optimizers (Adam, RMSprop) that maintain per-parameter learning rates. Even better: both together.

Why it's wrong: BatchNorm normalizes across the batch dimension, but vanishing gradients in RNNs occur across the time dimension. Normalizing hth_t across different sequences doesn't fix the temporal gradient flow within a single sequence. Layer normalization (across features at each time step) helps more, but still doesn't create gradient highways like LSTM gates do.

The fix: Use layer normalization + LSTM/GRU architecture. The gates are essential.

Practical Implications

1. Maximum learnable dependency length In practice, vanilla RNNs can only learn dependencies spanning 5-10 time steps. For language (need 20-50 token context) or time series (seasonal patterns over hundreds of steps), they fail completely.

2. Training symptoms

  • Loss plateaus early
  • Parameters barely change after first few epochs
  • Recent outputs learn, but early sequence context is ignored
  • Validation performance terrible on tasks requiring memory

3. When you still see this in modern architectures Even LSTMs can experience vanishing gradients if:

  • Sequences are extremely long (1000+ steps)
  • Forget gates saturate to 0 due to poor initialization
  • Very deep RNN stacks (many layers)

Solution Landscape

Approach How It Helps Limitations
LSTM/GRU Additive cell state updates create gradient highways More parameters, slower training
Gradient clipping Prevents explosion but not vanishing Doesn't create new gradient paths
Layer normalization Reduces saturation Doesn't fix multiplicative decay
Truncated BPTT Limits backprop depth Can't learn dependencies longer than truncation window
Attention mechanisms Bypass sequential processing entirely High memory cost, loses temporal inductive bias
Skip connections Add gradient highways like ResNets Must be carefully designed for recurrent structure
Recall Explain Like I'm Twelve

Imagine you're playing a game of telephone with 50 people in a line. The first person whispers a message, and each person passes it along. By the time it reaches the end, the message is completely garbled.

Now imagine you need to figure out who messed up the message. You start at the end and work backward, asking each person "how much did you change it?" But each person only remembers a tiny bit of what they did (like "I changed it by 10%"). When you multiply 0.9 × 0.9 × 0.9 fifty times, you get a number so small it's basically zero.

That's vanishing gradients: the "feedback signal" about what went wrong becomes so tiny by the time it reaches the beginning of the sequence that the network can't learn anything about the early parts.

LSTMs are like giving each person a notepad where they can write down the original message and pass THAT along too, not just their modified version. Now you have two paths: the telephone game (which still gets garbled) and the notepad (which stays accurate). The network learns to use the notepad for important long-term information.

Connections

  • Backpropagation Through Time - The training algorithm where this occurs
  • LSTM Architecture - The primary solution to vanishing gradients
  • GRU Architecture - A simplified alternative to LSTM
  • Exploding Gradients - The opposite problem when Whh>1\|W_{hh}\| > 1
  • Gradient Clipping - Addresses exploding but not vanishing
  • Attention Mechanisms - A way to bypass sequential processing entirely
  • Residual Connections - Similar additive gradient highways in feedforward networks
  • Activation Functions - Tanh saturation is a key contributor

#flashcards/ai-ml

What is the vanishing gradient problem in RNNs? :: When gradients become exponentially small as they backpropagate through time, making it impossible to learn long-term dependencies because parameter updates for early time steps approach zero.

What is the mathematical cause of vanishing gradients?
Gradients flow through a product of Jacobians k=t+1Thkhk1\prod_{k=t+1}^{T} \frac{\partial h_k}{\partial h_{k-1}}. When hkhk1<1\|\frac{\partial h_k}{\partial h_{k-1}}\| < 1 (due to tanh saturation and/or spectral norm Whh<1\|W_{hh}\| < 1), the product decays exponentially as γTt\gamma^{T-t} where γ<1\gamma < 1.
Why can't vanilla RNNs learn long-term dependencies?
For spanning T time steps, gradients decay as γT\gamma^T. With typical values like γ=0.9\gamma = 0.9, after 50 steps gradients are ~0.005, making parameter updates negligibly small. The network cannot learn from events that happened many steps ago.
How does LSTM solve the vanishing gradient problem?
LSTMs use a cell state with additive updates: Ct=ftCt1+itC~tC_t = f_t \odot C_{t-1} + i_t \odot \tilde{C}_t. The gradient path through the cell is CtCt1=ft\frac{\partial C_t}{\partial C_{t-1}} = f_t, which is additive not multiplicative. When forget gates are near 1, gradients flow nearly unchanged across many time steps—creating a "gradient highway."
What is the gradient decay formula in RNNs?
hThtWhhTtk=t+1Tdiag(tanh(zk))\left\| \frac{\partial h_T}{\partial h_t} \right\| \leq \| W_{hh} \|^{T-t} \cdot \prod_{k=t+1}^{T} \|\text{diag}(\tanh'(z_k))\|. Since tanh(z)1\tanh'(z) \leq 1 and typically Whh<1\|W_{hh}\| < 1, this product decays exponentially in the gap (Tt)(T-t).
Why does tanh saturation worsen vanishing gradients?
When z|z| is large, tanh(z)±1\tanh(z) \to \pm 1 and tanh(z)=1tanh2(z)0\tanh'(z) = 1 - \tanh^2(z) \to 0. Each saturated time step contributes a near-zero multiplier to the activation-derivative factor of the gradient product (separate from the weight norm), accelerating exponential decay.
Why won't simply using ReLU activation solve vanishing gradients?
ReLU removes the shrinking tanh-derivative factor (local derivative becomes 0 or 1) but does NOT inherently cause explosion. Whether gradients explode or vanish still depends on the spectral norm of WhhW_{hh}: >1>1 can explode, <1<1 can still vanish. ReLU removes the activation damping cushion without fixing credit assignment.
What are the three main causes of vanishing gradients?
(1) Long sequences—more time steps means more multiplications hence more decay; (2) Tanh saturation—shrinks the activation-derivative factor toward zero; (3) Small spectral norm—if Whh<1\|W_{hh}\| < 1, the weight factor shrinks gradients each step. These act on different factors in the product.
Why can't a larger learning rate compensate for vanishing gradients?
Gradients vanish at different rates for different time steps. Early steps might have gradients of 105010^{-50} while recent steps have 10210^{-2}. A single learning rate can't fix both: large enough for early steps causes exploding updates for recent steps, creating numerical instability.

What is the maximum dependency length vanilla RNNs can learn? :: Approximately 5-10 time steps in practice. Beyond this, exponential gradient decay makes parameter updates too small for effective learning, even though theoretically RNNs can model arbitrarily long dependencies.

Why doesn't batch normalization solve RNN vanishing gradients?
BatchNorm normalizes across the batch dimension, but vanishing gradients occur across the time dimension within each sequence. Normalizing different sequences doesn't fix temporal gradient flow. Layer normalization (across features at each time step) helps somewhat but doesn't create gradient highways like LSTM gates.
What is the key structural difference between RNN and LSTM gradient flow?
RNNs use multiplicative hidden state updates: ht=f(Whhht1+)h_t = f(W_{hh}h_{t-1} + \cdots), giving hTht=\frac{\partial h_T}{\partial h_t} = \prod (products decay). LSTMs use additive cell state updates: Ct=ftCt1+C_t = f_t \odot C_{t-1} + \cdots, giving CTCt=fk\frac{\partial C_T}{\partial C_t} = \prod f_k where fkf_k can be near 1 (preserves gradients).
How do you diagnose vanishing gradients during training?
Symptoms include: (1) Loss plateaus very early, (2) Gradient norms are orders of magnitude smaller for early layers than late layers, (3) Parameters barely change after initial epochs, (4) Model performs well on recent context but ignores earlier sequence information, (5) Validation performance is poor on tasks requiring long-term memory.

Concept Map

expands into

each term

shrinks

scales

product over T-t steps

if norm < 1

prevents learning

needed for

motivated

BPTT chain rule

Product of local derivatives

dh_k/dh_k-1 = diag tanh' times W_hh

tanh' bounded ≤ 1

Spectral norm of W_hh

Vanishing gradient

Long-term dependencies

Cat ... was example

LSTM and GRU

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, RNN ka basic kaam hai sequence yaad rakhna — jaise sentence mein "cat" singular hai, toh baad mein "was" aayega ya "were", yeh decide karne ke liye network ko purani cheez yaad rakhni padti hai. Problem tab aati hai jab yeh gap bada ho jaye. Training ke time gradient (yaani error ka feedback signal) ko piche ki taraf, har time step se hokar travel karna padta hai — isse hum Backpropagation Through Time bolte hain. Aur yahi jagah hai jahan "vanishing gradient" ka problem hota hai.

Ab core intuition yeh hai ki jab gradient piche jaata hai, toh har step pe woh ek matrix WhhW_{hh} se multiply hota hai, aur saath mein tanh ka derivative bhi lagta hai jo hamesha 1 se chhota ya barabar hota hai. Toh agar aap TtT-t steps piche jaate ho, toh effectively gradient WhhTt\|W_{hh}\|^{T-t} ke proportion mein chala jaata hai. Agar yeh norm 1 se kam hai, toh yeh exponentially chhota hota jaata hai — matlab jitna jyada piche, utna hi weak signal, lagbhag zero ho jaata hai. Isiliye network purani information se seekh hi nahi pata, kyunki feedback wahan tak pahunchte-pahunchte gayab ho jaata hai. Yaad rakho, do alag cheezein yahan kaam kar rahi hain: spectral norm (WhhW_{hh} ka property) aur tanh saturation — dono shrink karti hain par alag-alag factors pe, inko mix mat karna.

Yeh baat matter kyun karti hai? Kyunki isi problem ki wajah se plain RNNs real-world tasks pe fail ho jaate the — lambi dependencies capture nahi kar paate the. Isi wajah se LSTM aur GRU jaise architectures banaye gaye, jo special gates use karke gradient ko surakshit rakhte hain taaki woh vanish na ho. Toh yeh concept samajhna zaroori hai kyunki yahi foundation hai jispe modern sequence models aur aage chalke attention/transformers ki understanding tikki hui hai.

Go deeper — visual, from zero

Test yourself — Sequence Models

Connections