Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: stop the second prompt length recompiling Qwen-Image on the max tier and with int8 (#11842)
Daniel Han3cb9dd738155
diff --git a/studio/backend/core/inference/diffusion_compile_cache.py b/studio/backend/core/inference/diffusion_compile_cache.pyindex 9ea0eb5c797..b50e34871ac 100644--- a/studio/backend/core/inference/diffusion_compile_cache.py+++ b/studio/backend/core/inference/diffusion_compile_cache.py@@ -302,7 +302,7 @@ def model_fingerprint(# Native layers compile to a different graph than torchao under the same scheme name.from .diffusion_native_quant import native_quant_signaturequant = native_quant_signature(transformer) or quant- return {+ fp = {"family": str(family),"transformer_cls": type(transformer).__name__ if transformer is not None else None,"repeated_blocks": sorted(str(b) for b in blocks),@@ -317,6 +317,15 @@ def model_fingerprint(},"shape_bucket": shape_bucket,}+ # Added only when armed, so other bundles keep their key.+ try:+ from .diffusion_dynamic_text import fingerprint as _dynamic_text_fp+ dynamic_text = _dynamic_text_fp(transformer, compile_kwargs.get("dynamic", True))+ except Exception: # noqa: BLE001+ dynamic_text = None+ if dynamic_text:+ fp["dynamic_text"] = dynamic_text+ return fpdef cache_key(env_fp: dict[str, Any], model_fp: dict[str, Any]) -> str:diff --git a/studio/backend/core/inference/diffusion_dynamic_text.py b/studio/backend/core/inference/diffusion_dynamic_text.pynew file mode 100644index 00000000000..753578211f3--- /dev/null+++ b/studio/backend/core/inference/diffusion_dynamic_text.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++"""Mark a DiT's prompt-length inputs dynamic (``dynamic_sources``, scoped to its forward) so a new prompt length+never recompiles; blanket ``dynamic=True`` hits torchao CantSplit."""++from __future__ import annotations++from typing import Any, Optional++# segments[0][0] (always 0) stays static: a symbol there trips torchao CantSplit (rows become ``s0 - s_start``).+_QWEN_IMAGE_21_SOURCES: tuple[str, ...] = (+ "L['hidden_states']",+ "L['rotary_emb']",+ "L['target_token_mask']",+ "L['key_valid']",+ "L['attention_mask']",+ "L['layer_cache'].k",+ "L['layer_cache'].v",+ "L['cache_write_slice'].stop",+ "L['segments'][0][1]",+ r"L\['segments'\]\[\d+\]\[1\]$",+ r"L\['segments'\]\[[1-9]\d*\]\[0\]$",+)++# Suffix regexes cover FBCache hook paths: ``L['kwargs'][...]`` and, after a graph break, ``___stack0[1][...]``.+_QWEN_IMAGE_SOURCES: tuple[str, ...] = (+ "L['encoder_hidden_states']",+ "L['encoder_hidden_states_mask']",+ "L['image_rotary_emb'][1]",+ r".*\['encoder_hidden_states'\]$",+ r".*\['encoder_hidden_states_mask'\]$",+ r".*\['image_rotary_emb'\]\[1\]$",+)++_FAMILY_SOURCES: dict[str, tuple[str, ...]] = {+ "QwenImage21Transformer2DModel": _QWEN_IMAGE_21_SOURCES,+ "QwenImageTransformer2DModel": _QWEN_IMAGE_SOURCES,+}+++def _compiler_config() -> Any:+ try:+ import torch.compiler.config as cfg # noqa: PLC0415+ from torch._dynamo.variables import builder # noqa: PLC0415+ except Exception: # noqa: BLE001 - torch < 2.7 or no torch+ return None+ try:+ getattr(cfg, "dynamic_sources")+ except Exception: # noqa: BLE001 - knob absent on this build+ return None+ # 2.8+ only (is_dynamic_source): 2.7 caches its first read per process, so per-forward scoping leaks.+ if not callable(getattr(builder, "is_dynamic_source", None)):+ return None+ return cfg+++def supported() -> bool:+ return _compiler_config() is not None+++def sources_for(transformer: Any) -> tuple[str, ...]:+ return _FAMILY_SOURCES.get(type(transformer).__name__, ())+++def fingerprint(transformer: Any, dynamic: Any) -> Optional[str]:+ if dynamic is not None:+ return None+ sources = sources_for(transformer)+ if not sources or not supported():+ return None+ return ",".join(sources)+++def _merge(current: str, extra: tuple[str, ...]) -> str:+ parts = [p for p in (current or "").split(",") if p.strip()]+ for s in extra:+ if s not in parts:+ parts.append(s)+ return ",".join(parts)+++def install(transformer: Any, logger: Any = None) -> bool:+ if getattr(transformer, "_unsloth_dynamic_text", None) is not None:+ return True+ sources = sources_for(transformer)+ cfg = _compiler_config()+ if not sources or cfg is None:+ return False+ saved: list[Optional[str]] = []++ def _enter(module: Any, args: Any) -> None:+ prev = cfg.dynamic_sources+ saved.append(prev)+ cfg.dynamic_sources = _merge(prev, sources)++ def _exit(module: Any, args: Any, output: Any) -> None:+ if saved:+ cfg.dynamic_sources = saved.pop()++ try:+ pre = transformer.register_forward_pre_hook(_enter)+ post = transformer.register_forward_hook(_exit, always_call = True)+ except Exception as exc: # noqa: BLE001 - optimisation only+ if logger is not None:+ logger.warning("diffusion.dynamic_text: install failed: %s", exc)+ return False+ transformer._unsloth_dynamic_text = (pre, post)+ if logger is not None:+ logger.info(+ "diffusion.dynamic_text: prompt-length dims of %s compile dynamic from the first forward",+ type(transformer).__name__,+ )+ return True+++def uninstall(transformer: Any) -> None:+ handles = getattr(transformer, "_unsloth_dynamic_text", None)+ if not handles:+ return+ for h in handles:+ try:+ h.remove()+ except Exception: # noqa: BLE001+ pass+ try:+ del transformer._unsloth_dynamic_text+ except Exception: # noqa: BLE001+ passdiff --git a/studio/backend/core/inference/diffusion_speed.py b/studio/backend/core/inference/diffusion_speed.pyindex 0dc3f987e93..80bf3a41a52 100644--- a/studio/backend/core/inference/diffusion_speed.py+++ b/studio/backend/core/inference/diffusion_speed.py@@ -752,6 +752,12 @@ def _compile_repeated_blocks(except Exception as exc: # noqa: BLE001 - optimisation only_warn(logger, "compile_repeated_blocks", exc)continue+ if dit_kwargs["dynamic"] is None:+ try:+ from . import diffusion_dynamic_text+ diffusion_dynamic_text.install(transformer, logger)+ except Exception as exc: # noqa: BLE001 - optimisation only+ _warn(logger, "dynamic text dims", exc)# compile_repeated_blocks is lazy: inductor only runs on the first forward, inside generate(), where a lowering# bug would fail the render. Guard every compiled block so such a failure drops this DiT to eager instead.guard_compiled_blocks(transformer, logger)diff --git a/studio/backend/tests/test_diffusion_dynamic_text.py b/studio/backend/tests/test_diffusion_dynamic_text.pynew file mode 100644index 00000000000..487671d0f25--- /dev/null+++ b/studio/backend/tests/test_diffusion_dynamic_text.py@@ -0,0 +1,214 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from __future__ import annotations++import pytest++torch = pytest.importorskip("torch")++from core.inference import diffusion_dynamic_text as dt # noqa: E402++pytestmark = pytest.mark.skipif(+ not dt.supported(), reason = "torch lacks a re-read compiler.config.dynamic_sources (2.8+)"+)+++def _cfg():+ import torch.compiler.config as cfg+ return cfg+++class QwenImage21Transformer2DModel(torch.nn.Module):+ def __init__(self, raise_in_forward = False):+ super().__init__()+ self.seen = None+ self.raise_in_forward = raise_in_forward++ def forward(self, x):+ self.seen = _cfg().dynamic_sources+ if self.raise_in_forward:+ raise RuntimeError("boom")+ return x+++class OtherTransformer(torch.nn.Module):+ def forward(self, x):+ return x+++def test_allowlist_is_set_only_inside_forward():+ cfg = _cfg()+ before = cfg.dynamic_sources+ m = QwenImage21Transformer2DModel()+ assert dt.install(m) is True+ m(torch.zeros(1))+ for name in (+ "L['hidden_states']",+ "L['layer_cache'].k",+ "L['segments'][0][1]",+ "L['cache_write_slice'].stop",+ ):+ assert name in m.seen.split(",")+ assert cfg.dynamic_sources == before+++def test_allowlist_restored_when_forward_raises():+ cfg = _cfg()+ before = cfg.dynamic_sources+ m = QwenImage21Transformer2DModel(raise_in_forward = True)+ dt.install(m)+ with pytest.raises(RuntimeError):+ m(torch.zeros(1))+ assert cfg.dynamic_sources == before+++def test_existing_allowlist_is_kept():+ cfg = _cfg()+ before = cfg.dynamic_sources+ try:+ cfg.dynamic_sources = "L['user_thing']"+ m = QwenImage21Transformer2DModel()+ dt.install(m)+ m(torch.zeros(1))+ assert m.seen.split(",")[0] == "L['user_thing']"+ assert cfg.dynamic_sources == "L['user_thing']"+ finally:+ cfg.dynamic_sources = before+++def test_other_families_are_untouched():+ m = OtherTransformer()+ assert dt.install(m) is False+ assert not m._forward_pre_hooks and not m._forward_hooks+ assert dt.fingerprint(m, None) is None+++def test_install_is_idempotent_and_uninstall_removes_hooks():+ m = QwenImage21Transformer2DModel()+ assert dt.install(m) and dt.install(m)+ assert len(m._forward_pre_hooks) == 1+ dt.uninstall(m)+ assert not m._forward_pre_hooks and not m._forward_hooks+++def test_fingerprint_only_for_automatic_dynamic():+ m = QwenImage21Transformer2DModel()+ assert dt.fingerprint(m, None)+ assert dt.fingerprint(m, True) is None+ assert dt.fingerprint(m, False) is None+++def test_first_segment_start_stays_static():+ from torch._dynamo.variables.builder import is_dynamic_source as is_dynamic++ cfg = _cfg()+ before = cfg.dynamic_sources+ try:+ cfg.dynamic_sources = ",".join(dt.sources_for(QwenImage21Transformer2DModel()))+ assert not is_dynamic("L['segments'][0][0]")+ for name in (+ "L['segments'][0][1]",+ "L['segments'][2][0]",+ "L['segments'][2][1]",+ "L['layer_cache'].v",+ ):+ assert is_dynamic(name), name+ for name in ("L['modulation']", "L['hidden_states_2']", "L['layer_cache'].kv"):+ assert not is_dynamic(name), name+ finally:+ cfg.dynamic_sources = before+++def test_compile_cache_key_changes_only_for_armed_family():+ from core.inference import diffusion_compile_cache as cc++ kwargs = {"fullgraph": True, "dynamic": None, "mode": "max-autotune-no-cudagraphs"}+ other = cc.model_fingerprint(+ family = "x",+ transformer = OtherTransformer(),+ dtype = "bf16",+ quant = None,+ attention_backend = None,+ compile_kwargs = kwargs,+ )+ assert "dynamic_text" not in other+ q21 = cc.model_fingerprint(+ family = "qwen-image-2.1",+ transformer = QwenImage21Transformer2DModel(),+ dtype = "bf16",+ quant = None,+ attention_backend = None,+ compile_kwargs = kwargs,+ )+ assert q21["dynamic_text"]+ q21_default = cc.model_fingerprint(+ family = "qwen-image-2.1",+ transformer = QwenImage21Transformer2DModel(),+ dtype = "bf16",+ quant = None,+ attention_backend = None,+ compile_kwargs = {**kwargs, "dynamic": True},+ )+ assert "dynamic_text" not in q21_default+++class QwenImageTransformer2DModel(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.seen = None++ def forward(self, x):+ self.seen = _cfg().dynamic_sources+ return x+++def test_qwen_image_text_stream_is_armed():+ m = QwenImageTransformer2DModel()+ assert dt.install(m) is True+ m(torch.zeros(1))+ seen = m.seen.split(",")+ for name in (+ "L['encoder_hidden_states']",+ "L['encoder_hidden_states_mask']",+ "L['image_rotary_emb'][1]",+ ):+ assert name in seen+ assert "L['hidden_states']" not in seen+++def test_qwen_image_hook_paths_match_on_regex_torch():+ from torch._dynamo.variables.builder import is_dynamic_source as is_dynamic++ cfg = _cfg()+ before = cfg.dynamic_sources+ try:+ cfg.dynamic_sources = ",".join(dt.sources_for(QwenImageTransformer2DModel()))+ for name in (+ "L['kwargs']['encoder_hidden_states']",+ "___stack0[1]['encoder_hidden_states']",+ "L['kwargs']['encoder_hidden_states_mask']",+ "L['kwargs']['image_rotary_emb'][1]",+ ):+ assert is_dynamic(name), name+ for name in (+ "L['hidden_states']",+ "L['kwargs']['hidden_states']",+ "L['kwargs']['image_rotary_emb'][0]",+ "L['temb']",+ ):+ assert not is_dynamic(name), name+ finally:+ cfg.dynamic_sources = before+++def test_torch_that_reads_the_allowlist_once_is_not_armed(monkeypatch):+ from torch._dynamo.variables import builder++ monkeypatch.delattr(builder, "is_dynamic_source")+ model = QwenImage21Transformer2DModel()+ assert not dt.supported()+ assert not dt.install(model)+ assert dt.fingerprint(model, None) is None+ model(torch.zeros(1))+ assert model.seen == _cfg().dynamic_sourcesdiff --git a/studio/backend/tests/test_diffusion_speed.py b/studio/backend/tests/test_diffusion_speed.pyindex 3e3b074c4ed..ffacf8beb17 100644--- a/studio/backend/tests/test_diffusion_speed.py+++ b/studio/backend/tests/test_diffusion_speed.py@@ -2007,6 +2007,25 @@ def test_auto_dynamic_active_follows_the_torchao_marker():assert isinstance(ds_mod.dynamo_graph_count(), int)+def test_automatic_dynamic_compile_arms_the_prompt_length_allowlist(monkeypatch):+ from core.inference import diffusion_dynamic_text++ armed = []+ monkeypatch.setattr(+ diffusion_dynamic_text, "install", lambda t, logger = None: armed.append(t) or True+ )+ _stub_torch(monkeypatch)+ pipe = _Pipe(with_compile = True, with_fuse = True)+ apply_speed_optims(pipe, _target(), is_gguf = False, family = _family(), speed_mode = SPEED_MAX)+ assert armed == [pipe.transformer]++ armed.clear()+ _stub_torch(monkeypatch)+ pipe = _Pipe(with_compile = True)+ apply_speed_optims(pipe, _target(), is_gguf = False, family = _family(), speed_mode = SPEED_DEFAULT)+ assert armed == []++def test_speed_max_compiles_a_quantised_stream_merging_dit_static(monkeypatch):"""A torchao FLUX block under automatic dynamic hits CantSplit on the first new resolution and drops to eager;max compiles it static instead, and reports its artifacts as per-shape."""