Skip to content

Commit d33c33b

Browse files
justinchubyCopilot
andauthored
Fix GLM-5.2 (glm_moe_dsa) opset import + KV-cache shape bugs found via real export (#560)
## 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]> Co-authored-by: Copilot <[email protected]>
1 parent b4dcf43 commit d33c33b

7 files changed

Lines changed: 197 additions & 1 deletion

File tree

‎src/mobius/_registry.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -584,7 +584,7 @@ def _detect_fallback_registration(hf_config) -> ModelRegistration | None:
584584
"deepseek_v4": ModelRegistration(DeepSeekV4CausalLMModel, task="deepseek-v4"),
585585
"deepseek_vl_v2": ModelRegistration(DeepSeekOCR2CausalLMModel),
586586
# --- GLM-5.2 (MLA + DeepSeek Sparse Attention (DSA) + MoE) ---
587-
"glm_moe_dsa": ModelRegistration(GlmMoeDsaCausalLMModel),
587+
"glm_moe_dsa": ModelRegistration(GlmMoeDsaCausalLMModel, task="glm-moe-dsa"),
588588
# --- SSM (Mamba / Mamba2) ---
589589
"falcon_mamba": ModelRegistration(MambaCausalLMModel),
590590
"mamba": ModelRegistration(MambaCausalLMModel),

‎src/mobius/models/glm_moe_dsa.py‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,11 @@ def _index_share_attention(
394394
value_f32 = op.Cast(padded_value, to=ir.DataType.FLOAT) if needs_cast else padded_value
395395

396396
selected_indices = op.Unsqueeze(topk_indices, [1])
397+
# pkg.nxrt is a custom onnx-genai runtime domain; the ONNX checker
398+
# requires every domain used by a node to have a matching
399+
# opset_imports entry (not automatically added by the op call),
400+
# same as BlockQuantizedMatMul in _quantized_linear.py.
401+
op.builder.graph.opset_imports["pkg.nxrt"] = 1
397402
attn_output = op.IndexShare(
398403
q_f32,
399404
key_f32,
@@ -684,3 +689,31 @@ def preprocess_weights(
684689
filtered = {k: v for k, v in filtered.items() if k not in indexer_keys}
685690

686691
return DeepSeekV3CausalLMModel.preprocess_weights(self, filtered)
692+
693+
def dsa_kv_cache_specs(self) -> list[tuple[int, int]]:
694+
"""Per-layer ``(key_head_dim, value_head_dim)`` for the packed DSA cache.
695+
696+
Only meaningful when ``config.use_dsa`` (``self.model`` is a
697+
:class:`GlmMoeDsaTextModel`): ``GlmMoeDsaAttention._pack_present``
698+
packs the indexer's own key cache into the *same* present-KV tensor
699+
as the main attention (indexer columns appended after the main key
700+
columns), so the key head_dim varies per layer -- "full" indexer
701+
layers add ``index_head_dim`` extra columns, "shared" layers don't
702+
-- unlike the uniform per-layer shape every other registered task
703+
assumes. Reads the exact dims off the already-constructed attention
704+
modules (rather than recomputing from config) so this can never
705+
drift from what ``_pack_present``/``_unpack_past`` actually produce.
706+
Consumed by :class:`mobius.tasks._glm_moe_dsa.GlmMoeDsaTask`.
707+
"""
708+
return [
709+
(
710+
layer.self_attn.main_key_dim
711+
+ (
712+
layer.self_attn.index_head_dim
713+
if layer.self_attn.indexer_type == "full"
714+
else 0
715+
),
716+
layer.self_attn.main_value_dim,
717+
)
718+
for layer in self.model.layers
719+
]

‎src/mobius/tasks/__init__.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
"Gemma4Task",
4343
"Gemma4UnifiedTask",
4444
"Gemma4TextCausalLMTask",
45+
"GlmMoeDsaTask",
4546
"HybridCausalLMTask",
4647
"Cosmos3EdgeVLTask",
4748
"HybridQwenVLTask",
@@ -121,6 +122,7 @@
121122
Gemma4UnifiedTask,
122123
)
123124
from mobius.tasks._gemma4_assistant import Gemma4AssistantTask
125+
from mobius.tasks._glm_moe_dsa import GlmMoeDsaTask
124126
from mobius.tasks._glmasr_speech_language import GlmAsrSpeechLanguageTask
125127
from mobius.tasks._hunyuan_vl_mot import HunYuanVLMoTTask
126128
from mobius.tasks._image_classification import ImageClassificationTask
@@ -222,6 +224,7 @@
222224
"gemma4-text-generation": Gemma4TextCausalLMTask,
223225
"gemma4-unified": Gemma4UnifiedTask,
224226
"gemma4-assistant": Gemma4AssistantTask,
227+
"glm-moe-dsa": GlmMoeDsaTask,
225228
"hunyuan-vl-mot": HunYuanVLMoTTask,
226229
"sensenova-u1": SenseNovaU1Task,
227230
"multimodal": MultiModalTask,

‎src/mobius/tasks/_glm_moe_dsa.py‎

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
# Copyright (c) Microsoft Corporation.
2+
# Licensed under the MIT License.
3+
4+
"""Graph task for GLM-5.2 (``glm_moe_dsa``): DSA's packed IndexShare KV cache."""
5+
6+
from __future__ import annotations
7+
8+
import onnx_ir as ir
9+
10+
from mobius._configs import ArchitectureConfig
11+
from mobius._model_package import ModelPackage
12+
from mobius.tasks._base import ModelTask, _make_graph, _make_model
13+
from mobius.tasks._causal_lm import CausalLMTask
14+
15+
16+
class GlmMoeDsaTask(ModelTask):
17+
"""Causal LM build for GLM-5.2, aware of DSA's packed per-layer KV cache.
18+
19+
``GlmMoeDsaAttention`` (the DSA/IndexShare attention path, default when
20+
``config.use_dsa=True``) packs the indexer's own key cache into the
21+
*same* present-KV tensor as the main attention -- one packed "head" of
22+
width ``main_key_dim`` (plus ``index_head_dim`` extra columns on layers
23+
whose indexer is "full" rather than "shared") -- instead of the generic
24+
per-head ``[batch, num_heads, seq, head_dim]`` convention every other
25+
registered causal-LM task assumes. That per-layer-varying width can't be
26+
expressed by the generic :class:`~mobius.tasks._causal_lm.CausalLMTask`
27+
(uniform shape across layers), so DSA mode needs its own cache
28+
declaration, read directly off the built module via
29+
``GlmMoeDsaCausalLMModel.dsa_kv_cache_specs()`` to guarantee it never
30+
drifts from what ``_pack_present``/``_unpack_past`` actually produce.
31+
32+
``config.use_dsa=False`` (the ``--glm-full-attention`` fallback) builds
33+
a plain dense ``DeepSeekV3TextModel`` with the standard MLA present-KV
34+
convention, which ``CausalLMTask`` already declares correctly -- so
35+
that mode delegates to it unchanged rather than duplicating its
36+
input/output wiring.
37+
"""
38+
39+
def build(self, module, config: ArchitectureConfig) -> ModelPackage:
40+
if not config.use_dsa:
41+
return CausalLMTask().build(module, config)
42+
return self._build_dsa(module, config)
43+
44+
def _build_dsa(self, module, config: ArchitectureConfig) -> ModelPackage:
45+
specs_fn = getattr(module, "dsa_kv_cache_specs", None)
46+
if not callable(specs_fn):
47+
raise TypeError(
48+
f"{type(module).__name__} must implement dsa_kv_cache_specs() "
49+
"to build with GlmMoeDsaTask in DSA mode."
50+
)
51+
cache_specs = specs_fn()
52+
53+
graph, builder = _make_graph("glm_moe_dsa")
54+
op = builder.op
55+
56+
batch = ir.SymbolicDim("batch")
57+
seq_len = ir.SymbolicDim("sequence_len")
58+
past_seq_len = ir.SymbolicDim("past_sequence_len")
59+
60+
input_ids = builder.input("input_ids", dtype=ir.DataType.INT64, shape=[batch, seq_len])
61+
attention_mask = builder.input(
62+
"attention_mask",
63+
dtype=ir.DataType.INT64,
64+
shape=[batch, "past_sequence_len + sequence_len"],
65+
)
66+
position_ids = builder.input(
67+
"position_ids", dtype=ir.DataType.INT64, shape=[batch, seq_len]
68+
)
69+
70+
past_key_values = []
71+
for i, (key_head_dim, value_head_dim) in enumerate(cache_specs):
72+
past_key = builder.input(
73+
f"past_key_values.{i}.key",
74+
dtype=config.dtype,
75+
shape=[batch, 1, past_seq_len, key_head_dim],
76+
)
77+
past_value = builder.input(
78+
f"past_key_values.{i}.value",
79+
dtype=config.dtype,
80+
shape=[batch, 1, past_seq_len, value_head_dim],
81+
)
82+
past_key_values.append((past_key, past_value))
83+
84+
logits, present_key_values = module(
85+
op,
86+
input_ids=input_ids,
87+
attention_mask=attention_mask,
88+
position_ids=position_ids,
89+
past_key_values=past_key_values,
90+
)
91+
builder.add_output(logits, "logits")
92+
93+
# Stamp explicit present shapes/dtypes: ``pkg.nxrt::IndexShare`` has
94+
# no registered symbolic-shape-inference function (unlike the plain
95+
# ONNX ``Attention``/``com.microsoft::GroupQueryAttention`` ops), so
96+
# the present.* outputs would otherwise be left untyped.
97+
total_seq_len = "past_sequence_len + sequence_len"
98+
for i, (present_key, present_value) in enumerate(present_key_values):
99+
key_head_dim, value_head_dim = cache_specs[i]
100+
present_key.shape = ir.Shape([batch, 1, total_seq_len, key_head_dim])
101+
present_key.type = ir.TensorType(config.dtype)
102+
present_value.shape = ir.Shape([batch, 1, total_seq_len, value_head_dim])
103+
present_value.type = ir.TensorType(config.dtype)
104+
builder.add_output(present_key, f"present.{i}.key")
105+
builder.add_output(present_value, f"present.{i}.value")
106+
107+
return ModelPackage({"model": _make_model(graph)}, config=config)

‎tests/_test_configs.py‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -650,6 +650,47 @@ def _base_config(config_cls=None, **overrides) -> ArchitectureConfig:
650650
},
651651
True,
652652
),
653+
# glm_moe_dsa (zai-org/GLM-5.2): DeepSeekV3CausalLMModel subclass adding
654+
# DeepSeek Sparse Attention (DSA) indexers on top of MLA. Field values
655+
# below are shape-shrunk from the real zai-org/GLM-5.2 config.json
656+
# (n_group=1, topk_group=1, routed_scaling_factor=2.5, sigmoid/noaux_tc,
657+
# index_n_heads=32->2, index_head_dim=128->8, index_topk=2048->4). The
658+
# real checkpoint config also sets num_nextn_predict_layers=1 (it ships
659+
# model.layers.<num_hidden_layers>.* MTP weights), but the reference
660+
# transformers.models.glm_moe_dsa modeling code only builds
661+
# range(num_hidden_layers) decoder layers and has no MTP module, so those
662+
# weights are unused/unexpected keys under from_pretrained -- see
663+
# glm_moe_dsa.py for the matching drop-with-capability-message behavior.
664+
(
665+
"glm_moe_dsa",
666+
{
667+
# MLA: kv heads must equal attn heads (see MLA note near top of file).
668+
"num_key_value_heads": TINY_HEADS,
669+
"q_lora_rank": 32,
670+
"kv_lora_rank": 16,
671+
"qk_nope_head_dim": 16,
672+
"qk_rope_head_dim": 8,
673+
"v_head_dim": 16,
674+
"num_local_experts": 4,
675+
"num_experts_per_tok": 2,
676+
"moe_intermediate_size": 32,
677+
"n_group": 1,
678+
"topk_group": 1,
679+
"routed_scaling_factor": 2.5,
680+
"scoring_func": "sigmoid",
681+
"topk_method": "noaux_tc",
682+
"first_k_dense_replace": 1,
683+
"n_shared_experts": 1,
684+
"rope_interleave": True,
685+
"index_n_heads": 2,
686+
"index_head_dim": 8,
687+
"index_topk": 4,
688+
"index_topk_freq": None,
689+
"indexer_types": ["full", "shared"],
690+
"num_nextn_predict_layers": 1,
691+
},
692+
True,
693+
),
653694
(
654695
"deepseek_v4",
655696
{

‎tests/model_coverage_test.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,7 @@ def _all_registered_with_test_id() -> dict[str, str]:
221221
"dbrx": "Large MoE (132B) — no small public checkpoint",
222222
"deepseek_v3": "Very large MoE (671B) — no small public checkpoint",
223223
"deepseek_v4": "Very large MoE (284B) — no small public checkpoint",
224+
"glm_moe_dsa": "Very large MoE (~1.5T, zai-org/GLM-5.2) — no small public checkpoint",
224225
"llama4_text": "Very large MoE (109B) — no small public checkpoint",
225226
"qwen3_5_moe": "Large MoE (22B) — no small public checkpoint",
226227
# --- Models without test_model_id ---

‎tests/synthetic_parity_test.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,17 @@
8484
# Zamba weight-tying references layers.2.shared_transf (the third layer) but
8585
# the tiny config only has 2 layers — HF tie_weights validation crashes.
8686
"zamba": "Zamba weight-tying requires num_layers > 2; tiny 2-layer config causes HF tie_weights error",
87+
# GLM-5.2's default (config.use_dsa=True) DSA/IndexShare path emits
88+
# pkg.nxrt::IndexShare -- a custom onnx-genai-runtime domain with no
89+
# stock-ORT registration, so this generic OnnxModelSession-based harness
90+
# can never execute it (unlike com.microsoft::QMoE, a real ORT contrib
91+
# op). DSA numeric correctness is covered instead by the dedicated
92+
# GlmMoeDsaIndexer-vs-transformers parity test in glm_moe_dsa_test.py and
93+
# by onnx-genai's native-CPU/CUDA e2e regression
94+
# (glm_tiny_qmoe_native_cuda_e2e.rs); the config.use_dsa=False
95+
# (--glm-full-attention) dense-MLA fallback has no custom ops and would
96+
# be exercised by this harness if the tiny config defaulted to it.
97+
"glm_moe_dsa": "DSA/IndexShare emits pkg.nxrt::IndexShare, unsupported by stock ORT",
8798
}
8899

89100
# Per-model atol overrides for L3 synthetic parity.

0 commit comments

Comments
 (0)