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: run both guidance branches per streamed block upload for Qwen-Image-Edit under a VRAM budget (#15930)

Daniel Han9c30724ad6cf
diff --git a/studio/backend/core/inference/diffusion_cfg_batch.py b/studio/backend/core/inference/diffusion_cfg_batch.py
index 6e3176639fc..7057bb4ea2a 100644
--- a/studio/backend/core/inference/diffusion_cfg_batch.py
+++ b/studio/backend/core/inference/diffusion_cfg_batch.py
@@ -215,6 +215,35 @@ def cfg_batch_decline(
return None
+def cfg_pair_decline(
+ pipe: Any,
+ *,
+ offload_policy: Optional[str] = None,
+ graphs: bool = True,
+) -> Optional[str]:
+ """Why guidance branches cannot pair per streamed block, else None. ``graphs=False`` ignores armed CUDA graphs."""
+ from .diffusion_cfg_pair import pair_decline
+
+ torch = _torch()
+ denoiser = getattr(pipe, "transformer", None)
+ if not isinstance(denoiser, torch.nn.Module):
+ return "no DiT denoiser"
+ if getattr(pipe, "transformer_2", None) is not None:
+ return "two-expert denoiser"
+ if getattr(denoiser, "_compiled_call_impl", None) is not None:
+ return "denoiser is compiled whole"
+ if not _streamed(denoiser) or (
+ offload_policy is not None and not _offloaded(denoiser, offload_policy)
+ ):
+ return "the denoiser stays on the card"
+ if graphs and getattr(pipe, "_unsloth_cuda_graphs", None):
+ return "the denoiser replays CUDA graphs"
+ foreign = _foreign_layer(denoiser)
+ if foreign is not None:
+ return foreign
+ return pair_decline(denoiser, denoiser.forward)
+
+
def _usable_free_mib(device: Any) -> Optional[int]:
"""Driver free plus reusable cache (graph pools excluded) on ``device``, less the VRAM Budget reserve."""
torch = _torch()
@@ -432,7 +461,15 @@ class CfgBatchRouter:
self.logger = logger
self.disabled: Optional[str] = None
self.shapes: dict = {}
- self.stats = {"batched_steps": 0, "hits": 0, "misses": 0, "plain_calls": 0}
+ self.stats = {
+ "batched_steps": 0,
+ "paired_steps": 0,
+ "hits": 0,
+ "misses": 0,
+ "plain_calls": 0,
+ }
+ self.paired: Any = None
+ self._logged_paired = 0
self._reset_step()
self.template: Optional[tuple] = None
self.prev_latent: Any = None
@@ -459,6 +496,7 @@ class CfgBatchRouter:
shape = self.shape or self.last_shape
return {
"armed_for": self.reason,
+ "mode": "pair" if self.paired is not None else "batch",
"disabled_reason": self.disabled,
"shape_off": None if shape is None else shape.off,
"verdict": None if shape is None else shape.verdict,
@@ -475,6 +513,15 @@ class CfgBatchRouter:
def end_render(self) -> None:
"""Drop every tensor held between calls (the kept half, the template's constants, the latent)."""
+ paired = self.stats["paired_steps"] - self._logged_paired
+ if paired and self.logger is not None:
+ self._logged_paired = self.stats["paired_steps"]
+ self.logger.info(
+ "diffusion.cfg_pair: %d guided step(s) ran both branches through each streamed block "
+ "(one upload per step); %d paired so far",
+ paired,
+ self._logged_paired,
+ )
if self.render_checked:
self.renders += 1
if self.pending_disable is not None:
@@ -544,6 +591,13 @@ class CfgBatchRouter:
else:
self._new_step(args, kwargs, latent)
shape = self.shape
+ if self.branch == 0 and self.paired is not None:
+ # the first plain pair records the second call's template
+ if self.template is not None and shape.off is None and shape.render_steps > 1:
+ out = self._pair(args, kwargs, latent, shape)
+ if out is not None:
+ return out
+ return self._plain(args, kwargs)
if self.branch == 0:
if (
self.template is not None
@@ -569,6 +623,8 @@ class CfgBatchRouter:
return self._plain(args, kwargs)
self._record_template(args, kwargs, latent)
out = self._plain(args, kwargs)
+ if self.paired is not None:
+ return out
if not shape.judged and self.disabled is None and shape.render_steps == _PLAIN_STEPS:
t0, self.pair_t0 = self.pair_t0, None
if shape.verdict is None:
@@ -879,6 +935,45 @@ class CfgBatchRouter:
self.stats["batched_steps"] += 1
return mine
+ def _pair(self, args: tuple, kwargs: dict, latent: Any, shape: _Shape) -> Any:
+ from .diffusion_cfg_pair import NotPairable, root_forward
+
+ torch = _torch()
+ module = self.module_ref()
+ root_fn = root_forward(module, self.orig_forward) if module is not None else None
+ if root_fn is None:
+ self.disable("the denoiser's own forward is no longer reachable below its hooks")
+ return None
+ try:
+ second = self._predict(latent)
+ snapshots = _snapshot(second)
+ except _NotBatchable as exc:
+ self._shape_off(shape, f"not pairable: {exc}")
+ return None
+ graphs = _graph_count()
+ try:
+ mine, other = self.paired.run(
+ module, self.orig_forward, root_fn, (args, kwargs), second
+ )
+ except NotPairable as exc:
+ self._shape_off(shape, f"not pairable: {exc}")
+ return None
+ except Exception as exc: # noqa: BLE001 - the branch reruns plain
+ if _is_oom(exc):
+ try:
+ torch.cuda.empty_cache()
+ except Exception: # noqa: BLE001
+ pass
+ self._shape_off(shape, "out of memory on the paired call", _OFF_TRANSIENT)
+ return None
+ self.disable(f"the paired call failed ({type(exc).__name__}: {exc})")
+ return None
+ if _graph_count() != graphs:
+ self.pending_disable = "the paired call compiled a new graph"
+ self.kept = {"out": other, "snapshots": snapshots, "latent": latent}
+ self.stats["paired_steps"] += 1
+ return mine
+
def _take(self, args: tuple, kwargs: dict, shape: _Shape) -> Any:
kept, self.kept = self.kept, None
if not _matches(kept["snapshots"], (args, kwargs)):
@@ -1082,6 +1177,18 @@ def _install(
transformer_quant: Optional[str] = None,
logger: Any = None,
) -> Optional[str]:
+ if cfg_pair_decline(pipe, offload_policy = offload_policy) is None:
+ from .diffusion_cfg_pair import PairedForward
+
+ denoiser = pipe.transformer
+ router = CfgBatchRouter(
+ denoiser,
+ reason = f"offloaded denoiser ({offload_policy}): both branches run each streamed block",
+ logger = logger,
+ )
+ router.offloaded = True
+ router.paired = PairedForward(denoiser)
+ return _arm(pipe, denoiser, router, logger)
reason = cfg_batch_decline(pipe, offload_policy = offload_policy, speed_mode = speed_mode)
if reason is not None:
if logger is not None:
@@ -1101,6 +1208,10 @@ def _install(
)
router.offloaded = _offloaded(denoiser, offload_policy)
router.identity = _load_identity(denoiser, offload_policy, speed_mode, transformer_quant)
+ return _arm(pipe, denoiser, router, logger)
+
+
+def _arm(pipe: Any, denoiser: Any, router: CfgBatchRouter, logger: Any) -> Optional[str]:
try:
_ROUTERS[pipe] = router
except TypeError:
diff --git a/studio/backend/core/inference/diffusion_cfg_pair.py b/studio/backend/core/inference/diffusion_cfg_pair.py
new file mode 100644
index 00000000000..7ea75ec230e
--- /dev/null
+++ b/studio/backend/core/inference/diffusion_cfg_pair.py
@@ -0,0 +1,215 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Streamed denoiser: each block runs both guidance branches while its weights are on the card, so a step uploads
+them once instead of once per branch. Every block call keeps its plain inputs and shapes, so outputs are
+bit-identical. UNSLOTH_DIFFUSION_CFG_PAIR=0 streams each branch on its own."""
+
+from __future__ import annotations
+
+import os
+from typing import Any, Optional
+
+CFG_PAIR_ENV = "UNSLOTH_DIFFUSION_CFG_PAIR"
+
+# class -> (block list attribute, the block output's names in the next block's keyword arguments)
+PAIRED_CLASSES = {
+ "QwenImageTransformer2DModel": (
+ "transformer_blocks",
+ ("encoder_hidden_states", "hidden_states"),
+ ),
+}
+
+_OFF = ("0", "off", "false", "no", "disable", "disabled")
+
+
+def cfg_pair_enabled() -> bool:
+ return (os.environ.get(CFG_PAIR_ENV) or "").strip().lower() not in _OFF
+
+
+class NotPairable(Exception):
+ pass
+
+
+class _Captured(Exception):
+ pass
+
+
+def _bg() -> Any:
+ from . import diffusion_block_graph as bg
+ return bg
+
+
+def _hook_refs(module: Any) -> list:
+ return list(getattr(getattr(module, "_diffusers_hook", None), "_fn_refs", None) or ())
+
+
+def below_hook_ref(block: Any) -> Any:
+ """The offload hook reference whose ``forward`` is the block's own compute (compiled below the hook or not)."""
+ bg = _bg()
+ if bg._group_offload_hook(block) is None:
+ return None
+ refs = _hook_refs(block)
+ target = getattr(block, "_unsloth_below_hook_ref", None)
+ if any(r is target for r in refs):
+ return target
+ for r in refs:
+ if bg._own_forward(getattr(r, "forward", None), block) is not None:
+ return r
+ return None
+
+
+def root_forward(module: Any, fallback: Any = None) -> Any:
+ """The forward below the denoiser's top-level offload hook, else ``fallback`` if that is the plain forward."""
+ bg = _bg()
+ for r in _hook_refs(module):
+ fn = getattr(r, "forward", None)
+ if bg._own_forward(fn, module) is not None:
+ return fn
+ if not _hook_refs(module) and bg._own_forward(fallback, module) is not None:
+ return fallback
+ return None
+
+
+def _spec(module: Any) -> Optional[tuple]:
+ cls = type(module)
+ if not cls.__module__.startswith("diffusers."):
+ return None
+ return PAIRED_CLASSES.get(cls.__name__)
+
+
+def _streams_a_block(module: Any) -> bool:
+ try:
+ from .diffusion_memory import _offload_groups
+ return any(
+ not getattr(g, "_unsloth_resident", False)
+ and getattr(g, "offload_leader", None) is not module
+ for g in _offload_groups(module)
+ )
+ except Exception: # noqa: BLE001 - unreadable layout: treat as streamed, the block checks still apply
+ return True
+
+
+def pair_decline(module: Any, fallback_forward: Any = None) -> Optional[str]:
+ if not cfg_pair_enabled():
+ return f"{CFG_PAIR_ENV}=0"
+ spec = _spec(module)
+ if spec is None:
+ return f"{type(module).__name__} has no paired block loop"
+ import torch
+
+ blocks = getattr(module, "_modules", {}).get(spec[0])
+ if not isinstance(blocks, torch.nn.ModuleList) or not len(blocks):
+ return "no block list"
+ if any(below_hook_ref(b) is None for b in blocks):
+ return "a block runs without an offload hook to pair below"
+ inside = {id(m) for b in blocks for m in b.modules()}
+ for name, sub in module.named_modules():
+ if sub is module or id(sub) in inside:
+ continue
+ if (
+ getattr(sub, "_diffusers_hook", None) is not None
+ or getattr(sub, "_hf_hook", None) is not None
+ ):
+ return f"{name} carries its own hook"
+ if root_forward(module, fallback_forward) is None:
+ return "the denoiser's own forward is not reachable below its hooks"
+ if not _streams_a_block(module):
+ return "every block stays resident"
+ return None
+
+
+def _modules() -> tuple:
+ import torch
+
+ class _Probe(torch.nn.Module):
+ call: Any = None
+
+ def forward(self, *args: Any, **kwargs: Any) -> Any:
+ self.call = (args, kwargs)
+ raise _Captured
+
+ class _Inject(torch.nn.Module):
+ out: Any = None
+
+ def forward(self, *args: Any, **kwargs: Any) -> Any:
+ return self.out
+
+ return _Probe, _Inject
+
+
+class PairedForward:
+ """Second branch rides the first's block calls; its prologue/epilogue run the stock forward on a one-block list."""
+
+ def __init__(self, module: Any) -> None:
+ import torch
+
+ probe_cls, inject_cls = _modules()
+ self.probe, self.inject = probe_cls(), inject_cls()
+ self.probe_list = torch.nn.ModuleList([self.probe])
+ self.inject_list = torch.nn.ModuleList([self.inject])
+ self.blocks_attr, self.carry = _spec(module)
+
+ def run(self, module: Any, outer: Any, root_fn: Any, first: tuple, second: tuple) -> tuple:
+ """(first output, second output). ``outer`` is the hooked forward a plain first-branch call goes through."""
+ (args1, kwargs1), (args2, kwargs2) = first, second
+ if args1 or args2:
+ raise NotPairable("positional arguments")
+ for kw in (kwargs1, kwargs2):
+ if kw.get("controlnet_block_samples") is not None:
+ raise NotPairable("ControlNet residuals")
+ att = kw.get("attention_kwargs") or {}
+ if isinstance(att, dict) and att.get("scale", 1.0) != 1.0:
+ raise NotPairable("a LoRA scale in attention_kwargs")
+ mods = module._modules
+ blocks = mods[self.blocks_attr]
+ refs = [below_hook_ref(b) for b in blocks]
+ if any(r is None for r in refs):
+ raise NotPairable("a block lost its offload hook")
+ last = len(blocks) - 1
+ state: dict = {}
+
+ def nested(stand_in: Any) -> Any:
+ saved = mods[self.blocks_attr]
+ mods[self.blocks_attr] = stand_in
+ try:
+ return root_fn(**kwargs2)
+ finally:
+ mods[self.blocks_attr] = saved
+
+ def paired(index: int, compute: Any) -> Any:
+ def call(*a: Any, **k: Any) -> Any:
+ out = compute(*a, **k)
+ if index == 0:
+ try:
+ nested(self.probe_list)
+ except _Captured:
+ pass
+ p_args, p_kwargs = self.probe.call
+ self.probe.call = None
+ if p_args:
+ raise NotPairable("positional block arguments")
+ state["kwargs"] = dict(p_kwargs)
+ second_out = compute(**state["kwargs"])
+ state["kwargs"].update(zip(self.carry, second_out))
+ if index == last:
+ self.inject.out = second_out
+ try:
+ state["out"] = nested(self.inject_list)
+ finally:
+ self.inject.out = None
+ return out
+
+ return call
+
+ saved = [r.forward for r in refs]
+ try:
+ for i, r in enumerate(refs):
+ r.forward = paired(i, saved[i])
+ mine = outer(*args1, **kwargs1)
+ finally:
+ for r, fn in zip(refs, saved):
+ r.forward = fn
+ if "out" not in state:
+ raise NotPairable("the forward never reached its last block")
+ return mine, state["out"]
diff --git a/studio/backend/core/inference/diffusion_speed.py b/studio/backend/core/inference/diffusion_speed.py
index 72a7453feda..991a07d694f 100644
--- a/studio/backend/core/inference/diffusion_speed.py
+++ b/studio/backend/core/inference/diffusion_speed.py
@@ -711,6 +711,20 @@ def arm_graphs_after_placement(
pipe._unsloth_cuda_graph_reason = "offload active"
applied["cuda_graph"] = False
return applied
+ from .diffusion_cfg_batch import cfg_pair_decline # noqa: PLC0415 - import cycle
+
+ if cfg_pair_decline(pipe, graphs = False) is None:
+ cuda_graph.uninstall_all(getattr(pipe, "_unsloth_cuda_graphs", ()) or ())
+ pipe._unsloth_cuda_graphs = ()
+ pipe._unsloth_cuda_graph_after_placement = False
+ pipe._unsloth_cuda_graph_reason = "guidance branches pair per streamed block"
+ applied["cuda_graph"] = False
+ if logger is not None:
+ logger.info(
+ "diffusion.cuda_graph: off for this load (both guidance branches share each streamed "
+ "block's upload instead)"
+ )
+ return applied
handles, reason = cuda_graph.arm_after_placement(pipe, logger = logger)
pipe._unsloth_cuda_graph_after_placement = False
pipe._unsloth_cuda_graph_reason = reason
diff --git a/studio/backend/tests/test_diffusion_cfg_pair.py b/studio/backend/tests/test_diffusion_cfg_pair.py
new file mode 100644
index 00000000000..ced2159f0fd
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_cfg_pair.py
@@ -0,0 +1,167 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+import pytest
+import torch
+
+from core.inference import diffusion_cfg_batch as cb
+from core.inference import diffusion_cfg_pair as cp
+
+diffusers = pytest.importorskip("diffusers")
+QwenImageTransformer2DModel = diffusers.QwenImageTransformer2DModel
+from diffusers.hooks import apply_group_offloading # noqa: E402
+
+
+def _tiny(zero_cond_t = True, layers = 3):
+ torch.manual_seed(0)
+ m = QwenImageTransformer2DModel(
+ patch_size = 2,
+ in_channels = 16,
+ out_channels = 4,
+ num_layers = layers,
+ attention_head_dim = 8,
+ num_attention_heads = 2,
+ joint_attention_dim = 12,
+ axes_dims_rope = (2, 2, 4),
+ zero_cond_t = zero_cond_t,
+ ).eval()
+ return m
+
+
+def _offload(m):
+ apply_group_offloading(
+ m, onload_device = torch.device("cpu"), offload_type = "block_level", num_blocks_per_group = 1
+ )
+ return m
+
+
+class _Pipe:
+ def __init__(self, transformer):
+ self.transformer = transformer
+
+
+def _edit_loop(
+ model,
+ steps = 4,
+ *,
+ neg_len = 3,
+ scale = 4.0,
+ swap_neg_at = None,
+):
+ """The diffusers Qwen-Image-Edit-Plus loop: one ``latent_model_input`` per step (target + source image tokens),
+ cond then uncond call with their own prompt lengths and masks, normalised true CFG."""
+ g = torch.Generator().manual_seed(1)
+ latents = torch.randn(1, 16, 16, generator = g)
+ image_latents = torch.randn(1, 16, 16, generator = g)
+ pos = torch.randn(1, 7, 12, generator = g)
+ neg = torch.randn(1, neg_len, 12, generator = g)
+ pos_mask = torch.ones(1, 7, dtype = torch.long)
+ neg_mask = torch.ones(1, neg_len, dtype = torch.long)
+ img_shapes = [[(1, 4, 4), (1, 4, 4)]]
+ outs = []
+ with torch.no_grad():
+ for i in range(steps):
+ if i == swap_neg_at:
+ neg = torch.randn(1, neg_len, 12, generator = g)
+ latent_model_input = torch.cat([latents, image_latents], dim = 1)
+ t = torch.full((1,), 1000.0 - 200 * i)
+ common = dict(
+ hidden_states = latent_model_input,
+ timestep = t / 1000,
+ guidance = None,
+ img_shapes = img_shapes,
+ attention_kwargs = None,
+ return_dict = False,
+ )
+ cond = model(encoder_hidden_states_mask = pos_mask, encoder_hidden_states = pos, **common)[
+ 0
+ ][:, : latents.size(1)]
+ uncond = model(
+ encoder_hidden_states_mask = neg_mask, encoder_hidden_states = neg, **common
+ )[0][:, : latents.size(1)]
+ comb = uncond + scale * (cond - uncond)
+ pred = comb * (cond.norm(dim = -1, keepdim = True) / comb.norm(dim = -1, keepdim = True))
+ latents = latents - 0.1 * pred
+ outs.append(pred)
+ return latents, outs
+
+
+def _block_calls(model):
+ counts = [0] * len(model.transformer_blocks)
+ for i, b in enumerate(model.transformer_blocks):
+ b.register_forward_pre_hook(lambda *_a, _i = i: counts.__setitem__(_i, counts[_i] + 1))
+ return counts
+
+
[email protected]("zero_cond_t", [True, False])
+def test_paired_steps_are_bit_identical_and_upload_each_block_once(zero_cond_t):
+ ref, ref_outs = _edit_loop(_offload(_tiny(zero_cond_t)))
+ model = _offload(_tiny(zero_cond_t))
+ pipe = _Pipe(model)
+ assert cb.install_cfg_batch(pipe, offload_policy = "group") is None
+ router = cb.router_for(pipe)
+ assert router.paired is not None
+ counts = _block_calls(model)
+ got, outs = _edit_loop(model, steps = 4)
+ assert torch.equal(got, ref)
+ assert all(torch.equal(a, b) for a, b in zip(outs, ref_outs))
+ # step 1 plain (2 calls per block), steps 2-4 paired (1 call per block)
+ assert counts == [2 + 3] * len(counts)
+ assert router.stats["paired_steps"] == 3 and router.stats["hits"] == 3
+ assert router.describe()["mode"] == "pair"
+ cb.end_cfg_batch_render(pipe)
+ got2, _ = _edit_loop(model, steps = 4)
+ assert torch.equal(got2, ref)
+ assert router.stats["paired_steps"] == 6
+
+
+def test_a_changed_second_branch_reruns_plain():
+ ref, ref_outs = _edit_loop(_offload(_tiny()), steps = 5, swap_neg_at = 3)
+ model = _offload(_tiny())
+ pipe = _Pipe(model)
+ cb.install_cfg_batch(pipe, offload_policy = "group")
+ router = cb.router_for(pipe)
+ got, outs = _edit_loop(model, steps = 5, swap_neg_at = 3)
+ assert torch.equal(got, ref)
+ assert all(torch.equal(a, b) for a, b in zip(outs, ref_outs))
+ assert (
+ router.stats["misses"] == 1
+ and router.stats["paired_steps"] == 4
+ and router.stats["hits"] == 3
+ )
+
+
+def test_kill_switch_keeps_the_batch_router(monkeypatch):
+ monkeypatch.setenv(cp.CFG_PAIR_ENV, "0")
+ model = _offload(_tiny())
+ pipe = _Pipe(model)
+ assert cb.cfg_pair_decline(pipe, offload_policy = "group") == f"{cp.CFG_PAIR_ENV}=0"
+ cb.install_cfg_batch(pipe, offload_policy = "group")
+ router = cb.router_for(pipe)
+ assert router is None or router.paired is None
+ if router is not None:
+ cb.uninstall_cfg_batch(pipe)
+
+
+def test_declines_a_resident_or_unhooked_denoiser():
+ assert (
+ cb.cfg_pair_decline(_Pipe(_tiny()), offload_policy = "none")
+ == "the denoiser stays on the card"
+ )
+ model = _offload(_tiny())
+ assert cb.cfg_pair_decline(_Pipe(model), offload_policy = "group") is None
+ pipe = _Pipe(model)
+ pipe._unsloth_cuda_graphs = (object(),)
+ assert cb.cfg_pair_decline(pipe, offload_policy = "group") == "the denoiser replays CUDA graphs"
+ assert cb.cfg_pair_decline(pipe, offload_policy = "group", graphs = False) is None
+
+
+def test_a_lora_scale_or_controlnet_call_stays_plain():
+ model = _offload(_tiny())
+ pf = cp.PairedForward(model)
+ with pytest.raises(cp.NotPairable):
+ pf.run(model, model.forward, None, ((), {"attention_kwargs": {"scale": 0.5}}), ((), {}))
+ with pytest.raises(cp.NotPairable):
+ pf.run(model, model.forward, None, ((), {"controlnet_block_samples": [1]}), ((), {}))