Mixture of experts

Weighted expert sum

×

Sum the selected experts’ outputs, each scaled by its routing weight.

Δffn=∑i=1384Gi Ei{\htmlData{light=output combine}{\Delta_{\mathrm{ffn}}}}=\sum_{i=1}^{384}{\htmlData{light=gates router}{G_i}}\,{\htmlData{light=expert-outputs experts}{E_i}}
in
GG [B batch, 1 position, 384 experts]EiE_i [B batch, 1 position, 6144 d]
out
Δffn\Delta_{\mathrm{ffn}} [B batch, 1 position, 6144 d]
Sources

In codefinal_hidden_states.index_add_(0, token_indices, expert_output * expert_weights.unsqueeze(-1)) · 208

Open pinned code ↗

Direct evidence

The MoE block holds 384 SwiGLU experts of moe_intermediate_size and the router; each expert runs on the positions routed to it, its output scaled by the routing weight and added back at those positions; there is no shared expert.

modeling_mimo_v2.py 187–217 ↗ · XiaomiMiMo/MiMo-V2.6-Pro-RL @ b61f21852680

Excerpt
class MiMoV2MoE(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.config = config
        self.experts = nn.ModuleList(
            [MiMoV2MLP(config, intermediate_size=config.moe_intermediate_size) for _ in range(config.n_routed_experts)]
        )
        self.gate = MiMoV2MoEGate(config)

    def moe(self, hidden_states: torch.Tensor, topk_indices: torch.Tensor, topk_weights: torch.Tensor):
        final_hidden_states = torch.zeros_like(hidden_states, dtype=topk_weights.dtype)
        expert_mask = torch.nn.functional.one_hot(topk_indices, num_classes=len(self.experts))
        expert_mask = expert_mask.permute(2, 0, 1)

        for expert_idx, expert in enumerate(self.experts):
            mask = expert_mask[expert_idx]
            token_indices, weight_indices = torch.where(mask)
            if token_indices.numel() > 0:
                expert_weights = topk_weights[token_indices, weight_indices]
                expert_input = hidden_states[token_indices]
                expert_output = expert(expert_input)
                final_hidden_states.index_add_(0, token_indices, expert_output * expert_weights.unsqueeze(-1))

        return final_hidden_states.type(hidden_states.dtype)

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        orig_shape = hidden_states.shape
        topk_indices, topk_weights = self.gate(hidden_states)
        hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
        hidden_states = self.moe(hidden_states, topk_indices, topk_weights).view(*orig_shape)
        return hidden_states