Skip to content

Keep MiMo-V2-Flash's router in float32 in bfloat16 models - #50722

Merged
vasqu merged 4 commits into
huggingface:mainfrom
francesco-bertolotti:fix/mimo-v2-flash-router-fp32
Nov 16, 2026
Merged

vasqu merged 4 commits into
huggingface:mainfrom
francesco-bertolotti:fix/mimo-v2-flash-router-fp32

Conversation

@francesco-bertolotti

@francesco-bertolotti francesco-bertolotti commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🤗 Transformers CI

What does this PR do?

The MiMo-V2-Flash checkpoint stores the router in float32 (model_1.safetensors, layer 1):

tensor dtype
mlp.gate.weight [256, 4096] F32
mlp.gate.e_score_correction_bias F32
self_attn.q_proj.weight F8_E4M3
input_layernorm.weight BF16

MiMoV2FlashTopkRouter inherits DeepSeek-V3's router, which creates both tensors in the default dtype, and _keep_in_fp32_modules_strict = ["e_score_correction_bias"], which keeps only the bias in float32 on load. So in a bfloat16 model the gate weight is bf16:

  • from_pretrained(..., dtype=torch.bfloat16) (the config's torch_dtype) rounds the checkpoint's float32 gate to bf16.
  • _from_config(config, dtype=torch.bfloat16) creates both the gate and the bias in bf16.

The router upcasts the weight (F.linear(hidden_states.float(), self.weight.float())), but by then the precision is gone, and the routing logits differ from the checkpoint's.

The fix follows Ernie 4.5 MoE (router weight declared in float32 and listed in _keep_in_fp32_modules_strict) and GLM-4-MoE (correction bias declared in float32):

mlp.gate.weight matches only the MoE router: the dense layer's mlp.gate_proj.weight keeps the requested dtype. An explicit model.to(torch.bfloat16) still casts the router, as for Ernie and GLM.

Tests:

  • test_router_kept_in_float32: saves a model whose gate holds values bf16 cannot represent, reloads it with dtype=torch.bfloat16, and checks that the gate is float32 and bit-identical, the bias is float32, and the dense gate_proj is bf16.
  • test_router_built_in_float32: _from_config(config, dtype=torch.bfloat16) builds every router's weight and bias in float32, and the dense gate_proj in bf16.

Both fail on main (torch.bfloat16 != torch.float32). tests/models/mimo_v2_flash/test_modeling_mimo_v2_flash.py: 129 passed. The 5 failures (static-cache generation, device-context loading, training kwargs) fail the same way on main in my environment.

Related: #50002 (the same loading fix for MiniMax-M2, plus the bias for Step-3.7-Flash and LongCat), #50003 (router logits under autocast).

Who can review?

@vasqu

@vasqu vasqu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Generally agree, i just dont think we need to override the init

Comment on lines +324 to +325
# The checkpoint stores the router weight in float32, like the correction bias
_keep_in_fp32_modules_strict = ["e_score_correction_bias", "mlp.gate.weight"]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

isnt this enough to indicate that this is kept in fp32

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is honored only by .from_pretrained.

.from_config looks at the dtype.

I can double check this tomorrow

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @vasqu, I confirmed this behavior. _keep_in_fp32_modules_strict is only honored by .from_pretrained. .from_config, on the other hand, relies on the parameter's dtype when materializing tensors.

Here's a minimal repro:

"""`_keep_in_fp32_modules_strict` is applied by `from_pretrained`, but not by `from_config`.

- Beam keeps its router in fp32 only through `_keep_in_fp32_modules_strict = ["e_score_correction_bias",
  "mlp.gate.weight"]` (the pattern suggested for MiMo-V2-Flash): `from_config` builds the router in bf16.
- HunYuan V1 MoE explicitly declares its router with `nn.Linear(..., dtype=torch.float32)`: both paths keep it in fp32.
"""

import tempfile

import torch

from transformers import AutoModelForCausalLM, BeamConfig, HunYuanMoEV1Config


beam = BeamConfig(
    vocab_size=128,
    hidden_size=32,
    intermediate_size=64,
    num_hidden_layers=2,
    num_attention_heads=4,
    num_key_value_heads=2,
    head_dim=8,
    moe_intermediate_size=16,
    num_experts=4,
    num_experts_per_tok=2,
    n_group=2,
    topk_group=1,
    sliding_window=16,
    layer_types=["sliding_attention", "full_attention"],
    mlp_layer_types=["dense", "sparse"],
)
hunyuan = HunYuanMoEV1Config(
    vocab_size=128,
    hidden_size=32,
    intermediate_size=64,
    num_hidden_layers=1,
    num_attention_heads=4,
    num_key_value_heads=2,
    head_dim=8,
    num_experts=4,
    moe_topk=2,
)
routers = {
    "Beam (flag only)": (beam, lambda m: m.model.layers[1].mlp.gate.weight.dtype),
    "HunYuan (dtype=)": (hunyuan, lambda m: m.model.layers[0].mlp.gate.wg.weight.dtype),
}

for name, (config, router_dtype) in routers.items():
    with tempfile.TemporaryDirectory() as tmp:
        AutoModelForCausalLM.from_config(config).save_pretrained(tmp)
        pretrained = router_dtype(AutoModelForCausalLM.from_pretrained(tmp, dtype=torch.bfloat16))
    from_config = router_dtype(AutoModelForCausalLM.from_config(config, dtype=torch.bfloat16))
    print(f"{name}  from_pretrained: {pretrained}  from_config: {from_config}")
# Beam (flag only)  from_pretrained: torch.float32  from_config: torch.bfloat16
# HunYuan (dtype=)  from_pretrained: torch.float32  from_config: torch.float32

The difference is that Beam relies solely on the flag: .from_pretrained keeps the router in fp32, while .from_config materializes it in bf16.

HunYuan, on the other hand, sets both the flag and the parameter dtype explicitly. As a result, the router remains in fp32 with both loading methods.

I'm not sure what the intended behavior should be here, but I think .from_pretrained and .from_config should behave consistently.

Let me know how you'd like to proceed. Would you prefer to split the PR, keeping the change that sets the flag separate and addressing the .from_config behavior in a follow-up PR?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok so the issue is rather from_config can not respect the flag atm. But the implications are bigger as this affects a lot of models. So I'd like to rather make a bigger PR for from_config that fixes the behavior instead of overriding the init. The from_pretrained behavior is correct then at least

Tl;dr:

  1. Issue + PR for from_config respecting the fp32 flags
  2. This PR only handles from_pretrained by adding the flags

Comment on lines +181 to +186
self.weight = nn.Parameter(torch.zeros(self.num_experts, self.hidden_dim, dtype=torch.float32))
self.routed_scaling_factor = config.routed_scaling_factor
self.num_group = config.n_group
self.topk_group = config.topk_group
self.norm_topk_prob = config.norm_topk_prob
self.e_score_correction_bias = nn.Buffer(torch.zeros((self.num_experts), dtype=torch.float32))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i.e the dtype=... should not be necessary here

Comment on lines +86 to +117
def test_router_kept_in_float32(self):
# The checkpoint stores the router weight (`mlp.gate.weight`) and its correction bias in float32.
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
model = MiMoV2FlashForCausalLM(config)
gates = {n: p.detach().clone() for n, p in model.named_parameters() if n.endswith("mlp.gate.weight")}
self.assertTrue(gates)
for name in gates: # values bfloat16 cannot represent
gates[name] = 1.0 + 2.0**-12 * torch.randn_like(gates[name])
model.get_parameter(name).data.copy_(gates[name])
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(tmpdirname)
model = MiMoV2FlashForCausalLM.from_pretrained(tmpdirname, dtype=torch.bfloat16)
for name, gate in gates.items():
loaded = model.get_parameter(name)
self.assertEqual(loaded.dtype, torch.float32, name)
torch.testing.assert_close(loaded, gate.to(loaded.device), rtol=0, atol=0)
for name, bias in model.named_buffers():
if name.endswith("e_score_correction_bias"):
self.assertEqual(bias.dtype, torch.float32, name)
# the dense MLP's gate_proj is not matched and follows the requested dtype
self.assertEqual(model.model.layers[0].mlp.gate_proj.weight.dtype, torch.bfloat16)

def test_router_built_in_float32(self):
# Without a checkpoint too: the router declares its weight and correction bias in float32
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
model = MiMoV2FlashForCausalLM._from_config(config, dtype=torch.bfloat16)
routers = [m for m in model.modules() if isinstance(m, MiMoV2FlashTopkRouter)]
self.assertTrue(routers)
for router in routers:
self.assertEqual(router.weight.dtype, torch.float32)
self.assertEqual(router.e_score_correction_bias.dtype, torch.float32)
self.assertEqual(model.model.layers[0].mlp.gate_proj.weight.dtype, torch.bfloat16)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pretty sure we implicitly test already via the _keep_in_fp32_modules_strict flag

@github-actions

Copy link
Copy Markdown
Contributor

[For maintainers] Suggested jobs to run (before merge)

run-slow: mimo_v2_flash

@francesco-bertolotti

Copy link
Copy Markdown
Contributor Author

I reverted the change regarding the dtype for the router. Now this PR changes only _keep_in_fp32_modules_strict.

I will do a follow-up PR to address the .from_config issue

@vasqu vasqu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, ill run slow ci just to be sure the integration tests dont fail with this

@@ -81,6 +82,28 @@ def test_sliding_window_from_hub_config(self):
self.assertEqual(config.sliding_window, 129)
self.assertEqual(MiMoV2FlashConfig.from_dict(config.to_dict()).sliding_window, 129)

def test_router_kept_in_float32(self):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

imo we can remove that test as well then

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test is gone

@vasqu

vasqu commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator

run-slow: mimo_v2_flash

@vasqu
vasqu enabled auto-merge November 16, 2026 14:55
@github-actions

Copy link
Copy Markdown
Contributor

CI (Nvidia + AMD)

Nvidia · ✅ No new failures 🎉👏 · ⚙️ Workflow · 📊 Dashboard

AMD · ✅ No new failures 🎉👏 · ⚙️ Workflow · 📊 Dashboard

Failures (2 pre-existing)

    Pre-existing failures (still failing) — 2 total:

        Same error (2):

        - mimo_v2_flash:
            tests/models/mimo_v2_flash/test_modeling_mimo_v2_flash.py::MiMoV2FlashIntegrationTest::test_small_model_generation
            tests/models/mimo_v2_flash/test_modeling_mimo_v2_flash.py::MiMoV2FlashIntegrationTest::test_small_model_logits_batched

@vasqu

vasqu commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator

Thanks merging it now 🫡

@HuggingFaceDocBuilderDev

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

@vasqu
vasqu added this pull request to the merge queue Nov 16, 2026
Merged via the queue into huggingface:main with commit b7601f7 Nov 16, 2026
44 of 45 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants