--- 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 패턴, 결정 기준·안티패턴 정리.