Repository navigation
Fix QMoE gate scoping, router dtype/shape, swiglu layout, and hybrid-recurrent past_present_share_buffer - #494
Closed
titaiwangms wants to merge 1 commit into
Closed
titaiwangms wants to merge 1 commit into
titaiwangms wants to merge 1 commit into
Conversation
…enai execution Structural graph export (Olive RTN + MobiusBuilder) previously succeeded for Qwen3.5-MoE models, but the exported model.onnx had never actually been loaded/run with onnxruntime-genai. Doing so surfaced five real, pre-existing bugs in the QMoE fused-expert path and genai_config generation: 1. Router gate weight orphaned as an unqualified "weight" graph input. MoELayer._qmoe_forward() called self.gate.qmoe_routing() directly instead of through self.gate(op, ...), bypassing Module.__call__'s parameter realization (which qualifies "weight" into "<prefix>.gate.weight"). Fixed by manually pushing the gate's module scope and realizing its parameters first, mirroring the existing pattern in gemma4_assistant.py. 2. router_probs was hard-cast to float32, but QMoE's router_probs input shares type constraint "T" with the hidden_states input (per contrib_defs.cc) -- it must match hidden_states' actual dtype (e.g. fp16). Fixed with CastLike instead of a fixed Cast(..., FLOAT). 3. swiglu_fusion=2 (concatenated gate/up layout) is not supported by the CPU QMoE kernel in this ORT build (only swiglu_fusion=1, interleaved, is). Fixed by reordering fc1_experts_weights/fc1_scales/fc1_experts_zero_points rows from HF's concatenated [gate;up] layout to the interleaved [g_0,u_0,g_1,u_1,...] layout via a graph-level reshape/transpose/reshape (folded away at session load since it's applied to a constant initializer), matching the existing swiglu_fusion=1 path in gemma4.py. 4. router_probs/router_weights were left 3D (batch, seq, num_experts) when QMoE requires strictly 2D (num_tokens, num_experts). Added _flatten_to_2d() to collapse leading dims before the QMoE call. 5. genai_config's past_present_share_buffer auto-detection only checked for GroupQueryAttention nodes, defaulting to False for hybrid models that mix LinearAttention (recurrent state, e.g. Qwen3.5's GatedDeltaNet) with standard Attention. LinearAttention's recurrent state requires past_present_share_buffer=True unconditionally, so detection now also checks for LinearAttention nodes. All five were verified against actual onnxruntime-genai execution of an Olive RTN + MobiusBuilder export of a tiny Qwen3.5-MoE test model, fixed one at a time, and each confirmed to move execution further before the next bug surfaced. Not related to PR #493 (linear_class threading) or #491 (suffix mismatch) -- these bugs exist independently in the base QMoE/ genai-config code and were simply never exercised by prior structural-only export tests. Updated _moe_test.py's swiglu_fusion assertions from 2 to 1 to match.
Performance Comparison
|
This was referenced Aug 14, 2026
Contributor
Author
Contributor
There was a problem hiding this comment.
Pull request overview
This PR fixes several execution-blocking issues in the quantized fused MoE (com.microsoft::QMoE) path and ORT GenAI config generation, with the goal of making Olive-quantized Qwen3.5-MoE exports actually load and run under onnxruntime-genai (not just export structurally).
Changes:
- Fix QMoE gate parameter scoping (avoid unqualified
"weight"initializers) and ensure router logits matchhidden_statesdtype viaCastLike. - Ensure QMoE router inputs are rank-2 as required by the op schema by flattening
(B,S,*) -> (B*S,*)forrouter_probs/router_weights. - Switch to CPU-supported SwiGLU layout (
swiglu_fusion=1) by interleaving gate/up rows for fc1 quantized tensors at graph level (enabling ORT constant folding).
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.
| File | Description |
|---|---|
src/mobius/integrations/ort_genai/auto_export.py |
Extends past_present_share_buffer auto-detection to also require sharing for com.microsoft.LinearAttention recurrent-state models. |
src/mobius/components/_moe.py |
Fixes QMoE routing dtype/shape requirements, ensures gate parameter realization under correct module scope, and interleaves fc1 gate/up rows for CPU-compatible swiglu_fusion=1. |
src/mobius/components/_moe_test.py |
Updates test expectations to match swiglu_fusion=1 emission. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
🏗️ Architecture Diff
No architecture changes detected. ✅ Legend: ⚪ No change · 🔵 Minor (attrs/inits) · 🟡 Moderate (nodes added/removed) · 🔴 Major (interface changed) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
While validating that an Olive-quantized (RTN,
moe=true) Qwen3.5-MoE exportactually runs under
onnxruntime-genai(not just structurally exports —see discussion on #492), five independent, pre-existing bugs surfaced in the
QMoE fused-expert path and
genai_config.jsongeneration. None of these arerelated to #491 or #493 — this PR is based directly on
main.Each bug was fixed one at a time and re-verified against actual
onnxruntime_genai.Model(...)load + generation on a tiny Qwen3.5-MoE testmodel (Olive
Rtn(bits=4, group_size=16, sym=true, moe=true)→MobiusBuilder), confirming execution progressed further after each fix.1. Router gate weight orphaned as unqualified
"weight"graph inputMoELayer._qmoe_forward()calledself.gate.qmoe_routing(op, ...)directlyinstead of through
self.gate(op, ...), bypassingModule.__call__'sparameter-realization step (which qualifies
weightinto e.g.model.layers.0.mlp.gate.weight). This left a bare, unqualified"weight"node input in the graph, which
onnxruntime_genairejected at load:Node input 'weight' is not a graph input, initializer, or output of a previous node.Fixed by manually pushing the gate's module scope and realizing its
parameters before calling
qmoe_routing, mirroring the existing patternused for the sparse LM head in
gemma4_assistant.py.2.
router_probshard-cast to float32 instead of matching hidden_states' dtypeQMoE's
router_probsinput shares type constraintTwith theinput(hidden_states) tensor per
contrib_defs.cc— it must match hidden_states'actual dtype (e.g. fp16), not a fixed float32. The previous code did
op.Cast(router_logits, to=ir.DataType.FLOAT.value)unconditionally, whichproduced:
Type Error: Type parameter (T) of Optype (QMoE) bound to different types (tensor(float16) and tensor(float)).Fixed with
op.CastLike(router_logits, hidden_states)in all three gateclasses'
qmoe_routing()(TopKGate,SoftmaxTopKGate,SigmoidTopKGate).3.
swiglu_fusion=2(concatenated) unsupported by the CPU QMoE kernelswiglu_fusion=2tells QMoE the fc1 gate/up rows are concatenated(
[gate_rows; up_rows], matching HF'sexperts.gate_up_projlayout as-is).The CPU QMoE kernel in this ORT build only supports
swiglu_fusion=1(interleaved
[g_0, u_0, g_1, u_1, ...]):CPU QMoE only supports interleaved SwiGLU format. Please set swiglu_fusion=1.This also matches the officialonnxruntime-genaireference builders, which always emit the interleaved layout.
Fixed by adding
_interleave_gate_up_rows(), which reordersfc1_experts_weights/fc1_scales/fc1_experts_zero_pointsfrom theconcatenated to the interleaved row layout via a graph-level
reshape/transpose/reshape. Since this operates on constant initializers, ORT
folds it away at session load — this mirrors the existing unquantized-MoE
interleave already used for
swiglu_fusion=1ingemma4.py.4.
router_probs/router_weightsleft 3D instead of required 2DQMoE's
router_probsandrouter_weightsinputs require a strictly 2D(num_tokens, num_experts)shape (unlikeinput/hidden_states, whichaccepts 2D or 3D per the op schema). Router logits computed from a 3D
hidden_states(batch, seq, hidden) were passed through unflattened,producing:
Input 'router_probs' is expected to have 2 dimensions, got 3.Fixed by adding
_flatten_to_2d(), which collapses all leading dims intoone before the
QMoEcall (applied to bothrouter_probsandrouter_weightswhen present).5.
past_present_share_bufferauto-detection ignoresLinearAttentionauto_export.py's heuristic forpast_present_share_bufferonly checkedfor
GroupQueryAttentionnodes, defaulting the flag toFalsewhen absent— correct for models using only standard (non-GQA)
Attention, but wrongfor hybrid models that mix
com.microsoft.LinearAttention(recurrent state,e.g. Qwen3.5's GatedDeltaNet linear-attention layers) with standard
Attentionlayers for full self-attention.LinearAttention's recurrentstate requires
past_present_share_buffer=Trueunconditionally,regardless of whether any other layer uses GQA — otherwise
onnxruntime_genaifails at load:RecurrentState requires past_present_share_buffer=true.Fixed by also checking for
LinearAttentionnodes and OR-ing that into thedetection result.
Testing
pytest src/mobius/components/_moe_test.py src/mobius/integrations/ort_genai/— 203 passed.ruff checkon all changed files — clean.each fix and re-attempted
onnxruntime_genai.Model(...)load +generation; execution progressed past each bug in turn (orphaned weight →
type mismatch → CPU-kernel rejection → shape-rank error →
past_present_share_buffer load failure) until reaching a separate,
unrelated limitation specific to the tiny test model's abnormally small
head_dim(GQA's rotary-cache-size kernel constraint), which is a test-modelscale artifact rather than a design bug.
Not in scope
rewrite_rules/_qmoe_fusion.pyhas the sameswiglu_fusion=2+float32-router-cast pattern in its dense-fallback-to-QMoE rewrite rule, but
that module isn't wired into
MobiusBuilder's default pipeline (notinvoked anywhere outside its own tests), so it's left untouched here as a
possible future follow-up.
deepseek.py'sqmoe_routing()does its own float32 upcasting fornumerical stability in sigmoid/scoring, independent of this PR's scope.