Mixture of Experts Inference
Overview
Inference in Mixture of Experts (MoE) models differs from standard inference in dense models. In the MoE architecture, each token is processed not by all model parameters but by a small subset of experts selected by the router. This allows the use of models with a massive total number of parameters while maintaining moderate computational costs per token.
A key feature is the distinction between 'active parameters' and 'shared parameters.' For example, a model with 100 billion parameters may activate only 10 billion parameters per token.
Execution Details
During MoE model inference, the following steps are performed:
- The token passes through shared layers (attention, normalization).
- The router calculates weights for each expert.
- The top-k experts are activated (typically k=1 or k=2).
- The expert results are weighted and summed.
| Parameter | Dense Model | MoE Model |
|---|---|---|
| Parameters per token | All | Top-k experts |
| VRAM usage | Full | All experts loaded |
| Computation per token | Fixed | Dependent on k |
Important limitation: Although computations are reduced, all experts must be loaded into memory, requiring large amounts of VRAM or offloading.
Optimizations
To accelerate MoE inference, the following techniques are applied:
- Expert parallelism — distributing experts across multiple GPUs.
- Specialized kernels — for example, fused kernels for routing.
- Route caching — reusing router decisions for identical tokens.
# Example of simplified routing
import torch
def moe_forward(x, experts, router):
logits = router(x) # [batch, num_experts]
top_k = torch.topk(logits, k=2, dim=-1)
weights = torch.softmax(top_k.values, dim=-1)
out = torch.zeros_like(x)
for i, expert_idx in enumerate(top_k.indices):
out += weights[:, i:i+1] * experts[expert_idx](x)
return out