Repository navigation
Keep MiMo-V2-Flash's router in float32 in bfloat16 models - #50722
Conversation
vasqu
left a comment
There was a problem hiding this comment.
Generally agree, i just dont think we need to override the init
| # The checkpoint stores the router weight in float32, like the correction bias | ||
| _keep_in_fp32_modules_strict = ["e_score_correction_bias", "mlp.gate.weight"] |
There was a problem hiding this comment.
isnt this enough to indicate that this is kept in fp32
There was a problem hiding this comment.
I think this is honored only by .from_pretrained.
.from_config looks at the dtype.
I can double check this tomorrow
There was a problem hiding this comment.
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.float32The 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?
There was a problem hiding this comment.
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:
- Issue + PR for
from_configrespecting the fp32 flags - This PR only handles
from_pretrainedby adding the flags
| 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)) |
There was a problem hiding this comment.
i.e the dtype=... should not be necessary here
| 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) |
There was a problem hiding this comment.
pretty sure we implicitly test already via the _keep_in_fp32_modules_strict flag
|
[For maintainers] Suggested jobs to run (before merge) run-slow: mimo_v2_flash |
|
I reverted the change regarding the dtype for the router. Now this PR changes only I will do a follow-up PR to address the |
vasqu
left a comment
There was a problem hiding this comment.
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): | |||
There was a problem hiding this comment.
imo we can remove that test as well then
There was a problem hiding this comment.
test is gone
|
run-slow: mimo_v2_flash |
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: |
|
Thanks merging it now 🫡 |
|
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. |
What does this PR do?
The MiMo-V2-Flash checkpoint stores the router in float32 (
model_1.safetensors, layer 1):mlp.gate.weight[256, 4096]mlp.gate.e_score_correction_biasself_attn.q_proj.weightinput_layernorm.weightMiMoV2FlashTopkRouterinherits 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'storch_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):MiMoV2FlashTopkRouter.__init__createsweightande_score_correction_biaswithdtype=torch.float32._keep_in_fp32_modules_strict = ["e_score_correction_bias", "mlp.gate.weight"], as Keep the MoE correction bias (and MiniMax-M2's router) in float32 when loading in bfloat16 #50002 does for MiniMax-M2.mlp.gate.weightmatches only the MoE router: the dense layer'smlp.gate_proj.weightkeeps the requested dtype. An explicitmodel.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 withdtype=torch.bfloat16, and checks that the gate is float32 and bit-identical, the bias is float32, and the densegate_projis bf16.test_router_built_in_float32:_from_config(config, dtype=torch.bfloat16)builds every router's weight and bias in float32, and the densegate_projin 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 onmainin 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