Router
×Score all 160 experts for each position and keep 6 from the best 3 of 8 groups; their weights are their affinities times 16.
Why
3 of 8 groups. With expert parallelism the routed experts sit on several devices, and a token’s communication grows with the number of devices its experts are on; with fine-grained experts many are active. DeepSeek-V2’s authors therefore send each token to experts on at most M devices, chosen by the highest affinity of the experts on each, and report that with M ⩾ 3 this performs roughly as well as unrestricted top-K. In training a layer’s experts sat on 8 devices and M was 3; the configuration keeps the same limit at inference: 8 groups of 20 experts, at most 3 of them per token (n_group, topk_group). DeepSeek-V2 paper §2.2.2 and §3.1.2, pp. 9–10, 12
Balance losses. An unbalanced load raises the risk of routing collapse and lowers efficiency with expert parallelism, so DeepSeek-V2 trains with three auxiliary losses, for expert-level, device-level and communication balance (α₁ = 0.003, α₂ = 0.05, α₃ = 0.02), and drops tokens over a device’s budget in training but none in evaluation. The implementation keeps one of them, the expert-level loss, in its training branch, with the configuration’s aux_loss_alpha of 0.001, not the paper’s 0.003; the drawing leaves that branch out. DeepSeek-V2 paper §2.2.3–2.2.4 and §3.1.2, pp. 10–12
All 4 steps
- in
- [B batch, T positions, 5120 d]
- out
- [B batch, T positions, 160 experts]
Parameters819,200 × 59 layers
819,200 parameters per instance, across its learned components
| Component | Calculation | Parameters |
|---|---|---|
| Expert scores | 5,120 × 160 | 819,200 |
One in each of the 59 MoE layers, each with its own weights.
Explanation
The implementation returns each position’s 6 weights with their expert indices (modeling_deepseek.py 497); spreads them over all 160 experts, zero for the other 154.
Sources
In codeself.gate
Direct evidence
The router owns one score vector per routed expert; it reads the scoring function, the group-limited selection and whether to renormalize from the configuration, and has no bias.
modeling_deepseek.py 393–418 ↗ · deepseek-ai/DeepSeek-V2 @ 4461458f186c
Excerpt
class MoEGate(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.top_k = config.num_experts_per_tok
self.n_routed_experts = config.n_routed_experts
self.routed_scaling_factor = config.routed_scaling_factor
self.scoring_func = config.scoring_func
self.alpha = config.aux_loss_alpha
self.seq_aux = config.seq_aux
self.topk_method = config.topk_method
self.n_group = config.n_group
self.topk_group = config.topk_group
# topk selection algorithm
self.norm_topk_prob = config.norm_topk_prob
self.gating_dim = config.hidden_size
self.weight = nn.Parameter(
torch.empty((self.n_routed_experts, self.gating_dim))
)
self.reset_parameters()
def reset_parameters(self) -> None:
import torch.nn.init as init
init.kaiming_uniform_(self.weight, a=math.sqrt(5))Routing: softmax scores in float32; the 8 groups of 20 experts ranked by their highest score and the best 3 kept, the experts of the other groups masked with 0; the top-6 chosen; with norm_topk_prob false their scores are multiplied by the route scale and not renormalized; the expert indices and weights are returned (with an auxiliary loss only in training).
modeling_deepseek.py 420–497 ↗ · deepseek-ai/DeepSeek-V2 @ 4461458f186c
Excerpt
def forward(self, hidden_states):
bsz, seq_len, h = hidden_states.shape
### compute gating score
hidden_states = hidden_states.view(-1, h)
logits = F.linear(
hidden_states.type(torch.float32), self.weight.type(torch.float32), None
)
if self.scoring_func == "softmax":
scores = logits.softmax(dim=-1, dtype=torch.float32)
else:
raise NotImplementedError(
f"insupportable scoring function for MoE gating: {self.scoring_func}"
)
### select top-k experts
if self.topk_method == "gready":
topk_weight, topk_idx = torch.topk(
scores, k=self.top_k, dim=-1, sorted=False
)
elif self.topk_method == "group_limited_greedy":
group_scores = (
scores.view(bsz * seq_len, self.n_group, -1).max(dim=-1).values
) # [n, n_group]
group_idx = torch.topk(
group_scores, k=self.topk_group, dim=-1, sorted=False
)[
1
] # [n, top_k_group]
group_mask = torch.zeros_like(group_scores) # [n, n_group]
group_mask.scatter_(1, group_idx, 1) # [n, n_group]
score_mask = (
group_mask.unsqueeze(-1)
.expand(
bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
)
.reshape(bsz * seq_len, -1)
) # [n, e]
tmp_scores = scores.masked_fill(~score_mask.bool(), 0.0) # [n, e]
topk_weight, topk_idx = torch.topk(
tmp_scores, k=self.top_k, dim=-1, sorted=False
)
### norm gate to sum 1
if self.top_k > 1 and self.norm_topk_prob:
denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
topk_weight = topk_weight / denominator
else:
topk_weight = topk_weight * self.routed_scaling_factor… lines 468–496 omitted …
return topk_idx, topk_weight, aux_loss