Anyone who has trained an MoE knows that if you replace the MLP parts across the entire model with MoE layers, the first few MoE layers closest to the embedding often struggle to achieve load balancing. In response to this, DeepSeek V3, including our Kimi K2, adopted the strategy of "first_k_dense"—as the name suggests, the first layers do not use MoE, but rather conventional dense GLUs. With DeepSeek V4, this strategy was changed to "first_k_hash".
Here, "hash" refers to "Hash Routing", proposed in 《Hash Layers For Large Sparse Models》, which assigns experts to each token using a predetermined mapping table tid2eid. In this post, we explore how to generate this tid2eid.
As for V4 adopting Hash Routing, it can be seen as an exploration in a different direction for the same problem. The idea is that for the first few MoE layers, there is not much contextual information, so selecting experts based on their input vectors may not differ much from selecting them directly based on token IDs that carry no contextual information at all. In that case, why not simply hardcode in advance which experts each token should activate in the first few layers based on token ID? This is the origin of "tid2eid (Token Id to Expert Id)".
So how do we generate this tid2eid table? Would purely random assignment work? It seems not, because the frequency of each token varies, and purely random assignment would actually lead to imbalance. DeepSeek has not disclosed the details of how this table is generated, so we can only speculate based on our own line of thinking.
Suppose there are a total of distinct tokens, and the frequency of the -th token is , and without loss of generality, assume they are already sorted in descending order, namely . We use to denote whether token should activate expert ( indicates not activated, and indicates activated). With a total of experts and each token selecting experts, we actually need to solve the system of equations
Note that in the last equation we used approximately equal to , because if it were changed to , strictly speaking the system of equations might not have a solution. Therefore, we retain the notation, meaning that both sides should be as close as possible. It can also be formulated as the optimization problem
A relatively straightforward solution to this problem is a greedy algorithm:
Process token by token in descending order of frequency: first tally the allocated load of each expert, and then select the experts with the lightest load as the activated experts for the current token, subsequently updating the experts' load distribution.
Although the greedy algorithm is greedy in principle, in most cases it can achieve a near-optimal solution. A reference implementation is as follows:
import numpy as np
# Simulate distribution
m, n, k = 80000, 128, 4
p = 1 / (10 + np.arange(m))
p /= p.sum()
# Greedy processing
x, f = np.zeros((m, k), dtype='int32'), np.zeros(n)
for i in range(m):
j = f.argsort()[:k] # Select the k experts with the lightest load
f[j] += p[i] / k # Update load distribution
x[i] = j # Record into tid2eid
# Evaluate balance
max_vio, min_vio = f.max() * n - 1, f.min() * n - 1
Note that this code contains no randomness at all; in principle, it is a deterministic algorithm. What if we want different tid2eid tables for the first few layers? We can consider introducing some randomness, such as replacing range(m) with np.random.permutation(m), that is, not executing in descending order of frequency. This can still yield usable solutions, though the balance will be slightly worse. We can run it multiple times and pick the solutions with the lowest max_vio.
Now let us consider an extreme case: -- that is, the frequency of a certain token has far exceeded the balanced level, at which point no matter how tid2eid is arranged, it is impossible to achieve load balance. In other words, making decisions based solely on a single token ID cannot achieve balance in any case. How should one deal with this situation?
The answer is simple: switch to a hash method that relies on more input information. Previously, we made decisions based solely on the current token ID; in reality, every token resides in some sequence and has context. If the previous approach was "1-gram to expert", we can now consider combining it with preceding tokens to form "2-gram to expert", "3-gram to expert", and so forth.
Taking the 2-gram as an example, a naive hashing approach is: choose a prime larger than denoted by and compute as the activated expert. Repeating this with different primes times yields experts. Because the number of grams is increased, the number of input combinations increases substantially, which are then mapped to a finite set of numbers. Each number will likely be "filled up", so as long as the hash function is not particularly bad, the result is almost balanced.
Therefore, its advantage is that there is no need to consider frequencies, nor to memorize a tid2eid table beforehand. As for the disadvantage, computing the hash function is slightly more complicated, and the same token might select duplicate experts, but these are not particularly serious issues.