docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를 Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류. - 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로 자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거, 동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거. - 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming, Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business, Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로, 나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는 title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백). 원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지. - 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서. - 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는 지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지. - Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경. - 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
This commit is contained in:
@@ -0,0 +1,240 @@
|
||||
---
|
||||
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 |
|
||||
Reference in New Issue
Block a user