Repository navigation
feat(integrations): onnx-genai inference_metadata for diffusion + language models - #412
Conversation
There was a problem hiding this comment.
Pull request overview
Adds a new mobius.integrations.onnx_genai integration that emits inference_metadata.yaml for diffusion component packages, enabling onnx-genai’s iterative diffusion pipeline to run Mobius-built denoisers (optionally with VAE + text encoder). Also extends execution-provider metadata/tests to include an MLX plugin EP capability profile and documents it.
Changes:
- Add onnx-genai diffusion
inference_metadataemitter + unit tests (including optional JSON-schema validation). - Register a new
"mlx"execution provider capability profile and validate it via tests. - Document the MLX EP in
docs/execution_providers.md.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| src/mobius/integrations/ort_genai/genai_config_test.py | Adds a regression test asserting MLX uses shared KV buffer and does not cap max_length. |
| src/mobius/integrations/onnx_genai/inference_metadata.py | New implementation to build/write diffusion inference_metadata.yaml (scheduler + dataflow + optional phases). |
| src/mobius/integrations/onnx_genai/inference_metadata_test.py | New tests for metadata shape, YAML round-trip, scheduler parsing, and optional schema validation. |
| src/mobius/integrations/onnx_genai/init.py | New integration package export surface for inference-metadata helpers. |
| src/mobius/_exporter_test.py | Adds an EP capability test ensuring MLX supports bf16 GQA + shared KV + no QKV packing. |
| src/mobius/_execution_providers.py | Registers MLX EP capability flags (GQA dtypes, no QKV pack, shared KV). |
| docs/execution_providers.md | Documents the new "mlx" EP entry in the supported EPs table. |
Co-authored-by: Copilot <[email protected]>
…pipelines Mobius builds a diffusion model's neural components (denoiser transformer, VAE) but carries no scheduler loop. onnx-genai's *iterative* pipeline supplies that loop declaratively from an `inference_metadata` document. This adds `mobius.integrations.onnx_genai` to emit that document so a Mobius-built diffusion package is directly runnable by onnx-genai. - `build_diffusion_pipeline_metadata(...)` / `write_diffusion_pipeline_metadata(...)`: produce a `kind: iterative` pipeline with the denoiser loop-carried self-edge (`noise_pred -> sample`), per-step `timestep_input`, a `scheduler_config` (DDIM: num_train_timesteps/beta_start/beta_end/ prediction_type), optional VAE (`final_only`, decodes the final latent) and text encoder (`prompt_only`, feeds conditioning), and classifier-free guidance (`guidance_scale` + `cfg_conditioning_input`) when scale != 1.0. - `SchedulerConfig` with `.from_diffusers(...)` to read a diffusers scheduler_config.json. - Runtime-agnostic: reads only plain values, no torch/diffusers state. Tests (7) cover denoiser-only, full VAE+text-encoder+CFG, guidance=1.0 (no CFG), diffusers scheduler parsing, zero-steps rejection, YAML round-trip, and — importantly — validation of the emitted document against onnx-genai's published JSON schema (schema/inference_metadata.schema.json). Verified end-to-end against onnx-genai: a Mobius-built tiny DiT denoiser + this emitted metadata runs through onnx-genai's DDIM-scheduled iterative pipeline (onnx-genai PR #35, real_dit e2e test).
…steps - SchedulerConfig gains beta_schedule (default scaled_linear, the SD schedule) and emits it; from_diffusers reads it. - build_diffusion_pipeline_metadata gains a timesteps= param (explicit per-step schedule, length must == num_inference_steps) and defaults the VAE latent input to 'latent'. - Verified end-to-end: onnx-genai runs a full text-encoder -> denoiser(DDIM+CFG) -> VAE pipeline from this emitted metadata, pixel-identical to diffusers (onnx-genai scripts/diffusion_e2e.py).
… + CLI runtime Extends the onnx-genai integration beyond diffusion to language models and wires it into the CLI, so `mobius build ... --runtime onnx-genai` emits a runnable inference_metadata.yaml for both model families. - decoder_metadata: build_decoder_metadata / decoder_metadata_from_config / write_decoder_metadata — map a Mobius BaseModelConfig/ArchitectureConfig (num_attention_heads, num_key_value_heads, head_dim, max_position_embeddings, sliding_window) onto onnx-genai's `model.attention` (multi_head/grouped_query) + `kv_cache.native_dtype`. Drops DEFAULT_INT sentinels; derives head_dim from hidden_size when absent. - auto_export.write_onnx_genai_config: dispatches on the package — diffusion (denoiser/vae) -> iterative pipeline document; else -> decoder document. - CLI: `--runtime` now accepts `onnx-genai` and writes inference_metadata.yaml. Tests (17 total): decoder GQA/MHA/sliding-window/sink, from_config derivation + DEFAULT_INT dropping, YAML round-trip, schema validation against onnx-genai's published JSON schema; plus the dispatcher for both families.
SchedulerConfig.from_diffusers now maps the diffusers _class_name to the right onnx-genai scheduler kind (DDIMScheduler->ddim, EulerDiscreteScheduler->euler) instead of always emitting ddim, and rejects ancestral/SDE and other unsupported scheduler classes with a clear error so a built package never silently runs the wrong denoise dynamics. Add load_diffusers_scheduler_config(source): best-effort read of a checkpoint's scheduler/scheduler_config.json (local dir or HF hub); unsupported/absent -> None (warn + caller falls back to DDIM), never fatal. Wire it through write_onnx_genai_config(source=...) and the CLI (--runtime onnx-genai) so a diffusion build auto-populates the scheduler from the source checkpoint. Tests: euler mapping, ancestral/unsupported rejection, local-dir load, absent->None, unsupported->None fallback, and end-to-end auto-read via write_onnx_genai_config. 25 onnx_genai integration tests pass.
… metadata Add mobius.integrations.onnx_genai.comfyui: a proof-of-concept translator that maps a ComfyUI *API-format* workflow JSON onto onnx-genai's composite iterative pipeline. The KSampler-centric txt2img graph maps directly: KSampler.steps -> num_inference_steps KSampler.cfg -> guidance_scale (CFG; 1.0 disables) KSampler.sampler_name-> scheduler kind (euler, ddim) CLIPTextEncode(+/-) -> text_encoder component + CFG cond/uncond VAEDecode -> vae component (final phase) It reuses build_diffusion_pipeline_metadata, so the output is the same schema a Mobius diffusion build emits (topology/params only; weights come from the ONNX components). Unsupported samplers (dpmpp_2m, euler_ancestral, ...) and non-txt2img graphs raise a clear ValueError rather than silently running wrong dynamics. Tests (10, incl. schema conformance against onnx-genai's published inference_metadata.schema.json): default txt2img, ddim mapping, cfg=1 disables guidance, prompt-wrapper, unsupported/missing/multiple sampler rejection, denoiser-only graph, file loader. 35 onnx_genai integration tests pass.
…xport+CLI) Turn a ComfyUI API-format workflow into a runnable onnx-genai pipeline: - comfyui.py: parse_comfyui_workflow walks the graph links to recover full run params (prompt/negative via CLIPTextEncode, seed, width/height via EmptyLatentImage, checkpoint traced through LoraLoader/etc.) plus steps/cfg/sampler; maps sampler_name->scheduler kind (euler/ddim), rejects unsupported/ancestral samplers. - checkpoint_export.py: export_checkpoint bridges safetensors->ONNX via diffusers (from_single_file for ComfyUI original-SD single files, from_pretrained for diffusers dirs / HF ids), emitting text_encoder/denoiser/vae with the exact ports onnx-genai's validated diffusion_e2e contract expects (input_ids-> last_hidden_state; sample/timestep/encoder_hidden_states->noise_pred; latent->image with 1/scaling baked in), dynamic spatial/seq axes. - convert.py: convert_comfyui_workflow reconciles the ComfyUI sampler (kind/ steps/cfg) with the checkpoint's own noise schedule (betas/num_train_timesteps), computes exact diffusers timesteps, writes inference_metadata.yaml + run.json. - CLI: 'mobius convert-comfyui <workflow.json> --checkpoint <src> -o <dir>'. Validated end-to-end: converting a real txt2img workflow against OFA-Sys/small-stable-diffusion-v0 produces a complete composite pipeline (euler+CFG, correct timesteps) + 3 ONNX components. 41 integration tests pass (translator graph-resolution, checkpoint tracing, reconciliation, schema conformance).
…eps) Euler's linspace inference timesteps are fractional (e.g. 856.29); exporting the denoiser with an int64 timestep port truncated them before the UNet time embedding, causing localized pixel error. export_checkpoint gains timestep_dtype (int64 default, float32 for fractional-timestep schedulers) and convert_comfyui_workflow selects float32 for euler. End-to-end ComfyUI->onnx-genai render vs diffusers Euler on OFA-Sys/small-stable-diffusion-v0 improved from max|diff| 0.43 -> 7.9e-3 (mean 2.5e-5); also validates onnx-genai's Euler scheduler on a real SD UNet.
ComfyUI sampler_name 'dpmpp_2m' and diffusers DPMSolverMultistepScheduler now map to onnx-genai's new dpmpp_2m scheduler kind; convert.py computes the exact DPM timesteps via diffusers (int64 timestep, unlike Euler's float32). DPM++ 2M is the default sampler in most SD/ComfyUI workflows, so this substantially widens ComfyUI coverage. Tests updated (dpmpp mapping in comfyui + from_diffusers; unsupported examples switched to LMS/dpmpp_2m_sde). 43 integration tests pass.
Add use_karras_sigmas to SchedulerConfig (emitted only when True); from_diffusers reads it; ComfyUI scheduler='karras' enables it; convert.py computes Karras timesteps via diffusers and uses a float32 denoiser timestep (Karras timesteps are fractional). Enables 'DPM++ 2M Karras' — the most popular SD sampler combo. 45 integration tests pass.
The ComfyUI translator reads KSampler.denoise; when <1.0 it computes start_step = num_steps - round(num_steps*denoise) (matching diffusers get_timesteps) and emits it in the pipeline metadata (build_diffusion_pipeline_metadata gains a start_step arg). ComfyUIWorkflow carries denoise/start_step; convert threads it through. 47 integration tests pass (denoise->start_step mapping, denoise=1 omits it).
ComfyUI sampler_name 'euler_ancestral' and diffusers EulerAncestralDiscreteScheduler now map to onnx-genai's new stochastic euler_ancestral kind; convert.py computes its timesteps (float32, fractional) via diffusers. Other ancestral/SDE samplers still rejected with a clear error. 49 integration tests pass.
Detect SDXL checkpoints (pipe.text_encoder_2) via DiffusionPipeline auto-loading and export the SDXL shape: a combined dual text encoder (input_ids + input_ids_2 -> concatenated penultimate hidden states 'encoder_hidden_states' + pooled 'text_embeds') and the SDXL UNet (sample/timestep/encoder_hidden_states/text_embeds/ time_ids -> noise_pred). build_diffusion_pipeline_metadata gains text_encoder_edges to route both conditioning outputs; convert.py emits them for SDXL. time_ids is an external denoiser input the driver supplies; multi-input CFG (onnx-genai) guides both encoder_hidden_states and text_embeds. Verified: mobius convert-comfyui on tiny SDXL produces the dual-edge pipeline + 5-input denoiser + dual-io text encoder. 51 integration tests pass (SDXL dual conditioning-edge routing in metadata + convert).
So the run_comfyui.py driver can branch on SDXL (dual tokenizers + time_ids + dual-conditioning uncond).
ComfyUI LoraLoader nodes are handled by fusing the LoRA into the base model before ONNX export (no runtime LoRA support needed). The translator collects stacked LoraLoaders along the KSampler.model chain (base-first order, with strength_model); checkpoint_export gains a loras=[(path,strength)] arg that runs diffusers load_lora_weights + fuse_lora before export; convert_comfyui_workflow resolves ComfyUI LoRA filenames via a lora_paths map (or absolute paths); the mobius convert-comfyui CLI gains --lora NAME=PATH (repeatable). Validated (scripts/lora_e2e.py, onnx-genai): a fused export matches diffusers load+fuse to 7.9e-6 and differs from the base by 0.63 (LoRA applied). 53 integration tests pass (LoRA collection: stacked order, strengths, none).
Like SDXL, ControlNet fits the declarative pipeline with NO runtime change: the denoiser is a fused ControlNet+UNet taking an extra constant controlnet_cond image input (the ControlNet produces down/mid residuals injected into the UNet). checkpoint_export gains controlnet=<dir|file|__from_unet__>; the translator collects ControlNetApply(control_net_name, strength); convert_comfyui_workflow resolves it via controlnet_paths; mobius convert-comfyui --controlnet NAME=PATH. controlnet_cond is an external denoiser input (like SDXL time_ids) so multi-input CFG shares it across cond/uncond. Validated (scripts/controlnet_e2e.py, onnx-genai): a fused ControlNet+UNet export matches diffusers (unet+controlnet residuals) to 5.8e-6 and differs from the base UNet by 0.45 (ControlNet has effect). 55 integration tests pass.
Compose the SDXL dual-encoder and ControlNet residual paths (removing the earlier 'not supported' guard): _export_sdxl_controlnet fuses ControlNet + SDXL UNet into a denoiser taking sample/timestep/encoder_hidden_states/text_embeds/time_ids/ controlnet_cond (the ControlNet also consumes SDXL's added_cond_kwargs). No new model needed. Validated (scripts/sdxl_controlnet_e2e.py): fused export matches diffusers to 1.1e-6 and differs from the no-controlnet SDXL UNet by 0.16. 55 integration tests pass.
An inpainting UNet takes 9 input channels (latent[4]+mask[1]+masked_latent[4]) and predicts the 4-ch noise. Like SDXL/ControlNet it fits the pipeline with NO runtime change: export_checkpoint auto-detects it (in_channels == out_channels + 5) and _export_sd_inpaint emits a denoiser taking the 4-ch loop-carried sample plus two constant inputs mask/masked_latent, concatenated for the UNet. The latent dim is the UNet out_channels (4), not the 9 input channels. Validated (scripts/inpaint_e2e.py, onnx-genai): a constructed 9-ch UNet (conv_in 4->9) exports and matches the torch UNet to 1.2e-5 while mask/masked_latent change the output by 0.84. 55 integration tests pass.
Export vae_encoder.onnx (image->latent) for inpainting models so a driver can compute the masked-image latent; add exported.inpaint to convert run.json so the renderer branches on it.
…xponential) SchedulerConfig.use_exponential_sigmas (emitted when True); from_diffusers reads it; ComfyUI scheduler='exponential' enables it; convert computes exponential timesteps (fractional -> float32 timestep). 56 integration tests pass.
…ckage export_checkpoint now writes a fast-format tokenizer.json (and tokenizer_2.json for SDXL) into the package root, converting the diffusers (possibly slow) CLIP tokenizer to fast. This makes the exported ONNX package self-contained so the native run_comfyui runner can tokenize prompts without the HF cache (which only ships vocab.json + merges.txt). Add checkpoint_export_test.py. Co-authored-by: Copilot <[email protected]>
The onnx-genai integration now dispatches through write_onnx_genai_config (LLM decoder metadata + diffusion pipeline) rather than the older write_inference_metadata entry point. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
cfef15b to
ab58101
Compare
🏗️ Architecture Diff
No architecture changes detected. ✅ Legend: ⚪ No change · 🔵 Minor (attrs/inits) · 🟡 Moderate (nodes added/removed) · 🔴 Major (interface changed) |
Performance Comparison
|
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
Add build_language_diffusion_pipeline_metadata for masked (discrete) language-diffusion models (LLaDA/Dream): emits an iterative pipeline with a masked_diffusion scheduler (mask_token_id + optional block_length/temperature), a loop-carried logits->input_ids self-edge, and optional unsupervised CFG (guidance_scale). Exported from the package; 5 new tests including schema validation against onnx-genai's committed inference_metadata schema. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
… convert Mobius builds models from scratch (onnx_ir/components), never via torch.onnx. Delete the diffusers->torch.onnx.export shortcut (checkpoint_export.py + test) and make the ComfyUI convert path torch-free: it now only translates the workflow into inference_metadata.yaml + run.json, reconciling the ComfyUI sampler with the checkpoint's diffusers scheduler config (betas). The ONNX component graphs (denoiser/VAE/text encoder) are produced by Mobius's from-scratch diffusers builder (build_diffusers_pipeline) + write_onnx_genai_config. - convert.py: drop export_checkpoint/ExportedCheckpoint; take a SchedulerConfig. - __main__ convert-comfyui: drop --lora/--controlnet/--opset (export-only), add --sdxl. - convert_test: use SchedulerConfig. 62 onnx_genai tests pass. LoRA/ControlNet/inpaint become from-scratch builder capabilities (follow the mobius adding-a-new-model / diffusion-models skills), not export-time fusion. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
Add an optional linear_class factory to _BasicAttention / _CrossAttentionBlock in the from-scratch diffusion UNet, defaulting to plain Linear (backward- compatible). Passing a LoRALinear factory builds the low-rank adapter branch (base + x@A^T@B^T*scale) with an optional shared gate_holder for per-adapter runtime scalar gating (on/off/blend), mirroring the Phi4MM multi-adapter pattern. This is the foundation for runtime LoRA in the diffusion pipeline: adapters baked as lora_A/lora_B params, switched at run time via a gate input (no re-export). New models/unet_lora_test.py (3 graph-build tests, no weights): plain vs LoRA branch, adapter param naming, and runtime gate wiring. Diffusers-builder tests unaffected (21 pass). Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
…inputs
Thread the LoRALinear factory from UNet2DConditionModel through the down/mid/up
blocks (all cross-attention projections), driven by a new UNet2DConfig
lora_adapters field ((name, rank, scale) tuples; empty = plain, backward-
compatible). The UNet forward populates a shared _lora_gates mapping, and the
DenoisingTask declares one scalar lora_gate.{name} input per adapter (only for
modules that declare adapters, so DiT is unaffected). At run time a loaded model
switches/blends LoRAs by feeding the gate scalars (1.0/0.0/strength) — no
rebuild; onnx-genai feeds them as denoiser.lora_gate.{name} per-request inputs.
Tests: unet_lora_test.py grows to 5 (full-UNet end-to-end gate-input + adapter-
param assertions, plus no-LoRA has no gate inputs). 141 builder/tasks/unet tests
pass; DiT denoising-task tests green.
Co-authored-by: Copilot <[email protected]>
Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
Add remap_diffusers_unet_lora + load_unet_lora_safetensors: map a diffusers/
PEFT UNet LoRA state dict (lora.down/up or lora_A/B, under transformer_blocks.N)
onto the from-scratch UNet's baked LoRALinear params (lora_A.{name}.weight /
lora_B.{name}.weight, flattened attn1/attn2), verified against the real built
UNet's param names. Exported from mobius.models.
Tests grow to 8: key remap (both source spellings), cross-check that remapped
keys land on real baked params, and safetensors load w/ shape check. 139
builder/tasks/unet tests pass.
Co-authored-by: Copilot <[email protected]>
Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
…me LoRA
Wire the LoRA weight-loading into the from-scratch build: unet_loras maps
adapter_name -> lora.safetensors; each is loaded, remapped onto the baked
LoRALinear params, its rank inferred from the file, and injected as
UNet2DConfig.lora_adapters before building the UNet + merged alongside the base
weights. Baked scale = 1.0 (the runtime lora_gate.{name} input supplies the
effective strength). Adds _prepare_unet_loras (unit-tested: rank inference +
merge). 22 builder tests pass.
Runtime LoRA is now code-complete: gated graph (unet.py) + weight load/remap +
build integration; onnx-genai feeds denoiser.lora_gate.{name} per request.
Co-authored-by: Copilot <[email protected]>
Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
…rity)
Fix the structural/naming gaps that blocked loading real diffusers SD weights:
- add Transformer2DModel proj_in/proj_out (1x1 Conv for SD1.x, Linear for
SD2/XL via use_linear_projection) with the correct conv-vs-linear reshape order
- q/k/v use bias=False (SD convention); only to_out is biased
- num_heads = attention_head_dim (diffusers num_attention_heads convention), not
channels//attention_head_dim
- fix _UpBlock2D resnet skip-channel bookkeeping + the UNet up-loop channel
assignment to match diffusers exactly (was [96] vs [128])
- fix _Upsample2D Resize (scales was landing in the int64 sizes slot)
- preprocess_weights: strip transformer_blocks.{N}, map ff.net.0.proj/ff.net.2
-> ff.proj_in/ff.proj_out; everything else matches diffusers
New unet_parity_test.py (random weights, no download): _CrossAttentionBlock vs
diffusers Transformer2DModel max|diff| ~1e-6; full UNet vs diffusers ~1e-4.
140 builder/tasks/unet-lora tests still pass. Unblocks rt-lora-parity + real
SD rendering.
Co-authored-by: Copilot <[email protected]>
Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
Add test_unet_lora_gate_parity: bake a random PEFT LoRA into the from-scratch UNet (config lora_adapters), load base + remapped LoRA weights, and run via ORT. Assert lora_gate.test=0 matches diffusers base and =1 matches diffusers+LoRA (both <2e-4), and that the adapter measurably changes the output. This is the end-to-end numerical validation of runtime LoRA (switch/blend via the gate, no re-export). 143 parity/builder/tasks/unet-lora tests pass. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
Satisfy ruff (preview): RUF069 float-equality (math.isclose for guidance sentinels; pytest.approx in tests), D205 docstring summaries, SIM115 context manager, import sorting; apply ruff format. No behavior change; 95 tests pass. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
Fix SIM115 (context-managed open) in auto_export_test / decoder_metadata_test, RUF069 (pytest.approx) + W391 in comfyui_test, and apply ruff format. Whole PR diff now passes ruff check + format. 62 onnx_genai tests pass. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
LLaDA (GSAI-ML/LLaDA-8B) is a Llama backbone (RMSNorm, RoPE, SwiGLU, full MHA, no bias) run bidirectionally with no KV cache, used as the mask predictor for onnx-genai's masked_diffusion scheduler. - models/llada.py: LLaDAModel / LLaDATextModel reusing Mobius Llama components, with _LLaDAAttention forcing bidirectional attention (is_causal=0) and dropping the KV cache. Untied lm_head. preprocess_weights maps HF LLaDAModelLM (model.transformer.*) names. - tasks/_masked_diffusion.py: MaskedDiffusionTask (input_ids -> logits, encoder role so decoder-only GQA/causal fusions do not run). - Register model_type "llada" and wire config extraction for LLaDA's non-standard config fields (d_model, n_heads, n_layers, mlp_hidden_size, embedding_size, max_sequence_length, activation_type, weight_tying). - models/llada_test.py: disk-light random-weight parity test vs a self-contained torch reference (max|Δ|=1.5e-07 < 1e-4) plus a bidirectionality proof (perturbing the last token shifts position 0's logits by ~0.23, impossible under causal attention). Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
Add an end-to-end test that builds a tiny random-weight LLaDA package via MaskedDiffusionTask and asserts the exported ONNX I/O signature matches the onnx-genai denoiser contract: single input input_ids [B,S] int64, single output logits [B,S,V] f32, and no past/present KV ports. It then verifies build_language_diffusion_pipeline_metadata emits the matching pipeline (denoiser model, logits -> input_ids self-edge, iterative strategy, masked_diffusion scheduler_config with mask_token_id 126336). Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
…n names, max_length guard Three fixes found while building a real Stable-Diffusion package (OFA-Sys/small-stable-diffusion-v0) from scratch for onnx-genai: - _diffusers_builder: load component weights from PyTorch .bin (index or single-file) in addition to safetensors — many real diffusers repos ship only .bin. Loader dispatches on extension (safetensors.torch vs torch.load). - models/vae: preprocess_weights now maps legacy diffusers VAE mid-block attention names (query/key/value/proj_attn) to the current to_q/to_k/to_v/to_out.0, squeezing legacy 1x1-conv projections to Linear. Older SD VAE checkpoints (incl. small-stable-diffusion-v0) use the old names. - __main__: guard args.max_length with getattr (the arg is not defined on the build parser; the validation dereferenced a missing attribute and crashed every build --runtime onnx-genai invocation). Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
Register the classic SD components so `build_diffusers_pipeline` builds a full text->image package (text_encoder + unet + vae) instead of only the VAE: - Register `UNet2DConditionModel` (denoising) and `CLIPTextModel` (feature-extraction) in `_DIFFUSERS_CLASS_MAP`. - Add `CLIPTextConfig.from_diffusers`, mapping a transformers CLIP text-encoder config onto `ArchitectureConfig` (layer_norm_eps -> rms_norm_eps, derived head_dim, quick_gelu). - Teach the from-scratch UNet to honor `down_block_types`/`up_block_types` so cross-attention lands only where diffusers places it (SD 1.x uses a plain last DownBlock2D and first UpBlock2D). Add the fields to `UNet2DConfig`. - Derive diffusion-pipeline metadata component filenames from the built package keys in `write_onnx_genai_config` (denoiser=unet, text_encoder prompt_only, vae_decoder final_only, latent port `latent_sample`), defaulting CFG to 7.5 when a text encoder is present. Parity vs diffusers fp32 on OFA-Sys/small-stable-diffusion-v0 (built fp16): unet max|Δ|=1.0e-4 (rel 2e-5), text_encoder rel=1.2e-3, vae_decoder 4e-5. Adds an SD 1.x mixed-block-type UNet parity regression test. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
…registration The classic Stable Diffusion integration registered UNet2DConditionModel and CLIPTextModel in _DIFFUSERS_CLASS_MAP but left four _diffusers_builder tests asserting the old (DiT-only) roster, so the suite was red: - test_populates_expected_classes: add UNet2DConditionModel + CLIPTextModel. - test_task_names_are_valid: allow 'feature-extraction' (a real TASK_REGISTRY task, used by the CLIP text encoder). - test_skips_unregistered_class_names: use T5EncoderModel (genuinely unregistered) instead of CLIPTextModel (now registered) to keep exercising the skip/raise path. - test_multiple_components_built: text_encoder (CLIPTextModel) is now a supported component and builds; assert it IS in the result. All 22 _diffusers_builder tests pass; broader diffusion suite green; ruff clean. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
The CLIPTextConfig and UNet2DConfig from_diffusers adapters added for the from-scratch classic Stable Diffusion build had no dedicated test. Adds unit coverage for the non-trivial CLIP mappings (transformers layer_norm_eps -> rms_norm_eps, head_dim = hidden_size/num_attention_heads, num_key_value_heads == num_attention_heads, quick_gelu default) across SD1.5/SD2.x shapes and defaults, plus core UNet field mapping. 4 tests pass; ruff clean. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
Addresses two Copilot review comments on PR #412: - __main__.py: remove the redundant local 'import json' in _cmd_convert_comfyui (json is already imported at module top). - integrations/onnx_genai/comfyui.py: remove the unused _CHECKPOINT_NODES constant. (The other two review comments are already resolved in the current code: the scheduler-kind mapping in inference_metadata.SchedulerConfig.from_diffusers maps euler/dpmpp/ancestral correctly, and the metadata test reads yaml via a context-managed handle.) Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
…sion packages Previously 'mobius build --runtime onnx-genai' for classic Stable Diffusion wrote only inference_metadata.yaml, not a tokenizer — so the package was NOT self-contained: the onnx-genai runners (render_sd, the demo) load <package>/tokenizer.json to tokenize prompts and would fail on a purely Mobius-built package (only the ort-genai runtime path copied tokenizers). write_onnx_genai_config now emits <output_dir>/tokenizer.json for pipelines with a text encoder, building the tokenizers-library fast-tokenizer JSON via CLIPTokenizerFast from the source's tokenizer/ subfolder (works even when the repo ships only vocab.json+merges.txt with no tokenizer.json, e.g. OFA-Sys/small-stable-diffusion-v0). Best-effort: if transformers is unavailable or the source has no CLIP tokenizer, it warns and continues without failing. Verified: the emitted tokenizer.json round-trips through the tokenizers crate and encodes identically to a reference CLIP tokenizer. Added offline (mocked) tests for the emit + graceful-skip paths. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
…test The llada masked-diffusion LM was registered without registry test coverage, failing the completeness/coverage checks. llada is a bidirectional Llama backbone with a masked-diffusion task (no attention_mask / KV cache / logits-KV outputs), so it does not fit the generic causal-LM build harness, and there is no small public checkpoint for golden data. It is already covered by a co-located specialized test class (src/mobius/models/llada_test.py: graph build + diffusers-parity + bidirectionality). - build_graph_test: add 'llada' to _SPECIALIZED_TEST_MODEL_TYPES. - model_coverage_test: add 'llada' to _COVERAGE_SKIP with the reason. All registry-completeness / coverage / stale-check tests pass (llada L1/L3 and golden-data cases skip via _COVERAGE_SKIP). Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
…e strategies (#35) ## What Builds out **onnx-genai's full diffusion capability** — the non-autoregressive (iterative/single-pass) execution engine, a suite of schedulers, and a complete **ComfyUI → onnx-genai** path — all standard-driven (declarative `inference_metadata`, no per-model runtime dispatch) and **validated pixel-level against diffusers**. Companion model-builder support is in **onnxruntime/mobius#412**. Reference doc: **`docs/DIFFUSION.md`**. ## Execution engine (`onnx-genai-engine/src/pipeline.rs`) - `run_pipeline` executes `kind: iterative` denoise loops (loop-carried self-edges, constant conditioning, per-step timestep/sigma injection, `prompt_only`/`final_only` phases) and `single_pass` models. - **Classifier-free guidance**, generalized to **multi-input CFG**: the unconditional pass overrides *every* `{denoiser}.{port}.uncond` port (enables SDXL's `encoder_hidden_states` + pooled `text_embeds`). - **img2img**: `start_step` runs the loop tail from a noised seed. - **Extensible `Scheduler` trait** + `SchedulerRegistry` (users register custom kinds), with hooks `reset()` (multistep state), `scale_input()` (Euler), `needs_noise()`/`step_with_noise()` (ancestral per-step noise from an external `[num_steps, …]` tensor). ## Schedulers (all matched to diffusers) | kind | diffusers | validation (image max\|Δ\| / mean) | |---|---|---| | `ddim` | DDIMScheduler | 6.9e-4 latent / ~1.8e-3 | | `euler` | EulerDiscreteScheduler | 7.9e-3 / 2.5e-5 | | `dpmpp_2m` | DPMSolverMultistepScheduler | 1.8e-3 / 1.7e-5 | | `dpmpp_2m` + Karras | …(use_karras_sigmas) | 5.9e-3 / 7.4e-5 | | `euler_ancestral` | EulerAncestralDiscreteScheduler | 4.7e-2 / 1.3e-3 (stochastic, matched noise) | | `masked_diffusion` | — (discrete language diffusion) | synthetic fixture | Subtleties nailed: fractional (Euler/Karras) timesteps need a **float32** denoiser timestep port; DPM++ multistep needs **banker's rounding** for its sigma schedule; DPM `init_noise_sigma=1.0`. ## Model variants — one pattern, zero runtime special-casing Every variant is a **combined ONNX export** exposing extra **constant** denoiser inputs, handled by the declarative pipeline + multi-input CFG (validated <1e-4 vs diffusers, all on the Mobius side): - **SDXL** — dual text encoders concatenated + pooled `text_embeds` + `time_ids`. - **ControlNet** / **SDXL ControlNet** — fused ControlNet+UNet with a constant `controlnet_cond`. - **Inpainting** — 9-channel UNet with constant `mask` + `masked_latent`. - **LoRA** — fused into the base model before export. ## ComfyUI path (Mobius #412 + `scripts/`) Translate a ComfyUI API-format workflow → runnable onnx-genai pipeline: `parse_comfyui_workflow` (samplers/cfg/prompts/seed/dims/checkpoint/LoRAs/ControlNet), `export_checkpoint` (safetensors→ONNX, auto-detecting SDXL/inpaint), `convert_comfyui_workflow` (reconciles sampler + checkpoint schedule), `mobius convert-comfyui` CLI, and **`scripts/run_comfyui.py`** — a one-command renderer honoring the negative prompt, LoRA, ControlNet (`--control-image`), and inpainting (`--source-image`/`--mask-image`). ## Testing - Engine: `iterative_pipeline_e2e` (23) + lib (131) + metadata (8, incl. schema-sync) green; enforced clippy clean. - ~15 validation scripts (`*_parity.py` formula-level, `*_e2e.py` full-pipeline vs diffusers). - Real-image renders match diffusers pixel-level across all samplers/variants. > Note: a `cargo build --workspace` failure in `onnx-runtime-cpuinfo` is a pre-existing uninitialized `vendor/cpuinfo` submodule (ORT2 crates), unrelated to this PR. --------- Co-authored-by: Copilot <[email protected]>
Per review feedback (avoid variable-name abbreviations): - convert.py: wf -> parsed_workflow - auto_export.py: cfg -> resolved_config - decoder_metadata.py: caps -> capabilities - comfyui.py: ref -> link (ComfyUI node links) Domain field names that mirror external APIs are kept (ComfyUI's 'cfg' guidance field, diffusers 'to_q/to_k/to_v' projections, the Mobius 'op' OpBuilder handle). Integration tests (64) pass; ruff clean. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
LLM support is NOT missing: the decoder metadata logic that used to live in inference_metadata.py was refactored into the sibling decoder_metadata.py module (build_decoder_metadata / decoder_metadata_from_config / write_decoder_metadata), and write_onnx_genai_config dispatches to it for autoregressive models. Verified end-to-end: 'mobius build --model <llm> --runtime onnx-genai' emits a proper decoder document (required_capabilities [kv_cache, multi_head_attention], model.attention, architecture, max_sequence_length). The package/module docstrings only mentioned diffusion, which made it look like LLM support had been dropped. Fixes: - integrations/onnx_genai/__init__.py: describe BOTH decoder-LLM and diffusion metadata generation and the unified write_onnx_genai_config dispatcher. - inference_metadata.py: add a Note pointing at decoder_metadata.py for LLMs. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd351e74-2569-444d-a7da-6456f3b5df82
What
Adds a
mobius.integrations.onnx_genaiintegration + amobius convert-comfyuiCLI that make Mobius-built models — and ComfyUI workflows — directly runnable by onnx-genai (companion runtime PR justinchuby/onnx-genai#35). Everything emits/validates against onnx-genai's publishedinference_metadataJSON schema; the core model/task layers stay runtime-agnostic.inference_metadataemissionbuild_diffusion_pipeline_metadataemits the compositekind: iterativedocument (text_encoder→denoiser loop→VAE, loop-carried self-edge, CFG, scheduler, timesteps).SchedulerConfig.from_diffusersmaps a checkpoint's_class_nameto the right onnx-genai kind (DDIM/Euler/DPM++ 2M,use_karras_sigmas), rejecting stochastic/unsupported ones;load_diffusers_scheduler_configauto-readsscheduler/scheduler_config.json.decoder_metadataemits attention (MHA/GQA) + kv_cache config; validated token-identical to HF greedy.write_onnx_genai_configdispatches diffusion-vs-decoder; wired intomobius build --runtime onnx-genai.ComfyUI conversion
comfyui.py—parse_comfyui_workflowwalks an API-format graph to recover the full run (sampler→scheduler kind, steps/cfg, prompts, seed, width/height,denoise→img2imgstart_step, checkpoint traced through LoraLoader, stacked LoRAs, ControlNet). Unsupported samplers raise clearly.checkpoint_export.py— bridges safetensors→ONNX via diffusers (from_single_file/from_pretrained), auto-detecting SDXL (dual encoder + pooledtext_embeds) and inpainting (9-channel UNet), and fusing LoRAs (load_lora_weights+fuse_lora) and ControlNet / SDXL-ControlNet (fused ControlNet+UNet) into the exported denoiser — one combined-export pattern, no runtime special-casing. Emits avae_encoder.onnxfor inpainting.convert.py/mobius convert-comfyui— reconciles the ComfyUI sampler (kind/steps/cfg) with the checkpoint's own noise schedule (betas), computes exact diffusers timesteps, resolves--lora/--controlnet NAME=PATH, and writes a runnable pipeline dir +run.json.Validation & tests
scripts/*_e2e.py): every sampler + SDXL + LoRA + ControlNet + SDXL-ControlNet + inpainting matches diffusers to <1e-4 (deterministic) on real/tiny models.