skip to content
← Scientific Spaces English

MoE Journey, Part 6: Optimal Allocation Promotes Balance

As we know, load balancing is a fundamental and critical component in MoE architectures that directly affects the model's efficiency and performance. Two articles in this series have already introduced two mainstream approaches to achieving load balancing, namely MoE Journey, Part 2: Scarcity Is Not the Worry; Imbalance Is, which presents the classic Aux Loss approach, and MoE Journey, Part 3: A Different Approach to Allocation, which introduces the Loss-Free scheme proposed by DeepSeek. Both have their strengths, and each has its limitations.

This article will explore a third approach: optimal assignment, which treats load balancing as a linear programming problem under equality constraints. In terms of final form, it still belongs to the Loss-Free family, but based on a completely different principle, it provides a more accurate and hyperparameter-free update mechanism.

Method Review #

Between the two existing methods, the Aux Loss idea is relatively straightforward, with the core intuition of "penalizing wherever instability arises," imposing penalties on load imbalance via a regularization term. However, Aux Loss suffers from two issues: first, the penalty coefficient is difficult to tune—setting it too high interferes with the optimization of the main loss, while setting it too low yields poor balancing; second, underlying Aux Loss is the STE(Straight-Through Estimator), which means its gradients are suboptimal and it may introduce unknown effects beyond load balancing.

To address this, DeepSeek proposed a second approach, Loss-Free, which introduces an additional bias term to assist with ranking, as shown in the following formula:

Note that is only used to adjust the ranking of experts, while what multiplies the experts is still , so it does not directly participate in the model computation, nor does it generate interfering gradients. However, having no gradients for also implies that we need to tailor a separate update rule for it. The intuition is also very direct: being larger increases the probability that the -th expert is selected, so it first computes the current load distribution ; if exceeds the expected value , it decreases ; otherwise, it increases , namely:

Overall, Loss-Free is less intrusive to the model and can indeed be considered simpler and more elegant, but it is not entirely flawless. Although it does not have the penalty coefficient of Aux Loss, it still has a parameter to tune, which acts as the learning rate for . The paper recommends , which is actually tightly coupled with using the Sigmoid activation for ; once the activation function is changed, needs to be retuned.

Furthermore, even when using the Sigmoid activation, the distribution of in some layers can be relatively skewed, making the model quite sensitive to , such that a constant struggles to achieve load balance. This situation is not uncommon; for example, if MoE is used in the first few layers of a model, balancing is often difficult, which is why the "first_k_dense" practice exists; another example is that when the model is relatively large or the total number of experts is large, individual layers can also easily exhibit balancing difficulties.

Linear Programming #

Let us formulate the problem to be solved more precisely: suppose there are tokens, and the router scores of the -th token across the experts are ; then there are scores in total. These scores may be positive or negative, and are not necessarily constrained within a predefined range. Based on these scores, we aim to design an assignment scheme that decides which experts each token should activate.

We specify that each token must select experts. A basic scheme would be to select the experts with the highest scores. However, this approach can suffer from load imbalance, meaning certain experts might be activated significantly too often or too rarely. Therefore, we further specify that each expert must be activated exactly times. Under these two constraints, we seek the assignment scheme with the maximum total score, formalized as

where indicates that the -th token selects the -th expert, while indicates it is not selected. Furthermore, note that must be an integer for the two equality constraints to hold strictly; we assume for now that this condition is satisfied. Here, each expert is strictly activated times, representing the most ideal, perfectly balanced state. In practice, this could naturally be relaxed somewhat, but we adopt the strictest constraints for the theoretical derivation.

In the above formulation, can only take values of or , which constitutes an integer programming problem. Because discrete optimization is generally difficult, we consider its relaxed version:

Now can take any real number in , while all other conditions remain unchanged. Notice that enters linearly into both the objective function and the equality constraints, making this a linear programming problem over a bounded domain.

Minimax #

Constrained optimization is typically challenging as well, so we consider removing the constraints by adopting the formulation (namely, the method of "Lagrange multipliers"):

If and , then the expression above is equivalent to Equation , and the maximum is a finite value; but if either of them is not satisfied, then the step can attain negative infinity, making the maximum negative infinity. Obviously, negative infinity is strictly less than any finite value, so only the former case can hold; that is, it is equivalent to Equation .

The objective is linear with respect to ; linear functions are both convex and concave, and is a convex set, so it satisfies the conditions of the Minimax theorem. We can swap the order of and , meaning that it equals

In the above equation, we have separated out the terms in . A careful observation reveals that the step can actually be evaluated directly: when , we directly set to maximize the objective; when it is less than 0, we set to maximize the objective; when it equals 0, the result is identical for any value of . That is,

Here, is a special case. Assuming that its probability of occurrence is negligible, then is strictly either 0 or 1. Of course, even if , due to the arbitrariness of , we can also let take 0 or 1 according to the constraints. It can thus be seen that although formulation relaxes the original problem , its optimal solution is also the optimal solution to the original problem, and the two are completely equivalent.

Divide and Conquer #

Substituting the above into Eq. yields , so the optimization objective can be simplified to

We will solve this using the alternating minimization approach: first fix to solve for , and then fix to solve for , executing alternately. Since exhibit evident symmetry, these two steps are essentially the same problem. Let us first consider fixing to solve for ; the problem is then equivalent to

We can also observe that each term is summed independently, so we can decompose it into independent sub-optimization problems. This means we can temporarily drop the subscript and further simplify the problem to

Sort all in descending order as , meaning that the -th largest element is , and then assume we know that . Then the objective function equals

This indicates that whether or , the objective function will be amplified. Hence, the minimum of the objective function can only be attained at , where the result does not depend on the specific value of . That is, can be, among all , any number between the -th largest and the -th largest elements. By convention, we set to be the -th largest element.

Alternating Iterations #

Restoring the subscript , we obtain: for any given , is, among all sorted in descending order, the -th element. Similarly, fixing to solve for gives the result: for any given , is, among all sorted in descending order, the -th element. We alternate between these two steps as the final solution algorithm.

Assuming that we have obtained sufficiently accurate and , then according to the previous analysis, will automatically be binary (taking values 0 or 1) and satisfy the constraints. Since corresponds to , combining this with the constraint , we can deduce that for each token , its selected experts are necessarily, within , the top-.

This tells us that during the inference stage, we only need , is merely an intermediate variable in the solving process and can be disregarded once training is complete. This point is crucial because the size of is fixed at , whereas the size of is ; is the global batch size, which varies dynamically and is therefore not a sound format for inference. The solution procedure that utilizes this property is shown in the figure below, where denotes descending sort.

Another point of improvement is that we can use the concept of "quantile" to unify "within numbers, the -th largest element, and within numbers, the -th largest element"; they are actually the " quantile" along their respective dimensions. Numerical frameworks such as NumPy, JAX, and Torch all provide "quantile" function implementations, which can be leveraged to avoid full-sorting operations on the data and save some computational complexity.

Precisely for this reason, we refer to this algorithm as Quantile Balancing (QB).

Beware of Pitfalls #

However, it is not yet time to celebrate; there is an inconspicuous pitfall here, and falling into it can lead to fundamentally incorrect results, so we must be especially careful.

As mentioned earlier, QB uses only during inference, and during training it is sufficient to store only . Therefore, viewed through the lens of Loss-Free methods, QB provides a new bias update strategy that could equally well be termed "Quantile Bias." Whether using the original SignSGD or the quantile approach presented here, both depend on the routing scores of all tokens, so one must not reverse the execution order: we must use the old to select experts for the current batch of data, and only then update the values, ensuring that no information leakage can occur.

Some readers might wonder: what could a bias vector that does not directly enter the forward computation possibly leak? Intuition suggests that the leaked information is indeed minimal, but the risk remains real nonetheless. Perhaps we could try the information-leaking version when training small models, but we should not take this risk when training large models, because they are large and powerful enough to amplify any subtle bug. Thus, maintaining train-inference consistency and eliminating any risk of information leakage is a fundamental discipline in large-scale model training.

Tailoring this to realistic training workflows allows another adjustment to QB: instead of performing iterations from zero initialization, we can start from the bias of the previous step and iterate only once per training step, preventing overfitting to the current batch while reducing computation. Based on , selecting the top- experts is what MoE already did originally; now it is merely modified to top-, incurring virtually no extra cost. The only extra step is using to find, along , the quantile.

However, even with just one iteration, this added step remains relatively expensive: among elements, it requires finding the -th largest element. Here, equals "global batch size * sequence length," which typically starts in the millions; under various parallelism strategies and gradient accumulation, an exact implementation is often prohibitively expensive. A practical compromise is to divide samples into the largest mini-batches our setup can tolerate, compute a separate for each mini-batch using the formula, and then average them to form the final result.

Once these challenges are resolved, QB is almost entirely advantageous: first, it has no hyperparameters such as learning rates to tune; second, it balances extremely quickly and excels particularly at handling extreme cases. For example, when training an all-MoE model with QB, even the very first MoE layer achieves exceptional balance. Nevertheless, for layers that were already easily balanced under the standard SignSGD rule, QB generally offers no noticeable edge.

Comparison plot of MaxVio for the first MoE layer

Comparison of MaxVio in the first MoE layer

Demo Code #

Here is a piece of demonstration code for interested readers to explore:

import numpy as np

def quantile_bias(s, k, T=5):
    """Alternating quantiles to find optimal bias. Principle: https://kexue.fm/archives/11619"""
    m, n = s.shape
    beta = np.zeros((1, n))
    for _ in range(T):
        alpha = np.quantile(s - beta, 1 - k / n, axis=1, keepdims=True)
        # alpha = alpha.clip(0, np.inf)  # BIP includes this extra step
        beta = np.quantile(s - alpha, 1 - k / n, axis=0, keepdims=True)
        # beta = beta.clip(0, np.inf)  # BIP includes this extra step
    return beta

def max_min_avg_vio(s, k):
    """Compute max_vio, min_vio, and avg_vio, where max_vio >= 0, avg_vio >= 0, and -1 <= min_vio <= 0, with values closer to 0 indicating better balance."""
    m, n = s.shape
    topk = np.argsort(-s, axis=1)[:, :k]
    f = np.bincount(topk.reshape(-1), minlength=n)
    f = f / f.sum() * n - 1
    return f.max(), f.min(), np.abs(f).mean()

m, n, k = 100000, 256, 8
s = np.random.rand(m, n) + np.random.rand(n)  # Simulate uneven scores

b = quantile_bias(s, k, 5)
max_min_avg_vio(s, k)  # max_vio, min_vio, and avg_vio from direct top-k
max_min_avg_vio(s - b, k)  # max_vio, min_vio, and avg_vio from top-k after subtracting bias

Related Work #

Framing MoE load balancing from the perspective of optimal assignment first appeared in 《BASE Layers: Simplifying Training of Large, Sparse Models》, but the work that fully formulated a general solution is arguably 《Binary-Integer-Programming Based Algorithm for Expert Load Balancing in Mixture-of-Experts Models》 (referred to as BIP), from which QB is specifically adapted and improved.

Compared to QB's objective in , BIP changes the equality constraints to inequality constraints:

Then repeating the earlier series of derivations, at the step of the formulation, an additional constraint arises, meaning we must consider

for it to be equivalent to the relaxed version of problem . Next, and can still be swapped. Repeating a similar derivation process, the iteration rules for will end up with an additional truncation operation to ensure that they are non-negative:

However, my tests revealed that this truncation operation significantly slows down load balancing and frequently leads to cases where it only "robs the rich" without "relieving the poor" (experts with extremely high frequencies are suppressed, but experts with extremely low frequencies cannot be rescued), indicating that this truncation operation is entirely counterproductive. Therefore, QB directly formulates the original problem with equality constraints, which eliminates the non-negativity constraints on and simplifies the solution to the greatest extent.

Furthermore, BIP appears to make the mistake discussed in the previous section: its approach is to update first and then select the top- experts, which violates causality (leaking future information) and the principle of train-inference consistency (across samples). Nevertheless, BIP's comprehensive analysis of load balancing from the perspective of optimal assignment remains highly inspiring.

Upon searching, I found that following BIP, several other works have explored this direction. They share some overlaps with this post but are not entirely identical, so we will not discuss them in detail here:

《Maximum Score Routing For Mixture-of-Experts》

《Selective Sinkhorn Routing for Improved Sparse Mixture of Experts》

《MicroMoE: Fine-Grained Load Balancing for Mixture-of-Experts with Token Scheduling》

《A Theoretical Framework for Auxiliary-Loss-Free Load Balancing of Sparse Mixture-of-Experts in Large-Scale AI Models》

Gradient Descent #

Finally, let us introduce a solution that lies between Loss-Free and QB. We know that in the iterative formulation of QB, computing is relatively cheap; what is truly expensive is computing , which requires performing some form of sorting across all tokens. Assuming that is given, the optimization objective for is

Besides using quantiles to find its optimal solution, is there a cheaper way to obtain an approximate solution? Indeed there is! It is evident that the objective function is differentiable, so we can certainly consider gradient descent. Its gradient is

where is the indicator function, with . Clearly, computing this gradient is also relatively cheap. With the gradient in hand, we can proceed with gradient descent; to align with Loss-Free, we consider SignSGD

Using it to replace the step of updating via quantiles in QB can achieve a computational cost close to Loss-Free, with empirical performance also lying between the two (when both use Sigmoid activation and the same ). In fact, we can also prove that if within the score matrix , for every row, the -th largest and the -th largest elements are distinct, then this scheme is strictly equivalent to Loss-Free.

Summary #

In this post, we explored the MoE load balancing problem from the perspective of optimal assignment and derived a new aux-loss-free load balancing algorithm, Quantile Balancing. It is more stable and accurate than existing Loss-Free schemes, applies to router scores with arbitrary value ranges, and requires no extra hyperparameters to tune.