---
id: wiki-2026-0508-exploding-gradient-problem
title: Exploding Gradient Problem
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [exploding gradient, gradient clipping, RNN explosion, weight init, Xavier He]
duplicate_of: none
source_trust_level: A
confidence_score: 0.98
verification_status: applied
tags: [deep-learning, training, gradient-explosion, gradient-clipping, weight-initialization]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
  language: Python
  framework: PyTorch / TensorFlow
---

# Exploding Gradient Problem

## 매 한 줄
> **"매 deep / recurrent network 의 gradient 의 magnitude 의 explode"**. 매 loss = NaN. 매 cause: 매 deep chain rule + 매 weight > 1 의 multiply. 매 mitigation: gradient clipping, 매 better init (Xavier/He), 매 LayerNorm, 매 residual.

## 매 핵심

### 매 cause
- **Chain rule**: 매 ∏ (∂h/∂h_prev) > 1 → exp.
- **RNN**: 매 same weight 의 매 timestep multiply.
- **Bad init**: 매 weight scale.
- **High learning rate**.
- **No normalization**.

### 매 detection
- **Loss = NaN**.
- **Grad norm = inf**.
- **Weight diverge**.
- **Activation overflow**.

### 매 mitigation
1. **Gradient clipping** (norm or value).
2. **Weight init** (Xavier, He, orthogonal).
3. **LayerNorm / BatchNorm**.
4. **Residual connection**.
5. **LSTM / GRU** (gating).
6. **Smaller learning rate**.
7. **Gradient check**.

### 매 응용
- **RNN / LSTM training**.
- **Deep Transformer**.
- **GAN training**.
- **RL policy**.

## 💻 패턴

### Gradient clipping (norm)
```python
import torch
def train_step(model, loss, optim, max_norm=1.0):
    optim.zero_grad()
    loss.backward()
    torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm)
    optim.step()
```

### Gradient clipping (value)
```python
torch.nn.utils.clip_grad_value_(model.parameters(), clip_value=0.5)
```

### Adaptive clip (recent)
```python
def adaptive_clip(grads, percentile=99):
    norms = [g.norm() for g in grads]
    threshold = np.percentile([n.item() for n in norms], percentile)
    for g in grads: g.data.mul_(min(1, threshold / max(g.norm(), 1e-6)))
```

### Xavier / Glorot init
```python
import torch.nn as nn
for m in model.modules():
    if isinstance(m, nn.Linear):
        nn.init.xavier_uniform_(m.weight)
        nn.init.zeros_(m.bias)
```

### He init (ReLU)
```python
for m in model.modules():
    if isinstance(m, nn.Linear):
        nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
```

### Orthogonal init (RNN)
```python
for name, param in model.named_parameters():
    if 'weight_hh' in name:
        nn.init.orthogonal_(param)
```

### LayerNorm
```python
class TransformerBlock(nn.Module):
    def __init__(self, d):
        super().__init__()
        self.ln1 = nn.LayerNorm(d)
        self.ln2 = nn.LayerNorm(d)
        self.attn = MultiHeadAttention(d)
        self.mlp = nn.Sequential(nn.Linear(d, 4*d), nn.GELU(), nn.Linear(4*d, d))
    
    def forward(self, x):
        x = x + self.attn(self.ln1(x))  # 매 pre-norm
        x = x + self.mlp(self.ln2(x))
        return x
```

### Residual connection
```python
class ResBlock(nn.Module):
    def __init__(self, d):
        super().__init__()
        self.layers = nn.Sequential(nn.Linear(d, d), nn.ReLU(), nn.Linear(d, d))
    
    def forward(self, x):
        return x + self.layers(x)  # 매 gradient highway
```

### Detect explosion (logging)
```python
def grad_norm(model):
    total = 0
    for p in model.parameters():
        if p.grad is not None: total += p.grad.norm().item() ** 2
    return total ** 0.5

# 매 monitor + alert
gn = grad_norm(model)
if gn > 100 or np.isnan(gn):
    print(f'⚠️ Grad norm: {gn}')
```

### NaN guard
```python
def safe_train_step(model, loss, optim):
    if torch.isnan(loss).any() or torch.isinf(loss).any():
        print('Skipping NaN/Inf loss')
        return
    optim.zero_grad()
    loss.backward()
    grad_ok = all(not torch.isnan(p.grad).any() for p in model.parameters() if p.grad is not None)
    if grad_ok: optim.step()
```

### LR warmup (transformer)
```python
def warmup_cosine(step, warmup=4000, total=100000, peak_lr=1e-4):
    if step < warmup: return peak_lr * step / warmup
    progress = (step - warmup) / (total - warmup)
    return peak_lr * 0.5 * (1 + np.cos(np.pi * progress))
```

### Mixed precision (with GradScaler)
```python
from torch.cuda.amp import autocast, GradScaler
scaler = GradScaler()

with autocast():
    loss = model(batch)

scaler.scale(loss).backward()
scaler.unscale_(optim)
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
scaler.step(optim)
scaler.update()
```

### LSTM (gating fix for RNN)
```python
self.lstm = nn.LSTM(input_size, hidden_size, num_layers=2, batch_first=True)
# 매 forget gate 의 의 의 long sequence stabilize
```

### TBPTT (truncated BPTT)
```python
def tbptt_train(model, sequence, chunk=20):
    h = None
    losses = []
    for i in range(0, len(sequence), chunk):
        chunk_data = sequence[i:i+chunk]
        out, h = model(chunk_data, h)
        h = (h[0].detach(), h[1].detach())  # 매 detach 의 backprop 의 limit
        loss = compute_loss(out, target)
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        optim.step(); optim.zero_grad()
        losses.append(loss.item())
    return losses
```

## 매 결정 기준
| 상황 | Mitigation |
|---|---|
| Default DL | Clip + LayerNorm + He init |
| RNN | + orthogonal + TBPTT |
| Transformer | LayerNorm + warmup |
| GAN | Spectral norm + low LR |
| Mixed precision | + GradScaler |

**기본값**: 매 grad clip 1.0 + 매 He init + 매 LayerNorm + 매 LR warmup + 매 NaN guard.

## 🔗 Graph
- 부모: [[Deep-Learning]] · [[Optimization]]
- 변형: [[Gradient-Clipping]]
- 응용: [[데이터_사이언스_및_ML_엔지니어링|RNN]] · [[Transformer]] · [[Generative-Adversarial-Networks|GAN]]
- Adjacent: [[LayerNorm]]

## 🤖 LLM 활용
**언제**: 매 deep model train. 매 RNN. 매 GAN.
**언제 X**: 매 shallow / pretrained inference.

## ❌ 안티패턴
- **No clip in RNN**: 매 NaN guarantee.
- **Default init in deep ReLU**: 매 He init 의 use.
- **No LR warmup**: 매 transformer fail.
- **Ignore NaN once**: 매 cascade.
- **Clip 너무 작게**: 매 underfit.

## 🧪 검증 / 중복
- Verified (Pascanu 2013, He init 2015, Goodfellow Deep Learning).
- 신뢰도 A.

## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-04-26 | GRAD-EXPL auto |
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — clip / init / norm / TBPTT / mixed-prec code |
