Skip to content

Commit cce80a4

Browse files
justinchubyCopilot
andauthored
feat: any-to-any onnx-genai pipeline support (VLM/ASR/codec/GGUF + Qwen3-TTS) (#415)
## Summary Adds **model-builder + metadata-emitter support for any-to-any onnx-genai pipelines**, pairing with the onnx-genai `feat/any-to-any-pipeline` PR (runtime). Mobius now builds and self-describes VLM, ASR, audio-codec, GGUF, and multi-decoder TTS packages for the onnx-genai composite runtime. ## What's included **onnx-genai metadata emitters** (`src/mobius/integrations/onnx_genai/`) - Composite **ASR** (Whisper-style), **audio-codec** (audio-to-audio), and **multimodal VLM** pipeline metadata. - Self-contained packages: emit `tokenizer.json` for decoder/VLM/ASR builds. - **`build_tts_pipeline_metadata`**: emits the `pre_embedder`-driven `nested_autoregressive` contract for real Qwen3-TTS (talker + code_predictor + talker_step_embedder), validated against onnx-genai's committed JSON schema. Packages without the pre-embedder raise a precise error. - Structural dispatch in `write_onnx_genai_config` (fails loudly on unknown shapes). **GGUF integration** (`src/mobius/integrations/gguf/`) - `build-gguf --runtime onnx-genai` emits `inference_metadata` + `tokenizer.json`. - Build **Gemma3/Gemma4 from GGUF**; **Gemma4 multimodal VLM from mmproj GGUF** with quantization preserved (~4.2 GB self-contained). - Reconstruct `tokenizer.json` for archs transformers doesn't recognize (gemma4); fix string-array reader off-by-one. **Qwen3-TTS model** (`src/mobius/models/qwen3_tts.py`, `tasks/_tts.py`) - `talker_step_embedder` pre-embedding component (`frame_codes [+ text_embed] -> inputs_embeds`), sharing weights with embedding/code_predictor (validated maxdiff 0.0 vs HF; exact code match over full generation). - Build fixes: route the Identity-folded `codec_embeddings` initializer; preserve the talker's non-standard interleaved-MRoPE `rope_scaling` (dropped by HF standardization) so the talker uses MRoPE. ## Testing onnx-genai integration + qwen3-tts model tests green; TTS emitter validated end to end against the real 1.7B `Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice` package + the committed JSON schema. Co-authored-by: Copilot <[email protected]> --------- Co-authored-by: Copilot <[email protected]>
1 parent 556b22e commit cce80a4

26 files changed

Lines changed: 4375 additions & 77 deletions

‎src/mobius/__main__.py‎

Lines changed: 57 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,8 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
364364
)
365365
raise SystemExit(1)
366366

367+
mmproj_path = getattr(args, "mmproj", None)
368+
367369
if args.keep_quantized:
368370
print(
369371
"Quantized mode: preserving GGUF quantization as "
@@ -374,12 +376,22 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
374376
output_dir = args.output or os.path.splitext(gguf_path)[0] + "_onnx"
375377
os.makedirs(output_dir, exist_ok=True)
376378

377-
pkg = build_from_gguf(
378-
gguf_path,
379-
dtype=args.dtype,
380-
keep_quantized=args.keep_quantized,
381-
execution_provider=args.execution_provider,
382-
)
379+
if mmproj_path is not None:
380+
print(f"Multimodal mode: fusing vision/audio encoder from mmproj {mmproj_path}...")
381+
pkg = build_from_gguf(
382+
gguf_path,
383+
mmproj=mmproj_path,
384+
dtype=args.dtype,
385+
execution_provider=args.execution_provider,
386+
keep_quantized=args.keep_quantized,
387+
)
388+
else:
389+
pkg = build_from_gguf(
390+
gguf_path,
391+
dtype=args.dtype,
392+
keep_quantized=args.keep_quantized,
393+
execution_provider=args.execution_provider,
394+
)
383395

384396
pkg.save(
385397
output_dir,
@@ -393,6 +405,22 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
393405
path = os.path.join(output_dir, "model.onnx")
394406
print(f"Saved {name} to {path}")
395407

408+
if getattr(args, "runtime", None) == "onnx-genai":
409+
from mobius.integrations.gguf import write_gguf_tokenizer_json
410+
from mobius.integrations.onnx_genai import write_onnx_genai_config
411+
412+
# A GGUF checkpoint has no Hugging Face source directory, so the
413+
# tokenizer is reconstructed from the file's embedded ggml metadata
414+
# rather than copied from a `source`.
415+
tokenizer_path = write_gguf_tokenizer_json(gguf_path, output_dir)
416+
if tokenizer_path is not None:
417+
print(f" tokenizer: {tokenizer_path}")
418+
artifacts = write_onnx_genai_config(
419+
pkg, output_dir, config=getattr(pkg, "config", None), source=None
420+
)
421+
for name, path in artifacts.items():
422+
print(f" {name}: {path}")
423+
396424

397425
def _cmd_convert_comfyui(args: argparse.Namespace) -> None:
398426
"""Execute the 'convert-comfyui' subcommand."""
@@ -635,6 +663,17 @@ def main(argv: list[str] | None = None) -> None:
635663
metavar="DIR",
636664
help="Output directory (default: <gguf_stem>_onnx/).",
637665
)
666+
gguf_parser.add_argument(
667+
"--mmproj",
668+
default=None,
669+
metavar="PATH",
670+
help=(
671+
"Path to a companion 'clip' mmproj GGUF (vision/audio encoder). "
672+
"When set, builds a full multimodal package (decoder + "
673+
"vision_encoder + embedding) instead of a text-only model. "
674+
"Currently supports Gemma4 vision; audio is experimental."
675+
),
676+
)
638677
gguf_parser.add_argument(
639678
"--keep-quantized",
640679
action="store_true",
@@ -667,6 +706,18 @@ def main(argv: list[str] | None = None) -> None:
667706
"Defaults to 'default' (portable ONNX, no vendor fusions)."
668707
),
669708
)
709+
gguf_parser.add_argument(
710+
"--runtime",
711+
choices=["ort-genai", "onnx-genai"],
712+
default=None,
713+
help=(
714+
"Generate runtime-specific config files after building. "
715+
"'onnx-genai' writes inference_metadata.yaml plus a tokenizer.json "
716+
"reconstructed from the GGUF's embedded tokenizer metadata; "
717+
"'ort-genai' writes genai_config.json + copies tokenizer files. "
718+
"Either way the quantized model runs directly in the target runtime."
719+
),
720+
)
670721
gguf_parser.set_defaults(func=_cmd_build_gguf)
671722

672723
# --- list ---

‎src/mobius/_config_resolver.py‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,8 +161,24 @@ def _dict_to_pretrained_config(d: dict):
161161
setattr(config, k, v)
162162

163163
# Recursively convert known nested config keys
164+
rope_keys = ("rope_scaling", "rope_parameters")
164165
for key in nested_config_keys:
165166
val = getattr(config, key, None)
166167
if isinstance(val, dict):
167-
setattr(config, key, _dict_to_pretrained_config(val))
168+
# Capture the raw rope fields before conversion: constructing a
169+
# nested PretrainedConfig runs HF rope standardization, which
170+
# silently drops non-standard rope_scaling formats (e.g. the
171+
# Qwen3-TTS talker's ``{"interleaved": True, "mrope_section": ...,
172+
# "type": "default"}``). Restore them onto the converted config so
173+
# _extract_mrope_fields / _extract_rope_config can still read them.
174+
raw_rope = {k: val[k] for k in rope_keys if k in val}
175+
nested = _dict_to_pretrained_config(val)
176+
for k, v in raw_rope.items():
177+
# The raw config.json value is authoritative for our extractors.
178+
# Restore it whenever HF standardization dropped (None) OR
179+
# rewrote it to a different value, so non-standard formats
180+
# (e.g. Qwen3-TTS's ``interleaved``/``mrope_section``) survive.
181+
if getattr(nested, k, None) != v:
182+
setattr(nested, k, v)
183+
setattr(config, key, nested)
168184
return config

‎src/mobius/_configs/_base.py‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -269,8 +269,14 @@ def _extract_mrope_fields(config) -> dict:
269269
rope_scaling = getattr(config, "rope_scaling", None) or {}
270270
rope_parameters = getattr(config, "rope_parameters", None) or {}
271271
result: dict = {}
272-
mrope_interleaved = rope_scaling.get("mrope_interleaved", False) or rope_parameters.get(
273-
"mrope_interleaved", False
272+
# Some models (e.g. Qwen3-TTS talker) spell the interleaved flag as the
273+
# bare ``interleaved`` key inside ``rope_scaling`` rather than the
274+
# ``mrope_interleaved`` name that Qwen3-VL uses. Accept both spellings.
275+
mrope_interleaved = (
276+
rope_scaling.get("mrope_interleaved", False)
277+
or rope_scaling.get("interleaved", False)
278+
or rope_parameters.get("mrope_interleaved", False)
279+
or rope_parameters.get("interleaved", False)
274280
)
275281
if mrope_interleaved:
276282
result["mrope_interleaved"] = True

‎src/mobius/_configs_test.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -442,6 +442,20 @@ class Cfg:
442442
assert result["mrope_interleaved"] is True
443443
assert result["mrope_section"] == [8, 16, 8]
444444

445+
def test_mrope_interleaved_alias_from_rope_scaling(self):
446+
"""Qwen3-TTS talker spells the flag as bare ``interleaved``."""
447+
448+
class Cfg:
449+
rope_scaling: ClassVar[dict] = {
450+
"interleaved": True,
451+
"mrope_section": [24, 20, 20],
452+
"rope_type": "default",
453+
}
454+
455+
result = _extract_mrope_fields(Cfg())
456+
assert result["mrope_interleaved"] is True
457+
assert result["mrope_section"] == [24, 20, 20]
458+
445459
def test_original_max_position_embeddings(self):
446460
class Cfg:
447461
original_max_position_embeddings = 8192

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

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,24 @@
1010
1111
from mobius.integrations.gguf import build_from_gguf
1212
13+
# Text-only model
1314
pkg = build_from_gguf("path/to/model.gguf")
15+
16+
# Multimodal (text + companion mmproj vision/audio encoder)
17+
pkg = build_from_gguf("path/to/model.gguf", mmproj="path/to/mmproj.gguf")
18+
19+
:func:`build_from_gguf` is the single entry point; passing ``mmproj`` delegates
20+
to :func:`build_gemma4_vlm_from_gguf` for the multimodal assembly.
1421
"""
1522

1623
from __future__ import annotations
1724

1825
from mobius.integrations.gguf._builder import build_from_gguf
19-
20-
__all__ = ["build_from_gguf"]
26+
from mobius.integrations.gguf._mmproj import build_gemma4_vlm_from_gguf
27+
from mobius.integrations.gguf._tokenizer import write_gguf_tokenizer_json
28+
29+
__all__ = [
30+
"build_from_gguf",
31+
"build_gemma4_vlm_from_gguf",
32+
"write_gguf_tokenizer_json",
33+
]

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

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@ def build_from_gguf(
8383
dtype: str | None = None,
8484
keep_quantized: bool = False,
8585
execution_provider: str = "default",
86+
mmproj: str | Path | None = None,
8687
) -> ModelPackage:
8788
"""Build an ONNX :class:`ModelPackage` from a GGUF file.
8889
@@ -116,6 +117,12 @@ def build_from_gguf(
116117
optimisations (e.g. ``"cpu"`` to apply the
117118
GroupQueryAttention rewrite). Defaults to ``"default"``
118119
(portable, no vendor fusions).
120+
mmproj: Optional path (or HF ref) to a companion ``clip``
121+
multimodal-projector GGUF. When set, this becomes the single
122+
entry point for a multimodal build: the text GGUF and the
123+
mmproj vision/audio encoder are fused into one multimodal
124+
:class:`ModelPackage` (delegates to
125+
:func:`build_gemma4_vlm_from_gguf`).
119126
120127
Returns:
121128
A :class:`ModelPackage` containing the built model(s).
@@ -127,6 +134,20 @@ def build_from_gguf(
127134
"""
128135
import dataclasses
129136

137+
# A companion mmproj GGUF turns this into a multimodal build: the text +
138+
# vision/audio encoders are assembled by the dedicated VLM builder. Keep
139+
# build_from_gguf as the single public entry point (text-only or multimodal).
140+
if mmproj is not None:
141+
from mobius.integrations.gguf._mmproj import build_gemma4_vlm_from_gguf
142+
143+
return build_gemma4_vlm_from_gguf(
144+
gguf_path,
145+
mmproj,
146+
dtype=dtype,
147+
execution_provider=execution_provider,
148+
keep_quantized=keep_quantized,
149+
)
150+
130151
from mobius._builder import (
131152
build_from_module,
132153
resolve_dtype,
@@ -509,6 +530,68 @@ def _require_supported_requantization(
509530
)
510531

511532

533+
def repack_gguf_weight_to_target(
534+
gguf_model,
535+
raw,
536+
qtype,
537+
np_shape,
538+
*,
539+
target_bits: int,
540+
target_block_size: int,
541+
target_symmetric: bool,
542+
tensor_name: str,
543+
):
544+
"""Repack one 2-D GGUF weight to the graph's common MatMulNBits target.
545+
546+
Reuses the shared repacker machinery: a tensor whose native repacked layout
547+
already matches ``(target_bits, target_block_size)`` is repacked directly;
548+
otherwise it is dequantized and requantized to the target layout. This is
549+
the single-tensor building block reused by both the text-only
550+
(:func:`_load_quantized_state_dict`) and the multimodal quantized loaders.
551+
552+
Args:
553+
gguf_model: The source :class:`GGUFModel`.
554+
raw: Raw tensor bytes (as returned by ``tensor_items_raw``).
555+
qtype: The GGUF quantization type of the tensor.
556+
np_shape: The tensor's logical ``(N, K)`` shape.
557+
target_bits: Target MatMulNBits bit width.
558+
target_block_size: Target MatMulNBits block size.
559+
target_symmetric: Whether the requantization path should omit
560+
zero-points (symmetric). Only used when requantizing.
561+
tensor_name: Name used for error messages.
562+
563+
Returns:
564+
A ``RepackedTensor`` with the target ``(bits, block_size)`` layout.
565+
"""
566+
import numpy as np
567+
568+
from mobius.integrations.gguf._repacker import (
569+
can_repack,
570+
repack_dequantized_tensor,
571+
repack_gguf_tensor,
572+
)
573+
574+
qtype_val = qtype.value if hasattr(qtype, "value") else qtype
575+
if can_repack(qtype_val):
576+
shape_2d = (int(np_shape[0]), int(np_shape[1]))
577+
repacked = repack_gguf_tensor(raw.ravel().view(np.uint8), qtype_val, shape_2d)
578+
if repacked.bits == target_bits and repacked.block_size == target_block_size:
579+
return repacked
580+
581+
_require_supported_requantization(
582+
bits=target_bits,
583+
block_size=target_block_size,
584+
tensor_name=tensor_name,
585+
)
586+
values = gguf_model.dequantize_raw_tensor(raw, qtype, np_shape)
587+
return repack_dequantized_tensor(
588+
values,
589+
bits=target_bits,
590+
block_size=target_block_size,
591+
symmetric=target_symmetric,
592+
)
593+
594+
512595
def _load_dequantized_state_dict(
513596
gguf_model,
514597
gguf_arch: str,

0 commit comments

Comments
 (0)