Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
8 changes: 6 additions & 2 deletions src/transformers/models/minimax_m2/modeling_minimax_m2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down Expand Up @@ -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):
Expand Down
9 changes: 7 additions & 2 deletions src/transformers/models/minimax_m2/modular_minimax_m2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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"]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
7 changes: 5 additions & 2 deletions src/transformers/models/step3p7/modeling_step3p7.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions src/transformers/models/step3p7/modular_step3p7.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
18 changes: 18 additions & 0 deletions tests/models/longcat_flash/test_modeling_longcat_flash.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
30 changes: 30 additions & 0 deletions tests/models/minimax_m2/test_modeling_minimax_m2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
30 changes: 30 additions & 0 deletions tests/models/minimax_m3_vl/test_modeling_minimax_m3_vl.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
20 changes: 20 additions & 0 deletions tests/models/step3p7/test_modeling_step3p7.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"""Testing suite for the PyTorch Step3p7 model."""

import re
import tempfile
import unittest
from unittest.mock import patch

Expand Down Expand Up @@ -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
Expand Down
Loading