Repository navigation
Add Qwen Image Edit 2509 pipeline support - #465
Conversation
Performance Comparison
|
🏗️ 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 support for the Qwen/Qwen-Image-Edit-2509 diffusers pipeline in mobius, including model/task wiring for prompt encoding + denoising + edit-VAE, plus onnx-genai export metadata so the runtime can reproduce the pipeline’s non-neural contract (latent packing, RoPE inputs, scheduler shifting, etc.).
Changes:
- Introduces Qwen Image Edit–specific tasks (prompt text-encoder split, packed-token denoiser, normalized-latent VAE) and updates Qwen Image/Qwen VL model codepaths to match diffusers behavior.
- Extends diffusers pipeline building and onnx-genai auto-export to retain/emit pipeline metadata (scheduler + processor assets) and support filtered/single-component exports.
- Adds unit/integration coverage and deterministic L4/L5 diffusion-stage goldens for the new pipeline.
Reviewed changes
Copilot reviewed 24 out of 24 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/integration_test.py | Uses TemporaryDirectory for ORT session model saving to improve portability/cleanup. |
| tests/build_graph_test.py | Adds graph-build coverage for Qwen Image Edit text-encoder split and updates Qwen Image denoising task expectations. |
| testdata/golden/diffusion/qwen-image-edit-2509.json | Adds deterministic diffusion-stage golden outputs for the Qwen Image Edit 2509 pipeline. |
| testdata/cases/diffusion/qwen-image-edit-2509.yaml | Adds an L4/L5 golden-case descriptor for the official Qwen Image Edit 2509 pipeline. |
| src/mobius/tasks/_qwen_image.py | New packed-token denoising task for Qwen Image with external RoPE + mask + target slicing. |
| src/mobius/tasks/_qwen_image_vae.py | Adds dtype plumbing for VAE graphs and introduces an edit-VAE task that embeds latent normalization. |
| src/mobius/tasks/_qwen_image_text_encoder.py | New task that builds the Qwen2.5-VL prompt encoder split needed by image edit. |
| src/mobius/tasks/init.py | Exposes new Qwen Image tasks and registers their task names. |
| src/mobius/models/qwen_vl.py | Adds return_hidden_states option to support prompt-encoder hidden-state extraction. |
| src/mobius/models/qwen_image.py | Implements Qwen Image Edit denoiser changes: packed tokens, 3D RoPE inputs, masks, timestep embedding changes, output slicing, fp16 clipping. |
| src/mobius/models/qwen_image_vae.py | Adjusts RMSNorm broadcasting for attention paths and preserves diffusers weight names via passthrough preprocess. |
| src/mobius/models/qwen_image_test.py | Adds numerical parity tests vs diffusers, CUDA/precision coverage, and deterministic L4/L5 diffusion-stage golden replay. |
| src/mobius/integrations/onnx_genai/inference_metadata.py | Extends scheduler metadata to support FlowMatch Euler fields and omits beta fields for flow-match configs. |
| src/mobius/integrations/onnx_genai/inference_metadata_test.py | Adds coverage for FlowMatch Euler scheduler field mapping and metadata emission. |
| src/mobius/integrations/onnx_genai/auto_export.py | Adds Qwen Image Edit–specific metadata augmentation, processor asset copying, and flat-path handling for single-component diffusion exports. |
| src/mobius/integrations/onnx_genai/auto_export_test.py | Tests flat-path diffusion export and Qwen Image Edit metadata + processor assets emission. |
| src/mobius/_diffusers_configs.py | Adds Qwen2.5-VL text-encoder adapter config and stores non-neural pipeline metadata on ModelPackage; adds dtype + latent stats to Qwen configs. |
| src/mobius/_diffusers_configs_test.py | Adds L2-ish config mapping coverage for official Qwen Image Edit component configs (transformer + VAE latent stats). |
| src/mobius/_diffusers_builder.py | Adds Qwen2.5-VL component support, component allowlisting, EP-aware build plumbing, normalized VAE task selection for Qwen Image Edit, and retains pipeline metadata. |
| src/mobius/_diffusers_builder_test.py | Updates class/task expectations and adds tests for normalized VAE task selection + component allowlist behavior. |
| src/mobius/_builder.py | Passes execution_provider through to diffusers pipeline building. |
| src/mobius/main.py | Adds CLI component filtering behavior for diffusers pipelines and forwards EP selection through pipeline build. |
| README.md | Documents diffusion support including Qwen-Image-Edit-2509. |
| docs/model-catalog.md | Documents supported diffusers component classes including Qwen Image Edit prompt encoder + normalized VAE behavior. |
Suppressed comments (5)
src/mobius/models/qwen_image_test.py:187
- This path uses a Windows-style "\" separator. On POSIX it produces a filename containing a backslash and writes outside the temp directory, leaving artifacts behind.
path = f"{directory}\\model.onnx"
src/mobius/models/qwen_image_test.py:192
- Profiling output prefix uses a Windows-style "\" separator; on POSIX this writes profiling JSON outside the temp directory (and may leave it behind).
options.profile_file_prefix = f"{directory}\\cuda_profile"
src/mobius/models/qwen_image_test.py:371
- This path uses a Windows-style "\" separator. On POSIX it writes the model outside the temp directory (backslash becomes part of the filename), which can leak files between tests.
path = f"{directory}\\model.onnx"
src/mobius/models/qwen_image_test.py:486
- This path uses a Windows-style "\" separator. On POSIX it writes the model outside the temp directory, which can leak artifacts and break test isolation.
path = f"{directory}\\model.onnx"
src/mobius/tasks/_qwen_image_vae.py:111
- Same validation issue as the encoder: if
latents_mean/latents_stdlengths don’t matchz_dim, the decoder graph can be built but will fail at runtime.
if config.latents_mean is None or config.latents_std is None:
raise ValueError(
"Qwen Image Edit VAE config requires latents_mean and latents_std"
)
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
justinchuby
left a comment
There was a problem hiding this comment.
Correctness review: three onnx-genai runtime findings.
38d1b36 to
5650a3f
Compare
Implement the Qwen-Image-Edit-2509 packed-latent transformer contract, Qwen2.5-VL prompt encoder split, normalized Qwen VAE path, FlowMatch scheduler metadata, processor assets, and deterministic diffusion goldens. Co-authored-by: Copilot App <[email protected]> Signed-off-by: Justin Chu <[email protected]>
Use portable temporary paths in diffusion tests and validate Qwen VAE latent statistics before graph construction. Co-authored-by: Copilot App <[email protected]> Signed-off-by: Justin Chu <[email protected]>
Generate reduced L4 and L5 references from an independent diffusers VAE encode, packed transformer FlowMatch loop, and VAE decode, then replay the full Mobius ONNX chain against those outputs. Co-authored-by: Copilot App <[email protected]> Signed-off-by: Justin Chu <[email protected]>
Use data-driven diffusers pipeline overrides, document the fixed Qwen timestep embedding width, and reject onnx-genai export until its runtime can execute the required image-edit orchestration instead of emitting a non-runnable package. Co-authored-by: Copilot <[email protected]> Signed-off-by: justinchuby <[email protected]>
Apply the current Ruff formatter to the fixed-width timestep embedding construction. Co-authored-by: Copilot <[email protected]> Signed-off-by: justinchuby <[email protected]>
Fold diffusers component weight transposes after loading, classify Qwen VAE reconstruction as non-causal, and lock in fused Swish, SkipLayerNorm, Gelu, Attention, and post-weight graph counts. Co-authored-by: Copilot App <[email protected]> Signed-off-by: Justin Chu <[email protected]>
5650a3f to
08660b6
Compare
Apply repository formatting after resolving the latest main rebase conflict. Co-authored-by: Copilot App <[email protected]> Signed-off-by: Justin Chu <[email protected]>
## Summary - distill post-single-shot lessons from the Parakeet CTC, Mage-VL, Nemotron Parse, LFM2.5, Moonshine, MiniCPM-V, Qwen Image Edit, and Muse Glimmer integrations - tighten source/config/revision fidelity, real processor and runtime contracts, semantic multi-dtype validation, exact golden testing, and weighted graph optimization evidence - add precise CI baseline triage, targeted GPU validation, linear rebase/worktree guidance, quantization schema checks, and executable diffusion pipeline requirements - shorten the duplicated multimodal float32 input section and resolve contradictory encoder/component import guidance ## Sources Direct agent retrospectives plus commit/review history for merged PRs #462-#465, #471-#473, and #475. ## Validation - documentation diff is whitespace-clean - initialized repository-pinned Ruff/lintrunner tooling - independent rubber-duck review found no blocking issues; follow-up consistency suggestions were applied No runtime code is changed. --------- Signed-off-by: Justin Chu <[email protected]> Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]> Co-authored-by: Copilot Autofix powered by AI <[email protected]>
…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]>
Summary
QwenImageEditPlusPipelinedetection forQwen/Qwen-Image-Edit-2509, including its Qwen2.5-VL image-aware prompt encoder, Qwen Image transformer, normalized 3D VAE, processor assets, and FlowMatch Euler scheduler configurationmainand adopt its fusedSwishimplementation; fold diffusers weight transposes immediately after loading and prevent inappropriate causal/GQA optimization of the bidirectional VAE reconstruction graphValidation
origin/mainat1e6f61flintrunner -a— full repository lint cleanQwen/Qwen-Image-Edit-2509fp16 CUDA component CLI export with--runtime onnx-genai— succeeded and emittedmodel.onnx, FlowMatch metadata, tokenizer, Qwen2-VL image/video processor configs, and chat templatertol=atol=1e-2Graph optimization evidence
A two-block fp16 CUDA Mobius graph after the standard optimization pipeline contains:
Attentionnodes (one per layer); standard Attention is required because Qwen Image Edit needs an explicit padding bias, which correctly disqualifies Flash and contrib GQASwishnodes and 0 decomposedSigmoidnodesSkipLayerNormalizationnodesGelunodesIdentitynodesAfter weights become constants, Mobius post-weight folding reduces
Transposefrom 39 to 8 and total nodes from 391 to 360; the eight remaining transposes are dynamic RoPE/attention layout changes, not weight-layout overhead. Diffusers pipeline loading now performs this fold for every component instead of leaving Linear weight transposes in the saved graph.ORT CUDA
ORT_ENABLE_ALLfurther produces 3FastGelunodes, keeps the 6SkipLayerNormalizationnodes, foldsSwishinto surrounding kernels, retains only 8 transposes, and inserts 0 memcpy nodes. These counts are locked by model regression coverage where the representation is controlled by Mobius.The official-config, no-weight transformer graph remains 60 Attention layers with 0 Identity nodes; post-weight folding is validated on a reduced identical module tree because downloading the 57+ GB checkpoint is waived below.
Golden provenance and semantics
The committed golden is a genuine independently generated reduced Qwen Image Edit diffusion pipeline reference, but it is not generated with the official 20.4B checkpoint weights and is not an official-checkpoint perceptual output.
Reference generation uses diffusers 0.39.0 with a seeded one-block
QwenImageTransformer2DModeland seeded reducedAutoencoderKLQwenImagewhose weights are copied into the separate Mobius ONNX graphs. The source is the real nonzerotestdata/pipeline-cat-chonk.jpeg:FlowMatchEulerDiscreteSchedulerstepsThe test then independently runs the Mobius chain: ONNX VAE encoder -> separate NumPy 2x2 packing -> ONNX denoiser plus a separate FlowMatch scheduler -> NumPy unpacking -> ONNX VAE decoder.
l4_noise_pred): all 256 target-token flow-prediction values from the first actual diffusers transformer call. Both the diffusers reference and ONNX output are compared elementwise to the committed data.l5_final_latents,l5_final_image): all 256 target latent-token values after three actual diffusers transformer/scheduler steps and all 768 clipped decoded image values from the final reduced diffusers VAE decode. Mobius final latent tokens and decoded image are compared elementwise.This proves real-image VAE conditioning, packing, transformer invocation, multi-step scheduling, and decode semantics without fake token-generation data. It does not claim official-weight image quality or official-checkpoint end-to-end parity.
Waivers