In the previous article, MoE Journey, Part 6: Optimal Allocation Promotes Balance, we achieved load balancing by solving the following optimal assignment problem:
where indicates that each token activates exactly experts, while indicates that each expert is activated exactly times. However, upon careful reflection, the former is actually not necessary for either training or inference; what we truly need is the latter, which means "on average, each token activates experts" along with load balance for each expert, which is sufficient to achieve the MoE objective. Therefore, this post considers a more simplified problem:
Assuming that the reader is already familiar with the previous article, the derivations here will be relatively brief; if you have doubts about certain steps, you can return to the previous post for a review. As in the previous article, we first consider objective 's relaxed version:
and then consider its equivalent form:
Similarly, here the order of and is interchangeable. Swapping them and rearranging slightly yields can be evaluated first, giving
This tells us that as long as , the expert is activated. The number of activated experts is variable, which formally aligns precisely with MoE Journey, Part 4: Invest More Where It's Hard, except that previously we designed it intuitively, whereas here it is derived from the more fundamental objective .
Substituting back into Equation yields , so 's optimization objective simplifies to
The terms for each are separate, so it can be decomposed into independent sub-optimization problems, which means we can temporarily drop the subscript :
Arranging all in descending order as , and then assuming we know that , we can eliminate to obtain
This shows that both and will increase the objective, so the minimum is achieved at , meaning that lies, among the , between the -th largest and the -th largest elements; by convention, we pick the -th largest element. Restoring the subscript , then for a given , is obtained by sorting in descending order and taking the -th element, or likewise called the " quantile".
Notice that the only variable to be solved for now is , so there is no alternating iteration step anymore; a single quantile step directly yields the optimal solution with absolute balance! We still refer to it as "Quantile Balancing (QB)".
If you are already familiar with MoE Journey, Part 6: Optimal Allocation Promotes Balance, then you will find that this post is essentially a streamlined version of it. However, simple does not mean simplistic: it is actually more elegant and efficient than the Top- form of MoE: first, it activates experts based on whether is greater than 0, which is more efficient than selecting Top-; second, it obtains the optimal load-balanced solution in a single quantile step, which is also more efficient and elegant.
Of course, a one-step optimal solution is very likely to overfit the current training batch. To avoid this issue, the improved approach considered here is to apply an EMA (Exponential Moving Average) between the optimal solution of the current batch and historical solutions (of course, the Top- version in the previous post could also consider EMA). Note that we must likewise be careful of the information leakage trap, so we should first use the old to activate experts, and only then update .
The algorithmic procedure is as follows (in my experiments, ):
In practice, we also face the issue that for , finding the quantile is relatively expensive: it requires finding, among elements, the -th largest element, where equals "global sample count * sequence length". Due to the constraints of various parallel strategies and gradient accumulation, an exact implementation is usually unaffordable. Therefore, we still consider a compromise: partitioning the samples into the largest mini-batches we can accept, calculating a separate for each mini-batch, and averaging them as the final result.
In fact, there is a very simple way to understand this dynamic version of QB, namely "Expert Choice":
Didn't you want each expert to be activated exactly times? Then wouldn't it suffice to let the experts choose tokens? That is, each expert chooses the top- tokens; isn't this simply finding, along , the largest elements?
However, naive Expert Choice suffers from a fatal flaw: it requires comparing all tokens on a global scale, leading to cross-sample and cross-sequence selection, which both violates causality (seeing future information during training) and destroys training-inference consistency (inference results depend on the batch size). This is precisely why the method was previously difficult to deploy in practice.
The ingenuity of this article lies in converting it into a bias form: taking each expert's -th largest element (or equivalently, the quantile) as the threshold , we reframe Expert Choice as Token Choice—from "experts choose the top-" to "as long as , activate". Even more crucially, we delay the update of until after the activation decisions, perfectly circumventing the information leakage issue.
Surprisingly, this bias form that fixes the defects of Expert Choice is naturally embedded in the dual problem of the original linear program—it must be said, it possesses a delightful aesthetic beauty.
To prevent information leakage, during training we must first use the old to determine which experts each token activates, and only then update , which makes the first few training steps quite sensitive to how is initialized. For example, if is all positive, but uses zero initialization, then in the first training step every token will activate all experts, and the computation will explode.
In MoE Journey, Part 4: Invest More Where It's Hard, we already provided a simulation script to estimate a suitable initialization, but here we already know that 's optimal solution is the " quantile", so we can make some reasonable assumptions about the initial scores and derive an analytical formula for initialization. Specifically, we assume that the router's initial logits follow , then its quantile is
This is precisely the optimal for logits under this distribution, and we use it as the initialization for , where is the standard normal distribution's quantile function, also known as the inverse cumulative distribution function.
In addition, an activation function may be added to the router. Assuming the activation function is element-wise and monotonically increasing, such as Sigmoid, it does not alter the ranking, so one can simply apply the corresponding activation function to the formula above. If it is Softmax, it is slightly more complicated: it exponentiates first and then normalizes. Assuming the normalizing denominator is approximately constant, it is similar to the former case: we only need to exponentiate the above formula and then divide by the denominator estimated via quantile simulated sampling:
As for estimating , it is actually very simple. Assuming the router's input dimension is , with RMSNorm applied, and further assuming the router's weight matrix is initialized with , then the router logits approximately follow a normal distribution with mean around 0 and variance around , i.e., , which are standard results in initialization [reference].
In this section, I provide a piece of demo code again for readers to experiment with:
import numpy as np
def quantile_bias(s, k):
"""Dynamic QB: optimal bias obtained in a single quantile step. Principle: https://kexue.fm/archives/11626"""
m, n = s.shape
beta = np.quantile(s, 1 - k / n, axis=0)
return beta
def max_min_avg_vio(s):
"""Compute max_vio, min_vio, and avg_vio, where max_vio >= 0, avg_vio >= 0, -1 <= min_vio <= 0, and closer to 0 means better balance for all three"""
m, n = s.shape
f = (s > 0).mean(0)
f = f / f.sum() * n - 1
return f.max(), f.min(), np.abs(f).mean()
def avg_std_active(s):
"""Compute the mean and standard deviation of activation counts for each expert. Closer to k is better for avg, closer to 0 is better for std"""
m, n = s.shape
f = (s > 0).mean(0) * n
return f.mean(), f.std()
m, n, k = 100000, 256, 8
s = np.random.rand(m, n) + np.random.rand(n) # Simulate an uneven score matrix
b = quantile_bias(s, k)
max_min_avg_vio(s - b) # Expected to be all zeros
avg_std_active(s - b) # Expected to be (k, 0)
from scipy.stats import norm
sigma = 1
s = np.random.randn(m, n) * sigma # Simulate initialization
avg_std_active(s) # Roughly (128, 0.4), much larger than budget k
b0 = np.zeros(n) + norm.ppf(1 - k / n) * sigma # norm.ppf is precisely the quantile function of the standard normal distribution
avg_std_active(s - b0) # Roughly (8, 0.1), close to budget k
s2 = 1 / (1 + np.exp(-s)) # Sigmoid activation
b0_2 = 1 / (1 + np.exp(-b0)) # Sigmoid activation
avg_std_active(s2 - b0_2) # Still roughly (8, 0.1), close to budget k
s3 = np.exp(s) / np.exp(s).sum(axis=1, keepdims=True) # Softmax activation
q = (np.arange(n) + 1) / (n + 1) # Equally spaced points (quantiles)
b0_3 = np.exp(b0) / np.exp(sigma * norm.ppf(q)).sum() # Exp activation and divide by the simulated denominator
avg_std_active(s3 - b0_3) # Roughly (7.5, 0.1), close to budget k
Finally, if we do not want to use quantiles at all, we can still consider the gradient descent method. First, denote the loss function of objective as :
It is differentiable, with gradient
where is the indicator function, . Computing this gradient is cheaper than a global quantile, making it suitable for cost-sensitive readers. With the gradient in hand, we can perform gradient descent; we still consider SignSGD to align with Loss-Free:
This can be used to replace the quantile update step for , and because this is inherently a long-term iterative algorithm, EMA can also be dropped. In fact, this is precisely what we proposed in MoE Journey, Part 4: Invest More Where It's Hard as formula ; we have re-derived it here from the perspective of "optimal allocation + dual objective + gradient descent".
Continuing the exploration from the previous post on Quantile Balancing (QB), by removing the constraint in the optimal allocation problem that "each token can only activate experts", this post significantly simplifies the form of the solution: load balancing can be achieved with just a single quantile step, and each token can decide which experts to activate simply by checking the sign of the biased score, eliminating the overhead of Top- sorting.