🤖 AI/ML

MoE

Mixture of Experts

An architecture that selectively activates multiple expert networks. A key technology for building efficient large models, applied in GPT-4, Mixtral, Gemini, and others.

📖 Detailed Explanation

MoE (Mixture of Experts) is a neural network architecture that maximizes computational efficiency by selectively activating only some of its multiple "expert" subnetworks. Although the total number of parameters is large, only a portion is used during actual inference, so it is also called a "Sparse" model.

The core of MoE is the Gating Network (router). When each input token arrives, the router decides which Experts to activate. For example, Mixtral 8x7B selects the Top-2 of 8 Experts and performs inference with only 12B of its 45B total parameters. This allows it to achieve similar performance with 2-4 times fewer FLOPs than a Dense model.

The advantage of MoE lies in scaling model capacity. By increasing the number of Experts, the overall knowledge capacity can be expanded while the inference cost is kept constant. Google's Switch Transformer achieved 1.6T parameters, and Mistral Large 3 activates only 41B out of 675B.

In practice, MoE is essential for cost efficiency in large-scale LLM services. However, because all parameters must be loaded into memory, memory requirements are not reduced, and load balancing among Experts is a key challenge in training. Using MoE-optimized serving frameworks such as vLLM and TensorRT-LLM enables efficient deployment.

ModelTotal ParametersActive ParametersNumber of Experts
Mixtral 8x7B45B12B8 (Top-2)
Mixtral 8x22B141B39B8 (Top-2)
Mistral Large 3675B41BGranular MoE
Switch Transformer1.6T~12B2048 (Top-1)

💻 Code Example

# MoE 모델 사용 예제 (Mixtral)
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

# Mixtral 8x7B Instruct 로드 (약 90GB VRAM 필요)
model_id = "mistralai/Mixtral-8x7B-Instruct-v0.1"

tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype=torch.bfloat16,
    device_map="auto",  # 여러 GPU에 자동 분산
    load_in_4bit=True   # 양자화로 메모리 절약 (약 25GB)
)

# 추론
messages = [{"role": "user", "content": "MoE 아키텍처의 장단점을 설명해주세요."}]
inputs = tokenizer.apply_chat_template(messages, return_tensors="pt").to(model.device)

outputs = model.generate(
    inputs,
    max_new_tokens=512,
    do_sample=True,
    temperature=0.7,
    top_p=0.9
)

response = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(response)

# ===== MoE 모델 서빙 (vLLM) =====
# pip install vllm
from vllm import LLM, SamplingParams

# vLLM은 MoE 전용 최적화 지원
llm = LLM(
    model="mistralai/Mixtral-8x7B-Instruct-v0.1",
    tensor_parallel_size=2,  # 2 GPU 병렬
    dtype="bfloat16"
)

sampling_params = SamplingParams(temperature=0.7, max_tokens=512)

prompts = ["[INST] Python에서 async/await의 작동 원리는? [/INST]"]
outputs = llm.generate(prompts, sampling_params)

for output in outputs:
    print(output.outputs[0].text)

# ===== MoE 레이어 간단 구현 =====
import torch.nn as nn
import torch.nn.functional as F

class SimpleMoE(nn.Module):
    def __init__(self, dim, num_experts=8, top_k=2):
        super().__init__()
        self.num_experts = num_experts
        self.top_k = top_k

        # Expert FFN 네트워크들
        self.experts = nn.ModuleList([
            nn.Sequential(
                nn.Linear(dim, dim * 4),
                nn.GELU(),
                nn.Linear(dim * 4, dim)
            ) for _ in range(num_experts)
        ])

        # Gating Network (라우터)
        self.gate = nn.Linear(dim, num_experts)

    def forward(self, x):
        # 라우터: 각 토큰에 대해 Expert 선택
        gate_logits = self.gate(x)  # (batch, seq, num_experts)

        # Top-K Expert 선택
        weights, selected = torch.topk(gate_logits, self.top_k, dim=-1)
        weights = F.softmax(weights, dim=-1)

        # 선택된 Expert들의 출력 가중 합산
        output = torch.zeros_like(x)
        for i, expert in enumerate(self.experts):
            mask = (selected == i).any(dim=-1)
            if mask.any():
                expert_out = expert(x[mask])
                # 해당 Expert의 가중치 적용
                for k in range(self.top_k):
                    k_mask = (selected[..., k] == i) & mask.unsqueeze(-1)
                    if k_mask.any():
                        output[k_mask[..., 0]] += weights[..., k:k+1][k_mask[..., 0]] * expert_out

        return output

# 사용
moe = SimpleMoE(dim=512, num_experts=8, top_k=2)
x = torch.randn(2, 10, 512)  # (batch=2, seq=10, dim=512)
out = moe(x)
print(f"MoE 출력: {out.shape}")  # (2, 10, 512)

🗣️ Say It Like This in Practice

💬 In a Model Selection Meeting
"Let's consider an MoE model for cost efficiency. Mixtral 8x7B has 45B parameters, but its inference FLOPs are similar to those of a 12B Dense model. We can use a larger model capacity with the same GPU budget."
💬 In an Interview
"MoE is a Sparse architecture that activates only some Experts out of the total parameters. The Gating Network selects the appropriate Experts for each input. The amount of computation is reduced, but memory is not, because all parameters must be loaded. During training, it is important to balance Expert utilization with a Load Balancing Loss."
💬 In a Technical Discussion
"There is a Dense vs MoE trade-off. Dense is simple to implement and memory-efficient but has scaling limits, while MoE is computationally efficient but requires Expert Parallelism distributed processing. For large-scale services, MoE is advantageous."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Expecting Memory Savings

MoE reduces computation (FLOPs), not memory. An 8x7B MoE still has to load all 45B into memory.

❌
Trying a Single GPU

Large MoE models do not fit on a single GPU. Tensor Parallelism or quantization is essential.

✅
Correct Approach: Optimized Serving

Use frameworks that support MoE optimization, such as vLLM and TensorRT-LLM. Distributing Experts across multiple GPUs with Expert Parallelism is efficient. 4-bit quantization can save memory.

🔗 Related Terms

📚 Learn More