Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Format the diffusion auto-optimizer and LTX-2.5 prequant files (#13526)

Daniel Han4c9f6c70654d
diff --git a/studio/backend/core/inference/diffusion_attention.py b/studio/backend/core/inference/diffusion_attention.py
index 944623903ca..33d84bc5b54 100644
--- a/studio/backend/core/inference/diffusion_attention.py
+++ b/studio/backend/core/inference/diffusion_attention.py
@@ -1829,7 +1829,6 @@ def _attention_dits(pipe: Any) -> list:
families carry (Ideogram's ``unconditional_transformer``, an MoE ``transformer_2``). The
backend must be set on ALL of them, else the second DiT keeps the native default."""
from .diffusion_autoopt.targets import denoiser_dits
-
return denoiser_dits(pipe)
diff --git a/studio/backend/core/inference/diffusion_autoopt/apply.py b/studio/backend/core/inference/diffusion_autoopt/apply.py
index 739d87a709e..23c64d06b4e 100644
--- a/studio/backend/core/inference/diffusion_autoopt/apply.py
+++ b/studio/backend/core/inference/diffusion_autoopt/apply.py
@@ -26,7 +26,9 @@ VIDEO_COMPILE_CACHE_DECLINE = (
"not wired for video loads yet (process-wide inductor cache dir shared with the image backend)"
)
-_CURRENT_AUDIT: contextvars.ContextVar = contextvars.ContextVar("unsloth_autoopt_audit", default = None)
+_CURRENT_AUDIT: contextvars.ContextVar = contextvars.ContextVar(
+ "unsloth_autoopt_audit", default = None
+)
# ---------------------------------------------------------------------------------------------------------- audit
@@ -39,7 +41,12 @@ class Audit:
entries: dict[str, dict] = field(default_factory = dict)
generic: bool = False
- def record(self, step: str, status: str, reason: Optional[str] = None) -> None:
+ def record(
+ self,
+ step: str,
+ status: str,
+ reason: Optional[str] = None,
+ ) -> None:
prev = self.entries.get(step)
# A failure is never overwritten by a later "declined"; an engagement upgrades a decline (dual-DiT views).
if prev is not None:
@@ -87,8 +94,10 @@ class _AuditingLogger:
def __getattr__(self, name: str) -> Any:
inner = self.__dict__.get("_inner")
if inner is None:
+
def _noop(*a: Any, **k: Any) -> None:
return None
+
return _noop
return getattr(inner, name)
@@ -133,7 +142,9 @@ def _ltx_static_pre(view: Any, family: Any) -> None:
def _ltx_stg_post(view: Any, family: Any, applied: dict, logger: Any) -> Optional[dict]:
if applied.get("compiled"):
from ..video_ltx2 import install_stg_compile_adapter # noqa: PLC0415
- install_stg_compile_adapter(getattr(view, getattr(family, "denoiser_attr", "transformer"), None))
+ install_stg_compile_adapter(
+ getattr(view, getattr(family, "denoiser_attr", "transformer"), None)
+ )
return None
@@ -211,10 +222,16 @@ def install_compile_patches(
# ------------------------------------------------------------------------------------------------ the speed layer
-def _generic_family_view(view: Any, family: Any, plan: plan_mod.OptimizationPlan, logger: Any) -> Any:
+def _generic_family_view(
+ view: Any, family: Any, plan: plan_mod.OptimizationPlan, logger: Any
+) -> Any:
"""For a family with no data: trial-compile discovered blocks, or decline the compile with the plan's reason."""
step = plan.step("compiled")
- if step is not None and not step.attempt and str(step.reason or "").startswith(plan_mod.GRAPH_BREAK_DECLINE):
+ if (
+ step is not None
+ and not step.attempt
+ and str(step.reason or "").startswith(plan_mod.GRAPH_BREAK_DECLINE)
+ ):
# Graph-break suspects in a discovered block: decline rather than compile a graph that breaks every call.
if logger is not None:
logger.info("diffusion.autoopt: compile declined for %s: %s", plan.family, step.reason)
@@ -243,11 +260,13 @@ def _family_with(family: Any, **overrides: Any) -> Any:
try:
return replace(family, **overrides)
except Exception: # noqa: BLE001 - not a dataclass: a thin proxy
+
class _Proxy:
def __getattr__(self, name: str) -> Any:
if name in overrides:
return overrides[name]
return getattr(family, name)
+
return _Proxy()
@@ -323,7 +342,12 @@ def _safe_applies(hook: FamilyHook, family: Any) -> bool:
return False
-def record_applied(audit: Audit, applied: dict, plan: Optional[plan_mod.OptimizationPlan], view: Any = None) -> None:
+def record_applied(
+ audit: Audit,
+ applied: dict,
+ plan: Optional[plan_mod.OptimizationPlan],
+ view: Any = None,
+) -> None:
"""Fold an ``apply_speed_optims`` result into the audit with the plan's reasons for what did not engage."""
for name, on in applied.items():
if on:
@@ -375,7 +399,11 @@ def record_load_steps(
)
-def finalize(audit: Optional[Audit], speed_optims: Any, resolved: Optional[dict] = None) -> Optional[list]:
+def finalize(
+ audit: Optional[Audit],
+ speed_optims: Any,
+ resolved: Optional[dict] = None,
+) -> Optional[list]:
"""Reconcile the audit with the final ``speed_optims`` (post-placement arming may engage or drop a step) and attach
it to ``resolved["speed_mode"]["steps"]``. Returns the step list; never raises."""
if audit is None:
@@ -391,7 +419,12 @@ def _finalize(audit: Audit, speed_optims: Any, resolved: Optional[dict]) -> list
for name, entry in list(audit.entries.items()):
if name in final and entry["status"] != "engaged":
audit.entries[name] = {"status": "engaged", "reason": None}
- elif entry["status"] == "engaged" and name in plan_mod.STEP_ORDER and name not in final and _is_speed_key(name):
+ elif (
+ entry["status"] == "engaged"
+ and name in plan_mod.STEP_ORDER
+ and name not in final
+ and _is_speed_key(name)
+ ):
audit.entries[name] = {"status": "declined", "reason": "disengaged after placement"}
for name in final:
if name not in audit.entries:
@@ -406,9 +439,20 @@ def _finalize(audit: Audit, speed_optims: Any, resolved: Optional[dict]) -> list
_SPEED_KEYS = frozenset(
{
- "channels_last", "vae_fp16_decode", "vae_single_frame", "vae_fused", "cudnn_benchmark", "tf32",
- "fp16_accum", "fused_qkv", "compiled", "compiled_dequant", "rocm_query_chunks", "compiled_vae_decode",
- "cuda_graph", "int8_gemm",
+ "channels_last",
+ "vae_fp16_decode",
+ "vae_single_frame",
+ "vae_fused",
+ "cudnn_benchmark",
+ "tf32",
+ "fp16_accum",
+ "fused_qkv",
+ "compiled",
+ "compiled_dequant",
+ "rocm_query_chunks",
+ "compiled_vae_decode",
+ "cuda_graph",
+ "int8_gemm",
}
)
diff --git a/studio/backend/core/inference/diffusion_autoopt/patches.py b/studio/backend/core/inference/diffusion_autoopt/patches.py
index c9969b32c6d..220ac13bf9e 100644
--- a/studio/backend/core/inference/diffusion_autoopt/patches.py
+++ b/studio/backend/core/inference/diffusion_autoopt/patches.py
@@ -120,9 +120,7 @@ def _unresolved_names(tree: ast.AST, fn_globals: dict) -> list[str]:
bound.add((alias.asname or alias.name).split(".")[0])
elif isinstance(node, ast.ExceptHandler) and node.name:
bound.add(node.name)
- return sorted(
- n for n in loaded - bound if n not in fn_globals and not hasattr(builtins, n)
- )
+ return sorted(n for n in loaded - bound if n not in fn_globals and not hasattr(builtins, n))
def splice_source(
@@ -146,7 +144,9 @@ def splice_source(
if fingerprints is not None:
digest = source_digest(raw)
if digest not in set(fingerprints):
- raise SpliceError(f"source differs from the version this was written against ({digest})")
+ raise SpliceError(
+ f"source differs from the version this was written against ({digest})"
+ )
src = _source(raw)
if src is None:
raise SpliceError("source unavailable")
@@ -228,7 +228,10 @@ class PatchSpec:
@property
def kill_env(self) -> str:
- return "UNSLOTH_DIFFUSION_PATCH_" + "".join(c if c.isalnum() else "_" for c in self.name).upper()
+ return (
+ "UNSLOTH_DIFFUSION_PATCH_"
+ + "".join(c if c.isalnum() else "_" for c in self.name).upper()
+ )
@dataclass
@@ -288,7 +291,11 @@ def install_stage(
if ctx.backend not in spec.backends:
continue
if spec.classes:
- subject = ctx.transformer if ctx.transformer is not None else getattr(ctx.pipe, "transformer", None)
+ subject = (
+ ctx.transformer
+ if ctx.transformer is not None
+ else getattr(ctx.pipe, "transformer", None)
+ )
if _class_name(subject) not in spec.classes:
continue
if _env_off(spec.kill_env):
diff --git a/studio/backend/core/inference/diffusion_autoopt/plan.py b/studio/backend/core/inference/diffusion_autoopt/plan.py
index 200c8ab5263..012728a6049 100644
--- a/studio/backend/core/inference/diffusion_autoopt/plan.py
+++ b/studio/backend/core/inference/diffusion_autoopt/plan.py
@@ -99,7 +99,6 @@ DISCOVER_ENV = "UNSLOTH_DIFFUSION_AUTOOPT_DISCOVER"
def discovery_enabled() -> bool:
import os # noqa: PLC0415
-
return (os.environ.get(DISCOVER_ENV) or "").strip().lower() not in ("0", "off", "false", "no")
@@ -142,7 +141,9 @@ def build_plan(
candidates = dits or [m for m in [targets.denoiser_unet(pipe)] if m is not None]
if generic and not candidates:
candidates = targets.discovered_only(pipe, family)
- profiles = [p for p in (profile_model(m) for m in candidates if hasattr(m, "forward")) if p is not None]
+ profiles = [
+ p for p in (profile_model(m) for m in candidates if hasattr(m, "forward")) if p is not None
+ ]
plan = OptimizationPlan(
backend = backend,
family = getattr(family, "name", None),
@@ -151,7 +152,11 @@ def build_plan(
generic = generic,
)
- def add(name: str, attempt: bool, reason: Optional[str] = None) -> None:
+ def add(
+ name: str,
+ attempt: bool,
+ reason: Optional[str] = None,
+ ) -> None:
plan.steps.append(PlannedStep(name, attempt, reason))
if mode == SPEED_OFF:
@@ -164,11 +169,18 @@ def build_plan(
compile_reason: Optional[str] = None
if mode == SPEED_EAGER:
compile_reason = "eager tier does not compile"
- elif mode == SPEED_DEFAULT and is_gguf and on_cuda and getattr(family, "supports_torch_compile", True):
+ elif (
+ mode == SPEED_DEFAULT
+ and is_gguf
+ and on_cuda
+ and getattr(family, "supports_torch_compile", True)
+ ):
compile_reason = "GGUF compiles the dequant op chain instead"
else:
compile_reason = compile_ineligible_reason(target, family)
- if compile_reason is None and ds.fp16_unet_offloaded(target, pipe, offload_active = offload_active):
+ if compile_reason is None and ds.fp16_unet_offloaded(
+ target, pipe, offload_active = offload_active
+ ):
compile_reason = "offloaded fp16 U-Net stays eager (fused QKV costs more transfer than compile saves)"
if compile_reason is None and not candidates:
compile_reason = "no denoiser transformer or whole-compile U-Net"
@@ -187,7 +199,9 @@ def build_plan(
# No measured data: a discovered block whose forward host-syncs would graph-break on every call.
for p in profiles:
if not p.declared_blocks and p.graph_break_suspects:
- suspects = "; ".join(f"{k}: {', '.join(v)}" for k, v in p.graph_break_suspects.items())
+ suspects = "; ".join(
+ f"{k}: {', '.join(v)}" for k, v in p.graph_break_suspects.items()
+ )
step = plan.step("compiled")
step.attempt = False
step.reason = f"{GRAPH_BREAK_DECLINE} ({p.class_name}: {suspects})"
@@ -198,7 +212,11 @@ def build_plan(
)
add("tf32", mode == SPEED_MAX and on_cuda, None if mode == SPEED_MAX else "max tier only")
if not getattr(family, "cudnn_benchmark", True):
- add("cudnn_benchmark", False, "family keeps cudnn.benchmark off (per-process conv pick changes pixels)")
+ add(
+ "cudnn_benchmark",
+ False,
+ "family keeps cudnn.benchmark off (per-process conv pick changes pixels)",
+ )
elif not on_cuda:
add("cudnn_benchmark", False, "not a CUDA device")
else:
@@ -224,7 +242,9 @@ def compile_cache_kwargs(
# A step cache or planned offload graph-breaks, so the bundle keys on the fullgraph the compile uses.
"fullgraph": bool(fullgraph),
# max compiles DiTs with automatic dynamic (None), as does the default tier for torchao weights.
- "dynamic": ds.compile_dynamic(transformer, True if deferred else (None if mode == SPEED_MAX else True)),
+ "dynamic": ds.compile_dynamic(
+ transformer, True if deferred else (None if mode == SPEED_MAX else True)
+ ),
"mode": "max-autotune-no-cudagraphs" if mode == SPEED_MAX else "default",
"vae_decode": ds.vae_decode_compile_allowed(pipe, mode),
}
diff --git a/studio/backend/core/inference/diffusion_autoopt/profile.py b/studio/backend/core/inference/diffusion_autoopt/profile.py
index 0d09ad2e6fa..f9dbabf929b 100644
--- a/studio/backend/core/inference/diffusion_autoopt/profile.py
+++ b/studio/backend/core/inference/diffusion_autoopt/profile.py
@@ -156,7 +156,11 @@ def profile_model(model: Any) -> Optional[ModelProfile]:
return None
cls = type(model)
forward = getattr(cls, "forward", None)
- key = (f"{cls.__module__}.{cls.__qualname__}", source_digest(forward) if forward else None, _diffusers_version())
+ key = (
+ f"{cls.__module__}.{cls.__qualname__}",
+ source_digest(forward) if forward else None,
+ _diffusers_version(),
+ )
with _LOCK:
cached = _CACHE.get(key)
if cached is not None:
@@ -164,7 +168,6 @@ def profile_model(model: Any) -> Optional[ModelProfile]:
declared = tuple(getattr(cls, "_repeated_blocks", None) or ())
try:
from ..diffusion_regional_compile import discover_repeated_blocks, verified_repeated_blocks # noqa: PLC0415
-
verified = tuple(verified_repeated_blocks(cls.__name__))
discovered = tuple(discover_repeated_blocks(model))
except Exception: # noqa: BLE001
diff --git a/studio/backend/core/inference/diffusion_autoopt/runtime.py b/studio/backend/core/inference/diffusion_autoopt/runtime.py
index e6633159668..1388d797f78 100644
--- a/studio/backend/core/inference/diffusion_autoopt/runtime.py
+++ b/studio/backend/core/inference/diffusion_autoopt/runtime.py
@@ -22,7 +22,6 @@ from ..diffusion_multistage import encode_once, hold_denoiser_between_calls # n
def runner_opens_cache_context(runner: Any) -> bool:
from ..diffusion_cache import _pipeline_opens_cache_context # noqa: PLC0415
-
return _pipeline_opens_cache_context(runner)
@@ -34,7 +33,9 @@ def step_cache_runner_reason(base: Any, runner: Any) -> Optional[str]:
return None
if runner_opens_cache_context(runner):
return None
- return f"{type(runner).__name__} opens no cache_context, so the step cache stays off for this call"
+ return (
+ f"{type(runner).__name__} opens no cache_context, so the step cache stays off for this call"
+ )
def auto_cache_steps(base: Any, runner: Any, steps: int) -> tuple[int, Optional[str]]:
diff --git a/studio/backend/core/inference/diffusion_autoopt/targets.py b/studio/backend/core/inference/diffusion_autoopt/targets.py
index b406e934a71..c0f80b72499 100644
--- a/studio/backend/core/inference/diffusion_autoopt/targets.py
+++ b/studio/backend/core/inference/diffusion_autoopt/targets.py
@@ -33,7 +33,16 @@ PARTITION_ATTRS: tuple[str, ...] = ("transformer_ref",)
UNET_WHOLE_COMPILE: frozenset[str] = frozenset({"UNet2DConditionModel"})
# Component names that are never a denoiser even when they are a ModelMixin with repeated blocks.
-_NOT_DENOISERS = ("vae", "controlnet", "text_encoder", "image_encoder", "audio", "vocoder", "upsampler", "connector")
+_NOT_DENOISERS = (
+ "vae",
+ "controlnet",
+ "text_encoder",
+ "image_encoder",
+ "audio",
+ "vocoder",
+ "upsampler",
+ "connector",
+)
def _unique(modules: Iterable[Any]) -> list:
diff --git a/studio/backend/core/inference/diffusion_transformer_quant.py b/studio/backend/core/inference/diffusion_transformer_quant.py
index edfb09e05ea..b6791430dca 100644
--- a/studio/backend/core/inference/diffusion_transformer_quant.py
+++ b/studio/backend/core/inference/diffusion_transformer_quant.py
@@ -260,7 +260,9 @@ _INT8_FAMILY_CONVROT_VARIANT_REPOS: dict[str, tuple[str, ...]] = {
# Families whose int8 runs ConvRot unless the env turns it off; the rest stay opt-in (``=1``). For ltx-2.5 this only
# picks the hosted rotated file (the env's ``0`` picks the plain one).
-_INT8_FAMILY_CONVROT_DEFAULT_ON: frozenset[str] = frozenset({"qwen-image-2.1", "z-image", "ltx-2.5"})
+_INT8_FAMILY_CONVROT_DEFAULT_ON: frozenset[str] = frozenset(
+ {"qwen-image-2.1", "z-image", "ltx-2.5"}
+)
INT8_CONVROT_ENV = "UNSLOTH_DIFFUSION_INT8_CONVROT"
diff --git a/studio/backend/tests/test_diffusion_autoopt_core.py b/studio/backend/tests/test_diffusion_autoopt_core.py
index 0ec1799c9e3..c7791492595 100644
--- a/studio/backend/tests/test_diffusion_autoopt_core.py
+++ b/studio/backend/tests/test_diffusion_autoopt_core.py
@@ -72,7 +72,6 @@ def test_body_has_and_once():
def test_arch_patches_keep_a_monkeypatchable_body_has():
from core.inference import diffusion_arch_patches
-
assert diffusion_arch_patches._body_has is ap.body_has
@@ -157,7 +156,9 @@ def test_registry_lifecycle_kill_switch_speed_only_and_failures(scratch_registry
log = types.SimpleNamespace(warning = lambda *a: warnings.append(a))
pipe = types.SimpleNamespace(transformer = type("MyDiT", (), {})())
- res = ap.install_stage(ap.STAGE_LOAD, ap.PatchContext(pipe = pipe, speed_mode = "default", logger = log), audit = audit)
+ res = ap.install_stage(
+ ap.STAGE_LOAD, ap.PatchContext(pipe = pipe, speed_mode = "default", logger = log), audit = audit
+ )
assert res == {"fuse": True} and state["on"]
assert audit.entries["patch:fuse"]["status"] == "engaged"
assert audit.entries["patch:broken"]["status"] == "failed"
@@ -173,7 +174,10 @@ def test_registry_lifecycle_kill_switch_speed_only_and_failures(scratch_registry
monkeypatch.setenv("UNSLOTH_DIFFUSION_PATCH_FUSE", "0")
audit2 = ao.new_audit(backend = "image", family = None)
ap.install_stage(ap.STAGE_LOAD, ap.PatchContext(pipe = pipe, speed_mode = "max"), audit = audit2)
- assert audit2.entries["patch:fuse"] == {"status": "declined", "reason": "UNSLOTH_DIFFUSION_PATCH_FUSE=0"}
+ assert audit2.entries["patch:fuse"] == {
+ "status": "declined",
+ "reason": "UNSLOTH_DIFFUSION_PATCH_FUSE=0",
+ }
monkeypatch.delenv("UNSLOTH_DIFFUSION_PATCH_FUSE")
ap.install_stage(ap.STAGE_LOAD, ap.PatchContext(pipe = pipe, speed_mode = "max"))
@@ -238,7 +242,9 @@ def test_denoiser_dits_contract_is_unchanged():
from core.inference import diffusion_attention, diffusion_speed
a, b = object(), object()
- pipe = types.SimpleNamespace(transformer = a, transformer_2 = b, unconditional_transformer = a, unet = object())
+ pipe = types.SimpleNamespace(
+ transformer = a, transformer_2 = b, unconditional_transformer = a, unet = object()
+ )
assert targets.denoiser_dits(pipe) == [a, b]
assert diffusion_speed._denoiser_dits(pipe) == [a, b]
assert diffusion_attention._attention_dits(pipe) == [a, b]
@@ -283,10 +289,12 @@ def _toy_model(block_src_sync: bool):
self.lin = torch.nn.Linear(4, 4)
if block_src_sync:
+
def forward(self, x):
k = int(x.abs().max().item())
return self.lin(x) + k
else:
+
def forward(self, x):
return self.lin(x)
@@ -325,7 +333,6 @@ def test_profile_discovers_blocks_and_is_cached():
# -------------------------------------------------------------------------------------------- plan / generic
def _target():
import torch
-
return types.SimpleNamespace(
device = "cuda", backend = "cuda", dtype = torch.bfloat16, supports_default_torch_compile = True
)
@@ -354,7 +361,11 @@ def test_plan_reasons_mirror_the_primitive_gates():
assert eager.reason("compiled") == "eager tier does not compile"
-def _generic_run(model, monkeypatch, env = None):
+def _generic_run(
+ model,
+ monkeypatch,
+ env = None,
+):
from core.inference import diffusion_speed as ds
if env is not None:
@@ -422,8 +433,12 @@ def test_registered_family_passes_through_untouched():
return {"compiled": False}
ao.run_speed_layer(
- types.SimpleNamespace(transformer = None), _target(), family = fam, backend = "image",
- speed_mode = "default", apply = apply,
+ types.SimpleNamespace(transformer = None),
+ _target(),
+ family = fam,
+ backend = "image",
+ speed_mode = "default",
+ apply = apply,
)
assert seen["family"] is fam
@@ -467,7 +482,9 @@ def test_compile_cache_kwargs_match_the_former_inline_dicts():
"vae_decode": ds.vae_decode_compile_allowed(pipe, mode),
**({"below_hooks": True} if below else {}),
}
- got = plan_mod.compile_cache_kwargs(pipe, speed_mode = mode, fullgraph = True, offload_below_hooks = below)
+ got = plan_mod.compile_cache_kwargs(
+ pipe, speed_mode = mode, fullgraph = True, offload_below_hooks = below
+ )
assert got == want
deferred = plan_mod.compile_cache_kwargs(
pipe, speed_mode = "max", fullgraph = False, offload_below_hooks = False, deferred = True
@@ -524,11 +541,19 @@ def test_video_family_hooks_are_data():
seen["static"] = getattr(dit, "_unsloth_compile_static", False)
return {"compiled": False, "cudnn_benchmark": False}
- ao.run_speed_layer(view, _target(), family = ltx, backend = "video", speed_mode = "default", apply = apply)
+ ao.run_speed_layer(
+ view, _target(), family = ltx, backend = "video", speed_mode = "default", apply = apply
+ )
assert seen["static"] is True
image_dit = types.SimpleNamespace()
ao.run_speed_layer(
- types.SimpleNamespace(transformer = image_dit), _target(), family = ltx, backend = "image",
- speed_mode = "default", apply = apply,
+ types.SimpleNamespace(transformer = image_dit),
+ _target(),
+ family = ltx,
+ backend = "image",
+ speed_mode = "default",
+ apply = apply,
)
- assert not hasattr(image_dit, "_unsloth_compile_static") # video hooks never run on the image backend
+ assert not hasattr(
+ image_dit, "_unsloth_compile_static"
+ ) # video hooks never run on the image backend
diff --git a/studio/backend/tests/test_diffusion_autoopt_parity.py b/studio/backend/tests/test_diffusion_autoopt_parity.py
index 36625506ea6..afb244c9ba5 100644
--- a/studio/backend/tests/test_diffusion_autoopt_parity.py
+++ b/studio/backend/tests/test_diffusion_autoopt_parity.py
@@ -117,13 +117,21 @@ def _stub_denoiser(name: str) -> Any:
def _image_pipe(fam: Any) -> Any:
pipe = types.SimpleNamespace()
- setattr(pipe, getattr(fam, "denoiser_attr", "transformer") or "transformer", _stub_denoiser(fam.transformer_class))
+ setattr(
+ pipe,
+ getattr(fam, "denoiser_attr", "transformer") or "transformer",
+ _stub_denoiser(fam.transformer_class),
+ )
return pipe
def _video_pipe(fam: Any) -> Any:
pipe = types.SimpleNamespace()
- setattr(pipe, getattr(fam, "denoiser_attr", "transformer") or "transformer", _stub_denoiser(fam.transformer_class))
+ setattr(
+ pipe,
+ getattr(fam, "denoiser_attr", "transformer") or "transformer",
+ _stub_denoiser(fam.transformer_class),
+ )
if getattr(fam, "is_moe", False):
pipe.transformer_2 = _stub_denoiser(fam.transformer_class)
return pipe
@@ -131,7 +139,6 @@ def _video_pipe(fam: Any) -> Any:
def _target(dtype_name: str) -> Any:
import torch
-
return types.SimpleNamespace(
device = "cuda",
backend = "cuda",
@@ -151,6 +158,7 @@ def _engaged(result: Any) -> bool:
def _teardown() -> None:
"""Restore every process-global patch a case may have installed (old and new teardown entry points)."""
from core.inference import diffusion_arch_patches, diffusion_eager_patches
+
diffusion_eager_patches.uninstall_patches()
diffusion_arch_patches.uninstall_arch_patches()
for mod_name in (
@@ -171,15 +179,23 @@ def _teardown() -> None:
# ------------------------------------------------------------------------------------------------- entry points
-def legacy_entry(backend: str, pipe: Any, target: Any, fam: Any, speed: str, offload: bool, gguf: bool) -> dict:
+def legacy_entry(
+ backend: str, pipe: Any, target: Any, fam: Any, speed: str, offload: bool, gguf: bool
+) -> dict:
"""The pre-optimizer load-path sequence (diffusion.py / video.py at 5f38afbc2d), patch installs + speed layer."""
from core.inference import diffusion_speed as ds
patches: dict = {}
per_view: list = []
if backend == "image":
- from core.inference.diffusion_arch_patches import install_arch_patches, uninstall_arch_patches
- from core.inference.diffusion_eager_patches import install_compile_safe_patches, uninstall_patches
+ from core.inference.diffusion_arch_patches import (
+ install_arch_patches,
+ uninstall_arch_patches,
+ )
+ from core.inference.diffusion_eager_patches import (
+ install_compile_safe_patches,
+ uninstall_patches,
+ )
if speed != "off":
patches["eager_fusions"] = _engaged(install_compile_safe_patches())
@@ -213,7 +229,9 @@ def legacy_entry(backend: str, pipe: Any, target: Any, fam: Any, speed: str, off
from core.inference.video_families import LTX_FAMILIES
if speed != "off":
- patches["wan_fused"] = _engaged(video_wan_fused.install_for_pipe(pipe, target.dtype, target.device))
+ patches["wan_fused"] = _engaged(
+ video_wan_fused.install_for_pipe(pipe, target.dtype, target.device)
+ )
else:
video_wan_fused.uninstall()
for view in _views_for(pipe, fam):
@@ -242,7 +260,9 @@ def legacy_entry(backend: str, pipe: Any, target: Any, fam: Any, speed: str, off
return {"patches": patches, "views": per_view}
-def autoopt_entry(backend: str, pipe: Any, target: Any, fam: Any, speed: str, offload: bool, gguf: bool) -> dict:
+def autoopt_entry(
+ backend: str, pipe: Any, target: Any, fam: Any, speed: str, offload: bool, gguf: bool
+) -> dict:
"""The same load through the optimizer."""
from core.inference import diffusion_speed as ds
from core.inference.diffusion_autoopt import apply as ao
@@ -291,7 +311,6 @@ def autoopt_entry(backend: str, pipe: Any, target: Any, fam: Any, speed: str, of
views = [applied]
else:
from core.inference.video import _views_for
-
results.update(
ao.install_patches(
ap.STAGE_LOAD,
@@ -350,7 +369,6 @@ def _check_audit(audit: Any, applied: dict, speed: str) -> None:
def _families() -> list[tuple[str, Any]]:
from core.inference.diffusion_families import _FAMILIES as image
from core.inference.video_families import _FAMILIES as video
-
return [("image", f) for f in image] + [("video", f) for f in video]
@@ -362,7 +380,10 @@ def _observe(pipe: Any, out: dict) -> dict:
continue
mods[attr] = {
"compile_calls": [
- {k: (v if isinstance(v, (bool, int, float, str, type(None))) else repr(v)) for k, v in c.items()}
+ {
+ k: (v if isinstance(v, (bool, int, float, str, type(None))) else repr(v))
+ for k, v in c.items()
+ }
for c in getattr(m, "compile_calls", [])
],
"static": bool(getattr(m, "_unsloth_compile_static", False)),
@@ -403,7 +424,13 @@ def snapshot(entry: Callable) -> dict:
stash: dict = {}
- def _patch_function(target, attr, new_fn, match_level = "relaxed", force = False):
+ def _patch_function(
+ target,
+ attr,
+ new_fn,
+ match_level = "relaxed",
+ force = False,
+ ):
stash.setdefault((target, attr), getattr(target, attr))
setattr(target, attr, new_fn)
return True
@@ -415,7 +442,9 @@ def snapshot(entry: Callable) -> dict:
return True
patch.setattr(
- diffusion_patch_backend, "_HELPERS", {"patch": _patch_function, "restore": _restore_original}
+ diffusion_patch_backend,
+ "_HELPERS",
+ {"patch": _patch_function, "restore": _restore_original},
)
saved_env = {k: os.environ.pop(k, None) for k in _ENV_CLEAR}
patch.setattr(torch.cuda, "is_available", lambda: True)
@@ -431,12 +460,14 @@ def snapshot(entry: Callable) -> dict:
for speed in SPEEDS:
for dtype_name in DTYPES:
for offload in (False, True):
- for gguf in ((False, True) if backend == "image" else (False,)):
+ for gguf in (False, True) if backend == "image" else (False,):
case = f"{backend}|{fam.name}|{speed}|{dtype_name}|offload={int(offload)}|gguf={int(gguf)}"
pipe = (_image_pipe if backend == "image" else _video_pipe)(fam)
flags = ds.snapshot_backend_flags()
try:
- result = entry(backend, pipe, _target(dtype_name), fam, speed, offload, gguf)
+ result = entry(
+ backend, pipe, _target(dtype_name), fam, speed, offload, gguf
+ )
out[case] = _observe(pipe, result)
except Exception as exc: # noqa: BLE001 - recorded, compared like any outcome
out[case] = {"error": f"{type(exc).__name__}: {exc}"}
@@ -462,7 +493,9 @@ def captured() -> dict:
def test_fixture_covers_every_registered_family(captured):
meta = captured["meta"]
fams = {f"{b}|{f.name}" for b, f in _families()}
- assert fams == set(meta["families"]), "a registry family was added / removed: regenerate the fixture"
+ assert fams == set(
+ meta["families"]
+ ), "a registry family was added / removed: regenerate the fixture"
def test_autoopt_resolves_the_same_optimizations_as_before(captured):
diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.py
index 33675e016f3..1135f164add 100644
--- a/studio/backend/tests/test_diffusion_backend.py
+++ b/studio/backend/tests/test_diffusion_backend.py
@@ -7261,7 +7261,12 @@ def test_diffusion_status_response_carries_requested_precision():
}
resp = DiffusionStatusResponse(loaded = True, resolved = rec)
assert resp.model_dump()["resolved"] == {
- "transformer_quant": {**rec["transformer_quant"], "artifact": None, "replaced": None, "steps": None}
+ "transformer_quant": {
+ **rec["transformer_quant"],
+ "artifact": None,
+ "replaced": None,
+ "steps": None,
+ }
}
diff --git a/studio/backend/tests/test_diffusion_rocm_fused.py b/studio/backend/tests/test_diffusion_rocm_fused.py
index 279127e3332..2587b41b1a9 100644
--- a/studio/backend/tests/test_diffusion_rocm_fused.py
+++ b/studio/backend/tests/test_diffusion_rocm_fused.py
@@ -169,9 +169,15 @@ def test_load_and_teardown_wiring():
from core.inference import diffusion, diffusion_rocm_fused
seen = []
- orig_install, orig_uninstall = diffusion_rocm_fused.install_for_pipe, diffusion_rocm_fused.uninstall
+ orig_install, orig_uninstall = (
+ diffusion_rocm_fused.install_for_pipe,
+ diffusion_rocm_fused.uninstall,
+ )
try:
- diffusion_rocm_fused.install_for_pipe = lambda *a: seen.append(("install", a)) or {"rope": False, "adaln": 0}
+ diffusion_rocm_fused.install_for_pipe = lambda *a: seen.append(("install", a)) or {
+ "rope": False,
+ "adaln": 0,
+ }
diffusion_rocm_fused.uninstall = lambda: seen.append(("uninstall",))
pipe = _types.SimpleNamespace(transformer = None)
ap.install_stage(
diff --git a/studio/backend/tests/test_diffusion_speed.py b/studio/backend/tests/test_diffusion_speed.py
index 10725018c44..6f6e75a5fe8 100644
--- a/studio/backend/tests/test_diffusion_speed.py
+++ b/studio/backend/tests/test_diffusion_speed.py
@@ -1921,12 +1921,18 @@ def test_the_loader_keys_the_compile_bundle_on_the_vae_decode_decision():
try:
ds_mod.vae_decode_compile_allowed = lambda pipe, mode: seen.append(mode) or mode == "max"
pipe = types.SimpleNamespace(transformer = None)
- assert compile_cache_kwargs(pipe, speed_mode = "max", fullgraph = True, offload_below_hooks = False)[
- "vae_decode"
- ] is True
- assert compile_cache_kwargs(
- pipe, speed_mode = "max", fullgraph = True, offload_below_hooks = False, deferred = True
- )["vae_decode"] is False
+ assert (
+ compile_cache_kwargs(pipe, speed_mode = "max", fullgraph = True, offload_below_hooks = False)[
+ "vae_decode"
+ ]
+ is True
+ )
+ assert (
+ compile_cache_kwargs(
+ pipe, speed_mode = "max", fullgraph = True, offload_below_hooks = False, deferred = True
+ )["vae_decode"]
+ is False
+ )
finally:
ds_mod.vae_decode_compile_allowed = orig
assert seen == ["max", "default"]
diff --git a/studio/backend/tests/test_video_ltx25_prequant.py b/studio/backend/tests/test_video_ltx25_prequant.py
index 9c3864573ae..98f4980a39d 100644
--- a/studio/backend/tests/test_video_ltx25_prequant.py
+++ b/studio/backend/tests/test_video_ltx25_prequant.py
@@ -203,7 +203,11 @@ def test_the_baked_int8_excludes_are_this_runtimes():
@pytest.mark.parametrize(
"scheme, rotated, fmt",
- [("fp8", False, PREQUANT_FORMAT), ("int8", False, PREQUANT_FORMAT), ("int8", True, PREQUANT_FORMAT_ROTATED)],
+ [
+ ("fp8", False, PREQUANT_FORMAT),
+ ("int8", False, PREQUANT_FORMAT),
+ ("int8", True, PREQUANT_FORMAT_ROTATED),
+ ],
)
def test_the_baked_metadata_passes_the_loader(scheme, rotated, fmt):
meta = _meta(scheme, rotated)
@@ -237,7 +241,9 @@ def _api(siblings = None, missing = False):
if missing:
raise RuntimeError(f"404 Client Error: {repo_id}")
return types.SimpleNamespace(
- siblings = [types.SimpleNamespace(rfilename = n, size = s) for n, s in (siblings or {}).items()]
+ siblings = [
+ types.SimpleNamespace(rfilename = n, size = s) for n, s in (siblings or {}).items()
+ ]
)
return types.SimpleNamespace(token = None, model_info = model_info, asked = asked)
@@ -256,7 +262,9 @@ def _planning(monkeypatch):
import core.inference.diffusion_prequant as pq
from core.inference import video_denoiser_prequant as vdp
- monkeypatch.setattr(pq, "restricted_prequant_load_supported", lambda scheme = None, filename = None: True)
+ monkeypatch.setattr(
+ pq, "restricted_prequant_load_supported", lambda scheme = None, filename = None: True
+ )
monkeypatch.setattr(vdp, "hosted_denoiser_refused", lambda *a, **k: False)
@@ -268,7 +276,9 @@ def _planning(monkeypatch):
("fp8", None, "LTX-2.5-FP8.safetensors"),
],
)
-def test_once_published_the_plan_credits_the_hosted_file(fam, monkeypatch, _planning, scheme, env, expected):
+def test_once_published_the_plan_credits_the_hosted_file(
+ fam, monkeypatch, _planning, scheme, env, expected
+):
from core.inference.video import VideoBackend
if env is not None:
@@ -284,7 +294,10 @@ def test_until_published_the_plan_keeps_the_dense_shards(fam, _planning):
# renders are pixel-identical to that, so nothing but load time and the download changes).
from core.inference.video import VideoBackend
- assert VideoBackend._denoiser_prequant_hub_files(fam, "int8", PACK, _api(missing = True)) == (None, [])
+ assert VideoBackend._denoiser_prequant_hub_files(fam, "int8", PACK, _api(missing = True)) == (
+ None,
+ [],
+ )
# A listing without the rotated file still serves int8 from the plain one.
plain = {k: v for k, v in _PUBLISHED.items() if "ConvRot" not in k}
assert VideoBackend._denoiser_prequant_hub_files(fam, "int8", PACK, _api(plain)) == (
diff --git a/studio/backend/tests/test_video_wan_fused.py b/studio/backend/tests/test_video_wan_fused.py
index ae1829b03d6..a17c2c91c1a 100644
--- a/studio/backend/tests/test_video_wan_fused.py
+++ b/studio/backend/tests/test_video_wan_fused.py
@@ -437,7 +437,9 @@ def test_loader_installs_before_the_step_cache_and_offload_hooks():
try:
wf.install_for_pipe = lambda *a, **k: seen.append(("install", a)) or True
wf.uninstall = lambda: seen.append(("uninstall",))
- ctx = ap.PatchContext(pipe = "pipe", dtype = "fp16", device = "cuda", backend = "video", speed_mode = "off")
+ ctx = ap.PatchContext(
+ pipe = "pipe", dtype = "fp16", device = "cuda", backend = "video", speed_mode = "off"
+ )
assert ap.install_stage(ap.STAGE_LOAD, ctx) == {}
ctx.speed_mode = "default"
assert ap.install_stage(ap.STAGE_LOAD, ctx) == {"wan_fused": True}
@@ -448,6 +450,7 @@ def test_loader_installs_before_the_step_cache_and_offload_hooks():
def test_teardown_and_rollback_restore_the_stock_forward():
from core.inference import video
+
cls = next(
c
for c in vars(video).values()