Skip to content

[MoE] MiniMax-M2/M2.1 calibration follow-up#2335

Open
LudovicoYIN wants to merge 10 commits intovllm-project:mainfrom
LudovicoYIN:moe/minimax-m2-calibration-followup
Open

[MoE] MiniMax-M2/M2.1 calibration follow-up#2335
LudovicoYIN wants to merge 10 commits intovllm-project:mainfrom
LudovicoYIN:moe/minimax-m2-calibration-followup

Conversation

@LudovicoYIN
Copy link
Contributor

@LudovicoYIN LudovicoYIN commented Feb 6, 2026

Summary

Add initial MiniMax-M2 / M2.1 support in llm-compressor.

Changes

  • Add MiniMax-M2 MoE calibration integration.
  • Add MiniMax-M2 calibration tests.
  • Add MiniMax-M2 quantization example.

Files

  • src/llmcompressor/modeling/minimax_m2.py
  • tests/llmcompressor/modeling/test_calib_minimax_m2.py
  • examples/quantizing_moe/minimax_m2_example.py

Test Plan

  • CADENCE=weekly /root/miniforge3/envs/llm-compressor/bin/python -m pytest tests/llmcompressor/modeling/test_calib_minimax_m2.py -k minimax -rs
  • /root/miniforge3/envs/llm-compressor/bin/python examples/quantizing_moe/minimax_m2_example.py

Signed-off-by: LudovicoYIN <hankeyin@gmail.com>
Signed-off-by: LudovicoYIN <hankeyin@gmail.com>
Signed-off-by: LudovicoYIN <hankeyin@gmail.com>
@github-actions
Copy link

github-actions bot commented Feb 6, 2026

👋 Hi! Thank you for contributing to llm-compressor. Please add the ready label when the PR is ready for review.

Note: This is required to complete the testing suite, please only add the label once the PR is code complete and local testing has been performed.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @LudovicoYIN, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request integrates initial support for MiniMax-M2 and M2.1 models into the llm-compressor framework. It provides the necessary calibration logic for Mixture-of-Experts (MoE) layers, enabling efficient quantization workflows for these models. The changes include a dedicated calibration module, an illustrative example for AWQ quantization, and corresponding tests to ensure functionality and compatibility.

Highlights

  • MiniMax-M2/M2.1 MoE Calibration Module: A new CalibrationMiniMaxM2SparseMoeBlock module has been introduced to enable proper expert calibration for MiniMax-M2 and M2.1 models within the llm-compressor framework. This module ensures all experts are calibrated effectively.
  • AWQ Quantization Example for MiniMax-M2: An example script (minimax_m2_example.py) has been added, demonstrating how to perform AWQ quantization on MiniMax-M2 models. It includes specific configurations for handling MoE layers and setting sequential_targets.
  • Comprehensive Unit Tests: New unit tests (test_calib_minimax_m2.py) were added to verify the correct functionality of the CalibrationMiniMaxM2SparseMoeBlock, ensuring that all experts are properly engaged during calibration and that the module behaves as expected under different calibration settings.
  • Transformers Compatibility Improvement: The src/llmcompressor/utils/dev.py file was updated with a try-except block for importing TORCH_INIT_FUNCTIONS, enhancing compatibility with different versions of the transformers library.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • examples/quantizing_moe/minimax_m2_example.py
    • Added a new example script to demonstrate AWQ quantization for MiniMax-M2 models.
    • Includes steps for loading the model and tokenizer, preparing a calibration dataset, and configuring the AWQModifier with specific ignore patterns for MoE gate layers and the output head.
    • Explicitly sets sequential_targets=['MiniMaxM2DecoderLayer'] to address MiniMax-M2's unique architecture.
  • src/llmcompressor/modeling/init.py
    • Added a conditional import for CalibrationMiniMaxM2SparseMoeBlock from the new minimax_m2 module, wrapped in a try-except block for transformers compatibility.
  • src/llmcompressor/modeling/minimax_m2.py
    • Added a new module defining CalibrationMiniMaxM2SparseMoeBlock.
    • This class extends MoECalibrationModule and provides a calibration-specific forward pass for MiniMaxM2SparseMoeBlock.
    • Includes logic to ensure all experts are executed on all tokens during calibration when calibrate_all_experts=True, while maintaining routed-token weighting for the final output.
  • src/llmcompressor/utils/dev.py
    • Modified the import statement for TORCH_INIT_FUNCTIONS to include a try-except block, accommodating potential changes in transformers versions (e.g., transformers>=5).
  • tests/llmcompressor/modeling/test_calib_minimax_m2.py
    • Added a new test file dedicated to MiniMax-M2 calibration.
    • Includes test_calib_replace_minimax_m2_all_experts to verify that all experts are run during calibration when calibrate_all_experts is enabled.
    • Contains test_calib_minimax_m2_module to check the functional correctness of the calibration module.
    • Features test_calib_minimax_m2_uses_upstream_experts_when_not_calibrating_all to confirm that the original expert forward pass is used when calibrate_all_experts is false.
Activity
  • No human activity (comments, reviews, etc.) has been recorded on this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@mergify mergify bot added the documentation Improvements or additions to documentation label Feb 6, 2026
Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request adds support for MiniMax-M2/M2.1 models to llm-compressor, including a new calibration module, tests, and an example. The changes are well-structured and the new functionality is thoroughly tested. The implementation of the calibration module is correct, ensuring that all experts are exercised during calibration while maintaining numerical equivalence. I have a couple of suggestions for minor code improvements to enhance readability and remove a redundant type conversion.

Comment on lines 46 to 108
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
"""
Forward pass with optional all-expert calibration mode.

- `calibrate_all_experts=False`: use upstream expert execution path.
- `calibrate_all_experts=True`: execute every expert on all tokens,
then aggregate only routed-token outputs.
"""
batch_size, sequence_length, hidden_dim = hidden_states.shape
if self.training and self.jitter_noise > 0:
hidden_states *= torch.empty_like(hidden_states).uniform_(
1.0 - self.jitter_noise, 1.0 + self.jitter_noise
)
hidden_states = hidden_states.view(-1, hidden_dim)
_router_logits, top_k_weights, top_k_index = self.gate(
hidden_states, self.e_score_correction_bias
)

if not self.calibrate_all_experts:
final_hidden_states = self.experts(
hidden_states, top_k_index, top_k_weights
)
return final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)

# Reimplementing MiniMaxM2Experts.forward only when calibrating all experts.
final_hidden_states = torch.zeros(
(batch_size * sequence_length, hidden_dim),
dtype=hidden_states.dtype,
device=hidden_states.device,
)
expert_mask = F.one_hot(top_k_index, num_classes=self.experts.num_experts)
expert_mask = expert_mask.permute(2, 1, 0)

for expert_idx in range(self.experts.num_experts):
top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
has_tokens = token_idx.numel() > 0

# Run all tokens through the expert to gather stats.
gate, up = F.linear(
hidden_states, self.experts.gate_up_proj[expert_idx]
).chunk(2, dim=-1)
expert_out_full = self.experts.act_fn(gate) * up
expert_out_full = F.linear(
expert_out_full, self.experts.down_proj[expert_idx]
)
if not has_tokens:
continue
expert_out = expert_out_full[token_idx]

expert_weights = top_k_weights[token_idx, top_k_pos]
weighted_output = expert_out * expert_weights.unsqueeze(-1)
final_hidden_states.index_add_(
0,
token_idx,
weighted_output.to(hidden_states.dtype),
)

final_hidden_states = final_hidden_states.reshape(
batch_size, sequence_length, hidden_dim
)

return final_hidden_states

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The forward method is quite long and contains complex logic, especially for the calibrate_all_experts=True case. To improve readability and maintainability, consider extracting the calibration logic (lines 70-101) into a separate private helper method, e.g., _forward_calibrate_all_experts. The main forward method would then act as a clearer dispatcher between the standard and calibration forward paths.

final_hidden_states.index_add_(
0,
token_idx,
weighted_output.to(hidden_states.dtype),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The weighted_output tensor should already have the same dtype as hidden_states, as it's derived from operations on tensors that originate from hidden_states and top_k_weights. Therefore, the .to(hidden_states.dtype) call appears to be redundant and can be removed for a minor cleanup.

Suggested change
weighted_output.to(hidden_states.dtype),
weighted_output,

Copy link
Collaborator

@dsikka dsikka left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank for your contribution. I need to take a closer look into the modeling code but everything else looks good. Were you able to generate a checkpoint with the example?

Signed-off-by: LudovicoYIN <hankeyin@gmail.com>
@LudovicoYIN
Copy link
Contributor Author

Thank for your contribution. I need to take a closer look into the modeling code but everything else looks good. Were you able to generate a checkpoint with the example?

Thanks for your review @dsikka . I'm generating a checkpoint and will upload it to Hugging Face soon.

One question: MiniMax-M2 uses FP8 weights by default. I've converted it to BF16 using model = AutoModelForCausalLM.from_pretrained(model_id, dtype=torch.bfloat16). Would this approach be acceptable?

@LudovicoYIN LudovicoYIN marked this pull request as draft February 8, 2026 15:45
Signed-off-by: LudovicoYIN <hankeyin@gmail.com>
@dsikka
Copy link
Collaborator

dsikka commented Feb 9, 2026

Thank for your contribution. I need to take a closer look into the modeling code but everything else looks good. Were you able to generate a checkpoint with the example?

Thanks for your review @dsikka . I'm generating a checkpoint and will upload it to Hugging Face soon.

One question: MiniMax-M2 uses FP8 weights by default. I've converted it to BF16 using model = AutoModelForCausalLM.from_pretrained(model_id, dtype=torch.bfloat16). Would this approach be acceptable?

I think it may automatically decompress the model to bfloat16 without explicitly requiring the dtype (I believe this is currently the case for gpt-oss, for example) but you may have to test. But either way, this is fine to do as long is in bfloat16 for quantization

self.num_experts = config.num_local_experts
self.top_k = original.top_k
# Use unbound function so this module's buffers are used.
self._route_tokens_to_experts = type(original).route_tokens_to_experts
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In my initial commits, I followed the Transformers 5.x MiniMax-M2 structure, where expert weights are packed as nn.Parameter tensors (e.g., gate_up_proj / down_proj) instead of explicit nn.Linear layers (w1/w2/w3).

However, after validating quantization end-to-end, I found that the packed representation doesn't align well with our current AWQ module matching (which targets Linear modules), leading to incomplete expert weight coverage.

So, in subsequent commits, I switched to the original MiniMax structure where experts are explicitly defined as w1/w2/w3 nn.Linear layers (https://huggingface.co/MiniMaxAI/MiniMax-M2.1/blob/main/modeling_minimax_m2.py).

@LudovicoYIN
Copy link
Contributor Author

LudovicoYIN commented Feb 11, 2026

Hi @dsikka — quick clarification on why I changed direction in this follow-up.

In the initial implementation I followed the Transformers 5.x MiniMax-M2 structure, where expert weights are stored as packed nn.Parameter tensors (e.g. gate_up_proj / down_proj) instead of explicit per-expert nn.Linear modules (w1/w2/w3).

llm-compressor AWQ matching is currently module-based (e.g. Linear modules / module regex), and the calibration flow expects module-level weight semantics. Because of this, the packed-parameter structure leads to incomplete expert weight matching and expert weights are skipped during quantization.

The original MiniMax repo exposes experts as explicit linear layers, which aligns with existing AWQ mappings and produces stable end-to-end quantization. For now, I converged to that structure to ensure the workflow is functional and verifiable (in transformers==4.57.6). https://huggingface.co/MiniMaxAI/MiniMax-M2.1/blob/main/modeling_minimax_m2.py

I also experimented with forcing a structural rewrite on the Transformers 5.x path (is_permanent=True) to convert experts into explicit Linear-style modules. This fixes quantization matching, but it changes the saved model structure and vLLM fails to load the checkpoint due to MiniMax architecture mismatch.

@LudovicoYIN
Copy link
Contributor Author

hi @dsikka
MiniMax-M2 adaptation is now complete.

  • Integrated MiniMax-M2 using the official HF repo/modeling path (MiniMaxAI/MiniMax-M2, trust_remote_code=True).
  • MiniMax calibration tests are passing.
  • MiniMax quantization example has been run successfully end-to-end.
  • Quantized artifacts have been uploaded to Hugging Face: https://huggingface.co/ludovicoYIN/MiniMax-M2-BF16-W4A16
  • Current environment uses transformers==4.57.6.

@LudovicoYIN LudovicoYIN marked this pull request as ready for review February 13, 2026 14:01
@HDCharles HDCharles added the ready When a PR is ready for review label Feb 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation ready When a PR is ready for review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

Comments