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: offloaded diffusion runs both guidance branches in one batched call whenever memory allows (#16261)

Daniel Hancaf0a3bb7a94
diff --git a/studio/backend/core/inference/diffusion_cfg_batch.py b/studio/backend/core/inference/diffusion_cfg_batch.py
index e1c60bbe95a..c083d53de4e 100644
--- a/studio/backend/core/inference/diffusion_cfg_batch.py
+++ b/studio/backend/core/inference/diffusion_cfg_batch.py
@@ -1,9 +1,10 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Batches CFG branches into one forward for stateless denoisers only; a second call differing from
-the batched inputs reruns that branch plain; not always bit-exact; UNSLOTH_DIFFUSION_CFG_BATCH=0
-keeps one branch per call; UNSLOTH_DIFFUSION_CFG_BATCH_COMPILED=0 keeps a compiled resident Wan plain"""
+"""Batches CFG branches into one forward for stateless denoisers only (offloaded: whenever the doubled call fits;
+resident: where a per-shape timing trial measured a win); a second call differing from the batched inputs reruns
+that branch plain; not always bit-exact; UNSLOTH_DIFFUSION_CFG_BATCH=0 keeps one branch per call, =timed times
+offloaded loads too; UNSLOTH_DIFFUSION_CFG_BATCH_COMPILED=0 keeps a compiled resident denoiser plain"""
from __future__ import annotations
@@ -16,25 +17,64 @@ from typing import Any, Optional
CFG_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).
+# The CFG policy of every denoiser class Studio loads (test_diffusion_cfg_batch_policy pins it to diffusion_families
+# and video_families): exactly one of the three tables below.
+#
+# Batched by this router: the forward keeps no state between calls and both branches share every per-step input but
+# the text conditioning (diffusers 0.42.1 pipelines: same latent object, cond then uncond call). FLUX.3 batches only
+# when both prompts land in the same 80-token window (its transformer attends the padding, so a padded branch would
+# not be the same computation); a shorter negative keeps that shape plain.
STATELESS_CLASSES = frozenset(
{
"Flux2Transformer2DModel",
+ "Flux3Transformer2DModel",
"FluxTransformer2DModel",
+ "HunyuanImageTransformer2DModel",
+ "HunyuanVideo15Transformer3DModel",
+ "Krea2Transformer2DModel",
"QwenImageTransformer2DModel",
"WanTransformer3DModel",
}
)
+# The pipeline already runs both branches in one call (nothing for the router to pair).
+PIPELINE_BATCHED: dict[str, str] = {
+ "ZImageTransformer2DModel": "the pipeline batches the branches (a list of latents, one call per step)",
+ "HiDreamImageTransformer2DModel": "the pipeline batches the branches (torch.cat([latents] * 2))",
+ "LTX2VideoTransformer3DModel": "the pipeline batches the branches (torch.cat([latents] * 2))",
+ "UNet2DConditionModel": "the pipeline batches the branches (torch.cat([latents] * 2))",
+}
+
+# Two calls per step that are not the same computation on a doubled batch.
+NOT_BATCHABLE: dict[str, str] = {
+ "QwenImage21Transformer2DModel": "each branch passes its own prefix KV cache object",
+ "Ideogram4Transformer2DModel": "the negative branch runs a separate unconditional transformer on image-only tokens",
+ "MOSSImageTransformer": "the negative branch skips block 22 (uncond_skip_layers): per-branch compute",
+ "Cosmos3OmniTransformer": "each branch packs its own variable-length token sequence",
+ "MiniMaxH3Transformer3DModel": "one denoiser call per step (no guidance pair to batch)",
+ # Measured (Colab L4, 1024x1024, 8 steps): 1.817 vs 1.454 s/step eager, 1.312 vs 1.078 compiled. A single call
+ # packs each prompt at its own caption length with no mask; the doubled call pads both to the longer one and runs
+ # masked attention.
+ "Lumina2Transformer2DModel": "measured slower batched: the doubled call pads both captions and runs masked "
+ "attention (L4 +25% eager, +22% compiled)",
+}
+
# Arguments that are one entry per sample (a doubled call needs both branches' entries); compared, not concatenated.
_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"),)
+_PADDED_TEXT = (
+ ("encoder_hidden_states", "encoder_hidden_states_mask"),
+ ("encoder_hidden_states", "encoder_attention_mask"),
+)
-# Compiled + resident, batched with no trial: measured 1-2% win on an L4, below the trial's 8% bar.
+# Compiled + resident, batched with no trial (measured: Wan 1-2% on an L4). A batch-2 graph per compiled block is
+# compiled once, in the shape's warm-up render; later prompts of that shape compile nothing.
COMPILED_RESIDENT_CLASSES = frozenset({"WanTransformer3DModel"})
+# Measured slower batched than two calls: (class, card-name substring, "eager" | "compiled") -> measurement. Only
+# these keep two calls under the default; =force still batches them.
+MEASURED_SLOWER: dict[tuple[str, str, str], str] = {}
+
_MEASURED_FRACTION = 0.92
_BATCHED_SAMPLES = 2
_PLAIN_STEPS = 2
@@ -45,16 +85,42 @@ _OFF_TRANSIENT = "transient"
def cfg_batch_mode() -> str:
- """``off`` / ``auto`` (default: a listed class, resident or offloaded) / ``force``. Independent of the multi-GPU
- switches: a single card is the usual case."""
+ """``off`` / ``auto`` (default: a listed class; offloaded, batched whenever the doubled call fits; resident, after the
+ per-shape timing trial) / ``timed`` (the trial for offloaded loads too) / ``force`` (no trial, any class).
+ Independent of the multi-GPU switches: a single card is the usual case."""
raw = (os.environ.get(CFG_BATCH_ENV) or "").strip().lower()
if raw in ("0", "off", "false", "no", "disable", "disabled"):
return "off"
- if raw == "force":
- return "force"
+ if raw in ("force", "timed"):
+ return raw
return "auto"
+def cfg_policy(denoiser: Any) -> tuple[str, Optional[str]]:
+ """(``batch`` | ``pipeline`` | ``never`` | ``unlisted``, reason) for ``denoiser``'s class."""
+ name = type(denoiser).__name__
+ if name in PIPELINE_BATCHED:
+ return "pipeline", PIPELINE_BATCHED[name]
+ if name in NOT_BATCHABLE:
+ return "never", NOT_BATCHABLE[name]
+ if name in STATELESS_CLASSES and type(denoiser).__module__.startswith("diffusers."):
+ return "batch", None
+ return (
+ "unlisted",
+ f"{name} is not on the stateless-forward list ({CFG_BATCH_ENV}=force opts it in)",
+ )
+
+
+def measured_slower(denoiser: Any, card: Optional[str], compiled: bool) -> Optional[str]:
+ """The measurement that keeps this class on this card plain under the default, else None."""
+ name = type(denoiser).__name__
+ kind = "compiled" if compiled else "eager"
+ for (cls, card_part, k), why in MEASURED_SLOWER.items():
+ if cls == name and k == kind and card and card_part.lower() in card.lower():
+ return why
+ return None
+
+
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()
@@ -227,10 +293,9 @@ def cfg_batch_decline(
return f"per-call activation scaling ({scaled})"
if mode == "force":
return None
- if type(denoiser).__name__ not in STATELESS_CLASSES or not type(denoiser).__module__.startswith(
- "diffusers."
- ):
- return f"{type(denoiser).__name__} is not on the stateless-forward list ({CFG_BATCH_ENV}=force opts it in)"
+ policy, why = cfg_policy(denoiser)
+ if policy != "batch":
+ return why
if offload_policy == "model":
# diffusers rebuilds model-offload hooks between renders, evicting the router: later renders would differ.
return "model offload re-hooks the denoiser every render"
@@ -477,6 +542,7 @@ class CfgBatchRouter:
lambda: False
)
self.orig_forward = module.forward
+ self._mirror_signature()
self.had_override = "forward" in module.__dict__
self.prev_override = module.__dict__.get("forward")
self.reason = reason
@@ -548,6 +614,8 @@ class CfgBatchRouter:
)
if self.render_checked:
self.renders += 1
+ if self._displaced():
+ self._retake_slot()
if self.pending_disable is not None:
self.disable(self.pending_disable)
self.pair_t0 = None
@@ -589,6 +657,38 @@ class CfgBatchRouter:
module = self.module_ref()
return module is None or module.__dict__.get("forward") is not self
+ def _mirror_signature(self) -> None:
+ """FLUX.3's modular denoise step passes only the kwargs named in ``transformer.forward``'s signature
+ (``img_ids``): a bare ``**kwargs`` signature here would drop them."""
+ import inspect
+ try:
+ self.__signature__ = inspect.signature(self.orig_forward)
+ except (TypeError, ValueError):
+ pass
+
+ def _retake_slot(self) -> bool:
+ """Back in the forward slot after a diffusers hook removal wrote the class forward over it. A streamed
+ (``use_stream``) group offload drops its lazy-prefetch hook from the root after the first forward and restores
+ ``module.forward`` to the bound class forward, which bypassed the router for the rest of the load. Only that
+ exact slot is retaken (a CUDA graph or another layer that took the slot is left alone)."""
+ module = self.module_ref()
+ if module is None:
+ return False
+ slot = module.__dict__.get("forward")
+ if slot is self or getattr(slot, "__self__", None) is not module:
+ return False
+ if getattr(slot, "__func__", None) is not getattr(type(module), "forward", None):
+ return False
+ self.orig_forward = slot
+ self._mirror_signature()
+ module.__dict__["forward"] = self
+ self.stats["retaken"] = self.stats.get("retaken", 0) + 1
+ if self.logger is not None:
+ self.logger.info(
+ "diffusion.cfg_batch: back in the forward slot (a removed offload hook restored the class forward)"
+ )
+ return True
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
if self._is_compiling():
return self.orig_forward(*args, **kwargs)
@@ -609,9 +709,17 @@ class CfgBatchRouter:
if self.render_compiled is not None:
if not self.offloaded and not self.compiled_resident:
self.render_off = f"{self.render_compiled} and resident"
+ rejudge = self._untimed_mode() and (self.offloaded or self.compiled_resident)
for shape in self.shapes.values():
if shape.judged and not shape.compiled_at_trial and shape.off is None:
- self._shape_off(shape, "the denoiser was compiled after this shape's trial")
+ if rejudge:
+ # compiled after an eager render (the deferred profile): this render is the shape's
+ # compile warm-up, so its batch-2 graph is compiled here, once
+ shape.judged = False
+ else:
+ self._shape_off(
+ shape, "the denoiser was compiled after this shape's trial"
+ )
self.render_checked = True
if self.render_off is not None:
return self._plain(args, kwargs)
@@ -654,7 +762,7 @@ class CfgBatchRouter:
out = self._plain(args, kwargs)
if self.paired is not None:
return out
- if self.compiled_resident:
+ if self._untimed_mode():
if not shape.judged and self.disabled is None:
self._untimed(shape, latent)
return out
@@ -691,21 +799,44 @@ class CfgBatchRouter:
self.disable("more than two denoiser calls per step")
return self._plain(args, kwargs)
+ def _untimed_mode(self) -> bool:
+ """No timing trial: an offloaded denoiser batches whenever the doubled call fits (it saves one weight upload
+ per step), and so does a compiled resident one (a trial would compile the batch-2 graph anyway). A resident
+ eager load keeps the trial: measured speed-neutral on L4 / T4, so it batches only where it wins. ``timed``
+ puts offloaded loads back on the trial; ``force`` skips it everywhere."""
+ mode = cfg_batch_mode()
+ if mode == "force":
+ return True
+ if mode == "timed":
+ return self.compiled_resident
+ return self.compiled_resident or self.offloaded
+
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
+ return 1 if self._untimed_mode() 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":
+ """No trial: batched from step 2 under the memory gate. A resident denoiser off CUDA has no memory gate (and
+ was never measured there), so it stays plain unless forced."""
+ forced = cfg_batch_mode() == "force"
+ if not _cuda_latent(latent) and not self.offloaded and not forced:
self._shape_off(
shape,
- f"compiled resident batching is measured on CUDA only ({CFG_BATCH_ENV}=force batches anyway)",
+ f"resident batching is measured on CUDA only ({CFG_BATCH_ENV}=force batches anyway)",
)
return
+ module = self.module_ref()
+ slower = (
+ None
+ if forced or module is None or not _cuda_latent(latent)
+ else measured_slower(module, _card_name(latent), self.render_compiled is not None)
+ )
+ if slower is not None:
+ self._shape_off(shape, f"measured slower batched on this card ({slower})")
+ 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
+ shape.compiled_at_trial = self.render_compiled is not None
if self._memory_ok(latent, shape):
self._judge(shape)
else:
@@ -736,7 +867,10 @@ class CfgBatchRouter:
def _plain(self, args: tuple, kwargs: dict) -> Any:
self.stats["plain_calls"] += 1
- return self.orig_forward(*args, **kwargs)
+ out = self.orig_forward(*args, **kwargs)
+ if self.offloaded and self.stats["plain_calls"] <= 2 and self._displaced():
+ self._retake_slot()
+ return out
def _sync(self, latent: Any) -> bool:
if getattr(latent.device, "type", None) != "cuda":
@@ -1085,13 +1219,17 @@ def _pad_text(first: dict, second: dict) -> None:
"""Pad the shorter prompt's embeddings (and its mask) with masked zeros so both branches stack (Qwen-Image pads
each prompt to its own length; the masked keys leave every image token's attention unchanged)."""
torch = _torch()
+ masks: dict = {}
for emb_key, mask_key in _PADDED_TEXT:
+ masks.setdefault(emb_key, []).append(mask_key)
+ for emb_key, mask_keys in masks.items():
a, b = first.get(emb_key), second.get(emb_key)
if not (isinstance(a, torch.Tensor) and isinstance(b, torch.Tensor)) or a.dim() < 3:
continue
if a.shape[1] == b.shape[1]:
continue
- if mask_key not in first and mask_key not in second:
+ mask_key = next((k for k in mask_keys if k in first or k in second), None)
+ if mask_key is None:
raise _NotBatchable(f"{emb_key}: prompt lengths differ and the model takes no mask")
length = max(a.shape[1], b.shape[1])
given = [
diff --git a/studio/backend/tests/test_diffusion_cfg_batch.py b/studio/backend/tests/test_diffusion_cfg_batch.py
index db970cdf5f1..9b49e045520 100644
--- a/studio/backend/tests/test_diffusion_cfg_batch.py
+++ b/studio/backend/tests/test_diffusion_cfg_batch.py
@@ -152,9 +152,10 @@ def test_batched_steps_match_two_calls_and_engage(monkeypatch):
pipe, router = _armed(model, monkeypatch)
got, _ = _flux_loop(model)
torch.testing.assert_close(got, ref)
- assert router.stats["batched_steps"] == 4 and router.stats["hits"] == 4
- assert model.calls[-2:] == [2, 2]
- assert cb.cfg_batch_status(pipe)["batched_steps"] == 4
+ # offloaded: no timing trial, step 1 records the second call, steps 2-6 run doubled
+ assert router.stats["batched_steps"] == 5 and router.stats["hits"] == 5
+ assert model.calls == [1, 1] + [2] * 5
+ assert cb.cfg_batch_status(pipe)["batched_steps"] == 5
cb.end_cfg_batch_render(pipe)
assert cb.cfg_batch_status(pipe)["plain_pair_s"] is None
assert cb.cfg_batch_status(pipe)["shape_off"] is None
@@ -162,6 +163,7 @@ def test_batched_steps_match_two_calls_and_engage(monkeypatch):
@pytest.mark.skipif(not torch.cuda.is_available(), reason = "needs a CUDA device timer")
def test_cuda_latents_time_the_step_two_pair_and_keep_the_image(monkeypatch):
+ monkeypatch.setenv(cb.CFG_BATCH_ENV, "timed")
ref, _ = _flux_loop(_offloaded(Flux2Transformer2DModel()).cuda(), device = "cuda")
model = Flux2Transformer2DModel().cuda()
pipe, router = _armed(model, monkeypatch)
@@ -196,7 +198,7 @@ def test_wan_expanded_timesteps_serve_the_second_branch(monkeypatch):
model = Flux2Transformer2DModel()
_pipe, router = _armed(model, monkeypatch)
torch.testing.assert_close(loop(model), ref)
- assert router.stats["hits"] == 4 and router.stats["misses"] == 0, router.describe()
+ assert router.stats["hits"] == 5 and router.stats["misses"] == 0, router.describe()
assert router.shape.off is None
@@ -232,7 +234,7 @@ def test_qwen_unequal_prompt_lengths_and_img_shapes_batch(monkeypatch):
model = QwenImageTransformer2DModel()
_pipe, router = _armed(model, monkeypatch)
torch.testing.assert_close(loop(model), ref)
- assert router.stats["batched_steps"] == 4, router.describe()
+ assert router.stats["batched_steps"] == 5, router.describe()
def test_a_changed_second_branch_reruns_plain_and_stops_after_three_misses(monkeypatch):
@@ -248,7 +250,7 @@ def test_a_changed_second_branch_reruns_plain_and_stops_after_three_misses(monke
_pipe, router = _armed(model, monkeypatch)
got, _ = _flux_loop(model, steps = 8, neg = torch.zeros(1, 5, 8), between = between)
torch.testing.assert_close(got, ref, rtol = 0, atol = 0)
- assert router.stats["misses"] == 3 and router.stats["hits"] == 1
+ assert router.stats["misses"] == 3 and router.stats["hits"] == 2
assert router.shape.off is not None and "3 consecutive misses" in router.shape.off
@@ -297,6 +299,18 @@ def test_install_uninstall_restores_the_forward_slot(monkeypatch):
assert cb.cfg_batch_status(pipe) is None
+def test_the_router_keeps_the_forward_signature(monkeypatch):
+ # FLUX.3's modular denoise step passes only the kwargs named in transformer.forward's signature (img_ids)
+ import inspect
+
+ model = Flux2Transformer2DModel()
+ _, router = _armed(model, monkeypatch)
+ assert model.forward is router
+ params = inspect.signature(model.forward).parameters
+ assert {"hidden_states", "img_ids", "txt_ids", "return_dict"} <= set(params)
+ assert "self" not in params
+
+
def test_switches_are_independent_of_multi_gpu(monkeypatch):
pipe = _Pipe(_offloaded(Flux2Transformer2DModel()))
monkeypatch.setenv("UNSLOTH_DIFFUSION_MULTIGPU", "0")
@@ -355,6 +369,8 @@ class _Clock:
def _timed(monkeypatch, cost):
+ # the opt-in timing trial (the default batches with no trial)
+ monkeypatch.setenv(cb.CFG_BATCH_ENV, "timed")
clock = _Clock(cost)
monkeypatch.setattr(cb.time, "perf_counter", clock)
monkeypatch.setattr(cb, "_RESIDENT_MAX_PAIR_S", 1e9)
@@ -478,18 +494,41 @@ def test_a_compile_on_a_resident_denoiser_after_install_keeps_every_render_plain
assert cb.cfg_batch_status(pipe)["render_off"] == "the denoiser is compiled and resident"
-def test_an_offloaded_shape_judged_before_a_compile_stays_plain_after_it(monkeypatch):
+def test_an_offloaded_shape_judged_before_a_compile_rejudges_in_the_compile_render(monkeypatch):
model = Flux2Transformer2DModel()
pipe, router = _armed(model, monkeypatch)
- _flux_loop(model) # eager render: trial on step 1, steps 2-6 batched
+ _flux_loop(model) # eager render: step 1 plain, steps 2-6 batched
cb.end_cfg_batch_render(pipe)
- assert router.stats["batched_steps"] == 4
+ assert router.stats["batched_steps"] == 5
model._unsloth_regional_compile_kwargs = {
"dynamic": False
- } # compiled below the offload hooks afterwards
+ } # compiled below the offload hooks afterwards (the deferred profile)
+ del model.calls[:]
+ graphs = iter(range(1000))
+ monkeypatch.setattr(cb, "_graph_count", lambda: next(graphs)) # every doubled call "compiles"
+ _flux_loop(model)
+ # the compile render is the shape's warm-up again: step 1 plain, then doubled (its batch-2 graph compiles here)
+ assert model.calls == [1, 1] + [2] * 5
+ assert router.last_shape.off is None and router.last_shape.compiled_at_trial
+ cb.end_cfg_batch_render(pipe)
+ assert router.disabled is None
+ monkeypatch.setattr(
+ cb, "_graph_count", lambda: 7
+ ) # warm: nothing compiles on a follow-up prompt
+ del model.calls[:]
+ _flux_loop(model)
+ assert model.calls == [1, 1] + [2] * 5 and router.disabled is None
+
+
+def test_the_timed_mode_keeps_a_shape_judged_before_a_compile_plain(monkeypatch):
+ model = Flux2Transformer2DModel()
+ pipe, router = _armed(model, monkeypatch, mode = "timed")
+ _flux_loop(model)
+ cb.end_cfg_batch_render(pipe)
+ model._unsloth_regional_compile_kwargs = {"dynamic": False}
del model.calls[:]
_flux_loop(model)
- assert model.calls == [1] * 12 # no doubled call reaches the new compile on a follow-up prompt
+ assert model.calls == [1] * 12
assert "compiled after this shape's trial" in router.last_shape.off
@@ -500,7 +539,7 @@ def test_an_offloaded_compiled_denoiser_batches_from_its_trial_render(monkeypatc
for _ in range(2):
_flux_loop(model)
cb.end_cfg_batch_render(pipe)
- assert router.stats["batched_steps"] == 8 and router.disabled is None
+ assert router.stats["batched_steps"] == 10 and router.disabled is None
assert router.last_shape.compiled_at_trial and router.last_shape.trial_render == 0
@@ -517,7 +556,7 @@ def test_a_doubled_call_compiling_on_a_follow_up_render_ends_batching_after_that
) # every doubled call "compiles" from now on
del model.calls[:]
_flux_loop(model)
- assert model.calls == [1, 1, 1, 1] + [2] * 4 # render 2 stays on its one path
+ assert model.calls == [1, 1] + [2] * 5 # render 2 stays on its one path
cb.end_cfg_batch_render(pipe)
assert "after its warm-up render" in router.disabled
del model.calls[:]
@@ -612,10 +651,18 @@ def test_declines(monkeypatch):
pass
ZImageTransformer2DModel.__module__ = "diffusers.models.fake"
- assert "not on the stateless-forward list" in cb.cfg_batch_decline(
+ assert "the pipeline batches the branches" in cb.cfg_batch_decline(
_Pipe(_offloaded(ZImageTransformer2DModel())), offload_policy = "group"
)
+ class SomeNewTransformer2DModel(Flux2Transformer2DModel):
+ pass
+
+ SomeNewTransformer2DModel.__module__ = "diffusers.models.fake"
+ assert "not on the stateless-forward list" in cb.cfg_batch_decline(
+ _Pipe(_offloaded(SomeNewTransformer2DModel())), offload_policy = "group"
+ )
+
class ComfyNVFP4DynamicLinear(torch.nn.Linear):
pass
@@ -798,7 +845,7 @@ def _switchable(
the verdict store in ``tmp_path``. ``raising = False``: main has no store, so the behaviour is what fails there."""
cost = {"batched": 1.2}
model = _timed(monkeypatch, lambda b: 1.0 if b == 1 else cost["batched"])
- monkeypatch.setenv(cb.CFG_BATCH_ENV, "auto")
+ monkeypatch.setenv(cb.CFG_BATCH_ENV, "timed")
monkeypatch.setenv("UNSLOTH_DIFFUSION_CFG_BATCH_VERDICTS_FILE", str(tmp_path / "verdicts.json"))
monkeypatch.setattr(cb, "_card_name", lambda latent: card, raising = False)
return model, cost
@@ -1009,3 +1056,21 @@ def test_a_version_1_verdict_store_is_not_read(monkeypatch, tmp_path):
)
)
assert cb.stored_verdict("k") == entry["k"]
+
+
[email protected]("batched_cost, wins", [(1.2, True), (2.0, False)])
+def test_the_default_times_a_resident_eager_load_and_skips_the_trial_offloaded(
+ monkeypatch, batched_cost, wins
+):
+ model = _timed(monkeypatch, lambda b: 1.0 if b == 1 else batched_cost)
+ monkeypatch.delenv(cb.CFG_BATCH_ENV, raising = False)
+ pipe = _Pipe(model)
+ assert cb.install_cfg_batch(pipe, offload_policy = "none") is None
+ calls = _render(pipe, model)
+ assert calls[4:10] == _TRIAL # resident eager: the trial still prices the shape
+ assert calls[10:] == ([2] * 4 if wins else [1] * 8)
+ off = _timed(monkeypatch, lambda b: 1.0 if b == 1 else 2.0) # slower batched, but offloaded
+ monkeypatch.delenv(cb.CFG_BATCH_ENV, raising = False)
+ opipe = _Pipe(_offloaded(off))
+ assert cb.install_cfg_batch(opipe, offload_policy = "group") is None
+ assert _render(opipe, off) == [1, 1] + [2] * 5 # no trial: batched from step 2
diff --git a/studio/backend/tests/test_diffusion_cfg_batch_policy.py b/studio/backend/tests/test_diffusion_cfg_batch_policy.py
new file mode 100644
index 00000000000..c19b8bdd79f
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_cfg_batch_policy.py
@@ -0,0 +1,447 @@
+# 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 policy: every denoiser class Studio loads is classified once (batched by the router, batched by its
+own pipeline, or not batchable), an offloaded load batches with no timing trial whenever memory allows, and the
+newly batched classes match two plain calls in their pipeline's call shape. CPU only."""
+
+from __future__ import annotations
+
+import types
+
+import pytest
+import torch
+
+from core.inference import diffusion_cfg_batch as cb
+from core.inference import diffusion_families as df
+from core.inference import video_families as vf
+
+
+def _family_classes() -> set[str]:
+ out: set[str] = set()
+ for fam in (*df._FAMILIES, *vf._FAMILIES):
+ for attr in ("transformer_class", "transformer2_class"):
+ name = getattr(fam, attr, None)
+ if name:
+ out.add(str(name))
+ return out
+
+
+def test_every_family_denoiser_has_exactly_one_cfg_policy():
+ tables = (set(cb.STATELESS_CLASSES), set(cb.PIPELINE_BATCHED), set(cb.NOT_BATCHABLE))
+ for i, a in enumerate(tables):
+ for b in tables[i + 1 :]:
+ assert not (a & b), sorted(a & b)
+ classified = set().union(*tables)
+ missing = sorted(_family_classes() - classified)
+ assert not missing, f"no CFG batching policy for {missing}"
+
+
+def test_the_compiled_resident_and_measured_tables_only_name_batched_classes():
+ assert cb.COMPILED_RESIDENT_CLASSES <= cb.STATELESS_CLASSES
+ for cls, card, kind in cb.MEASURED_SLOWER:
+ assert cls in cb.STATELESS_CLASSES and kind in ("eager", "compiled") and card
+
+
+def test_the_default_mode_and_its_switches(monkeypatch):
+ monkeypatch.delenv(cb.CFG_BATCH_ENV, raising = False)
+ assert cb.cfg_batch_mode() == "auto"
+ for raw, mode in (("timed", "timed"), ("force", "force"), ("0", "off"), ("1", "auto")):
+ monkeypatch.setenv(cb.CFG_BATCH_ENV, raw)
+ assert cb.cfg_batch_mode() == mode
+
+
+def _offloaded(module):
+ sub = torch.nn.Linear(1, 1)
+ module.add_module("offloaded_group", sub)
+ sub._diffusers_hook = types.SimpleNamespace(hooks = {"group_offloading": object()})
+ return module
+
+
+class _Pipe:
+ def __init__(self, transformer):
+ self.transformer = transformer
+
+
+class _Calls(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.w = torch.nn.Parameter(torch.linspace(0.5, 1.5, 8))
+ self.calls = []
+
+
+class Krea2Transformer2DModel(_Calls):
+ """A masked-text call (Krea2 / Lumina2 shape): 4-D latents, per-sample text with ``encoder_attention_mask``."""
+
+ def forward(
+ self,
+ hidden_states,
+ timestep,
+ encoder_hidden_states,
+ encoder_attention_mask,
+ attention_kwargs = None,
+ return_dict = True,
+ ):
+ self.calls.append(int(hidden_states.shape[0]))
+ m = encoder_attention_mask.float().unsqueeze(-1)
+ text = (encoder_hidden_states * m).sum(1) / m.sum(1)
+ out = (
+ hidden_states * self.w[:4].view(1, 4, 1, 1)
+ + text.mean(-1).view(-1, 1, 1, 1)
+ + timestep.view(-1, 1, 1, 1)
+ )
+ return (out,)
+
+
+class Flux3Transformer2DModel(_Calls):
+ """FLUX.3 modular call: ``img_ids`` / ``txt_ids`` without a batch dim, no text mask (padding is attended)."""
+
+ def forward(
+ self,
+ hidden_states,
+ encoder_hidden_states,
+ timestep,
+ img_ids,
+ txt_ids,
+ image_cond_hidden_states = None,
+ image_cond_ids = None,
+ target_timestep = None,
+ attention_kwargs = None,
+ return_dict = True,
+ ):
+ self.calls.append(int(hidden_states.shape[0]))
+ assert img_ids.dim() == 2 and txt_ids.shape[0] == encoder_hidden_states.shape[1]
+ text = encoder_hidden_states.mean(1, keepdim = True)
+ return (hidden_states * self.w + text + timestep.view(-1, 1, 1) + txt_ids.float().mean(),)
+
+
+class HunyuanImageTransformer2DModel(_Calls):
+ """HunyuanImagePipeline guider call: two text encoders, each with a mask."""
+
+ def forward(
+ self,
+ hidden_states,
+ timestep,
+ encoder_hidden_states,
+ encoder_attention_mask,
+ timestep_r = None,
+ encoder_hidden_states_2 = None,
+ encoder_attention_mask_2 = None,
+ guidance = None,
+ attention_kwargs = None,
+ return_dict = True,
+ ):
+ self.calls.append(int(hidden_states.shape[0]))
+ m = encoder_attention_mask.float().unsqueeze(-1)
+ m2 = encoder_attention_mask_2.float().unsqueeze(-1)
+ t1 = (encoder_hidden_states * m).sum(1) / m.sum(1)
+ t2 = (encoder_hidden_states_2 * m2).sum(1) / m2.sum(1)
+ return (
+ hidden_states * 0.9
+ + (t1.mean(-1) + t2.mean(-1)).view(-1, 1, 1, 1)
+ + timestep.view(-1, 1, 1, 1),
+ )
+
+
+for _cls in (Krea2Transformer2DModel, Flux3Transformer2DModel, HunyuanImageTransformer2DModel):
+ _cls.__module__ = "diffusers.models.fake"
+
+
+def _loop(
+ model,
+ kind,
+ steps = 6,
+ neg_len = None,
+):
+ g = torch.Generator().manual_seed(0)
+ preds = []
+ if kind == "lumina2":
+ lat = torch.randn(1, 4, 2, 2, generator = g)
+ pos, neg = torch.randn(1, 6, 8, generator = g), torch.randn(1, 6, 8, generator = g)
+ pm = torch.tensor([[1, 1, 1, 1, 1, 0]])
+ nm = torch.tensor([[1, 0, 0, 0, 0, 0]])
+ kw = lambda c: dict(
+ encoder_hidden_states = pos if c else neg, encoder_attention_mask = pm if c else nm
+ ) # noqa: E731
+ elif kind == "flux3":
+ lat = torch.randn(1, 4, 8, generator = g)
+ T, Tn = 8, neg_len or 8
+ pos, neg = torch.randn(1, T, 8, generator = g), torch.randn(1, Tn, 8, generator = g)
+ img_ids = torch.zeros(4, 4)
+ ids = {T: torch.arange(T * 4.0).view(T, 4), Tn: torch.arange(Tn * 4.0).view(Tn, 4)}
+ kw = lambda c: dict(
+ encoder_hidden_states = pos if c else neg, img_ids = img_ids, txt_ids = ids[T if c else Tn]
+ ) # noqa: E731
+ else:
+ lat = torch.randn(1, 4, 2, 2, generator = g)
+ pos, neg = torch.randn(1, 6, 8, generator = g), torch.randn(1, 6, 8, generator = g)
+ pos2, neg2 = torch.randn(1, 3, 4, generator = g), torch.randn(1, 3, 4, generator = g)
+ pm, nm = torch.tensor([[1, 1, 1, 1, 0, 0]]), torch.tensor([[1, 1, 0, 0, 0, 0]])
+ pm2, nm2 = torch.tensor([[1, 1, 1]]), torch.tensor([[1, 0, 0]])
+ kw = lambda c: dict( # noqa: E731
+ encoder_hidden_states = pos if c else neg,
+ encoder_attention_mask = pm if c else nm,
+ encoder_hidden_states_2 = pos2 if c else neg2,
+ encoder_attention_mask_2 = pm2 if c else nm2,
+ )
+ for i in range(steps):
+ t = (torch.tensor(1000.0 - 100 * i) / 1000).expand(lat.shape[0])
+ c = model(hidden_states = lat, timestep = t, return_dict = False, **kw(True))[0]
+ u = model(hidden_states = lat, timestep = t, return_dict = False, **kw(False))[0]
+ pred = u + 3.5 * (c - u)
+ preds.append(pred)
+ lat = lat - 0.1 * pred
+ return lat, preds
+
+
+ "cls, kind",
+ [
+ (Krea2Transformer2DModel, "lumina2"),
+ (Flux3Transformer2DModel, "flux3"),
+ (HunyuanImageTransformer2DModel, "hunyuanimage"),
+ ],
+)
+def test_a_newly_batched_class_matches_two_calls_from_step_two(monkeypatch, cls, kind):
+ monkeypatch.delenv(cb.CFG_BATCH_ENV, raising = False)
+ ref, _ = _loop(cls(), kind)
+ model = _offloaded(cls())
+ pipe = _Pipe(model)
+ assert cb.install_cfg_batch(pipe, offload_policy = "group") is None
+ got, _ = _loop(model, kind)
+ torch.testing.assert_close(got, ref)
+ router = cb.router_for(pipe)
+ assert model.calls == [1, 1] + [2] * 5, router.describe()
+ assert router.stats["hits"] == 5 and router.stats["misses"] == 0
+ assert router.describe()["plain_pair_s"] is None # no timing trial ran
+
+
+def test_flux3_branches_in_different_text_windows_stay_two_calls(monkeypatch):
+ """No transformer mask: padding the shorter window would change its attention, so that shape stays plain."""
+ monkeypatch.delenv(cb.CFG_BATCH_ENV, raising = False)
+ ref, _ = _loop(Flux3Transformer2DModel(), "flux3", neg_len = 4)
+ model = _offloaded(Flux3Transformer2DModel())
+ pipe = _Pipe(model)
+ assert cb.install_cfg_batch(pipe, offload_policy = "group") is None
+ got, _ = _loop(model, "flux3", neg_len = 4)
+ torch.testing.assert_close(got, ref, rtol = 0, atol = 0)
+ assert set(model.calls) == {1}
+ assert "takes no mask" in cb.router_for(pipe).describe()["shape_off"]
+
+
+def test_lumina2_unequal_text_lengths_pad_with_its_attention_mask():
+ a = (
+ (),
+ {
+ "hidden_states": torch.zeros(1, 2),
+ "encoder_hidden_states": torch.ones(1, 3, 2),
+ "encoder_attention_mask": torch.ones(1, 3, dtype = torch.long),
+ },
+ )
+ b = (
+ (),
+ {
+ "hidden_states": torch.zeros(1, 2),
+ "encoder_hidden_states": torch.ones(1, 5, 2),
+ "encoder_attention_mask": torch.ones(1, 5, dtype = torch.long),
+ },
+ )
+ _args, kw = cb.merge_branches(a, b, 1)
+ assert kw["encoder_hidden_states"].shape == (2, 5, 2)
+ assert kw["encoder_attention_mask"].tolist() == [[1, 1, 1, 0, 0], [1, 1, 1, 1, 1]]
+ assert "encoder_hidden_states_mask" not in kw
+
+
+ "name",
+ [
+ "QwenImage21Transformer2DModel",
+ "Ideogram4Transformer2DModel",
+ "Lumina2Transformer2DModel",
+ "ZImageTransformer2DModel",
+ "HiDreamImageTransformer2DModel",
+ ],
+)
+def test_classified_but_not_router_batched_classes_decline_with_their_reason(monkeypatch, name):
+ monkeypatch.delenv(cb.CFG_BATCH_ENV, raising = False)
+ cls = type(name, (Krea2Transformer2DModel,), {})
+ cls.__module__ = "diffusers.models.fake"
+ reason = cb.cfg_batch_decline(_Pipe(_offloaded(cls())), offload_policy = "group")
+ assert reason == {**cb.PIPELINE_BATCHED, **cb.NOT_BATCHABLE}[name]
+
+
+def test_a_measured_slower_card_keeps_two_calls_unless_forced(monkeypatch):
+ monkeypatch.delenv(cb.CFG_BATCH_ENV, raising = False)
+ monkeypatch.setitem(
+ cb.MEASURED_SLOWER, ("Krea2Transformer2DModel", "Tesla T4", "eager"), "1.04x slower"
+ )
+ monkeypatch.setattr(cb, "_cuda_latent", lambda latent: True)
+ monkeypatch.setattr(cb, "_card_name", lambda latent: "Tesla T4")
+ monkeypatch.setattr(cb.CfgBatchRouter, "_memory_ok", lambda self, latent, shape: True)
+ model = _offloaded(Krea2Transformer2DModel())
+ pipe = _Pipe(model)
+ assert cb.install_cfg_batch(pipe, offload_policy = "group") is None
+ _loop(model, "lumina2")
+ assert set(model.calls) == {1}
+ assert (
+ "measured slower batched on this card (1.04x slower)"
+ in cb.router_for(pipe).describe()["shape_off"]
+ )
+ monkeypatch.setattr(cb, "_card_name", lambda latent: "NVIDIA L4")
+ other = _offloaded(Krea2Transformer2DModel())
+ opipe = _Pipe(other)
+ assert cb.install_cfg_batch(opipe, offload_policy = "group") is None
+ _loop(other, "lumina2")
+ assert other.calls[-1] == 2
+ monkeypatch.setattr(cb, "_card_name", lambda latent: "Tesla T4")
+ monkeypatch.setenv(cb.CFG_BATCH_ENV, "force")
+ forced = _offloaded(Krea2Transformer2DModel())
+ fpipe = _Pipe(forced)
+ assert cb.install_cfg_batch(fpipe, offload_policy = "group") is None
+ _loop(forced, "lumina2")
+ assert forced.calls[-1] == 2
+
+
+def test_the_memory_gate_still_keeps_a_render_plain_without_a_trial(monkeypatch):
+ monkeypatch.delenv(cb.CFG_BATCH_ENV, raising = False)
+ monkeypatch.setattr(cb.CfgBatchRouter, "_memory_ok", lambda self, latent, shape: False)
+ ref, _ = _loop(Krea2Transformer2DModel(), "lumina2")
+ model = _offloaded(Krea2Transformer2DModel())
+ pipe = _Pipe(model)
+ assert cb.install_cfg_batch(pipe, offload_policy = "group") is None
+ got, _ = _loop(model, "lumina2")
+ torch.testing.assert_close(got, ref, rtol = 0, atol = 0)
+ assert set(model.calls) == {1} and "no room" in cb.router_for(pipe).describe()["shape_off"]
+
+
+# Real diffusers classes (tiny random configs): batched vs two calls in fp32 on CPU, forced (CPU resident is plain).
+_REAL = {
+ "Lumina2Transformer2DModel": dict(
+ sample_size = 8,
+ patch_size = 2,
+ in_channels = 4,
+ hidden_size = 32,
+ num_layers = 1,
+ num_refiner_layers = 1,
+ num_attention_heads = 2,
+ num_kv_heads = 1,
+ multiple_of = 16,
+ axes_dim_rope = (4, 6, 6),
+ axes_lens = (300, 64, 64),
+ cap_feat_dim = 16,
+ ),
+ "HunyuanImageTransformer2DModel": dict(
+ in_channels = 4,
+ out_channels = 4,
+ num_attention_heads = 2,
+ attention_head_dim = 16,
+ num_layers = 1,
+ num_single_layers = 1,
+ num_refiner_layers = 1,
+ text_embed_dim = 16,
+ text_embed_2_dim = 8,
+ rope_axes_dim = (8, 8),
+ ),
+}
+
+
[email protected]("name", sorted(_REAL))
+def test_real_diffusers_class_batched_matches_two_calls(monkeypatch, name):
+ diffusers = pytest.importorskip("diffusers")
+ cls = getattr(diffusers, name, None)
+ if cls is None:
+ pytest.skip(f"diffusers {diffusers.__version__} has no {name}")
+ monkeypatch.setenv(cb.CFG_BATCH_ENV, "force")
+ torch.manual_seed(0)
+ model = cls(**_REAL[name]).eval()
+ g = torch.Generator().manual_seed(1)
+ r = lambda *s: torch.randn(*s, generator = g) # noqa: E731
+ pm = torch.zeros(1, 12, dtype = torch.long)
+ pm[:, :9] = 1
+ nm = torch.zeros(1, 12, dtype = torch.long)
+ nm[:, :3] = 1
+ pos, neg = r(1, 12, 16), r(1, 12, 16)
+ extra = {}
+ if name == "HunyuanImageTransformer2DModel":
+ pos2, neg2 = r(1, 6, 8), r(1, 6, 8)
+ m2p, m2n = torch.ones(1, 6, dtype = torch.long), torch.tensor([[1, 0, 0, 0, 0, 0]])
+ extra = {
+ True: dict(encoder_hidden_states_2 = pos2, encoder_attention_mask_2 = m2p),
+ False: dict(encoder_hidden_states_2 = neg2, encoder_attention_mask_2 = m2n),
+ }
+ lat0 = r(1, 4, 8, 8)
+
+ def loop(m):
+ lat, outs = lat0.clone(), []
+ for i in range(4):
+ t = torch.full((1,), 1.0 - i / 4)
+ x = lat.clone()
+ c = m(
+ hidden_states = x,
+ timestep = t,
+ encoder_hidden_states = pos,
+ encoder_attention_mask = pm,
+ return_dict = False,
+ **extra.get(True, {}),
+ )[0]
+ u = m(
+ hidden_states = x,
+ timestep = t,
+ encoder_hidden_states = neg,
+ encoder_attention_mask = nm,
+ return_dict = False,
+ **extra.get(False, {}),
+ )[0]
+ outs += [c, u]
+ lat = lat - 0.1 * (u + 3.0 * (c - u))
+ return outs
+
+ with torch.no_grad():
+ ref = loop(model)
+ pipe = _Pipe(model)
+ assert cb.install_cfg_batch(pipe, offload_policy = "none") is None
+ got = loop(model)
+ status = cb.cfg_batch_status(pipe)
+ cb.uninstall_cfg_batch(pipe)
+ assert status["batched_steps"] == 3 and status["misses"] == 0, status
+ for a, b in zip(got, ref):
+ torch.testing.assert_close(a, b, rtol = 1e-5, atol = 1e-5)
+
+
+def test_a_streamed_offload_hook_removal_does_not_end_batching(monkeypatch):
+ """diffusers' use_stream group offload removes its lazy-prefetch hook after the first forward and writes the bound
+ class forward over ``module.forward``: the router takes its slot back and the render still batches."""
+ monkeypatch.delenv(cb.CFG_BATCH_ENV, raising = False)
+ model = _offloaded(HunyuanImageTransformer2DModel())
+ pipe = _Pipe(model)
+ assert cb.install_cfg_batch(pipe, offload_policy = "group") is None
+ router = cb.router_for(pipe)
+ real = router.orig_forward
+ state = {"n": 0}
+
+ def lazy_hook(*a, **k): # the root hook: runs once, then restores the class forward
+ state["n"] += 1
+ out = real(*a, **k)
+ if state["n"] == 1:
+ model.__dict__["forward"] = types.MethodType(type(model).forward, model)
+ return out
+
+ router.orig_forward = lazy_hook
+ ref, _ = _loop(HunyuanImageTransformer2DModel(), "hunyuanimage")
+ got, _ = _loop(model, "hunyuanimage")
+ torch.testing.assert_close(got, ref)
+ assert model.__dict__["forward"] is router and router.stats["retaken"] == 1
+ assert model.calls == [1, 1] + [2] * 5
+
+
+def test_a_slot_taken_by_another_layer_is_not_retaken(monkeypatch):
+ monkeypatch.delenv(cb.CFG_BATCH_ENV, raising = False)
+ model = _offloaded(HunyuanImageTransformer2DModel())
+ pipe = _Pipe(model)
+ assert cb.install_cfg_batch(pipe, offload_policy = "group") is None
+ router = cb.router_for(pipe)
+ graphed = lambda *a, **k: router.orig_forward(*a, **k) # noqa: E731 - a CUDA graph layer took the slot
+ model.__dict__["forward"] = graphed
+ _loop(model, "hunyuanimage")
+ cb.end_cfg_batch_render(pipe)
+ assert model.__dict__["forward"] is graphed and "retaken" not in router.stats