Skip to content

Fix MoE wrapper handling for PR 450#453

Closed
danielhanchen wants to merge 73 commits into
mainfrom
fix/pr450-moe-wrappers
Closed

Fix MoE wrapper handling for PR 450#453
danielhanchen wants to merge 73 commits into
mainfrom
fix/pr450-moe-wrappers

Conversation

@danielhanchen
Copy link
Copy Markdown
Member

Summary

  • Fix ParamWrapper handling in MoE weight unwrapping and expert detection
  • Ensure grouped_gemm weights and LoRA transposes are contiguous
  • Fix offsets computation when only down LoRA is present

Testing

  • python temp/moe_train_bench.py (GLM4 MoE native/grouped_mm/unsloth_triton)

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @danielhanchen, 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 significantly advances the Unsloth framework's capabilities for Mixture of Experts (MoE) models. It introduces comprehensive fixes for LoRA adapter integration, expands support to include GLM4 and Qwen3-VL MoE architectures, and incorporates high-performance grouped GEMM kernels for optimized execution. Furthermore, it refines quantization behaviors for MXFP4 and enhances vLLM's LoRA management, ensuring a more robust and efficient experience for training and inference with MoE models.

Highlights

  • Enhanced MoE LoRA Handling: Improved the handling of LoRA adapters within Mixture of Experts (MoE) layers by patching PEFT's ParamWrapper.forward. This ensures LoRA weights are correctly unwrapped, detected, and applied, especially for 3D expert parameters, and fixes offset computations when only down LoRA is present.
  • Expanded MoE Model Support: Added specific patches and LoRA extraction logic for GLM4 MoE and Qwen3-VL MoE models. For Qwen3-VL MoE, the __init__ method was modified to align weight parameters with the grouped_mm format used in checkpoints, ensuring seamless loading and compatibility.
  • Optimized MoE Backends: Integrated and enabled highly optimized grouped GEMM kernels for MoE forward passes. This includes support for torch._grouped_mm and Unsloth's Triton grouped GEMM kernels, with an automatic backend selection mechanism to choose the most performant option available. LoRA weights are now ensured to be contiguous for these operations.
  • MXFP4 Quantization Configuration: Introduced new logic to control MXFP4 dequantization during training. Users can now choose to keep MXFP4 weights quantized if triton_kernels are available, or dequantize to bf16 for broader compatibility, providing flexibility for different hardware setups.
  • GRPO Training for MoE Models: Patched the forward methods of CausalLM classes for Qwen3-MoE and Qwen3-VL MoE models to optionally return hidden states. This enables compatibility with GRPO (Gradient-based Regularization for Policy Optimization) training methodologies.
  • vLLM LoRA Management Improvements: Made minor updates to vLLM's LoRA worker manager and utility functions, including a more robust vllm_version import and improved handling of lora_request_id for better LoRA adapter management within the vLLM ecosystem.

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

Copy link
Copy Markdown
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 introduces significant enhancements for Mixture-of-Experts (MoE) models. Key changes include centralizing MoE forward logic into a new moe_utils.py module, adding support for GLM-4 and Qwen3-VL MoE models, and refactoring LoRA handling for MoE layers to be more robust and performant. Additionally, it adds a custom 4-bit quantization scheme for MoE layers and configuration options for MXFP4 dequantization. The changes are well-structured and address complex integration challenges. I have one suggestion to simplify a part of the LoRA extraction logic for better maintainability. Overall, this is a high-quality contribution.

Comment on lines +197 to +205
hidden_dim = None
experts_module = getattr(wrapper, "base_layer", None)
# Traverse base_layer until we find the experts module which might have hidden_dim
current = wrapper
while hasattr(current, "base_layer"):
current = current.base_layer
if hasattr(current, "hidden_dim"):
hidden_dim = current.hidden_dim
break
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.

medium

The manual traversal to find hidden_dim can be simplified. The ParamWrapper class in PEFT provides a get_base_layer() method that recursively finds the underlying module. Using this method and getattr makes the code cleaner, more concise, and less fragile to potential changes in the PEFT wrapper structure. The existing code also has an unused experts_module variable on line 198.

Suggested change
hidden_dim = None
experts_module = getattr(wrapper, "base_layer", None)
# Traverse base_layer until we find the experts module which might have hidden_dim
current = wrapper
while hasattr(current, "base_layer"):
current = current.base_layer
if hasattr(current, "hidden_dim"):
hidden_dim = current.hidden_dim
break
experts_module = wrapper.get_base_layer() if hasattr(wrapper, "get_base_layer") else None
hidden_dim = getattr(experts_module, "hidden_dim", None)

Copy link
Copy Markdown

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

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.

Reviewed commit: 14e9c9a51b

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +386 to +389
# lora_B.weight: (dim2, E*R) -> view(dim2, E, R) -> permute(1, 0, 2)
# first_weight (A): (E, in_dim, R)
first_weight = weight_A.view(num_experts, rank_per_expert, dim1)
first_weight = first_weight.permute(0, 2, 1).contiguous() # (E, dim1, R)
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 Use lora_B as first weight for standard-format MoE

When the expert weight is in the standard F.linear layout (E, out_dim, in_dim) (the case described in the comments), PEFT’s ParamWrapper treats in_features as out_dim, so weight_A is shaped (E*R, out_dim) while weight_B is (in_dim, E*R). The grouped-mm LoRA path expects the first weight to match the input dimension (E, in_dim, R), which means it must come from weight_B, not weight_A. As written, first_weight becomes (E, out_dim, R), causing a dimension mismatch or incorrect LoRA application when grouped-mm is used with standard-format MoE weights (e.g., older transformer MoE models without a custom extractor). This will break or corrupt LoRA outputs in those configurations.

Useful? React with 👍 / 👎.

@Datta0
Copy link
Copy Markdown
Collaborator

Datta0 commented Feb 16, 2026

I think this can be closed now after #450 and #470 and #471

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.

2 participants