refactor(models): run MiniMax-M3 on the shared decoder layer (#3205)

## Summary

`MiniMaxM3DecoderLayer.forward` was a copy of
`BaseDecoderLayer.forward`. The layer now subclasses `BaseDecoderLayer`,
as the Llama, gpt-oss and Qwen3 layers do, and only builds what is its
own: Gemma RMSNorms, its attention, and per layer either the MoE block
(`block_sparse_moe`, on the shared alt stream) or the dense SwiGLU-OAI
MLP. `is_moe_layer` and `is_prev_moe_layer` come from `mlp_layer_types`,
so a MoE layer after a dense layer opens with the dense layout, as
before ([#3192](https://github.com/lightseekorg/tokenspeed/pull/3192)
added `is_prev_moe_layer`).

The layer makes the same CommManager calls in the same order.

## Test Plan

- Greedy tokens and logprobs of single requests (10 × 128 tokens, and
one 1.3k-token prompt) are identical to main on MiniMax-M3-NVFP4 at TP1
(4 layers, dummy weights), TP4 with and without fusion, and DP2 + TP2 +
EP4.
- 16 concurrent requests at TP4: main differs from itself between runs
in 15 of them, and so does this branch, while two of four
main-versus-branch pairs of runs match exactly.
- A new MiniMax-M3 test builds a dense, MoE, MoE, dense stack and checks
each layer's MoE and previous-layer MoE flags; it fails without the
`is_prev_moe_layer` override and when the override always returns
`False`.
- MiniMax-M3, multimodal warmup, ModelOpt mixed config, attention
backend and aux capture tests: 138 passed.

---------

Signed-off-by: Nicolas Perrin <nperrin.ai@gmail.com>
This commit is contained in:
Nicolas Perrin
2026-11-08 21:49:03 -05:00
committed by GitHub
parent 578b9c80df
commit 1d4d48ab4e
2 changed files with 76 additions and 88 deletions
+52 -87
View File
@@ -37,7 +37,6 @@ from tokenspeed.runtime.configs.minimax_m3_config import (
MiniMaxM3Config,
MiniMaxM3VisionConfig,
)
from tokenspeed.runtime.distributed.comm_manager import CommManager
from tokenspeed.runtime.distributed.mapping import Mapping
from tokenspeed.runtime.distributed.utils import divide
from tokenspeed.runtime.execution.context import ForwardContext
@@ -74,7 +73,11 @@ from tokenspeed.runtime.layers.quantization.mxfp8_nvfp4 import (
from tokenspeed.runtime.layers.rotary_embedding import get_rope
from tokenspeed.runtime.layers.vocab_parallel_embedding import VocabParallelEmbedding
from tokenspeed.runtime.model_loader.weight_utils import default_weight_loader
from tokenspeed.runtime.models.base import BaseCausalLM, BaseTransformerModel
from tokenspeed.runtime.models.base import (
BaseCausalLM,
BaseDecoderLayer,
BaseTransformerModel,
)
from tokenspeed.runtime.models.utils import validate_attention_partition
from tokenspeed.runtime.moe.expert_location import ModelConfigForExpertLocation
from tokenspeed.runtime.multimodal.embedder import (
@@ -568,7 +571,7 @@ class MiniMaxM3Attention(nn.Module):
return output
class MiniMaxM3DecoderLayer(nn.Module):
class MiniMaxM3DecoderLayer(BaseDecoderLayer[MiniMaxM3VLTextConfig]):
"""Decoder layer selected as dense or MoE by ``mlp_layer_types``."""
def __init__(
@@ -580,100 +583,62 @@ class MiniMaxM3DecoderLayer(nn.Module):
prefix: str = "",
alt_stream: torch.cuda.Stream | None = None,
) -> None:
super().__init__()
self.mapping = mapping
self.layer_id = layer_id
self.is_moe_layer = config.mlp_layer_types[layer_id] == "sparse"
previous_is_moe_layer = (
layer_id > 0 and config.mlp_layer_types[layer_id - 1] == "sparse"
# Set before the base constructor, whose resolve_mlp() reads it.
self.alt_stream = alt_stream
super().__init__(
config=config,
layer_id=layer_id,
mapping=mapping,
quant_config=quant_config,
prefix=prefix,
)
self.input_layernorm = GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm = GemmaRMSNorm(
config.hidden_size, eps=config.rms_norm_eps
@property
def is_moe_layer(self) -> bool:
return self.config.mlp_layer_types[self.layer_id] == "sparse"
@property
def is_prev_moe_layer(self) -> bool:
return (
self.layer_id > 0
and self.config.mlp_layer_types[self.layer_id - 1] == "sparse"
)
self.self_attn = MiniMaxM3Attention(
config=config,
mapping=mapping,
layer_id=layer_id,
quant_config=quant_config,
def resolve_norm(self) -> nn.Module:
return GemmaRMSNorm(self.config.hidden_size, eps=self.config.rms_norm_eps)
def resolve_attn(self, prefix: str) -> nn.Module:
return MiniMaxM3Attention(
config=self.config,
mapping=self.mapping,
layer_id=self.layer_id,
quant_config=self.quant_config,
prefix=add_prefix("self_attn", prefix),
)
def resolve_mlp(self, prefix: str) -> nn.Module:
if self.is_moe_layer:
self.mlp = MiniMaxM3SparseMoeBlock(
config=config,
mapping=mapping,
quant_config=quant_config,
layer_index=layer_id,
return MiniMaxM3SparseMoeBlock(
config=self.config,
mapping=self.mapping,
quant_config=self.quant_config,
layer_index=self.layer_id,
prefix=add_prefix("block_sparse_moe", prefix),
alt_stream=alt_stream,
alt_stream=self.alt_stream,
)
else:
self.mlp = GatedMLP.tensor_parallel(
hidden_size=config.hidden_size,
intermediate_size=config.dense_intermediate_size,
activation=SwigluOAI(config.swiglu_alpha, config.swiglu_limit),
tp_rank=mapping.dense.tp_rank,
tp_size=mapping.dense.tp_size,
tp_group=mapping.dense.tp_group,
reduce_results=False,
fusions=(),
quant_config=quant_config,
prefix=add_prefix("mlp", prefix),
)
self.comm_manager = CommManager(
mapping=mapping,
layer_id=layer_id,
is_moe=self.is_moe_layer,
prev_is_moe=previous_is_moe_layer,
dense_batch_invariant=False,
input_layernorm=self.input_layernorm,
post_attn_layernorm=self.post_attention_layernorm,
query_sharded=False,
return GatedMLP.tensor_parallel(
hidden_size=self.config.hidden_size,
intermediate_size=self.config.dense_intermediate_size,
activation=SwigluOAI(self.config.swiglu_alpha, self.config.swiglu_limit),
tp_rank=self.mapping.dense.tp_rank,
tp_size=self.mapping.dense.tp_size,
tp_group=self.mapping.dense.tp_group,
reduce_results=False,
fusions=(),
quant_config=self.quant_config,
prefix=add_prefix("mlp", prefix),
)
def forward(
self,
positions: torch.Tensor,
hidden_states: torch.Tensor,
ctx: ForwardContext,
residual: torch.Tensor | None,
aux_hidden_states: list[torch.Tensor] | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
num_global_tokens, max_num_tokens_per_gpu = self.comm_manager.get_num_tokens(
ctx
)
if not ctx.forward_mode.is_idle():
hidden_states, residual = self.comm_manager.input_reduce_norm(
hidden_states, residual
)
if aux_hidden_states is not None:
aux_hidden_states.append(
self.comm_manager.gather_residual(residual, ctx).clone()
)
hidden_states = self.comm_manager.pre_attn_comm(hidden_states, ctx)
hidden_states = self.self_attn(
positions=positions,
hidden_states=hidden_states,
ctx=ctx,
)
hidden_states, residual = self.comm_manager.post_attn_reduce_norm(
hidden_states, residual, ctx
)
hidden_states = self.comm_manager.pre_mlp_comm(hidden_states, ctx)
if self.is_moe_layer:
hidden_states = self.mlp(
hidden_states, num_global_tokens, max_num_tokens_per_gpu
)
else:
hidden_states = self.mlp(hidden_states)
hidden_states, residual = self.comm_manager.post_mlp_fused(
hidden_states, residual, ctx
)
return hidden_states, residual
class MiniMaxM3Model(BaseTransformerModel):
"""MiniMax-M3 decoder-only text backbone."""
+24 -1
View File
@@ -112,6 +112,7 @@ def _build_model(
*,
quant_config: Mxfp8Config | None = None,
is_multimodal_active: bool = False,
config: MiniMaxM3Config | None = None,
) -> MiniMaxM3SparseForConditionalGeneration:
mapping = _tp4_mapping()
monkeypatch.setitem(global_server_args_dict, "ep_num_redundant_experts", 0)
@@ -124,7 +125,7 @@ def _build_model(
try:
with torch.device("meta"):
return MiniMaxM3SparseForConditionalGeneration(
_tiny_config(),
_tiny_config() if config is None else config,
mapping,
quant_config=quant_config,
is_multimodal_active=is_multimodal_active,
@@ -259,6 +260,28 @@ def test_minimax_m3_tp4_meta_layout_and_loader(monkeypatch: pytest.MonkeyPatch)
}
def test_minimax_m3_layers_open_on_the_previous_layers_layout(
monkeypatch: pytest.MonkeyPatch,
) -> None:
config = _tiny_config()
config.text_config.mlp_layer_types = ["dense", "sparse", "sparse", "dense"]
layers = _build_model(monkeypatch, config=config).model.layers
assert [layer.comm_manager.is_moe for layer in layers] == [
False,
True,
True,
False,
]
assert [layer.comm_manager.prev_is_moe for layer in layers] == [
False,
False,
True,
True,
]
def _mixed_precision_config() -> "ModelOptMixedConfig":
from tokenspeed.runtime.layers.quantization.modelopt_mixed import (
ModelOptMixedConfig,