[MoE] MiniMax-M2/M2.1 calibration follow-up#2335
[MoE] MiniMax-M2/M2.1 calibration follow-up#2335LudovicoYIN wants to merge 10 commits intovllm-project:mainfrom
Conversation
Signed-off-by: LudovicoYIN <hankeyin@gmail.com>
Signed-off-by: LudovicoYIN <hankeyin@gmail.com>
Signed-off-by: LudovicoYIN <hankeyin@gmail.com>
|
👋 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. |
Summary of ChangesHello @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 Highlights
🧠 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
Activity
Using Gemini Code AssistThe 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
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 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
|
There was a problem hiding this comment.
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.
| 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 | ||
|
|
There was a problem hiding this comment.
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), |
There was a problem hiding this comment.
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.
| weighted_output.to(hidden_states.dtype), | |
| weighted_output, |
dsikka
left a comment
There was a problem hiding this comment.
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>
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? |
Signed-off-by: LudovicoYIN <hankeyin@gmail.com>
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 |
There was a problem hiding this comment.
There was a problem hiding this comment.
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).
|
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 llm-compressor AWQ matching is currently module-based (e.g. 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 ( |
Signed-off-by: LudovicoYIN <hankeyin@gmail.com>
Signed-off-by: LudovicoYIN <hankeyin@gmail.com>
|
hi @dsikka
|
Summary
Add initial MiniMax-M2 / M2.1 support in llm-compressor.
Changes
Files
src/llmcompressor/modeling/minimax_m2.pytests/llmcompressor/modeling/test_calib_minimax_m2.pyexamples/quantizing_moe/minimax_m2_example.pyTest 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