Skip to content

Commit a52e72c

Browse files
justinchubyCopilot
andcommitted
Carry the generated sampler graphs with the parsed ComfyUI workflow
The translated document declares the sampler as executable components under ``policies/*.onnx``, but ``parse_comfyui_workflow`` built those graphs and threw them away, so a caller holding only the metadata could not produce a loadable package. ``ComfyUIWorkflow`` now carries them and exposes ``save_policy_components``; the dict-only wrappers point at it. ``convert_comfyui_workflow`` keeps building its own package rather than reusing the parse-time one, because the checkpoint's scheduler config can reconcile to a different solver than the ComfyUI sampler implied -- reusing it would leave that run's components behind for a document that never references them. That is now stated where someone would otherwise "simplify" it, and covered by a test asserting the written set equals the referenced set exactly. Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent e5a00bf commit a52e72c

3 files changed

Lines changed: 84 additions & 1 deletion

File tree

‎src/mobius/integrations/onnx_genai/comfyui.py‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
import json
4242
import logging
4343
import math
44+
import os
4445
from typing import Any
4546

4647
from mobius.integrations.onnx_genai.inference_metadata import (
@@ -80,6 +81,12 @@ class ComfyUIWorkflow:
8081
``metadata`` is the onnx-genai ``inference_metadata`` document (topology +
8182
scheduler + guidance). The remaining fields are the per-run inputs recovered
8283
from the graph so a caller can actually drive the pipeline.
84+
85+
The document declares the sampler as executable components under
86+
``policies/*.onnx``. Those graphs are generated during translation rather
87+
than read off disk, so they are carried here in ``policy_components``;
88+
:meth:`save_policy_components` writes them next to the metadata. A package
89+
whose metadata references them without shipping them is not loadable.
8390
"""
8491

8592
metadata: dict[str, Any]
@@ -99,6 +106,18 @@ class ComfyUIWorkflow:
99106
start_step: int = 0
100107
loras: tuple[tuple[str, float], ...] = ()
101108
controlnet: tuple[str, float] | None = None
109+
policy_components: Any | None = None
110+
111+
def save_policy_components(self, directory: str) -> dict[str, str]:
112+
"""Write the generated sampler graphs ``metadata`` references.
113+
114+
Returns the package-relative artifact paths, or an empty mapping when
115+
the workflow carries no generated components.
116+
"""
117+
if self.policy_components is None:
118+
return {}
119+
os.makedirs(directory, exist_ok=True)
120+
return self.policy_components.save_policy_components(directory)
102121

103122

104123
def _nodes(workflow: dict[str, Any]) -> dict[str, Any]:
@@ -327,6 +346,11 @@ def parse_comfyui_workflow(
327346
"the workflow before converting it."
328347
)
329348

349+
from mobius._model_package import ModelPackage
350+
351+
# The sampler components the document declares are generated here, so they
352+
# travel with the parsed workflow instead of being discarded.
353+
policy_components = ModelPackage({})
330354
metadata = build_diffusion_pipeline_metadata(
331355
num_inference_steps=steps,
332356
scheduler=sched,
@@ -335,9 +359,11 @@ def parse_comfyui_workflow(
335359
denoiser_filename=denoiser_filename,
336360
vae_filename=vae_filename,
337361
text_encoder_filename=text_encoder_filename if has_text_encoder else None,
362+
package=policy_components,
338363
)
339364
return ComfyUIWorkflow(
340365
metadata=metadata,
366+
policy_components=policy_components,
341367
prompt=prompt,
342368
negative_prompt=negative_prompt,
343369
width=width,
@@ -362,6 +388,12 @@ def translate_comfyui_workflow(workflow: dict[str, Any], **kwargs: Any) -> dict[
362388
363389
Convenience wrapper over :func:`parse_comfyui_workflow` for callers that only
364390
need the pipeline document (see that function for the full run parameters).
391+
392+
The document references generated sampler graphs under ``policies/*.onnx``,
393+
which this wrapper drops. To write a loadable package use
394+
:func:`convert_comfyui_workflow`, or keep the
395+
:class:`ComfyUIWorkflow` and call
396+
:meth:`~ComfyUIWorkflow.save_policy_components`.
365397
"""
366398
return parse_comfyui_workflow(workflow, **kwargs).metadata
367399

@@ -374,5 +406,9 @@ def parse_comfyui_workflow_file(path: str, **kwargs: Any) -> ComfyUIWorkflow:
374406

375407

376408
def translate_comfyui_workflow_file(path: str, **kwargs: Any) -> dict[str, Any]:
377-
"""Load a ComfyUI API-format JSON file and translate it to metadata."""
409+
"""Load a ComfyUI API-format JSON file and translate it to metadata.
410+
411+
Returns the document only; see :func:`translate_comfyui_workflow` for how to
412+
materialize the sampler graphs it references.
413+
"""
378414
return parse_comfyui_workflow_file(path, **kwargs).metadata

‎src/mobius/integrations/onnx_genai/comfyui_test.py‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import json
99

1010
import pytest
11+
import yaml
1112

1213
from mobius.integrations.onnx_genai.comfyui import (
1314
ComfyUIWorkflow,
@@ -307,6 +308,47 @@ def test_translate_from_file(tmp_path):
307308
assert workflow["inputs"]["request.max_iterations"]["default"] == 20
308309

309310

311+
def _referenced_artifacts(metadata: dict) -> set[str]:
312+
"""Every ONNX artifact the published workflow declares."""
313+
return {
314+
declaration["implementation"]["artifact"]
315+
for declaration in metadata["pipeline"]["workflow"]["components"].values()
316+
if declaration["implementation"]["kind"] == "onnx"
317+
}
318+
319+
320+
def test_parsed_workflow_can_materialize_the_policies_it_references(tmp_path):
321+
"""The generated sampler graphs travel with the parse result.
322+
323+
The document declares them as ``policies/*.onnx`` artifacts, so a caller
324+
that only had the metadata dict could not produce a loadable package.
325+
"""
326+
parsed = parse_comfyui_workflow(_DEFAULT_TXT2IMG)
327+
written = parsed.save_policy_components(str(tmp_path))
328+
assert written, "a diffusion workflow always generates sampler components"
329+
for artifact in _referenced_artifacts(parsed.metadata):
330+
if artifact.startswith("policies/"):
331+
assert (tmp_path / artifact).is_file(), artifact
332+
333+
334+
def test_conversion_writes_every_referenced_policy_artifact(tmp_path):
335+
convert_comfyui_workflow(_DEFAULT_TXT2IMG, None, str(tmp_path), compute_timesteps=False)
336+
with open(tmp_path / "inference_metadata.yaml", encoding="utf-8") as handle:
337+
metadata = yaml.safe_load(handle)
338+
policies = {
339+
artifact
340+
for artifact in _referenced_artifacts(metadata)
341+
if artifact.startswith("policies/")
342+
}
343+
assert policies
344+
for artifact in policies:
345+
assert (tmp_path / artifact).is_file(), artifact
346+
# And nothing stale: the reconciled solver's components are the only ones
347+
# written, so a package never ships a graph its document does not declare.
348+
written = {f"policies/{path.name}" for path in (tmp_path / "policies").iterdir()}
349+
assert written == policies
350+
351+
310352
def test_translated_metadata_matches_onnx_genai_schema():
311353
"""A ComfyUI-translated pipeline validates against onnx-genai's real schema."""
312354
import jsonschema

‎src/mobius/integrations/onnx_genai/convert.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,11 @@ def convert_comfyui_workflow(
217217
os.makedirs(output_dir, exist_ok=True)
218218
from mobius._model_package import ModelPackage
219219

220+
# Deliberately a fresh package rather than ``parsed_workflow.policy_components``:
221+
# the checkpoint's scheduler config can reconcile to a different solver than
222+
# the ComfyUI sampler implied, and reusing the parse-time package would leave
223+
# that run's components (say Euler's ``model_input_scale``) behind for a DDIM
224+
# document that never references them.
220225
package = ModelPackage({})
221226
use_karras = parsed_workflow.scheduler_spacing == "karras"
222227
use_exponential = parsed_workflow.scheduler_spacing == "exponential"

0 commit comments

Comments
 (0)