MoE and Agent Hierarchical Routing: When to Choose Efficiency Models
As LLMs move into everyday scenarios like customer service, office work, and data processing, enterprises care more about cost per thousand tokens, latency, and task completion rate than parameter counts and benchmark scores. This article explains what efficiency models are, how Mixture of Experts (MoE) sparse routing works, and provides a runnable PyTorch implementation of an MoE layer, covering load balancing, inference overhead, expert capacity, and comparisons with dense models to help you decide when efficiency models are the right choice.
Why Efficiency Models Matter
Over the past two years, marketing around large models focused mostly on parameter counts and leaderboard scores. Once models entered everyday scenarios such as customer service, office work, and data processing, enterprises started caring about three numbers instead: cost per thousand tokens, response latency, and per-task completion rate. Latency is best split into P50 and P95: the former reflects the typical experience, while the latter captures the tail of slow requests. Per-task cost can be calculated as total cost divided by the number of successfully completed tasks. Looking only at the price of a single call makes it easy to overlook the extra overhead caused by retries after failures.
Efficiency models are models that make deliberate trade-offs between capability and cost. Early approaches reduced the number of network layers or compressed hidden dimensions, which significantly degraded performance on complex reasoning and long-chain tasks. Newer solutions start from the architecture itself, and Mixture of Experts (MoE) is a representative example.
How MoE Sparse Routing Works
MoE splits the feed-forward network into multiple expert sub-networks. When each token enters a layer, a gating network scores every expert and selects only the top-K experts with the highest scores to participate in computation; the remaining experts do not run. The model’s total parameter count can be very large, while each token actually activates only a fraction of them.
Take Mixtral 8x7B as an example. The data comes from the paper “Mixtral of Experts” published by Mistral AI (arXiv:2401.04088, 2024). The paper reports that the model has about 46.7 billion total parameters, with about 12.9 billion activated per token, selecting 2 out of 8 experts per layer. Total parameters count all weights, including unselected experts; activated parameters count only the weights that actually participate in the forward computation of a single token. The two figures use different accounting methods and cannot simply be subtracted to estimate memory usage.
There is an easily overlooked detail with top-k weights. The code below first takes the top-K expert logits and then applies softmax. This is equivalent to applying softmax over all experts first and then taking the top-K and renormalizing, because the normalization constant cancels out in both formulations.
Runnable Code and Production Gaps
The following code shows a runnable version of an MoE layer. It flattens the tokens in a batch, groups them by expert, and routes only the selected tokens through their corresponding experts.
import torchimport torch.nn as nnimport torch.nn.functional as Fclass MoELayer(nn.Module):def __init__(self, d_model, d_ff, num_experts, top_k):super().__init__()assert 1 <= top_k <= num_expertsself.num_experts = num_expertsself.top_k = top_kself.gate = nn.Linear(d_model, num_experts, bias=False)self.experts = nn.ModuleList([nn.Sequential(nn.Linear(d_model, d_ff), nn.GELU(), nn.Linear(d_ff, d_model))for _ in range(num_experts)])def forward(self, x):# x: [batch, seq_len, d_model]B, T, D = x.shapex_flat = x.reshape(-1, D) # [N, D], N = B * Tgate_logits = self.gate(x_flat) # [N, E]topk_logits, topk_idx = torch.topk(gate_logits, self.top_k, dim=-1) # [N, K]topk_weights = F.softmax(topk_logits, dim=-1) # [N, K]out = torch.zeros_like(x_flat)for e in range(self.num_experts):# Find the token positions routed to expert e and their slots in top-ktoken_pos, slot = torch.where(topk_idx == e)if token_pos.numel() == 0:continueexpert_out = self.experts[e](x_flat[token_pos]) # [M, D]w = topk_weights[token_pos, slot].unsqueeze(-1) # [M, 1]out.index_add_(0, token_pos, expert_out * w)return out.view(B, T, D)# Example: batch=2, seq_len=5, d_model=16, 8 experts, top-2 per tokenlayer = MoELayer(d_model=16, d_ff=64, num_experts=8, top_k=2)x = torch.randn(2, 5, 16)print(layer(x).shape) # torch.Size([2, 5, 16])
The code runs on PyTorch 2.x. The input shape must be [batch, seq_len, d_model], and top_k must not exceed num_experts. This code is for teaching purposes only: it has no expert capacity limits, no load balancing loss, and no expert parallelism. Used directly in production, you would run into load imbalance, memory peaks, and communication bottlenecks.
Load Balancing and Inference Overhead
Sparse routing has two common problems. The first is load imbalance. A small number of experts receive most tokens while the rest sit idle for long periods. Training typically adds an auxiliary loss to encourage tokens to spread across experts. The weight of this loss needs to be tuned per training recipe; common values are around 0.01, but refer to the defaults of the framework or paper you are using.
The second is communication overhead. When experts are distributed across multiple GPUs, tokens need to be sent and received across devices. If expert parallelism spans nodes, network bandwidth can become the bottleneck. As a result, MoE throughput does not scale up proportionally as activated parameters decrease.
Production environments also need expert capacity settings. The number of tokens each expert can receive is usually calculated as a capacity factor multiplied by the average load, with the capacity factor typically ranging from 1.0 to 1.5. Tokens that exceed capacity can be dropped or passed through only the residual connection. The drop rate needs continuous monitoring; a high rate usually indicates a problem with load balancing or capacity configuration.
MoE vs. Dense Models
| Dimension | Dense Model | MoE Model |
|---|---|---|
| Memory (inference, FP16) | Roughly 2 bytes times parameter count; about 26GB for 13B |
