Skip to content

Commit e0b6893

Browse files
Copilotjustinchuby
andauthored
Merge latest main into GLM cache fix
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]>
2 parents 3e50163 + d33c33b commit e0b6893

10 files changed

Lines changed: 185 additions & 72 deletions

‎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: 32 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,10 @@ 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.
397401
op.builder.graph.opset_imports["pkg.nxrt"] = 1
398402
attn_output = op.IndexShare(
399403
q_f32,
@@ -408,9 +412,6 @@ def _index_share_attention(
408412
_domain="pkg.nxrt",
409413
_outputs=1,
410414
)
411-
# IndexShare has no ONNX shape-inference schema; its output matches Q in BNSH layout.
412-
attn_output.type = q_f32.type
413-
attn_output.shape = q_f32.shape
414415
if needs_cast:
415416
attn_output = op.Cast(attn_output, to=self.dtype)
416417
if value_pad > 0:
@@ -655,26 +656,6 @@ def __init__(self, config: ArchitectureConfig):
655656
)
656657
self.lm_head = Linear(config.hidden_size, config.vocab_size, bias=False)
657658

658-
def dynamic_kv_cache_specs(self) -> list[tuple[int, int, int]] | None:
659-
"""Return the packed per-layer DSA cache layouts."""
660-
if not self.config.use_dsa:
661-
return None
662-
# DSA packs each token's per-head main key/value columns into one cache
663-
# head, with the indexer key appended to full-layer keys: (B, 1, T, D).
664-
main_key_dim = self.config.num_attention_heads * (
665-
(self.config.qk_nope_head_dim or 0) + (self.config.qk_rope_head_dim or 0)
666-
)
667-
main_value_dim = self.config.num_attention_heads * (self.config.v_head_dim or 0)
668-
index_head_dim = self.config.index_head_dim or 0
669-
return [
670-
(
671-
1,
672-
main_key_dim + (index_head_dim if indexer_type == "full" else 0),
673-
main_value_dim,
674-
)
675-
for indexer_type in _indexer_types(self.config)
676-
]
677-
678659
def preprocess_weights(
679660
self, state_dict: dict[str, torch.Tensor]
680661
) -> dict[str, torch.Tensor]:
@@ -708,3 +689,31 @@ def preprocess_weights(
708689
filtered = {k: v for k, v in filtered.items() if k not in indexer_keys}
709690

710691
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/models/glm_moe_dsa_test.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ class TestGlmMoeDsaGraphBuild:
243243
def _build(self, **overrides):
244244
config = _glm_config(**overrides)
245245
model = GlmMoeDsaCausalLMModel(config)
246-
package = build_from_module(model, config, task="text-generation")
246+
package = build_from_module(model, config, task="glm-moe-dsa")
247247
return config, package["model"]
248248

249249
def test_dsa_path_emits_one_index_share_per_hidden_layer_and_no_attention(self):

‎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/_cache_utils.py‎

Lines changed: 6 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,6 @@ def _make_kv_cache_inputs(
9494
prefix: str = "past_key_values",
9595
key_head_dim: int | None = None,
9696
value_head_dim: int | None = None,
97-
cache_specs: list[tuple[int, int, int]] | None = None,
9897
) -> list[tuple[ir.Value, ir.Value]]:
9998
"""Create KV cache input values for ``num_layers`` layers.
10099
@@ -106,31 +105,23 @@ def _make_kv_cache_inputs(
106105
For MLA attention, this is ``qk_nope_head_dim + qk_rope_head_dim``.
107106
value_head_dim: Head dim for values. Defaults to ``head_dim``.
108107
For MLA attention, this is ``v_head_dim``.
109-
cache_specs: Optional per-layer ``(num_heads, key_head_dim,
110-
value_head_dim)`` values for models with non-uniform cache layouts.
111108
112109
Returns:
113110
A list of ``(key, value)`` tuples for passing to the module.
114111
"""
115-
if cache_specs is None:
116-
k_dim = key_head_dim if key_head_dim is not None else head_dim
117-
v_dim = value_head_dim if value_head_dim is not None else head_dim
118-
cache_specs = [(num_kv_heads, k_dim, v_dim)] * num_layers
119-
elif len(cache_specs) != num_layers:
120-
raise ValueError(
121-
f"cache_specs has {len(cache_specs)} entries for {num_layers} cache layers"
122-
)
112+
k_dim = key_head_dim if key_head_dim is not None else head_dim
113+
v_dim = value_head_dim if value_head_dim is not None else head_dim
123114
pairs: list[tuple[ir.Value, ir.Value]] = []
124-
for i, (layer_num_heads, k_dim, v_dim) in enumerate(cache_specs):
115+
for i in range(num_layers):
125116
past_key = builder.input(
126117
f"{prefix}.{i}.key",
127118
dtype=dtype,
128-
shape=[batch, layer_num_heads, past_seq_len, k_dim],
119+
shape=[batch, num_kv_heads, past_seq_len, k_dim],
129120
)
130121
past_value = builder.input(
131122
f"{prefix}.{i}.value",
132123
dtype=dtype,
133-
shape=[batch, layer_num_heads, past_seq_len, v_dim],
124+
shape=[batch, num_kv_heads, past_seq_len, v_dim],
134125
)
135126
pairs.append((past_key, past_value))
136127
return pairs
@@ -147,7 +138,6 @@ def _register_kv_cache_outputs(
147138
value_head_dim: int | None = None,
148139
total_seq_len: ir.SymbolicDim | str | int | None = None,
149140
dtype: ir.DataType | None = None,
150-
cache_specs: list[tuple[int, int, int]] | None = None,
151141
) -> None:
152142
"""Name and register KV cache outputs on the graph.
153143
@@ -171,9 +161,6 @@ def _register_kv_cache_outputs(
171161
When the parameters are omitted, output shapes/dtypes are left to the
172162
shape inference pass that runs during model optimization.
173163
174-
``cache_specs`` replaces the three uniform head parameters with per-layer
175-
``(num_heads, key_head_dim, value_head_dim)`` values.
176-
177164
The present-shape parameters are all-or-nothing by design: pass every one
178165
to stamp the explicit type, or none to opt out and infer. A *partial* set
179166
is always a wiring slip (a caller wired some dims but dropped others) and is
@@ -189,30 +176,19 @@ def _register_kv_cache_outputs(
189176
"total_seq_len": total_seq_len,
190177
"dtype": dtype,
191178
}
192-
if cache_specs is not None:
193-
params.pop("num_kv_heads")
194-
params.pop("key_head_dim")
195-
params.pop("value_head_dim")
196179
provided = [name for name, value in params.items() if value is not None]
197180
stamp = len(provided) == len(params)
198181
if provided and not stamp:
199182
missing = [name for name in params if params[name] is None]
200183
raise ValueError(
201184
f"_register_kv_cache_outputs received a partial set of present-shape "
202185
f"parameters (provided {provided}, missing {missing}); these are "
203-
f"all-or-nothing. Pass all required values to stamp explicit present.* types "
186+
f"all-or-nothing. Pass all six to stamp explicit present.* types "
204187
f"(required for correct GroupQueryAttention head_dim), or none to opt "
205188
f"out and infer."
206189
)
207-
if cache_specs is not None and len(cache_specs) != len(present_key_values):
208-
raise ValueError(
209-
f"cache_specs has {len(cache_specs)} entries for "
210-
f"{len(present_key_values)} present cache pairs"
211-
)
212190
for i, (present_key, present_value) in enumerate(present_key_values):
213191
if stamp:
214-
if cache_specs is not None:
215-
num_kv_heads, key_head_dim, value_head_dim = cache_specs[i]
216192
present_key.shape = ir.Shape([batch, num_kv_heads, total_seq_len, key_head_dim])
217193
present_key.type = ir.TensorType(dtype)
218194
present_value.shape = ir.Shape(

‎src/mobius/tasks/_causal_lm.py‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -185,8 +185,6 @@ def build(
185185
# than they have layers; they report the count via this hook.
186186
count_fn = getattr(module, "kv_cache_layer_count", None)
187187
num_cache_layers = count_fn() if callable(count_fn) else config.num_hidden_layers
188-
specs_fn = getattr(module, "dynamic_kv_cache_specs", None)
189-
cache_specs = specs_fn() if callable(specs_fn) else None
190188

191189
past_key_values = _make_kv_cache_inputs(
192190
builder,
@@ -198,7 +196,6 @@ def build(
198196
past_seq_len,
199197
key_head_dim=kv_key_head_dim,
200198
value_head_dim=kv_value_head_dim,
201-
cache_specs=cache_specs,
202199
)
203200

204201
with prefill_prefix_pruning(self._prune_prefill_prefix):
@@ -239,7 +236,6 @@ def build(
239236
value_head_dim=kv_value_head_dim,
240237
total_seq_len="past_sequence_len + sequence_len",
241238
dtype=config.dtype,
242-
cache_specs=cache_specs,
243239
)
244240

245241
if intermediate_hidden_states is not None:

‎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)

0 commit comments

Comments
 (0)