Skip to content

Commit b9c9043

Browse files
justinchubyCopilot
andauthored
Support compact SD and complete video diffusion workflows (#538)
## Summary - export BK-SDM checkpoints without a UNet mid-block - add encoder-only T5 export for CogVideoX - add typed DDIM epsilon/sample/v-prediction contracts - add model-agnostic video CFG, layout, unscale, causal-cache, and recurrence workflows - add typed cast/clamp adapters and nested artifact paths for image APIs/image edit ## Validation - 76 policy/workflow tests passed - earlier targeted model tests: 27 passed - real Stable Diffusion and CogVideoX packages validated and executed through ONNX GenAI --------- Signed-off-by: justinchuby <[email protected]> Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot <[email protected]> Copilot-Session: 39ff6824-d35f-4d3b-8f5f-043a7119a100
1 parent c047f77 commit b9c9043

27 files changed

Lines changed: 1505 additions & 164 deletions

‎src/mobius/__main__.py‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,9 @@ def _resolve_static_cache_task(model_type: str) -> ModelTask:
205205
raise SystemExit("Error: --max-length can only be used with --runtime onnx-genai.")
206206
if max_length is not None and max_length <= 0:
207207
raise SystemExit("Error: --max-length must be a positive integer.")
208+
guidance_scale = getattr(args, "guidance_scale", None)
209+
if guidance_scale is not None and args.runtime != "onnx-genai":
210+
raise SystemExit("Error: --guidance-scale can only be used with --runtime onnx-genai.")
208211

209212
# Validate static-cache + --task compatibility.
210213
if args.static_cache and args.task is not None:
@@ -469,6 +472,7 @@ def _save_package(
469472
config=config,
470473
source=source,
471474
revision=getattr(args, "revision", None),
475+
guidance_scale=getattr(args, "guidance_scale", None),
472476
)
473477
except ValueError as error:
474478
raise SystemExit(f"Error: {error}") from error
@@ -622,6 +626,7 @@ def _cmd_convert_comfyui(args: argparse.Namespace) -> None:
622626
args.checkpoint,
623627
args.output,
624628
sdxl=getattr(args, "sdxl", False),
629+
revision=args.revision,
625630
)
626631
wf = result.workflow
627632
print(f"Converted ComfyUI workflow -> {result.output_dir}")
@@ -846,6 +851,18 @@ def main(argv: list[str] | None = None) -> None:
846851
"with --config (local directory), they are copied from that directory."
847852
),
848853
)
854+
build_parser.add_argument(
855+
"--guidance-scale",
856+
type=float,
857+
default=None,
858+
metavar="SCALE",
859+
help=(
860+
"Classifier-free guidance scale for --runtime onnx-genai diffusion "
861+
"metadata. Required for conditioned diffusion pipelines so export does "
862+
"not guess a source pipeline's generation default; pass 1.0 explicitly "
863+
"for unguided generation."
864+
),
865+
)
849866
build_parser.add_argument(
850867
"--kv-cache-scale-file",
851868
dest="kv_cache_scale_file",
@@ -1005,6 +1022,11 @@ def main(argv: list[str] | None = None) -> None:
10051022
"scheduler config supplies the noise-schedule betas (Stable Diffusion "
10061023
"defaults are used when omitted).",
10071024
)
1025+
comfy_parser.add_argument(
1026+
"--revision",
1027+
default=None,
1028+
help="Pinned Hugging Face revision used to resolve the checkpoint scheduler config.",
1029+
)
10081030
comfy_parser.add_argument(
10091031
"--output", "-o", required=True, help="Output directory for the pipeline metadata."
10101032
)

‎src/mobius/generation/_policy_components.py‎

Lines changed: 79 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,7 @@ def build_boolean_not() -> PolicyComponent:
228228
keepdims=1,
229229
)
230230
continued = builder.op.Equal(any_done, builder.op.Constant(value_int=0))
231+
continued.dtype = ir.DataType.BOOL
231232
continued.shape = ir.Shape([1])
232233
builder.add_output(continued, "continue")
233234
return _component("mobius.policy.auxiliary@1", graph, {})
@@ -1255,6 +1256,7 @@ def ewma(old, sample):
12551256
)
12561257
next_k = op.Where(valid, computed_k, current_k)
12571258
next_estimates = op.Where(valid_col, computed_estimates, estimates)
1259+
next_k.dtype = ir.DataType.INT64
12581260
next_k.shape = ir.Shape(["batch"])
12591261
next_estimates.shape = ir.Shape(["batch", estimate_slots])
12601262
builder.add_output(next_k, "next_k")
@@ -1471,6 +1473,8 @@ def build_seeded_categorical_sampler() -> PolicyComponent:
14711473
op.Add(counter, op.Constant(value_int=1)),
14721474
counter,
14731475
)
1476+
token_ids.dtype = ir.DataType.INT64
1477+
next_counter.dtype = ir.DataType.INT64
14741478
_set_public_shape(logits, ["batch", "vocabulary"])
14751479
for value in (temperature, top_k, top_p, min_p, seed, counter, active, done):
14761480
_set_public_shape(value, ["batch"])
@@ -1573,6 +1577,9 @@ def build_eos_termination(*, row_selective: bool = False) -> PolicyComponent:
15731577
_set_public_shape(active, ["batch"])
15741578
_set_public_shape(done, ["batch"])
15751579
_set_public_shape(next_active, ["batch"])
1580+
next_active.dtype = ir.DataType.BOOL
1581+
done.dtype = ir.DataType.BOOL
1582+
continued.dtype = ir.DataType.BOOL
15761583
_set_public_shape(continued, [1])
15771584
builder.add_output(done, "done")
15781585
if row_selective:
@@ -1644,19 +1651,24 @@ def build_tensor_scale(dtype: ir.DataType = ir.DataType.FLOAT) -> PolicyComponen
16441651

16451652
def build_tensor_clamp(
16461653
dtype: ir.DataType = ir.DataType.FLOAT,
1654+
dims: Sequence[str] = ("batch", "channels", "height", "width"),
16471655
*,
16481656
minimum: float,
16491657
maximum: float,
1658+
output_dtype: ir.DataType | None = None,
16501659
) -> PolicyComponent:
1651-
"""Clamp a rank-4 tensor to an explicitly declared numeric range."""
1660+
"""Clamp an arbitrary-rank tensor to a declared runtime output range."""
16521661
graph, builder = _make_graph("tensor_clamp")
1653-
op = builder.op
1654-
tensor = builder.input("tensor", dtype, ["batch", "channels", "height", "width"])
1655-
clamped = op.Clip(
1656-
tensor,
1657-
op.Cast(op.Constant(value_float=minimum), to=dtype),
1658-
op.Cast(op.Constant(value_float=maximum), to=dtype),
1662+
tensor = builder.input("tensor", dtype, list(dims))
1663+
output_dtype = output_dtype or dtype
1664+
clamp_input = tensor if output_dtype == dtype else builder.op.Cast(tensor, to=output_dtype)
1665+
minimum_value = builder.op.CastLike(
1666+
builder.op.Constant(value_float=float(minimum)), clamp_input
16591667
)
1668+
maximum_value = builder.op.CastLike(
1669+
builder.op.Constant(value_float=float(maximum)), clamp_input
1670+
)
1671+
clamped = builder.op.Clip(clamp_input, minimum_value, maximum_value)
16601672
clamped.shape = tensor.shape
16611673
builder.add_output(clamped, "clamped")
16621674
return _component("mobius.policy.auxiliary@1", graph, {})
@@ -1673,7 +1685,10 @@ def build_zeros_like(dtype: ir.DataType = ir.DataType.FLOAT) -> PolicyComponent:
16731685
return _component("mobius.policy.auxiliary@1", graph, {})
16741686

16751687

1676-
def build_guidance_combine(dtype: ir.DataType = ir.DataType.FLOAT) -> PolicyComponent:
1688+
def build_guidance_combine(
1689+
dtype: ir.DataType = ir.DataType.FLOAT,
1690+
latent_dims: Sequence[str] = ("batch", "channels", "height", "width"),
1691+
) -> PolicyComponent:
16771692
"""Combine two conditioned estimates by a per-row guidance scale.
16781693
16791694
``estimate = unconditional + scale * (conditional - unconditional)`` is the
@@ -1682,13 +1697,14 @@ def build_guidance_combine(dtype: ir.DataType = ir.DataType.FLOAT) -> PolicyComp
16821697
"""
16831698
graph, builder = _make_graph("guidance_combine")
16841699
op = builder.op
1685-
unconditional = builder.input(
1686-
"unconditional", dtype, ["batch", "channels", "height", "width"]
1687-
)
1688-
conditional = builder.input("conditional", dtype, ["batch", "channels", "height", "width"])
1700+
unconditional = builder.input("unconditional", dtype, list(latent_dims))
1701+
conditional = builder.input("conditional", dtype, list(latent_dims))
16891702
scale = builder.input("scale", ir.DataType.FLOAT, ["batch"])
1690-
# (batch,) -> (batch, 1, 1, 1) so the row scale broadcasts over the latent.
1691-
factor = op.Unsqueeze(op.Cast(scale, to=dtype), op.Constant(value_ints=[1, 2, 3]))
1703+
# (batch,) -> (batch, 1, ..., 1) so the row scale broadcasts over the latent.
1704+
factor = op.Unsqueeze(
1705+
op.Cast(scale, to=dtype),
1706+
op.Constant(value_ints=list(range(1, len(latent_dims)))),
1707+
)
16921708
estimate = op.Add(unconditional, op.Mul(factor, op.Sub(conditional, unconditional)))
16931709
estimate.shape = unconditional.shape
16941710
builder.add_output(estimate, "estimate")
@@ -1710,7 +1726,7 @@ def build_tensor_cast(
17101726
target_dtype: ir.DataType,
17111727
dims: Sequence[str] = ("batch", "heads", "sequence", "head_dim"),
17121728
) -> PolicyComponent:
1713-
"""Cast a typed tensor at an explicit component precision boundary."""
1729+
"""Cast an arbitrary-rank tensor at an explicit component precision boundary."""
17141730
graph, builder = _make_graph("tensor_cast")
17151731
value = builder.input("value", source_dtype, list(dims))
17161732
cast = builder.op.Cast(value, to=target_dtype)
@@ -2168,8 +2184,9 @@ def build_ddim_solver_step(
21682184
latent_dims: Sequence[str] = _IMAGE_LATENT_DIMS,
21692185
*,
21702186
clip_sample_range: float | None = None,
2187+
prediction_type: str = "epsilon",
21712188
) -> PolicyComponent:
2172-
"""Build the deterministic DDIM update (``eta = 0``, epsilon prediction).
2189+
"""Build the deterministic DDIM update (``eta = 0``).
21732190
21742191
``schedule`` holds the cumulative alpha of every denoising step followed by
21752192
the alpha of the final step's predecessor, so entry ``i + 1`` is the
@@ -2181,8 +2198,12 @@ def build_ddim_solver_step(
21812198
``clip_sample_range`` reproduces schedulers configured with
21822199
``clip_sample=True``, which clamp the predicted clean sample before the
21832200
reverse step. ``latent_dims`` names the latent axes, so the same update
2184-
serves image and video latents.
2201+
serves image and video latents. ``prediction_type`` selects the scheduler's
2202+
architecture-neutral output interpretation: ``epsilon``, ``sample``, or
2203+
``v_prediction``.
21852204
"""
2205+
if prediction_type not in {"epsilon", "sample", "v_prediction"}:
2206+
raise ValueError(f"unsupported DDIM prediction_type {prediction_type!r}")
21862207
graph, builder = _make_graph("ddim_solver_step")
21872208
op = builder.op
21882209
sample = builder.input("sample", dtype, list(latent_dims))
@@ -2197,16 +2218,28 @@ def build_ddim_solver_step(
21972218
op.Cast(op.Gather(schedule, next_step, axis=0), to=dtype), broadcast_axes
21982219
)
21992220
one = op.CastLike(op.Constant(value_float=1.0), sample)
2200-
# Recover the predicted clean latent, then re-noise it to alpha_prev.
2201-
pred_original = op.Div(
2202-
op.Sub(sample, op.Mul(op.Sqrt(op.Sub(one, alpha)), derivative)), op.Sqrt(alpha)
2203-
)
2221+
alpha_sqrt = op.Sqrt(alpha)
2222+
beta_sqrt = op.Sqrt(op.Sub(one, alpha))
2223+
if prediction_type == "epsilon":
2224+
pred_original = op.Div(op.Sub(sample, op.Mul(beta_sqrt, derivative)), alpha_sqrt)
2225+
pred_epsilon = derivative
2226+
elif prediction_type == "sample":
2227+
pred_original = derivative
2228+
epsilon_numerator = op.Sub(sample, op.Mul(alpha_sqrt, pred_original))
2229+
pred_epsilon = op.Where(
2230+
op.Greater(beta_sqrt, op.CastLike(op.Constant(value_float=0.0), sample)),
2231+
op.Div(epsilon_numerator, beta_sqrt),
2232+
op.CastLike(op.Constant(value_float=0.0), sample),
2233+
)
2234+
else:
2235+
pred_original = op.Sub(op.Mul(alpha_sqrt, sample), op.Mul(beta_sqrt, derivative))
2236+
pred_epsilon = op.Add(op.Mul(alpha_sqrt, derivative), op.Mul(beta_sqrt, sample))
22042237
if clip_sample_range is not None:
22052238
limit = op.CastLike(op.Constant(value_float=float(clip_sample_range)), sample)
22062239
pred_original = op.Clip(pred_original, op.Neg(limit), limit)
22072240
next_sample = op.Add(
22082241
op.Mul(op.Sqrt(alpha_prev), pred_original),
2209-
op.Mul(op.Sqrt(op.Sub(one, alpha_prev)), derivative),
2242+
op.Mul(op.Sqrt(op.Sub(one, alpha_prev)), pred_epsilon),
22102243
)
22112244
_set_public_shape(next_sample, list(latent_dims))
22122245
builder.add_output(next_sample, "next_state")
@@ -2349,6 +2382,7 @@ def build_true_cfg(
23492382

23502383

23512384
SOLVER_BUILDERS = {
2385+
"ddim": build_ddim_solver_step,
23522386
"euler": build_euler_solver_step,
23532387
"multistep": build_multistep_solver_step,
23542388
}
@@ -2737,12 +2771,17 @@ def build_schedule_history_append(dtype: ir.DataType) -> PolicyComponent:
27372771
history = builder.input("history", dtype, ["batch", "history"])
27382772
timestep = builder.input("timestep", dtype, ["batch"])
27392773
updated = op.Concat(history, op.Unsqueeze(timestep, op.Constant(value_ints=[1])), axis=1)
2740-
_set_public_shape(updated, ["batch", "history"])
2774+
# Appending changes the temporal extent, so the output must not reuse the
2775+
# input symbol: runtimes may otherwise preallocate the old zero-length shape.
2776+
_set_public_shape(updated, ["batch", "next_history"])
27412777
builder.add_output(updated, "next")
27422778
return _component("mobius.policy.auxiliary@1", graph, {})
27432779

27442780

2745-
def build_video_decode_chunk_count(latent_frame_axis: int = 2) -> PolicyComponent:
2781+
def build_video_decode_chunk_count(
2782+
latent_frame_axis: int = 2,
2783+
dtype: ir.DataType = ir.DataType.FLOAT,
2784+
) -> PolicyComponent:
27462785
"""Number of causal decode chunks a latent clip is split into.
27472786
27482787
Mirrors ``AutoencoderKLCogVideoX._decode``: ``max(latent_frames // 2, 1)``.
@@ -2751,7 +2790,7 @@ def build_video_decode_chunk_count(latent_frame_axis: int = 2) -> PolicyComponen
27512790
op = builder.op
27522791
latent = builder.input(
27532792
"latent",
2754-
ir.DataType.FLOAT,
2793+
dtype,
27552794
["batch", "channels", "latent_frames", "height", "width"],
27562795
)
27572796
frames = op.Shape(latent, start=latent_frame_axis, end=latent_frame_axis + 1)
@@ -2764,7 +2803,10 @@ def build_video_decode_chunk_count(latent_frame_axis: int = 2) -> PolicyComponen
27642803
return _component("mobius.policy.auxiliary@1", graph, {})
27652804

27662805

2767-
def build_video_decode_chunk(latent_frame_axis: int = 2) -> PolicyComponent:
2806+
def build_video_decode_chunk(
2807+
latent_frame_axis: int = 2,
2808+
dtype: ir.DataType = ir.DataType.FLOAT,
2809+
) -> PolicyComponent:
27682810
"""Slice the latent frames belonging to one causal decode chunk.
27692811
27702812
Reproduces the reference chunk walk, where the odd frame left over by the
@@ -2778,7 +2820,7 @@ def build_video_decode_chunk(latent_frame_axis: int = 2) -> PolicyComponent:
27782820
op = builder.op
27792821
latent = builder.input(
27802822
"latent",
2781-
ir.DataType.FLOAT,
2823+
dtype,
27822824
["batch", "channels", "latent_frames", "height", "width"],
27832825
)
27842826
step = builder.input("step", ir.DataType.INT64, ["batch"])
@@ -2846,7 +2888,10 @@ def build_video_conv_cache_initializer(
28462888
return _component("mobius.policy.auxiliary@1", graph, {})
28472889

28482890

2849-
def build_video_latent_permute(perm: list[int]) -> PolicyComponent:
2891+
def build_video_latent_permute(
2892+
perm: list[int],
2893+
dtype: ir.DataType = ir.DataType.FLOAT,
2894+
) -> PolicyComponent:
28502895
"""Reorder a video latent between the denoiser and VAE layouts.
28512896
28522897
CogVideoX denoises ``[batch, frames, channels, height, width]`` but decodes
@@ -2855,22 +2900,21 @@ def build_video_latent_permute(perm: list[int]) -> PolicyComponent:
28552900
"""
28562901
graph, builder = _make_graph("video_latent_permute")
28572902
op = builder.op
2858-
source = builder.input(
2859-
"latent", ir.DataType.FLOAT, ["batch", "frames", "channels", "height", "width"]
2860-
)
2903+
source = builder.input("latent", dtype, ["batch", "frames", "channels", "height", "width"])
28612904
permuted = op.Transpose(source, perm=perm)
28622905
_set_public_shape(permuted, ["batch", "channels", "frames", "height", "width"])
28632906
builder.add_output(permuted, "permuted")
28642907
return _component("mobius.policy.auxiliary@1", graph, {})
28652908

28662909

2867-
def build_video_latent_unscale(scaling_factor: float) -> PolicyComponent:
2910+
def build_video_latent_unscale(
2911+
scaling_factor: float,
2912+
dtype: ir.DataType = ir.DataType.FLOAT,
2913+
) -> PolicyComponent:
28682914
"""Undo the autoencoder's latent scaling before decoding."""
28692915
graph, builder = _make_graph("video_latent_unscale")
28702916
op = builder.op
2871-
latent = builder.input(
2872-
"latent", ir.DataType.FLOAT, ["batch", "channels", "frames", "height", "width"]
2873-
)
2917+
latent = builder.input("latent", dtype, ["batch", "channels", "frames", "height", "width"])
28742918
unscaled = op.Div(latent, op.CastLike(op.Constant(value_float=scaling_factor), latent))
28752919
_set_public_shape(unscaled, ["batch", "channels", "frames", "height", "width"])
28762920
builder.add_output(unscaled, "unscaled")

0 commit comments

Comments
 (0)