Skip to content

Emit native onnx-genai metadata for VLM packages - #416

Merged
justinchuby merged 5 commits into
mainfrom
vlm-wp1-emission
Jul 22, 2026
Merged

justinchuby merged 5 commits into
mainfrom
vlm-wp1-emission

Conversation

@justinchuby

Copy link
Copy Markdown
Member

Summary

  • emit native VLM pipeline metadata from ModelPackage graph I/O and component topology
  • select typed image processor programs through a structural rank/dtype registry (no model_type or architecture-name dispatch)
  • declare every component port, every-step embedding routes, sparse KV/fixed state pairs, expansion, and multi-axis positions
  • copy tokenizer, chat-template, and processor assets for self-contained packages

Validation

  • python3 -m pytest src/mobius/integrations/onnx_genai/inference_metadata_test.py tests/cli_test.py -x -q (54 passed)
  • Ruff check/format on changed files
  • no-weight Gemma4 E2B, Qwen3-VL-2B-Instruct, and Phi-4-multimodal builds validated against onnx-genai schema with exact ONNX port lists

Implements onnx-genai VLM WP1.

Copilot AI review requested due to automatic review settings July 22, 2026 03:01
@github-actions

github-actions Bot commented Jul 22, 2026 •

Copy link
Copy Markdown

🏗️ Architecture Diff

Comparing f56db25 → ee07a8b

Model Sub-model Changes Status

No architecture changes detected. ✅


Legend: ⚪ No change · 🔵 Minor (attrs/inits) · 🟡 Moderate (nodes added/removed) · 🔴 Major (interface changed)

@github-actions

github-actions Bot commented Jul 22, 2026 •

Copy link
Copy Markdown

Performance Comparison

Comparing f56db25 → ee07a8b

Model Metric Baseline Current Delta
bert (feature-extraction) model_size_bytes 359 KB 359 KB +0.0% ⚪
bert (feature-extraction) num_nodes 60 60 +0.0% ⚪
falcon model_size_bytes 364 KB 364 KB +0.0% ⚪
falcon num_nodes 68 68 +0.0% ⚪
gemma2 model_size_bytes 428 KB 428 KB +0.0% ⚪
gemma2 num_nodes 107 107 +0.0% ⚪
gpt2 model_size_bytes 388 KB 388 KB +0.0% ⚪
gpt2 num_nodes 54 54 +0.0% ⚪
llama model_size_bytes 425 KB 425 KB +0.0% ⚪
llama num_nodes 62 62 +0.0% ⚪
llama (static-cache) model_size_bytes 425 KB 425 KB +0.0% ⚪
llama (static-cache) num_nodes 58 58 +0.0% ⚪
mamba (ssm-text-generation) model_size_bytes 296 KB 296 KB +0.0% ⚪
mamba (ssm-text-generation) num_nodes 98 98 +0.0% ⚪
phi3 model_size_bytes 421 KB 421 KB +0.0% ⚪
phi3 num_nodes 60 60 +0.0% ⚪
phi3 (static-cache) model_size_bytes 421 KB 421 KB +0.0% ⚪
phi3 (static-cache) num_nodes 56 56 +0.0% ⚪
qwen2 model_size_bytes 425 KB 425 KB +0.0% ⚪
qwen2 num_nodes 62 62 +0.0% ⚪
qwen2 (static-cache) model_size_bytes 425 KB 425 KB +0.0% ⚪
qwen2 (static-cache) num_nodes 58 58 +0.0% ⚪
qwen3_5_moe (hybrid-text-generation) model_size_bytes 506 KB 506 KB +0.0% ⚪
qwen3_5_moe (hybrid-text-generation) num_nodes 275 275 +0.0% ⚪
qwen3_5_text (hybrid-text-generation) model_size_bytes 458 KB 458 KB +0.0% ⚪
qwen3_5_text (hybrid-text-generation) num_nodes 129 129 +0.0% ⚪
qwen3_5_vl (hybrid-qwen-vl) model_size_bytes 977 KB 977 KB +0.0% ⚪
qwen3_5_vl (hybrid-qwen-vl) num_nodes 413 413 +0.0% ⚪
t5 (seq2seq) model_size_bytes 836 KB 836 KB +0.0% ⚪
t5 (seq2seq) num_nodes 166 166 +0.0% ⚪
whisper (speech-to-text) model_size_bytes 1008 KB 1008 KB +0.0% ⚪
whisper (speech-to-text) num_nodes 128 128 +0.0% ⚪

No performance regressions.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds a “native VLM” metadata emitter for onnx-genai packages by inspecting ModelPackage component graphs (ports + topology) rather than dispatching on model_type, and wires the CLI to prefer this native emitter when a package matches the expected VLM structure.

Changes:

  • Add a structural image-processor registry and native VLM inference_metadata.yaml emitter derived from component I/O signatures and inferred dataflow.
  • Copy tokenizer/chat-template/processor assets into the output directory to make exported VLM packages self-contained.
  • Update the CLI --runtime onnx-genai path (and tests) to use the native VLM emitter when applicable.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.

File Description
tests/cli_test.py Adds coverage that the CLI uses the native VLM metadata writer (and not the generic writer) when is_native_vlm_package() is true.
src/mobius/main.py Routes --runtime onnx-genai exports through the native VLM emitter when the package structure matches.
src/mobius/integrations/onnx_genai/inference_metadata.py Implements native VLM metadata emission, image-input signature registry, and runtime asset copying.
src/mobius/integrations/onnx_genai/inference_metadata_test.py Adds schema-validation tests for native VLM metadata and asset copying behavior.

Comment on lines 37 to +41
os.path.join(
os.path.dirname(__file__),
"../../../../../onnx-genai/schema/inference_metadata.schema.json",
),
"/home/justinchu/onnx-genai/schema/inference_metadata.schema.json",
Comment on lines +748 to +752
return {
Path(filename).stem: os.path.join(output_dir, filename)
for filename in _RUNTIME_ASSET_NAMES
if os.path.isfile(os.path.join(output_dir, filename))
}
Copilot AI review requested due to automatic review settings July 22, 2026 04:35

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

Comments suppressed due to low confidence (1)

src/mobius/integrations/onnx_genai/inference_metadata_test.py:45

  • The schema-path candidate list includes a developer-specific absolute path ("/home/justinchu/..."), which makes the test non-hermetic and will never exist for other contributors or CI runners. Keep lookup to the env var + repo-relative path (and optionally a generic home-dir fallback), but avoid hard-coded user paths.
            "../../../../../onnx-genai/schema/inference_metadata.schema.json",
        ),
        "/home/justinchu/onnx-genai/schema/inference_metadata.schema.json",
        os.path.expanduser(
            "~/Documents/GitHub/onnx-genai/schema/inference_metadata.schema.json"

Comment on lines +799 to +803
try:
names = set(pkg)
except (AttributeError, TypeError):
return False
return "vision_encoder" in names
justinchuby added a commit that referenced this pull request Jul 22, 2026
Target the extended onnx-genai ImageTransform contract for Qwen temporal packing, Gemma patch-budget padding, and Phi dynamic-HD masks, and make incomplete packages fail actionably. Updates draft PR #416.

Co-authored-by: Copilot <[email protected]>
Copilot AI review requested due to automatic review settings July 22, 2026 06:42

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.

Comments suppressed due to low confidence (2)

src/mobius/integrations/onnx_genai/inference_metadata_test.py:43

  • The schema search candidates include a hard-coded developer-specific absolute path ("/home/justinchu/..."), which makes the test suite non-portable and leaks a local environment detail into the repo. Prefer a generic user-relative location (or rely on ONNX_GENAI_SCHEMA).
        "/home/justinchu/onnx-genai/schema/inference_metadata.schema.json",

src/mobius/integrations/onnx_genai/inference_metadata.py:1042

  • _copy_runtime_assets() returns a dict keyed by Path(filename).stem, but some asset names share the same stem (e.g. tokenizer.json and tokenizer.model → "tokenizer"). This silently drops one entry in the returned mapping and makes CLI output/artifact consumers ambiguous. Key by the full filename (or otherwise make keys unique).
    return {
        Path(filename).stem: os.path.join(output_dir, filename)
        for filename in _RUNTIME_ASSET_NAMES
        if os.path.isfile(os.path.join(output_dir, filename))
    }

Comment on lines +851 to +866
model_id = "google/gemma-4-E2B-it-assistant"
cached_config = next(
(
str(file.file_path)
for repo in scan_cache_dir().repos
if repo.repo_id == model_id
for revision in repo.revisions
for file in revision.files
if file.file_name == "config.json"
),
None,
)
assert cached_config is not None, "cached Gemma4 assistant config.json unavailable"
assert json.loads(Path(cached_config).read_text(encoding="utf-8"))["model_type"] == (
"gemma4_assistant"
)
Comment on lines +872 to +875
processor_path = max(
processor_cache.glob("*/processor_config.json"),
key=lambda path: path.stat().st_mtime,
)
Copilot AI review requested due to automatic review settings July 22, 2026 06:46

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 4 out of 4 changed files in this pull request and generated no new comments.

Comments suppressed due to low confidence (2)

src/mobius/integrations/onnx_genai/inference_metadata.py:1042

  • The artifacts dict returned here keys runtime assets by Path(filename).stem, which causes key collisions (e.g., tokenizer.json and tokenizer.model both become tokenizer). That can overwrite the tokenizer.json path and diverges from write_onnx_genai_config() which returns tokenizer for tokenizer.json. Return unique keys (at least keep tokenizer pointing to tokenizer.json and use a separate key for tokenizer.model).
    return {
        Path(filename).stem: os.path.join(output_dir, filename)
        for filename in _RUNTIME_ASSET_NAMES
        if os.path.isfile(os.path.join(output_dir, filename))
    }

src/mobius/integrations/onnx_genai/inference_metadata_test.py:43

  • This candidate path is hard-coded to a specific developer machine/user (/home/justinchu/...) and is unlikely to exist in CI or for other contributors. Prefer environment-variable configuration (already supported via ONNX_GENAI_SCHEMA) and/or a generic ~-relative fallback instead of an absolute per-user path.
        "/home/justinchu/onnx-genai/schema/inference_metadata.schema.json",

Copilot AI review requested due to automatic review settings July 22, 2026 08:01

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 4 out of 4 changed files in this pull request and generated no new comments.

Comments suppressed due to low confidence (2)

src/mobius/integrations/onnx_genai/inference_metadata.py:1044

  • _copy_runtime_assets() returns a dict keyed by Path(filename).stem, but _RUNTIME_ASSET_NAMES includes both tokenizer.json and tokenizer.model, which share the same stem "tokenizer". This causes a key collision and the later entry overwrites the former, so callers may lose the tokenizer.json artifact path.
    return {
        Path(filename).stem: os.path.join(output_dir, filename)
        for filename in _RUNTIME_ASSET_NAMES
        if os.path.isfile(os.path.join(output_dir, filename))
    }

src/mobius/integrations/onnx_genai/inference_metadata_test.py:47

  • _onnx_genai_schema_path() includes a hard-coded developer-specific absolute path ("/home/justinchu/..."), which is unlikely to exist for other contributors/CI and reduces portability. The environment variable + repo-relative + user-home candidates already cover the intended use cases.
    candidates = [
        os.environ.get("ONNX_GENAI_SCHEMA"),
        os.path.join(
            os.path.dirname(__file__),
            "../../../../../onnx-genai/schema/inference_metadata.schema.json",
        ),
        "/home/justinchu/onnx-genai/schema/inference_metadata.schema.json",
        os.path.expanduser(
            "~/Documents/GitHub/onnx-genai/schema/inference_metadata.schema.json"
        ),
    ]

justinchuby and others added 5 commits July 22, 2026 09:23
Target the extended onnx-genai ImageTransform contract for Qwen temporal packing, Gemma patch-budget padding, and Phi dynamic-HD masks, and make incomplete packages fail actionably. Updates draft PR #416.

Co-authored-by: Copilot <[email protected]>
Fail instead of skipping when required Qwen or Phi cached processors are missing, keeping WP1 coverage honest alongside the cached Gemma assertion.

Co-authored-by: Copilot <[email protected]>
- _validate: pytest.skip instead of hard assert when onnx-genai schema not co-located (consistent with sibling schema tests) — unblocks mobius CI where onnx-genai isn't checked out.
- cached Qwen/Phi4MM processor tests: pytest.skip instead of pytest.fail on offline LocalEntryNotFoundError/OSError, so CI (no network) skips while local dev with warm HF cache still runs parity checks.
- ruff format.

Co-authored-by: Copilot <[email protected]>
Copilot AI review requested due to automatic review settings July 22, 2026 09:24

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

Comments suppressed due to low confidence (2)

src/mobius/integrations/onnx_genai/inference_metadata.py:1044

  • _copy_runtime_assets() returns its artifacts dict keyed by Path(filename).stem, which collides for files like tokenizer.json and tokenizer.model (both stem to "tokenizer"). This silently overwrites entries and can cause callers to miss copied assets.
    return {
        Path(filename).stem: os.path.join(output_dir, filename)
        for filename in _RUNTIME_ASSET_NAMES
        if os.path.isfile(os.path.join(output_dir, filename))
    }

src/mobius/integrations/onnx_genai/inference_metadata_test.py:46

  • _onnx_genai_schema_path() includes a hard-coded developer-specific absolute path ("/home/justinchu/..."), which is not portable and can cause confusing behavior on other machines. Prefer only the env var and repo-relative candidate(s).
    candidates = [
        os.environ.get("ONNX_GENAI_SCHEMA"),
        os.path.join(
            os.path.dirname(__file__),
            "../../../../../onnx-genai/schema/inference_metadata.schema.json",
        ),
        "/home/justinchu/onnx-genai/schema/inference_metadata.schema.json",
        os.path.expanduser(
            "~/Documents/GitHub/onnx-genai/schema/inference_metadata.schema.json"
        ),

Comment on lines +83 to +85
model = ir.Model(graph, ir_version=10)
assert ir.to_proto(model).graph.name == name
return model
@justinchuby
justinchuby marked this pull request as ready for review July 22, 2026 09:42
@justinchuby
justinchuby requested a review from a team July 22, 2026 09:42
@justinchuby
justinchuby merged commit 00c8fac into main Jul 22, 2026
22 of 23 checks passed
@justinchuby
justinchuby deleted the vlm-wp1-emission branch July 22, 2026 09:42
@codecov

codecov Bot commented Jul 22, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 70.65073% with 221 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...integrations/onnx_genai/inference_metadata_test.py 56.50% 126 Missing and 1 partial ⚠️
...bius/integrations/onnx_genai/inference_metadata.py 79.73% 59 Missing and 33 partials ⚠️
src/mobius/__main__.py 71.42% 1 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

justinchuby added a commit that referenced this pull request Aug 23, 2026
…nce, Gemma4 cache skip) (#553)

Two unrelated, long-standing failures on `main`. Both turned out to be
defects in the *tests*, not in the product. Suite goes from **8 failed /
4613 passed** to **6 failed / 4621 passed**; the remaining 6 are the
onnx-genai schema-drift failures being fixed in a separate PR.

## Failure 1 —
`qwen_image_test.py::test_deterministic_l4_l5_image_edit_golden`

**Root cause: float32 noise floor, not a numerical regression.**

The failing assertion compares a *pure* PyTorch/diffusers chain against
golden values recorded in #465 on a different BLAS backend — no ONNX
involved — at `rtol=atol=1e-6`.

Evidence gathered before changing anything:

- The divergence is **stable and deterministic**: identical value under
`OMP_NUM_THREADS=1` and `=4`, and byte-identical across runs. Not flaky.
- It is a **single isolated element** moving in the last decimal place
(1.5196e-6), not a broad shift — a logic bug would move many values or
move one a lot.
- Magnitude analysis: these tensors peak near `|x| ≈ 3.3`, where one
float32 ULP is ≈ 2.4e-7. So `atol=1e-6` was only ~4 ULP of headroom for
a chain of one transformer layer + three scheduler steps + a VAE decode.
The observed drift is ~6 ULP.
- The *sibling* golden comparisons in the same test already sit at
6.3e-7 and 5.8e-7 against the same 1e-6 bound — i.e. the whole test was
riding the float32 noise floor and would have tipped over on the next
platform change regardless.

**Fix:** a principled, commented bound of `rtol=1e-5 / atol=5e-6` (~20
ULP at the peak magnitude, ~3x the observed drift) applied to the three
golden comparisons via a shared named constant. That is still two orders
of magnitude tighter than the `1e-4` this same test uses for
ONNX-vs-torch parity, so a genuine logic regression still fails. The
ONNX-vs-reference assertions are untouched.

**On the `Weight '...' not found in the model. Skipped applying.`
warnings** — these are **expected, not a second bug**. The test applies
the *full* VAE state dict to both halves of the split encoder/decoder
package (`apply_weights(vae_package["encoder"], vae_weights)` and again
for `"decoder"`), so each half warns about the other's weights. Verified
by counting: 90 skip warnings, and **no weight name is skipped twice** —
every weight lands in exactly one of the two models, including
`quant_conv` (encoder side) and `post_quant_conv` (decoder side). Noisy,
but correct. No follow-up needed.

## Failure 2 —
`inference_metadata_test.py::TestNativeVlmPackageMetadata::test_cached_gemma_processor_matches_emitted_patch_budget`

**Root cause: a hard assert on optional local Hugging Face cache
state.**

The test reads two artifacts *straight out of the local HF cache*
(deliberately offline-style, like its siblings), but handled absence
badly in both places:

1. `assert cached_config is not None` on
`google/gemma-4-E2B-it-assistant/config.json` — hard failure when
uncached. This value is never used again; it is only a sanity
cross-check that the assistant variant reports `model_type ==
"gemma4_assistant"`.
2. `max(processor_cache.glob("*/processor_config.json"), ...)` on
`google/gemma-4-E2B-it` — would raise `ValueError: max() arg is an empty
sequence` if uncached. This is the artifact the test actually needs.

Neither repo is fetched by the test or vendored; they just happened to
be in the author's cache at #416. Both exist on the Hub, so this is
genuinely environmental/optional, matching how
`_onnx_genai_schema_path()`, the Qwen test and the Phi test in this same
file already `pytest.skip`.

**Fix (surgical, confined to the cache lookup to minimise conflict with
the schema PR):**
- The assistant `config.json` cross-check becomes conditional — **still
asserted when the repo is cached**, skipped as a check when it is not.
- Missing processor config now `pytest.skip`s with an explicit reason
instead of crashing.

**Verified it does not degrade into a silent skip:** I fetched both
artifacts into the cache and re-ran — the test **runs and passes**,
exercising all original assertions including the `model_type`
cross-check and the `(1, 2520, 768)` / `252` patch-budget parity.
Without them it skips cleanly.

## Verification

```
python -m pytest tests/build_graph_test.py tests/cli_test.py src/ -q \
  -k "not phi4mm and not apply_weights_unknown" -n auto
```

| | before | after |
|---|---|---|
| failed | 8 | 6 |
| passed | 4613 | 4621 |

Remaining 6 are exactly the out-of-scope
`jsonschema.exceptions.ValidationError` failures in `comfyui_test.py` /
`inference_metadata_test.py`. No new failures.

`lintrunner f --output oneline --all-files` then `lintrunner` → `ok No
lint issues.` Commit is signed off.

---------

Signed-off-by: Justin Chu <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants