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