Skip to content

Commit 556b22e

Browse files
justinchubyCopilot
andauthored
feat(integrations): onnx-genai inference_metadata for diffusion + language models (#412)
## What Adds a **`mobius.integrations.onnx_genai`** integration + a **`mobius convert-comfyui`** CLI that make Mobius-built models — and **ComfyUI workflows** — directly runnable by [onnx-genai](https://github.com/justinchuby/onnx-genai) (companion runtime PR justinchuby/onnx-genai#35). Everything emits/validates against onnx-genai's published `inference_metadata` JSON schema; the core model/task layers stay runtime-agnostic. ## `inference_metadata` emission - **Diffusion pipelines**: `build_diffusion_pipeline_metadata` emits the composite `kind: iterative` document (text_encoder→denoiser loop→VAE, loop-carried self-edge, CFG, scheduler, timesteps). `SchedulerConfig.from_diffusers` maps a checkpoint's `_class_name` to the right onnx-genai kind (DDIM/Euler/DPM++ 2M, `use_karras_sigmas`), rejecting stochastic/unsupported ones; `load_diffusers_scheduler_config` auto-reads `scheduler/scheduler_config.json`. - **Decoder LLMs**: `decoder_metadata` emits attention (MHA/GQA) + kv_cache config; validated token-identical to HF greedy. - `write_onnx_genai_config` dispatches diffusion-vs-decoder; wired into `mobius build --runtime onnx-genai`. ## ComfyUI conversion - **`comfyui.py`** — `parse_comfyui_workflow` walks an API-format graph to recover the full run (sampler→scheduler kind, steps/cfg, prompts, seed, width/height, `denoise`→img2img `start_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 + pooled `text_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 a `vae_encoder.onnx` for 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 - **55 integration tests** (translator graph-resolution incl. LoRA/ControlNet, scheduler mapping, SDXL/inpaint routing, schema conformance). - End-to-end (onnx-genai `scripts/*_e2e.py`): every sampler + SDXL + LoRA + ControlNet + SDXL-ControlNet + inpainting matches diffusers to <1e-4 (deterministic) on real/tiny models. --------- Co-authored-by: Copilot <[email protected]>
1 parent 9d544b4 commit 556b22e

35 files changed

Lines changed: 4081 additions & 307 deletions

‎docs/execution_providers.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ pkg = build_from_module(
5555
| **CUDA** | `"cuda"` | ORT CUDA EP. GQA fusion for FP16/BF16. SkipLayerNorm fusion. |
5656
| **DirectML** | `"dml"` | DirectML (Windows GPU). GQA for FP16. RoPE and packed QKV lowered to separate ops. |
5757
| **WebGPU** | `"webgpu"` | ORT WebGPU EP. GQA for FP32/FP16. `Shape` eliminated. INT4 accuracy level 4. |
58+
| **MLX** | `"mlx"` | Apple-silicon MLX plugin EP. GQA for FP32/FP16/BF16 with unpacked Q/K/V and shared KV buffers. |
5859
| **TRT-RTX** | `"trt-rtx"` | NVIDIA TensorRT-RTX. GQA for FP16/BF16. `SkipLayerNorm`/`SkipSimplifiedLayerNorm` expanded via InlinePass (TRT handles these primitives natively). GPU graph capture enabled. |
5960
| **ONNX-standard** | `"onnx-standard"` | Strict ONNX. Zero custom-domain ops — all `com.microsoft` ops (FusedMatMul, SkipLayerNorm, PackedMHA) are expanded to standard ONNX via InlinePass. No GQA or QKV packing. Use for non-ORT runtimes that do not support ORT extensions. |
6061

@@ -643,4 +644,3 @@ cuda_pkg, dml_pkg = await asyncio.gather(build_cuda(), build_dml())
643644

644645
This is implemented using Python's `contextvars` module, which provides
645646
copy-on-write isolation for threads and coroutines.
646-

‎src/mobius/__main__.py‎

Lines changed: 67 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -127,9 +127,10 @@ def _cmd_build(args: argparse.Namespace) -> None:
127127
if args.max_seq_len is not None and args.max_seq_len <= 0:
128128
raise SystemExit("Error: --max-seq-len must be a positive integer.")
129129

130-
if args.max_length is not None and args.runtime != "onnx-genai":
130+
max_length = getattr(args, "max_length", None)
131+
if max_length is not None and args.runtime != "onnx-genai":
131132
raise SystemExit("Error: --max-length can only be used with --runtime onnx-genai.")
132-
if args.max_length is not None and args.max_length <= 0:
133+
if max_length is not None and max_length <= 0:
133134
raise SystemExit("Error: --max-length must be a positive integer.")
134135

135136
# Validate --static-cache + --task compatibility
@@ -299,12 +300,13 @@ def _save_package(
299300
for name, path in artifacts.items():
300301
print(f" {name}: {path}")
301302
elif runtime == "onnx-genai":
302-
from mobius.integrations.onnx_genai import write_inference_metadata
303+
from mobius.integrations.onnx_genai import write_onnx_genai_config
303304

304-
path = write_inference_metadata(
305-
pkg, output_dir, max_sequence_length=getattr(args, "max_length", None)
306-
)
307-
print(f" inference_metadata: {path}")
305+
config = getattr(pkg, "config", None)
306+
source = getattr(args, "config", None) or getattr(args, "model", None)
307+
artifacts = write_onnx_genai_config(pkg, output_dir, config=config, source=source)
308+
for name, path in artifacts.items():
309+
print(f" {name}: {path}")
308310

309311

310312
def _cmd_list(args: argparse.Namespace) -> None:
@@ -392,6 +394,32 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
392394
print(f"Saved {name} to {path}")
393395

394396

397+
def _cmd_convert_comfyui(args: argparse.Namespace) -> None:
398+
"""Execute the 'convert-comfyui' subcommand."""
399+
from mobius.integrations.onnx_genai import convert_comfyui_workflow
400+
401+
with open(args.workflow, encoding="utf-8") as handle:
402+
workflow = json.load(handle)
403+
result = convert_comfyui_workflow(
404+
workflow,
405+
args.checkpoint,
406+
args.output,
407+
sdxl=getattr(args, "sdxl", False),
408+
)
409+
wf = result.workflow
410+
print(f"Converted ComfyUI workflow -> {result.output_dir}")
411+
print(f" metadata: {result.metadata_path}")
412+
print(f" run params: {result.run_params_path}")
413+
print(
414+
f" {wf.steps} steps, cfg {wf.cfg}, sampler {wf.sampler_name} "
415+
f"(scheduler {wf.scheduler_kind}), {wf.width}x{wf.height}"
416+
)
417+
if wf.loras:
418+
print(f" loras: {', '.join(f'{n}@{s}' for n, s in wf.loras)}")
419+
if wf.prompt is not None:
420+
print(f" prompt: {wf.prompt!r}")
421+
422+
395423
def _cmd_info(args: argparse.Namespace) -> None:
396424
"""Execute the 'info' subcommand."""
397425
from mobius._diffusers_builder import (
@@ -567,25 +595,15 @@ def main(argv: list[str] | None = None) -> None:
567595
build_parser.add_argument(
568596
"--runtime",
569597
default=None,
570-
choices=["onnx-genai", "ort-genai"],
598+
choices=["ort-genai", "onnx-genai"],
571599
metavar="RUNTIME",
572600
help=(
573-
"Generate runtime-specific config files after building. "
574-
"Supports: 'onnx-genai' (writes inference_metadata.yaml) and "
575-
"'ort-genai' (writes genai_config.json and copies tokenizer files). "
576-
"For ort-genai, --model downloads tokenizer files from HuggingFace "
577-
"and --config copies them from the local directory."
578-
),
579-
)
580-
build_parser.add_argument(
581-
"--max-length",
582-
type=int,
583-
default=None,
584-
metavar="N",
585-
help=(
586-
"Serving KV capacity written to onnx-genai inference metadata. "
587-
"Only used with --runtime onnx-genai. Defaults to the smaller of "
588-
"4096 and the model's max_position_embeddings."
601+
"Generate runtime-specific config files after building. Supports: "
602+
"'ort-genai' (writes genai_config.json + copies tokenizer files) and "
603+
"'onnx-genai' (writes inference_metadata.yaml — a decoder attention/KV "
604+
"document for LLMs, or an iterative pipeline document for diffusion). "
605+
"When used with --model, tokenizer files are downloaded from HuggingFace; "
606+
"with --config (local directory), they are copied from that directory."
589607
),
590608
)
591609
build_parser.add_argument(
@@ -675,6 +693,31 @@ def main(argv: list[str] | None = None) -> None:
675693
)
676694
info_parser.set_defaults(func=_cmd_info)
677695

696+
# --- convert-comfyui ---
697+
comfy_parser = subparsers.add_parser(
698+
"convert-comfyui",
699+
help="Translate a ComfyUI API-format workflow JSON into an onnx-genai "
700+
"pipeline metadata directory (inference_metadata.yaml + run.json). The "
701+
"ONNX component graphs are built separately by Mobius's diffusers builder.",
702+
)
703+
comfy_parser.add_argument("workflow", help="Path to the ComfyUI API-format workflow JSON.")
704+
comfy_parser.add_argument(
705+
"--checkpoint",
706+
default=None,
707+
help="Optional diffusers directory or Hugging Face model id whose "
708+
"scheduler config supplies the noise-schedule betas (Stable Diffusion "
709+
"defaults are used when omitted).",
710+
)
711+
comfy_parser.add_argument(
712+
"--output", "-o", required=True, help="Output directory for the pipeline metadata."
713+
)
714+
comfy_parser.add_argument(
715+
"--sdxl",
716+
action="store_true",
717+
help="Target an SDXL pipeline (routes the dual text-encoder conditioning edges).",
718+
)
719+
comfy_parser.set_defaults(func=_cmd_convert_comfyui)
720+
678721
args = parser.parse_args(argv)
679722
args.func(args)
680723

‎src/mobius/_configs/_base.py‎

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,8 @@ def _resolve_hidden_act(config, model_type: str) -> str | None:
6363
or getattr(config, "dense_act_fn", None)
6464
or getattr(config, "activation", None)
6565
or getattr(config, "afn", None)
66+
# LLaDA/OLMo expose the activation as ``activation_type`` (e.g. "silu").
67+
or getattr(config, "activation_type", None)
6668
or ("silu" if model_type in ("qwen",) else None)
6769
# gelu_activation is a boolean (XLM) — must be after all string
6870
# attrs so it cannot override an explicit hidden_act.
@@ -547,16 +549,19 @@ def from_transformers(cls, config, parent_config=None) -> ArchitectureConfig:
547549
# instead of scalar ones. Resolve to a scalar for the base config.
548550
hidden_size = (
549551
getattr(config, "hidden_size", None)
552+
or getattr(config, "d_model", None)
550553
or _first(getattr(config, "hidden_sizes", None))
551554
or 0
552555
)
553556
num_attention_heads = (
554557
getattr(config, "num_attention_heads", None)
558+
or getattr(config, "n_heads", None)
555559
or _first(getattr(config, "num_heads", None))
556560
or 1
557561
)
558562
num_hidden_layers = (
559563
getattr(config, "num_hidden_layers", None)
564+
or getattr(config, "n_layers", None)
560565
or getattr(config, "num_encoder_blocks", None)
561566
or 0
562567
)
@@ -583,13 +588,20 @@ def from_transformers(cls, config, parent_config=None) -> ArchitectureConfig:
583588
),
584589
num_attention_heads=_as_int(num_attention_heads),
585590
num_key_value_heads=_as_int(
586-
getattr(config, "num_key_value_heads", num_attention_heads)
591+
getattr(config, "num_key_value_heads", None)
592+
or getattr(config, "n_kv_heads", None)
593+
or num_attention_heads
587594
),
588595
num_hidden_layers=_as_int(num_hidden_layers),
589-
vocab_size=getattr(config, "vocab_size", None) or 0,
596+
vocab_size=(
597+
getattr(config, "vocab_size", None)
598+
or getattr(config, "embedding_size", None)
599+
or 0
600+
),
590601
hidden_size=_as_int(hidden_size),
591602
intermediate_size=(
592603
getattr(config, "intermediate_size", None)
604+
or getattr(config, "mlp_hidden_size", None)
593605
or getattr(config, "n_inner", None)
594606
or getattr(config, "d_ff", None)
595607
or getattr(config, "ffn_dim", None)
@@ -744,10 +756,16 @@ def from_transformers(cls, config, parent_config=None) -> ArchitectureConfig:
744756
rope_config.rope_interleave if rope_config is not None else False
745757
),
746758
**mrope_fields,
747-
max_position_embeddings=getattr(config, "max_position_embeddings", 0),
759+
max_position_embeddings=(
760+
getattr(config, "max_position_embeddings", None)
761+
or getattr(config, "max_sequence_length", None)
762+
or 0
763+
),
748764
tie_word_embeddings=(
749765
getattr(config, "tie_word_embeddings", None)
750766
if getattr(config, "tie_word_embeddings", None) is not None
767+
else getattr(config, "weight_tying", None)
768+
if getattr(config, "weight_tying", None) is not None
751769
else getattr(parent_config, "tie_word_embeddings", False)
752770
),
753771
# MoE

0 commit comments

Comments
 (0)