Skip to content

Commit a437f03

Browse files
justinchubyCopilot
andcommitted
Add GLM-5.2 (glm_moe_dsa) model support with DSA/IndexShare + full-attention 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]>
1 parent b65bbd9 commit a437f03

8 files changed

Lines changed: 1597 additions & 2 deletions

File tree

‎src/mobius/__main__.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
"fp8-kv-cache": "fp8_kv_cache",
4242
"prune-prefill-prefix": "prune_prefill_prefix",
4343
"text-only": "text_only",
44+
"glm-full-attention": "glm_full_attention",
4445
}
4546

4647

@@ -342,6 +343,13 @@ def _resolve_static_cache_task(model_type: str) -> ModelTask:
342343
config = _config_from_hf(hf_config, parent_config=parent_config)
343344
if dtype_override is not None:
344345
config = dataclasses.replace(config, dtype=dtype_override)
346+
if args.glm_full_attention:
347+
if model_type != "glm_moe_dsa":
348+
raise SystemExit(
349+
"Error: --features glm-full-attention is only supported for "
350+
f"model_type 'glm_moe_dsa' (got '{model_type}')."
351+
)
352+
config = dataclasses.replace(config, use_dsa=False)
345353
if static_cache_params is not None:
346354
task = _resolve_static_cache_task(model_type)
347355
elif task is None:
@@ -389,6 +397,7 @@ def _resolve_static_cache_task(model_type: str) -> ModelTask:
389397
fp8_kv_cache=fp8_kv_cache,
390398
kv_cache_scales=kv_cache_scales,
391399
prune_prefill_prefix=prune_prefill_prefix,
400+
glm_full_attention=args.glm_full_attention,
392401
)
393402

394403
_save_package(pkg, output_dir, args, optimize, component_filter)

‎src/mobius/_configs/_base.py‎

Lines changed: 53 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -495,6 +495,30 @@ class ArchitectureConfig(BaseModelConfig):
495495
swiglu_limit: float = 0.0
496496
num_nextn_predict_layers: int = 0
497497

498+
# GLM-5.2 (``glm_moe_dsa``) DeepSeek Sparse Attention (DSA).
499+
#
500+
# ``use_dsa`` is not an upstream HF field -- it is a Mobius export-time
501+
# toggle (default True) flipped to False by ``--glm-full-attention`` /
502+
# ``config_overrides={"use_dsa": False}`` to fall back to plain dense MLA
503+
# (reusing ``DeepSeekV3TextModel`` unchanged) on runtimes that cannot yet
504+
# execute ``pkg.nxrt::IndexShare``.
505+
use_dsa: bool = True
506+
# Per-layer indexer schedule ("full" runs the indexer; "shared" reuses the
507+
# top-k selection from the closest preceding "full" layer). When the
508+
# checkpoint config omits this list, it is derived from
509+
# ``index_topk_freq`` / ``index_skip_topk_offset`` -- see
510+
# ``mobius.models.glm_moe_dsa._indexer_types``, which mirrors HF
511+
# ``GlmMoeDsaConfig.__post_init__`` exactly.
512+
indexer_types: list[str] | None = None
513+
index_topk_freq: int | None = None
514+
index_skip_topk_offset: int | None = None
515+
indexer_rope_interleave: bool = False
516+
# Whether the (currently unexported, see ``glm_moe_dsa.py``) MTP layer is
517+
# meant to reuse the target's shared top-k indices rather than running its
518+
# own indexer pass. Recorded for round-tripping/documentation; not yet
519+
# acted on since MTP export itself is out of scope this cycle.
520+
index_share_for_mtp_iteration: bool = False
521+
498522
# Vision shared fields (accessed as top-level config.X by tasks)
499523
mm_tokens_per_image: int | None = None
500524
image_token_id: int | None = None
@@ -897,8 +921,20 @@ def from_transformers(cls, config, parent_config=None) -> ArchitectureConfig:
897921
n_group=getattr(config, "n_group", 1),
898922
topk_group=getattr(config, "topk_group", 1),
899923
routed_scaling_factor=getattr(config, "routed_scaling_factor", 1.0),
900-
scoring_func=getattr(config, "scoring_func", "softmax"),
901-
topk_method=getattr(config, "topk_method", "greedy"),
924+
# ``scoring_func``/``topk_method`` are not real HF dataclass
925+
# fields on ``GlmMoeDsaConfig`` -- transformers hardcodes
926+
# sigmoid + e_score_correction_bias + (degenerate, n_group=1)
927+
# top-k routing for GLM-5.2 rather than exposing it as a config
928+
# knob. A checkpoint that omits these keys entirely (unlike the
929+
# real zai-org/GLM-5.2 config.json, which sets them explicitly)
930+
# would otherwise silently default to the wrong (softmax/greedy)
931+
# DeepSeek-V2 routing.
932+
scoring_func=getattr(
933+
config, "scoring_func", "sigmoid" if model_type == "glm_moe_dsa" else "softmax"
934+
),
935+
topk_method=getattr(
936+
config, "topk_method", "noaux_tc" if model_type == "glm_moe_dsa" else "greedy"
937+
),
902938
first_k_dense_replace=getattr(config, "first_k_dense_replace", 0),
903939
n_shared_experts=getattr(config, "n_shared_experts", None),
904940
# Multi-head Latent Attention (MLA)
@@ -927,6 +963,21 @@ def from_transformers(cls, config, parent_config=None) -> ArchitectureConfig:
927963
),
928964
swiglu_limit=getattr(config, "swiglu_limit", 0.0),
929965
num_nextn_predict_layers=getattr(config, "num_nextn_predict_layers", 0),
966+
# GLM-5.2 DSA. ``use_dsa`` has no HF equivalent -- every checkpoint
967+
# defaults to the sparse path; ``--glm-full-attention`` overrides
968+
# it afterwards via ``dataclasses.replace``/``config_overrides``.
969+
use_dsa=getattr(config, "use_dsa", True),
970+
indexer_types=(
971+
list(config.indexer_types)
972+
if getattr(config, "indexer_types", None) is not None
973+
else None
974+
),
975+
index_topk_freq=getattr(config, "index_topk_freq", None),
976+
index_skip_topk_offset=getattr(config, "index_skip_topk_offset", None),
977+
indexer_rope_interleave=getattr(config, "indexer_rope_interleave", False),
978+
index_share_for_mtp_iteration=getattr(
979+
config, "index_share_for_mtp_iteration", False
980+
),
930981
# Encoder-specific
931982
type_vocab_size=getattr(config, "type_vocab_size", 0),
932983
# Encoder-decoder

‎src/mobius/_registry.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@
6868
Glm4CausalLMModel,
6969
Glm4MoECausalLMModel,
7070
GlmCausalLMModel,
71+
GlmMoeDsaCausalLMModel,
7172
GPTOSSCausalLMModel,
7273
GraniteCausalLMModel,
7374
GraniteMoECausalLMModel,
@@ -582,6 +583,8 @@ def _detect_fallback_registration(hf_config) -> ModelRegistration | None:
582583
"deepseek_v3": ModelRegistration(DeepSeekV3CausalLMModel),
583584
"deepseek_v4": ModelRegistration(DeepSeekV4CausalLMModel, task="deepseek-v4"),
584585
"deepseek_vl_v2": ModelRegistration(DeepSeekOCR2CausalLMModel),
586+
# --- GLM-5.2 (MLA + DeepSeek Sparse Attention (DSA) + MoE) ---
587+
"glm_moe_dsa": ModelRegistration(GlmMoeDsaCausalLMModel),
585588
# --- SSM (Mamba / Mamba2) ---
586589
"falcon_mamba": ModelRegistration(MambaCausalLMModel),
587590
"mamba": ModelRegistration(MambaCausalLMModel),
@@ -1027,6 +1030,8 @@ def _create_default_registry() -> ModelRegistry:
10271030
"deepseek_v2_moe": "deepseek-ai/DeepSeek-V2-Lite",
10281031
"deepseek_v3": "deepseek-ai/DeepSeek-V3",
10291032
"deepseek_v4": "deepseek-ai/DeepSeek-V4-Flash",
1033+
# --- GLM-5.2 (MLA + DSA + MoE) ---
1034+
"glm_moe_dsa": "zai-org/GLM-5.2",
10301035

10311036
# --- SSM (Mamba) ---
10321037
"mamba": "state-spaces/mamba-130m-hf",
@@ -1288,6 +1293,7 @@ def _create_default_registry() -> ModelRegistry:
12881293
"deepseek_v3": "deepseek",
12891294
"deepseek_v4": "deepseek",
12901295
"deepseek_vl_v2": "deepseek",
1296+
"glm_moe_dsa": "glm",
12911297
"olmo": "olmo",
12921298
"olmo2": "olmo",
12931299
"olmo3": "olmo",
@@ -1361,6 +1367,7 @@ def _create_default_registry() -> ModelRegistry:
13611367
"deepseek_v2_moe": "mla+moe",
13621368
"deepseek_v3": "mla+moe",
13631369
"deepseek_v4": "dense-csa-fallback+mtp+moe+hc",
1370+
"glm_moe_dsa": "mla+dsa-indexshare+full-attention-fallback+moe",
13641371
"phi3small": "blocksparse",
13651372
"falcon_h1": "hybrid-ssm",
13661373
"mamba": "ssm",

‎src/mobius/integrations/transformers/_builder.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,11 +158,18 @@ def build_transformers_model(
158158
fp8_kv_cache: bool = False,
159159
kv_cache_scales: dict[int, tuple[float, float]] | None = None,
160160
prune_prefill_prefix: bool = False,
161+
glm_full_attention: bool = False,
161162
) -> ModelPackage:
162163
"""Build a model package from a Transformers checkpoint.
163164
164165
If the repository is not a supported Transformers checkpoint, dispatch to
165166
the Diffusers integration so :func:`mobius.build` remains ecosystem-agnostic.
167+
168+
``glm_full_attention`` is the ``--glm-full-attention`` CLI feature: it
169+
forces ``config.use_dsa=False`` so GLM-5.2 (``glm_moe_dsa``) exports plain
170+
dense causal attention (executable on stock ORT) instead of the DSA
171+
``IndexShare`` path, which requires the native custom-op runtime kernel.
172+
It is only valid for ``model_type == "glm_moe_dsa"``.
166173
"""
167174
from mobius.integrations.diffusers import build_diffusers_pipeline
168175
from mobius.integrations.transformers._config_resolver import (
@@ -182,6 +189,12 @@ def build_transformers_model(
182189
"resolve to a registered text-capable model_type (it looks like "
183190
"a diffusers pipeline or an unsupported config)."
184191
)
192+
if glm_full_attention:
193+
raise ValueError(
194+
f"glm_full_attention=True is not supported for '{model_id}': it "
195+
"does not resolve to a registered 'glm_moe_dsa' model_type (it "
196+
"looks like a diffusers pipeline or an unsupported config)."
197+
)
185198
return build_diffusers_pipeline(
186199
model_id,
187200
revision=revision,
@@ -225,6 +238,14 @@ def build_transformers_model(
225238
config,
226239
output_layer_indices=list(output_layer_indices),
227240
)
241+
if glm_full_attention:
242+
if model_type != "glm_moe_dsa":
243+
raise ValueError(
244+
f"glm_full_attention=True is not supported for model_type "
245+
f"'{model_type}'. It is only available for GLM-5.2 "
246+
"('glm_moe_dsa') checkpoints."
247+
)
248+
config = dataclasses.replace(config, use_dsa=False)
228249
if task is None:
229250
task = _default_task_for_model(model_type)
230251

‎src/mobius/integrations/transformers/_builder_test.py‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from unittest import mock
99

1010
import onnx_ir as ir
11+
import pytest
1112
from onnxscript import nn
1213

1314
from mobius._model_package import ModelPackage
@@ -57,6 +58,72 @@ def test_transformers_build_uses_canonical_weight_loader(monkeypatch) -> None:
5758
download.assert_called_once_with("fake/model", revision=None)
5859

5960

61+
def test_glm_full_attention_overrides_use_dsa_for_glm_moe_dsa(monkeypatch) -> None:
62+
"""``--glm-full-attention`` forces ``config.use_dsa=False`` for GLM-5.2."""
63+
hf_config = type("HFConfig", (), {"model_type": "glm_moe_dsa"})()
64+
config = make_config(model_type="glm_moe_dsa", use_dsa=True)
65+
model = ir.Model(ir.Graph([], [], nodes=[], name="model"), ir_version=11)
66+
package = ModelPackage({"model": model}, config=config)
67+
captured_configs: list = []
68+
69+
monkeypatch.setattr(
70+
transformers_builder,
71+
"_load_transformers_config",
72+
lambda *args, **kwargs: (hf_config, False),
73+
)
74+
monkeypatch.setattr(
75+
transformers_builder,
76+
"_select_primary_config",
77+
lambda value: (value, value, "glm_moe_dsa"),
78+
)
79+
monkeypatch.setattr(
80+
transformers_builder,
81+
"_resolve_module_class",
82+
lambda *args, **kwargs: (_DummyModule, "text-generation", "glm_moe_dsa"),
83+
)
84+
monkeypatch.setattr(_config_resolver, "_config_from_hf", lambda *args, **kwargs: config)
85+
86+
def fake_build_from_module(_module, built_config, *args, **kwargs):
87+
captured_configs.append(built_config)
88+
return package
89+
90+
monkeypatch.setattr(transformers_builder, "build_from_module", fake_build_from_module)
91+
monkeypatch.setattr(transformers_builder, "_download_weights", mock.Mock(return_value={}))
92+
93+
result = transformers_builder.build_transformers_model(
94+
"zai-org/GLM-5.2", glm_full_attention=True
95+
)
96+
97+
assert result is package
98+
assert captured_configs[0].use_dsa is False
99+
100+
101+
def test_glm_full_attention_rejects_non_glm_model_type(monkeypatch) -> None:
102+
"""``--glm-full-attention`` is only meaningful for ``glm_moe_dsa``."""
103+
hf_config = type("HFConfig", (), {"model_type": "qwen2"})()
104+
config = make_config(model_type="qwen2")
105+
106+
monkeypatch.setattr(
107+
transformers_builder,
108+
"_load_transformers_config",
109+
lambda *args, **kwargs: (hf_config, False),
110+
)
111+
monkeypatch.setattr(
112+
transformers_builder,
113+
"_select_primary_config",
114+
lambda value: (value, value, "qwen2"),
115+
)
116+
monkeypatch.setattr(
117+
transformers_builder,
118+
"_resolve_module_class",
119+
lambda *args, **kwargs: (_DummyModule, "text-generation", "qwen2"),
120+
)
121+
monkeypatch.setattr(_config_resolver, "_config_from_hf", lambda *args, **kwargs: config)
122+
123+
with pytest.raises(ValueError, match="glm_full_attention=True is not supported"):
124+
transformers_builder.build_transformers_model("fake/model", glm_full_attention=True)
125+
126+
60127
def test_build_threads_revision_to_diffusers_fallback(monkeypatch) -> None:
61128
import transformers
62129

@@ -99,3 +166,35 @@ def fake_build_diffusers(*args, **kwargs):
99166
},
100167
)
101168
]
169+
170+
171+
def test_glm_full_attention_rejects_diffusers_dispatch(monkeypatch) -> None:
172+
"""``--glm-full-attention`` must raise on the diffusers-dispatch branch.
173+
174+
Mirrors the existing ``text_only`` guard on the same early-return path:
175+
a repo that doesn't resolve to a registered ``model_type`` (and so falls
176+
through to the Diffusers integration) can never be GLM-5.2, so silently
177+
ignoring the flag there would swallow a real user error.
178+
"""
179+
import transformers
180+
181+
monkeypatch.setattr(
182+
transformers.AutoConfig,
183+
"from_pretrained",
184+
lambda *args, **kwargs: (_ for _ in ()).throw(OSError("not transformers")),
185+
)
186+
monkeypatch.setattr(
187+
_config_resolver, "_try_load_config_json", lambda *args, **kwargs: None
188+
)
189+
monkeypatch.setattr(
190+
diffusers_builder,
191+
"build_diffusers_pipeline",
192+
lambda *args, **kwargs: (_ for _ in ()).throw(
193+
AssertionError("should not reach build_diffusers_pipeline")
194+
),
195+
)
196+
197+
with pytest.raises(ValueError, match="glm_full_attention=True is not supported"):
198+
transformers_builder.build_transformers_model(
199+
"fake/diffusers", glm_full_attention=True
200+
)

‎src/mobius/models/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@
6565
"GlmAsrForConditionalGeneration",
6666
"Glm4MoECausalLMModel",
6767
"GlmCausalLMModel",
68+
"GlmMoeDsaCausalLMModel",
6869
"GraniteCausalLMModel",
6970
"GraniteMoECausalLMModel",
7071
"GraniteMoeHybridCausalLMModel",
@@ -234,6 +235,7 @@
234235
from mobius.models.gemma4_assistant import Gemma4AssistantCausalLMModel
235236
from mobius.models.glm import Glm4CausalLMModel, GlmCausalLMModel
236237
from mobius.models.glm_asr import GlmAsrForConditionalGeneration
238+
from mobius.models.glm_moe_dsa import GlmMoeDsaCausalLMModel
237239
from mobius.models.gpt2 import GPT2CausalLMModel
238240
from mobius.models.gpt_neox import GPTNeoXCausalLMModel, GPTNeoXJapaneseCausalLMModel
239241
from mobius.models.gptj_codegen import CodeGenCausalLMModel, GPTJCausalLMModel

0 commit comments

Comments
 (0)