Skip to content

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
mainfrom
fix/qmoe-swiglu-routing-genai-config
Closed

titaiwangms wants to merge 1 commit into
mainfrom
fix/qmoe-swiglu-routing-genai-config

Conversation

@titaiwangms

Copy link
Copy Markdown
Contributor

Summary

While validating that an Olive-quantized (RTN, moe=true) Qwen3.5-MoE export
actually 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.json generation. None of these are
related 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 test
model (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 input

MoELayer._qmoe_forward() called self.gate.qmoe_routing(op, ...) directly
instead of through self.gate(op, ...), bypassing Module.__call__'s
parameter-realization step (which qualifies weight into e.g.
model.layers.0.mlp.gate.weight). This left a bare, unqualified "weight"
node input in the graph, which onnxruntime_genai rejected 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 pattern
used for the sparse LM head in gemma4_assistant.py.

2. router_probs hard-cast to float32 instead of matching hidden_states' dtype

QMoE's router_probs input shares type constraint T with the input
(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, which
produced: 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 gate
classes' qmoe_routing() (TopKGate, SoftmaxTopKGate, SigmoidTopKGate).

3. swiglu_fusion=2 (concatenated) unsupported by the CPU QMoE kernel

swiglu_fusion=2 tells QMoE the fc1 gate/up rows are concatenated
([gate_rows; up_rows], matching HF's experts.gate_up_proj layout 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 official onnxruntime-genai
reference builders, which always emit the interleaved layout.

Fixed by adding _interleave_gate_up_rows(), which reorders
fc1_experts_weights / fc1_scales / fc1_experts_zero_points from the
concatenated 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=1 in gemma4.py.

4. router_probs/router_weights left 3D instead of required 2D

QMoE's router_probs and router_weights inputs require a strictly 2D
(num_tokens, num_experts) shape (unlike input/hidden_states, which
accepts 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 into
one before the QMoE call (applied to both router_probs and
router_weights when present).

5. past_present_share_buffer auto-detection ignores LinearAttention

auto_export.py's heuristic for past_present_share_buffer only checked
for GroupQueryAttention nodes, defaulting the flag to False when absent
— correct for models using only standard (non-GQA) Attention, but wrong
for hybrid models that mix com.microsoft.LinearAttention (recurrent state,
e.g. Qwen3.5's GatedDeltaNet linear-attention layers) with standard
Attention layers for full self-attention. LinearAttention's recurrent
state requires past_present_share_buffer=True unconditionally,
regardless of whether any other layer uses GQA — otherwise
onnxruntime_genai fails at load: RecurrentState requires past_present_share_buffer=true.

Fixed by also checking for LinearAttention nodes and OR-ing that into the
detection result.

Testing

  • pytest src/mobius/components/_moe_test.py src/mobius/integrations/ort_genai/ — 203 passed.
  • ruff check on all changed files — clean.
  • End-to-end verification: re-ran the Olive RTN + MobiusBuilder export after
    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-model
    scale artifact rather than a design bug.

Not in scope

  • rewrite_rules/_qmoe_fusion.py has the same swiglu_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 (not
    invoked anywhere outside its own tests), so it's left untouched here as a
    possible future follow-up.
  • deepseek.py's qmoe_routing() does its own float32 upcasting for
    numerical stability in sigmoid/scoring, independent of this PR's scope.

…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.
@titaiwangms
titaiwangms requested review from a team and a lite review from Copilot August 14, 2026 23:06
@CLAassistant

CLAassistant commented Aug 14, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@github-actions

Copy link
Copy Markdown

Performance Comparison

Comparing 01008cf → 2e5b433

Model Metric Baseline Current Delta
bert (feature-extraction) model_size_bytes 359 KB 359 KB +0.0% ⚪
bert (feature-extraction) num_nodes 60 60 +0.0% ⚪
falcon model_size_bytes 364 KB 364 KB +0.0% ⚪
falcon num_nodes 66 66 +0.0% ⚪
gemma2 model_size_bytes 428 KB 428 KB +0.0% ⚪
gemma2 num_nodes 105 105 +0.0% ⚪
gpt2 model_size_bytes 388 KB 388 KB +0.0% ⚪
gpt2 num_nodes 54 54 +0.0% ⚪
llama model_size_bytes 425 KB 425 KB +0.0% ⚪
llama num_nodes 60 60 +0.0% ⚪
llama (static-cache) model_size_bytes 425 KB 425 KB +0.0% ⚪
llama (static-cache) num_nodes 56 56 +0.0% ⚪
mamba (ssm-text-generation) model_size_bytes 296 KB 296 KB +0.0% ⚪
mamba (ssm-text-generation) num_nodes 94 94 +0.0% ⚪
phi3 model_size_bytes 421 KB 421 KB +0.0% ⚪
phi3 num_nodes 58 58 +0.0% ⚪
phi3 (static-cache) model_size_bytes 421 KB 421 KB +0.0% ⚪
phi3 (static-cache) num_nodes 54 54 +0.0% ⚪
qwen2 model_size_bytes 425 KB 425 KB +0.0% ⚪
qwen2 num_nodes 60 60 +0.0% ⚪
qwen2 (static-cache) model_size_bytes 425 KB 425 KB +0.0% ⚪
qwen2 (static-cache) num_nodes 56 56 +0.0% ⚪
qwen3_5_moe (hybrid-text-generation) model_size_bytes 506 KB 506 KB +0.0% ⚪
qwen3_5_moe (hybrid-text-generation) num_nodes 264 264 +0.0% ⚪
qwen3_5_text (hybrid-text-generation) model_size_bytes 458 KB 458 KB +0.0% ⚪
qwen3_5_text (hybrid-text-generation) num_nodes 126 126 +0.0% ⚪
qwen3_5_vl (hybrid-qwen-vl) model_size_bytes 977 KB 977 KB +0.0% ⚪
qwen3_5_vl (hybrid-qwen-vl) num_nodes 428 428 +0.0% ⚪
t5 (seq2seq) model_size_bytes 836 KB 836 KB +0.0% ⚪
t5 (seq2seq) num_nodes 166 166 +0.0% ⚪
whisper (speech-to-text) model_size_bytes 1008 KB 1008 KB +0.0% ⚪
whisper (speech-to-text) num_nodes 128 128 +0.0% ⚪

No performance regressions.

@titaiwangms

Copy link
Copy Markdown
Contributor Author

Consolidated into #495 along with #491 and #493 to simplify review.

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

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 match hidden_states dtype via CastLike.
  • Ensure QMoE router inputs are rank-2 as required by the op schema by flattening (B,S,*) -> (B*S,*) for router_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.

@github-actions

Copy link
Copy Markdown

🏗️ Architecture Diff

Comparing 01008cf → 2e5b433

Model Sub-model Changes Status
bert (feature-extraction) model 0 ⚪
falcon model 0 ⚪
gemma2 model 0 ⚪
gemma4 (gemma4) decoder 0 ⚪
gemma4 (gemma4) embedding 0 ⚪
gemma4 (gemma4) vision_encoder 0 ⚪
gemma4_text model 0 ⚪
gpt2 model 0 ⚪
llama model 0 ⚪
llama (static-cache) model 0 ⚪
mamba (ssm-text-generation) model 0 ⚪
phi3 model 0 ⚪
phi3 (static-cache) model 0 ⚪
qwen model 0 ⚪
qwen (static-cache) model 0 ⚪
qwen2 model 0 ⚪
qwen2 (static-cache) model 0 ⚪
qwen2_moe model 0 ⚪
qwen2_moe (static-cache) model 0 ⚪
qwen3 model 0 ⚪
qwen3 (static-cache) model 0 ⚪
qwen3_5_moe (hybrid-text-generation) model 0 ⚪
qwen3_5_text (hybrid-text-generation) model 0 ⚪
qwen3_5_vl (hybrid-qwen-vl) decoder 0 ⚪
qwen3_5_vl (hybrid-qwen-vl) embedding 0 ⚪
qwen3_5_vl (hybrid-qwen-vl) vision_encoder 0 ⚪
qwen3_moe model 0 ⚪
qwen3_moe (static-cache) model 0 ⚪
qwen3_next (hybrid-text-generation) model 0 ⚪
t5 (seq2seq) decoder 0 ⚪
t5 (seq2seq) encoder 0 ⚪
whisper (speech-to-text) decoder 0 ⚪
whisper (speech-to-text) encoder 0 ⚪

No architecture changes detected. ✅


Legend: ⚪ No change · 🔵 Minor (attrs/inits) · 🟡 Moderate (nodes added/removed) · 🔴 Major (interface changed)

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.

3 participants