refactor(topics): 멀티 에이전트용 지식 재편 — _Common(공통 기본기) + Domain_* 구조

에이전트 8종(대화형/프로그래머 C·S/디자이너/설계자/기획자/QA/PD/PM)에게
[공통 기본 능력 + 롤별 Specialty] 2층으로 지식을 주입하기 위한 재분류.
문서 내용·포맷은 무수정, 폴더 이동만 (6,372개 문서 수 보존 확인).

- Topic_Programming → Domain_Programming (내부 구조 보존)
- Topic_Graphic → Domain_Design
- Topic_Business → Domain_Product
- Topic_General → Domain_General
- _Common 신설: Math(구 Topic_Math_Specialty), Reasoning(구 General/From_Thinking & Reasoning),
  Reasoning_Creativity(구 General/From_창의성), Communication(Poetic_Blog_Writing + From_writing)
- 타 도메인의 From_* 폴더는 유지 (출처 표기일 뿐, 이미 도메인에 맞게 분류된 문서)
- 빈 폴더 정리 (memory/procedures)
- 에이전트→폴더 매핑은 workspace의 .astra/agent-knowledge-map.json (9개 에이전트)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Antigravity Agent
2026-07-11 11:05:56 +09:00
parent 6549ead309
commit c24165b8bc
6193 changed files with 1717 additions and 31 deletions
@@ -0,0 +1,194 @@
---
id: wiki-2026-0508-momentum-and-optimization
title: Momentum and Optimization
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [Optimizers, SGD momentum, Adam, AdamW, Lion, Nesterov]
duplicate_of: none
source_trust_level: A
confidence_score: 0.95
verification_status: applied
tags: [optimization, deep-learning, adam, lion, sgd, training]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack: { language: python, framework: pytorch }
---
# Momentum and Optimization
## 매 한 줄
**Momentum**은 gradient에 관성(velocity)을 부여해 SGD의 수렴 속도와 안정성을 개선하는 1차 최적화의 핵심 트릭이며, 이를 진화시킨 Adam/AdamW/Lion이 2026년 LLM·비전 학습 표준이다.
## 매 핵심
### 1. Vanilla SGD vs Momentum
```
SGD: θ ← θ - η · ∇L(θ)
Momentum: v ← μ · v + ∇L(θ); θ ← θ - η · v (μ ≈ 0.9)
```
- 관성 계수 μ ≈ 0.9 — 직전 gradient의 90% 누적.
- ravine(좁은 골짜기)에서 SGD는 진동, momentum은 직진.
### 2. Nesterov Accelerated Gradient (NAG)
```
v ← μ · v + ∇L(θ - η · μ · v) ← look-ahead gradient
θ ← θ - η · v
```
- 이론적 convergence O(1/k²) (Nesterov 1983), volatile loss에서 momentum보다 안정.
### 3. Adaptive: Adam (Kingma 2014)
- 1차 모멘트 m, 2차 모멘트 v 모두 EMA.
- bias correction 후 `θ ← θ - η · m̂ / (√v̂ + ε)`.
- 기본 hyperparam: lr=1e-3, β₁=0.9, β₂=0.999, ε=1e-8.
### 4. AdamW (Loshchilov 2017) — 표준
- weight decay를 gradient에서 분리 (decoupled).
- LLM/Transformer 학습에서 사실상 default. lr=1e-4~3e-4, wd=0.01~0.1.
### 5. Lion (Chen et al., Google 2023)
- sign-based update: `θ ← θ - η · sign(β₁·m + (1-β₁)·g)`.
- 메모리 50% 절감 (1차 모멘트만), AdamW 대비 lr 10× 작게(1e-4 → 1e-5).
- 대규모 비전(ViT-G) / LLM 미세조정에서 동등 또는 우수 성능.
### 6. 2026 best practices
- **LLM pretrain**: AdamW, β₂=0.95, cosine LR with warmup, gradient clipping 1.0.
- **LLM finetune**: AdamW lr=2e-5 또는 Lion lr=2e-6.
- **Vision (ViT)**: AdamW or Lion, weight decay 0.05.
- **Diffusion**: AdamW lr=1e-4, EMA on weights.
- **Sophia / Shampoo**: 2차 정보 활용, 일부 frontier lab에서 채택 — wall-clock 1.5-2× 개선 보고.
## 💻 패턴
```python
# 1. SGD with momentum (PyTorch)
import torch
opt = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9, nesterov=True)
```
```python
# 2. AdamW — LLM finetune 표준
opt = torch.optim.AdamW(
model.parameters(),
lr=2e-5, betas=(0.9, 0.95), weight_decay=0.01, eps=1e-8,
)
```
```python
# 3. Lion (lion-pytorch 패키지)
from lion_pytorch import Lion
opt = Lion(model.parameters(), lr=1e-5, weight_decay=0.1) # AdamW lr / 10
```
```python
# 4. Cosine schedule with warmup
from torch.optim.lr_scheduler import LambdaLR
import math
def warmup_cosine(step, warmup, total):
if step < warmup:
return step / warmup
p = (step - warmup) / (total - warmup)
return 0.5 * (1 + math.cos(math.pi * p))
sched = LambdaLR(opt, lr_lambda=lambda s: warmup_cosine(s, 2000, 100_000))
```
```python
# 5. Gradient clipping
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
opt.step()
```
```python
# 6. Manual momentum (educational)
velocity = {p: torch.zeros_like(p) for p in model.parameters()}
mu, lr = 0.9, 0.01
for p in model.parameters():
velocity[p].mul_(mu).add_(p.grad)
p.data.add_(velocity[p], alpha=-lr)
```
```python
# 7. EMA on model weights (diffusion 표준)
class EMA:
def __init__(self, model, decay=0.999):
self.shadow = {n: p.clone().detach() for n, p in model.named_parameters()}
self.decay = decay
def update(self, model):
for n, p in model.named_parameters():
self.shadow[n].mul_(self.decay).add_(p.data, alpha=1-self.decay)
```
```python
# 8. Param-group: no weight decay on bias/LN
no_decay = ["bias", "LayerNorm.weight"]
groups = [
{"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], "weight_decay": 0.01},
{"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0},
]
opt = torch.optim.AdamW(groups, lr=2e-5)
```
```python
# 9. fused / 8-bit optimizer (메모리 절감)
import bitsandbytes as bnb
opt = bnb.optim.AdamW8bit(model.parameters(), lr=2e-5) # 메모리 75% 절감
```
```python
# 10. Sophia (2차 근사, 일부 lab)
# from sophia import SophiaG
# opt = SophiaG(model.parameters(), lr=3e-4, betas=(0.965, 0.99), rho=0.04)
```
## 매 결정 기준
| 상황 | 추천 옵티마이저 | 비고 |
|------|----------------|------|
| LLM pretrain | AdamW (β₂=0.95) | 표준 |
| LLM finetune | AdamW or Lion | Lion: lr=AdamW/10, wd=AdamW×3 |
| ViT / 큰 비전 모델 | AdamW or Lion | Lion 메모리 우위 |
| Diffusion | AdamW + EMA | EMA 필수 |
| Sparse embedding | SparseAdam | RecSys |
| 메모리 부족 | AdamW8bit (bitsandbytes) | 75% 절감 |
| RL policy gradient | Adam (낮은 β₂=0.9) | 노이즈 환경 |
| 단순 CNN/from scratch | SGD+momentum 0.9 | 잘 일반화 |
## 🔗 Graph
- 부모: [[Gradient Descent]]
- Adjacent: [[Gradient Clipping]], [[Weight Decay]]
## 🤖 LLM 활용
- "AdamW와 Lion의 학습 곡선을 비교해서 어느 게 stable한지 분석" — wandb log dump.
- LLM에 hyperparameter sweep 결과 요약 요청.
- "이 loss curve가 발산 중인데 lr / clipping / momentum 중 무엇을 조정?" — diagnostic.
## ❌ 안티패턴
- **Adam에 weight decay를 L2로 추가**: Adam은 v로 나누므로 의도와 다른 효과 → AdamW 사용.
- **lr 그대로 Lion 채택**: Lion은 sign-based, AdamW lr / 10 ~ / 5.
- **β₂=0.999 LLM에**: long sequence + 큰 gradient → β₂=0.95 권장.
- **Warmup 없이 Adam 시작**: 초기 v 추정 불안정 → divergence.
- **EMA 없이 diffusion**: 샘플 품질 크게 저하.
## 🧪 검증 / 중복
- 검증: PyTorch docs, Adam(2014), AdamW(2017), Lion(2023) 원논문.
- 중복: [[Adam Optimizer]] (specific) — 본 문서는 비교/선택 가이드.
## 🕓 Changelog
- 2026-05-10: 신규 작성. SGD momentum → Nesterov → Adam → AdamW → Lion + 2026 best practice.