Skip to content

Fix GLM-5.2 (glm_moe_dsa) opset import + KV-cache shape bugs found via real export - #560

Merged
justinchuby merged 1 commit into
mainfrom
feat/glm52-e2e-fixture
Aug 23, 2026
Merged

justinchuby merged 1 commit into
mainfrom
feat/glm52-e2e-fixture

Conversation

@justinchuby

Copy link
Copy Markdown
Member

Summary

While exporting a tiny GLM-5.2 (glm_moe_dsa) fixture through the production build_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. #555 had only ever been exercised through a manual registry.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.nxrt opset import

GlmMoeDsaAttention's op.IndexShare(...) call (custom pkg.nxrt-domain op) never registered opset_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 emit BlockQuantizedMatMul on 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's BlockQuantizedMatMul already does, right before the IndexShare call.

Bug 2: KV-cache shape mismatch (needs a dedicated task)

glm_moe_dsa was registered with the generic CausalLMTask, 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 add index_head_dim extra key columns, "shared" layers don't. 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" warning.

Fixed with a new GlmMoeDsaTask (mirrors the DeepSeekV4Task precedent for models needing a dedicated cache convention):

  • config.use_dsa=False (--glm-full-attention fallback): delegates unchanged to CausalLMTask, 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 new GlmMoeDsaCausalLMModel.dsa_kv_cache_specs() method, so the task can never drift from what _pack_present/_unpack_past actually produce.

Also in this PR

  • tests/_test_configs.py: new glm_moe_dsa entry in ALL_CAUSAL_LM_CONFIGS, shape-shrunk from the real zai-org/GLM-5.2 config.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=1 in the real checkpoint) are legitimately unused: 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.
  • tests/model_coverage_test.py: glm_moe_dsa added to _COVERAGE_SKIP (no small public checkpoint), matching deepseek_v3/deepseek_v4 precedent.
  • tests/synthetic_parity_test.py: glm_moe_dsa added to _SKIP_REASONS — the default DSA/IndexShare path emits a custom pkg.nxrt op with no stock-ORT registration, so this generic harness can never execute it; DSA numerics are covered separately by glm_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 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 failures unrelated to this diff (gemma4/gemma3n multimodal audio_features None, modernbert-decoder L3 tolerance) — confirmed unrelated by inspecting touched files
  • ruff check + ruff format --check: clean
  • Independent review completed (verified fixes by reproducing pre-fix failures on the parent commit, tracing exact shape math through _pack_present/_unpack_past, and re-running the full test suite) — no findings

Context

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]

…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]>
@justinchuby
justinchuby requested review from a team and a lite review from Copilot August 23, 2026 04:12
@justinchuby
justinchuby merged commit d33c33b into main Aug 23, 2026
17 checks passed
@justinchuby
justinchuby deleted the feat/glm52-e2e-fixture branch August 23, 2026 04:13
@github-actions

Copy link
Copy Markdown

Performance Comparison

Comparing b4dcf43 → cb05fb2

Model Metric Baseline Current Delta
bert (feature-extraction) model_size_bytes 359 KB 359 KB +0.0% ⚪
bert (feature-extraction) num_nodes 68 68 +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 176 176 +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.

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

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.nxrt opset import before emitting pkg.nxrt::IndexShare, preventing ONNX-checker failures for non-quantized exports.
  • Introduce a dedicated GlmMoeDsaTask that declares DSA’s packed, per-layer-varying KV-cache shapes (and stamps explicit present.* types/shapes).
  • Add a tiny glm_moe_dsa test config and update coverage/parity skip lists to reflect runtime limitations of the custom IndexShare op.

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.

@github-actions

Copy link
Copy Markdown

🏗️ Architecture Diff

Comparing b4dcf43 → cb05fb2

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)

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]>
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.

2 participants