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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio video: batch the CFG pair into one call on a compiled resident Wan denoiser (#16067)
Daniel Han856799b4272e
diff --git a/studio/backend/core/inference/diffusion_cfg_batch.py b/studio/backend/core/inference/diffusion_cfg_batch.pyindex 7057bb4ea2a..e1c60bbe95a 100644--- a/studio/backend/core/inference/diffusion_cfg_batch.py+++ b/studio/backend/core/inference/diffusion_cfg_batch.py@@ -3,7 +3,7 @@"""Batches CFG branches into one forward for stateless denoisers only; a second call differing fromthe batched inputs reruns that branch plain; not always bit-exact; UNSLOTH_DIFFUSION_CFG_BATCH=0-keeps one branch per call"""+keeps one branch per call; UNSLOTH_DIFFUSION_CFG_BATCH_COMPILED=0 keeps a compiled resident Wan plain"""from __future__ import annotations@@ -14,6 +14,7 @@ import weakreffrom typing import Any, OptionalCFG_BATCH_ENV = "UNSLOTH_DIFFUSION_CFG_BATCH"+COMPILED_RESIDENT_ENV = "UNSLOTH_DIFFUSION_CFG_BATCH_COMPILED"# Forward keeps no state between calls, both branches share every per-step input but the text conditioning. Z-Image is# absent on purpose: its pipeline already batches the branches (a list of latents, one call per step).@@ -31,6 +32,9 @@ _PER_SAMPLE_LISTS = ("img_shapes",)# (embeddings, mask) pairs a branch pads to its own prompt length: padded to the longer one with masked zeros._PADDED_TEXT = (("encoder_hidden_states", "encoder_hidden_states_mask"),)+# Compiled + resident, batched with no trial: measured 1-2% win on an L4, below the trial's 8% bar.+COMPILED_RESIDENT_CLASSES = frozenset({"WanTransformer3DModel"})+_MEASURED_FRACTION = 0.92_BATCHED_SAMPLES = 2_PLAIN_STEPS = 2@@ -51,11 +55,25 @@ def cfg_batch_mode() -> str:return "auto"+def compiled_resident_batch(denoiser: Any) -> bool:+ """A compiled denoiser kept on the card that still batches its guidance branches (one doubled call per step)."""+ raw = (os.environ.get(COMPILED_RESIDENT_ENV) or "").strip().lower()+ if raw in ("0", "off", "false", "no", "disable", "disabled"):+ return False+ return type(denoiser).__name__ in COMPILED_RESIDENT_CLASSES and type(+ denoiser+ ).__module__.startswith("diffusers.")++def _torch():import torchreturn torch+def _cuda_latent(latent: Any) -> bool:+ return getattr(getattr(latent, "device", None), "type", None) == "cuda"++def _mg():from . import diffusion_multigpu as mgreturn mg@@ -193,7 +211,11 @@ def cfg_batch_decline(if getattr(denoiser, "_compiled_call_impl", None) is not None:return "denoiser is compiled whole"compiled = compiled_denoiser(denoiser)- if compiled is not None and not _offloaded(denoiser, offload_policy):+ if (+ compiled is not None+ and not _offloaded(denoiser, offload_policy)+ and not compiled_resident_batch(denoiser)+ ):return f"{compiled} and resident"if getattr(pipe, "_unsloth_cuda_graphs", None):return "the denoiser replays CUDA graphs"@@ -482,6 +504,7 @@ class CfgBatchRouter:self.pair_t0: Optional[float] = Noneself.renders = 0 # completed renders: a doubled-batch compile is warm-up only in a shape's trial renderself.render_compiled: Optional[str] = None+ self.compiled_resident = Falseself.identity: Optional[str] = (None # the load's verdict-store identity (None: verdicts stay per load))@@ -507,6 +530,7 @@ class CfgBatchRouter:if shape is None or not shape.batched_selse round(min(shape.batched_s), 4),"displaced": self._displaced(),+ "compiled_resident": self.compiled_resident,"render_off": self.render_off,**self.stats,}@@ -577,8 +601,13 @@ class CfgBatchRouter:module = self.module_ref()self.render_off = _foreign_hook(module) if module is not None else Noneself.render_compiled = compiled_denoiser(module) if module is not None else None+ self.compiled_resident = (+ self.render_compiled is not None+ and not self.offloaded+ and compiled_resident_batch(module)+ )if self.render_compiled is not None:- if not self.offloaded:+ if not self.offloaded and not self.compiled_resident:self.render_off = f"{self.render_compiled} and resident"for shape in self.shapes.values():if shape.judged and not shape.compiled_at_trial and shape.off is None:@@ -603,7 +632,7 @@ class CfgBatchRouter:self.template is not Noneand shape.off is Noneand shape.judged- and shape.render_steps > _PLAIN_STEPS+ and shape.render_steps > self._plain_steps()):out = self._batched(args, kwargs, latent, shape)if out is not None:@@ -625,6 +654,10 @@ class CfgBatchRouter:out = self._plain(args, kwargs)if self.paired is not None:return out+ if self.compiled_resident:+ if not shape.judged and self.disabled is None:+ self._untimed(shape, latent)+ return outif not shape.judged and self.disabled is None and shape.render_steps == _PLAIN_STEPS:t0, self.pair_t0 = self.pair_t0, Noneif shape.verdict is None:@@ -658,6 +691,26 @@ class CfgBatchRouter:self.disable("more than two denoiser calls per step")return self._plain(args, kwargs)+ def _plain_steps(self) -> int:+ """Plain steps per render: step 1 records the template; the timed path also prices step 2."""+ return 1 if self.compiled_resident else _PLAIN_STEPS++ def _untimed(self, shape: _Shape, latent: Any) -> None:+ """No trial: it would compile the batch 2 graph anyway and the win is inside its noise."""+ if not _cuda_latent(latent) and cfg_batch_mode() != "force":+ self._shape_off(+ shape,+ f"compiled resident batching is measured on CUDA only ({CFG_BATCH_ENV}=force batches anyway)",+ )+ return+ shape.verdict = _BATCH+ # reached under compile: a render that had no room re-judges the shape at its end (end_render)+ shape.compiled_at_trial = True+ if self._memory_ok(latent, shape):+ self._judge(shape)+ else:+ self._shape_off(shape, "no room for a doubled call", _OFF_TRANSIENT)+def _new_step(self, args: tuple, kwargs: dict, latent: Any) -> None:if self.kept is not None:self._miss(self.shape, "the second branch never came")@@ -1207,6 +1260,12 @@ def _install(logger = logger,)router.offloaded = _offloaded(denoiser, offload_policy)+ if (+ cfg_batch_mode() != "force"+ and not router.offloaded+ and compiled_denoiser(denoiser) is not None+ ):+ router.reason = "compiled resident denoiser: one doubled call per guided step from step 2"router.identity = _load_identity(denoiser, offload_policy, speed_mode, transformer_quant)return _arm(pipe, denoiser, router, logger)diff --git a/studio/backend/tests/test_diffusion_cfg_batch_compiled.py b/studio/backend/tests/test_diffusion_cfg_batch_compiled.pynew file mode 100644index 00000000000..6bc6f3119f6--- /dev/null+++ b/studio/backend/tests/test_diffusion_cfg_batch_compiled.py@@ -0,0 +1,225 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""CFG batching on a compiled + resident Wan denoiser: one doubled call per guided step from step 2, CPU fakes."""++from __future__ import annotations++import pytest+import torch++from core.inference import diffusion_cfg_batch as cb+++class WanTransformer3DModel(torch.nn.Module):+ """Stateless per-sample forward in the diffusers Wan call shape (hidden, expanded timestep, text)."""++ def __init__(self):+ super().__init__()+ self.w = torch.nn.Parameter(torch.linspace(0.5, 1.5, 8))+ self.calls = []++ def forward(+ self,+ hidden_states,+ timestep,+ encoder_hidden_states,+ encoder_hidden_states_image = None,+ return_dict = True,+ attention_kwargs = None,+ ):+ self.calls.append(int(hidden_states.shape[0]))+ text = encoder_hidden_states.mean(dim = 1, keepdim = True)+ return (hidden_states * self.w + text + timestep.view(-1, 1, 1).float() / 1000,)+++class Flux2Transformer2DModel(WanTransformer3DModel):+ pass+++for _cls in (WanTransformer3DModel, Flux2Transformer2DModel):+ _cls.__module__ = "diffusers.models.fake"+++class _Pipe:+ def __init__(self, transformer):+ self.transformer = transformer+++def _compiled(model):+ model._unsloth_regional_compile_kwargs = {"fullgraph": True, "dynamic": True}+ return model+++def _wan_loop(+ model,+ steps = 6,+ seed = 0,+ neg_seed = 1,+):+ """WanPipeline's loop: one latent object per step, cond then uncond with ``t.expand(batch)``, CFG combine."""+ torch.manual_seed(seed)+ latents = torch.randn(1, 4, 8)+ pos = torch.randn(1, 5, 8)+ neg = torch.randn(1, 5, 8, generator = torch.Generator().manual_seed(neg_seed))+ for t in torch.tensor([999, 941, 883, 825, 767, 709])[:steps]:+ latent_model_input = latents+ timestep = t.expand(latents.shape[0])+ c = model(hidden_states = latent_model_input, timestep = timestep, encoder_hidden_states = pos, return_dict = False)[0] # fmt: skip+ u = model(hidden_states = latent_model_input, timestep = timestep, encoder_hidden_states = neg, return_dict = False)[0] # fmt: skip+ latents = latents - 0.1 * (u + 5.0 * (c - u))+ return latents+++def on_cuda(monkeypatch):+ monkeypatch.setattr(cb, "_cuda_latent", lambda latent: True)+++def _install(model):+ pipe = _Pipe(model)+ assert cb.install_cfg_batch(pipe, offload_policy = "none") is None+ return pipe, cb.router_for(pipe)+++def test_a_compiled_resident_wan_batches_from_step_two_on_every_render(on_cuda):+ ref = _wan_loop(WanTransformer3DModel())+ model = _compiled(WanTransformer3DModel())+ pipe, router = _install(model)+ assert "compiled resident" in router.reason+ for _ in range(3):+ del model.calls[:]+ torch.testing.assert_close(_wan_loop(model), ref, rtol = 0, atol = 0)+ assert (+ model.calls == [1, 1] + [2] * 5+ ) # step 1 plain (records the template), steps 2-6 doubled+ cb.end_cfg_batch_render(pipe)+ status = cb.cfg_batch_status(pipe)+ assert status["compiled_resident"] and status["render_off"] is None and router.disabled is None+ assert status["batched_steps"] == 15 and status["hits"] == 15 and status["misses"] == 0+ assert status["plain_pair_s"] is None and status["batched_pair_s"] is None+++def test_a_new_prompt_negative_and_seed_keep_the_one_path(on_cuda):+ model = _compiled(WanTransformer3DModel())+ pipe, router = _install(model)+ _wan_loop(model)+ cb.end_cfg_batch_render(pipe)+ ref = _wan_loop(WanTransformer3DModel(), seed = 7, neg_seed = 9)+ del model.calls[:]+ torch.testing.assert_close(_wan_loop(model, seed = 7, neg_seed = 9), ref, rtol = 0, atol = 0)+ assert model.calls == [1, 1] + [2] * 5 and router.stats["misses"] == 0+++def test_the_compiled_resident_kill_switch_keeps_one_branch_per_call(monkeypatch, on_cuda):+ monkeypatch.setenv(cb.COMPILED_RESIDENT_ENV, "0")+ model = _compiled(WanTransformer3DModel())+ pipe = _Pipe(model)+ assert (+ cb.install_cfg_batch(pipe, offload_policy = "none") == "the denoiser is compiled and resident"+ )+ _wan_loop(model)+ assert model.calls == [1] * 12+++def test_the_global_switch_still_turns_everything_off(monkeypatch, on_cuda):+ monkeypatch.setenv(cb.CFG_BATCH_ENV, "0")+ assert cb.install_cfg_batch(+ _Pipe(_compiled(WanTransformer3DModel())), offload_policy = "none"+ ) == (f"{cb.CFG_BATCH_ENV}=0")+++def test_other_compiled_resident_classes_stay_declined(on_cuda):+ model = _compiled(Flux2Transformer2DModel())+ assert (+ cb.install_cfg_batch(_Pipe(model), offload_policy = "none")+ == "the denoiser is compiled and resident"+ )+++def test_off_cuda_a_compiled_resident_wan_stays_plain():+ model = _compiled(WanTransformer3DModel())+ pipe, router = _install(model)+ _wan_loop(model)+ assert model.calls == [1] * 12+ assert "CUDA only" in router.last_shape.off+++def test_a_doubled_call_compiling_on_a_follow_up_render_ends_batching_after_it(+ monkeypatch, on_cuda+):+ model = _compiled(WanTransformer3DModel())+ pipe, router = _install(model)+ _wan_loop(model) # render 1 compiles the batch 2 graph: expected warm-up+ cb.end_cfg_batch_render(pipe)+ graphs = iter(range(1000))+ monkeypatch.setattr(+ cb, "_graph_count", lambda: next(graphs)+ ) # every doubled call "compiles" from now on+ del model.calls[:]+ _wan_loop(model)+ assert model.calls == [1, 1] + [2] * 5+ cb.end_cfg_batch_render(pipe)+ assert "after its warm-up render" in router.disabled+ del model.calls[:]+ _wan_loop(model)+ assert model.calls == [1] * 12+++def test_the_first_render_doubled_compile_is_warm_up(monkeypatch, on_cuda):+ graphs = iter(range(1000))+ monkeypatch.setattr(cb, "_graph_count", lambda: next(graphs))+ model = _compiled(WanTransformer3DModel())+ pipe, router = _install(model)+ _wan_loop(model)+ cb.end_cfg_batch_render(pipe)+ assert router.disabled is None and router.pending_disable is None+++def test_no_room_for_the_doubled_call_keeps_that_render_plain(monkeypatch, on_cuda):+ model = _compiled(WanTransformer3DModel())+ pipe, router = _install(model)+ monkeypatch.setattr(router, "_memory_ok", lambda latent, shape: False)+ _wan_loop(model)+ assert model.calls == [1] * 12 and "no room" in router.last_shape.off+ cb.end_cfg_batch_render(pipe)+ monkeypatch.setattr(router, "_memory_ok", lambda latent, shape: True)+ del model.calls[:]+ _wan_loop(model)+ assert model.calls == [1, 1] + [2] * 5 # memory pressure is per render+++def test_an_oom_on_the_doubled_call_reruns_the_branch_plain(monkeypatch, on_cuda):+ ref = _wan_loop(WanTransformer3DModel())+ model = _compiled(WanTransformer3DModel())+ pipe, router = _install(model)+ real = router.orig_forward++ def oom_on_doubled(*args, **kwargs):+ if kwargs["hidden_states"].shape[0] == 2:+ raise torch.cuda.OutOfMemoryError("CUDA out of memory")+ return real(*args, **kwargs)++ router.orig_forward = oom_on_doubled+ torch.testing.assert_close(_wan_loop(model), ref, rtol = 0, atol = 0)+ assert router.stats["batched_steps"] == 0 and "out of memory" in router.last_shape.off+ cb.end_cfg_batch_render(pipe)+ router.orig_forward = real+ del model.calls[:]+ torch.testing.assert_close(_wan_loop(model), ref, rtol = 0, atol = 0)+ assert model.calls == [1, 1] + [2] * 5+++def test_an_offloaded_compiled_wan_keeps_the_timed_path(monkeypatch):+ model = _compiled(WanTransformer3DModel())+ sub = torch.nn.Linear(1, 1)+ model.add_module("offloaded_group", sub)+ import types++ sub._diffusers_hook = types.SimpleNamespace(hooks = {"group_offloading": object()})+ pipe = _Pipe(model)+ assert cb.install_cfg_batch(pipe, offload_policy = "group") is None+ router = cb.router_for(pipe)+ assert router.offloaded and "compiled resident" not in router.reason+ _wan_loop(model)+ assert not router.compiled_resident