From b4a5b4b2c652615ef0c4dfa8adabad1756a6ec3f Mon Sep 17 00:00:00 2001 From: Felipe Sens Bonetto Date: Mon, 26 Oct 2026 13:49:38 -0300 Subject: [PATCH] Keep the MoE correction bias (and MiniMax-M2's router) in float32 MiniMax-M2/M3, Step-3.7 and LongCat-Flash store e_score_correction_bias in float32 with large values that differ little between experts; bfloat16 collapses them to a few values and changes the selected experts for almost every token. MiniMax also stores the router weight in float32; keep it in float32 on load and under autocast. --- .../longcat_flash/modeling_longcat_flash.py | 1 + .../longcat_flash/modular_longcat_flash.py | 1 + .../models/minimax_m2/modeling_minimax_m2.py | 8 +++-- .../models/minimax_m2/modular_minimax_m2.py | 9 ++++-- .../minimax_m3_vl/modeling_minimax_m3_vl.py | 8 +++-- .../minimax_m3_vl/modular_minimax_m3_vl.py | 6 ++-- .../models/step3p7/modeling_step3p7.py | 7 +++-- .../models/step3p7/modular_step3p7.py | 1 + .../test_modeling_longcat_flash.py | 18 +++++++++++ .../minimax_m2/test_modeling_minimax_m2.py | 30 +++++++++++++++++++ .../test_modeling_minimax_m3_vl.py | 30 +++++++++++++++++++ tests/models/step3p7/test_modeling_step3p7.py | 20 +++++++++++++ 12 files changed, 129 insertions(+), 10 deletions(-) diff --git a/src/transformers/models/longcat_flash/modeling_longcat_flash.py b/src/transformers/models/longcat_flash/modeling_longcat_flash.py index ddd078028a11..76611b6d5810 100644 --- a/src/transformers/models/longcat_flash/modeling_longcat_flash.py +++ b/src/transformers/models/longcat_flash/modeling_longcat_flash.py @@ -543,6 +543,7 @@ class LongcatFlashPreTrainedModel(PreTrainedModel): _keep_in_fp32_modules = [ "classifier.weight" ] # TODO let's make sure original code base has this, for now it fixes quantization + _keep_in_fp32_modules_strict = ["e_score_correction_bias"] @torch.no_grad() def _init_weights(self, module): diff --git a/src/transformers/models/longcat_flash/modular_longcat_flash.py b/src/transformers/models/longcat_flash/modular_longcat_flash.py index 30bc253ad159..f98ea890541c 100644 --- a/src/transformers/models/longcat_flash/modular_longcat_flash.py +++ b/src/transformers/models/longcat_flash/modular_longcat_flash.py @@ -326,6 +326,7 @@ class LongcatFlashPreTrainedModel(PreTrainedModel): _keep_in_fp32_modules = [ "classifier.weight" ] # TODO let's make sure original code base has this, for now it fixes quantization + _keep_in_fp32_modules_strict = ["e_score_correction_bias"] @torch.no_grad() def _init_weights(self, module): diff --git a/src/transformers/models/minimax_m2/modeling_minimax_m2.py b/src/transformers/models/minimax_m2/modeling_minimax_m2.py index 708aba574f1d..a2b850c6ce9b 100644 --- a/src/transformers/models/minimax_m2/modeling_minimax_m2.py +++ b/src/transformers/models/minimax_m2/modeling_minimax_m2.py @@ -37,7 +37,7 @@ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel, slice_logits_to_keep from ...processing_utils import Unpack from ...utils import TransformersKwargs, auto_docstring, can_return_tuple -from ...utils.generic import merge_with_config_defaults +from ...utils.generic import maybe_autocast, merge_with_config_defaults from ...utils.output_capturing import OutputRecorder, capture_outputs from .configuration_minimax_m2 import MiniMaxM2Config @@ -52,7 +52,9 @@ def __init__(self, config): def forward(self, hidden_states, e_score_correction_bias): hidden_states = hidden_states.reshape(-1, self.hidden_dim) - router_logits = F.linear(hidden_states.to(self.weight.dtype), self.weight) # (seq_len, num_experts) + device_type = hidden_states.device.type if isinstance(hidden_states.device.type, str) else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): # Keep the gate's dtype, even under autocast + router_logits = F.linear(hidden_states.to(self.weight.dtype), self.weight) # (seq_len, num_experts) # Main difference to other Moe, using Sigmoid activation instead of Softmax routing_weights = nn.functional.sigmoid(router_logits.float()) scores_for_choice = routing_weights + e_score_correction_bias @@ -393,6 +395,8 @@ class MiniMaxM2PreTrainedModel(PreTrainedModel): "hidden_states": MiniMaxM2DecoderLayer, "attentions": MiniMaxM2Attention, } + # The checkpoints store the router and its correction bias in float32 + _keep_in_fp32_modules_strict = ["e_score_correction_bias", "mlp.gate.weight"] @torch.no_grad() def _init_weights(self, module): diff --git a/src/transformers/models/minimax_m2/modular_minimax_m2.py b/src/transformers/models/minimax_m2/modular_minimax_m2.py index 57090e31a927..ed109129e148 100644 --- a/src/transformers/models/minimax_m2/modular_minimax_m2.py +++ b/src/transformers/models/minimax_m2/modular_minimax_m2.py @@ -27,7 +27,7 @@ from ...modeling_utils import PreTrainedModel from ...processing_utils import Unpack from ...utils import TransformersKwargs, auto_docstring -from ...utils.generic import merge_with_config_defaults, no_inherit_decorator +from ...utils.generic import maybe_autocast, merge_with_config_defaults, no_inherit_decorator from ...utils.output_capturing import capture_outputs from ..flex_olmo.modeling_flex_olmo import FlexOlmoAttention from ..glm4_moe.modeling_glm4_moe import ( @@ -126,7 +126,9 @@ def convert_rope_params_to_dict(self, **kwargs): class MiniMaxM2TopKRouter(MixtralTopKRouter): def forward(self, hidden_states, e_score_correction_bias): hidden_states = hidden_states.reshape(-1, self.hidden_dim) - router_logits = F.linear(hidden_states.to(self.weight.dtype), self.weight) # (seq_len, num_experts) + device_type = hidden_states.device.type if isinstance(hidden_states.device.type, str) else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): # Keep the gate's dtype, even under autocast + router_logits = F.linear(hidden_states.to(self.weight.dtype), self.weight) # (seq_len, num_experts) # Main difference to other Moe, using Sigmoid activation instead of Softmax routing_weights = nn.functional.sigmoid(router_logits.float()) scores_for_choice = routing_weights + e_score_correction_bias @@ -176,6 +178,9 @@ def __init__(self, config: MiniMaxM2Config, layer_idx: int): class MiniMaxM2PreTrainedModel(MixtralPreTrainedModel): + # The checkpoints store the router and its correction bias in float32 + _keep_in_fp32_modules_strict = ["e_score_correction_bias", "mlp.gate.weight"] + @torch.no_grad() def _init_weights(self, module): PreTrainedModel._init_weights(self, module) diff --git a/src/transformers/models/minimax_m3_vl/modeling_minimax_m3_vl.py b/src/transformers/models/minimax_m3_vl/modeling_minimax_m3_vl.py index 5ae40536bc96..541883d58bd6 100644 --- a/src/transformers/models/minimax_m3_vl/modeling_minimax_m3_vl.py +++ b/src/transformers/models/minimax_m3_vl/modeling_minimax_m3_vl.py @@ -43,7 +43,7 @@ from ...processing_utils import Unpack from ...utils import ModelOutput, TransformersKwargs, auto_docstring, torch_compilable_check from ...utils.deprecation import deprecate_kwarg -from ...utils.generic import can_return_tuple, merge_with_config_defaults +from ...utils.generic import can_return_tuple, maybe_autocast, merge_with_config_defaults from ...utils.import_utils import is_torchdynamo_compiling from ...utils.output_capturing import OutputRecorder, capture_outputs from ...vision_utils import get_vision_position_ids @@ -230,7 +230,9 @@ def __init__(self, config: MiniMaxM3VLTextConfig): def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: hidden_states = hidden_states.reshape(-1, self.hidden_dim) - router_logits = F.linear(hidden_states.to(self.weight.dtype), self.weight) + device_type = hidden_states.device.type if isinstance(hidden_states.device.type, str) else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): # Keep the gate's dtype, even under autocast + router_logits = F.linear(hidden_states.to(self.weight.dtype), self.weight) # Sigmoid scoring (not softmax), as in M2. routing_weights = F.sigmoid(router_logits.float()) scores_for_choice = routing_weights + self.e_score_correction_bias @@ -683,6 +685,8 @@ class MiniMaxM3VLPreTrainedModel(PreTrainedModel): "hidden_states": MiniMaxM3VLDecoderLayer, "attentions": MiniMaxM3VLAttention, } + # The checkpoints store the router and its correction bias in float32 + _keep_in_fp32_modules_strict = ["e_score_correction_bias", "mlp.gate.weight"] input_modalities = ("image", "video", "text") _keys_to_ignore_on_load_unexpected = [r"(^|\.)mtp\..*"] _compatible_flash_implementations = ["MiniMaxAI/msa"] diff --git a/src/transformers/models/minimax_m3_vl/modular_minimax_m3_vl.py b/src/transformers/models/minimax_m3_vl/modular_minimax_m3_vl.py index a5d826666ace..87da764b79a7 100644 --- a/src/transformers/models/minimax_m3_vl/modular_minimax_m3_vl.py +++ b/src/transformers/models/minimax_m3_vl/modular_minimax_m3_vl.py @@ -32,7 +32,7 @@ from ...processing_utils import Unpack from ...utils import TransformersKwargs, auto_docstring, logging, torch_compilable_check from ...utils.deprecation import deprecate_kwarg -from ...utils.generic import can_return_tuple, merge_with_config_defaults +from ...utils.generic import can_return_tuple, maybe_autocast, merge_with_config_defaults from ...utils.import_utils import is_torchdynamo_compiling from ...utils.output_capturing import capture_outputs from ...vision_utils import get_vision_position_ids @@ -359,7 +359,9 @@ def __init__(self, config: MiniMaxM3VLTextConfig): def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: hidden_states = hidden_states.reshape(-1, self.hidden_dim) - router_logits = F.linear(hidden_states.to(self.weight.dtype), self.weight) + device_type = hidden_states.device.type if isinstance(hidden_states.device.type, str) else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): # Keep the gate's dtype, even under autocast + router_logits = F.linear(hidden_states.to(self.weight.dtype), self.weight) # Sigmoid scoring (not softmax), as in M2. routing_weights = F.sigmoid(router_logits.float()) scores_for_choice = routing_weights + self.e_score_correction_bias diff --git a/src/transformers/models/step3p7/modeling_step3p7.py b/src/transformers/models/step3p7/modeling_step3p7.py index 4934e1b05e84..927003e6f0ef 100644 --- a/src/transformers/models/step3p7/modeling_step3p7.py +++ b/src/transformers/models/step3p7/modeling_step3p7.py @@ -42,7 +42,7 @@ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel, slice_logits_to_keep from ...processing_utils import Unpack from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, torch_compilable_check, torch_int -from ...utils.generic import merge_with_config_defaults +from ...utils.generic import maybe_autocast, merge_with_config_defaults from ...utils.output_capturing import OutputRecorder, capture_outputs from ...vision_utils import get_vision_position_ids from .configuration_step3p7 import Step3p7Config, Step3p7TextConfig, Step3p7VisionConfig @@ -350,6 +350,7 @@ class Step3p7PreTrainedModel(PreTrainedModel): _supports_flex_attn = True _supports_static_cache = True _supports_attention_backend = True + _keep_in_fp32_modules_strict = ["e_score_correction_bias"] @torch.no_grad() def _init_weights(self, module): @@ -589,7 +590,9 @@ def __init__(self, config: Step3p7TextConfig): def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: hidden_states = hidden_states.reshape(-1, self.hidden_dim) - router_logits = F.linear(hidden_states.to(self.weight.dtype), self.weight) + device_type = hidden_states.device.type if isinstance(hidden_states.device.type, str) else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): # Keep the gate's dtype, even under autocast + router_logits = F.linear(hidden_states.to(self.weight.dtype), self.weight) # Sigmoid scoring (not softmax), as in M2. routing_weights = F.sigmoid(router_logits.float()) scores_for_choice = routing_weights + self.e_score_correction_bias diff --git a/src/transformers/models/step3p7/modular_step3p7.py b/src/transformers/models/step3p7/modular_step3p7.py index 38d878b881e4..d7f7123b8765 100644 --- a/src/transformers/models/step3p7/modular_step3p7.py +++ b/src/transformers/models/step3p7/modular_step3p7.py @@ -682,6 +682,7 @@ class Step3p7PreTrainedModel(PreTrainedModel): _supports_flex_attn = True _supports_static_cache = True _supports_attention_backend = True + _keep_in_fp32_modules_strict = ["e_score_correction_bias"] @torch.no_grad() def _init_weights(self, module): diff --git a/tests/models/longcat_flash/test_modeling_longcat_flash.py b/tests/models/longcat_flash/test_modeling_longcat_flash.py index 8721b217801e..ff33150dd8a0 100644 --- a/tests/models/longcat_flash/test_modeling_longcat_flash.py +++ b/tests/models/longcat_flash/test_modeling_longcat_flash.py @@ -213,6 +213,24 @@ class LongcatFlashModelTest(CausalLMModelTest, unittest.TestCase): model_tester_class = LongcatFlashModelTester + def test_e_score_correction_bias_kept_in_float32(self): + # LongCat-Flash checkpoints store the routing bias in float32, and loading in bfloat16 must keep it there: + # with large biases (the values below), bfloat16 would collapse experts' biases to a few distinct values. + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + model = LongcatFlashForCausalLM(config) + biases = [b for n, b in model.named_buffers() if n.endswith("e_score_correction_bias")] + self.assertTrue(biases) + for bias in biases: + bias.copy_(8.5 + 0.02 * torch.arange(bias.numel(), dtype=torch.float32)) + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model = LongcatFlashForCausalLM.from_pretrained(tmpdirname, dtype=torch.bfloat16) + for name, bias in model.named_buffers(): + if name.endswith("e_score_correction_bias"): + self.assertEqual(bias.dtype, torch.float32, name) + expected = 8.5 + 0.02 * torch.arange(bias.numel(), dtype=torch.float32) + torch.testing.assert_close(bias, expected.to(bias.device), rtol=0, atol=0) + @unittest.skip("LongcatFlash buffers include complex numbers, which breaks this test") def test_save_load_fast_init_from_base(self): pass diff --git a/tests/models/minimax_m2/test_modeling_minimax_m2.py b/tests/models/minimax_m2/test_modeling_minimax_m2.py index 1def660b976f..e6087afac68d 100644 --- a/tests/models/minimax_m2/test_modeling_minimax_m2.py +++ b/tests/models/minimax_m2/test_modeling_minimax_m2.py @@ -13,6 +13,7 @@ # limitations under the License. """Testing suite for the PyTorch MiniMaxM2 model.""" +import tempfile import unittest from transformers import AutoTokenizer, is_torch_available, set_seed @@ -114,6 +115,35 @@ def test_legacy_rotary_dim_maps_to_partial_rotary_factor(self): # Configs without the legacy field keep full-width rotary. self.assertIsNone(MiniMaxM2Config().rope_parameters.get("partial_rotary_factor")) + def test_router_and_correction_bias_kept_in_float32(self): + # The checkpoints store the router weight and its correction bias in float32. The bias has values of + # 1.5-8.6 that differ by ~0.02 between experts, which bfloat16 would collapse to a few distinct values. + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + model = MiniMaxM2ForCausalLM(config) + biases = [b for n, b in model.named_buffers() if n.endswith("e_score_correction_bias")] + self.assertTrue(biases) + for bias in biases: + bias.copy_(8.5 + 0.02 * torch.arange(bias.numel(), dtype=torch.float32)) + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model = MiniMaxM2ForCausalLM.from_pretrained(tmpdirname, dtype=torch.bfloat16) + for name, bias in model.named_buffers(): + if name.endswith("e_score_correction_bias"): + self.assertEqual(bias.dtype, torch.float32, name) + expected = 8.5 + 0.02 * torch.arange(bias.numel(), dtype=torch.float32) + torch.testing.assert_close(bias, expected.to(bias.device), rtol=0, atol=0) + gates = [p for n, p in model.named_parameters() if n.endswith("mlp.gate.weight")] + self.assertTrue(gates) + for gate in gates: + self.assertEqual(gate.dtype, torch.float32) + + # Under bf16 autocast, as in training, the router still computes in float32 + mlp = model.model.layers[0].mlp + hidden_states = torch.randn(4, config.hidden_size, dtype=torch.bfloat16) + with torch.autocast("cpu", dtype=torch.bfloat16): + router_logits, _, _ = mlp.gate(hidden_states, mlp.e_score_correction_bias) + self.assertEqual(router_logits.dtype, torch.float32) + @slow @require_torch diff --git a/tests/models/minimax_m3_vl/test_modeling_minimax_m3_vl.py b/tests/models/minimax_m3_vl/test_modeling_minimax_m3_vl.py index 482bea6078ee..3242fee35f62 100644 --- a/tests/models/minimax_m3_vl/test_modeling_minimax_m3_vl.py +++ b/tests/models/minimax_m3_vl/test_modeling_minimax_m3_vl.py @@ -13,6 +13,7 @@ # limitations under the License. """Testing suite for the PyTorch MiniMax-M3-VL model.""" +import tempfile import unittest from parameterized import parameterized @@ -377,6 +378,35 @@ def test_three_axes_frequency_ladder(self, head_dim, axis_dim): torch.testing.assert_close(cosine, angles.cos()) torch.testing.assert_close(sine, angles.sin()) + def test_router_and_correction_bias_kept_in_float32(self): + # The checkpoints store the router weight and its correction bias in float32. The bias has values of + # 4.9-7.9 that differ by ~0.05 between experts, which bfloat16 would collapse to a few distinct values. + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + model = MiniMaxM3SparseForConditionalGeneration(config) + biases = [b for n, b in model.named_buffers() if n.endswith("e_score_correction_bias")] + self.assertTrue(biases) + for bias in biases: + bias.copy_(8.5 + 0.02 * torch.arange(bias.numel(), dtype=torch.float32)) + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model = MiniMaxM3SparseForConditionalGeneration.from_pretrained(tmpdirname, dtype=torch.bfloat16) + for name, bias in model.named_buffers(): + if name.endswith("e_score_correction_bias"): + self.assertEqual(bias.dtype, torch.float32, name) + expected = 8.5 + 0.02 * torch.arange(bias.numel(), dtype=torch.float32) + torch.testing.assert_close(bias, expected.to(bias.device), rtol=0, atol=0) + gates = [p for n, p in model.named_parameters() if n.endswith("mlp.gate.weight")] + self.assertTrue(gates) + for gate in gates: + self.assertEqual(gate.dtype, torch.float32) + + # Under bf16 autocast, as in training, the router still computes in float32 + router = next(m for m in model.modules() if type(m).__name__ == "MiniMaxM3VLTopKRouter") + hidden_states = torch.randn(4, router.hidden_dim, dtype=torch.bfloat16) + with torch.autocast("cpu", dtype=torch.bfloat16): + router_logits, _, _ = router(hidden_states) + self.assertEqual(router_logits.dtype, torch.float32) + @slow @require_torch diff --git a/tests/models/step3p7/test_modeling_step3p7.py b/tests/models/step3p7/test_modeling_step3p7.py index 3ab767b252c9..0ef32e43c342 100644 --- a/tests/models/step3p7/test_modeling_step3p7.py +++ b/tests/models/step3p7/test_modeling_step3p7.py @@ -14,6 +14,7 @@ """Testing suite for the PyTorch Step3p7 model.""" import re +import tempfile import unittest from unittest.mock import patch @@ -189,6 +190,25 @@ def _image_features_get_expected_num_attentions(self, model_tester=None): model_tester = self.model_tester return model_tester.get_vision_config().num_hidden_layers + def test_e_score_correction_bias_kept_in_float32(self): + # Step-3.7-Flash checkpoints store the routing bias (`router_bias`) in float32, with + # values of 5.8-8.7 that differ by ~0.05 between experts. In bfloat16, experts' biases would collapse to a few + # distinct values, so loading in bfloat16 must keep them in float32. + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + model = Step3p7ForConditionalGeneration(config) + biases = [b for n, b in model.named_buffers() if n.endswith("e_score_correction_bias")] + self.assertTrue(biases) + for bias in biases: + bias.copy_(8.5 + 0.02 * torch.arange(bias.numel(), dtype=torch.float32)) + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model = Step3p7ForConditionalGeneration.from_pretrained(tmpdirname, dtype=torch.bfloat16) + for name, bias in model.named_buffers(): + if name.endswith("e_score_correction_bias"): + self.assertEqual(bias.dtype, torch.float32, name) + expected = 8.5 + 0.02 * torch.arange(bias.numel(), dtype=torch.float32) + torch.testing.assert_close(bias, expected.to(bias.device), rtol=0, atol=0) + @require_torch @slow