Why Mixture of Experts Routes by Token Instead of by Sentence
Mixture of Experts (MoE) models inherently route at the token level rather than the sentence level, dictated by the Transformer architecture and the challenges of autoregressive generation. This article explores the structural bottlenecks of sentence-level routing, clarifies the mathematics behind routing combinations, and addresses common token-level routing challenges such as expert collapse and numerical stability. It also provides practical strategies for FP8 mixed precision, pseudo-code for top-k routing, and guidelines for evaluating routing designs.
1. Where Does Routing Occur?
Mixture of Experts (MoE) models typically replace the original single Feed-Forward Network (FFN) in a Transformer with multiple FFN submodules. After the attention layer outputs, each position in the sequence corresponds to a hidden vector, and the FFN computes independently per position. The router reads the hidden vector at each position, scores it, and selects the top-k highest-scoring experts. Therefore, routing naturally acts on the token position, which is determined by the model architecture rather than being an additional design choice.
If changed to sentence-level routing, one question must first be answered: where does a sentence begin and end? During training, sentence boundaries can be obtained through tokenization and punctuation annotations. However, during autoregressive generation, the model does not know whether the current sentence has ended before outputting the next token. Sentence-level decisions cannot be completed in advance within a step-by-step token decoding pipeline.
2. Three Structural Issues with Sentence-Level Routing
1. Representation Bottleneck
Sentence-level routing requires generating a single vector for the entire sentence, commonly done by averaging token vectors or extracting a vector from a special position. This step compresses information. A single sentence contains syntactic function words, numbers, proper nouns, punctuation, and code snippets, all of which have vastly different processing requirements. Assigning them all to a single expert forces that expert to simultaneously cover multiple patterns.
2. Load Imbalance and Parallelism Difficulties
Sentence lengths vary significantly, meaning the computational load per sentence also differs. Long sentences cause a particular expert to handle a massive amount of computation, while short sentences leave experts idle. Large-scale training relies on expert parallelism, placing different experts on different devices. Load imbalance forces some devices to wait for others to finish, degrading overall throughput. Token-level routing also has load issues, but since the computation per token is fixed, it is easier to control through capacity limits and auxiliary losses.
3. Inference Scheduling Conflicts
Inference services typically batch tokens from multiple requests together. Token-level routing allows all tokens in a batch to be grouped by expert at each decoding step and computed uniformly. Sentence-level routing, however, requires all tokens of the same sentence to execute on the same expert, which conflicts with step-by-step decoding scheduling and increases cache management complexity.
3. Correctly Understanding Combination Numbers
Original materials often mention that the number of expert combinations in token-level routing is extremely large, a point that requires accurate formulation. Suppose there are N routing experts, k are activated per token, and the sequence length is n. If each token selects experts independently, the number of possible routing schemes is:
C(N, k)^n
Using an example configuration of N=256, k=8, and n=2048:
- C(256, 8) is approximately 4.5×10^14
- Raised to the 2048th power, the order of magnitude is approximately 10^30000
The number of atoms in the universe is on the order of 10^80, differing by far more than a single order of magnitude. This comparison is mathematically valid, but it illustrates the “space of optional routing patterns” and does not directly prove that the model is more capable. A large number of routing schemes only indicates high degrees of freedom. Whether the model can utilize these degrees of freedom depends on the training data, the division of labor learned by the router, the differentiation between experts, and the load balancing strategy.
Applying the same calculation to sentence-level routing yields C(N, k)^m, where m is the number of sentences, which is much smaller than n. The difference between the two reflects a difference in routing degrees of freedom. Equating a difference in degrees of freedom directly with a performance difference lacks sufficient evidence. A more sound conclusion is: token-level routing allows the model to allocate computation at a finer granularity, which aligns with the characteristic that words in language have significantly different functions.
4. Common Issues and Countermeasures in Token-Level Routing
1. Expert Collapse
Expert collapse occurs when the router assigns most tokens to a few experts, leaving the rest with almost no training signal and rendering them effectively useless. Common countermeasures include:
- Auxiliary load balancing loss: Adding a term to the training objective that penalizes uneven distribution of tokens across experts.
- Dynamic bias adjustment: Maintaining a routing bias for each expert; reducing its score when overloaded and increasing it when underloaded.
- Capacity factor: Limiting the maximum number of tokens an expert can process in a batch; excess tokens are dropped or routed to the next best expert based on predefined rules.
- Routing noise: Adding slight random perturbations to routing logits during early training to help the router explore different experts.
2. Gradient and Numerical Stability
Top-k selection is a discrete operation and is inherently non-differentiable. In practice, the model only performs a weighted sum of the selected experts based on gating weights, and gradients are backpropagated to the router through these gating weights. Additionally, when routing logits are too large, the softmax function saturates, causing gradients to diminish. Common techniques include:
- Applying z-loss to routing logits to constrain their numerical range.
- Normalizing gating weights so that the sum of the weights for selected experts equals 1.
- Using gradient clipping to limit the magnitude of a single update step.
3. Inference Memory Footprint
Although MoE models only activate a subset of experts per token, all expert parameters must reside in GPU or system memory. Thus, the storage pressure brought by total parameters does not disappear due to sparse activation. Consider the following solutions:
- Expert parallelism: Splitting experts across multiple cards, with each card storing only a portion of the experts.
- Weight quantization: Using lower-bit representations for expert weights to reduce storage overhead.
- Grouped expert computation: Grouping tokens that need to be processed by the same expert to reduce scheduling overhead.
5. Boundaries of FP8 Mixed Precision
FP8 uses 1 byte per value, while BF16 uses 2 bytes, theoretically halving the storage for weights and activations. However, FP8 has a small dynamic range, and using it directly for all calculations easily leads to precision loss. In practice, the following principles are generally followed:
- Matrix multiplications use FP8 inputs, while accumulation uses higher precision (e.g., FP32).
- Numerically sensitive components like routing logits, softmax, and normalization maintain higher precision.
- Using block-wise scaling and other methods to adjust the numerical range of each tensor to the representable range of FP8.
Actual acceleration depends on the hardware’s support for low-precision computation and should be tested on the target platform. It is not advisable to directly apply numbers from others.
6. Pseudo-Code: Token-Level Top-k Routing
The following pseudo-code illustrates the basic routing process, omitting details like capacity limits and load balancing.
function moe_forward(x): # x shape: [batch, seq, d]logits = router(x) # shape: [batch, seq, N]probs = softmax(logits)topk_p, topk_idx = topk(probs, k)topk_p = topk_p / sum(topk_p) # Normalize weights for selected expertsout = zeros_like(x)for e in range(N):mask = (topk_idx == e) # Mark if each token selected expert eif no token selected:continueselected_x = x[mask] # Extract tokens assigned to expert ey = expert[e](selected_x)out[mask] += topk_p[mask] * yreturn out
Real implementations replace the loop with batched operations and introduce capacity limits and load statistics.
7. How to Evaluate Routing Design
When comparing MoE models with dense models, ensure consistent comparison conditions. Common benchmarks include:
- Equal activated computation per token (FLOPs)
- Equal training data and training steps
- Total parameters and activated parameters reported separately
In addition to final accuracy, the following metrics should be recorded:
- The proportion and variance of tokens received by each expert, to determine the degree of expert collapse
- Changes in router entropy during training
- Peak memory usage and throughput per unit time
- Performance on downstream tasks
If only total parameters or a single benchmark score is reported, it is difficult to determine whether the performance improvement comes from the routing design or merely an increase in parameters.
8. Practical Recommendations
- Default to token-level top-k routing unless the task has explicit sentence-level structural requirements and can solve the inference scheduling issues.
- Always enable load balancing constraints during training and monitor the receiving ratio of each expert.
- Prioritize expert parallelism and grouped expert computation during inference, addressing memory and throughput issues during the early design phase.
- Evaluate using equal activated computation as a baseline to avoid misinterpreting parameter scale differences as routing design advantages.
- When dealing with specific model configurations and performance data, rely on original technical reports and papers rather than second-hand summaries.
