Router

Select experts

×

Keep 3 of 8 expert groups, then the top 6 experts.

Eisel=[ i∈top⁡6(s) within the top 3 groups ]{\htmlData{light=selected select}{E^{\mathrm{sel}}_i}}=\big[\,i\in\operatorname{top}_{6}({\htmlData{light=affinities softmax}{s}})\text{ within the top }3\text{ groups}\,\big]
Eisel=[ i∈top⁡6(s)within the top 3 groups ]\begin{aligned}{\htmlData{light=selected select}{E^{\mathrm{sel}}_i}}=\big[\,&i\in\operatorname{top}_{6}({\htmlData{light=affinities softmax}{s}})\\&\text{within the top }3\text{ groups}\,\big]\end{aligned}
in
ss [B batch, T positions, 160 experts]
out
EselE^{\mathrm{sel}} [B batch, T positions, 160 experts]
Explanation

The 160 experts form 8 groups of 20. Each group is ranked by the highest affinity among its experts; experts outside the best 3 groups are excluded, and the 6 highest remaining experts are selected. The router has no selection bias: the affinities that choose the experts also weight them.

group 0group 1group 2group 3group 4group 5group 6group 7chosen: 6in play: 3 of 8 groups
One position, an illustrative choice. Experts outside the 3 kept groups cannot be chosen, whatever their affinity.
Sources

In codetorch.topk(tmp_scores, k=self.top_k, dim=-1, sorted=False)

Open pinned code ↗

Direct evidence

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