Skip to content

Qwen3 moe optimisations#396

Closed
Datta0 wants to merge 54 commits into
unslothai:mainfrom
Datta0:qwen3_moe_kernels
Closed

Qwen3 moe optimisations#396
Datta0 wants to merge 54 commits into
unslothai:mainfrom
Datta0:qwen3_moe_kernels

Conversation

@Datta0

@Datta0 Datta0 commented Dec 29, 2025

Copy link
Copy Markdown
Collaborator

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

image

Transformers v4 unsloth latest release
image

Transformers v5 + pure pytorch
image

Transformers v5 + grouped_mm
image

Transformers v5 + unsloth triton kernels
image

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @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

  • Performance Optimization for Qwen3 MoE: Introduces highly optimized grouped GEMM (General Matrix Multiply) kernels for Qwen3 and Qwen3-VL Mixture-of-Experts (MoE) models, significantly improving fine-tuning performance.
  • Leveraging Advanced GEMM Techniques: Implements conditional logic to utilize either native PyTorch torch._grouped_mm or custom Triton kernels for efficient matrix multiplications in MoE layers, with a robust fallback to a loop-based approach.
  • New MoE Utility Module: Adds a new moe_utils.py file to encapsulate common logic for grouped GEMM operations, including persistent Triton allocator initialization and optimized token-to-expert mapping.
  • Transformers V5 Compatibility: The optimizations are specifically designed with compatibility for upcoming Transformers v5 changes in mind, as noted in the pull request description.

🧠 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 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +143 to +147
# 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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Comment on lines +323 to +326
if self.down_proj.shape[1] == inter.shape[-1]:
w2 = self.down_proj
else:
w2 = self.down_proj.transpose(-2, -1)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

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

Copy link
Copy Markdown
Contributor

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 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.

Comment thread unsloth_zoo/temporary_patches/moe_utils.py Outdated
Comment thread unsloth_zoo/temporary_patches/moe_utils.py Outdated
Comment thread unsloth_zoo/temporary_patches/moe_utils.py Outdated
Comment thread unsloth_zoo/temporary_patches/moe_utils.py Outdated
# # 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

critical

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)

Comment thread unsloth_zoo/temporary_patches/qwen3_vl_moe.py Outdated
Comment thread unsloth_zoo/temporary_patches/qwen3_vl_moe.py
@Datta0 Datta0 changed the base branch from nightly to main January 5, 2026 11:40
@Datta0 Datta0 force-pushed the qwen3_moe_kernels branch from 034aa21 to ec20171 Compare January 6, 2026 06:45
@Datta0

Datta0 commented Jan 14, 2026

Copy link
Copy Markdown
Collaborator Author

/gemini review

@Datta0

Datta0 commented Jan 26, 2026

Copy link
Copy Markdown
Collaborator Author

/gemini review

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

Copy link
Copy Markdown
Contributor

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 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.

Comment thread unsloth_zoo/temporary_patches/moe_bnb.py
Comment thread unsloth_zoo/temporary_patches/moe_utils.py
Comment thread unsloth_zoo/temporary_patches/moe_utils.py
@Datta0

Datta0 commented Feb 3, 2026

Copy link
Copy Markdown
Collaborator Author

Closing in favor of #450

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant