Repository navigation
Fix GLM-5.2 (glm_moe_dsa) opset import + KV-cache shape bugs found via real export - #560
Merged
Merged
Conversation
…a real export Two real bugs surfaced while exporting the tiny GLM-5.2 fixture through the production build_from_module() pipeline for onnx-genai e2e testing (#555 had only been exercised through a manual registry.get()+task.build() path that skips shape inference): 1. GlmMoeDsaAttention's IndexShare call never registered the pkg.nxrt opset_imports entry (unlike BlockQuantizedMatMul in _quantized_linear.py, which does this explicitly). The ONNX checker rejects "No opset import for domain 'pkg.nxrt'" on a non-quantized DSA export; this was previously masked because quantized fixtures also emit BlockQuantizedMatMul on the same domain, incidentally registering the import as a side effect. Fixed by adding the same explicit registration before the IndexShare call. 2. glm_moe_dsa was registered without a dedicated task, so it fell back to the generic CausalLMTask, which declares uniform per-head [batch, num_heads, seq, head_dim] past/present KV cache shapes. GLM's DSA attention (GlmMoeDsaAttention._pack_present/_unpack_past) packs the indexer's key cache into the SAME present-KV tensor as the main attention at a per-layer-varying width ("full" indexer layers add index_head_dim extra key columns; "shared" layers don't) -- a genuinely different, valid convention the generic task's uniform-shape assumption can't express. This produced a graph-build-time Squeeze shape-mismatch, previously invisible because a broad except Exception in the shape-inference pass silently swallowed it as an "upstream bug". Fixed with a new GlmMoeDsaTask (mirroring the DeepSeekV4Task precedent for models needing a dedicated cache convention): delegates to CausalLMTask unchanged for config.use_dsa=False (--glm-full-attention fallback, which already builds a plain dense MLA model correctly), and for config.use_dsa=True builds explicit per-layer past/present KV I/O by reading exact dims off the constructed module via a new GlmMoeDsaCausalLMModel.dsa_kv_cache_specs() method, so the task can never drift from what _pack_present/_unpack_past actually produce. Also: - Added a glm_moe_dsa entry to tests/_test_configs.py's ALL_CAUSAL_LM_CONFIGS (shape-shrunk from the real zai-org/GLM-5.2 config.json), which exposed both bugs above through existing coverage tests, plus a documented no-op MTP-drop note (transformers==5.15.0's glm_moe_dsa modeling code has no MTP module and hardcodes _keys_to_ignore_on_load_unexpected for the trailing MTP layer -- base model generation legitimately excludes MTP, matching upstream). - Added glm_moe_dsa to model_coverage_test.py's _COVERAGE_SKIP (no small public checkpoint), matching the deepseek_v3/deepseek_v4 precedent. - Added glm_moe_dsa to synthetic_parity_test.py's _SKIP_REASONS: the default DSA/IndexShare path emits a custom pkg.nxrt domain op with no stock-ORT registration, so this generic harness can never execute it; DSA numerics are covered by glm_moe_dsa_test.py's dedicated indexer parity test and onnx-genai's native e2e regression test instead. Tests: - glm_moe_dsa_test.py: 21/21 passed - _registry_test.py + _builder_test.py: 43/43 passed - model_coverage_test.py + build_graph_test.py (glm_moe_dsa/deepseek filter): 57 passed, 8 skipped - synthetic_parity_test.py + weight_alignment_test.py (glm_moe_dsa filter): 1 passed, 1 skipped (documented skip, not silent) - Full model_coverage_test.py + build_graph_test.py + synthetic_parity_test.py + weight_alignment_test.py: 2434 passed, 341 skipped, 62 xfailed, 3 pre-existing unrelated failures (gemma4/gemma3n multimodal audio_features None, modernbert-decoder L3 tolerance) -- confirmed unrelated to any file touched here - ruff check + ruff format --check: clean Co-authored-by: Copilot <[email protected]>
Performance Comparison
|
Contributor
There was a problem hiding this comment.
Pull request overview
Fixes two export-time correctness issues in the glm_moe_dsa (GLM-5.2) implementation that only surfaced when running the full production build_from_module() pipeline (incl. ONNX checker / shape inference), and extends test fixtures to prevent regressions.
Changes:
- Register the
pkg.nxrtopset import before emittingpkg.nxrt::IndexShare, preventing ONNX-checker failures for non-quantized exports. - Introduce a dedicated
GlmMoeDsaTaskthat declares DSA’s packed, per-layer-varying KV-cache shapes (and stamps explicit present.* types/shapes). - Add a tiny
glm_moe_dsatest config and update coverage/parity skip lists to reflect runtime limitations of the customIndexShareop.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated no comments.
Show a summary per file
| File | Description |
|---|---|
| tests/synthetic_parity_test.py | Skips synthetic parity for glm_moe_dsa due to pkg.nxrt::IndexShare being unsupported in the generic stock-ORT harness. |
| tests/model_coverage_test.py | Adds glm_moe_dsa to coverage skip list (no small public checkpoint). |
| tests/_test_configs.py | Adds a shape-shrunk glm_moe_dsa tiny config fixture to exercise production build/export paths. |
| src/mobius/tasks/_glm_moe_dsa.py | New task that declares/stamps GLM DSA packed KV-cache I/O per layer. |
| src/mobius/tasks/init.py | Exports/registers GlmMoeDsaTask under the glm-moe-dsa task key. |
| src/mobius/models/glm_moe_dsa.py | Adds explicit pkg.nxrt opset import for IndexShare and exposes dsa_kv_cache_specs() for the task. |
| src/mobius/_registry.py | Routes glm_moe_dsa registration through the dedicated glm-moe-dsa task. |
💡 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) |
Copilot AI
added a commit
that referenced
this pull request
Aug 23, 2026
Adopt main's dedicated GlmMoeDsaTask implementation from #560 and retain focused production-task cache layout regression coverage. Signed-off-by: GitHub <[email protected]> Co-authored-by: justinchuby <[email protected]>
justinchuby
added a commit
that referenced
this pull request
Aug 23, 2026
#560 landed the real fix for glm_moe_dsa while this branch was open: a dedicated GlmMoeDsaTask supplying the packed KV-cache shape the model's _unpack_past expects, plus its own tiny config and a _COVERAGE_SKIP entry. That makes both of my stopgaps redundant, and one actively harmful: * tests/_test_configs.py had two "glm_moe_dsa" entries after the merge, so every parametrized case ran twice as glm_moe_dsa_0 / glm_moe_dsa_1 and each failure was reported twice. Removed mine; #560's is shape-shrunk from the real zai-org/GLM-5.2 config.json and is better sourced. * testdata/cases/causal-lm/glm-5.2.yaml existed only to satisfy model_coverage_test, which #560 now satisfies via _COVERAGE_SKIP. A YAML case that can never run (753B across 282 shards) is worse than an explicit skip with a stated reason. The invalid Squeeze I reported in #557 is fixed by #560 as well, so synthetic_parity[glm_moe_dsa] passes again rather than being skipped. Two glm_moe_dsa failures remain (test_onnx_checker_passes, test_outputs_have_shapes_and_dtypes). Verified those reproduce on a clean origin/main worktree, so they are not from this branch and not from the dedupe. Full suite on this branch: 11 failed / 7169 passed. All 11 pre-existing — 8 arch_validation (network-dependent), the 2 glm_moe_dsa above, and synthetic_parity[granitemoehybrid]. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 43bb31ac-c136-44bc-8cdf-70cbcedd4a42 Signed-off-by: Copilot <[email protected]>
justinchuby
added a commit
that referenced
this pull request
Aug 23, 2026
## 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]>
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 exporting a tiny GLM-5.2 (
glm_moe_dsa) fixture through the productionbuild_from_module()pipeline (for an onnx-genai end-to-end native-runtime test), two real, previously-undetected bugs surfaced in#555's GLM-5.2 support.#555had only ever been exercised through a manualregistry.get()+task.build()sequence that skips shape inference and the ONNX checker — this is the first time the model has gone through the full production pipeline.Bug 1: missing
pkg.nxrtopset importGlmMoeDsaAttention'sop.IndexShare(...)call (custompkg.nxrt-domain op) never registeredopset_imports["pkg.nxrt"] = 1. The ONNX checker rejects this with "No opset import for domain 'pkg.nxrt'". This was previously masked because quantized fixtures also emitBlockQuantizedMatMulon the same domain, incidentally registering the import as a side effect — but a float/non-quantized DSA export produces an invalid graph. Fixed by adding the same explicit registration_quantized_linear.py'sBlockQuantizedMatMulalready does, right before theIndexSharecall.Bug 2: KV-cache shape mismatch (needs a dedicated task)
glm_moe_dsawas registered with the genericCausalLMTask, which declares uniform per-head[batch, num_heads, seq, head_dim]past/present KV shapes. GLM's DSA attention (_pack_present/_unpack_past) instead packs the indexer's key cache into the same present-KV tensor as the main attention, at a per-layer-varying width — "full" indexer layers addindex_head_dimextra key columns, "shared" layers don't. This produced a graph-build-timeSqueezeshape mismatch, previously invisible because a broadexcept Exceptionin the shape-inference pass silently swallowed it as an "upstream bug" warning.Fixed with a new
GlmMoeDsaTask(mirrors theDeepSeekV4Taskprecedent for models needing a dedicated cache convention):config.use_dsa=False(--glm-full-attentionfallback): delegates unchanged toCausalLMTask, which already builds the plain dense MLA model correctly.config.use_dsa=True: builds explicit per-layer past/present KV I/O by reading exact dims off the constructed module via a newGlmMoeDsaCausalLMModel.dsa_kv_cache_specs()method, so the task can never drift from what_pack_present/_unpack_pastactually produce.Also in this PR
tests/_test_configs.py: newglm_moe_dsaentry inALL_CAUSAL_LM_CONFIGS, shape-shrunk from the realzai-org/GLM-5.2config.json. This addition is what exposed both bugs above via existing coverage tests. Includes a documented note on why MTP weights (num_nextn_predict_layers=1in the real checkpoint) are legitimately unused:transformers==5.15.0'sglm_moe_dsamodeling code has no MTP module and hardcodes_keys_to_ignore_on_load_unexpectedfor the trailing MTP layer.tests/model_coverage_test.py:glm_moe_dsaadded to_COVERAGE_SKIP(no small public checkpoint), matchingdeepseek_v3/deepseek_v4precedent.tests/synthetic_parity_test.py:glm_moe_dsaadded to_SKIP_REASONS— the default DSA/IndexShare path emits a custompkg.nxrtop with no stock-ORT registration, so this generic harness can never execute it; DSA numerics are covered separately byglm_moe_dsa_test.py's dedicated indexer parity test and onnx-genai's native e2e regression test.Tests
glm_moe_dsa_test.py: 21/21 passed_registry_test.py+_builder_test.py: 43/43 passedmodel_coverage_test.py+build_graph_test.py(glm_moe_dsa/deepseek filter): 57 passed, 8 skippedsynthetic_parity_test.py+weight_alignment_test.py(glm_moe_dsa filter): 1 passed, 1 skipped (documented skip, not silent)model_coverage_test.py+build_graph_test.py+synthetic_parity_test.py+weight_alignment_test.py: 2434 passed, 341 skipped, 62 xfailed, 3 pre-existing failures unrelated to this diff (gemma4/gemma3n multimodalaudio_featuresNone, modernbert-decoder L3 tolerance) — confirmed unrelated by inspecting touched filesruff check+ruff format --check: clean_pack_present/_unpack_past, and re-running the full test suite) — no findingsContext
This is a follow-up to #555 (GLM-5.2 model support), discovered while building the onnx-genai end-to-end test fixture. Scope is intentionally limited to these two bugs plus the test-config gap that exposed them — no GLM-5.2 registration semantics, MoE routing, YaRN, or attention changes beyond the two fixes above.
Working as Sapper (Systems Dev for Models & Preprocess).
Co-authored-by: Copilot [email protected]