Machine Learning Academy · 课时

深层时间步中的梯度消失问题

您将通过记录梯度范数观察深层 RNN 中的梯度爆炸与梯度消失,并理解为什么长序列会使训练变得不稳定。

第 2 / 4 课13 个步骤

深层时间步中的梯度消失问题 是 CoddyKit 上的免费 Machine Learning Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Machine Learning Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Machine Learning Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

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 explodes

Vanishing 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 steps

Observing 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: larger

Exploding 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 smaller

Why 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.0

Why 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.

免费开始

用 AI 导师学习 Python — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
30
课程
120

常见问题解答

「深层时间步中的梯度消失问题」课时是免费的吗?

是的 — 「深层时间步中的梯度消失问题」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Machine Learning Academy 课程的其余内容,请升级到 CoddyKit PRO。 Machine Learning Academy 课程共包含 4 节课。

「深层时间步中的梯度消失问题」这节课中我会学到什么?

您将通过记录梯度范数观察深层 RNN 中的梯度爆炸与梯度消失,并理解为什么长序列会使训练变得不稳定。 你通过在浏览器中直接运行的动手代码来练习 Machine Learning Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Machine Learning Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Machine Learning Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「深层时间步中的梯度消失问题」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Machine Learning Academy 课中编写并运行代码吗?

能。每节 Machine Learning Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 基础 RNN:隐藏状态与序列展开
  2. 深层时间步中的梯度消失问题
  3. LSTM 单元:输入门、遗忘门与输出门
  4. 序列到单值:使用 LSTM 进行情感分析
← 返回 Machine Learning Academy