Skip to content

Add GLM-5.2 (glm_moe_dsa) model support with DSA/IndexShare + full-attention fallback - #555

Merged
justinchuby merged 1 commit into
mainfrom
feat/glm-5.2-enablement
Aug 23, 2026
Merged

justinchuby merged 1 commit into
mainfrom
feat/glm-5.2-enablement

Conversation

@justinchuby

Copy link
Copy Markdown
Member

Summary

Registers the glm_moe_dsa model_type — zai-org/GLM-5.2, architecture GlmMoeDsaForCausalLM (78 layers, hidden 6144, MLA+DSA, 256 routed + 1 shared expert, top-8, sigmoid/noaux_tc routing, routed_scaling_factor=2.5, 1 MTP layer, default RoPE) — by reusing existing DeepSeek MLA/MoE/QMoE-fusion machinery rather than merging draft PR #404 or sibling branch feat/glm-dsa-indexshare wholesale.

Both stale branches were diffed and classified hunk-by-hunk against current main. Several correctness bugs present in the sibling branch were identified and not carried over — fixed from scratch instead:

  1. Indexer RoPE split only rotating qk_rope_head_dim of the wider index_head_dim (sibling rotated the whole head).
  2. A 4D-query × 3D-key MatMul broadcast that silently mispairs axes whenever batch_size != seq_len (sibling omitted an unsqueeze).
  3. (Found during independent review of this PR, fixed here) IndexShare's query/key/value inputs must be cast to f32 per the frozen op schema (docs/architecture/INDEXSHARE_DESIGN.md in onnx-genai) regardless of the model's compute dtype — the real zai-org/GLM-5.2 checkpoint is bfloat16.

What's included

  • src/mobius/models/glm_moe_dsa.py (new): GlmMoeDsaIndexer (DSA top-k scoring/selection), GlmMoeDsaAttention (subclasses DeepSeekMLA, exports the frozen pkg.nxrt::IndexShare op per the "full"/"shared" indexer schedule), GlmMoeDsaDecoderLayer, GlmMoeDsaTextModel, GlmMoeDsaCausalLMModel (subclasses DeepSeekV3CausalLMModel). Existing DeepSeek MLA math, MoE gate/FFN, and QMoE fusion (Fuse DeepSeek-V4 routed experts into a single QMoE op per layer #550) are reused unchanged.
  • config.use_dsa=False (new --glm-full-attention CLI feature) switches to plain dense MLA attention, executable on stock ONNX Runtime today, as an explicit fallback until the native IndexShare runtime kernel lands in onnx-genai. Wired through both the --config (local dir) and --model (HF id, including the diffusers-dispatch fallback branch) build paths, validated to only apply to glm_moe_dsa.
  • src/mobius/_configs/_base.py: 6 new ArchitectureConfig fields for DSA (index_topk, index_head_dim, index_n_heads, index_topk_freq, index_skip_topk_offset, use_dsa) and HF-config extraction, including a model_type == "glm_moe_dsa"-conditional default so scoring_func/topk_method correctly resolve to GLM's sigmoid/noaux_tc routing. (The real GlmMoeDsaConfig does not declare these as dataclass fields at all when omitted from config.json — they're silently absent, not defaulted — so without this fix GLM-5.2 would silently inherit DeepSeek's softmax/greedy routing defaults.)
  • src/mobius/_registry.py, src/mobius/models/__init__.py: registration wiring.
  • src/mobius/models/glm_moe_dsa_test.py (new, 21 tests): registry mapping; indexer schedule formula (cross-checked against the real installed transformers.models.glm_moe_dsa config's own .indexer_types derivation, not just a hand-written expectation); scoring_func/topk_method regression test; graph-build structural tests for both the DSA and full-attention-fallback paths (IndexShare/Attention op counts, indexer-weight presence, QMoE-fusion node count, and a regression test asserting IndexShare's query/key/value inputs are float32 under a non-float compute dtype — verified to fail without the fix above and pass with it); preprocess_weights tests (MTP-layer and indexer-weight dropping); two numeric-parity tests against the real HF reference implementation (raw index-score parity to ~1e-6, and a tie-tolerant "true top-k + strictly increasing indices" property test — selected-index-set equality is deliberately not asserted because torch.topk and ONNX TopK have different, individually valid tie-breaking conventions at degenerate/tied score boundaries; this was verified empirically, not assumed).
  • src/mobius/integrations/transformers/_builder_test.py: tests for the new glm_full_attention override/validation on both the main and diffusers-dispatch code paths.

Explicitly out of scope (no open tracking issue found — searched onnxruntime/mobius issues for GLM/MTP/DSA/IndexShare/GGUF, none exist)

  • MTP (multi-token-prediction) layer. The real transformers.models.glm_moe_dsa reference implementation itself has no MTP module — preprocess_weights drops MTP-layer weights with a warning, matching upstream's own _keys_to_ignore_on_load_unexpected pattern. Base-model logits never accidentally include an unsupported MTP path. Exporting MTP is a follow-up.
  • GGUF import support.
  • CUDA residency policy / q* / scheduler work.

Local evidence

  • ruff check / ruff format --check: clean (pinned lintrunner version 0.16.2).
  • pytest src/mobius/models/ -q (full directory, excluding arch_validation/golden/generation/benchmark markers): 523 passed, 4 skipped.
  • pytest src/mobius/models/glm_moe_dsa_test.py src/mobius/models/deepseek_test.py src/mobius/models/deepseek_v4_test.py src/mobius/_registry_test.py src/mobius/integrations/transformers/ src/mobius/_configs/ -q: 146 passed.
  • Independent review (via a separate agent pass over the staged diff) found and this PR fixes: the IndexShare f32-input-cast bug above (blocker) and a missing glm_full_attention validation gap on the diffusers-dispatch branch (should-fix, also fixed + tested here).

Remaining runtime/MTP/full-model blockers & next onnx-genai gate

  • Native IndexShare runtime kernel: this PR only emits the frozen pkg.nxrt::IndexShare op into the graph; actually generating tokens end-to-end for the DSA path requires the corresponding onnx-genai/ORT custom-op kernel to exist and execute it. That is the concrete next onnx-genai-side gate — without it, only the --glm-full-attention dense fallback (stock-ORT-executable) can currently run tokens today.
  • MTP layer: tracked as a documented follow-up above, no export path yet.
  • GGUF import: not attempted in this slice.

Co-authored-by: Copilot [email protected]

…tention fallback

Registers the `glm_moe_dsa` model_type (zai-org/GLM-5.2,
`GlmMoeDsaForCausalLM`) by reusing existing DeepSeek MLA/MoE/QMoE-fusion
machinery rather than merging draft PR #404 or sibling branch
`feat/glm-dsa-indexshare` wholesale. Both were audited hunk-by-hunk; several
correctness bugs found in the sibling branch (RoPE-split, 4D/3D MatMul
broadcast, and IndexShare non-f32 inputs) were fixed here instead of carried
over.

- `src/mobius/models/glm_moe_dsa.py` (new): `GlmMoeDsaIndexer` (DSA top-k
  scoring/selection), `GlmMoeDsaAttention` (subclasses `DeepSeekMLA`,
  exports the frozen `pkg.nxrt::IndexShare` op for the "full"/"shared"
  indexer schedule), `GlmMoeDsaDecoderLayer`, `GlmMoeDsaTextModel`,
  `GlmMoeDsaCausalLMModel` (subclasses `DeepSeekV3CausalLMModel`).
  `config.use_dsa=False` (the new `--glm-full-attention` CLI feature)
  switches to plain dense MLA attention executable on stock ONNX Runtime,
  as a fallback until the native IndexShare runtime kernel lands.
- `src/mobius/_configs/_base.py`: 6 new `ArchitectureConfig` fields for DSA
  (index_topk, index_head_dim, index_n_heads, index_topk_freq,
  index_skip_topk_offset, use_dsa) and HF-config extraction, including a
  `model_type == "glm_moe_dsa"`-conditional default so `scoring_func`/
  `topk_method` correctly resolve to GLM's sigmoid/noaux_tc routing (the
  real GlmMoeDsaConfig does not declare these as dataclass fields, so they
  are silently absent instead of inheriting DeepSeek's softmax/greedy
  defaults) when a config omits them.
- `src/mobius/_registry.py`, `src/mobius/models/__init__.py`: registration
  wiring for `glm_moe_dsa`.
- `src/mobius/__main__.py`, `src/mobius/integrations/transformers/_builder.py`:
  new `--glm-full-attention` cargo-style build feature, threaded through
  both the `--config` (local directory) and `--model` (HF id, including the
  diffusers-dispatch fallback branch) build paths as `glm_full_attention`,
  validated to only apply to `model_type == "glm_moe_dsa"`.
- `src/mobius/models/glm_moe_dsa_test.py` (new, 21 tests): registry mapping,
  indexer schedule formula (cross-checked against the real installed
  `transformers.models.glm_moe_dsa` config's own derivation), HF config
  extraction (scoring_func/topk_method regression), graph-build structural
  tests for both the DSA and full-attention-fallback paths (IndexShare/
  Attention op counts, indexer weight presence, QMoE fusion, and a
  regression test asserting IndexShare's query/key/value inputs are cast to
  float32 under a non-float compute dtype, matching the frozen op's f32-only
  schema), `preprocess_weights` tests (MTP-layer and indexer-weight
  dropping), and two numeric-parity tests against the real HF reference
  implementation (raw index-score parity, and a tie-tolerant top-k
  correctness property test -- selected-index-set equality is not asserted
  because `torch.topk`/ONNX `TopK` have different, individually valid
  tie-breaking conventions at degenerate/tied score boundaries).
- `src/mobius/integrations/transformers/_builder_test.py`: tests for the new
  `glm_full_attention` override/validation, including the diffusers-dispatch
  branch.

Not in scope for this PR (documented here as follow-ups, no open tracking
issue found for either): MTP (multi-token-prediction) layer export -- the
real `transformers.models.glm_moe_dsa` reference implementation itself has
no MTP module, so base-model logits correctly never include an unsupported
MTP path; `preprocess_weights` drops MTP-layer weights with a warning
instead. GGUF import support. CUDA residency/scheduler work.

Local evidence: 523/523 `src/mobius/models/` tests pass, 115/115 targeted
tests pass (glm_moe_dsa_test.py, deepseek_test.py, deepseek_v4_test.py,
_registry_test.py, integrations/transformers/*), 28/28 `_configs/` tests
pass. `ruff check`/`ruff format --check` clean (pinned lintrunner version
0.16.2).

Co-authored-by: Copilot <[email protected]>
@justinchuby
justinchuby requested review from a team and a lite review from Copilot August 23, 2026 02:11
@justinchuby
justinchuby merged commit b4dcf43 into main Aug 23, 2026
16 of 23 checks passed
@justinchuby
justinchuby deleted the feat/glm-5.2-enablement branch August 23, 2026 02:13
@github-actions

Copy link
Copy Markdown

🏗️ Architecture Diff

Comparing b65bbd9 → a437f03

Model Sub-model Changes Status

No architecture changes detected. ✅


Legend: ⚪ No change · 🔵 Minor (attrs/inits) · 🟡 Moderate (nodes added/removed) · 🔴 Major (interface changed)

@github-actions

Copy link
Copy Markdown

Performance Comparison

Comparing b65bbd9 → a437f03

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

Adds GLM-5.2 (glm_moe_dsa) support with DSA/IndexShare attention, DeepSeek MLA/MoE reuse, and a full-attention fallback.

Changes:

  • Implements the GLM DSA model, indexer, attention, and MoE integration.
  • Adds configuration, registry, exports, and --glm-full-attention support.
  • Adds graph, parity, preprocessing, and builder tests.

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 7 comments.

Show a summary per file
File Review summary
src/mobius/models/glm_moe_dsa.py Four critical findings: incompatible cache/task contract (4 votes); missing IndexShare attention bias (3 votes); missing default RoPE handling (1 vote); incorrect CUDA QMoE behavior (3 votes).
src/mobius/models/glm_moe_dsa_test.py No final comments.
src/mobius/models/__init__.py No final comments.
src/mobius/integrations/transformers/_builder.py No final comments.
src/mobius/integrations/transformers/_builder_test.py No final comments.
src/mobius/_registry.py Moderate finding: shared graph-build configuration lacks a shape-valid tiny GLM override (3 votes).
src/mobius/_configs/_base.py Moderate finding: production config extraction selects the wrong indexer RoPE mode (2 votes).
src/mobius/__main__.py Moderate finding: the Diffusers auto-detection path ignores glm-full-attention (4 votes).
Suppressed comments (5)

src/mobius/models/glm_moe_dsa.py:277

  • DeepSeekMLA.__init__ creates both MLA latent RMSNorms with config.rms_norm_eps. The HuggingFace GLM implementation uses the DeepSeek norm's 1e-6 default for q_a_layernorm and kv_a_layernorm, while GLM's rms_norm_eps (1e-5) is used by the outer decoder norms. Passing the GLM config unchanged therefore changes latent normalization in both DSA and dense-fallback paths and breaks numerical parity. Use a 1e-6 MLA-specific config here without changing the decoder norms.
        super().__init__(config, linear_class=linear_class)

src/mobius/models/glm_moe_dsa_test.py:360

  • model.named_parameters() already includes the outer model. wrapper (model.layers...), so prefixing every non-lm_head name creates malformed model.model... fixture keys. The preprocessing tests then do not exercise realistic HF names or verify that ordinary model weights align; only the separately injected MTP/indexer keys have the expected prefix. Use the generated names directly (or conditionally prefix only names that lack model.) and assert a regular initializer survives.
        renamed = {
            f"model.{name}" if not name.startswith("lm_head") else name: v
            for name, v in state.items()
        }

src/mobius/models/glm_moe_dsa_test.py:377

  • The injected key is model.layers.4..., and preprocess_weights() preserves that prefix, so this predicate never matches it. If MTP filtering regresses and returns the injected key, the assertion still passes; check model.layers.4. (or compare the processed keys against the expected initializer set) so this test actually verifies the drop.
        assert not any(k.startswith("layers.4.") for k in out)

src/mobius/models/glm_moe_dsa_test.py:708

  • This property test does not assert that selected positions are causally valid. When s < index_topk - 1, all positions in [:s+1] can be selected along with masked future positions, making non_selected empty and causing the test to continue; thus it passes despite the early-prefill failure in the indexer. Assert selected <= s before indexing the selected scores.
                valid = expected_scores[b, s, : s + 1]

src/mobius/models/glm_moe_dsa_test.py:300

  • This fallback test only counts dense attention operators and checks initializer names; it never executes the advertised stock-ORT path. A graph can satisfy both assertions while its cache I/O or full-model numerics are unusable, and the new custom decoder/config wiring is not covered by the indexer-only parity tests. Add a tiny-weight ORT prefill plus cached-decode test for use_dsa=False against the corresponding reference computation.
    def test_full_attention_fallback_emits_dense_attention_and_no_index_share(self):
        config, onnx_model = self._build(use_dsa=False)
        graph = onnx_model.graph
        assert count_op_type(graph, "IndexShare") == 0
        dense_attn_ops = (
            count_op_type(graph, "Attention")
            + count_op_type(graph, "GroupQueryAttention")
            + count_op_type(graph, "MultiHeadAttention")
        )
        assert dense_attn_ops > 0

💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/mobius/__main__.py
fp8_kv_cache=fp8_kv_cache,
kv_cache_scales=kv_cache_scales,
prune_prefill_prefix=prune_prefill_prefix,
glm_full_attention=args.glm_full_attention,
),
index_topk_freq=getattr(config, "index_topk_freq", None),
index_skip_topk_offset=getattr(config, "index_skip_topk_offset", None),
indexer_rope_interleave=getattr(config, "indexer_rope_interleave", False),
Comment thread src/mobius/_registry.py
"deepseek_v4": ModelRegistration(DeepSeekV4CausalLMModel, task="deepseek-v4"),
"deepseek_vl_v2": ModelRegistration(DeepSeekOCR2CausalLMModel),
# --- GLM-5.2 (MLA + DeepSeek Sparse Attention (DSA) + MoE) ---
"glm_moe_dsa": ModelRegistration(GlmMoeDsaCausalLMModel),
Comment on lines +288 to +292
key_tokens = op.Squeeze(packed_key, [1])
main_key = op.Slice(key_tokens, [0], [self.main_key_dim], [2])
main_key = op.Transpose(
op.Reshape(main_key, [0, 0, self.num_heads, self.qk_head_dim]),
perm=[0, 2, 1, 3],
Comment on lines +397 to +401
attn_output = op.IndexShare(
q_f32,
key_f32,
value_f32,
None,
Comment on lines +596 to +601
position_embeddings = self.rotary_emb(op, position_ids)
attention_bias = create_attention_bias(
op,
input_ids=hidden_states if input_ids is None else input_ids,
attention_mask=attention_mask,
dtype=self.config.dtype,
Comment on lines +510 to +512
self.mlp = _DeepSeekMoEFFN(
config, DeepSeekMoEGate(config), linear_class=linear_class
)
# ``config_overrides={"use_dsa": False}`` to fall back to plain dense MLA
# (reusing ``DeepSeekV3TextModel`` unchanged) on runtimes that cannot yet
# execute ``pkg.nxrt::IndexShare``.
use_dsa: bool = True

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you move to model specific config files?

If the repository is not a supported Transformers checkpoint, dispatch to
the Diffusers integration so :func:`mobius.build` remains ecosystem-agnostic.

``glm_full_attention`` is the ``--glm-full-attention`` CLI feature: it

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Generalize this so that it is not model specific

justinchuby added a commit that referenced this pull request Aug 23, 2026
…erage

Three small changes, the last two inherited from the main merge rather than
from this branch's work.

1. SequenceSelectiveScan's zero carried state dropped its `value` attribute.
   ONNX already defines ConstantOfShape's default as a float32 zero, so the
   attribute only restated the default.

2. tests/model_coverage_test.py failed for glm_moe_dsa, which landed in #555
   with a test_model_id but no YAML case. Added one, with a skip reason that
   states why L4/L5 cannot run: GLM-5.2 is 753B parameters across 282
   safetensors shards.

3. glm_moe_dsa had no entry in _test_configs.py, so it fell back to an
   auto-generated config with qk_nope_head_dim/qk_rope_head_dim unset, and
   the shared MLA component raised `TypeError: unsupported operand type(s)
   for +: 'NoneType' and 'NoneType'`. Added a tiny config mirroring the
   model's own fixture in src/mobius/models/glm_moe_dsa_test.py.

That takes glm_moe_dsa from 5 failures to 3. The remaining ones are a real
defect in the model, not the config: with a buildable graph it now emits an
invalid Squeeze in the MLA attention, and ORT refuses to load the model at all:

    Node (model/layers.0/self_attn/Squeeze_node_46) Op (Squeeze)
    [ShapeInferenceError] Dimension of input 1 must be 1 instead of 4

which also explains its onnx_checker failure. Fixing that needs GLM-5.2 DSA
knowledge and belongs with #555; filed separately rather than guessed at here.

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
…a 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]>
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