Mixture of Experts
MoE / 혼합 전문가 모델
여러 전문가(Expert) 네트워크를 선택적으로 활성화하는 효율적인 모델 아키텍처. GPT-4, Mixtral, Gemini 등 최신 대규모 LLM의 핵심 기술.
MoE / 혼합 전문가 모델
여러 전문가(Expert) 네트워크를 선택적으로 활성화하는 효율적인 모델 아키텍처. GPT-4, Mixtral, Gemini 등 최신 대규모 LLM의 핵심 기술.
Mixture of Experts(MoE)는 여러 개의 전문가(Expert) 서브네트워크 중 일부만 선택적으로 활성화하여 연산 효율을 극대화하는 신경망 아키텍처입니다. "분할 정복" 전략으로, 입력에 따라 가장 적합한 전문가들만 동원하여 연산량을 줄이면서도 모델 용량(capacity)은 유지합니다.
MoE 개념은 1991년 처음 제안되었지만, 2017년 Google의 "Outrageously Large Neural Networks" 논문에서 Transformer와 결합되며 주목받았습니다. 이후 GPT-4(추정), Mixtral 8x7B, Gemini 1.5, DBRX 등 최신 대규모 모델들이 MoE를 채택하면서 사실상 대형 LLM의 표준 아키텍처가 되었습니다.
MoE의 핵심 구성요소는 Expert 네트워크와 Gating Network(라우터)입니다. 각 토큰이 입력되면 Gating Network가 어떤 Expert를 활성화할지 결정합니다. 예를 들어 Mixtral 8x7B는 8개 Expert 중 2개만 활성화(Top-2 routing)하여, 총 45B 파라미터지만 추론 시 12B만 사용합니다.
실무에서 MoE는 대규모 모델의 비용 효율적 운영을 가능하게 합니다. 동일 성능의 Dense 모델 대비 2-4배 적은 연산으로 추론이 가능하며, 모델 확장 시 Expert만 추가하면 되어 스케일링이 용이합니다. 다만 전체 파라미터를 메모리에 로드해야 하므로 메모리 요구량은 줄지 않습니다.
# Mixture of Experts 개념 구현 (PyTorch)
import torch
import torch.nn as nn
import torch.nn.functional as F
class Expert(nn.Module):
"""개별 Expert 네트워크 (FFN)"""
def __init__(self, input_dim, hidden_dim, output_dim):
super().__init__()
self.fc1 = nn.Linear(input_dim, hidden_dim)
self.fc2 = nn.Linear(hidden_dim, output_dim)
def forward(self, x):
x = F.gelu(self.fc1(x))
return self.fc2(x)
class TopKGating(nn.Module):
"""Top-K Gating Network (라우터)"""
def __init__(self, input_dim, num_experts, top_k=2):
super().__init__()
self.gate = nn.Linear(input_dim, num_experts)
self.top_k = top_k
def forward(self, x):
# 각 Expert에 대한 점수 계산
logits = self.gate(x) # (batch, seq, num_experts)
# Top-K Expert 선택
top_k_logits, top_k_indices = torch.topk(logits, self.top_k, dim=-1)
top_k_gates = F.softmax(top_k_logits, dim=-1)
return top_k_gates, top_k_indices
class MixtureOfExperts(nn.Module):
"""Sparse MoE Layer"""
def __init__(self, input_dim, hidden_dim, output_dim,
num_experts=8, top_k=2):
super().__init__()
self.num_experts = num_experts
self.top_k = top_k
# Expert 네트워크들
self.experts = nn.ModuleList([
Expert(input_dim, hidden_dim, output_dim)
for _ in range(num_experts)
])
# Gating Network
self.gating = TopKGating(input_dim, num_experts, top_k)
def forward(self, x):
batch_size, seq_len, dim = x.shape
# Gating: 어떤 Expert를 활성화할지 결정
gates, indices = self.gating(x)
# gates: (batch, seq, top_k) - 각 Expert의 가중치
# indices: (batch, seq, top_k) - 선택된 Expert 인덱스
# Expert 출력 계산 및 가중 합산
output = torch.zeros_like(x)
for i in range(self.top_k):
expert_idx = indices[:, :, i] # (batch, seq)
expert_gate = gates[:, :, i:i+1] # (batch, seq, 1)
for e in range(self.num_experts):
mask = (expert_idx == e)
if mask.any():
expert_input = x[mask]
expert_output = self.experts[e](expert_input)
output[mask] += expert_gate[mask].squeeze(-1).unsqueeze(-1) * expert_output
return output
# 사용 예시: Mixtral 스타일 MoE
moe_layer = MixtureOfExperts(
input_dim=4096, # 임베딩 차원
hidden_dim=14336, # FFN 히든 차원
output_dim=4096,
num_experts=8, # 8개 Expert
top_k=2 # 토큰당 2개 활성화
)
# 입력: (batch=2, seq_len=10, dim=4096)
x = torch.randn(2, 10, 4096)
output = moe_layer(x)
print(f"입력 shape: {x.shape}")
print(f"출력 shape: {output.shape}")
print(f"총 Expert 수: 8, 활성화 Expert: 2")
print(f"총 파라미터 대비 활성 파라미터: 2/8 = 25%")
"모델 스케일업할 때 MoE 구조를 고려해봐요. 8x7B MoE면 총 파라미터는 45B지만 추론 FLOPs는 12B Dense 수준이에요. 같은 GPU 예산으로 훨씬 큰 모델 용량을 활용할 수 있습니다."
"MoE는 Gating Network가 입력 토큰마다 적합한 Expert를 선택하는 Sparse 아키텍처입니다. Dense 모델 대비 연산량을 크게 줄이면서 모델 용량은 유지하죠. 다만 전체 파라미터를 메모리에 로드해야 해서 메모리는 줄지 않습니다. Load Balancing Loss로 Expert 활용 균형을 맞추는 게 학습의 핵심입니다."
"GPT-4가 MoE라는 루머가 있었는데, Mistral Large 3도 MoE고 675B 중 41B만 활성화해요. MoE의 어려운 점은 Expert Collapse와 Load Imbalance인데, Auxiliary Loss나 Expert Choice 라우팅으로 해결합니다."
MoE는 연산량(FLOPs)을 줄이지 메모리를 줄이지 않습니다. 모든 Expert 파라미터를 메모리에 로드해야 하므로 Mixtral 8x7B는 45B 전체 메모리가 필요합니다.
일부 Expert만 과도하게 사용되면 학습이 불안정해지고 성능이 저하됩니다. Load Balancing Loss를 반드시 추가하세요.
MoE 모델은 Expert Parallelism으로 여러 GPU에 Expert를 분산 배치하면 효율적입니다. vLLM, TensorRT-LLM 등 MoE 최적화를 지원하는 서빙 프레임워크를 사용하세요.