Repository navigation
Fuse DeepSeek-V4 routed experts into a single QMoE op per layer - #550
Conversation
DeepSeekV4MoE previously exported routed experts as a hand-rolled Python loop over num_local_experts (up to 256), emitting one MatMulNBits triple plus mask/select ops per expert. Replace it with the shared MoELayer's existing QMoE fusion (already used by DeepSeek-V3), so each layer's routed experts collapse into a single com.microsoft::QMoE node. DeepSeekV4Gate's hash-routing/top-k selection math is preserved byte-for-byte (forward() is reused verbatim). Since hash-table lookups and DeepSeek-V4's noaux_tc-style bias-corrected top-k select a different tensor than the one used for weighting, they cannot express selection as "top-k of a score" (QMoE's only selection ABI). A new DeepSeekV4Gate.qmoe_routing() adapts the already-selected (routing_weights, selected_experts) pair into QMoE's full-width (router_probs, router_weights) tensors via a new _scatter_selected_to_full helper (ScatterElements-based), reusing QMoE's optional router_weights input (gathered at the selected experts) rather than re-deriving selection/weights from a full score tensor. Clipped-SwiGLU attributes (activation_alpha=1.0, activation_beta=0.0, swiglu_limit) are threaded through MoELayer/_qmoe_forward with backward-compatible None defaults, so existing MoELayer callers are unaffected. Weight preprocessing renames the gate to mlp.moe.gate.* (was mlp.gate.*) unconditionally, and routed experts to mlp.moe.experts.*i* only for the dense (non-QMoE) fallback; the QMoE-eligible path instead wires stack_per_expert_moe_weights + pack_qmoe_expert_weights over the unrenamed per-index experts. GGUF tensor mapping is updated to match the new gate path (3 entries in _DEEPSEEK4_MAPPING); the GGUF experts mapping is left untouched (pre-existing, separate architectural gap: GGUF's fused expert tensors are incompatible with both the dense per-index format and pack_qmoe_expert_weights' expected input, and this predates this change -- affects V3/Qwen2MoE/Qwen3MoE the same way). preprocess_weights now validates that every hash-routing table names top_k distinct experts per token before reaching the graph: ScatterElements overwrites rather than accumulates duplicate indices, so a repeated expert would otherwise silently drop a contribution instead of erroring. Structural evidence (test_qmoe_eligible_quantization_fuses_routed_experts_into_one_qmoe_per_layer): at the real DeepSeek-V4 scale of 256 routed experts, this reduces a 2-layer graph from 1554 MatMulNBits / 7508 total nodes down to a constant 18 MatMulNBits / 633 total nodes (independent of expert count), with exactly one QMoE node per layer. Numeric correctness (deepseek_v4_test.py) is proven against a pure-numpy dense reference for hash-routed, clipped-SwiGLU, int4 block-quantized experts, executed via real ORT CPUExecutionProvider, for both single-block and multi-block quantization layouts; both new tests were verified to fail against the pre-change code. Known runtime gap (pre-existing, not introduced by this change, and already present in DeepSeek-V3's merged QMoE gate): ORT's CUDA QMoE kernel ignores the router_weights input entirely, always deriving per-token weights via its own softmax-top-k over router_probs. This makes any gate whose selection tensor differs from its weighting tensor (hash routing, or noaux_tc-style bias-corrected top-k) CPU-EP-correct only until CUDA support lands -- tracked upstream at microsoft/onnxruntime#31570 (open draft PR). Documented in _scatter_selected_to_full, DeepSeekV4Gate.qmoe_routing, and (as a pre-existing gap made explicit) DeepSeekMoEGate.qmoe_routing. Also fixes two DeepSeekV4 tests whose assertions referenced the old mlp.gate.*/mlp.experts.* attribute paths, now mlp.moe.gate.*/ mlp.moe.experts.*. Co-authored-by: Copilot <[email protected]>
Performance Comparison
|
There was a problem hiding this comment.
Pull request overview
This PR refactors DeepSeek-V4’s routed-expert MoE export to use a single fused com.microsoft::QMoE op per layer (via the shared MoELayer infrastructure), replacing the prior per-expert unrolled MatMulNBits/mask/select loop while keeping DeepSeek-V4 gate selection math unchanged. It also adds weight-preprocess validation for hash-routing tables (distinct experts per token) and expands tests to cover both structural fusion evidence and numerical parity against a dense reference.
Changes:
- Add a QMoE routing adapter (
_scatter_selected_to_full) and extendMoELayerto support gate args + clipped-SwiGLU attributes while preserving existing callsites. - Update DeepSeek-V4 model export and weight preprocessing to route through
MoELayer+ QMoE packing, including validation for duplicate expert indices in hash routing tables. - Add new DeepSeek-V4 QMoE correctness/structure tests; update DeepSeek-V4 flash tests and GGUF tensor mappings for the new gate path.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| src/mobius/models/deepseek.py | Expands qmoe_routing docstring to document the CPU-vs-CUDA router_weights limitation and upstream tracking. |
| src/mobius/models/deepseek_v4.py | Switches routed experts to MoELayer (QMoE when eligible), adds qmoe_routing adapter for V4 gate, validates hash tables, and packs QMoE expert weights. |
| src/mobius/models/deepseek_v4_test.py | Adds a new CPU-EP numerical parity fixture vs a dense NumPy reference + structure assertions for fused QMoE export. |
| src/mobius/models/deepseek_v4_flash_test.py | Updates parameter-path assertions for the new mlp.moe.gate location; adds structural fusion test and preprocess duplicate-expert validation tests. |
| src/mobius/integrations/gguf/_tensor_mapping.py | Updates DeepSeek-V4 GGUF mapping keys to the new mlp.moe.gate.* path. |
| src/mobius/integrations/gguf/_tensor_mapping_test.py | Updates DeepSeek-V4 mapping expectations to match the new gate path. |
| src/mobius/components/_moe.py | Introduces _scatter_selected_to_full and extends MoELayer to support gate args, custom expert factories, and optional clipped-SwiGLU QMoE attributes. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| ) | ||
|
|
||
|
|
||
| def _run_layer(layer, hidden_values: np.ndarray, input_ids_values: np.ndarray) -> np.ndarray: |
🏗️ Architecture Diff
No architecture changes detected. ✅ Legend: ⚪ No change · 🔵 Minor (attrs/inits) · 🟡 Moderate (nodes added/removed) · 🔴 Major (interface changed) |
## Root cause `_DeepSeekMoEFFN.__init__` (src/mobius/models/deepseek.py) accepted `linear_class` but only forwarded it to `_SharedExpertMLP`, not to the `MoELayer` that builds the routed-expert dense loop-over-experts fallback: ```python self.moe = MoELayer(config, gate=gate) # linear_class silently dropped ``` Consequence: a quantized config correctly quantized attention, dense FFN, and the shared expert, but every routed MoE expert's gate/up/down projections stayed plain float `MatMul`. This both loses quantization for the routed experts and breaks the `fuse_dense_moe_to_qmoe` post-hoc rewrite, which only pattern-matches a quantized `MatMulNBits` dense-fallback shape — so a quantized DeepSeek-V2/V3 config would silently fail to fuse into QMoE for its routed experts. DeepSeek-V4 is unaffected: its `DeepSeekV4MoE` uses `expert_factory` to build `_DeepSeekV4Expert`, which independently recomputes its quantized class from `config.quantization` per-expert rather than relying on `MoELayer`'s `linear_class` forwarding — verified via review, no matching fix needed there. ## Fix One line: thread `linear_class` through to the routed-expert `MoELayer`: ```python self.moe = MoELayer(config, gate=gate, linear_class=linear_class) ``` ## Tests Added `test_deepseek_moe_ffn_linear_class_reaches_routed_experts` in `deepseek_test.py`, which isolates the assertion on `module.moe.experts` (routed) separately from `module.shared_experts` (already worked before this fix), rather than relying on an aggregate creation count — so it can't pass for the wrong reason. - Verified the new test **fails** on pre-fix code (`assert False` at the routed-experts isinstance check) and **passes** post-fix. - Full suite: `PYTHONPATH=src python3 -m pytest src/` → **3249 passed, 9 skipped**, no failures. - `ruff check` / `ruff format --check` on changed files: clean. - Independently reviewed (separate reviewer pass over the diff); verdict: **Approve**, no findings. ## Scope Deliberately minimal and focused: does not touch GLM-5.2 registration, DeepSeek-V4 QMoE export, YaRN, or any other follow-up — those are tracked/ landed separately (#548, #550, #555, #559, #560). Co-authored-by: Copilot <[email protected]> Co-authored-by: Copilot <[email protected]>
## Summary - clean up still-valid typing, documentation, test robustness, error-message, maintainability, and performance findings left by the GGUF PR stack - preserve the behavioral fixes merged in #625-#632 - hash reused multi-GB GGUF sources once, at the final pre-publication integrity gate, while retaining cheap identity checks around staging Exact base: `2db9d33debdc254d879a51b14434c9a81c230f4f` Exact head: `4541ed2bc9d2ab4227484510b4a85b2d9113eb25` ## Reconstructed original 17-item low-priority tranche The persisted audit retained only the totals, so this list was reconstructed from the live threads and current source. All but the already-fixed #596 comment are addressed in this PR. | PR | Comment | Disposition | |---|---:|---| | #550 | 3837144656 | Implemented: correct tuple return annotation | | #552 | 3837389183 | Implemented: multichannel waveform shape docs | | #559 | 3837716261 | Implemented: name-based cache assertions | | #573 | 3854308350 | Implemented: one final GGUF hash, with integrity regression coverage | | #574 | 3854345521 | Implemented: `TensorRole \| None` typing | | #574 | 3854345597 | Implemented: removed obsolete verdict filtering | | #577 | 3854472859 | Implemented: documented SSM sequence length | | #578 | 3843112613 | Implemented: documented F64 passthrough | | #579 | 3854518332 | Implemented: generalized fused-projection error | | #580 | 3854576300 | Implemented: removed brittle node counts | | #583 | 3854681386 | Implemented: documented conditional draft outputs | | #587 | 3854816872 | Implemented: corrected MTP output contract docs | | #596 | 3846110059 | Already fixed on base: unambiguous GQA bias comment | | #600 | 3855174281 | Implemented: metadata-count-only MTP error | | #607 | 3855776048 | Implemented: stable route-field assertions | | #607 | 3855776086 | Implemented: public tensor iterator | | #609 | 3856486136 | Implemented: fail-closed LM-head comment | ## Current unresolved-thread disposition This covers all 48 Copilot threads returned by the reproducible #600-#630 query. The one human #623 thread is excluded. | PR | Comment | Current-main disposition and evidence | |---|---:|---| | #600 | 3855174177 | Already fixed by #629: package cycle and reserved-sidecar validation | | #600 | 3855174238 | Already fixed by #629: explicit MTP sidecar naming/loading | | #600 | 3855174281 | Implemented here: error no longer invents an observed block count | | #602 | 3848155961 | Outside exact stack; already fixed: top-level `expert_dtype` is classified before early return | | #602 | 3848155983 | Outside exact stack; still-valid behavioral block-quant validation, unchanged | | #602 | 3848156000 | Outside exact stack; still-valid truncated-read behavioral finding, unchanged | | #602 | 3848156022 | Outside exact stack; still-valid descriptor byte/dtype validation, unchanged | | #602 | 3848156040 | Outside exact stack; still-valid expert-bank payload validation, unchanged | | #603 | 3855249765 | Already fixed by #630: runtime preflight preserves shard sets | | #603 | 3855249840 | Already fixed by #630: success output follows durable runtime publication | | #604 | 3855343082 | Implemented here: graph-only MTP persistence distinguished from runtime rejection | | #604 | 3855343131 | Already fixed by #630: runtime success messages are atomic | | #607 | 3855776001 | Implemented here: missing generation golden skips before provenance read | | #607 | 3855776048 | Implemented here: only stable route fields are asserted | | #607 | 3855776086 | Implemented here: tensor count uses `tensor_items_raw()` | | #608 | 3856079371 | Still-valid behavioral cache-symlink containment finding; unchanged | | #608 | 3856079415 | Still-valid behavioral lowercase-digest validation finding; unchanged | | #609 | 3856486136 | Implemented here: comment matches value-preserving policy | | #610 | 3855541683 | Already fixed by #628: Falcon bias precedence is explicit | | #610 | 3855541761 | Already fixed by #628: CTRL tiny config exercises projection biases | | #611 | 3856595840 | Implemented here: runtime test resolves the distribution providing the module | | #612 | 3855677383 | Already fixed by #625: supported-version endianness detection | | #612 | 3855677427 | Implemented here: shared `INT64_MAX` sentinel | | #612 | 3855677460 | Implemented here: shared PLaMo2 width inference | | #612 | 3855677486 | Implemented here: accepted PLaMo2 activation spellings are explicit | | #613 | 3855845678 | Implemented here: canonical issue URL | | #613 | 3855845757 | Implemented here: Mamba-1 function-registration docs | | #613 | 3855845806 | Implemented here: test expects the canonical issue URL | | #614 | 3855988545 | Implemented here: removed stale Nemotron-H divergence comments | | #614 | 3855988597 | Already fixed by #628: zero-head geometry raises actionable `ValueError` | | #615 | 3856082290 | Already fixed by #626: dense GraniteHybrid bias closure | | #618 | 3856729330 | Implemented here: required routes filter ORT GenAI evidence | | #618 | 3856729409 | Implemented here: env-selected runtime version is authoritative | | #618 | 3856729490 | Stale/N/A: PR-description-only matrix claim; repository workflow claims one pinned version | | #618 | 3856729563 | Implemented here: schema tail restored to normal indentation | | #619 | 3856342484 | Already fixed on base: Kimi Linear uses `/issues/605` | | #619 | 3856342532 | Already fixed by #628: config rejects convolution kernels below 2 | | #619 | 3856342580 | Already fixed by #628: GGUF contract rejects convolution kernels below 2 | | #620 | 3855717041 | Already fixed by #627: tied LM-head-only checkpoints are retained | | #621 | 3856722324 | Already fixed by #628: Kimi-K3 required metadata is complete | | #623 | 3855931210 | N/A to current main: comment belongs to open, unmerged #623 | | #623 | 3855939302 | N/A to current main: comment belongs to open, unmerged #623 | | #623 | 3855939358 | N/A to current main: comment belongs to open, unmerged #623 | | #623 | 3855939394 | N/A to current main: comment belongs to open, unmerged #623 | | #624 | 3856777152 | Implemented here: runtime compatibility reuses the emitted model type | | #625 | 3857049733 | Implemented here: unsupported header reports both endian candidates | | #629 | 3857313182 | Newer post-audit behavioral sidecar-symlink cleanup finding; unchanged | | #629 | 3857313251 | Newer post-audit cross-platform path-safety finding; unchanged | ## Validation - affected GGUF/package/ORT GenAI/model/schema tests: 1,040 passed - broad non-integration suite: 7,851 passed, 56 skipped, 1 subtest passed - generated GGUF docs checks: 7 passed - initialized `lintrunner`; full lint/format passed - GPT-5.6 Sol medium review: one integrity finding fixed; re-review found no significant issues Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]>
Summary
Working as Sapper (Systems Dev for Models & Preprocess). This is a dedicated vertical slice: replace DeepSeek-V4's routed-expert MoE export (a hand-rolled Python loop over
num_local_experts, up to 256, emitting oneMatMulNBitstriple + mask/select ops per expert) with a single fusedcom.microsoft::QMoEop per layer, reusing the sharedMoELayerinfra already used by DeepSeek-V3.DeepSeekV4Gate's hash-routing/top-k selection math is unchanged —forward()is reused verbatim.Root cause / design
DeepSeek-V4 routes experts two ways depending on layer depth:
layer_id < num_hash_layers): atid2eidlookup table, entirely independent of any per-expert score.noaux_tc-style bias-corrected top-k — selection usesscores + bias, but the actual mixing weight is gathered from the unbiasedscorestensor.Both cases select via a tensor that differs from the one used for weighting, so selection can't be expressed as "top-k of a score" — QMoE's only native selection ABI. A new
DeepSeekV4Gate.qmoe_routing()adapts the gate's already-selected(routing_weights, selected_experts)pair into QMoE's full-width(router_probs, router_weights)tensors via a new_scatter_selected_to_fullhelper (ScatterElements-based):-infeverywhere except a constant positive marker at the selected slots ofrouter_probs(so QMoE's internal top-k recovers exactly the externally-chosen set), and the real weights scattered intorouter_weights(QMoE's optional input 14, gathered at the selected experts,normalize_routing_weights=0).Clipped-SwiGLU attributes (
activation_alpha=1.0,activation_beta=0.0,swiglu_limit) are threaded throughMoELayer/_qmoe_forwardwith backward-compatibleNonedefaults — verified via a full call-site grep that no existingMoELayercaller (V3, Jamba, JetMoE, MiniMax, Qwen2MoE, gpt-oss, etc.) is affected.Weight preprocessing
mlp.moe.gate.*(wasmlp.gate.*) unconditionally.mlp.moe.experts.{i}.*only for the dense (non-QMoE) fallback path.stack_per_expert_moe_weights+pack_qmoe_expert_weightsover the unrenamed per-index expert tensors._DEEPSEEK4_MAPPING, 3 entries) updated to the new gate path. The GGUF experts mapping is left untouched — a pre-existing, separate architectural gap (GGUF's already-fused expert tensors are incompatible with both the dense per-index format andpack_qmoe_expert_weights' expected input); this predates this change and affects V3/Qwen2MoE/Qwen3MoE identically.preprocess_weightsnow validates every hash-routing table namestop_kdistinct experts per token before it reaches the graph:ScatterElementsoverwrites rather than accumulates duplicate indices, so a repeated expert would otherwise silently drop a contribution instead of raising an error. Covered by 2 new tests (reject-with-duplicate / accept-with-distinct).Structural (graph) evidence
test_qmoe_eligible_quantization_fuses_routed_experts_into_one_qmoe_per_layerprovesQMoEnode count ==num_hidden_layersand totalMatMulNBitscount is invariant tonum_local_experts(built with 2 and 8 experts, same counts both times) — unlike the old per-expert loop.Measured directly at DeepSeek-V4's real scale (256 routed experts, 2 layers, one hash-routed + one learned):
MatMulNBitsQMoE(~86x fewer
MatMulNBits, ~11.9x fewer total nodes, at real-config expert count.)Correctness evidence
deepseek_v4_test.py(new) proves numeric equivalence against a pure-numpy dense reference for hash-routed, clipped-SwiGLU, int4 block-quantized experts, executed via real ORTCPUExecutionProvider:test_hash_routed_clipped_swiglu_qmoe_matches_dense_reference[single_block]and[multi_block]— sparse QMoE output vs. dense-loop-with-clipped-SwiGLU numpy reference, plus graph-structure assertions (exactly 1QMoE, 0MatMulNBits, 0Equal).test_qmoe_routing_preserves_hash_selected_experts_and_weights—qmoe_routing()'s scatter adapter reproducesforward()'s exact hash-routed selection/weights, not merely a plausible one.Fail-before/pass-after verified: both new tests were run against the pre-change code (via
git stash) and failed withTypeError/AttributeErroron the new APIs, confirming the fixture genuinely exercises the new code path.Remaining runtime gate (pre-existing, not introduced by this PR)
ORT's CUDA QMoE kernel ignores the
router_weightsinput entirely — confirmed by inspectingcontrib_ops/cuda/moe/moe_quantization.ccupstream (no reference torouter_weightsanywhere in the CUDA EP, vs.contrib_ops/cpu/moe/moe_quantization_cpu.ccwhich gathers it correctly) — and always derives per-token weights via its own softmax-top-k overrouter_probs. Any gate whose selection tensor differs from its weighting tensor (hash routing, or DeepSeek'snoaux_tc-style bias-corrected top-k) is therefore CPU-EP-correct only until CUDA support lands. This is not a regression: DeepSeek-V3's already-mergedDeepSeekMoEGate.qmoe_routinghas the identical exposure (itsqmoe_routingdocstring is now updated to say so explicitly, as a documentation-only touch). Tracked upstream: microsoft/onnxruntime#31570 (open draft PR adding CUDArouter_weightssupport). Documented in code at_scatter_selected_to_full,DeepSeekV4Gate.qmoe_routing, andDeepSeekMoEGate.qmoe_routing.Tests run
Reviewed by an independent code-review pass; the CUDA
router_weightsgap and the unenforced duplicate-expert invariant it flagged are both addressed above (documentation + a new validation + test, respectively). A nit about single-block-only quantization coverage was closed by parametrizing the fixture over single- and multi-block layouts.Explicitly out of scope
GLM-5.2 registration, paging/residency, YaRN/attention changes — none touched.
Closes: N/A (implementation slice per Justin Chu's request; no tracking issue was filed for this specific slice — see audit history in
.squadfor context).