5.2 Routing Algorithms
A router allocates a finite expert-compute budget. Think of it as a dispatcher: sending every job to one worker leaves other workers idle, but enforcing equal counts does not necessarily minimize end-to-end latency. Token affinity, expert capacity, communication, and causal consistency all matter.
Token choice and load balancing
For token representation and router matrix , standard token-choice routing selects experts from . The selected weights may be renormalized before combining outputs. Collapse is a possible feedback loop—underused experts receive fewer updates—not an inevitable event after a fixed number of steps.
Noisy top- encourages exploration; a balancing penalty changes the training objective to . The coefficient trades modeling behavior against load. Evaluate validation loss and routing load jointly; experts do not necessarily specialize into clean human subjects such as mathematics and literature. [1]
Expert choice: fixed expert capacity
Expert Choice reverses the selection axis: each expert selects a fixed number of tokens from a routing group. A capacity factor is a multiplier; the resulting integer capacity is a token count. Equal counts do not guarantee equal wall-clock work. A token can receive several expert outputs or none. With , a token receiving no expert output still retains its residual representation. [2]
The important causal issue is competition across the routing group. If future tokens participate in the selection, changing a suffix can change how an earlier token is routed. A causal decoder therefore needs an explicitly causal grouping or routing design; merely retaining a KV cache does not solve this.
Educational selection example. This CPU tensor example returns indices and weights only. It omits expert computation, residual/scatter combination, causal grouping, distributed dispatch, and training. Capacity is clamped to the available token count.
import torch
import torch.nn as nn
import torch.nn.functional as F
class ExpertChoiceRouting(nn.Module):
def __init__(self, d_model, num_experts, capacity_factor):
super().__init__()
if num_experts < 1 or capacity_factor <= 0:
raise ValueError("positive expert count and capacity factor required")
self.num_experts = num_experts
self.capacity_factor = capacity_factor
# Router network
self.router = nn.Linear(d_model, num_experts, bias=False)
def forward(self, x):
"""
x shape: [batch_size, seq_len, d_model]
"""
batch_size, seq_len, d_model = x.shape
num_tokens = batch_size * seq_len
# Calculate fixed capacity per expert
# E.g., if capacity_factor=2.0, an expert processes twice the average token share
if num_tokens == 0:
raise ValueError("empty routing group")
expert_capacity = min(num_tokens, max(1, int(
(num_tokens / self.num_experts) * self.capacity_factor)))
x_flat = x.reshape(-1, d_model) # [num_tokens, d_model]
# 1. Compute affinity logits: [num_tokens, num_experts]
logits = self.router(x_flat)
# 2. Convert to routing weights (Softmax over experts)
weights = F.softmax(logits, dim=-1)
# 3. TRANSPOSE: Let experts view all tokens -> [num_experts, num_tokens]
weights_t = weights.t()
# 4. Expert Choice: Each expert picks its top `expert_capacity` tokens
# top_weights, top_indices shape: [num_experts, expert_capacity]
top_weights, top_indices = torch.topk(weights_t, expert_capacity, dim=-1)
# (In a full implementation, tokens would now be gathered using top_indices,
# processed by their respective experts, and scattered back)
return top_indices, top_weights
# Example usage
layer = ExpertChoiceRouting(d_model=1024, num_experts=8, capacity_factor=1.5)
dummy_input = torch.randn(2, 128, 1024) # 256 total tokens
indices, weights = layer(dummy_input)
# Each of the 8 experts exactly selected 48 tokens (256 / 8 * 1.5)
print(f"Indices shape: {indices.shape}") # Expected: [8, 48]
Soft MoE: differentiable slots
Soft MoE forms weighted token mixtures for expert input slots and combines expert outputs back into token representations. Sparse computation is performed over these combined slots. The original study evaluates vision models; the central obstacle to naive causal reuse is mixing across future positions, not a claim that soft assignments necessarily eliminate all compute savings. [3]
Dynamic selection bias in DeepSeek-V3
DeepSeek-V3 separates expert selection from output weighting. For token , expert vector , affinity , and load-controller bias , the simplified selection rule is:
The bias shifts selection after sigmoid; selected output weights use the unbiased affinities. The load controller decreases overloaded experts’ biases and increases underloaded ones. “Auxiliary-loss-free” names this load-control mechanism: the report still includes a small complementary sequence-wise balancing loss. Node limits, routed scaling and shared experts are omitted from this equation. [4]
This is one documented design, not proof that every model should remove auxiliary losses. A useful ablation keeps data, compute, expert count, and routing capacity fixed and measures both held-out quality and imbalance.
Explore allocation
The following authored assignments illustrate selection axes; they are not outputs of a trained router. Compare expert load and token coverage, then ask what dispatch traffic each allocation would create. Section 5.3 follows that traffic across devices.
Routing Paradigm Simulator
Authored assignments illustrate expert load and token coverage.
Tokens
Experts
Quizzes
Quiz 1: Why can a larger balancing coefficient hurt held-out quality even when expert loads become more uniform?
It changes the optimization objective. Better load balance can trade off against useful routing, but the direction and size of the quality change require a controlled evaluation.
Quiz 2: Does an unselected ECR token disappear, and what causal problem remains?
The residual path retains the token. Selection over a group containing future tokens can still make its representation depend on that future context; causal grouping or another routing design is required.
Quiz 3: Where does DeepSeek-V3 apply its load bias, and does it remove every auxiliary term?
Bias modifies sigmoid affinities used for selection. Output weights use unbiased affinities, and the reported design retains a small sequence-wise auxiliary balancing loss.
References
- Shazeer, N., et al. (2017). Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer. arXiv:1701.06538.
- Zhou, Y., et al. (2022). Mixture-of-Experts with Expert Choice Routing. arXiv:2202.09368.
- Puigcerver, J., et al. (2023). From Sparse to Soft Mixtures of Experts. arXiv:2308.00951.
- DeepSeek-AI. (2024). DeepSeek-V3 Technical Report. arXiv:2412.19437.