Qwen3 moe optimisations#396
Conversation
Summary of ChangesHello @Datta0, 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 delivers substantial performance enhancements for fine-tuning Qwen3 and Qwen3-VL Mixture-of-Experts models. It achieves this by integrating advanced grouped General Matrix Multiply (GEMM) kernels, which are critical for accelerating the sparse computations inherent in MoE architectures. The implementation intelligently selects between native PyTorch grouped GEMM or custom Triton kernels based on availability, ensuring optimal performance while providing a robust fallback mechanism. This update is particularly geared towards compatibility and performance with upcoming Transformers v5 changes. 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. 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.
💡 Codex Review
Here are some automated review suggestions for this pull request.
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| # Force grouped mm usage if available to avoid fallback entirely | ||
| if hasattr(torch, "_grouped_mm"): | ||
| _TORCH_GROUPED_MM_AVAILABLE = True | ||
|
|
||
| if not _TORCH_GROUPED_MM_AVAILABLE and not use_grouped_gemm: |
There was a problem hiding this comment.
Avoid unbound grouped_mm flag when torch lacks support
In patch_qwen3_vl_moe the _TORCH_GROUPED_MM_AVAILABLE flag is assigned inside if hasattr(torch, "_grouped_mm"): without a global, so Python treats it as a local; when running on torch versions without _grouped_mm, the subsequent if not _TORCH_GROUPED_MM_AVAILABLE and not use_grouped_gemm: reads that uninitialized local and raises UnboundLocalError before the slow-path fallback can run. This crashes patching on older torch builds instead of falling back; the flag needs to be read from the imported value or declared global before assignment.
Useful? React with 👍 / 👎.
| if self.down_proj.shape[1] == inter.shape[-1]: | ||
| w2 = self.down_proj | ||
| else: | ||
| w2 = self.down_proj.transpose(-2, -1) |
There was a problem hiding this comment.
Fix undefined variable in Triton grouped GEMM down projection
In the Triton MoE path forward_triton_grouped_gemm, the down-projection weight selection uses if self.down_proj.shape[1] == inter.shape[-1]: but the tensor is named intermediate above, so every call to this code raises NameError as soon as grouped GEMM is attempted. This makes the Triton fast path unusable; the condition should reference the computed intermediate tensor.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Code Review
This pull request introduces significant optimizations for Mixture-of-Experts (MoE) forward passes in Qwen3 and Qwen3-VL models by integrating grouped GEMM kernels. A new file, moe_utils.py, was added to provide common utilities such as a persistent Triton allocator, availability checks for grouped GEMM, and implementations for both native PyTorch _grouped_mm and Triton-based grouped GEMM. The qwen3_moe.py and qwen3_vl_moe.py files were updated (or created) to leverage these new grouped GEMM kernels, with a fallback to a loop-based approach if kernels are unavailable, and handling different Transformers library versions. Additionally, compiler.py was updated to include Qwen3MoeExperts in its patching logic and fix a minor bug in n_items retrieval, and __init__.py was updated to import the new Qwen3-VL MoE patch. Review comments highlight several critical issues, including multiple indentation errors in moe_utils.py that would cause IndentationErrors, missing initialization of batch_size, sequence_length, and hidden_dim in qwen3_moe.py leading to runtime errors, redundant code and further indentation issues in qwen3_moe.py's conditional logic, and a request to clean up unused imports in qwen3_moe.py.
| # # we cast back to the input dtype | ||
| # routing_weights = routing_weights.to(hidden_states.dtype) | ||
| # router_scores = torch.zeros_like(router_logits, dtype = hidden_states.dtype).scatter_(1, selected_experts, routing_weights) | ||
| router_scores, selected_experts, router_logits = router_forward(self, hidden_states) |
There was a problem hiding this comment.
This function is missing the initialization of batch_size, sequence_length, and hidden_dim, which are used later. Also, hidden_states is not reshaped to 2D before being used. This will cause a runtime error.
batch_size, sequence_length, hidden_dim = hidden_states.shape
hidden_states = hidden_states.view(-1, hidden_dim)
router_scores, selected_experts, router_logits = router_forward(self, hidden_states)034aa21 to
ec20171
Compare
|
/gemini review |
This reverts commit ed8633a.
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces significant optimizations for Qwen3 MoE models, focusing on performance enhancements through grouped GEMM kernels and 4-bit quantization. It effectively integrates both PyTorch native _grouped_mm and Triton-based kernels for faster forward passes, and extends bitsandbytes-style 4-bit quantization to MoE experts. The changes also ensure compatibility with different transformers versions (v4 vs v5) and improve robustness in the compiler and vLLM integration. The addition of vllm_config and lora_request_id parameters in vLLM-related files enhances flexibility for LoRA management. Overall, these changes are well-structured and aim to provide substantial speed and memory usage improvements for Qwen3 fine-tuning.
|
Closing in favor of #450 |
This PR extensively improves Qwen3 fine tuning performance but is reliant on some changes that are integral to transformers V5.
PS: If we want to use triton kernels as mentioned here, we need the changes in unsloth
Note that along with speed improvements, I also observed memory usage improvements wherein the grouped_mm was able to do a 8192 sequence length fine-tuning on H100 in 16-bit LoRA, but the same was not true for pure PyTorch code which threw OOMs
Transformers v4 unsloth latest release

Transformers v5 + pure pytorch

Transformers v5 + grouped_mm

Transformers v5 + unsloth triton kernels
