skip to content
← Scientific Spaces English

MoE Journey, Part 8: Enforcing Sequence-Level Balance

So far, seven articles have been written in the "MoE Journey" series, five of which center on MoE routing and load balancing. In terms of routing form, they can be divided into two categories: static computation and dynamic computation; in terms of methods for achieving load balancing, they can also be divided into two categories: Aux-Loss and Loss-Free, where Loss-Free can be further divided into the SignSGD scheme proposed by DeepSeek and the QB scheme I proposed.

There is also a detail: the Loss-Free schemes we discussed earlier all achieve balance in the sense of a global batch, whereas in many cases we add a sequence-level Aux Loss to avoid extreme sequence-level imbalance. If we believe that every Aux-Loss scheme has a corresponding Loss-Free counterpart, how should sequence-level Loss-Free balance be implemented? This is precisely the topic to be explored in this post.

Recap of Previous Posts #

First, let us review our previous explorations of load balancing. In MoE Journey, Part 2: Scarcity Is Not the Worry; Imbalance Is, we discussed the load balancing problem of MoE for the first time, proposing the Aux Loss solution—that is, adding an auxiliary loss function to promote balance. The drawback of Aux Loss is that it involves an additional weight coefficient to tune, while its advantage is that the granularity of balancing can be freely adjusted, allowing balance at the sequence, group, or global level (of course, the more global it is, the greater the communication overhead).

Starting from MoE Journey, Part 3: A Different Approach to Allocation, we discussed load balancing strategies in the Loss-Free form, which adjust the degree of balance by introducing an extra bias term and hand-crafting a SignSGD-style rule to update it. This paradigm is more flexible than Aux Loss and is infra-friendly. In MoE Journey, Part 4: Invest More Where It's Hard, we extended it to MoEs with dynamic numbers of activated experts.

And in MoE Journey, Part 6: Optimal Allocation Promotes Balance, we looked at the load balancing problem from the perspective of optimal allocation; by alternately solving the dual objective, we obtained a new load balancing strategy, Quantile Balancing (QB). Strictly in terms of results, it can be viewed as a new, more accurate solving method for the bias term in Loss-Free schemes. Next, in MoE Journey, Part 7: A Minimalist Solution to Dynamic Activation, we likewise extended QB to dynamic MoE.

Here lies a detail: the bias term introduced by Loss-Free is globally shared, so currently all Loss-Free schemes, without exception, can only achieve global load balancing. As mentioned earlier, if needed, Aux Loss can also be used to promote sequence-level balance; does Loss-Free also have a corresponding sequence-level balancing scheme?

Local Centering #

Coincidentally, @ChangJonathanC in the article 《Causal Routing Bias for Aux-Loss-Free MoE Training》, also explored related ideas. The author proposed two approaches. Let's briefly examine them first, which will also make it easier to compare with our own approach later. Let denote the router output of a length- sequence, and denote the router output of the -th token. The first idea proposed in the article is to subtract from its exponential moving average (EMA):

Then, use to decide which experts to activate (for example, choosing Top- , or combined with techniques like QB). The intuition behind this approach is quite straightforward: intuitively, if using to make decisions causes Expert to be activated many times, it means its score is on average on the larger side. Therefore, to achieve balance, it should be penalized accordingly, with the penalty amount being precisely the local average estimated by the EMA.

In this way, in the new , each expert's score locally has approximately zero mean, preventing any single expert from being overly "prominent" and thereby achieving sequence-level balance. However, this is merely an empirical heuristic with no theoretical guarantee that it will necessarily lead to better balance. I conducted some simple tests, and in extremely imbalanced scenarios such as the first MoE layer, it did not provide any substantive help. Perhaps the author also realized this limitation, which is why he proposed a second approach.

Test-Time Training #

The idea behind the second scheme is actually quite intuitive as well. In MoE Journey, Part 3: A Different Approach to Allocation, didn't we introduce a bias term to control global balance? This bias term is updated using SignSGD. That being the case, we can mimic TTT's idea of "test-time training", activating experts token by token along the sequence dimension and updating this bias term based on the distribution of already activated experts.

Taking and a Top- MoE as an example, the original Loss-Free scheme introduces a global bias vector , and then changes the activation mechanism to selecting from each the Top-. The idea here, however, is to assign each a , and change the activation mechanism to selecting from the Top-. 's update rule can be sign gradient ascent:

where is the distribution of activated experts up to the -th token. In the author's final version, some adjustments were made: the sign function was removed, and was changed to (the activation distribution of the -th token), to better achieve local balance

This idea can preserve sequence causality while also guaranteeing almost absolute balance at the sequence level, but because every step requires selecting the Top- and using the resulting to update the bias term, this essentially introduces a non-linear RNN. Non-linear RNNs cannot be parallelized, so it is foreseeable that long sequences will become a bottleneck. Of course, we could also consider updating chunk by chunk (mini-batch TTT) to improve efficiency, but that feels slightly inelegant.

The Optimal Solution #

Next, the approach proposed in this post is called "Moving Quantile Balancing (MQB)". As the name implies, it evolved from "Quantile Balancing (QB)". To this end, let us first briefly review QB.

In the order I wrote them, first came MoE Journey, Part 6: Optimal Allocation Promotes Balance, followed by MoE Journey, Part 7: A Minimalist Solution to Dynamic Activation, but in fact the latter is much simpler both conceptually and methodologically, so we will start with the latter. As before, given , we introduce a bias term . In the static version of MoE, each token selects, based on , the top experts. Dynamic activation instead activates every expert for which holds, so the number of activated experts varies.

To simultaneously ensure load balancing and control the average number of activations to be , an appropriate needs to be chosen. Wonderfully enough, in this setting, the optimal solution for can be expressed exactly:

That is to say, sorting in descending order along the sequence dimension (currently ) and taking the -th largest element yields the optimal solution for , which also corresponds to the " quantile".

In fact, this is merely another representation of Expert Choice. As we know, the problem with Expert Choice is that it breaks causality (it is non-causal), which can also be seen from the fact that it computes along the sequence dimension. If we are in an encoder scenario, such a non-causal scheme is naturally not an issue, but for unidirectional autoregressive models, it is unacceptable.

Moving Quantile #

Earlier, @ChangJonathanC 's "test-time training" scheme gave me some inspiration. We can compute the bias term token by token based on QB along the sequence dimension. Since QB can directly express the optimal solution for the bias term based on without needing to know expert activation states, this brings some possibilities for parallelism.

My initial idea was , that is, calculating bias terms over the token scores for all positions up to the current one. In this way, every position has its own bias term, and the optimality of QB ensures balance up to the current position. Since it requires progressively computing quantiles along the sequence dimension, we might call this operation "Cumulative Quantile", and the corresponding scheme "Cumulative Quantile Balancing (CQB)".

CQB is viable in principle, but because quantiles cannot be updated incrementally, CQB has to read the entire data history to perform quantile computation at every step. Its computational complexity increases linearly, making the total complexity quadratic. To alleviate this problem, and also to better reflect local balance, my idea was to set a window , such that each token only seeks the optimal bias term within a window not exceeding , namely:

In this way, the operation turns from "Cumulative Quantile" into "Moving Quantile", and the corresponding scheme becomes the prototype of "Moving Quantile Balancing (MQB)". It is very similar to SWA (Sliding Window Attention), has linear complexity, and theoretically can also be parallelized. The reason it is still an "early prototype" is again that quantiles cannot be updated incrementally, resulting in a single-step complexity that remains relatively high, so we still need to find a way to improve it.

Binning Estimation #

All the obstacles mentioned in the previous section are essentially constrained by the fact that "quantiles are nonlinear and cannot be updated incrementally." Is there any possibility that we could manage to linearize it, even if only approximately? Fortunately, here we really can!

Schematic diagram of quantile estimation via histogram approximation

Schematic diagram of quantile estimation via histogram approximation

A key fact is that: As long as the distribution of a variable is known, quantiles can be obtained via cumulative probability, and distributions can be updated incrementally!Therefore, the key here is to convert the estimation of quantiles into the estimation of distributions. For this, we use binned counting, also known as "histogram approximation". First, assume that router scores all lie in , which can be guaranteed by adding activation functions such as Sigmoid; next, divide equally into bins, and discretize each value of into an integer, which is then converted into the corresponding one-hot vector.

In this way, we obtain an 0/1 array. If we average it along the sequence dimension , we obtain the score distribution for each expert (represented as a -dimensional vector), from which we can then find each expert's quantile. However, to guarantee causality, we cannot average directly over the entire sequence and can only perform an operation like a "Cumulative Average". To avoid the trouble brought by the rigid boundaries of a "Moving Quantile" and to make the entire process "smoother", here we choose to compute an EMA.

That is, after binning and one-hot encoding it, we compute an EMA along the sequence dimension. Each token gets a local distribution, from which we can find the corresponding quantile. This is the key variable of MQB, . Since the EMA operation is linear and parallelizable, we have achieved sequence-level balance in a relatively efficient, loss-free manner. This is the final version of MQB.

The General Case #

So far, our discussion has been based on the dynamic-activation MoE variant, which activates every expert for which holds, so the number of activated experts varies. From MoE Journey, Part 6: Optimal Allocation Promotes Balance, we know that for Top- MoE, its has no simple analytical solution and requires alternating iterations.

How, then, should Top- MoE achieve sequence-level load balancing in a loss-free manner? In fact, MQB's ability to achieve sequence-level balance under dynamic activation shows that it has already "flattened" the router's local anomalous peaks. At this point, if we take and select its Top-, it might be unbalanced, but this imbalance is at most at the global level; we then only need to supplement it with a step of globally balanced QB to restore balance.

That is, for Top- MoE, our scheme for enforcing sequence-level balance is MQB+QB: on top of the sequence, we perform another QB step (using SignSGD also works, of course), which achieves sequence-level load balancing. Note, however, that perfect sequence-level load balancing often visibly hurts performance. In general, global balance is sufficient, while sequence-level balance is only meant to prevent extreme cases, so the degree of enforcement should not be too heavy.

To reduce the impact on the primary task, auxiliary loss schemes can lower the loss coefficient, whereas with MQB, we can consider taking a weighted average of the scores before and after:

That is, by introducing to weaken the degree of sequence balance, we then overlay QB on top of it to guarantee global balance (since cannot guarantee balance, at this point, whether for the dynamic variant or the Top- variant, QB needs to be added).

Other Details #

After binning, the core operation of MQB also becomes EMA. So after circling back, we return to EMA, in a form similar to @ChangJonathanC 's first proposed scheme, except that the target of the EMA is different. @ChangJonathanC 's scheme directly applies EMA to the -sized raw scores, whereas MQB expands them to size before applying EMA.

This change is somewhat like linear attention expanding capacity via outer products to memorize more information, and the optimality of QB also guarantees that it achieves sequence-level balance, rather than remaining an empirical heuristic. Another similarity to linear attention is that EMA is essentially an RNN, so during inference an additional -sized state vector must be stored. In practice, we find that already achieves good results, so a state of this size should be acceptable.

It should also be pointed out that, whether with QB or MQB, they are only used for expert activation decisions. The gating function that is ultimately multiplied with the experts is still computed based on the original router scores before subtracting the bias terms. This is a common feature of all loss-free schemes, ensuring that the balancing intervention terms do not directly alter the MoE formulation, in order to minimize the impact on the main model.

Finally, regarding the binning method, my current experiments apply a Sigmoid activation followed by uniform discretization into bins. As for how to bin more finely, there may still be room for further exploration; I leave this to interested readers.

Experimental Results #

For MQB, I ran some simple experiments on a MoE model configuration with about 3B total parameters and top-4 out of 128 routing. The exponential moving average coefficient for MQB is 0.99, the default number of bins is 100, and MaxVio is used as the load balancing metric. Since the first MoE layer is the most imbalanced, below we only demonstrate the results on the first layer.

First is in its full MQB form:

Comparison of results between MQB (λ=1), QB, and SignSGD

Comparison of results between MQB (λ=1), QB, and SignSGD

As can be seen, can achieve nearly perfect load balancing, at the cost of a 0.06 increase in loss. This is quite a noticeable drop, indicating that excessive sequence balance hurts performance. However, if we adjust to around 0.3, there is virtually no degradation in loss, while load balancing still improves, as shown below:

Load balancing under different λ

Load balancing under different λ

Further Thoughts #

From the experiments above, we can further confirm that perfect sequence-level balance () degrades performance rather severely; if we set , we can roughly ensure lossless performance while improving the balance of each layer.

Overall, this post only answers "how to achieve sequence-level load balancing in a loss-free way." However, as to whether sequence-level load balancing is necessary, why it is needed, and to what extent it is needed, we cannot provide a definitive answer. A preliminary understanding is that extreme sequence-level imbalance might impair the sequence's own performance (collapsing into a smaller model), so we want to encourage a certain degree of sequence-level balance.

Besides MQB, there are actually other schemes that can also achieve sequence-level balance in a loss-free manner. For example, in "Where Does DeepSeek V4's tid2eid Come From?", we introduced Hash Routing, which can also be considered a simple scheme for enforcing sequence balance. But Hash Routing already redefines the routing form and represents an unconventional approach.

The value of a scheme like MQB lies in the fact that it is better compatible with standard MoE formulations and transforms "tuning the auxiliary loss coefficient" into "tuning an interpretable local bias term," allowing us to control the intervention strength more intuitively, while its parallelizability also ensures efficiency. Since it only affects router decisions without injecting gradients, its impact on the primary task's performance is also kept as minimal as possible.

Summary #

Centered around "how to achieve sequence-level load balancing in a loss-free manner," this post started from the original Quantile Balancing (QB) and progressively derived a method named Moving Quantile Balancing (MQB), successfully achieving this goal. However, whether sequence-level balance is truly necessary and to what degree it should be enforced remain an open question.