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: record a prompt length's CUDA graph on the first render only (#14387)

Daniel Hanc6d77f242633
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 960b8d46c97..8008987b6bc 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -12671,6 +12671,8 @@ class DiffusionBackend:
raise
if previewer is not None:
previewer.finish()
+ # A denoiser whose text length follows the prompt records no new prompt length after this render.
+ cuda_graph.seal_lengths(state.cuda_graphs)
_record_peak_probe(
state,
peak_probe,
diff --git a/studio/backend/core/inference/diffusion_cuda_graph.py b/studio/backend/core/inference/diffusion_cuda_graph.py
index 3b0238b5e45..3383e9be46a 100644
--- a/studio/backend/core/inference/diffusion_cuda_graph.py
+++ b/studio/backend/core/inference/diffusion_cuda_graph.py
@@ -51,6 +51,36 @@ def _torch():
FORCE_FAMILIES_ENV = "UNSLOTH_DIFFUSION_CUDA_GRAPH_FAMILIES"
# A module attribute: zero-arg callable returning hashable per-call state that the forward branches on.
GRAPH_KEY_EXTRA_ATTR = "_unsloth_graph_key_extra"
+# =1: a denoiser whose text length follows the prompt records every new prompt length, on any render (the old way).
+EVERY_LENGTH_ENV = "UNSLOTH_DIFFUSION_CUDA_GRAPH_EVERY_LENGTH"
+
+
+def _every_length() -> bool:
+ return (os.environ.get(EVERY_LENGTH_ENV) or "").strip().lower() in _TRUE_TOKENS
+
+
+def _length_varies(module: Any) -> bool:
+ """Whether ``module``'s graphs key on the prompt length (diffusion_dynamic_text.PROMPT_LENGTH_POLICY)."""
+ if _every_length():
+ return False
+ try:
+ from .diffusion_dynamic_text import prompt_length_varies # noqa: PLC0415
+ return bool(prompt_length_varies(module))
+ except Exception: # noqa: BLE001 - an unanswerable probe keeps today's graphs
+ return False
+
+
+_REFERENCE_KWARGS = ("image_cond_hidden_states", "image_cond_ids")
+
+
+def _image_scope(args: tuple, kwargs: dict) -> tuple:
+ """The non-text part of a call's shape: the key of its first argument, the latents in every variable-length
+ family's denoiser call (``hidden_states`` for Qwen-Image, Qwen-Image-2.1's planned step, FLUX.1 and FLUX.3, the
+ latent list for Z-Image), plus any separate reference images. Resolution, batch and reference images change it;
+ the prompt length does not."""
+ first = args[0] if args else next(iter(kwargs.values()), None)
+ refs = tuple((name, graph_key(kwargs[name])) for name in _REFERENCE_KWARGS if name in kwargs)
+ return (graph_key(first),) + refs if refs else graph_key(first)
def _family_forced(family: Any) -> bool:
@@ -714,10 +744,26 @@ class GraphedForward:
"shape_warmups": 0,
"evictions": 0,
"speed_eager": 0,
+ "length_eager": 0,
}
self.valid_token: Any = None
+ # A denoiser whose text length follows the prompt keys a graph per prompt length, so every new prompt recorded
+ # one (warm-up forwards, a sync, the capture) on its render: Qwen-Image captured on generations 2 and 3. Per
+ # image scope (resolution, batch, references: _image_scope) it records the lengths of that scope's first render
+ # only: once one of its graphs replayed (or that render ended, seal_lengths), a prompt length it never recorded
+ # runs the compiled step ungraphed (the same kernels, so the same image) and a recorded one replays. A scope
+ # seen for the first time opens its own window, so a new resolution still records as before.
+ self.length_varies = _length_varies(module)
+ self._sealed_scopes: set = set()
+ self._scope_captures: dict = {}
+ self._render_scopes: set = set()
_LIVE_WRAPPERS.add(self)
+ @property
+ def length_sealed(self) -> bool:
+ """Whether some image scope stopped recording new prompt lengths."""
+ return bool(getattr(self, "_sealed_scopes", None))
+
def install(self) -> "GraphedForward":
"""Set ``forward`` via ``__dict__`` (``__setattr__`` would inspect it), under any outer step-skip layer."""
if self.placement is not None:
@@ -787,6 +833,10 @@ class GraphedForward:
"""Drop every captured graph (weights changed under us: LoRA load, unload, adapter switch)."""
self.cache.clear()
self._recorded.clear()
+ # Nothing recorded is left to replay: every scope's first render starts over (captures counted afresh).
+ self._sealed_scopes.clear()
+ self._scope_captures.clear()
+ self._render_scopes.clear()
if getattr(self, "fallback_handle", None) is not None:
try:
self.fallback_handle.reset()
@@ -840,6 +890,7 @@ class GraphedForward:
"warmup": int(self.warmup),
"max_graphs": int(self.max_graphs),
"cap_hit": bool(self.cap_hit),
+ "length_sealed": bool(getattr(self, "length_sealed", False)),
"placement": None if self.placement is None else self.placement.mode,
"stats": dict(self.stats),
"fallback": None
@@ -1090,6 +1141,10 @@ class GraphedForward:
# null-mask flag): a graph recorded on one branch must never replay for the other.
key = key + (("x", extra()),)
entry = self.cache.get(key)
+ scope = _image_scope(args, kwargs) if getattr(self, "length_varies", False) else None
+ # A key that also follows the step (NVFP4 protect branch, a pre-hook's branch flag) has variants a later
+ # step of this render still has to record: its scope seals when the render ends (seal_lengths).
+ step_keyed = bool(self.protect_keyed) or callable(extra)
except Exception: # noqa: BLE001 - an unhashable tree is simply not capturable
self.stats["refused_object"] += 1
return self._eager(eager_args, eager_kwargs)
@@ -1101,6 +1156,15 @@ class GraphedForward:
if _has_float(key):
self.stats["refused_float"] += 1
return self._eager(eager_args, eager_kwargs)
+ if scope is not None:
+ self._render_scopes.add(scope)
+ if scope in getattr(self, "_sealed_scopes", ()) and (
+ self.placement is None or key not in self._recorded
+ ):
+ # A prompt length first seen after the first render: no warm-up, no capture, no eviction on this
+ # render. (An offloaded key it recorded before re-records after its weights moved, as before.)
+ self.stats["length_eager"] += 1
+ return self._eager(eager_args, eager_kwargs)
if self.placement is not None and speed_check_enabled():
if key in self._dropped:
return self._eager(eager_args, eager_kwargs)
@@ -1174,6 +1238,8 @@ class GraphedForward:
return self._eager(eager_args, eager_kwargs)
entry = captured
self.cache[key] = entry
+ if scope is not None:
+ self._scope_captures[scope] = self._scope_captures.get(scope, 0) + 1
self._unsloth_capture_device = capture_device()
note_capture(self._unsloth_capture_device)
if self.logger is not None:
@@ -1185,8 +1251,13 @@ class GraphedForward:
len(entry.static),
)
- elif self.plan is not None:
- self.cache[key] = self.cache.pop(key)
+ else:
+ if scope is not None:
+ self._render_scopes.add(scope)
+ if not step_keyed:
+ self._sealed_scopes.add(scope)
+ if self.plan is not None:
+ self.cache[key] = self.cache.pop(key)
live: list = []
_flatten((args, kwargs), live)
@@ -1890,6 +1961,32 @@ def _denoiser_modules(pipe: Any) -> list:
return [unet] if unet is not None else []
+PROMPT_LENGTH_REASON = "text length follows the prompt"
+
+
+def prompt_length_reason(pipe: Any, family: Any = None) -> Optional[str]:
+ """Why a denoiser whose text length follows the prompt (diffusion_dynamic_text.PROMPT_LENGTH_POLICY) records no
+ per-block graphs, else None. A block's graph keys on its inputs, which carry the text stream, so every new prompt
+ length would record every block again on that render; its whole-step graph instead records the first render's
+ lengths only (``GraphedForward.length_sealed``). ``UNSLOTH_DIFFUSION_CUDA_GRAPH_FAMILIES`` and
+ ``UNSLOTH_DIFFUSION_CUDA_GRAPH_EVERY_LENGTH`` still force it."""
+ if _family_forced(family) or _every_length():
+ return None
+ try:
+ from .diffusion_dynamic_text import prompt_length_varies # noqa: PLC0415
+ names = sorted(
+ {type(m).__name__ for m in _denoiser_modules(pipe) if prompt_length_varies(m)}
+ )
+ except Exception: # noqa: BLE001 - an unanswerable probe keeps today's graphs
+ return None
+ if not names:
+ return None
+ return (
+ f"{PROMPT_LENGTH_REASON} ({', '.join(names)}): per-block graphs would record every block again on each "
+ f"new prompt length, so the blocks run compiled ungraphed"
+ )
+
+
def graph_eligible(
target: Any,
*,
@@ -1997,6 +2094,23 @@ def install_cuda_graphs(
return installed
+def seal_lengths(handles: Any) -> None:
+ """A render ended: a denoiser whose text length follows the prompt records no new prompt length from here on
+ (until ``reset``). Covers a first render that recorded but never replayed (an offloaded key still being timed)."""
+ for handle in handles or ():
+ try:
+ if not getattr(handle, "length_varies", False):
+ continue
+ # Only a scope that recorded since the last reset: a render that only warmed up (a planned step's first
+ # call at a new length) or recorded nothing keeps its window open.
+ for scope in handle._render_scopes:
+ if handle._scope_captures.get(scope, 0) > 0:
+ handle._sealed_scopes.add(scope)
+ handle._render_scopes.clear()
+ except Exception: # noqa: BLE001 - optimisation only
+ pass
+
+
def set_bypass(handles: Any, on: bool) -> None:
"""Run eager without dropping graphs, for every handle."""
for handle in handles or ():
@@ -2209,7 +2323,9 @@ def arm_block_graphs(
if whole and len(step) == len(whole):
# The whole step stays primary; where per-block graphs are the default they arm for the calls it leaves eager.
pipe._unsloth_cuda_graph_mode = "step"
- why = _block_basics(target, family, cache_engaged, speed_mode, family_default)
+ why = _block_basics(
+ target, family, cache_engaged, speed_mode, family_default
+ ) or prompt_length_reason(pipe, family)
if why is None:
_attach_block_fallback(pipe, step, target, hooked, pinned, logger)
return handles
@@ -2217,7 +2333,9 @@ def arm_block_graphs(
# Nothing moves the denoiser: the speed layer's decision stands, except a forward that is not capture-safe,
# whose blocks still record.
return handles
- why = _block_basics(target, family, cache_engaged, speed_mode, family_default)
+ why = _block_basics(
+ target, family, cache_engaged, speed_mode, family_default
+ ) or prompt_length_reason(pipe, family)
if whole:
uninstall_all(whole, logger = logger)
pipe._unsloth_cuda_graph_mode = None
diff --git a/studio/backend/core/inference/diffusion_dynamic_text.py b/studio/backend/core/inference/diffusion_dynamic_text.py
index f86c3de79a8..8f913cd52d4 100644
--- a/studio/backend/core/inference/diffusion_dynamic_text.py
+++ b/studio/backend/core/inference/diffusion_dynamic_text.py
@@ -65,6 +65,63 @@ _FLUX3_SOURCES: tuple[str, ...] = (
"L['image_rotary_emb'][1]",
)
+# FLUX.1: Studio pads T5 to 256 tokens, or 512 for a longer prompt (diffusion_text_length.flux_t5_sequence_length),
+# so the first prompt past 256 tokens was a new shape. Double blocks see the text stream beside the image tokens,
+# single blocks take both, and the rotary tables span text + image.
+_FLUX1_SOURCES: tuple[str, ...] = (
+ "L['hidden_states']",
+ "L['encoder_hidden_states']",
+ "L['image_rotary_emb'][0]",
+ "L['image_rotary_emb'][1]",
+ r".*\['hidden_states'\]$",
+ r".*\['encoder_hidden_states'\]$",
+ r".*\['image_rotary_emb'\]\[[01]\]$",
+)
+
+# Z-Image: the pipeline drops the padded caption tokens (pipeline_z_image.py, ``prompt_embeds[i][prompt_masks[i]]``)
+# and the transformer pads the caption to a multiple of 32, so every new 32-token bucket was a new shape. The
+# context refiner sees the caption alone, the main layers the unified caption + image sequence, both positionally
+# as (x, attn_mask, freqs_cis, ...).
+_ZIMAGE_SOURCES: tuple[str, ...] = (
+ "L['x']",
+ "L['attn_mask']",
+ "L['freqs_cis']",
+ r".*\['args'\]\[[0-2]\]$",
+)
+
+# Prompt-length policy for every denoiser class Studio loads (the ONE list; test_diffusion_prompt_length_policy checks
+# it covers diffusion_families and video_families). A tuple: the denoiser's text length follows the prompt, and these
+# are the repeated block's dynamo sources that carry it. FIXED_LENGTH: the pipeline pads every prompt to one length
+# (padding="max_length" to max_sequence_length, masked), so a new prompt never changes a shape.
+FIXED_LENGTH = "fixed"
+PROMPT_LENGTH_POLICY: dict[str, Any] = {
+ "FluxTransformer2DModel": _FLUX1_SOURCES,
+ "Flux2Transformer2DModel": FIXED_LENGTH, # Mistral / Qwen3 padded to max_sequence_length 512
+ "Flux3Transformer2DModel": _FLUX3_SOURCES,
+ "QwenImageTransformer2DModel": _QWEN_IMAGE_SOURCES,
+ "QwenImage21Transformer2DModel": _QWEN_IMAGE_21_SOURCES,
+ "ZImageTransformer2DModel": _ZIMAGE_SOURCES,
+ "Krea2Transformer2DModel": FIXED_LENGTH, # padded to max_sequence_length 512
+ "Lumina2Transformer2DModel": FIXED_LENGTH, # Gemma padded to max_sequence_length 256
+ "HunyuanImageTransformer2DModel": FIXED_LENGTH, # padded to the tokenizer max length
+ "HiDreamImageTransformer2DModel": FIXED_LENGTH, # T5 / Llama padded to max_sequence_length 128
+ "Ideogram4Transformer2DModel": FIXED_LENGTH, # token ids left-padded into max_sequence_length 2048
+ "UNet2DConditionModel": FIXED_LENGTH, # CLIP padded to 77
+ "MiniMaxH3Transformer3DModel": _MINIMAX_H3_SOURCES,
+ "LTX2VideoTransformer3DModel": FIXED_LENGTH, # Gemma left-padded to max_sequence_length 1024
+ "WanTransformer3DModel": FIXED_LENGTH, # UMT5 padded to max_sequence_length 512
+ "HunyuanVideo15Transformer3DModel": FIXED_LENGTH, # padded to the tokenizer max length
+}
+
+
+def prompt_length_varies(transformer: Any) -> bool:
+ """Whether ``transformer``'s text length follows the prompt (a class or an instance), so every new prompt length is
+ a new input shape. An unclassified class answers False: it keeps what it does today."""
+ cls = transformer if isinstance(transformer, type) else type(transformer)
+ return isinstance(PROMPT_LENGTH_POLICY.get(cls.__name__), tuple)
+
+
+# What the compile arms (FLUX.1 and Z-Image are classified above but not armed here).
_FAMILY_SOURCES: dict[str, tuple[str, ...]] = {
"Flux3Transformer2DModel": _FLUX3_SOURCES,
"QwenImage21Transformer2DModel": _QWEN_IMAGE_21_SOURCES,
diff --git a/studio/backend/tests/test_diffusion_block_graph.py b/studio/backend/tests/test_diffusion_block_graph.py
index fbc06dbe937..db0426f7806 100644
--- a/studio/backend/tests/test_diffusion_block_graph.py
+++ b/studio/backend/tests/test_diffusion_block_graph.py
@@ -876,3 +876,17 @@ def test_torchao_int8_weights_stream_through_the_slot_ring_with_graphs():
assert handle.stats["replays"] > 0 and handle.stats["fallbacks"] == 0
assert pf.stats["slot_fills"] > 0
handle.free()
+
+
+def test_a_variable_length_denoiser_records_no_block_graphs(monkeypatch):
+ """Per-block graphs key on the block inputs, which carry the text stream: a denoiser whose text length follows
+ the prompt would record every block again for each new prompt length, so it runs compiled ungraphed."""
+ monkeypatch.delenv(bg.BLOCK_GRAPHS_ENV, raising = False)
+ monkeypatch.delenv(cg.FORCE_FAMILIES_ENV, raising = False)
+ net = type("QwenImageTransformer2DModel", (Net,), {})(blocks = 3)
+ pipe = _pipe_with(net)
+ pipe._unsloth_cuda_graph_reason = "offload active"
+ handles, applied = _arm(pipe, monkeypatch, hooked = True, pinned = True, opt_in = False)
+ assert handles == () and not applied["cuda_graph"]
+ assert cg.status_reason(pipe, False).startswith(cg.PROMPT_LENGTH_REASON)
+ assert not any(isinstance(b.__dict__.get("forward"), bg.BlockGraph) for b in net.blocks)
diff --git a/studio/backend/tests/test_diffusion_cuda_graph.py b/studio/backend/tests/test_diffusion_cuda_graph.py
index 42b752d0679..3010fbb5a21 100644
--- a/studio/backend/tests/test_diffusion_cuda_graph.py
+++ b/studio/backend/tests/test_diffusion_cuda_graph.py
@@ -1179,3 +1179,293 @@ def test_graph_eligible_keeps_other_backends(stub_torch, monkeypatch, backend):
dit = _FakeDiT()
dit._unsloth_attention_backend = backend
assert _eligible(monkeypatch, pipe = types.SimpleNamespace(transformer = dit)) == (True, "eligible")
+
+
+def _named_dit(name):
+ return type(name, (_FakeDiT,), {})()
+
+
+def _policy():
+ from core.inference.diffusion_dynamic_text import PROMPT_LENGTH_POLICY
+ return PROMPT_LENGTH_POLICY
+
+
+def _step(
+ handle,
+ text_len,
+ value = 0.0,
+):
+ """One denoiser call whose text stream is ``text_len`` tokens (the graph key follows it)."""
+ return handle(
+ _t((1, 64), value = value), encoder_hidden_states = _t((1, text_len)), return_dict = False
+ )
+
+
+def _render(
+ handle,
+ text_len,
+ steps = 3,
+ negative_len = 7,
+):
+ """A true-CFG render: per step the prompt's call, then the negative prompt's."""
+ for i in range(steps):
+ _step(handle, text_len, value = float(i))
+ _step(handle, negative_len, value = float(i))
+
+
+class _LenDiT:
+ """``_FakeDiT`` that also takes the text stream."""
+
+ def __init__(self):
+ self.calls = 0
+
+ def forward(
+ self,
+ hidden_states,
+ encoder_hidden_states = None,
+ return_dict = True,
+ ):
+ self.calls += 1
+ return (_FakeTensor((1, 64), value = ("out", hidden_states.value), tag = "out"),)
+
+
+def _len_dit(name):
+ return type(name, (_LenDiT,), {})()
+
+
[email protected]("name", sorted(_policy()))
+def test_the_wrapper_reads_the_prompt_length_policy(stub_torch, monkeypatch, name):
+ monkeypatch.delenv(cg.EVERY_LENGTH_ENV, raising = False)
+ handle = _armed(_len_dit(name))
+ assert handle.length_varies is isinstance(_policy()[name], tuple)
+ assert handle.length_sealed is False
+ # whole-step graphs stay eligible for every family: only what they record changes
+ ok, reason = _eligible(monkeypatch, pipe = types.SimpleNamespace(transformer = _named_dit(name)))
+ assert (ok, reason) == (True, "eligible")
+
+
+def test_a_new_prompt_length_after_the_first_render_records_nothing(stub_torch, monkeypatch):
+ """Qwen-Image's text length follows the prompt: generation 2 with a new length recorded a graph on that render
+ (seconds of capture). The first render's lengths replay; a new one runs the step ungraphed."""
+ monkeypatch.delenv(cg.EVERY_LENGTH_ENV, raising = False)
+ module = _len_dit("QwenImageTransformer2DModel")
+ handle = _armed(module)
+ _render(handle, 3)
+ assert handle.stats["captures"] == 2 and handle.length_sealed is True
+ calls, replays, graphs = module.calls, handle.stats["replays"], stub_torch._records["graphs"][:]
+
+ _render(handle, 15)
+ assert handle.stats["captures"] == 2
+ assert stub_torch._records["graphs"] == graphs
+ assert handle.stats["length_eager"] == 3
+ assert module.calls == calls + 3
+ assert handle.stats["replays"] == replays + 3
+ assert len(handle.cache) == 2 and handle.stats["evictions"] == 0
+
+ _render(handle, 3)
+ assert handle.stats["captures"] == 2 and handle.stats["replays"] == replays + 9
+ assert handle.stats["length_eager"] == 3
+
+
+def test_the_ungraphed_step_returns_what_the_step_itself_returns(stub_torch, monkeypatch):
+ monkeypatch.delenv(cg.EVERY_LENGTH_ENV, raising = False)
+ handle = _armed(_len_dit("ZImageTransformer2DModel"))
+ _render(handle, 32, negative_len = 32)
+ out = _step(handle, 64, value = 5.0)
+ assert out[0].value == ("out", 5.0) and out[0].clone_of is None
+
+
+def test_a_fixed_length_family_records_as_before(stub_torch):
+ handle = _armed(_len_dit("Flux2Transformer2DModel"))
+ _render(handle, 512, negative_len = 512)
+ _render(handle, 300, negative_len = 300) # (cannot happen for FLUX.2: its text is padded to 512)
+ # what it did before this policy: every new shape records (behaviour only, so it holds on either side)
+ assert handle.stats["captures"] == 2 and handle.stats.get("length_eager", 0) == 0
+ assert not getattr(handle, "length_sealed", False)
+
+
+def test_reset_reopens_the_first_render(stub_torch, monkeypatch):
+ monkeypatch.delenv(cg.EVERY_LENGTH_ENV, raising = False)
+ handle = _armed(_len_dit("QwenImageTransformer2DModel"))
+ _render(handle, 3)
+ handle.reset() # a LoRA changed the weights: nothing recorded is left to replay
+ assert handle.length_sealed is False
+ _render(handle, 15)
+ assert handle.stats["captures"] == 4 and handle.stats["length_eager"] == 0
+ assert handle.length_sealed is True
+
+
+def test_the_every_length_switch_records_each_new_length(stub_torch, monkeypatch):
+ monkeypatch.setenv(cg.EVERY_LENGTH_ENV, "1")
+ handle = _armed(_len_dit("QwenImageTransformer2DModel"))
+ _render(handle, 3)
+ _render(handle, 15)
+ assert handle.length_varies is False and handle.stats["captures"] == 3
+
+
+def test_seal_lengths_closes_a_first_render_that_never_replayed(stub_torch, monkeypatch):
+ monkeypatch.delenv(cg.EVERY_LENGTH_ENV, raising = False)
+ varying = _armed(_len_dit("QwenImageTransformer2DModel"))
+ fixed = _armed(_len_dit("Flux2Transformer2DModel"))
+ idle = _armed(_len_dit("Flux3Transformer2DModel"))
+ _step(varying, 3)
+ _step(fixed, 512)
+ assert varying.length_sealed is False
+ cg.seal_lengths((varying, fixed, idle, object()))
+ assert varying.length_sealed is True
+ assert fixed.length_sealed is False
+ assert idle.length_sealed is False
+ _step(varying, 15)
+ assert varying.stats["captures"] == 1 and varying.stats["length_eager"] == 1
+
+
+def test_describe_reports_the_seal(stub_torch, monkeypatch):
+ monkeypatch.delenv(cg.EVERY_LENGTH_ENV, raising = False)
+ handle = _armed(_len_dit("QwenImageTransformer2DModel"))
+ _render(handle, 3)
+ _render(handle, 15)
+ info = handle.describe()
+ assert info["length_sealed"] is True and info["stats"]["length_eager"] == 3
+ json.dumps(info)
+
+
+def test_block_graphs_decline_a_variable_length_denoiser(stub_torch, monkeypatch):
+ monkeypatch.delenv(cg.FORCE_FAMILIES_ENV, raising = False)
+ pipe = types.SimpleNamespace(transformer = _named_dit("QwenImageTransformer2DModel"))
+ assert cg.prompt_length_reason(pipe).startswith(cg.PROMPT_LENGTH_REASON)
+ assert (
+ cg.prompt_length_reason(
+ types.SimpleNamespace(transformer = _named_dit("Flux2Transformer2DModel"))
+ )
+ is None
+ )
+ family = types.SimpleNamespace(name = "qwen-image")
+ monkeypatch.setenv(cg.FORCE_FAMILIES_ENV, "qwen-image")
+ assert cg.prompt_length_reason(pipe, family) is None
+
+
+def _render_at(
+ handle,
+ width,
+ text_len,
+ steps = 2,
+ negative_len = 7,
+):
+ """A true-CFG render at latent width ``width`` (the image scope) with a ``text_len``-token prompt."""
+ for i in range(steps):
+ handle(
+ _t((1, width), value = float(i)),
+ encoder_hidden_states = _t((1, text_len)),
+ return_dict = False,
+ )
+ handle(
+ _t((1, width), value = float(i)),
+ encoder_hidden_states = _t((1, negative_len)),
+ return_dict = False,
+ )
+
+
+def test_a_new_resolution_still_records_after_the_seal(stub_torch, monkeypatch):
+ """The seal stops new TEXT lengths only: a later render at a new resolution (or batch) is a new image scope and
+ records its first render, as before; a further new prompt length at that resolution then runs ungraphed."""
+ monkeypatch.delenv(cg.EVERY_LENGTH_ENV, raising = False)
+ handle = _armed(_len_dit("QwenImageTransformer2DModel"), max_graphs = 8)
+ _render_at(handle, 64, 3)
+ assert handle.stats["captures"] == 2 and handle.length_sealed
+ _render_at(handle, 128, 15)
+ assert handle.stats["captures"] == 4 and handle.stats["length_eager"] == 0
+ replays = handle.stats["replays"]
+ _render_at(handle, 128, 40)
+ assert handle.stats["captures"] == 4 and handle.stats["length_eager"] == 2
+ assert handle.stats["replays"] == replays + 2
+ _render_at(handle, 64, 40)
+ assert handle.stats["captures"] == 4 and handle.stats["length_eager"] == 4
+
+
+def test_a_render_with_no_capture_after_reset_does_not_seal(stub_torch, monkeypatch):
+ """seal_lengths counts captures since the last reset: a first render after reset that recorded nothing (bypassed
+ here, or a planned step that only warmed up) must not seal an empty cache, or its key runs ungraphed forever."""
+ monkeypatch.delenv(cg.EVERY_LENGTH_ENV, raising = False)
+ handle = _armed(_len_dit("QwenImageTransformer2DModel"))
+ _render(handle, 3)
+ handle.reset()
+ handle.set_bypass(True)
+ _render(handle, 15)
+ handle.set_bypass(False)
+ cg.seal_lengths((handle,))
+ assert handle.length_sealed is False
+ _render(handle, 15)
+ assert handle.stats["captures"] == 4 and handle.stats["length_eager"] == 0
+
+
+def test_a_step_dependent_key_seals_only_when_the_render_ends(stub_torch, monkeypatch):
+ """A key that also follows the step (NVFP4's protect branch, a pre-hook's branch flag) gets a new variant on a
+ later step of the first render: a replay on step 2 must not seal the scope before that variant records."""
+ monkeypatch.delenv(cg.EVERY_LENGTH_ENV, raising = False)
+ module = _len_dit("QwenImageTransformer2DModel")
+ branch = {"v": "a"}
+ setattr(module, cg.GRAPH_KEY_EXTRA_ATTR, lambda: branch["v"])
+ handle = _armed(module, max_graphs = 8)
+ for i, flag in enumerate(("a", "a", "b", "b")):
+ branch["v"] = flag
+ _step(handle, 3, value = float(i))
+ assert handle.stats["captures"] == 2 and handle.stats["length_eager"] == 0
+ assert handle.length_sealed is False
+ cg.seal_lengths((handle,))
+ assert handle.length_sealed is True
+ _step(handle, 15)
+ assert handle.stats["captures"] == 2 and handle.stats["length_eager"] == 1
+
+
+class _RefDiT(_LenDiT):
+ def forward(
+ self,
+ hidden_states,
+ encoder_hidden_states = None,
+ image_cond_hidden_states = None,
+ image_cond_ids = None,
+ return_dict = True,
+ ):
+ return super().forward(hidden_states, encoder_hidden_states, return_dict)
+
+
+def test_separate_reference_images_are_part_of_the_image_scope(stub_torch, monkeypatch):
+ """FLUX.3 passes its reference images apart from the latents: a new reference layout at the same output size is a
+ new scope that records its first render, not a sealed one that runs ungraphed."""
+ monkeypatch.delenv(cg.EVERY_LENGTH_ENV, raising = False)
+ module = type("Flux3Transformer2DModel", (_RefDiT,), {})()
+ handle = _armed(module, max_graphs = 8)
+ assert handle.length_varies is True
+
+ def call(
+ text_len,
+ refs,
+ value = 0.0,
+ ):
+ kw = {}
+ if refs:
+ kw = {"image_cond_hidden_states": _t((1, refs)), "image_cond_ids": _t((refs, 3))}
+ return handle(
+ _t((1, 64), value = value),
+ encoder_hidden_states = _t((1, text_len)),
+ return_dict = False,
+ **kw,
+ )
+
+ for i in range(2):
+ call(3, 0, float(i)) # text-only render: records, then replays and seals its scope
+ assert handle.stats["captures"] == 1 and handle.length_sealed
+ for i in range(2):
+ call(3, 16, float(i))
+ assert handle.stats["captures"] == 2 and handle.stats["length_eager"] == 0
+ call(9, 16)
+ assert handle.stats["captures"] == 2 and handle.stats["length_eager"] == 1
+
+
+def test_the_every_length_switch_keeps_block_graphs(stub_torch, monkeypatch):
+ monkeypatch.delenv(cg.FORCE_FAMILIES_ENV, raising = False)
+ pipe = types.SimpleNamespace(transformer = _named_dit("QwenImageTransformer2DModel"))
+ monkeypatch.delenv(cg.EVERY_LENGTH_ENV, raising = False)
+ assert cg.prompt_length_reason(pipe) is not None
+ monkeypatch.setenv(cg.EVERY_LENGTH_ENV, "1")
+ assert cg.prompt_length_reason(pipe) is None
diff --git a/studio/backend/tests/test_diffusion_prompt_length_policy.py b/studio/backend/tests/test_diffusion_prompt_length_policy.py
new file mode 100644
index 00000000000..cda7a40dd33
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_prompt_length_policy.py
@@ -0,0 +1,73 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Every denoiser class Studio loads has a prompt-length policy (diffusion_dynamic_text.PROMPT_LENGTH_POLICY): either
+the text length follows the prompt (the dynamo sources that carry it), or the pipeline pads every prompt to one
+length. The whole-step CUDA graph keys on input shapes, so it reads this table to tell the two apart."""
+
+from __future__ import annotations
+
+import re
+
+from core.inference import diffusion_dynamic_text as dt
+from core.inference import diffusion_families as df
+from core.inference import video_families as vf
+
+VARIABLE = (
+ "FluxTransformer2DModel",
+ "Flux3Transformer2DModel",
+ "QwenImageTransformer2DModel",
+ "QwenImage21Transformer2DModel",
+ "ZImageTransformer2DModel",
+ "MiniMaxH3Transformer3DModel",
+)
+
+
+def _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_class_has_a_prompt_length_policy():
+ missing = sorted(_classes() - set(dt.PROMPT_LENGTH_POLICY))
+ assert not missing, f"no prompt-length policy for {missing}"
+
+
+def test_policies_are_sources_or_fixed():
+ for name, policy in dt.PROMPT_LENGTH_POLICY.items():
+ assert policy == dt.FIXED_LENGTH or (isinstance(policy, tuple) and policy), name
+ if isinstance(policy, tuple):
+ for source in policy:
+ assert source.startswith("L[") or re.compile(source), (name, source)
+
+
+def test_variable_length_pipelines_are_classified():
+ for name in VARIABLE:
+ assert isinstance(dt.PROMPT_LENGTH_POLICY[name], tuple), name
+ fixed = sorted(n for n, p in dt.PROMPT_LENGTH_POLICY.items() if p == dt.FIXED_LENGTH)
+ assert fixed == sorted(set(dt.PROMPT_LENGTH_POLICY) - set(VARIABLE))
+
+
+def test_prompt_length_varies_reads_the_policy():
+ for name, policy in dt.PROMPT_LENGTH_POLICY.items():
+ cls = type(name, (), {})
+ assert dt.prompt_length_varies(cls) is isinstance(policy, tuple), name
+ assert dt.prompt_length_varies(cls()) is isinstance(policy, tuple), name
+ assert dt.prompt_length_varies(type("SomeNewTransformer", (), {})()) is False
+
+
+def test_the_compile_arms_only_its_own_sources():
+ # the classification adds no compile sources: FLUX.1 and Z-Image compile as before
+ assert set(dt._FAMILY_SOURCES) == {
+ "Flux3Transformer2DModel",
+ "QwenImage21Transformer2DModel",
+ "QwenImageTransformer2DModel",
+ "MiniMaxH3Transformer3DModel",
+ }
+ for name, sources in dt._FAMILY_SOURCES.items():
+ assert dt.PROMPT_LENGTH_POLICY[name] == sources, name