f8b21af4be
10_Wiki/Topics 대규모 정리: - 오류 캡처/미완성 stub 문서 227개 제거 - 교차폴더 중복 43클러스터 병합 (63파일 → redirect) - 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건 - 카테고리 MOC 6개 신규 생성 - Graph 섹션 미해결 related-keyword 링크 10,058건 제거 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
6.5 KiB
6.5 KiB
id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
| id | title | category | status | canonical_id | aliases | duplicate_of | source_trust_level | confidence_score | verification_status | tags | raw_sources | last_reinforced | github_commit | tech_stack | ||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| wiki-2026-0508-exploding-gradient-problem | Exploding Gradient Problem | 10_Wiki/Topics | verified | self |
|
none | A | 0.98 | applied |
|
2026-05-10 | pending |
|
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
- Gradient clipping (norm or value).
- Weight init (Xavier, He, orthogonal).
- LayerNorm / BatchNorm.
- Residual connection.
- LSTM / GRU (gating).
- Smaller learning rate.
- Gradient check.
매 응용
- RNN / LSTM training.
- Deep Transformer.
- GAN training.
- RL policy.
💻 패턴
Gradient clipping (norm)
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)
torch.nn.utils.clip_grad_value_(model.parameters(), clip_value=0.5)
Adaptive clip (recent)
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
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)
for m in model.modules():
if isinstance(m, nn.Linear):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
Orthogonal init (RNN)
for name, param in model.named_parameters():
if 'weight_hh' in name:
nn.init.orthogonal_(param)
LayerNorm
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
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)
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
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)
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)
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)
self.lstm = nn.LSTM(input_size, hidden_size, num_layers=2, batch_first=True)
# 매 forget gate 의 의 의 long sequence stabilize
TBPTT (truncated BPTT)
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_엔지니어링 · Transformer · Generative-Adversarial-Networks
- 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 |