Das Problem verschwindender Gradienten über tiefe Zeitschritte
Lernende beobachten explodierende und verschwindende Gradienten in einem tiefen RNN anhand der Protokollierung von Gradientennormen und verstehen, warum lange Sequenzen das Training instabil machen.
Das Problem verschwindender Gradienten über tiefe Zeitschritte ist eine kostenlose Machine Learning Academy-Lektion auf CoddyKit. Dies ist Lektion 2 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Machine Learning Academy-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Machine Learning Academy-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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.
Häufig gestellte Fragen
Ist die Lektion „Das Problem verschwindender Gradienten über tiefe Zeitschritte“ kostenlos?
Ja — der vollständige Text von „Das Problem verschwindender Gradienten über tiefe Zeitschritte“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Machine Learning Academy-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Machine Learning Academy-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Das Problem verschwindender Gradienten über tiefe Zeitschritte“?
Lernende beobachten explodierende und verschwindende Gradienten in einem tiefen RNN anhand der Protokollierung von Gradientennormen und verstehen, warum lange Sequenzen das Training instabil machen. Du übst Machine Learning Academy mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Machine Learning Academy zu starten?
Keine Vorkenntnisse erforderlich. Machine Learning Academy auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 2 von 4.
Wie lange dauert die Lektion „Das Problem verschwindender Gradienten über tiefe Zeitschritte“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Machine Learning Academy-Lektion Code schreiben und ausführen?
Ja. Jede Machine Learning Academy-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Klassische RNNs: Hidden State und Entfaltung über Sequenzen
- Das Problem verschwindender Gradienten über tiefe Zeitschritte
- LSTM-Zelle: Eingabe-, Vergessens- und Ausgabegates
- Sequence-to-One: Sentimentanalyse mit einem LSTM