Router

Selected experts

×

Which 10 experts each position uses.

shape
EselE^{\mathrm{sel}} [B batch, 1 position, 512 experts]
Sources

Contextual evidence from Select experts

The router scores all experts with one weight matrix, takes the softmax in float32, keeps the top 10 and divides them by their sum.

modeling_qwen3_5_moe.py 870–887 ↗ · huggingface/transformers @ 18329f106538

Excerpt
@use_kernel_forward_from_hub("SoftmaxTopKRouter")
class Qwen3_5MoeTopKRouter(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.top_k = config.num_experts_per_tok
        self.num_experts = config.num_experts
        self.hidden_dim = config.hidden_size
        self.weight = nn.Parameter(torch.zeros(self.num_experts, self.hidden_dim))

    def forward(self, hidden_states):
        hidden_states = hidden_states.reshape(-1, self.hidden_dim)
        router_logits = F.linear(hidden_states, self.weight)  # (seq_len, num_experts)
        router_probs = torch.nn.functional.softmax(router_logits, dtype=torch.float, dim=-1)
        router_top_value, router_indices = torch.topk(router_probs, self.top_k, dim=-1)  # (seq_len, top_k)
        router_top_value /= router_top_value.sum(dim=-1, keepdim=True)
        router_top_value = router_top_value.to(router_logits.dtype)
        router_scores = router_top_value
        return router_logits, router_scores, router_indices