9148c358d0
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 폴더 제거.
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 |