Skip to content
Open
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
6 changes: 4 additions & 2 deletions src/transformers/models/step3p7/modeling_step3p7.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
from ...processing_utils import Unpack
from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging, torch_compilable_check, torch_int
from ...utils.deprecation import deprecate_kwarg
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 @@ -593,7 +593,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):
router_logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32))
# 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
16 changes: 14 additions & 2 deletions src/transformers/models/step3p7/modular_step3p7.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import torch
import torch.nn as nn
import torch.nn.functional as F
from huggingface_hub.dataclasses import strict

from ... import initialization as init
Expand All @@ -40,7 +41,7 @@
torch_int,
)
from ...utils.deprecation import deprecate_kwarg
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 ..clip.modeling_clip import CLIPAttention
Expand Down Expand Up @@ -863,7 +864,18 @@ def _apply_gate(self, gate_up: torch.Tensor) -> torch.Tensor:


class Step3p7TopKRouter(MiniMaxM3VLTopKRouter):
pass
def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
hidden_states = hidden_states.reshape(-1, self.hidden_dim)
device_type = hidden_states.device.type if isinstance(hidden_states.device.type, str) else "cpu"
with maybe_autocast(device_type=device_type, enabled=False):
router_logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32))
# Sigmoid scoring (not softmax), as in M2.
routing_weights = F.sigmoid(router_logits.float())
scores_for_choice = routing_weights + self.e_score_correction_bias
_, top_k_index = torch.topk(scores_for_choice, self.top_k, dim=-1, sorted=False)
top_k_weights = routing_weights.gather(1, top_k_index)
top_k_weights /= top_k_weights.sum(dim=-1, keepdim=True)
return router_logits, top_k_weights, top_k_index


class Step3p7SparseMoeBlock(MiniMaxM3VLSparseMoeBlock):
Expand Down
26 changes: 25 additions & 1 deletion tests/models/step3p7/test_modeling_step3p7.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from transformers.testing_utils import (
cleanup,
require_torch,
require_torch_bf16,
slow,
torch_device,
)
Expand All @@ -36,7 +37,8 @@
if is_torch_available():
import torch

from transformers import Step3p7ForConditionalGeneration, Step3p7Model
from transformers import Step3p7ForConditionalGeneration, Step3p7Model, Step3p7TextConfig
from transformers.models.step3p7.modeling_step3p7 import Step3p7TopKRouter


_REAL_CHECKPOINT = "stepfun-ai/Step-3.7-Flash"
Expand Down Expand Up @@ -151,6 +153,28 @@ def _image_features_get_expected_num_attentions(self, model_tester=None):
model_tester = self.model_tester
return model_tester.get_config().vision_config.num_hidden_layers

@require_torch_bf16
def test_router_computes_in_float32(self):
config = Step3p7TextConfig(hidden_size=128, n_routed_experts=288, num_experts_per_tok=8)
torch.manual_seed(0)
router = Step3p7TopKRouter(config)
torch.nn.init.normal_(router.weight, std=0.02)
router = router.bfloat16().to(torch_device).eval()
reference = Step3p7TopKRouter(config).float().to(torch_device).eval()
with torch.no_grad():
reference.weight.copy_(router.weight)
reference.e_score_correction_bias.copy_(router.e_score_correction_bias)
hidden_states = torch.randn(1024, config.hidden_size, dtype=torch.bfloat16, device=torch_device)

for use_autocast in (False, True):
with self.subTest(use_autocast=use_autocast), torch.no_grad():
with torch.autocast(torch_device, dtype=torch.bfloat16, enabled=use_autocast):
actual = router(hidden_states)
expected = reference(hidden_states.float())
self.assertEqual(actual[0].dtype, torch.float32)
for actual_tensor, expected_tensor in zip(actual, expected):
torch.testing.assert_close(actual_tensor, expected_tensor, rtol=0, atol=0)


@require_torch
@slow
Expand Down
Loading