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:
+134
@@ -0,0 +1,134 @@
|
||||
---
|
||||
id: wiki-2026-0508-mixture-of-experts-moe-sparse-ar
|
||||
title: "Mixture of Experts (MoE) & Sparse Architectures"
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [MoE, Mixture of Experts, Sparse Transformer, Switch Transformer, Sparse MoE]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.93
|
||||
verification_status: applied
|
||||
tags: [llm, transformer, moe, sparse, mixtral, deepseek, switch-transformer, expert-parallelism]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack: { language: python, framework: pytorch|megablocks|deepspeed }
|
||||
---
|
||||
|
||||
# Mixture of Experts (MoE) & Sparse Architectures
|
||||
|
||||
> 한 줄: 매 토큰마다 N개 expert 중 top-k(보통 1-2)만 활성화 — 총 파라미터는 키우면서 추론 FLOPs는 dense 대비 작게. Mixtral·DeepSeek-V3·GPT-4·Gemini가 채택.
|
||||
|
||||
## 핵심
|
||||
- **Sparse activation**: 8명의 expert × 2 active = 25% 활성. 총 파라미터 8× FFN, 연산은 2× FFN.
|
||||
- **Gating(router)**: token → softmax(W_g · x) → top-k expert. noisy top-k (Shazeer), expert choice (Google), DeepSeek-V3 fine-grained + shared expert.
|
||||
- **Load balancing**: aux loss (entropy/CV²) 또는 expert capacity factor — 한 expert에 쏠림 방지.
|
||||
- **모델 사례**: Mixtral 8×7B (47B 총, 13B active), Mixtral 8×22B, DeepSeek-V3 671B/37B active, Qwen2.5-MoE, Switch-T (1 expert), GShard.
|
||||
- **인프라**: expert parallelism (EP), all-to-all 통신, MegaBlocks (block-sparse GEMM), DeepSpeed-MoE, Tutel.
|
||||
|
||||
## 결정 기준
|
||||
| 상황 | MoE 적용? | 비고 |
|
||||
|---|---|---|
|
||||
| 추론 비용↓, 품질↑ | ✅ | 같은 active로 dense보다 성능↑ |
|
||||
| 단일 GPU 메모리 빠듯 | ❌ | 총 파라미터 그대로 메모리 차지 |
|
||||
| Edge / 모바일 | ❌ | dense 작은 모델·distillation |
|
||||
| 학습 안정성 우선 | ⚠️ | dense보다 튜닝 까다로움 |
|
||||
| 멀티-도메인 (코드+자연어) | ✅ | expert specialization 효과 |
|
||||
| FT만 할 거면 | dense LoRA | MoE FT는 까다로움 |
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Top-k gating (PyTorch sketch)
|
||||
```python
|
||||
import torch, torch.nn as nn, torch.nn.functional as F
|
||||
|
||||
class MoELayer(nn.Module):
|
||||
def __init__(self, d, n_experts=8, k=2, ffn_hidden=4*1024):
|
||||
super().__init__()
|
||||
self.k = k
|
||||
self.gate = nn.Linear(d, n_experts, bias=False)
|
||||
self.experts = nn.ModuleList([
|
||||
nn.Sequential(nn.Linear(d, ffn_hidden), nn.SiLU(), nn.Linear(ffn_hidden, d))
|
||||
for _ in range(n_experts)])
|
||||
|
||||
def forward(self, x): # x: (B, T, D)
|
||||
logits = self.gate(x) # (B, T, E)
|
||||
topk_v, topk_i = logits.topk(self.k, dim=-1)
|
||||
weights = F.softmax(topk_v, dim=-1) # (B, T, k)
|
||||
out = torch.zeros_like(x)
|
||||
for slot in range(self.k):
|
||||
idx = topk_i[..., slot]
|
||||
w = weights[..., slot].unsqueeze(-1)
|
||||
for e in range(len(self.experts)):
|
||||
mask = (idx == e)
|
||||
if mask.any():
|
||||
out[mask] += w[mask] * self.experts[e](x[mask])
|
||||
return out
|
||||
```
|
||||
|
||||
### Load balancing aux loss
|
||||
```python
|
||||
def load_balance_loss(gate_logits, topk_idx, n_experts):
|
||||
# f_i = fraction of tokens routed to expert i
|
||||
# P_i = mean gating prob for expert i
|
||||
probs = gate_logits.softmax(-1)
|
||||
P = probs.mean(dim=(0,1)) # (E,)
|
||||
one_hot = F.one_hot(topk_idx, n_experts).float()
|
||||
f = one_hot.sum(dim=(0,1,2)) / one_hot.sum() # (E,)
|
||||
return n_experts * (f * P).sum() # Switch-T loss
|
||||
```
|
||||
|
||||
### Mixtral 추론 (Hugging Face)
|
||||
```python
|
||||
from transformers import AutoModelForCausalLM, AutoTokenizer
|
||||
m = AutoModelForCausalLM.from_pretrained(
|
||||
"mistralai/Mixtral-8x7B-Instruct-v0.1",
|
||||
torch_dtype="auto", device_map="auto", load_in_4bit=True)
|
||||
tok = AutoTokenizer.from_pretrained("mistralai/Mixtral-8x7B-Instruct-v0.1")
|
||||
out = m.generate(**tok("Hi", return_tensors="pt").to(m.device), max_new_tokens=200)
|
||||
```
|
||||
|
||||
### vLLM으로 MoE 서빙
|
||||
```bash
|
||||
vllm serve mistralai/Mixtral-8x7B-Instruct-v0.1 \
|
||||
--tensor-parallel-size 4 --enable-expert-parallel \
|
||||
--quantization awq --gpu-memory-utilization 0.9
|
||||
```
|
||||
|
||||
### Expert capacity (overflow drop)
|
||||
```python
|
||||
capacity = int(capacity_factor * tokens_per_batch / n_experts)
|
||||
# 각 expert 처리량 ≤ capacity. 초과 토큰 drop or fallback.
|
||||
```
|
||||
|
||||
### DeepSeek-V3 스타일 shared + routed
|
||||
```python
|
||||
out = shared_expert(x) + sum(top_k_routed(x, experts, gate, k=8))
|
||||
# 공통 지식은 shared, specialization은 routed
|
||||
```
|
||||
|
||||
## 🔗 Graph
|
||||
- 상위: [[Transformer]] · [[Sparse-Models]]
|
||||
- 관련: [[Switch-Transformer]] · [[LLM_Optimization_and_Deployment_Strategies|vLLM]]
|
||||
- 비교: [[LLM_Optimization_and_Deployment_Strategies|Quantization]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
- 모델 선택 의사결정: "8B dense vs 8×3B MoE 중 어느 게 우리 throughput·메모리에 맞나" — 표 기반 비교.
|
||||
- expert 라벨 분석: 각 expert가 어떤 토큰에 자주 활성화되는지 LLM에 줘 해석.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **load balance loss 생략** — 1-2 expert 독식 → 나머지 유휴, 성능 저하.
|
||||
- **메모리 산정 시 active만 계산** — 총 파라미터 다 메모리 적재(추론 시), VRAM OOM.
|
||||
- **batch size 1 추론** — all-to-all 통신 오버헤드 비효율. batched serving (vLLM) 권장.
|
||||
- **MoE에 표준 LoRA 그대로** — gating·expert 둘 다 고려 필요. MoE 전용 PEFT (e.g., MoLE).
|
||||
- **expert 너무 잘게 (32+)** — 통신 비용 폭증. Mixtral 8 / DeepSeek 256 fine-grained는 인프라 받쳐줘야.
|
||||
- **Switch (k=1) 학습 불안정 무시** — z-loss·router noise·warmup 필수.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- 중복: [[Mixtral]], [[DeepSeek-V3]], [[Switch-Transformer]] 별도 — 본 문서는 개념 허브.
|
||||
- 검증: 라우팅 분포 (expert별 token %) plot · MMLU/GSM8K 등 dense 동급 active 모델과 비교.
|
||||
|
||||
## 🕓 Changelog
|
||||
- 2026-05-08 | Phase 1 — 자동 시드.
|
||||
- 2026-05-10 | Manual cleanup — top-k gating·load balance·Mixtral·DeepSeek-V3·vLLM 패턴, 결정 기준·안티패턴 정리.
|
||||
Reference in New Issue
Block a user