Repository navigation
feat: any-to-any onnx-genai pipeline support (VLM/ASR/codec/GGUF + Qwen3-TTS) - #415
Conversation
Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
…+ tokenizer.json A GGUF-built model can now run directly in the onnx-genai runtime. `build-gguf` gains a `--runtime onnx-genai` flag that, after saving the ONNX, reconstructs a HF-compatible tokenizer.json from the GGUF's embedded tokenizer.ggml.* metadata (via transformers' gguf_file loading) and emits inference_metadata.yaml through the existing write_onnx_genai_config path. - New _tokenizer.write_gguf_tokenizer_json: best-effort fast-tokenizer reconstruction (warns + skips on unavailable transformers or unconvertible ggml tokenizer model, never blocks the build), mirroring the diffusion CLIP tokenizer helper. - Wires tokenizer + config emission into _cmd_build_gguf; source=None since a GGUF has no HF source dir. - Tests: graceful-skip without tokenizer metadata, mocked fast-tokenizer serialization (asserts gguf_file load), and inference_metadata.yaml emission for a GGUF-built decoder package. gguf + onnx_genai suites: 231 passed. Unblocks running unsloth/gemma-4-12b-it-GGUF (quantized text) in onnx-genai. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
…or names) Building a Gemma3 model from GGUF crashed three ways because GGUF omits fields Gemma3TextModel needs and the shared Gemma2/3 tensor map used names llama.cpp doesn't emit for Gemma3. Fixes so `build-gguf` produces a runnable Gemma3 model: - _gemma3_postprocess: default rope_local_base_freq (10000.0) and derive layer_types from the sliding_window_pattern (default 6) — GGUF stores neither, so the local rotary embedding and per-layer local/global attention pattern were None. - _GEMMA3_EXTRAS: Gemma3 uses the llama.cpp Gemma tensor names (ffn_norm = pre-feedforward norm, post_ffw_norm, post_attention_norm, attn_q/k_norm) — the same as Gemma4 — not the pre_ffn_norm/post_ffn_norm names in _GEMMA2_EXTRAS. Dispatch gemma3 to its own extras, leaving gemma/gemma2 untouched. Verified end to end: `build-gguf unsloth/gemma-3-1b-it Q4_0 --runtime onnx-genai` now builds model.onnx + tokenizer.json + inference_metadata.yaml and loads and decodes in onnx-genai. Full numerical parity of the decoded text is a follow-up (output is not yet coherent — a separate weight/runtime correctness issue). Tests: gemma3 tensor-name mapping + config-postprocess defaults; gguf suite 168. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
…h-to-text The multimodal emitter only handled the embedding-fusion VLM shape (encoder -> inputs_embeds -> decoder). Whisper-style ASR is a different composite shape: encoder -> decoder via encoder_hidden_states CROSS-ATTENTION, no embedding fusion. The onnx-genai engine already runs this (tiny-whisper fixture), but Mobius emitted only bare decoder metadata for it. - build_speech_to_text_pipeline_metadata / write_speech_to_text_pipeline_metadata: emit the composite (encode_audio single_pass prompt_only + decode_transcript autoregressive every_step) with the encoder.encoder_hidden_states -> decoder.encoder_hidden_states dataflow edge, retaining decoder capabilities. - _looks_like_speech_to_text: structural detection (encoder+decoder where the decoder consumes encoder_hidden_states), which cleanly separates ASR from a codec (whose encoder/decoder are pure single_pass, no cross-attn input). - Dispatch order: diffusion -> multimodal(fusion) -> speech_to_text(cross-attn) -> decoder. Tests: ASR emission + codec-not-misdetected. onnx_genai suite 70. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
Rounds out the audio emission contract: Mobius now emits the pure single-pass composite for a neural codec (encoder waveform->codes, decoder codes->waveform), matching the tiny-codec fixture the engine already runs via run_pipeline. - build_audio_codec_pipeline_metadata / write_audio_codec_pipeline_metadata: two single_pass stages (encode_waveform, decode_waveform) sharing one pool, wired encoder.codes -> decoder.codes; encoder type audio_encoder, decoder type vocoder; no decoder capabilities (produces tensors, not tokens). - _looks_like_audio_codec: structural detection (encoder outputs `codes`, decoder consumes `codes`, no encoder_hidden_states) — separates a codec from Whisper ASR and from an image VAE (latent/sample). _audio_codec_codes_dtype reads the codes dtype (default int64). Dispatched before the config requirement since a codec needs no decoder config. - Tests: codec emission (int64 codes, single_pass stages) + ASR still cross-attn. onnx_genai suite 70. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
…ly on unknown shapes Makes the onnx-genai config emission contract explicit and extensible: - write_onnx_genai_config docstring now documents the full ordered dispatch (diffusion -> audio codec -> multimodal VLM -> speech-to-text -> decoder LM), each shape's structural detector signal, the emitted strategy, and the recipe for adding a new modality (structural _looks_like_X detector + build_X builder + a specificity-ordered dispatch branch). - Fail loudly: a multi-component package matching no composite shape (e.g. a multi-decoder TTS stack: talker + code_predictor + vocoder) now raises a clear error naming the components and supported shapes, instead of silently emitting bare decoder metadata for the wrong component. This marks the current contract boundary — real Qwen3-TTS needs a dedicated multi-decoder emitter. - Test: unrecognized multi-component package raises. onnx_genai suite 71. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
…t paths Found by building a real whisper-tiny end to end: Mobius saves multi-component packages under per-component subfolders (encoder/model.onnx, decoder/model.onnx), but the ASR and audio-codec emitters hardcoded flat filenames (encoder.onnx), so the emitted inference_metadata.yaml pointed at nonexistent paths. The multimodal emitter already used the subfolder layout; align ASR/codec with it. Verified: `mobius build --model openai/whisper-tiny --task speech-to-text --runtime onnx-genai` now emits filename: encoder/model.onnx + decoder/model.onnx matching the on-disk layout. Also confirmed the real whisper decoder recomputes cross-attention from encoder_hidden_states each step (self-attention KV only) — exactly the pattern the onnx-genai engine's fixed-cross-conditioning path supports. Tests updated; onnx_genai suite 71. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
…lti-decoder TTS shape A nested multi-decoder TTS package (talker + code_predictor, e.g. Qwen3-TTS) now raises a specific NotImplementedError pointing to the nested_autoregressive design (DESIGN.md §20.3), instead of the generic "unrecognized multi-component" message. This sharpens the contract boundary: the one designed-but-unimplemented modality is diagnosed precisely and actionably, while genuinely unknown multi-component shapes still fail loudly with the generic guard. - _looks_like_multi_decoder_tts: structural detection (talker + code_predictor). - Tests: TTS shape -> NotImplementedError(nested_autoregressive); a non-TTS unknown multi-component package -> ValueError(multi-component). Suite 72. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
…ge ASR) The multimodal emitter already handles the audio-only fusion shape (audio_encoder -> embedding -> AR decoder) used by speech-language ASR models such as qwen3_asr and fun_asr, but only vision-only and vision+audio were tested. Add an audio-only test asserting the emitted models, the audio_encoder.audio_features -> embedding.audio_features -> decoder.inputs_embeds dataflow, and the encode_audio/fuse_embeddings/decode stages. onnx_genai 73. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
…elf-contained) Only the diffusion (CLIP) and GGUF paths emitted a tokenizer.json; the decoder-LM, multimodal (VLM / speech-language ASR), and Whisper-style ASR paths referenced `tokenizer: tokenizer.json` in their metadata but never wrote one, so `build --runtime onnx-genai` produced packages the onnx-genai runtime could not tokenize prompts from. - _write_hf_tokenizer: reconstruct tokenizer.json from the source model's fast tokenizer (best-effort; warns + skips if transformers/source/fast-backend is unavailable), mirroring the diffusion CLIP helper. - Wired into the decoder, multimodal, and speech_to_text branches (codec is tensor-only and needs none). - Tests: tokenizer emitted with a source, skipped without one. Suite 75. Verified on a real build: `mobius build --model openai/whisper-tiny --task speech-to-text --runtime onnx-genai` now emits encoder + decoder + inference_metadata.yaml + tokenizer.json — a self-contained package. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
Add support for reading a companion `clip`-arch mmproj GGUF (vision/audio encoder) and assembling a full Gemma4 multimodal ONNX package (decoder + vision_encoder + embedding) alongside the text backbone. - _mmproj_mapping.py: map clip mmproj `v.*`/`mm.*` (and `a.*`) tensor names to the HF `vision_tower.*`/`embed_vision.*` (`audio_tower.*`/`embed_audio.*`) names consumed by Gemma4Model.preprocess_weights; skip llama.cpp activation-range stat tensors (.input_max/min/.output_max/min). - _mmproj.py: read_mmproj_vision_config / read_mmproj_audio_config extract the Gemma4 VisionConfig/Gemma4AudioConfig from clip.vision.*/clip.audio.* metadata; build_gemma4_vlm_from_gguf merges configs, reuses the existing Gemma4 graphs, maps + applies dequantized weights via preprocess_weights. - __main__.py: add `build-gguf --mmproj <path>` to produce the multimodal package (with composite onnx-genai metadata via --runtime onnx-genai). - _config_mapping.py: collapse Gemma4 per-layer feed_forward_length array to a scalar intermediate_size + use_double_wide_mlp (required to build E2B/E4B). - Tests: mmproj tensor-name mapping, config extraction from a synthetic clip GGUF, a vision encoder build+ORT-run smoke test, and double-wide MLP collapse. Vision is validated end-to-end (build + finite image_features). Audio config extraction + tensor mapping are provided and name-tested but the audio encoder is not yet wired into the assembled package (Conformer forward-pass layout still needs validation against llama.cpp clip.cpp gemma4a). Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
…rts nested_autoregressive The onnx-genai runtime landed nested_autoregressive execution (b4c236f), so the fail-loud message for a multi-decoder TTS package is updated: the runtime now supports the strategy; only this Mobius emitter does not yet map the Qwen3-TTS component graph to it. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
`build-gguf --mmproj --keep-quantized` previously ignored --keep-quantized and dequantized everything, yielding a ~20 GB package. It now produces a mixed-precision multimodal package: the text decoder stays MatMulNBits and the token embedding stays GatherBlockQuantized (int4), while the mmproj-sourced vision encoder stays float. The E2B test package drops from ~20 GB to 4.2 GB (decoder 1.8G, embedding 1.7G, vision 684M). Mixed precision needs no per-module opt-out: only the Gemma4 *text* components read `config.quantization` (via `_text_linear_class` / `_make_scaled_word_embedding` / `_make_lm_head`); the vision/audio encoder modules always build float `Linear`, so a single module-global `QuantizationConfig` quantizes decoder + embedding and leaves vision float. - models/gemma4.py: wire quantization into text attention/MLP/embeddings/ lm_head; add `Gemma4ScaledQuantizedWordEmbedding`; route quantized embed_tokens suffixes in `preprocess_weights`. - integrations/gguf/_mmproj.py: add `keep_quantized` to `build_gemma4_vlm_from_gguf` and a quantized text loader (`_text_gguf_to_hf_multimodal_quantized`) reusing the text keep_quantized repack flow; vision stays via `_mmproj_vision_to_hf`. - integrations/gguf/_builder.py: extract reusable `repack_gguf_weight_to_target` helper. - __main__.py: pass keep_quantized through; drop the "ignored" note. Also fix a pre-existing decoder ORT-load failure (affects float builds too): KV-shared layers reshaped their borrowed K/V with a dynamic `-1` hidden size, so onnxruntime could not shape-infer the attention output width and rejected the graph with a MatMul "Incompatible dimensions" error at session creation. Reshaping to the static `num_key_value_heads * head_dim` fixes it with no numeric change. All three components now load + run in ORT with finite outputs. Tests: extend _mmproj_test.py with a keep_quantized mixed-precision build assertion (decoder has MatMulNBits, embedding has GatherBlockQuantized, vision has neither) and a quantized-decoder ORT-load test covering KV-shared layers. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
… + fix string-array reader
Two fixes that make a GGUF-built Gemma4 (VLM or text) package self-contained:
1. _reader string-array bug: _parse_array iterated all parts and picked up the
field key name as element 0, shifting every string in tokenizer.ggml.tokens /
.merges by one (e.g. tokens[2] came back '<eos>' instead of '<bos>' despite
bos_token_id=2). Use the `data` value-indices like the numeric path. Verified:
tokens[0]='<pad>', tokens[2]='<bos>', full 262144 vocab, clean merges.
2. Tokenizer fallback: transformers' GGUF loader doesn't support the gemma4 arch
("architecture gemma4 is not supported yet"), so write_gguf_tokenizer_json now
falls back to reconstructing the fast BPE tokenizer directly from the ggml
metadata (tokens + merges + special ids), with SentencePiece metaspace +
byte-fallback + a <bos> post-processor. Round-trips cleanly; <bos>=2, <eos>=1
match the GGUF. Emits a correct 262144-token tokenizer.json for Gemma4 GGUFs.
Tests: reconstruction with correct ids/round-trip; reader suite 43. gguf +
onnx_genai suites: 290 passed.
Co-authored-by: Copilot <[email protected]>
Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
…alrus parens, TRY300) Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
…ializer name
The code predictor exposes its stacked codec-embedding table via
`op.Identity(stacked_codec_embedding)` as the `codec_embeddings` graph
output. onnx-ir folds the Identity, so the sole initializer takes the
OUTPUT name `codec_embeddings` (unprefixed) rather than the
`code_predictor.stacked_codec_embedding` name that `finalize_stacked_weights`
previously emitted. The name mismatch meant the stacked weight was never
applied, leaving `codec_embeddings` unpopulated and failing the build.
Key the stacked weight to the exact `codec_embeddings` initializer name so
apply_weights routes the unprefixed name to the only component that declares
it. Verified end-to-end: the built package's code_predictor now emits a
[15, 2048, 2048] codec_embeddings that matches the HF
`talker.code_predictor.model.codec_embedding.{i}.weight` stack exactly
(maxdiff 0.0).
Co-authored-by: Copilot <[email protected]>
Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
…es MRoPE
The Qwen3-TTS talker uses interleaved MRoPE, but the built talker fell back
to plain 1D RoPE — a Gather of the 2D cos_cache by 3D MRoPE position_ids
(3, batch, seq) produced a 4D cos_cache and ORT failed with
"Input 'cos_cache' is expected to have 3 dimensions, got 4".
Two root causes, both fixed:
1. The talker's rope_scaling is
`{"interleaved": True, "mrope_section": [24,20,20], "type": "default"}`.
Constructing a nested PretrainedConfig runs HF rope standardization, which
silently drops this non-standard format (rope_scaling becomes None).
`_dict_to_pretrained_config` now captures the raw rope_scaling/rope_parameters
of each nested config before conversion and restores them onto the converted
config when standardization dropped them, so the extractors can still read them.
2. `_extract_mrope_fields` only recognized the `mrope_interleaved` key (Qwen3-VL
spelling). Qwen3-TTS spells it as bare `interleaved`; accept both spellings
in rope_scaling and rope_parameters.
With both fixes the talker exports with InterleavedMRope (section [24,20,20])
and end-to-end codec-token generation runs: 27 frames x 16 codes for
"Hello world.", all codes in the valid codebook range [0,2047] with natural EOS
termination. Adds a unit test for the `interleaved` alias.
Co-authored-by: Copilot <[email protected]>
Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
Materialize the per-step talker codec_sum construction inside a new ONNX graph so a generic runtime loop can drive the talker from the previous frame's raw integer codes instead of a pre-built inputs_embeds. The component takes frame_codes [batch, num_code_groups] int64 and text_embed [batch, 1, hidden] float, and outputs inputs_embeds [batch, 1, hidden] == talker.codec_embed(code_0) + Σ_i cp_codec_weights[i][codes[i+1]] + text_embed, computed via Gather+Add. It holds the talker codec-embedding table and the code predictor stacked codec-embedding table as initializers, sharing weights with the existing embedding and code_predictor models (routed in preprocess_weights, no re-quantization). Text projection stays on the embedding model. Wired into TTSTask as a new package model. Validated against the examples/qwen3_tts.py generate_codes reference: inputs_embeds matches the in-loop codec_sum + text_embed to 0.0 max abs diff, and a full greedy generation driven by the component reproduces identical codes. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
…metadata Add build_tts_pipeline_metadata / write_tts_pipeline_metadata and wire the write_onnx_genai_config dispatcher so a real Qwen3-TTS package (talker + code_predictor + talker_step_embedder) emits the pre_embedder-driven nested_autoregressive contract instead of raising NotImplementedError. The emitter maps exactly the three engine-driven components: the talker (outer decoder, driven by inputs_embeds), the code_predictor (inner decoder), and the talker_step_embedder pre-embedder, with the required `talker_step_embedder.inputs_embeds -> talker.inputs_embeds` feed edge and the `talker.last_hidden_state -> code_predictor.inputs_embeds` inner seed edge. num_code_groups comes from config.tts. The package's embedding/speaker_encoder (trailing-text + prefill path) are deliberately omitted until the runtime consumes them (see onnx-genai DESIGN §20.3). A package lacking the pre-embedder still raises a precise, updated NotImplementedError. Validated end to end: the real 1.7B Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice package emits metadata that validates against onnx-genai's committed JSON schema. Adds builder + dispatch + schema-validation tests (43 pass). Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
Performance Comparison
|
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
🏗️ Architecture Diff
No architecture changes detected. ✅ Legend: ⚪ No change · 🔵 Minor (attrs/inits) · 🟡 Moderate (nodes added/removed) · 🔴 Major (interface changed) |
There was a problem hiding this comment.
Pull request overview
Adds end-to-end onnx-genai “any-to-any” composite pipeline support across multimodal (VLM), ASR, audio codec, GGUF-based packages, and nested multi-decoder TTS (Qwen3‑TTS), including metadata emission and supporting model/task changes.
Changes:
- Add composite
inference_metadata.yamlemitters + structural dispatch for multimodal, speech-to-text, audio codec, and TTS nested-autoregressive pipelines (plus tokenizer.json emission). - Extend GGUF integration: tokenizer.json reconstruction, Gemma4 multimodal build from text+mmproj GGUF, and updated Gemma3/Gemma4 GGUF tensor/config mapping.
- Add Qwen3‑TTS “talker_step_embedder” pre-embedding component and wire it into the TTS task + weight routing.
Reviewed changes
Copilot reviewed 26 out of 26 changed files in this pull request and generated 8 comments.
Show a summary per file
| File | Description |
|---|---|
| src/mobius/tasks/_tts.py | Add talker_step_embedder component build output for Qwen3‑TTS TTS package. |
| src/mobius/models/qwen3_tts.py | Implement talker pre-embedder module and route shared codec tables into it. |
| src/mobius/models/qwen3_tts_test.py | Unit tests for the talker step embedder graph behavior + weight sharing. |
| src/mobius/models/gemma4.py | Add mixed-precision quantization helpers for text path (decoder/embeddings/lm_head). |
| src/mobius/integrations/onnx_genai/inference_metadata.py | Add composite metadata builders for multimodal, ASR, codec, and nested TTS pipelines. |
| src/mobius/integrations/onnx_genai/inference_metadata_test.py | Schema/shape/unit tests for the new composite metadata emitters. |
| src/mobius/integrations/onnx_genai/auto_export.py | Structural package-shape detection and dispatch to the right metadata emitter; emit tokenizer.json. |
| src/mobius/integrations/onnx_genai/auto_export_test.py | Tests covering new dispatch cases + tokenizer emission behavior. |
| src/mobius/integrations/onnx_genai/init.py | Export surface updates for onnx-genai integration module. |
| src/mobius/integrations/gguf/_tokenizer.py | Best-effort tokenizer.json emission from GGUF (via transformers or ggml metadata reconstruction). |
| src/mobius/integrations/gguf/_tokenizer_test.py | Tests for GGUF tokenizer emission + onnx-genai config emission for GGUF builds. |
| src/mobius/integrations/gguf/_tensor_mapping.py | Add Gemma3-specific GGUF tensor-name mapping adjustments. |
| src/mobius/integrations/gguf/_tensor_mapping_test.py | Unit tests validating Gemma3 GGUF tensor-name mapping. |
| src/mobius/integrations/gguf/_reader.py | Fix string-array parsing off-by-one for GGUF metadata arrays. |
| src/mobius/integrations/gguf/_mmproj.py | Build Gemma4 multimodal package from text GGUF + clip mmproj GGUF (vision/audio config extraction). |
| src/mobius/integrations/gguf/_mmproj_test.py | Synthetic mmproj GGUF generation + vision encoder build/run and mixed-precision assertions. |
| src/mobius/integrations/gguf/_mmproj_mapping.py | Map clip-mmproj tensor names to Gemma4 HF names; skip activation-range stat tensors. |
| src/mobius/integrations/gguf/_mmproj_mapping_test.py | Unit tests for mmproj name mapping and stat-tensor detection. |
| src/mobius/integrations/gguf/_config_mapping.py | Add Gemma4 per-layer FFN postprocess + Gemma3 postprocess defaults for omitted fields. |
| src/mobius/integrations/gguf/_config_mapping_test.py | Unit tests for Gemma3/Gemma4 GGUF config postprocessing behaviors. |
| src/mobius/integrations/gguf/_builder.py | Expose single-tensor repack helper for quantized GGUF loading paths. |
| src/mobius/integrations/gguf/init.py | Export new GGUF helpers (mmproj build, tokenizer.json emission). |
| src/mobius/_configs/_base.py | Accept rope_scaling["interleaved"] alias for MRoPE interleaving. |
| src/mobius/_configs_test.py | Tests for the new MRoPE interleaved alias behavior. |
| src/mobius/_config_resolver.py | Preserve raw rope_scaling/rope_parameters when HF nested-config standardization drops non-standard fields. |
| src/mobius/main.py | build-gguf CLI: add --mmproj multimodal build and --runtime onnx-genai emission path. |
| def _looks_like_multi_decoder_tts(pkg: Any) -> bool: | ||
| """Detect a nested multi-decoder TTS package (e.g. Qwen3-TTS). | ||
|
|
||
| The defining signal is a ``talker`` plus a ``code_predictor`` decoder — a | ||
| dual, nested autoregressive shape (the code_predictor expands each talker | ||
| frame's residual codebooks). This shape is designed but not yet executable by | ||
| the onnx-genai composite runtime (see DESIGN.md §20.3), so it is detected | ||
| only to raise a precise, actionable error rather than mis-emitting. | ||
| """ |
| "build_diffusion_pipeline_metadata", | ||
| "build_language_diffusion_pipeline_metadata", | ||
| "build_audio_codec_pipeline_metadata", | ||
| "build_multimodal_pipeline_metadata", |
|
|
||
| __all__ = [ | ||
| "build_from_gguf", | ||
| "build_gemma4_vlm_from_gguf", |
There was a problem hiding this comment.
Should this just keep build_from_gguf? Or maybe add a separate mmproj handler?
There was a problem hiding this comment.
Unified it: build_from_gguf now takes an optional mmproj= param and delegates to the multimodal VLM builder when set, so there's a single public entry point for both text-only and multimodal GGUF builds. The CLI (build-gguf --mmproj) uses it. build_gemma4_vlm_from_gguf stays available for direct use. Done in 49da572.
| ) | ||
| gguf_parser.add_argument( | ||
| "--runtime", | ||
| choices=["onnx-genai"], |
There was a problem hiding this comment.
Added — build-gguf --runtime now offers {ort-genai, onnx-genai} (matching the main build command). The save path already handled ort-genai; only the argparse choices had omitted it. Done in 49da572.
…nent Materialize the talker PREFILL + trailing-text embedding construction into ONNX so the runtime can drive real Qwen3-TTS audio without TTS-specific slicing/interleaving logic. The new talker_prefill_embedder component takes already-tokenized text_ids and emits prefill_embeds (role + codec_text_pairs + first_text_codec) and trailing_text_embeds (remaining text + tts_eos), exactly matching generate_codes for the default path (language=Auto, no speaker, no instruct). It reuses the embedding model's text + codec tables (shared weights, routed in preprocess_weights) and does the Slice/Concat/Add/Tile interleaving in-graph. Wired into TTSTask as a fifth package model. Validated against generate_codes's in-function values on the real 1.7B model (prefill/trailing maxdiff ~1e-7). Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
… + trailing-text) The onnx-genai engine now consumes a `prefill_embedder`: a prompt-phase `talker_prefill_embedder` (text_ids -> prefill_embeds + trailing_text_embeds) whose outputs seed the talker on frame 0 and thread the per-frame text_embed. build_tts_pipeline_metadata now emits `talker_prefill_embedder` (prompt_only) + the `prefill_embedder` strategy field when the package carries it; the dispatcher includes it only when present (else the prefill-less shape). Validated against the regenerated onnx-genai JSON schema. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
| # 2. Build the multimodal graph (decoder + vision + embedding [+ audio]). | ||
| module = Gemma4Model(config) | ||
| pkg = Gemma4Task().build(module, config) | ||
| logger.info("Built Gemma4 VLM graph (%d components: %s)", len(pkg), list(pkg)) |
| dataflow.append( | ||
| { | ||
| "from": f"{name}.{output_name}", | ||
| "to": f"embedding.{output_name}", | ||
| "dtype": "fp32", | ||
| "device_transfer": False, | ||
| } | ||
| ) |
| "dataflow": [ | ||
| { | ||
| "from": "encoder.encoder_hidden_states", | ||
| "to": "decoder.encoder_hidden_states", | ||
| "dtype": "fp32", | ||
| "device_transfer": False, | ||
| } |
| "dataflow": [ | ||
| { | ||
| "from": "talker_step_embedder.inputs_embeds", | ||
| "to": "talker.inputs_embeds", | ||
| "dtype": "fp32", | ||
| "device_transfer": False, | ||
| }, | ||
| { | ||
| "from": "talker.last_hidden_state", | ||
| "to": "code_predictor.inputs_embeds", | ||
| "dtype": "fp32", | ||
| "device_transfer": False, | ||
| }, |
| def __init__(self, config: ArchitectureConfig): | ||
| super().__init__() | ||
| tts = config.tts | ||
| text_hidden = tts.text_hidden_size if tts else 2048 | ||
| text_vocab = tts.text_vocab_size if tts else 151936 | ||
| hidden = config.hidden_size | ||
|
|
||
| # Same tables as the embedding model (shared weights, routed in | ||
| # preprocess_weights). Text embedding + ResizeMLP projection. | ||
| self.text_embedding = Embedding(text_vocab, text_hidden) | ||
| self.text_projection_fc1 = Linear(text_hidden, text_hidden, bias=True) | ||
| self.text_projection_fc2 = Linear(text_hidden, hidden, bias=True) | ||
| # Codec embedding (audio codes → hidden). | ||
| self.codec_embedding = Embedding(config.vocab_size, hidden) | ||
|
|
| if _text_lm_head_quantized(config): | ||
| return _text_linear_class(config)(config.hidden_size, config.vocab_size, bias=False) | ||
| return Linear(config.hidden_size, config.vocab_size, bias=False) |
| # Capture the raw rope fields before conversion: constructing a | ||
| # nested PretrainedConfig runs HF rope standardization, which | ||
| # silently drops non-standard rope_scaling formats (e.g. the | ||
| # Qwen3-TTS talker's ``{"interleaved": True, "mrope_section": ..., | ||
| # "type": "default"}``). Restore them onto the converted config so | ||
| # _extract_mrope_fields / _extract_rope_config can still read them. | ||
| raw_rope = {k: val[k] for k in rope_keys if k in val} | ||
| nested = _dict_to_pretrained_config(val) | ||
| for k, v in raw_rope.items(): | ||
| if getattr(nested, k, None) is None: | ||
| setattr(nested, k, v) | ||
| setattr(config, key, nested) |
…pecs (explicit ports)
The engine no longer guesses TTS graph ports by name/dtype. Emit the structured
pre_embedder {component, frame_codes_input, text_embed_input} and prefill_embedder
{component, prompt_input, prefill_output, trailing_output} specs so every port is
declared in metadata. Validated against the regenerated onnx-genai JSON schema.
Co-authored-by: Copilot <[email protected]>
Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 26 out of 26 changed files in this pull request and generated 1 comment.
Comments suppressed due to low confidence (4)
src/mobius/integrations/onnx_genai/inference_metadata.py:401
- The pipeline dataflow hard-codes
dtype: "fp32"for encoder→embedding transfers, but Mobius packages can be built in fp16/bf16 and the shared tensor pool dtype needs to match the actual ONNX tensor element types. As-is, an fp16 multimodal package would still emit fp32 dataflow, which can cause incorrect buffer binding or unnecessary casts in the onnx-genai runtime.
dataflow.append(
{
"from": f"{name}.{output_name}",
"to": f"embedding.{output_name}",
"dtype": "fp32",
"device_transfer": False,
}
src/mobius/integrations/onnx_genai/inference_metadata.py:528
- The ASR encoder→decoder cross-attention edge is emitted with
dtype: "fp32"unconditionally. For fp16/bf16 speech-to-text packages, this metadata will not match the actualencoder_hidden_statestensor type and may cause runtime binding/cast issues.
"from": "encoder.encoder_hidden_states",
"to": "decoder.encoder_hidden_states",
"dtype": "fp32",
"device_transfer": False,
}
src/mobius/integrations/onnx_genai/inference_metadata.py:723
- TTS dataflow edges are emitted with
dtype: "fp32", but the talker_step_embedder output and talker/code_predictor inputs will be fp16/bf16 when the package is built in reduced precision. The metadata should match the actual tensor element type exchanged between components.
"from": "talker_step_embedder.inputs_embeds",
"to": "talker.inputs_embeds",
"dtype": "fp32",
"device_transfer": False,
},
src/mobius/integrations/onnx_genai/inference_metadata.py:729
- The talker→code_predictor seed edge is also hard-coded as
dtype: "fp32"; for fp16/bf16 builds this will diverge from the actuallast_hidden_statetype. Both TTS dataflow edges should use the package’s activation dtype.
"from": "talker.last_hidden_state",
"to": "code_predictor.inputs_embeds",
"dtype": "fp32",
"device_transfer": False,
},
| dataflow.append( | ||
| { | ||
| "from": "embedding.inputs_embeds", | ||
| "to": "decoder.inputs_embeds", | ||
| "dtype": "fp32", | ||
| "device_transfer": False, | ||
| } |
…I Lint) Formatting-only (line-wrapping) to satisfy the RUFF-FORMAT lint check; no behavior change. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
| # Text side of codec prefill: tts_pad * (N-2) ++ tts_bos. | ||
| text_pad_rep = op.Tile( | ||
| tts_pad, op.Constant(value_ints=[1, num_prefill - 2, 1]) | ||
| ) # (1, N-2, H) | ||
| text_side = op.Concat(text_pad_rep, tts_bos, axis=1) # (1, N-1, H) | ||
| codec_side = op.Slice(codec_prefill, [0], [num_prefill - 1], [1]) # (1, N-1, H) | ||
| codec_text_pairs = op.Add(text_side, codec_side) # (1, N-1, H) | ||
|
|
||
| # First text token + last codec token (bos). | ||
| first_text = op.Slice(all_text_embeds, [3], [4], [1]) # (B, 1, H) | ||
| codec_bos = op.Slice(codec_prefill, [num_prefill - 1], [num_prefill], [1]) # (1, 1, H) | ||
| first_text_codec = op.Add(first_text, codec_bos) # (B, 1, H) | ||
|
|
||
| prefill_embeds = op.Concat( | ||
| role, codec_text_pairs, first_text_codec, axis=1 | ||
| ) # (B, 8, H) | ||
|
|
||
| # Trailing text: remaining tokens [4:-5] ++ tts_eos. | ||
| remaining_text = op.Slice(all_text_embeds, [4], [-5], [1]) # (B, L-9, H) | ||
| trailing_text_embeds = op.Concat(remaining_text, tts_eos, axis=1) # (B, L-8, H) |
| def _looks_like_multimodal(pkg: Any) -> bool: | ||
| try: | ||
| names = set(pkg.keys()) | ||
| except AttributeError: | ||
| return False | ||
| return "decoder" in names and bool(names & {"vision_encoder", "audio_encoder"}) |
| for text_len in (10, 14, 20): | ||
| text_ids = rng.integers(0, 1000, size=(1, text_len)).astype(np.int64) | ||
| exp_prefill, exp_trailing = _numpy_prefill_reference(weights, text_ids) | ||
|
|
||
| out = session.run({"text_ids": text_ids}) | ||
| got_prefill = out["prefill_embeds"] | ||
| got_trailing = out["trailing_text_embeds"] | ||
|
|
||
| # prefill_len is constant: 3 (role) + 4 (N-1 pairs) + 1 (first_text_codec) | ||
| assert got_prefill.shape == (1, 8, _HIDDEN) | ||
| # trailing_len = (text_len - 9) + 1 = text_len - 8 | ||
| assert got_trailing.shape == (1, text_len - 8, _HIDDEN) |
…tion) - qwen3_tts prefill embedder: broadcast the batch=1 codec/special pieces to the dynamic batch B before Concat, fixing a batch-dim mismatch for B>1; add a batched test. - Validate the prefill embedder's fixed special-token/codec ids fit the vocab. - onnx_genai composite emitters (multimodal/ASR/TTS): derive the dataflow edge dtype from the model's activation dtype instead of hardcoding fp32, so fp16/bf16 builds are described correctly. - _looks_like_multimodal now also requires the `embedding` fusion component, so we never emit multimodal metadata referencing a missing embedding model. - gguf mmproj VLM build routes through build_from_module so components get the EP-aware optimize_model passes (matching the text-only build_from_gguf path). - gemma4 _make_lm_head guards the `type | None` linear class. - _config_resolver restores raw nested rope_scaling whenever HF standardization dropped OR rewrote it (not only when None). Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
|
Addressed the review comments in Second review round (fixed now):
First round (already fixed earlier in this PR): empty-except → explicit return; |
| stacked = torch.stack([codec_emb_weights[i] for i in range(num_groups)]) | ||
| remaining["code_predictor.stacked_codec_embedding"] = stacked | ||
| remaining["codec_embeddings"] = stacked | ||
| # Share the same stacked table with the talker step embedder so it | ||
| # can materialize codec_sum in-graph (Σ cp_codec_weights[i][code]). | ||
| remaining["talker_step_embedder.stacked_codec_embedding"] = stacked |
There was a problem hiding this comment.
Reasonable — done in 4ae2e0b. The stacked codec table is now keyed under both codec_embeddings (Identity-folded case) and code_predictor.stacked_codec_embedding (unfolded case). apply_weights populates whichever initializer the build actually emits and only logs the other as unmapped (it doesn't error on extra keys), so the table is applied robustly without depending on the IR fold.
…dder The prefill embedder bakes fixed TTS special-token / codec ids as Gather indices; the table must contain them at run time. A hard ValueError broke tiny structural-build tests (text_vocab=256), where the graph builds fine and the OOB gather is never executed. Downgrade to a logger.warning so real misconfigurations are surfaced without failing legitimate structural builds. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
Per review: don't depend on onnx-ir folding op.Identity(stacked_codec_embedding) and renaming the initializer to `codec_embeddings`. Key the stacked table under BOTH `codec_embeddings` (folded case) and `code_predictor.stacked_codec_embedding` (unfolded case); apply_weights populates whichever initializer exists and only logs the other as unmapped (no error on extra keys), so the table is applied robustly regardless of IR rewrite behavior. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
| if getattr(config, "rope_local_base_freq", None) is None: | ||
| local_freq_base = metadata.get("gemma3.rope.local_freq_base") or metadata.get( | ||
| "gemma3.rope.freq_base_local" | ||
| ) | ||
| config.rope_local_base_freq = ( | ||
| float(local_freq_base) | ||
| if local_freq_base is not None | ||
| else _GEMMA3_DEFAULT_ROPE_LOCAL_BASE_FREQ | ||
| ) | ||
| if getattr(config, "layer_types", None) is None: | ||
| pattern = ( | ||
| metadata.get("gemma3.attention.sliding_window_pattern") | ||
| or _GEMMA3_DEFAULT_SLIDING_WINDOW_PATTERN | ||
| ) | ||
| config.layer_types = [ | ||
| "full_attention" if (index + 1) % pattern == 0 else "sliding_attention" | ||
| for index in range(config.num_hidden_layers) | ||
| ] | ||
| return config |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 26 out of 26 changed files in this pull request and generated 2 comments.
Comments suppressed due to low confidence (2)
src/mobius/integrations/onnx_genai/auto_export.py:383
- The dispatch docstring table doesn’t list the multi-decoder TTS shape, but
write_onnx_genai_confignow has an explicit_looks_like_multi_decoder_ttsbranch that emitsnested_autoregressivemetadata. The table should include TTS to reflect the actual supported shapes and emitted strategy.
Diffusion denoiser / VAE present ``iterative``
Audio codec encoder→``codes``→decoder, no cross-attn ``composite`` (two single_pass)
Multimodal VLM decoder + vision/audio encoder + fusion ``composite`` (encoders→fuse→AR)
Speech-to-text (ASR) decoder consumes ``encoder_hidden_states`` ``composite`` (encode→AR)
Decoder LM fallback (a config is required) bare decoder (``kv_cache`` + attn)
src/mobius/integrations/onnx_genai/inference_metadata.py:8
- The module docstring now says it emits metadata for “multi-model pipelines”, but the following paragraphs still describe diffusion-only semantics (denoiser/VAE/scheduler loop). This is misleading now that the module contains multimodal/ASR/codec/TTS pipeline emitters.
Consider rewriting the docstring intro to describe the full scope (diffusion + composite pipelines) and keep diffusion-specific details closer to build_diffusion_pipeline_metadata.
"""Emit onnx-genai ``inference_metadata`` for multi-model pipelines.
Mobius builds the neural components of a diffusion model (denoiser transformer,
VAE, and — externally — a text encoder) as separate ONNX graphs, but does not
itself carry a scheduler loop. onnx-genai's *iterative* pipeline supplies that
| raise ValueError( | ||
| "onnx-genai config emission does not recognize this multi-component " | ||
| f"package shape (components: {component_names}). Supported composite " | ||
| "shapes: diffusion, audio codec, multimodal VLM, speech-to-text. " | ||
| "Multi-decoder pipelines such as TTS require a dedicated emitter." | ||
| ) |
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT License. | ||
|
|
||
| """Tests for the Qwen3-TTS talker step embedder pre-embedding component.""" |
Summary
Adds model-builder + metadata-emitter support for any-to-any onnx-genai pipelines, pairing with the onnx-genai
feat/any-to-any-pipelinePR (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/)tokenizer.jsonfor decoder/VLM/ASR builds.build_tts_pipeline_metadata: emits thepre_embedder-drivennested_autoregressivecontract 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.write_onnx_genai_config(fails loudly on unknown shapes).GGUF integration (
src/mobius/integrations/gguf/)build-gguf --runtime onnx-genaiemitsinference_metadata+tokenizer.json.tokenizer.jsonfor 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_embedderpre-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).codec_embeddingsinitializer; preserve the talker's non-standard interleaved-MRoPErope_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-CustomVoicepackage + the committed JSON schema.Co-authored-by: Copilot [email protected]