The Vanishing Gradient Problem in Deep Time Steps
Learners will observe exploding and vanishing gradients in a deep RNN through gradient norm logging and understand why long sequences make training unstable.
The Vanishing Gradient Problem in Deep Time Steps is a free Machine Learning Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Machine Learning Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Gradients Must Travel Through Time
To learn from long-range dependencies in a sequence, gradients from the loss at the final timestep must travel backward through every timestep to update the parameters that processed the early inputs. For a sequence of length T, this means multiplying the same weight matrix W_hh by itself T times during BPTT. This repeated multiplication is the root cause of both vanishing gradients (exponential decay) and exploding gradients (exponential growth).
import torch
# Conceptual illustration of gradient travel through T steps
# Gradient = dL/dh_T * (W_hh)^T * ...
# If W_hh has spectral radius < 1:
W_small = torch.eye(4) * 0.9
print('W^10 max value:', (W_small @ W_small @ W_small @
W_small @ W_small @ W_small @
W_small @ W_small @ W_small @ W_small).abs().max().item())
# -> very small: gradient vanishes
# If W_hh has spectral radius > 1:
W_big = torch.eye(4) * 1.1
print('W^10 max value:', (W_big ** 10).abs().max().item())
# -> very large: gradient explodesVanishing Gradient: The Mathematical Root Cause
During BPTT, the gradient of the loss with respect to the hidden state at timestep t involves the product of the Jacobian matrices of h with respect to h at each step from t to T. The Jacobian at each step involves diag(f'(h_t)) * W_hh where f' is the derivative of the activation. For tanh, f' is bounded by 1, and typical random weights have spectral radius less than 1 — so this product of T matrices drives gradients to zero exponentially fast with T.
import torch
# Track gradient norm through BPTT
def simulate_bptt_gradient(T, weight_scale=0.9):
W = torch.eye(8) * weight_scale
grad = torch.ones(8) # gradient at final timestep
norms = [grad.norm().item()]
for t in range(T):
grad = W.T @ grad # one BPTT step
norms.append(grad.norm().item())
return norms
norms = simulate_bptt_gradient(T=20)
print('Gradient norms over 20 steps:')
print([f'{n:.4f}' for n in norms[::5]])
# Decreases from 2.83 -> nearly 0 after 20 stepsObserving Vanishing Gradients Experimentally
You can directly observe vanishing gradients by logging the gradient norm at each timestep during BPTT. Register backward hooks on each RNN step's hidden state to capture gradient magnitudes. In a 50-step vanilla RNN, the gradient at timestep 1 will typically be 1e-6 or smaller — effectively zero — meaning the first several tokens of a sequence have almost no influence on the model parameters. The model cannot learn that the subject at the start of a long sentence determines the verb at the end.
import torch
import torch.nn as nn
rnn = nn.RNN(4, 8, batch_first=True)
X = torch.randn(1, 30, 4, requires_grad=True)
output, h_n = rnn(X)
loss = output[:, -1, :].sum() # loss at last timestep
loss.backward()
# Gradient with respect to early inputs
if X.grad is not None:
per_step_grads = X.grad.abs().mean(dim=-1)
print('Gradient norms per timestep (first 5 vs last 5):')
print(per_step_grads[0, :5].tolist()) # early: tiny
print(per_step_grads[0, -5:].tolist()) # late: largerExploding Gradients: The Other Extreme
Exploding gradients occur when the spectral radius of W_hh exceeds 1 — gradient norms grow exponentially with sequence length. The symptom is NaN loss values or parameters updating to infinity. Unlike vanishing gradients (which cause silent learning failure), exploding gradients crash training visibly. The standard fix is gradient clipping: rescale the gradient vector to have maximum L2 norm of 1.0 before the optimizer step. This prevents catastrophic updates without removing the gradient signal.
import torch
import torch.nn as nn
import torch.optim as optim
rnn = nn.RNN(4, 8, batch_first=True)
optimizer = optim.SGD(rnn.parameters(), lr=0.1)
X = torch.randn(2, 50, 4) # 50-step sequence
output, _ = rnn(X)
loss = output.sum()
loss.backward()
# Check gradient norm before clipping
total_norm = 0
for p in rnn.parameters():
if p.grad is not None:
total_norm += p.grad.data.norm(2) ** 2
total_norm = total_norm ** 0.5
print(f'Gradient norm before clip: {total_norm:.2f}')
# Clip to max_norm=1.0
nn.utils.clip_grad_norm_(rnn.parameters(), max_norm=1.0)
optimizer.step()Visualising Gradient Norms Across Layers
A practical debugging technique is to log gradient norms for all parameters after each backward pass and plot them over training. For vanilla RNNs, the recurrent weight matrix W_hh typically shows much smaller gradients than the input weight W_xh, confirming that long-range information is not reaching the earlier parameters. This visualisation often reveals that only the last few timesteps contribute meaningfully to learning, motivating the switch to gated architectures.
import torch
import torch.nn as nn
rnn = nn.RNN(4, 8, batch_first=True, num_layers=1)
X = torch.randn(1, 20, 4)
out, _ = rnn(X)
out.sum().backward()
print('Gradient norms per parameter:')
for name, p in rnn.named_parameters():
if p.grad is not None:
norm = p.grad.norm().item()
print(f' {name}: {norm:.6f}')
# weight_ih_l0 (input weights): larger
# weight_hh_l0 (recurrent weights): often much smallerWhy tanh Makes Vanishing Worse
The tanh activation function is bounded between -1 and 1 with derivative 1 - tanh^2(x). When the input is large (saturated), the derivative approaches 0 — cutting the gradient to nearly zero at that step. Multiplying many near-zero derivatives through BPTT compounds the vanishing problem. ReLU has derivative 1 for positive inputs (no saturation), which helps gradient flow in feedforward networks, but in RNNs the repeated multiplication of W_hh still dominates and can cause explosions with ReLU.
import torch
# Tanh derivative: 1 - tanh(x)^2
x = torch.linspace(-4, 4, 9)
tanh_x = torch.tanh(x)
tanh_deriv = 1 - tanh_x ** 2
print('x: ', x.tolist())
print('tanh(x): ', [f'{v:.2f}' for v in tanh_x.tolist()])
print('tanh_deriv:', [f'{v:.2f}' for v in tanh_deriv.tolist()])
# At x=+/-3: deriv ~0.01 -- 100x smaller than at x=0
# Multiplied over 20 steps: 0.01^20 = 10^-40!Truncated BPTT: A Practical Workaround
Truncated BPTT limits gradient propagation to a fixed window of K timesteps instead of the full sequence length. Gradients are propagated back K steps, then the hidden state is detached from the computation graph (becoming a constant). This prevents memory and gradient explosion for very long sequences (audio, text corpora) at the cost of not learning dependencies spanning more than K steps. K=20-50 is typical for language modelling with vanilla RNNs.
import torch
import torch.nn as nn
rnn = nn.RNN(4, 8, batch_first=True)
batch_size = 4
h = torch.zeros(1, batch_size, 8) # initial hidden state
# Process a 200-step sequence in chunks of 20
full_sequence = torch.randn(batch_size, 200, 4)
for chunk_start in range(0, 200, 20):
chunk = full_sequence[:, chunk_start:chunk_start+20, :]
out, h = rnn(chunk, h.detach()) # detach: stop grad here
loss = out.sum()
loss.backward()
print(f'Chunk {chunk_start}-{chunk_start+20}: done')The Long-Range Dependency Challenge
Consider the sentence: 'The trophy that the man won was big.' The verb 'was' must agree with 'trophy', not with 'man'. This requires carrying information about 'trophy' across 5 words to where 'was' appears. A vanilla RNN trained via BPTT essentially cannot do this reliably for gaps longer than 5-10 tokens. This is the core limitation that motivated the development of LSTM (1997) and later Transformers (2017), both of which have explicit mechanisms for maintaining long-range information.
# Classic long-range dependency examples:
examples = [
'The trophy ... man ... was [big/big] -- which subject?',
'The cat ... [sat/sat] -- past vs present?',
'The key [was/were] -- singular subject far away'
]
for ex in examples:
print('Example:', ex)
# Vanilla RNN performance on long-range deps:
print('\nVanishing gradient effect on learning:')
for gap in [1, 5, 10, 20, 50]:
ability = 'easy' if gap < 5 else ('hard' if gap < 20 else 'nearly impossible')
print(f' {gap}-step gap: {ability} for vanilla RNN')Weight Initialisation Tricks for RNNs
Several initialisation tricks improve vanilla RNN training on moderate-length sequences. Initialising W_hh as an orthogonal matrix (spectral radius exactly 1) prevents early vanishing/explosion. Adding a skip connection from input directly to output bypasses several matrix multiplications. Identity matrix initialisation for W_hh with ReLU activation (IRNN) was shown to match LSTM on some tasks, proving initialisation alone can partially address the vanishing gradient problem.
import torch
import torch.nn as nn
rnn = nn.RNN(4, 8, batch_first=True)
# Orthogonal init for hidden-to-hidden weights
nn.init.orthogonal_(rnn.weight_hh_l0)
# Identity init (IRNN) for W_hh
nn.init.eye_(rnn.weight_hh_l0) # identity matrix
print('Spectral radius after orthogonal init:')
eigvals = torch.linalg.eigvals(rnn.weight_hh_l0)
print(eigvals.abs().max().item()) # should be ~1.0Why LSTM Was Invented
The vanishing gradient problem in RNNs was documented by Hochreiter in 1991. His solution, the Long Short-Term Memory (LSTM) network, introduced in 1997, replaces the single hidden state with a cell state that is protected by gates. The cell state flows through time with only additive modifications (not multiplicative), creating a gradient highway that allows gradients to flow backward indefinitely without vanishing. This single architectural innovation unlocked practical training of sequences with 100+ timestep dependencies.
# The core difference between RNN and LSTM gradient flow:
# Vanilla RNN: h_t = tanh(W_hh * h_{t-1} + W_xh * x_t)
# Gradient must pass through tanh and W_hh MULTIPLICATIVELY
# -> vanishes after ~10 steps
# LSTM: c_t = f_t * c_{t-1} + i_t * g_t
# Cell state c_t is updated ADDITIVELY
# Forget gate f_t can be near 1 (keep everything)
# -> gradient flows back cleanly
print('LSTM key insight: additive cell state update')
print('Gradient highway: constant error carousel')
print('Forget gate f_t controls information retention')Comparing RNN and LSTM Training Stability
The difference in training stability between vanilla RNNs and LSTMs becomes dramatic for sequences longer than 20-30 timesteps. On the classic copy task (reproduce the input sequence after a long delay), vanilla RNNs fail completely for delays above 10 steps, while LSTMs succeed for delays of 100+ steps. This practical benchmark concretely demonstrates that the vanishing gradient problem fundamentally limits vanilla RNNs, and that LSTM's architectural solution is necessary for real sequence modelling.
import torch
import torch.nn as nn
# Compare RNN vs LSTM on a 30-step sequence
models = {
'RNN': nn.RNN(4, 16, batch_first=True),
'LSTM': nn.LSTM(4, 16, batch_first=True)
}
X = torch.randn(8, 30, 4) # 30-step sequence
for name, model in models.items():
out, _ = model(X)
loss = out.sum()
loss.backward()
# Check gradient of first input vs last input
total_grad_norm = sum(
p.grad.norm().item() for p in model.parameters()
if p.grad is not None
)
print(f'{name} total grad norm: {total_grad_norm:.4f}')Quick Check
Test your understanding of Machine Learning with Python concepts from this lesson.
Lesson Recap
In this lesson you learned: vanishing gradients occur when repeated multiplication by W_hh (with spectral radius < 1) drives gradients to zero exponentially over long sequences, exploding gradients occur when spectral radius > 1 and are fixed with gradient clipping, and LSTM was invented specifically to solve the vanishing gradient problem through an additive cell state update that provides a gradient highway. Next up we examine the LSTM cell architecture in detail.
Frequently asked questions
Is the “The Vanishing Gradient Problem in Deep Time Steps” lesson free?
Yes — the full text of “The Vanishing Gradient Problem in Deep Time Steps” is free to read here on the web, and the Machine Learning Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Machine Learning Academy course, upgrade to CoddyKit PRO.
What will I learn in “The Vanishing Gradient Problem in Deep Time Steps”?
Learners will observe exploding and vanishing gradients in a deep RNN through gradient norm logging and understand why long sequences make training unstable. You practise Machine Learning Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Machine Learning Academy?
No prior experience is required. Machine Learning Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “The Vanishing Gradient Problem in Deep Time Steps” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Machine Learning Academy lesson?
Yes. Every Machine Learning Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Vanilla RNNs: Hidden State and Sequence Unrolling
- The Vanishing Gradient Problem in Deep Time Steps
- LSTM Cell: Input, Forget, and Output Gates
- Sequence-to-One: Sentiment Analysis with an LSTM