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.

Studio diffusion: compile group-offloaded blocks below their hooks on the deferred profile and for planned-offload video (#14528)

Daniel Han36497673f7d5
diff --git a/studio/backend/core/inference/diffusion_block_graph.py b/studio/backend/core/inference/diffusion_block_graph.py
index 10af8d16478..638d6f849a3 100644
--- a/studio/backend/core/inference/diffusion_block_graph.py
+++ b/studio/backend/core/inference/diffusion_block_graph.py
@@ -1127,6 +1127,33 @@ def _is_original_forward(fn: Any, module: Any) -> bool:
)
+def _own_forward(fn: Any, module: Any) -> Any:
+ """``module``'s live class ``forward`` (bound) when ``fn`` is the forward a hook captured from it, else None.
+
+ A hook registered before a class-level patch of ``forward`` (the deferred profile's per-arch fusions land on
+ render 3, after group offload hooked every block at load) still holds the class's own definition-time forward.
+ That is the same callable slot, so it is matched too, and the live (patched) forward is what runs below the hook,
+ exactly as when the patch came first."""
+ if getattr(fn, "__self__", None) is not module:
+ return None
+ func = getattr(fn, "__func__", None)
+ cls = type(module)
+ live = getattr(cls, "forward", None)
+ if func is None or live is None:
+ return None
+ if func is live:
+ return fn
+ qualname = getattr(func, "__qualname__", None)
+ owner = getattr(func, "__module__", None)
+ for base in cls.__mro__:
+ if qualname == f"{base.__qualname__}.forward" and owner == base.__module__:
+ try:
+ return live.__get__(module, cls)
+ except Exception: # noqa: BLE001 - not a descriptor: leave the hook's forward alone
+ return None
+ return None
+
+
def _inner_hook_reason(block: Any) -> Optional[str]:
"""Why a block's own subtree moves weights mid-forward (per-layer offload), which no recording can hold."""
for name, sub in block.named_modules():
@@ -1459,23 +1486,24 @@ def install_block_graphs(
registry = getattr(block, "_diffusers_hook", None)
refs = list(getattr(registry, "_fn_refs", None) or ())
target = getattr(block, "_unsloth_below_hook_ref", None)
- if target not in refs:
- target = next(
- (
- r
- for r in refs
- if _is_original_forward(getattr(r, "forward", None), block)
- ),
- None,
- )
+ compute = None
+ if target in refs:
+ compute = target.forward
+ else:
+ target = None
+ for r in refs:
+ compute = _own_forward(getattr(r, "forward", None), block)
+ if compute is not None:
+ target = r
+ break
if target is None:
refused["a stacked hook chain"] = refused.get("a stacked hook chain", 0) + 1
continue
- compute = target.forward
+ original_fwd = target.forward
graph = BlockGraph(block, compute, block_shared)
target.forward = graph
- def restore(ref: Any = target, fn: Any = compute) -> None:
+ def restore(ref: Any = target, fn: Any = original_fwd) -> None:
if ref.forward is not fn:
ref.forward = fn
elif compiled is not None:
@@ -1595,26 +1623,29 @@ def compile_below_offload_hooks(transformer: Any, logger: Any = None) -> int:
if compiled is None or _group_offload_hook(block) is None:
continue
registry = getattr(block, "_diffusers_hook", None)
- target = next(
- (
- r
- for r in list(getattr(registry, "_fn_refs", None) or ())
- if _is_original_forward(getattr(r, "forward", None), block)
- ),
- None,
- )
+ target = live = None
+ for r in list(getattr(registry, "_fn_refs", None) or ()):
+ live = _own_forward(getattr(r, "forward", None), block)
+ if live is not None:
+ target = r
+ break
if target is None:
continue
- original = target.forward
- fn = torch.compile(original, **dict(kwargs))
+ # compiles the live class forward: a per-arch patch installed after the hook captured the original runs too
+ fn = torch.compile(live, **dict(kwargs))
if guard is not None and callable(getattr(guard, "wrap", None)):
- fn = guard.wrap(fn, original, transformer)
- guard.restores.append(lambda ref = target, f = original: setattr(ref, "forward", f))
+ fn = guard.wrap(fn, live, transformer)
+ # A failed compile falls back to the live forward, so a class patch keeps running eager below the hook.
+ guard.restores.append(lambda ref = target, f = live: setattr(ref, "forward", f))
from . import diffusion_block_restride
if diffusion_block_restride.is_wrapped(compiled):
# FLUX.1's block 0 keeps the slice layout of the others, so all of them share one compiled graph.
fn = diffusion_block_restride.wrap(fn)
+ rewrap = getattr(compiled, "_unsloth_rewrap", None)
+ if callable(rewrap):
+ # A family adapter around the compiled call (LTX-2's STG flag) must wrap the moved compile too.
+ fn = rewrap(fn)
target.forward = fn
block._compiled_call_impl = None
block._unsloth_below_hook_ref = target
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index dc707d3ace3..6b4c6a7a693 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -9493,8 +9493,10 @@ class VideoBackend:
speed_optims += ("vae_untiled_when_fits",)
# Wan's decode also grows within a single tile, which tiling alone cannot bound.
install_decoder_sync(pipe, target, logger = logger)
- if not speed_offload and _video_denoiser_hooked(pipe):
- # compiled for a resident denoiser but it landed hooked: move the compile below the offload hooks (as the image backend)
+ if _video_denoiser_hooked(pipe):
+ # Below the offload hooks (as the image backend), whether the speed layer planned the offload or a split
+ # fell back to a hooked placement: compiled through them, each block splits at the hook's
+ # torch.compiler.disable'd pre / post forward.
compile_pipe_below_offload_hooks(pipe, logger)
# A family that opts in to graphs arms them against the placement that landed (offload hooks included).
graph_applied = arm_graphs_after_placement(
diff --git a/studio/backend/core/inference/video_ltx2.py b/studio/backend/core/inference/video_ltx2.py
index 389decda521..69989fc8d85 100644
--- a/studio/backend/core/inference/video_ltx2.py
+++ b/studio/backend/core/inference/video_ltx2.py
@@ -1120,6 +1120,29 @@ def _recompile_limit_hit(exc: BaseException) -> bool:
return isinstance(kind, type) and isinstance(exc, kind)
+def _stg_adapted(inner: Any, guard: Any, transformer: Any, torch: Any) -> Any:
+ def adapted(*args: Any, **kwargs: Any) -> Any:
+ flag = kwargs.get("all_perturbed")
+ if isinstance(flag, torch.Tensor):
+ kwargs["all_perturbed"] = bool(flag)
+ try:
+ return inner(*args, **kwargs)
+ except Exception as exc: # noqa: BLE001 -- reraised unless the recompile limit was hit
+ if guard is None or guard.error is not None or not _recompile_limit_hit(exc):
+ raise
+ # Past the recompile limit fullgraph raises unclassified by the guard: drop this DiT to eager.
+ guard.fail(exc, transformer)
+ exc.__traceback__ = None
+ return inner(*args, **kwargs)
+
+ adapted._unsloth_stg_adapter = True
+ if guard is not None:
+ adapted._unsloth_compile_guard = guard
+ # A compile moved below an offload hook rebuilds the block's callable: re-apply the adapter around it.
+ adapted._unsloth_rewrap = lambda new_inner: _stg_adapted(new_inner, guard, transformer, torch)
+ return adapted
+
+
def install_stg_compile_adapter(transformer: Any) -> int:
"""Convert the STG pass's 0-d ``all_perturbed`` tensor to a bool before the compiled block (LTX2Attention branches
on it, which fails fullgraph and drops the DiT to eager). Keeps the guard's marker so ``guard_compiled_blocks``
@@ -1135,32 +1158,9 @@ def install_stg_compile_adapter(transformer: Any) -> int:
inner = getattr(module, "_compiled_call_impl", None)
if inner is None or getattr(inner, "_unsloth_stg_adapter", False):
continue
-
- guard = getattr(inner, "_unsloth_compile_guard", None)
-
- def adapted(
- *args: Any,
- _inner: Any = inner,
- _guard: Any = guard,
- **kwargs: Any,
- ) -> Any:
- flag = kwargs.get("all_perturbed")
- if isinstance(flag, torch.Tensor):
- kwargs["all_perturbed"] = bool(flag)
- try:
- return _inner(*args, **kwargs)
- except Exception as exc: # noqa: BLE001 -- reraised unless the recompile limit was hit
- if _guard is None or _guard.error is not None or not _recompile_limit_hit(exc):
- raise
- # Past the recompile limit fullgraph raises unclassified by the guard: drop this DiT to eager.
- _guard.fail(exc, transformer)
- exc.__traceback__ = None
- return _inner(*args, **kwargs)
-
- adapted._unsloth_stg_adapter = True
- if guard is not None:
- adapted._unsloth_compile_guard = guard
- module._compiled_call_impl = adapted
+ module._compiled_call_impl = _stg_adapted(
+ inner, getattr(inner, "_unsloth_compile_guard", None), transformer, torch
+ )
count += 1
return count
diff --git a/studio/backend/tests/test_diffusion_block_graph.py b/studio/backend/tests/test_diffusion_block_graph.py
index 7ce7686a254..796df8bfd79 100644
--- a/studio/backend/tests/test_diffusion_block_graph.py
+++ b/studio/backend/tests/test_diffusion_block_graph.py
@@ -316,6 +316,112 @@ def test_compile_moves_below_the_offload_hook_and_the_kill_switch_keeps_it_trace
assert not any(isinstance(b._unsloth_below_hook_ref.forward, bg.BlockGraph) for b in net.blocks)
+def _shifted_forward(
+ self,
+ x,
+ temb = None,
+ layer_cache = None,
+ kv_cache_mode = None,
+):
+ return _ORIGINAL_BLOCK_FORWARD(self, x, temb = temb) + 1.0
+
+
+_ORIGINAL_BLOCK_FORWARD = Block.forward
+
+
+def test_compile_below_the_hook_engages_after_a_class_patch_lands_on_the_hooked_forward(
+ monkeypatch,
+):
+ # The deferred profile installs its per-arch block fusions on render 3, after group offload hooked every block at
+ # load: each hook still holds the definition-time forward. The compile must still go below the hook, and run the
+ # patched forward exactly as when the patch came first.
+ net = _hooked_net(blocks = 2)
+ net._unsloth_regional_compile_kwargs = {"backend": "eager", "fullgraph": False, "dynamic": True}
+ marker = lambda *a, **k: None # noqa: E731
+ for b in net.blocks:
+ b._compiled_call_impl = marker
+ monkeypatch.setattr(Block, "forward", _shifted_forward)
+ x = torch.randn(3, 16)
+ with torch.no_grad():
+ want = net.proj_in(x)
+ for b in net.blocks:
+ want = _shifted_forward(b, want)
+ want = net.proj_out(want)
+ assert bg.compile_below_offload_hooks(net) == 2
+ for b in net.blocks:
+ assert b._compiled_call_impl is None
+ assert b._unsloth_below_hook_ref is not None
+ torch._dynamo.reset()
+ with torch.no_grad():
+ got = net(x)
+ torch._dynamo.reset()
+ assert torch.allclose(got, want, atol = 1e-6)
+
+
+def test_a_compile_failure_below_the_hook_keeps_the_class_patch(monkeypatch):
+ # A handled compile failure restores each hook's forward: it must be the patched live forward, not the
+ # definition-time one the hook captured, or later blocks silently drop the per-arch fusion.
+ from core.inference.diffusion_speed import _CompileGuard
+
+ net = _hooked_net(blocks = 2)
+ net._unsloth_regional_compile_kwargs = {"backend": "eager", "fullgraph": False, "dynamic": True}
+ net._unsloth_compile_guard = _CompileGuard(None)
+ marker = lambda *a, **k: None # noqa: E731
+ for b in net.blocks:
+ b._compiled_call_impl = marker
+ monkeypatch.setattr(Block, "forward", _shifted_forward)
+ assert bg.compile_below_offload_hooks(net) == 2
+ net._unsloth_compile_guard.fail(RuntimeError("compile failed"), net)
+ for b in net.blocks:
+ assert getattr(b._unsloth_below_hook_ref.forward, "__func__", None) is _shifted_forward
+
+
+def test_compile_below_the_hook_reapplies_a_family_adapter():
+ # LTX-2's STG adapter sits on _compiled_call_impl; moving the compile below the hook must keep it around the move.
+ import torch as _t
+
+ from core.inference import video_ltx2
+
+ net = _hooked_net(blocks = 2)
+ net._unsloth_regional_compile_kwargs = {"backend": "eager", "fullgraph": False, "dynamic": True}
+ seen = []
+
+ def marker(*a, **k):
+ return None
+
+ for b in net.blocks:
+ b._compiled_call_impl = video_ltx2._stg_adapted(marker, None, net, _t)
+ assert bg.compile_below_offload_hooks(net) == 2
+ for b in net.blocks:
+ moved = b._unsloth_below_hook_ref.forward
+ assert getattr(moved, "_unsloth_stg_adapter", False)
+ inner = lambda *a, **k: seen.append(k.get("all_perturbed")) # noqa: E731
+ moved._unsloth_rewrap(inner)(all_perturbed = _t.tensor(True))
+ assert seen == [True, True] and all(type(v) is bool for v in seen)
+
+
+def test_block_graphs_find_the_compute_below_a_hook_that_predates_a_class_patch(monkeypatch):
+ net = _hooked_net(blocks = 2)
+ monkeypatch.setattr(Block, "forward", _shifted_forward)
+ refs = [r for b in net.blocks for r in b._diffusers_hook._fn_refs]
+ before = [r.forward for r in refs]
+ handle, reason = bg.install_block_graphs(net, slots = False)
+ assert reason == "armed" and handle is not None and len(handle.graphs) == 2
+ for g in handle.graphs:
+ assert getattr(g.compute, "__func__", None) is _shifted_forward
+ handle.free()
+ assert [r.forward for r in refs] == before
+
+
+def test_own_forward_refuses_a_foreign_bound_method():
+ block = Block()
+ other = Block()
+ assert bg._own_forward(block.forward, block) is not None
+ assert bg._own_forward(other.forward, block) is None
+ assert bg._own_forward(types.MethodType(lambda self, x: x, block), block) is None
+ assert bg._own_forward(None, block) is None
+
+
def test_compile_below_the_hook_keeps_the_block_restride():
from core.inference import diffusion_block_restride as restride
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index b27436b8231..7366681c2f0 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -14089,7 +14089,12 @@ def test_an_automatic_encoder_pick_that_does_not_engage_loads_dense_without_a_re
True,
), # the split fell back to a hooked one-card placement: the compile moves below the hooks
(True, False, False), # the split landed resident: nothing to move
- (False, True, False), # planned offloaded: the speed layer already compiled for the hooks
+ (
+ False,
+ True,
+ True,
+ ), # planned offloaded: the compile still moves below the hooks (no split at them)
+ (False, False, False), # planned offloaded but nothing landed hooked: nothing to move
],
)
def test_a_layer_split_fallback_moves_the_compile_below_the_offload_hooks(