0Pricing
Machine Learning Academy · 강의

긴 시간 단계의 그래디언트 소실 문제

학습자는 그래디언트 크기 기록을 통해 깊은 RNN에서 그래디언트 폭주와 소실을 관찰하고, 긴 시퀀스가 학습을 불안정하게 만드는 이유를 이해합니다.

긴 시간 단계의 그래디언트 소실 문제은(는) CoddyKit의 무료 Machine Learning Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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.

자주 묻는 질문

“긴 시간 단계의 그래디언트 소실 문제” 강의는 무료인가요?

네 — “긴 시간 단계의 그래디언트 소실 문제” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Machine Learning Academy 강의 전체를 잠금 해제할 수 있습니다. Machine Learning Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“긴 시간 단계의 그래디언트 소실 문제”에서 뭘 배우나요?

학습자는 그래디언트 크기 기록을 통해 깊은 RNN에서 그래디언트 폭주와 소실을 관찰하고, 긴 시퀀스가 학습을 불안정하게 만드는 이유를 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 Machine Learning Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Machine Learning Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Machine Learning Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“긴 시간 단계의 그래디언트 소실 문제” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Machine Learning Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Machine Learning Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 기본 RNN: 은닉 상태와 시퀀스 전개
  2. 긴 시간 단계의 그래디언트 소실 문제
  3. LSTM 셀: 입력, 망각 및 출력 게이트
  4. 시퀀스 대 하나: LSTM을 활용한 감성 분석
← Machine Learning Academy(으)로 돌아가기