Repository navigation
Fix Qwen3.5-MoE Olive->Mobius export: suffix mismatch, linear_class threading, QMoE routing/layout, and genai_config detection - #495
Conversation
…onvention preprocess_olive_weights() assumed a dotted suffix convention (<pname>.qweight/.scales/.qzeros) that never matches Olive's actual on-disk keys, which use an underscore suffix appended directly to the owning parameter name (<pname>_qweight/_scales/_qzeros, e.g. "...gate_proj.weight_qweight" or "...experts.gate_up_proj_qweight" -- see olive/common/quant/state_dict.py). Every endswith/replace check in this function silently failed to match, so any real Olive-quantized checkpoint fell through to the "pass through unchanged" branch instead of being renamed/reshaped for MatMulNBits/GatherBlockQuantized/QMoE consumption, and was missing an explicit rename branch for `_scales` entirely. This was flagged (for a different, narrower symptom) in #427, which scoped itself to a defensive ndim==2 guard for RTN's older moe=True 3-D case and left "real MoE quantization support" for a follow-up. #451 added that follow-up (QMoE emission for Qwen3.5/3.6-MoE), but its projections dict and `preprocess_olive_weights` reshape logic were themselves written against the same incorrect dotted-suffix assumption, so they never actually exercised a real Olive checkpoint end-to-end. Repro: chaining Olive's Rtn(moe=true) -> MobiusBuilder against yujiepan/qwen3.5-moe-tiny-random surfaced "N initializer(s) without weights" at save time, because every quantized nn.Linear/nn.Embedding key in the checkpoint (attention/MLP projections, embeddings) failed to match and was left un-renamed. Fix: introduce a `_rename` helper that strips the underscore suffix, drops a redundant trailing ".weight" component (present for regular nn.Linear/nn.Embedding parameters but not for bare fused-MoE parameters like "gate_up_proj"), and appends the target dotted name. Update the embed_tokens special case (which keeps the "qweight" name for GatherBlockQuantized instead of renaming to "weight") accordingly, and add the previously-missing "_scales" rename branch for the general (non-embedding) case. Update tests in _weight_utils_test.py/qwen35_test.py/_moe_test.py that had been written against the same incorrect fixture convention. Note: this fixes weight *naming*, not quantization *coverage*. Qwen3.5's Qwen35Attention/GatedDeltaNet/MLP call sites still hardcode plain Linear regardless of config.quantization (only the MoE fused-expert path added in #451 threads through quantization), so self_attn/linear_attn/MLP weights in a quantized Qwen3.5/3.6 checkpoint still fail to load with a shape mismatch after this fix. Tracked separately.
…_expert Qwen35Attention, GatedDeltaNet, and Qwen2MoELayer's shared_expert (reused by Qwen35MoEBlock) all hardcoded plain Linear regardless of config.quantization, unlike the generic Attention/MLP classes used elsewhere in Mobius. Since Mobius rebuilds the ONNX graph from scratch rather than tracing the PyTorch model, this meant the corresponding initializer slots were always built expecting dense float weights -- so a quantized checkpoint's packed uint8 tensors for these modules could never load, failing with a shape mismatch (or, before #491's suffix fix, "initializer without weights"). Fix: - Add an optional `linear_class` constructor parameter to Qwen35Attention (q/k/v/o_proj) and GatedDeltaNet (in_proj_qkv/z/b/a, out_proj), matching the pattern already used by the generic Attention/MLP classes. GatedDeltaNet's dt_bias/A_log/conv1d.weight are small recurrent-state parameters and are intentionally left unquantized regardless of this argument. - Add an optional `linear_class` parameter to Qwen2MoELayer for its shared_expert/shared_expert_gate (the routed experts are already quantized separately via the fused QMoE path, driven directly by config.quantization -- this only covers the always-active shared expert, which isn't part of that fused op). Defaults to None (plain Linear), so existing Qwen2MoEDecoderLayer callers are unaffected. - Add a `_linear_factory(config)` helper in qwen35.py (mirrors the existing pattern in deepseek.py) and thread it through Qwen35DecoderLayer/Qwen35MoEDecoderLayer's self_attn/linear_attn/mlp construction. Verified end-to-end: Olive Rtn(bits=4, group_size=16, sym=true, moe=true) -> MobiusBuilder against optimum-intel-internal-testing/tiny-random-qwen3.5-moe now succeeds without excluding linear_attn/shared_expert via modules_to_not_convert -- self_attn/linear_attn/shared_expert weights save as quantized u8 tensors and a full ONNX model + genai_config are produced. Fixes #492.
…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
|
There was a problem hiding this comment.
Pull request overview
This PR consolidates multiple fixes needed to export an Olive-quantized Qwen3.5-MoE checkpoint through Mobius and successfully run the resulting model with onnxruntime-genai. It addresses weight-key compatibility, threads quantization through previously-unquantized projections, fixes several QMoE ABI/runtime issues, and improves ORT GenAI config auto-detection for hybrid recurrent models.
Changes:
- Update Olive quantized-weight preprocessing to match Olive’s underscore suffix convention and adjust related unit tests/fixtures.
- Thread a quantized
linear_classfactory through Qwen3.5 attention, GatedDeltaNet (LinearAttention), MLP, and MoE shared-expert paths. - Fix QMoE execution details: gate parameter scoping, router dtype, required router rank (2D), CPU-supported SwiGLU layout (
swiglu_fusion=1with interleaving), and detectLinearAttentionforpast_present_share_buffer.
Reviewed changes
Copilot reviewed 10 out of 10 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| src/mobius/models/qwen35.py | Adds a quantized-linear factory helper and threads linear_class through Qwen3.5 decoder layers and MoE variant. |
| src/mobius/models/qwen35_test.py | Updates synthetic Olive quantized MoE expert tensor keys to underscore suffixes. |
| src/mobius/models/moe.py | Adds linear_class support to Qwen2MoELayer for shared-expert quantization. |
| src/mobius/integrations/ort_genai/auto_export.py | Extends past_present_share_buffer auto-detection to include com.microsoft.LinearAttention. |
| src/mobius/components/_moe.py | Fixes QMoE routing dtype, gate parameter realization, router flattening, and fc1 interleaving for swiglu_fusion=1. |
| src/mobius/components/_moe_test.py | Updates expectations for swiglu_fusion and Olive key suffixes in tests. |
| src/mobius/components/_gated_deltanet.py | Adds linear_class injection for quantized projections while keeping small recurrent params unquantized. |
| src/mobius/components/_attention.py | Adds linear_class injection for Qwen3.5 q/k/v/o projections. |
| src/mobius/_weight_utils.py | Updates Olive preprocessing to underscore suffixes and adds fused-MoE rename handling. |
| src/mobius/_weight_utils_test.py | Updates Olive preprocessing tests to underscore suffixes and adds fused MoE coverage. |
Suppressed comments (2)
src/mobius/_weight_utils.py:795
- This rename of
embed_tokens.weight_qzerosshould be gated onquantize_embeddings(same as theweight_qweightbranch) so the function behavior matches itsquantize_embeddingsargument.
elif key.endswith("embed_tokens.weight_qzeros"):
src/mobius/_weight_utils.py:801
- This rename of
embed_tokens.weight_scalesshould be gated onquantize_embeddings; otherwisequantize_embeddingshas no effect on embedding-scale handling.
elif key.endswith("embed_tokens.weight_scales"):
💡 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) |
Fixes applied after the 5-reviewer fan-out on the consolidated PR: - deepseek.py: cast qmoe_routing()'s router_probs/router_weights back to hidden_states' dtype (same fp32-hardcast bug as the Qwen3.5 gates fixed earlier, confirmed reachable via the existing DeepSeek-V2-Lite int4 GQA fusion test, which asserted the buggy FLOAT-only behavior). - auto_export.py: raise a clear build-time error when a hybrid decoder graph has LinearAttention (mandates past_present_share_buffer=True) and standard non-GQA Attention (incompatible with it) with no GQA node to reconcile them, instead of silently emitting an unrunnable genai_config. - _moe.py: thread linear_class through MoELayer's dense loop-over-experts fallback (previously only the fused QMoE path was quantized); use recurse=False when manually realizing the gate's parameters to match Module.__call__'s direct-only semantics. - moe.py: Qwen2MoELayer now forwards linear_class to the base MoELayer. Also verified and refuted the integration reviewer's "Critical" rank- mismatch claim: fc1_experts_weights is confirmed 3D end-to-end (checked the actual exported model.onnx initializer shape), not 4D as claimed, so _interleave_gate_up_rows's perm=[0,2,1,3] is correct as-is. Added regression tests for all four fixes and updated the one existing test whose assertions encoded the pre-fix DeepSeek dtype bug. Full suite: 2564 passed (2 pre-existing/unrelated failures excluded: a cache-dependent test and a flaky CUDA/CPU tolerance test, both reproduced identically on pre-fix commits). Lint clean. Co-authored-by: Copilot <[email protected]> Copilot-Session: e10674c1-6909-4b09-9f5a-d41b28c89d2d
Full-team review synthesis & fixesRan the 5-reviewer parallel fan-out (readability, code, critical, deep, integration) on this consolidated diff. Findings triaged and resolved: Fixed
Investigated and refuted
Deferred (out of scope for this PR)
Verification
|
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 14 out of 14 changed files in this pull request and generated 2 comments.
Suppressed comments (3)
src/mobius/components/_moe.py:215
- This now evaluates the sigmoid routing scores in fp16/bf16 instead of the prior float32 path. The QMoE type constraint only requires the tensors passed to QMoE to match
hidden_states; it does not require the score computation itself to use reduced precision. Keep the sigmoid in float32 and applyCastLiketo both returned tensors afterward.
router_logits = op.CastLike(router_logits, hidden_states)
routing_probs = op.Sigmoid(router_logits)
src/mobius/components/_moe.py:154
- Casting before
Softmaxmoves full-expert routing to fp16/bf16, whereas this path previously widened logits to float32. That can change aggregation weights and loses the routing-score stability retained byDeepSeekMoEGate.qmoe_routing(). Compute the softmax in float32, then cast both QMoE inputs back tohidden_statesdtype to satisfy the sharedTconstraint.
This issue also appears on line 214 of the same file.
router_logits = op.CastLike(router_logits, hidden_states)
routing_probs = op.Softmax(router_logits, axis=-1)
src/mobius/integrations/ort_genai/auto_export.py:1056
- The suggested CPU workaround is not reachable through
auto_export: that function mapsep="cpu"tobuild_ep="default"at auto_export.py:1682, and the default EP deliberately has no GQA fusion. Consequently a Qwen3.5 hybrid CPU export still contains LinearAttention + standard Attention and always raises here even whendtype=float32. Select the CPU build capabilities for recurrent hybrid models (or expose a build-EP override) before presenting fp32 CPU as the recovery path.
"node was found. This EP/dtype combination cannot produce a "
"runnable genai_config -- pick an EP/dtype that lowers full "
"attention to GroupQueryAttention instead (e.g. fp32 on the "
"CPU EP)."
… quantize flag Three follow-up fixes responding to GitHub Copilot's automated review of #495: - auto_export.py: the past_present_share_buffer guard incorrectly dropped its check when any GQA node existed anywhere in the graph, even though a separate unfused standard Attention node still coexisted (partial GQA fusion). A GQA node on one layer doesn't make a standard Attention node on another layer safe for a shared buffer. Removed the `not has_gqa` short-circuit so any standard Attention node co-existing with recurrent state is unconditionally rejected. - qwen35.py: Qwen35MoECausalLMModel.preprocess_weights's dense loop-over- experts fallback only knows how to unfuse *unquantized* float gate_up_proj/down_proj tensors. When quantization is present but doesn't match the native QMoE ABI, Olive's packed *_qweight/_scales/_qzeros keys stay fused and were silently passed through unchanged, producing a graph whose per-expert Linear modules expect keys that were never generated. Now raises a clear ValueError instead of emitting an unloadable graph. - _weight_utils.py: preprocess_olive_weights's embed_tokens branches matched purely on key suffix, ignoring the quantize_embeddings flag entirely. Now gated on quantize_embeddings, with an explicit error for a caller/state-dict mismatch instead of silently misrouting through the generic Linear renaming path (which would incorrectly 3-D reshape the 2-D embedding qweight table). Added regression tests for all three fixes. Co-authored-by: Copilot <[email protected]>
…CPU EP (#505) ## 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.
…kpoints (#513) MoE decoder layers built their attention (Q/K/V/O) and always-active shared-expert projections with dense `Linear`/`MLP` regardless of the checkpoint's quantization. For GPTQ/AWQ MoE checkpoints this makes the model unloadable: the packed weight does not fit a dense `Linear`, and the export fails with a shape mismatch (mobius#513), e.g. Weight shape mismatch for 'model.layers.0.self_attn.k_proj.weight': model expects [2048, 2048], got [2048, 16, 64] and, once attention loads, the same on `mlp.shared_expert.*`. The GPTQ checkpoint `Qwen/Qwen1.5-MoE-A2.7B-Chat-GPTQ-Int4` quantizes `self_attn.{q,k,v,o}_proj` and `mlp.shared_expert.{gate,up,down}_proj` (they are listed in `modules_in_block_to_quantize`), so those projections must be built through the same quantization-aware factory as the routed experts. Affected registry models: `qwen2_moe` (Qwen1.5-MoE), `glm4_moe` and `ernie4_5_moe` (ungated shared expert), plus attention for the whole generic MoE family (Mixtral / GraniteMoE / OLMoE / Qwen3-MoE). `Qwen2MoELayer` already accepted a `linear_class` (added in #495) but its call site never passed one; `UngatedSharedMoELayer` and `MoEDecoderLayer` did not thread quantization at all. Derive the factory from the config and pass it into attention and the shared-expert MLP. The tiny `shared_expert_gate` (hidden -> 1) stays dense: it is excluded from quantization in the source checkpoints. Adds graph-only tests asserting attention and shared-expert projections become MatMulNBits (routed experts still fuse to QMoE) under int4, and stay dense otherwise. Co-authored-by: Copilot <[email protected]>
#513) (#517) ## Summary MoE decoder layers built their **attention (Q/K/V/O)** and always-active **shared-expert** projections with dense `Linear`/`MLP` regardless of the checkpoint's quantization. For GPTQ/AWQ MoE checkpoints this makes the model unloadable — the packed weight does not fit a dense `Linear` and export fails with a shape mismatch (mobius#513): ``` Weight shape mismatch for 'model.layers.0.self_attn.k_proj.weight': model expects [2048, 2048], got [2048, 16, 64] ``` and, once attention loads, the same on `mlp.shared_expert.*`. The GPTQ checkpoint `Qwen/Qwen1.5-MoE-A2.7B-Chat-GPTQ-Int4` quantizes `self_attn.{q,k,v,o}_proj` and `mlp.shared_expert.{gate,up,down}_proj` (they are listed in `modules_in_block_to_quantize`), so those projections must be built through the same quantization-aware factory as the routed experts. Affected registry models: `qwen2_moe` (Qwen1.5-MoE), `glm4_moe` and `ernie4_5_moe` (ungated shared expert), plus attention for the whole generic MoE family (Mixtral / GraniteMoE / OLMoE / Qwen3-MoE). ## Root cause `Qwen2MoELayer` already accepts a `linear_class` (added in #495), but its call site `Qwen2MoEDecoderLayer` never passed one; `UngatedSharedMoELayer` and `MoEDecoderLayer` did not thread quantization at all, so attention was always dense. ## Change - Add `_quantized_linear_class(config)` deriving `make_quantized_linear_factory(...)` from `config.quantization` (returns `None` when unquantized, so unquantized models are unchanged). - Thread it into `MoEDecoderLayer` attention and the routed `MoELayer` dense-fallback experts, the `Qwen2MoEDecoderLayer` shared expert, and `UngatedSharedMoELayer`. - Keep the tiny `shared_expert_gate` (`hidden -> 1`) **dense** (`shared_expert_gate_class=Linear`): it is excluded from quantization in the source checkpoints. ## Tests Graph-only (no weights / GPU), added to `TestBuildGraphQuantized`: - `test_qwen2_moe_int4_quantizes_shared_expert` — attention `q_proj` and shared-expert `gate/up/down_proj` become `QuantizedLinear` (>=3 `MatMulNBits`), routed experts still fuse to one `QMoE`, and `shared_expert_gate` stays `Linear`. - `test_qwen2_moe_dense_shared_expert_stays_linear` — unquantized config keeps the shared expert dense. - `test_glm4_moe_int4_quantizes_shared_expert` — the ungated-shared variant quantizes its shared expert too. `pytest tests/build_graph_test.py` MoE-family selection: 192 passed, 14 skipped, no regressions. `ruff check` clean. ## Note (follow-up, out of scope here) With this fix the Qwen1.5-MoE-GPTQ export progresses past attention and the shared expert, but still fails to populate the **fused QMoE routed-expert weights** (`fc1/fc2_experts_weights`). AutoGPTQ stores the 60 routed experts as *separate per-expert* quantized `nn.Linear` modules, whereas `pack_qmoe_expert_weights` (and the working DeepSeek / Qwen3.5-Olive QMoE paths) expect an *already-fused expert-major* tensor. Wiring per-expert-GPTQ → fused-QMoE stacking for the generic MoE family is a separate change and needs numerical validation, so it is intentionally not included here. Closes #513 --- ## Update — per-expert → fused QMoE stacking now implemented (commit bd666bc) The "follow-up, out of scope" item above is now **done** in this branch, so the scope of the PR is broadened: Qwen1.5-MoE-A2.7B-GPTQ-Int4 (and the per-expert GPTQ/AWQ MoE family) now export a **fully fused** graph. ### Change - New `stack_per_expert_moe_weights` in `_weight_utils.py`: after the MatMulNBits reshape, concatenate each expert's `gate_proj`/`up_proj` in HF-concatenated `[gate; up]` order and stack all experts into a leading expert axis, producing the fused `gate_up_proj` / `down_proj` tensors that `pack_qmoe_expert_weights` consumes. No-op on already-fused (Olive) checkpoints. - Wire the generic MoE models (`MoECausalLMModel`, `Qwen2MoECausalLMModel`, `Ernie45MoECausalLMModel`, `Glm4MoECausalLMModel`) through `preprocess_quantized_weights(qmoe_target_path=".mlp")` via a shared `_preprocess_moe_weights` helper. - Symmetric GPTQ (`sym=True`) drops zero-points on **both** the dense and QMoE paths (implicit zp=8); no zero-point transport is added. Asymmetric zero-point transport stays out of scope. ### Measured (RTX 4060 8 GB, Qwen1.5-MoE-A2.7B-Chat-GPTQ-Int4) - **Graph:** before = 0 QMoE / 1440 Equal; after = **24 QMoE / 0 Equal**, `fc1_experts_weights` populated `[60, 2816, 1024]` (was 96 empty initializers). - **Numerical equivalence** (fp32, same weights, dense per-expert MatMulNBits vs fused QMoE, CUDA): identical greedy output ("Paris"), identical token stream, **identical top-5**, **max abs first-step logit diff 0.072** / mean 0.0058 over 151,936 logits. This magnitude is consistent with fused-SwiGLU FP accumulation order, not a wrong expert mapping (a permutation would diverge massively). Per-tensor validation additionally proved the fused `fc1/fc2` weights+scales are a **byte-exact** rearrangement of the source experts (1080 checks across 3 layers × 60 experts, 0 failures). - **fp16 note:** the fp16 build produces garbage under `onnxruntime` 1.27.0 because the ORT QMoE CUDA kernel is **fp32-activation-only** (a known runtime kernel constraint, independently recorded on the H200 team's side). The fp32 build runs correctly. This is a runtime kernel property, not an emission bug — the fused graph itself is correct. ### Tests - `TestStackPerExpertMoEWeights` (5 tests): fused shape, gate-first/up-second row ordering, expert-axis order preservation (catches permutation), Olive already-fused no-op, non-expert passthrough. - `TestPreprocessQuantizedWeights::test_per_expert_gptq_moe_produces_populated_fused_qmoe`: end-to-end per-expert GPTQ → populated non-empty `fc1/fc2_experts_weights` with a leading expert axis and no surviving per-expert tensors. - `pytest src/mobius/_weight_utils_test.py src/mobius/components/_moe_test.py src/mobius/rewrite_rules/_qmoe_fusion_test.py` → **162 passed**. `ruff check` + `ruff format --check` clean. (`tests/moe_integration_test.py` needs `onnxruntime_easy`, absent on this box.) --------- Co-authored-by: Copilot <[email protected]>
Summary
Consolidates #491, #493, and #494 into a single PR (closing all three) to
simplify review. This is the full chain of fixes needed to take an
Olive-quantized (RTN,
moe=true) Qwen3.5-MoE checkpoint all the waythrough
MobiusBuilderexport and actually run the result withonnxruntime-genai— not just structurally export it.Three commits, each independently tested and lint-clean:
1. Fix Olive quantized-weight suffix mismatch (was #491)
preprocess_olive_weightsmatched Olive's dotted quantized-weight suffixconvention (
.qweight/.qzeros/.scales), but Olive actually emitsan underscore convention. Fixes weight loading for any Olive-quantized
checkpoint.
2. Thread
linear_classthrough Qwen3.5 self_attn/linear_attn/shared_expert (was #493, closes #492)Qwen35Attention,GatedDeltaNet, andQwen2MoELayer(shared_expert/shared_expert_gate) didn't accept alinear_classparameter, soquantization couldn't be threaded into them the way it is for other
components. Added
linear_classparams and a_linear_factory()helper inqwen35.py(mirroringdeepseek.py's existing pattern), verified against atiny Qwen3.5-MoE model with RTN quantization (no
modules_to_not_convertexclusions needed).
qwen3_next.py(Qwen3-Coder-Next, reusing the sameQwen35Attention/GatedDeltaNetcomponents) intentionally not touched — no regression sincelinear_classdefaults toNone, and itsQwen3NextMoEBlockhas no QMoEwiring at all (separate, larger gap, noted as a possible follow-up).
3. Fix QMoE routing/layout bugs + genai_config detection (was #494)
Actually loading/running the exported model with
onnxruntime_genai(rather than just checking that MobiusBuilder could structurally export it)
surfaced five further bugs, fixed one at a time and re-verified by re-running
inference after each:
"weight"graph input —MoELayer._qmoe_forward()calledself.gate.qmoe_routing()directly,bypassing
Module.__call__'s parameter-realization step. Fixed bymanually pushing the gate's module scope first (mirrors the existing
pattern in
gemma4_assistant.py).router_probshard-cast to float32 instead of matchinghidden_states' dtype (QMoE's
router_probsshares type constraintTwith
inputpercontrib_defs.cc). Fixed withCastLike.swiglu_fusion=2(concatenated) unsupported by the CPU QMoE kernelin this ORT build (only
swiglu_fusion=1, interleaved, works). Fixed byreordering fc1 gate/up rows into the interleaved layout via a
graph-level reshape/transpose/reshape (folded away at session load since
it operates on a constant initializer), matching the existing pattern
already used for unquantized MoE in
gemma4.py.router_probs/router_weightsleft 3D when QMoE requires strictly2D. Added
_flatten_to_2d().past_present_share_bufferauto-detection ignoredLinearAttention(recurrent state, e.g. Qwen3.5's GatedDeltaNet), defaulting to
Falseforhybrid models and causing a hard load failure (
RecurrentState requires past_present_share_buffer=true). Fixed by also detectingLinearAttentionnodes.
Testing
pytestacross all affected suites (qwen35_test.py,_qwen35_mtp_test.py,_attention_test.py,_gated_deltanet_test.py,_moe_test.py,_mlp_test.py,_weight_utils_test.py,deepseek_test.py,integrations/ort_genai/) — 381 passed.ruff checkon all changed files — clean.Rtn(bits=4, group_size=16, sym=true, moe=true)→MobiusBuilderexport of a tiny Qwen3.5-MoE test model, followed byactually loading and generating with
onnxruntime_genai.Model(...).Execution progressed past each of the 5 QMoE/genai_config bugs above in
turn as they were fixed, confirming the full weight-loading → QMoE →
LinearAttention pipeline is now structurally and semantically correct up
to a separate, unrelated limitation specific to the tiny test model's
abnormally small
head_dim(a GQA rotary-cache-size kernel constraint —a test-model-scale artifact, not 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, so it'sleft untouched as a possible future follow-up.
deepseek.py'sqmoe_routing()does its own float32 upcasting fornumerical stability, independent of this PR's scope.
Closes #492.