Skip to content

Commit 9930a91

Browse files
justinchubyCopilot
andcommitted
Auto-detect KV in-place support from graph; thread --ep through build-gguf
ORT GenAI's past_present_share_buffer mode requires the decoder graph to update the KV cache in place (com.microsoft.GroupQueryAttention). The standard ONNX opset 23 Attention op concatenates past_key + new_K and returns a dynamic-shape present_key, which is incompatible with the pre-allocated shared buffer ORT GenAI passes in. The previous config wrote past_present_share_buffer=True purely from the target EP flag, which meant builds that didn't apply the GQA rewrite (anything other than --ep cpu / cuda / dml / etc.) silently shipped a broken config and crashed at first inference with 'inconsistent total_sequence_length'. This change: * Adds supports_in_place_kv_cache to GenaiConfigGenerator and _default_search_params; when set it overrides the EP flag. * In auto_export._write_genai_config, introspects the decoder graph for GroupQueryAttention nodes and passes the result through. Standard-Attention graphs now correctly get share_buffer=False regardless of the target EP. * Adds --ep to the build-gguf CLI and threads execution_provider through build_from_gguf so users can opt into the GQA rewrite for GGUF imports the same way they can for HF imports. * Updates examples/hy_mt1_5.py to build the Q1_0 variant with --ep cpu so the example exercises the full share-buffer path end-to-end and removes the post-hoc _patch_genai_config workaround. Verified end-to-end on tencent/Hy-MT1.5-1.8B-2bit: - 32 GroupQueryAttention nodes after build - genai_config.search.past_present_share_buffer = true - 'Translate to Spanish: The cat is sleeping on the chair.' -> 'El gato está durmiendo en la silla.' Full suite: 2753 passed, 0 failures. Co-authored-by: Copilot <[email protected]> Signed-off-by: Justin Chu <[email protected]>
1 parent fb59741 commit 9930a91

5 files changed

Lines changed: 79 additions & 26 deletions

File tree

‎examples/hy_mt1_5.py‎

Lines changed: 8 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,6 @@ def _build_bf16(output_dir: Path) -> None:
7272
pkg = mobius.build(HF_MODEL_ID, dtype="bf16", load_weights=True)
7373
pkg.save(str(output_dir))
7474
write_ort_genai_config(pkg, str(output_dir), hf_model_id=HF_MODEL_ID, ep="cpu")
75-
_patch_genai_config(output_dir)
7675
print(" genai_config.json + tokenizer files written")
7776

7877

@@ -82,30 +81,19 @@ def _build_q1_0(gguf_path: Path, output_dir: Path) -> None:
8281
from mobius.integrations.ort_genai.auto_export import write_ort_genai_config
8382

8483
print(f"Building Q1_0 -> {output_dir}")
85-
pkg = build_from_gguf(str(gguf_path), keep_quantized=True, dtype="f32")
84+
# ep='cpu' applies the GroupQueryAttention rewrite. With standard
85+
# opset 23 Attention (ep='default'), ORT GenAI's
86+
# past_present_share_buffer mode cannot be used; mobius's
87+
# write_ort_genai_config inspects the resulting graph and turns
88+
# share_buffer off automatically when GQA is absent.
89+
pkg = build_from_gguf(
90+
str(gguf_path), keep_quantized=True, dtype="f32", execution_provider="cpu"
91+
)
8692
pkg.save(str(output_dir))
8793
write_ort_genai_config(pkg, str(output_dir), hf_model_id=HF_MODEL_ID, ep="cpu")
88-
_patch_genai_config(output_dir)
8994
print(" genai_config.json + tokenizer files written")
9095

9196

92-
def _patch_genai_config(output_dir: Path) -> None:
93-
"""Disable ``past_present_share_buffer`` for the dynamic-cache export.
94-
95-
mobius emits a dynamic-shape KV cache (no pre-allocated buffer);
96-
ORT GenAI's default of ``past_present_share_buffer = True`` would
97-
feed the attention op a mask whose ``total_sequence_length`` doesn't
98-
match the dynamic past_key/past_value shapes, producing
99-
``inconsistent total_sequence_length`` at runtime.
100-
"""
101-
import json
102-
103-
cfg_path = output_dir / "genai_config.json"
104-
cfg = json.loads(cfg_path.read_text())
105-
cfg.setdefault("search", {})["past_present_share_buffer"] = False
106-
cfg_path.write_text(json.dumps(cfg, indent=4))
107-
108-
10997
def _ensure_built(args: argparse.Namespace) -> Path:
11098
out = Path(args.out).resolve()
11199
if args.build:

‎src/mobius/__main__.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,7 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
324324
gguf_path,
325325
dtype=args.dtype,
326326
keep_quantized=args.keep_quantized,
327+
execution_provider=args.execution_provider,
327328
)
328329

329330
pkg.save(
@@ -558,6 +559,18 @@ def main(argv: list[str] | None = None) -> None:
558559
default="onnx",
559560
help="External data format (default: onnx).",
560561
)
562+
gguf_parser.add_argument(
563+
"--ep",
564+
"--execution-provider",
565+
dest="execution_provider",
566+
default="default",
567+
metavar="EP",
568+
help=(
569+
"Target execution provider for EP-aware graph optimisations "
570+
"(e.g. 'cpu' to apply the GroupQueryAttention rewrite). "
571+
"Defaults to 'default' (portable ONNX, no vendor fusions)."
572+
),
573+
)
561574
gguf_parser.set_defaults(func=_cmd_build_gguf)
562575

563576
# --- list ---

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ def build_from_gguf(
3535
task: str | None = None,
3636
dtype: str | None = None,
3737
keep_quantized: bool = False,
38+
execution_provider: str = "default",
3839
) -> ModelPackage:
3940
"""Build an ONNX :class:`ModelPackage` from a GGUF file.
4041
@@ -59,6 +60,10 @@ def build_from_gguf(
5960
keep_quantized: When ``True``, preserve quantization for
6061
supported GGUF types (Q4_0, Q4_1, Q8_0) by repacking
6162
linear-layer weights into MatMulNBits format.
63+
execution_provider: Target execution provider for EP-aware
64+
optimisations (e.g. ``"cpu"`` to apply the
65+
GroupQueryAttention rewrite). Defaults to ``"default"``
66+
(portable, no vendor fusions).
6267
6368
Returns:
6469
A :class:`ModelPackage` containing the built model(s).
@@ -137,7 +142,7 @@ def build_from_gguf(
137142

138143
# 5. Build ONNX graph
139144
module = module_class(config)
140-
pkg = build_from_module(module, config, task)
145+
pkg = build_from_module(module, config, task, execution_provider=execution_provider)
141146
logger.info(
142147
"Built ONNX graph for %s (%d components)",
143148
model_type,

‎src/mobius/integrations/ort_genai/auto_export.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -641,6 +641,22 @@ def _write_genai_config(
641641
# Derive decoder filename from the actual package key
642642
decoder_filename = f"{decoder_key}/model.onnx" if decoder_key != "model" else "model.onnx"
643643

644+
# ORT GenAI's ``past_present_share_buffer`` mode requires the decoder
645+
# graph to write the KV cache in place. Only ``com.microsoft.
646+
# GroupQueryAttention`` does that; the standard ONNX ``Attention`` op
647+
# concatenates ``past_key`` with the new ``K`` and returns a dynamic-
648+
# shape ``present_key``, which is incompatible with the pre-allocated
649+
# shared buffer. Introspect the graph: if there is at least one GQA
650+
# node, the model supports shared-buffer mode; otherwise force it off
651+
# regardless of the EP capability flag.
652+
decoder_model = pkg.get(decoder_key)
653+
supports_in_place_kv_cache: bool | None = None
654+
if decoder_model is not None:
655+
supports_in_place_kv_cache = any(
656+
node.op_type == "GroupQueryAttention" and node.domain == "com.microsoft"
657+
for node in decoder_model.graph
658+
)
659+
644660
generator = GenaiConfigGenerator.from_config(
645661
config,
646662
ort_model_type,
@@ -651,6 +667,7 @@ def _write_genai_config(
651667
pad_token_id=pad_token_id,
652668
decoder_inputs=decoder_inputs,
653669
decoder_filename=decoder_filename,
670+
supports_in_place_kv_cache=supports_in_place_kv_cache,
654671
)
655672

656673
if is_vlm:

‎src/mobius/integrations/ort_genai/genai_config.py‎

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,12 @@ def _default_decoder_outputs() -> dict[str, str]:
4747
_SHARE_BUFFER_MAX_LENGTH_CAP = 4096
4848

4949

50-
def _default_search_params(*, ep: str, context_length: int) -> dict[str, Any]:
50+
def _default_search_params(
51+
*,
52+
ep: str,
53+
context_length: int,
54+
supports_in_place_kv_cache: bool | None = None,
55+
) -> dict[str, Any]:
5156
"""Return sensible default search parameters.
5257
5358
Args:
@@ -56,11 +61,23 @@ def _default_search_params(*, ep: str, context_length: int) -> dict[str, Any]:
5661
:data:`~mobius._execution_providers.ep_registry`.
5762
context_length: Model context window; used as the default
5863
``max_length`` for generation so the limit matches the model.
64+
supports_in_place_kv_cache: When ``True`` / ``False``, forces
65+
``past_present_share_buffer`` regardless of the EP flag.
66+
ORT GenAI's shared-buffer mode requires the decoder graph to
67+
update the KV cache *in place* — only the
68+
``com.microsoft.GroupQueryAttention`` op does that. The
69+
standard ONNX ``Attention`` op concatenates past/new K,V into
70+
a dynamically-sized tensor, which is incompatible with the
71+
pre-allocated buffer mode. When ``None`` (legacy callers),
72+
falls back to the EP capability flag.
5973
"""
6074
from mobius._execution_providers import ep_registry
6175

6276
caps = ep_registry.get(ep)
63-
share_buffer = caps.supports_past_present_share_buffer if caps is not None else False
77+
if supports_in_place_kv_cache is None:
78+
share_buffer = caps.supports_past_present_share_buffer if caps is not None else False
79+
else:
80+
share_buffer = supports_in_place_kv_cache
6481
cap_length = caps.cap_kv_buffer_max_length if caps is not None else False
6582
if share_buffer and cap_length:
6683
# Memory-constrained EPs (e.g. WebGPU on consumer GPUs) pre-allocate
@@ -151,6 +168,7 @@ def __init__(
151168
pad_token_id: int | None = None,
152169
decoder_inputs: dict[str, str] | None = None,
153170
decoder_filename: str | None = None,
171+
supports_in_place_kv_cache: bool | None = None,
154172
):
155173
self.model_type = model_type
156174
self.vocab_size = vocab_size
@@ -165,10 +183,16 @@ def __init__(
165183
self.eos_token_id = eos_token_id
166184
self.pad_token_id = pad_token_id
167185

168-
# Explicit decoder inputs (from graph introspection); None → use defaults
186+
# Explicit decoder inputs (from graph introspection); None -> use defaults
169187
self._decoder_inputs = decoder_inputs
170-
# Explicit decoder filename; None → use "model.onnx"
188+
# Explicit decoder filename; None -> use "model.onnx"
171189
self._decoder_filename = decoder_filename
190+
# Whether the exported decoder ONNX graph supports in-place KV-cache
191+
# updates (i.e. uses ``com.microsoft.GroupQueryAttention`` rather than
192+
# the standard ``Attention`` op that concatenates). ``None`` falls back
193+
# to the EP capability flag, preserving existing behaviour for callers
194+
# that don't introspect the graph.
195+
self._supports_in_place_kv_cache = supports_in_place_kv_cache
172196

173197
# Optional VLM fields (set via with_vision())
174198
self._vision: dict[str, Any] | None = None
@@ -194,6 +218,7 @@ def from_config(
194218
pad_token_id: int | None = None,
195219
decoder_inputs: dict[str, str] | None = None,
196220
decoder_filename: str | None = None,
221+
supports_in_place_kv_cache: bool | None = None,
197222
) -> GenaiConfigGenerator:
198223
"""Create a generator from a BaseModelConfig-like dataclass.
199224
@@ -227,6 +252,7 @@ def from_config(
227252
pad_token_id=pad,
228253
decoder_inputs=decoder_inputs,
229254
decoder_filename=decoder_filename,
255+
supports_in_place_kv_cache=supports_in_place_kv_cache,
230256
)
231257

232258
def with_vision(
@@ -410,7 +436,11 @@ def generate(self) -> dict[str, Any]:
410436
model["speech"] = self._audio
411437
model.update(self._vlm_token_ids)
412438

413-
search = _default_search_params(ep=self.ep, context_length=self.context_length)
439+
search = _default_search_params(
440+
ep=self.ep,
441+
context_length=self.context_length,
442+
supports_in_place_kv_cache=self._supports_in_place_kv_cache,
443+
)
414444
search.update(self._search_overrides)
415445

416446
return {

0 commit comments

Comments
 (0)