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: FLUX.3 modulation heads project once per sample; offloaded Base edits reuse the conditioning streams (#17059)

Daniel Han3194a8356be6
diff --git a/studio/backend/core/inference/diffusion_cfg_batch.py b/studio/backend/core/inference/diffusion_cfg_batch.py
index 59323f5bb9c..f92607536fb 100644
--- a/studio/backend/core/inference/diffusion_cfg_batch.py
+++ b/studio/backend/core/inference/diffusion_cfg_batch.py
@@ -1020,6 +1020,10 @@ class CfgBatchRouter:
def _record_template(self, args: tuple, kwargs: dict, latent: Any) -> None:
"""How the second call's arguments relate to the first's: the latent, a first-branch tensor (same object, or a
small per-call scalar recomputed with equal bytes), or a constant of the second branch."""
+ if getattr(kwargs.get("unsloth_cond"), "pending", False):
+ # FLUX.3 conditioning still computing (diffusion_cond_blocks): later steps pass its states instead
+ self.template = None
+ return
mg = _mg()
torch = _torch()
b0_leaves = dict(mg._leaves(self.b0)) if self.b0 is not None else {}
diff --git a/studio/backend/core/inference/diffusion_cond_blocks.py b/studio/backend/core/inference/diffusion_cond_blocks.py
index 437088645cb..00a5a8538b4 100644
--- a/studio/backend/core/inference/diffusion_cond_blocks.py
+++ b/studio/backend/core/inference/diffusion_cond_blocks.py
@@ -3,7 +3,9 @@
"""FLUX.3 Klein Base conditioning blocks run once per render, bit-identical; cache cleared at start
and end of each pipeline call; installed only on matching diffusers forward hash, else stock;
-UNSLOTH_DIFFUSION_COND_BLOCKS=0 disables"""
+UNSLOTH_DIFFUSION_COND_BLOCKS=0 disables. Offloaded (CUDA): computed inside the hooked forward,
+UNSLOTH_DIFFUSION_OFFLOAD_COND_CACHE=0 keeps stock. Modulation heads project one row per sample,
+not per token (any FLUX.3), UNSLOTH_DIFFUSION_FLUX3_COMPACT_MOD=0 restores per-token rows"""
from __future__ import annotations
@@ -13,8 +15,14 @@ import os
import weakref
from typing import Any, Optional
+from .rocm_bf16 import is_rocm_torch
+
COND_BLOCKS_ENV = "UNSLOTH_DIFFUSION_COND_BLOCKS"
+OFFLOAD_COND_ENV = "UNSLOTH_DIFFUSION_OFFLOAD_COND_CACHE"
+COMPACT_MOD_ENV = "UNSLOTH_DIFFUSION_FLUX3_COMPACT_MOD"
COND_KWARG = "unsloth_cond"
+_COMPACT_ATTR = "_unsloth_compact_mod"
+_OFFLOADED_ATTR = "_unsloth_cond_offloaded"
# sha256[:16] of inspect.getsource(Flux3Transformer2DModel.forward) the replacement mirrors (d42ebf9c and 0.42.1).
_FLUX3_FORWARD_SHA = frozenset({"f2f7c836416cfd58"})
@@ -22,9 +30,20 @@ _FLUX3_FORWARD_SHA = frozenset({"f2f7c836416cfd58"})
_PATCHED: dict[type, Any] = {}
+def _switch(name: str) -> bool:
+ return (os.environ.get(name) or "").strip().lower() not in ("0", "off", "false", "no")
+
+
def enabled() -> bool:
- raw = (os.environ.get(COND_BLOCKS_ENV) or "").strip().lower()
- return raw not in ("0", "off", "false", "no")
+ return _switch(COND_BLOCKS_ENV)
+
+
+def offload_cache_enabled() -> bool:
+ return _switch(OFFLOAD_COND_ENV)
+
+
+def compact_enabled() -> bool:
+ return _switch(COMPACT_MOD_ENV)
def _forward_sha(cls: type) -> Optional[str]:
@@ -57,7 +76,7 @@ class _Entry:
def _offloaded(module: Any) -> Optional[str]:
- """Offloaded weights keep the stock path: running conditioning blocks outside the forward reorders prefetch."""
+ """Why ``module`` is offloaded (None: resident); its conditioning then runs only inside the hooked forward."""
for name, sub in module.named_modules():
if getattr(sub, "_hf_hook", None) is not None:
return f"{name or '<root>'} carries an accelerate hook"
@@ -68,6 +87,26 @@ def _offloaded(module: Any) -> Optional[str]:
return None
+def _fixed_prefetch_chain(module: Any) -> Optional[str]:
+ """diffusers' fixed next-group prefetch chain would leave a skipped block on the device."""
+ for name, sub in module.named_modules():
+ hooks = getattr(getattr(sub, "_diffusers_hook", None), "hooks", None) or {}
+ for key, hook in hooks.items():
+ if "lazy_prefetch" in str(key).lower() or getattr(hook, "next_group", None) is not None:
+ return f"{name or '<root>'} streams with diffusers' prefetch chain"
+ return None
+
+
+def _offload_device_ok(t: Any) -> bool:
+ """Offload cache: CUDA only for now (ROCm, XPU, MPS, CPU keep stock)."""
+ import torch
+ return bool(t.is_cuda) and not is_rocm_torch(torch)
+
+
+def _rows(t: Any, batch_size: int, n: int) -> Any:
+ return t if t.shape[1] == n else t.expand(batch_size, n, -1)
+
+
def flux3_conditioning(
module: Any,
*,
@@ -78,17 +117,25 @@ def flux3_conditioning(
batch_size: int,
dtype: Any,
device: Any,
+ compact: bool = False,
+ target_temb: Any = None,
) -> dict:
- """The conditioning-only part of ``Flux3Transformer2DModel.forward`` for a non-flow-map transformer, op for op:
- the timestep-0 embedding, the text and reference modulations, projections and RoPE, and their per-mode blocks."""
+ """The conditioning part of ``Flux3Transformer2DModel.forward``, op for op. ``compact``: one modulation row per
+ sample (every token of a mode shares its timestep), broadcast by the blocks."""
import torch
import torch.nn.functional as F
zero_temb = module.time_proj(torch.zeros(batch_size, device = device, dtype = dtype))
zero_temb = module.timestep_embedder(zero_temb.to(dtype))[:, None, :]
+ if target_temb is not None:
+ zero_temb = zero_temb + target_temb
zero_temb_act = F.silu(zero_temb)
- txt_temb_act = zero_temb_act.expand(batch_size, encoder_hidden_states.shape[1], -1)
+ txt_temb_act = (
+ zero_temb_act
+ if compact
+ else zero_temb_act.expand(batch_size, encoder_hidden_states.shape[1], -1)
+ )
txt_early_mod = module.early_stream_modulations["txt"](txt_temb_act)
txt_single_mod = module.single_stream_modulations["txt"](txt_temb_act)
txt_states = module.context_embedder(encoder_hidden_states)
@@ -96,7 +143,11 @@ def flux3_conditioning(
out: dict = {}
if image_cond_hidden_states is not None:
- cond_temb_act = zero_temb_act.expand(batch_size, image_cond_hidden_states.shape[1], -1)
+ cond_temb_act = (
+ zero_temb_act
+ if compact
+ else zero_temb_act.expand(batch_size, image_cond_hidden_states.shape[1], -1)
+ )
cond_early_mod = module.early_stream_modulations["image_cond"](cond_temb_act)
cond_single_mod = module.single_stream_modulations["image_cond"](cond_temb_act)
cond_states = module.x_embedders["image_cond"](image_cond_hidden_states)
@@ -119,6 +170,57 @@ def flux3_conditioning(
return out
+def _compact_call(module: Any, attention_kwargs: Any) -> bool:
+ """Inference without a per-call LoRA scale (stock ``apply_lora_scale`` handles it)."""
+ import torch
+
+ if not module.__dict__.get(_COMPACT_ATTR) or torch.is_grad_enabled():
+ return False
+ return not (attention_kwargs and "scale" in attention_kwargs)
+
+
+class Pending:
+ """An offloaded miss passed as ``unsloth_cond``: a non-tensor, so a CUDA graph runs this call eager and a CFG
+ router records no template from it (``pending``)."""
+
+ __slots__ = ("key", "sources")
+ pending = True
+
+ def __init__(self, key: tuple, sources: tuple) -> None:
+ self.key = key
+ self.sources = sources
+
+
+def _claim_pending(
+ module: Any, hidden_states: Any, pending: Pending, sources: tuple
+) -> Optional[dict]:
+ """Offloaded miss: compute and cache inside the hooked forward, only for the exact call it was recorded for."""
+ import torch
+
+ key, recorded = pending.key, pending.sources
+ if key[1] != int(hidden_states.shape[0]) or any(a is not b for a, b in zip(sources, recorded)):
+ return None
+ if hidden_states.is_cuda and torch.cuda.is_current_stream_capturing():
+ return None
+ ehs, txt_ids, ich, iid = sources
+ states = flux3_conditioning(
+ module,
+ encoder_hidden_states = ehs,
+ txt_ids = txt_ids,
+ image_cond_hidden_states = ich,
+ image_cond_ids = iid,
+ batch_size = int(hidden_states.shape[0]),
+ dtype = hidden_states.dtype,
+ device = hidden_states.device,
+ compact = bool(module.__dict__.get(_COMPACT_ATTR)),
+ )
+ module.__dict__.setdefault("_unsloth_cond_cache", {})[key] = _Entry(sources, states)
+ stats = _stats(module)
+ stats["misses"] += 1
+ stats["in_forward"] = stats.get("in_forward", 0) + 1
+ return states
+
+
def _flux3_cached_forward(
self: Any,
hidden_states: Any,
@@ -133,10 +235,16 @@ def _flux3_cached_forward(
return_dict: bool = True,
unsloth_cond: Optional[dict] = None,
) -> Any:
- """Stock forward op for op, taking precomputed ``unsloth_cond``; without it, it IS the stock forward."""
- stock = _stock_forward(self)
- if unsloth_cond is None:
- return stock(
+ """Stock forward op for op, with precomputed ``unsloth_cond`` and / or compact modulation; else stock."""
+ if isinstance(unsloth_cond, Pending):
+ unsloth_cond = _claim_pending(
+ self,
+ hidden_states,
+ unsloth_cond,
+ (encoder_hidden_states, txt_ids, image_cond_hidden_states, image_cond_ids),
+ )
+ if unsloth_cond is None and not _compact_call(self, attention_kwargs):
+ return _stock_forward(self)(
self,
hidden_states = hidden_states,
encoder_hidden_states = encoder_hidden_states,
@@ -153,15 +261,49 @@ def _flux3_cached_forward(
import torch.nn.functional as F
from diffusers.models.modeling_outputs import Transformer2DModelOutput
- if target_timestep is not None or bool(self.config.flow_map):
- raise ValueError("cached conditioning states are only valid for a non-flow-map transformer")
-
batch_size, image_seq_len = hidden_states.shape[:2]
dtype = hidden_states.dtype
+ compact = bool(self.__dict__.get(_COMPACT_ATTR))
image_temb = self.time_proj(timestep.to(dtype) * 1000)
image_temb = self.timestep_embedder(image_temb.to(dtype))[:, None, :]
- image_temb = image_temb.expand(batch_size, image_seq_len, -1)
+ if unsloth_cond is not None:
+ if target_timestep is not None or bool(self.config.flow_map):
+ raise ValueError(
+ "cached conditioning states are only valid for a non-flow-map transformer"
+ )
+ else:
+ if image_cond_hidden_states is not None and image_cond_ids is None:
+ raise ValueError("`image_cond_hidden_states` requires `image_cond_ids`.")
+ if image_cond_hidden_states is None and image_cond_ids is not None:
+ raise ValueError("`image_cond_ids` was passed without `image_cond_hidden_states`.")
+ if (target_timestep is not None) != bool(self.config.flow_map):
+ raise ValueError(
+ "`target_timestep` is required by, and only by, a flow-map transformer (`flow_map=True`)."
+ )
+ target_temb = None
+ if target_timestep is not None:
+ target_temb = self.time_proj(target_timestep.to(dtype) * 1000)
+ target_temb = self.target_timestep_embedder(target_temb.to(dtype))[:, None, :]
+ image_temb = image_temb + target_temb
+ unsloth_cond = flux3_conditioning(
+ self,
+ encoder_hidden_states = encoder_hidden_states,
+ txt_ids = txt_ids,
+ image_cond_hidden_states = image_cond_hidden_states,
+ image_cond_ids = image_cond_ids,
+ batch_size = batch_size,
+ dtype = dtype,
+ device = hidden_states.device,
+ compact = True,
+ target_temb = target_temb,
+ )
+ if (
+ not torch.compiler.is_compiling()
+ ): # a module int Dynamo would guard on: one recompile per call
+ _stats(self)["compact"] = _stats(self).get("compact", 0) + 1
+ if not compact:
+ image_temb = image_temb.expand(batch_size, image_seq_len, -1)
encoder_hidden_states = unsloth_cond["txt_states"]
txt_single_mod = unsloth_cond["txt_single_mod"]
@@ -178,9 +320,17 @@ def _flux3_cached_forward(
hidden_states = block(hidden_states, image_early_mod, image_rotary_emb)
if has_cond:
+ cond_states = unsloth_cond["cond_states"]
cond_rotary_emb = (unsloth_cond["cond_cos"], unsloth_cond["cond_sin"])
- content_states = torch.cat([hidden_states, unsloth_cond["cond_states"]], dim = 1)
- content_mod = torch.cat([image_single_mod, unsloth_cond["cond_single_mod"]], dim = 1)
+ content_states = torch.cat([hidden_states, cond_states], dim = 1)
+ # image and reference spans carry different timesteps: per token here
+ content_mod = torch.cat(
+ [
+ _rows(image_single_mod, batch_size, image_seq_len),
+ _rows(unsloth_cond["cond_single_mod"], batch_size, cond_states.shape[1]),
+ ],
+ dim = 1,
+ )
joint_rotary_emb = (
torch.cat([txt_rotary_emb[0], image_rotary_emb[0], cond_rotary_emb[0]], dim = 0),
torch.cat([txt_rotary_emb[1], image_rotary_emb[1], cond_rotary_emb[1]], dim = 0),
@@ -241,11 +391,31 @@ def _stats(module: Any) -> dict:
return stats
+def _conditioning_blocks(module: Any, has_cond: bool) -> list:
+ blocks = list(module.txt_mode_blocks)
+ if has_cond:
+ blocks += list(module.mode_blocks["image_cond"])
+ return blocks
+
+
+def _match_prefetch_order(module: Any, has_cond: bool, *, skipping: bool) -> None:
+ """Keep the streamed prefetch on order when a hit skips (or a miss runs) the conditioning blocks."""
+ from .diffusion_offload_prefetch import match_skipped_order
+ try:
+ match_skipped_order(module, _conditioning_blocks(module, has_cond), skipping = skipping)
+ except Exception: # noqa: BLE001 - speed hint only
+ pass
+
+
def _pre_hook(module: Any, args: tuple, kwargs: dict) -> Any:
import torch
if args or kwargs.get(COND_KWARG) is not None or not module.__dict__.get("_unsloth_cond_live"):
return None
+ if (
+ torch.compiler.is_compiling()
+ ): # a whole-model compile: identity cache and counters stay out of the graph
+ return None
if torch.is_grad_enabled() or kwargs.get("target_timestep") is not None:
return None
stats = _stats(module)
@@ -266,6 +436,13 @@ def _pre_hook(module: Any, args: tuple, kwargs: dict) -> Any:
return None
if hidden_states.is_cuda and torch.cuda.is_current_stream_capturing():
return None
+ offloaded = bool(module.__dict__.get(_OFFLOADED_ATTR))
+ if offloaded and not _offload_device_ok(hidden_states):
+ stats["skipped"] += 1
+ stats["reason"] = (
+ f"offloaded on {hidden_states.device.type} (the offload cache is CUDA only)"
+ )
+ return None
sources = (ehs, txt_ids, ich, iid)
key = (
tuple(_tkey(t) for t in sources),
@@ -276,6 +453,11 @@ def _pre_hook(module: Any, args: tuple, kwargs: dict) -> Any:
cache = module.__dict__.setdefault("_unsloth_cond_cache", {})
entry = cache.get(key)
if entry is None or not entry.matches(sources):
+ if offloaded:
+ _match_prefetch_order(module, ich is not None, skipping = False)
+ new_kwargs = dict(kwargs)
+ new_kwargs[COND_KWARG] = Pending(key, sources)
+ return args, new_kwargs
states = flux3_conditioning(
module,
encoder_hidden_states = ehs,
@@ -285,12 +467,15 @@ def _pre_hook(module: Any, args: tuple, kwargs: dict) -> Any:
batch_size = int(hidden_states.shape[0]),
dtype = hidden_states.dtype,
device = hidden_states.device,
+ compact = bool(module.__dict__.get(_COMPACT_ATTR)),
)
cache[key] = _Entry(sources, states)
stats["misses"] += 1
else:
states = entry.states
stats["hits"] += 1
+ if offloaded:
+ _match_prefetch_order(module, ich is not None, skipping = True)
new_kwargs = dict(kwargs)
new_kwargs[COND_KWARG] = states
return args, new_kwargs
@@ -305,15 +490,34 @@ def _applies(transformer: Any) -> Optional[str]:
def prepare(transformer: Any, logger: Any = None) -> bool:
- """Call at load, before the speed layer binds the class forward. True when the cache can arm."""
- if transformer is None or not enabled():
+ """Call at load, before the speed layer binds the class forward. True when the conditioning cache can arm."""
+ cond_on = enabled()
+ compact = compact_enabled()
+ if transformer is None or not (cond_on or compact):
+ return False
+ applies = _applies(transformer)
+ if applies is not None and (not compact or "not a FLUX.3" in applies):
+ if cond_on:
+ _stats(transformer)["reason"] = applies
+ if logger is not None and "not a FLUX.3" not in applies:
+ logger.info("diffusion.cond_blocks: off (%s)", applies)
return False
- why = _applies(transformer) or patch_class(type(transformer))
+ why = patch_class(type(transformer))
if why is not None:
_stats(transformer)["reason"] = why
- if logger is not None and "not a FLUX.3" not in why:
+ if logger is not None:
logger.info("diffusion.cond_blocks: off (%s)", why)
return False
+ transformer.__dict__[_COMPACT_ATTR] = compact
+ if compact and logger is not None:
+ logger.info("diffusion.cond_blocks: FLUX.3 modulation heads project one row per sample")
+ if not cond_on:
+ return False
+ if applies is not None:
+ _stats(transformer)["reason"] = applies
+ if logger is not None:
+ logger.info("diffusion.cond_blocks: off (%s)", applies)
+ return False
return True
@@ -333,9 +537,10 @@ def begin_render(transformer: Any, logger: Any = None) -> bool:
_stats(transformer)["reason"] = "the class forward was not patched at load"
return False
why = _offloaded(transformer)
- if why is not None:
- _stats(transformer)["reason"] = why
+ if why is not None and (not offload_cache_enabled() or _fixed_prefetch_chain(transformer)):
+ _stats(transformer)["reason"] = _fixed_prefetch_chain(transformer) or why
return False
+ transformer.__dict__[_OFFLOADED_ATTR] = why is not None
handle = transformer.__dict__.get("_unsloth_cond_hook")
hooks = transformer._forward_pre_hooks
if handle is None or handle.id not in hooks:
diff --git a/studio/backend/core/inference/diffusion_flux3.py b/studio/backend/core/inference/diffusion_flux3.py
index f0a16eefd2f..534693d5326 100644
--- a/studio/backend/core/inference/diffusion_flux3.py
+++ b/studio/backend/core/inference/diffusion_flux3.py
@@ -662,9 +662,8 @@ def load_flux3_pipeline(
reason = flux3_family_blocks_mismatch(family_name, blocks, repo_id)
if reason is not None:
raise ValueError(reason)
- if blocks == FLUX3_BASE_BLOCKS:
- # Before the speed layer: a whole-step CUDA graph binds the class forward when it is built.
- cond_blocks.prepare(transformer)
+ # Before the speed layer: a whole-step CUDA graph binds the class forward when it is built.
+ cond_blocks.prepare(transformer)
# The scheduler is the block graph's own (shift 6.93, the reference timestep shift); the repos ship none.
scheduler = flux3_blocks(blocks).init_pipeline().scheduler
return flux3_pipeline_class()(
diff --git a/studio/backend/core/inference/diffusion_offload_prefetch.py b/studio/backend/core/inference/diffusion_offload_prefetch.py
index 2d94e33d5b0..0147eeff396 100644
--- a/studio/backend/core/inference/diffusion_offload_prefetch.py
+++ b/studio/backend/core/inference/diffusion_offload_prefetch.py
@@ -1121,6 +1121,31 @@ def module_prefetcher(module: Any) -> Optional[GroupPrefetcher]:
return getattr(module, PREFETCHER_ATTR, None)
+def match_skipped_order(module: Any, skipped: list, *, skipping: bool) -> None:
+ """Call after ``begin``: drop (``skipping``) or restore the groups wholly inside ``skipped`` in the order."""
+ pf = module_prefetcher(module)
+ if pf is None or not pf.active or pf.seen or pf.pos or not pf.order:
+ return
+ inside = {id(m) for block in skipped for m in block.modules()}
+ ids = {
+ gid
+ for gid, group in pf.by_id.items()
+ if getattr(group, "modules", None) and all(id(m) in inside for m in group.modules)
+ }
+ if not ids:
+ return
+ kept = [gid for gid in pf.order if gid not in ids]
+ if skipping:
+ if len(kept) != len(pf.order):
+ pf.__dict__["_unsloth_full_order"] = list(pf.order)
+ pf.order = kept
+ else:
+ full = pf.__dict__.get("_unsloth_full_order")
+ if full and len(kept) == len(pf.order) and [g for g in full if g not in ids] == kept:
+ pf.order = list(full)
+ pf.on_order = bool(pf.order)
+
+
def _pinned_done(pinner: Any, group: Any) -> bool:
event = getattr(pinner, "_done", {}).get(id(group))
return event is None or event.is_set()
diff --git a/studio/backend/tests/test_diffusion_cond_blocks.py b/studio/backend/tests/test_diffusion_cond_blocks.py
index 4e6bc14504f..1e7b45093e2 100644
--- a/studio/backend/tests/test_diffusion_cond_blocks.py
+++ b/studio/backend/tests/test_diffusion_cond_blocks.py
@@ -78,6 +78,7 @@ def _steps(
def test_cached_steps_match_stock_bitwise(refs, monkeypatch):
cls = _flux3()
monkeypatch.delenv(cb.COND_BLOCKS_ENV, raising = False)
+ monkeypatch.setenv(cb.COMPACT_MOD_ENV, "0")
model = _tiny(cls)
# text-only renders keep the stock forward by default; the flag exercises the cached text path anyway
model.__dict__["_unsloth_cond_text_only"] = not refs
@@ -99,6 +100,41 @@ def test_cached_steps_match_stock_bitwise(refs, monkeypatch):
assert not model.__dict__["_unsloth_cond_cache"]
[email protected]("refs", [False, True])
[email protected]("armed", [False, True])
[email protected]("fullgraph", [False, True])
+def test_whole_transformer_compile_traces_once(refs, armed, fullgraph, monkeypatch):
+ """Studio compiles blocks, but a caller may compile the whole denoiser: no counter may become a guard."""
+ from torch._dynamo.testing import CompileCounter
+
+ cls = _flux3()
+ monkeypatch.delenv(cb.COND_BLOCKS_ENV, raising = False)
+ monkeypatch.delenv(cb.COMPACT_MOD_ENV, raising = False)
+ model = _tiny(cls)
+ model.__dict__["_unsloth_cond_text_only"] = armed
+ kw = _inputs(refs)
+ with torch.no_grad():
+ want = _tiny(cls)(**kw)[0]
+ assert cb.prepare(model)
+ if armed:
+ assert cb.begin_render(model)
+ model(
+ **kw
+ ) # an eager render first, as before Studio's deferred compile: the counters are already set
+ torch._dynamo.reset()
+ cc = CompileCounter()
+ fn = torch.compile(model, backend = cc, fullgraph = fullgraph)
+ try:
+ outs = [fn(**kw)[0] for _ in range(12)]
+ finally:
+ if armed:
+ cb.end_render(model)
+ torch._dynamo.reset()
+ assert cc.frame_count == 1
+ for out in outs:
+ torch.testing.assert_close(out, want)
+
+
def test_new_conditioning_tensor_recomputes(monkeypatch):
cls = _flux3()
monkeypatch.delenv(cb.COND_BLOCKS_ENV, raising = False)
@@ -138,6 +174,7 @@ def test_in_place_edit_of_cached_source_is_not_a_hit(monkeypatch):
def test_text_only_render_keeps_stock(monkeypatch):
cls = _flux3()
monkeypatch.delenv(cb.COND_BLOCKS_ENV, raising = False)
+ monkeypatch.setenv(cb.COMPACT_MOD_ENV, "0")
model = _tiny(cls)
kw = _inputs(False)
with torch.no_grad():
@@ -179,9 +216,10 @@ def test_flow_map_is_never_armed(monkeypatch):
assert "flow map" in cb.status(model)["reason"]
-def test_offloaded_denoiser_declines(monkeypatch):
+def test_offloaded_denoiser_declines_with_the_kill_switch(monkeypatch):
cls = _flux3()
monkeypatch.delenv(cb.COND_BLOCKS_ENV, raising = False)
+ monkeypatch.setenv(cb.OFFLOAD_COND_ENV, "0")
model = _tiny(cls)
cb.prepare(model)
model.single_transformer_blocks[0]._hf_hook = object()
@@ -192,6 +230,217 @@ def test_offloaded_denoiser_declines(monkeypatch):
del model.single_transformer_blocks[0]._hf_hook
+def _group_offloaded(cls):
+ from diffusers.hooks import apply_group_offloading
+
+ model = _tiny(cls)
+ cpu = torch.device("cpu")
+ apply_group_offloading(
+ model,
+ onload_device = cpu,
+ offload_device = cpu,
+ offload_type = "block_level",
+ num_blocks_per_group = 1,
+ )
+ return model
+
+
+def _count_calls(blocks):
+ calls = [0]
+ for block in blocks:
+ block.register_forward_pre_hook(lambda *_: calls.__setitem__(0, calls[0] + 1))
+ return calls
+
+
+def test_offloaded_conditioning_runs_once_inside_the_forward(monkeypatch):
+ """Group offloaded: computed once per branch inside the forward, bitwise equal to the uncached forward."""
+ cls = _flux3()
+ monkeypatch.delenv(cb.COND_BLOCKS_ENV, raising = False)
+ monkeypatch.delenv(cb.OFFLOAD_COND_ENV, raising = False)
+ monkeypatch.setattr(
+ cb, "_offload_device_ok", lambda t: True
+ ) # the CUDA gate, opened for this CPU proxy
+ model = _group_offloaded(cls)
+ cond_calls = _count_calls(list(model.txt_mode_blocks) + list(model.mode_blocks["image_cond"]))
+ image_calls = _count_calls(model.mode_blocks["image"])
+ cond = _inputs(True, seed = 1)
+ uncond = dict(cond, encoder_hidden_states = torch.randn(1, 7, 24), txt_ids = torch.zeros(7, 4))
+ with torch.no_grad():
+ assert cb.prepare(model)
+ want = _steps(model, [cond, uncond])
+ assert cond_calls[0] == 3 * 2 * 2
+ cond_calls[0] = 0
+ assert cb.begin_render(model)
+ try:
+ got = _steps(model, [cond, uncond])
+ finally:
+ cb.end_render(model)
+ assert all(torch.equal(a, b) for a, b in zip(want, got))
+ # 2 blocks x 2 branches once per render; image blocks every step
+ assert cond_calls[0] == 2 * 2 and image_calls[0] == 2 * 3 * 2
+ stats = cb.status(model)
+ assert (stats["misses"], stats["hits"], stats["in_forward"]) == (2, 4, 2)
+ assert not model.__dict__["_unsloth_cond_cache"]
+
+
+def test_offloaded_cache_is_cuda_only(monkeypatch):
+ cls = _flux3()
+ monkeypatch.delenv(cb.COND_BLOCKS_ENV, raising = False)
+ monkeypatch.delenv(cb.OFFLOAD_COND_ENV, raising = False)
+ model = _group_offloaded(cls)
+ kw = _inputs(True)
+ with torch.no_grad():
+ cb.prepare(model)
+ want = model(**kw)[0]
+ assert cb.begin_render(model)
+ got = model(**kw)[0]
+ cb.end_render(model)
+ assert torch.equal(got, want)
+ stats = cb.status(model)
+ assert stats["hits"] == stats["misses"] == 0 and "CUDA only" in stats["reason"]
+
+
+def test_offloaded_cache_declines_a_fixed_diffusers_prefetch_chain(monkeypatch):
+ cls = _flux3()
+ monkeypatch.delenv(cb.COND_BLOCKS_ENV, raising = False)
+ model = _group_offloaded(cls)
+ cb.prepare(model)
+ assert cb.begin_render(model)
+ cb.end_render(model)
+ hooks = model.single_transformer_blocks[0]._diffusers_hook.hooks
+ hook = next(iter(hooks.values()))
+ hook.next_group = object()
+ try:
+ assert not cb.begin_render(model)
+ assert "prefetch chain" in cb.status(model)["reason"]
+ finally:
+ hook.next_group = None
+
+
+def test_offloaded_miss_is_claimed_only_by_its_own_call(monkeypatch):
+ """The miss travels as ``Pending``: a call with other sources (a merged CFG batch) computes stock, caches nothing."""
+ cls = _flux3()
+ monkeypatch.delenv(cb.COND_BLOCKS_ENV, raising = False)
+ monkeypatch.setattr(cb, "_offload_device_ok", lambda t: True)
+ model = _group_offloaded(cls)
+ kw = _inputs(True)
+ with torch.no_grad():
+ cb.prepare(model)
+ want = model(**kw)[0]
+ assert cb.begin_render(model)
+ _, hooked = cb._pre_hook(model, (), dict(kw))
+ pending = hooked[cb.COND_KWARG]
+ assert isinstance(pending, cb.Pending)
+ other = dict(kw, encoder_hidden_states = kw["encoder_hidden_states"].clone())
+ got = model(**other, unsloth_cond = pending)[0]
+ cb.end_render(model)
+ assert torch.equal(got, want)
+ stats = cb.status(model)
+ assert stats["misses"] == 0 and stats.get("in_forward", 0) == 0
+
+
+def test_a_pending_miss_is_never_graphed_or_a_cfg_template():
+ from core.inference import diffusion_cfg_batch as cfg
+ from core.inference import diffusion_cuda_graph as cg
+
+ pending = cb.Pending(("k", 1), (None,) * 4)
+ assert cg._uncapturable(cg.graph_key({cb.COND_KWARG: pending}))
+ router = SimpleNamespace(template = ("stale",), b0 = None)
+ cfg.CfgBatchRouter._record_template(router, (), {cb.COND_KWARG: pending}, None)
+ assert router.template is None
+
+
+def test_prefetch_order_follows_skipped_blocks():
+ from core.inference import diffusion_offload_prefetch as op
+
+ blocks = [torch.nn.Linear(1, 1) for _ in range(4)]
+ groups = [SimpleNamespace(modules = [b]) for b in blocks] + [
+ SimpleNamespace(modules = [torch.nn.Linear(1, 1)])
+ ]
+ ids = [id(g) for g in groups]
+ pf = SimpleNamespace(
+ active = True, seen = [], pos = 0, order = list(ids), on_order = True, by_id = dict(zip(ids, groups))
+ )
+ module = SimpleNamespace(**{op.PREFETCHER_ATTR: pf})
+ op.match_skipped_order(module, blocks[:2], skipping = True)
+ assert pf.order == ids[2:] and pf.on_order
+ op.match_skipped_order(module, blocks[:2], skipping = False)
+ assert pf.order == ids
+ pf.seen = [ids[0]]
+ op.match_skipped_order(module, blocks[:2], skipping = True)
+ assert pf.order == ids
+
+
+def _mod_rows(model):
+ rows = []
+ heads = [m.linear for m in model.early_stream_modulations.values()]
+ heads += [m.linear for m in model.single_stream_modulations.values()] + [model.norm_out.linear]
+ for head in heads:
+ head.register_forward_pre_hook(lambda m, a: rows.append(int(a[0].shape[1])))
+ return rows
+
+
+ "flow_map,refs", [(False, False), (False, True), (True, False), (True, True)]
+)
+def test_compact_modulation_matches_stock_in_float64(flow_map, refs, monkeypatch):
+ """One modulation row per sample equals the stock per-token rows up to float64 rounding."""
+ cls = _flux3()
+ monkeypatch.delenv(cb.COMPACT_MOD_ENV, raising = False)
+ model = _tiny(cls, flow_map = flow_map).double()
+ kw = _inputs(refs)
+ kw = {
+ k: v.double() if torch.is_tensor(v) and k.endswith("states") else v for k, v in kw.items()
+ }
+ if flow_map:
+ kw["target_timestep"] = torch.tensor([0.3])
+ with torch.no_grad():
+ want = model(**kw)[0]
+ cb.prepare(model)
+ rows = _mod_rows(model)
+ got = model(**kw)[0]
+ assert rows and set(rows) == {1}
+ assert torch.allclose(got, want, rtol = 1e-12, atol = 1e-13)
+ assert cb.status(model)["compact"] == 1
+
+
+def test_compact_cached_render_matches_compact_stock_bitwise(monkeypatch):
+ cls = _flux3()
+ monkeypatch.delenv(cb.COND_BLOCKS_ENV, raising = False)
+ monkeypatch.delenv(cb.COMPACT_MOD_ENV, raising = False)
+ model = _tiny(cls)
+ cond = _inputs(True, seed = 1)
+ uncond = dict(cond, encoder_hidden_states = torch.randn(1, 7, 24), txt_ids = torch.zeros(7, 4))
+ with torch.no_grad():
+ assert cb.prepare(model)
+ want = _steps(model, [cond, uncond])
+ assert cb.begin_render(model)
+ try:
+ got = _steps(model, [cond, uncond])
+ finally:
+ cb.end_render(model)
+ assert all(torch.equal(a, b) for a, b in zip(want, got))
+ assert model.__dict__["_unsloth_cond_cache"] == {}
+
+
+def test_compact_kill_switch_grad_and_lora_scale_keep_stock(monkeypatch):
+ cls = _flux3()
+ model = _tiny(cls, flow_map = True)
+ kw = dict(_inputs(True), target_timestep = torch.tensor([0.3]))
+ monkeypatch.setenv(cb.COMPACT_MOD_ENV, "0")
+ cb.prepare(model)
+ assert not model.__dict__.get(cb._COMPACT_ATTR)
+ with torch.no_grad():
+ model(**kw)
+ monkeypatch.delenv(cb.COMPACT_MOD_ENV)
+ cb.prepare(model)
+ assert model.__dict__.get(cb._COMPACT_ATTR)
+ model(**kw)
+ with torch.no_grad():
+ model(**dict(kw, attention_kwargs = {"scale": 0.5}))
+ assert cb.status(model).get("compact", 0) == 0
+
+
def test_pre_hook_stays_last(monkeypatch):
"""A hook registered after the cache (dynamic text dims installs at compile time) must still run first, so the
conditioning blocks run inside its scope."""
diff --git a/studio/backend/tests/test_diffusion_cond_blocks_device.py b/studio/backend/tests/test_diffusion_cond_blocks_device.py
new file mode 100644
index 00000000000..9fa8114919a
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_cond_blocks_device.py
@@ -0,0 +1,129 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""FLUX.3 compact modulation and offload cache on a real CUDA / ROCm device, against a float64 CPU oracle."""
+
+import pytest
+
+torch = pytest.importorskip("torch")
+
+from core.inference import diffusion_cond_blocks as cb # noqa: E402
+
+pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason = "needs a CUDA or ROCm device")
+
+
+def _cls():
+ diffusers = pytest.importorskip("diffusers")
+ cls = getattr(diffusers, "Flux3Transformer2DModel", None)
+ if cls is None or (
+ cb._forward_sha(cls) not in cb._FLUX3_FORWARD_SHA and cls not in cb._PATCHED
+ ):
+ pytest.skip("no matching diffusers Flux3Transformer2DModel")
+ return cls
+
+
+def _tiny(cls, flow_map):
+ torch.manual_seed(0)
+ return cls(
+ in_channels = 16,
+ cond_in_channels = 16,
+ num_layers = 2,
+ num_single_layers = 2,
+ attention_head_dim = 32,
+ num_attention_heads = 4,
+ joint_attention_dim = 64,
+ timestep_channels = 64,
+ axes_dims_rope = (8, 8, 8, 8),
+ flow_map = flow_map,
+ ).eval()
+
+
+def _inputs(refs, flow_map, device, dtype):
+ g = torch.Generator().manual_seed(1)
+ img, txt = 256, 24
+ kw = {
+ "hidden_states": torch.randn(1, img, 16, generator = g),
+ "encoder_hidden_states": torch.randn(1, txt, 64, generator = g),
+ "timestep": torch.tensor([0.7]),
+ "img_ids": torch.randint(0, 16, (img, 4), generator = g).float(),
+ "txt_ids": torch.randint(0, 16, (txt, 4), generator = g).float(),
+ "return_dict": False,
+ }
+ if refs:
+ kw["image_cond_hidden_states"] = torch.randn(1, 192, 16, generator = g)
+ kw["image_cond_ids"] = torch.randint(0, 16, (192, 4), generator = g).float()
+ if flow_map:
+ kw["target_timestep"] = torch.tensor([0.4])
+ out = {}
+ for k, v in kw.items():
+ if torch.is_tensor(v):
+ v = v.to(device)
+ if k.endswith("states"):
+ v = v.to(dtype)
+ out[k] = v
+ return out
+
+
+ "flow_map,refs", [(False, False), (False, True), (True, False), (True, True)]
+)
+def test_prepared_forward_tracks_the_float64_oracle(flow_map, refs):
+ cls = _cls()
+ ref = _tiny(cls, flow_map).double()
+ with torch.no_grad():
+ want = ref(**_inputs(refs, flow_map, "cpu", torch.float64))[0]
+ dev = torch.device("cuda")
+ stock = _tiny(cls, flow_map).to(dev, torch.bfloat16)
+ prepared = _tiny(cls, flow_map).to(dev, torch.bfloat16)
+ kw = _inputs(refs, flow_map, dev, torch.bfloat16)
+ with torch.no_grad():
+ base = stock(**kw)[0].double().cpu()
+ cb.prepare(prepared)
+ cb.begin_render(prepared)
+ try:
+ got = prepared(**kw)[0].double().cpu()
+ finally:
+ cb.end_render(prepared)
+ err_stock = (base - want).abs().max().item()
+ err_got = (got - want).abs().max().item()
+ assert torch.isfinite(got).all()
+ assert err_got <= 1.5 * err_stock + 1e-3, (err_got, err_stock)
+
+
+def test_group_offloaded_base_edit_matches_stock():
+ cls = _cls()
+ from diffusers.hooks import apply_group_offloading
+
+ dev = torch.device("cuda")
+ stock = _tiny(cls, False).to(dev, torch.bfloat16)
+ model = _tiny(cls, False).to(torch.bfloat16)
+ apply_group_offloading(
+ model,
+ onload_device = dev,
+ offload_device = torch.device("cpu"),
+ offload_type = "block_level",
+ num_blocks_per_group = 1,
+ )
+ cond = _inputs(True, False, dev, torch.bfloat16)
+ uncond = dict(cond, encoder_hidden_states = torch.randn_like(cond["encoder_hidden_states"]))
+ with torch.no_grad():
+ cb.prepare(stock)
+ cb.prepare(model)
+ want, got = [], []
+ for net, out in ((stock, want), (model, got)):
+ cb.begin_render(net)
+ try:
+ for i in range(3):
+ for kw in (cond, uncond):
+ out.append(
+ net(**dict(kw, timestep = torch.tensor([0.9 - 0.2 * i], device = dev)))[0]
+ )
+ finally:
+ cb.end_render(net)
+ for a, b in zip(want, got):
+ assert torch.allclose(a.float(), b.float(), rtol = 0, atol = 1e-2), (a - b).abs().max()
+ stats = cb.status(model) or {}
+ if getattr(torch.version, "hip", None) is None and hasattr(cb, "offload_cache_enabled"):
+ assert (stats.get("misses"), stats.get("hits"), stats.get("in_forward")) == (2, 4, 2)
+ else:
+ assert not stats.get("hits") and not stats.get("misses")