Skip to content

Fix QMoE scale precision: scales silently forced entire MoE FFN onto CPU EP - #505

Merged
titaiwangms merged 3 commits into
mainfrom
fix/qmoe-scale-precision
Aug 17, 2026
Merged

titaiwangms merged 3 commits into
mainfrom
fix/qmoe-scale-precision

Conversation

@titaiwangms

Copy link
Copy Markdown
Contributor

Bug

When exporting a hybrid MoE model (e.g. Qwen/Qwen3.6-35B-A3B) via the native QMoE-emission path in MoELayer (_moe.py) at a non-float32 precision (e.g. fp16 for CUDA), the fc1_scales/fc2_scales parameters were pinned with _keep_float32 = True, which _cast_module_dtype() (_builder.py) honors by skipping them during the FLOAT->target-dtype cast pass. Every other parameter (weights, activations) was correctly cast to FLOAT16, but the scales stayed FLOAT32.

ONNX Runtime's com.microsoft::QMoE kernel (quant_type="int") requires its T2 type constraint (used by fc1_scales/fc2_scales) to be exactly equal to T (the activation dtype) — confirmed by reading onnxruntime/contrib_ops/{cuda,cpu}/moe/moe_quantization*.{cc,h}. There is no registered kernel variant for T2=FLOAT32 while T=FLOAT16.

Because of this mismatch, ONNX Runtime silently fails to find any matching QMoE kernel — on either CPU or CUDA EP — and falls back to placing every QMoE node on CPUExecutionProvider, inserting InsertedPrecisionFreeCast_* bridging nodes. Since QMoE is the entire MoE FFN compute (the dominant cost for a large MoE model), this silently forced 100% of the MoE compute onto CPU even when the workflow explicitly targeted CUDA — and also broke enable_cuda_graph in ONNX Runtime GenAI, since not all decoder nodes were assigned to the same EP.

Fix

  • _moe.py: stop pinning fc1_scales/fc2_scales to FLOAT32; let them be downcast to the model's target export precision (FP16/BF16) like every other float parameter.
  • _qmoe_fusion.py (the separate "dense-fallback -> QMoE" rewrite rule): had the same class of bug — scales and router logits were hardcoded to FLOAT/FLOAT32 regardless of the model's activation dtype. Fixed to use the activation dtype instead.
  • Updated _moe_test.py and _qmoe_fusion_test.py to reflect the corrected (dtype-matching) behavior, and added explicit FP32/FP16/BF16 coverage in _qmoe_fusion_test.py.

Validation

  • python -m pytest src/mobius/components/_moe_test.py src/mobius/rewrite_rules/_qmoe_fusion_test.py -v — 39 passed.
  • ruff — passed.
  • Real-model validation: re-ran the Olive Rtn(moe=true) + MobiusBuilder(precision=fp16, CUDA EP) export against Qwen/Qwen3.6-35B-A3B. All 430 QMoE scale initializers in the exported graph are now FLOAT16 (previously FLOAT32).
  • Loaded the re-exported model with onnxruntime (verbose session logging): zero "CUDA kernel not found in registries" messages for QMoE, and all 40 QMoE nodes are now correctly assigned to CUDAExecutionProvider (previously all 40 fell back to CPU).
  • onnxruntime_genai.Model(...) now loads successfully with enable_cuda_graph=1 in genai_config.json, with no manual workaround needed (previously required manually stripping enable_cuda_graph from the generated config).

Related: builds on top of the export fixes merged in #495.

@titaiwangms
titaiwangms requested review from a team and a lite review from Copilot August 17, 2026 15:03

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.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

@github-actions

github-actions Bot commented Aug 17, 2026 •

Copy link
Copy Markdown

Performance Comparison

Comparing 9d540af → d5d3718

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.

@github-actions

github-actions Bot commented Aug 17, 2026 •

Copy link
Copy Markdown

🏗️ Architecture Diff

Comparing 9d540af → d5d3718

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)

- Fix pre-existing test test_deepseek_v2_lite_int4_uses_one_qmoe_per_moe_layer
  in _group_query_attention_test.py: it hardcoded the old (buggy) FLOAT
  expectation for QMoE scale dtypes, missed by the original fix's test
  sweep. Confirmed via test run that this was a real CI-breaking
  regression; updated to FLOAT16 and corrected the stale comment.
- Make the BF16/FLOAT/FLOAT16 parametrized tests in _qmoe_fusion_test.py
  non-vacuous: thread activation_dtype into the synthetic MatMulNBits
  scale fixtures (previously hardcoded FLOAT16 regardless of the
  parametrization), so the tests actually exercise mixed source/target
  dtype packing.
- Harden fuse_dense_moe_to_qmoe's activation-dtype guard: fall back to an
  expert's existing MatMulNBits scale dtype when layer.hidden.dtype is
  None (common for untyped, graph-internal values in real models),
  instead of silently skipping the layer. Added a regression test
  (test_fuses_when_hidden_dtype_is_untyped).
- Add fc2 scale content assertion to test_scales_match_activation_dtype
  (previously only fc1 was checked).

Full suite: 1963 passed, 2 skipped. ruff check + format clean.
@titaiwangms

Copy link
Copy Markdown
Contributor Author

Full review pass — findings & fixes

Ran a 4-reviewer pass (code / critical / deep / integration) over this PR. Summary:

Confirmed & fixed (this commit):

  • CI-breaking regression (integration-reviewer, confirmed by actually running the test): _group_query_attention_test.py::test_deepseek_v2_lite_int4_uses_one_qmoe_per_moe_layer was a pre-existing test not touched by the original fix — it hardcoded the old buggy FLOAT expectation for QMoE scale dtypes. Fixed the assertions + stale comment.
  • Vacuous test parametrization (deep-reviewer): the new BF16/FLOAT/FLOAT16 parametrized tests in _qmoe_fusion_test.py built synthetic MatMulNBits fixtures with scales hardcoded to FLOAT16 regardless of the parametrized activation_dtype, so they didn't really exercise mixed dtype packing. Fixed by threading activation_dtype into the fixture.
  • Coverage gap in the new dtype guard (deep-reviewer): fuse_dense_moe_to_qmoe's guard skipped fusion whenever layer.hidden.dtype is None, which is common for untyped graph-internal values in real models (not just the schema-invalid case it was meant to catch). Added a fallback to an existing expert's MatMulNBits scale dtype, plus a regression test (test_fuses_when_hidden_dtype_is_untyped).
  • Minor: added the missing fc2 scale content assertion to test_scales_match_activation_dtype (previously only fc1 was checked).

Verified correct, no fix needed:

  • deep-reviewer independently confirmed the core fix's premise against ORT source: T2 == T (scales must match activation dtype) is the only kernel-registered combination for quant_type="int" on both CPU and CUDA. Also flagged that WebGPU's QMoE registration is untyped, meaning the pre-fix bug could have silently produced wrong results there (not just failed to dispatch) — good independent confirmation this was a real bug worth fixing.

Discussed, deferred as follow-up (not blocking this PR):

  • critical-reviewer raised two Major points: (1) no numerical-representability check before the FP16/BF16 scale downcast (extreme-dynamic-range scales could silently overflow/underflow), and (2) the "validated end-to-end" claim in the PR description isn't covered by the repo's own test suite (tests check IR-level dtypes/NumPy math, not real ORT InferenceSession CUDA kernel dispatch). Both are reasonable but larger-scope asks than this bugfix; flagging here for a follow-up issue rather than blocking merge, since the manual end-to-end validation (~30x speedup, all 40 QMoE nodes on CUDA EP) is described in the PR body.

Full suite after fixes: 1963 passed, 2 skipped. ruff check + ruff format --check clean.

@CLAassistant

CLAassistant commented Aug 17, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@titaiwangms
titaiwangms merged commit 781bbe8 into main Aug 17, 2026
17 of 22 checks passed
@titaiwangms
titaiwangms deleted the fix/qmoe-scale-precision branch August 17, 2026 17:37
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.

4 participants