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: warm the deferred SDXL speed profile off the render thread (#16360)
Daniel Han4c7c10e21cdd
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 9ae98e92264..e9567ff0ad9 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -13118,6 +13118,7 @@ class DiffusionBackend:def _engage_deferred_profile(self, state: _LoadState) -> None:"""Runs the deferred speed profile at the 3rd generation under _generate_lock; the flag clears first so it never retries."""object.__setattr__(state, "speed_deferred", False)+ bg_compile.wait_prewarm()from .diffusion_qwenimage21_eager import demotedemote(getattr(state, "pipe", None))@@ -13452,8 +13453,8 @@ class DiffusionBackend:and not aux_passand str(getattr(state, "device", "")).startswith("cuda")):- # 2nd image: warm inductor's workers so the deferred compile does not wait on them.- bg_compile.warm_compile_pool(logger)+ # 2nd image: warm inductor's workers and Triton's key off this render's thread.+ bg_compile.start_deferred_prewarm(logger)if (state.speed_deferredand state.generation_count >= 2diff --git a/studio/backend/core/inference/diffusion_bg_compile.py b/studio/backend/core/inference/diffusion_bg_compile.pyindex 9b094e96abe..6686181e48f 100644--- a/studio/backend/core/inference/diffusion_bg_compile.py+++ b/studio/backend/core/inference/diffusion_bg_compile.py@@ -99,6 +99,103 @@ def warm_compile_pool(logger: Any = None) -> bool:return True+PREWARM_ENV = "UNSLOTH_DIFFUSION_DEFERRED_PREWARM"+_PREWARM_LOCK = threading.Lock()+_PREWARM_THREAD: Optional[threading.Thread] = None+++def prewarm_enabled() -> bool:+ raw = (os.environ.get(PREWARM_ENV) or "").strip().lower()+ return raw not in ("0", "false", "no", "off")+++def _triton_key_fn() -> Optional[Callable[[], Any]]:+ try:+ from triton.runtime.cache import triton_key+ except Exception: # noqa: BLE001 - another Triton layout+ try:+ from triton.compiler.compiler import triton_key+ except Exception: # noqa: BLE001 - no Triton+ return None+ return triton_key if callable(triton_key) else None+++def warm_triton_key(logger: Any = None) -> bool:+ """Fill Triton's per-process ``triton_key()`` cache (1-1.5 s, paid by the first JIT even on a warm disk cache)."""+ fn = _triton_key_fn()+ if fn is None:+ return False+ t0 = time.perf_counter()+ try:+ fn()+ except Exception as exc: # noqa: BLE001 - the first JIT call computes it as before+ if logger is not None:+ logger.debug("diffusion.bg_compile: triton key warm-up skipped: %s", exc)+ return False+ if logger is not None:+ logger.info("diffusion.bg_compile: triton key ready in %.2f s", time.perf_counter() - t0)+ return True+++def warm_engage_imports(logger: Any = None) -> int:+ """Model-free first-use work of the engagement; returns how many steps ran."""++ def _zoo_patch_utils() -> None:+ # Import only: diffusion_patch_backend._helpers() keeps its own retry (import unsloth) for the 3rd image.+ import unsloth_zoo.temporary_patches.utils # noqa: F401++ def _vae_kernels() -> None:+ from . import diffusion_vae_fused+ diffusion_vae_fused._kernels()++ done = 0+ steps: list[Callable[[], Any]] = [_zoo_patch_utils, _vae_kernels]+ for step in steps:+ try:+ step()+ done += 1+ except Exception as exc: # noqa: BLE001 - the 3rd image does this inline as before+ if logger is not None:+ logger.debug("diffusion.bg_compile: engage warm-up step skipped: %s", exc)+ return done+++def start_deferred_prewarm(logger: Any = None) -> bool:+ """Run the warm-ups on a side thread so none of it lands inside a render; ``PREWARM_ENV=0`` warms the pool inline."""+ global _PREWARM_THREAD+ if not prewarm_enabled():+ return warm_compile_pool(logger)+ with _PREWARM_LOCK:+ if _PREWARM_THREAD is not None:+ return False++ def run() -> None:+ t0 = time.perf_counter()+ warm_compile_pool(logger)+ warm_triton_key(logger)+ n = warm_engage_imports(logger)+ if logger is not None:+ logger.info(+ "diffusion.bg_compile: deferred profile warm-up done in %.2f s (%d import steps)",+ time.perf_counter() - t0,+ n,+ )++ _PREWARM_THREAD = threading.Thread(target = run, name = "unsloth-deferred-prewarm", daemon = True)+ _PREWARM_THREAD.start()+ return True+++def wait_prewarm(timeout: Optional[float] = 60.0) -> bool:+ """Join the side warm-up before the profile engages (no second pool start, no second key hash)."""+ with _PREWARM_LOCK:+ thread = _PREWARM_THREAD+ if thread is None or thread is threading.current_thread():+ return True+ thread.join(timeout)+ return not thread.is_alive()++def slice_seconds(eager_render_s: Optional[float]) -> float:"""Compile seconds a render lets run before it pauses the compile: ``SLICE_ENV`` when set, else the load'sfastest eager render (0 when none was timed), clamped to [0, 30]."""diff --git a/studio/backend/tests/test_diffusion_deferred_prewarm.py b/studio/backend/tests/test_diffusion_deferred_prewarm.pynew file mode 100644index 00000000000..3318b5b2775--- /dev/null+++ b/studio/backend/tests/test_diffusion_deferred_prewarm.py@@ -0,0 +1,227 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Deferred speed profile warm-up runs on a side thread off the render. CPU only."""++from __future__ import annotations++import ast+import logging+import sys+import threading+import types+from pathlib import Path++import pytest++from core.inference import diffusion_bg_compile as bg++LOG = logging.getLogger("test_diffusion_deferred_prewarm")+DIFFUSION = Path(__file__).resolve().parents[1] / "core" / "inference" / "diffusion.py"+++def fresh(monkeypatch):+ monkeypatch.setattr(bg, "_PREWARM_THREAD", None)+ monkeypatch.delenv(bg.PREWARM_ENV, raising = False)+ yield+ thread = bg._PREWARM_THREAD+ if thread is not None:+ thread.join(10)+++def recorder(monkeypatch, fresh):+ calls: list = []+ release = threading.Event()++ def pool(logger = None):+ calls.append(("pool", threading.current_thread().name))+ return True++ def key(logger = None):+ # Blocks until the test lets it go: proves the caller does not wait for the warm-up.+ release.wait(30)+ calls.append(("key", threading.current_thread().name))+ return True++ def imports(logger = None):+ calls.append(("imports", threading.current_thread().name))+ return 3++ monkeypatch.setattr(bg, "warm_compile_pool", pool)+ monkeypatch.setattr(bg, "warm_triton_key", key)+ monkeypatch.setattr(bg, "warm_engage_imports", imports)+ return calls, release+++def test_prewarm_runs_off_the_calling_thread_and_never_blocks_it(recorder):+ calls, release = recorder+ assert bg.start_deferred_prewarm(LOG) is True+ assert not release.is_set()+ assert ("key", "unsloth-deferred-prewarm") not in calls+ release.set()+ assert bg.wait_prewarm(10) is True+ assert [c[0] for c in calls] == ["pool", "key", "imports"]+ assert {c[1] for c in calls} == {"unsloth-deferred-prewarm"}+ assert threading.current_thread().name not in {c[1] for c in calls}+++def test_prewarm_starts_once(recorder):+ calls, release = recorder+ release.set()+ assert bg.start_deferred_prewarm(LOG) is True+ assert bg.start_deferred_prewarm(LOG) is False+ assert bg.wait_prewarm(10) is True+ assert [c[0] for c in calls] == ["pool", "key", "imports"]++[email protected]("raw", ["0", "off", "false", "no"])+def test_kill_switch_warms_the_pool_inline_as_before(monkeypatch, recorder, raw):+ calls, release = recorder+ release.set()+ monkeypatch.setenv(bg.PREWARM_ENV, raw)+ assert bg.start_deferred_prewarm(LOG) is True+ assert bg._PREWARM_THREAD is None+ assert calls == [("pool", threading.current_thread().name)]+++def test_wait_prewarm_without_a_thread_or_from_inside_it(fresh, monkeypatch):+ assert bg.wait_prewarm(0.1) is True+ seen: list = []+ monkeypatch.setattr(+ bg, "warm_compile_pool", lambda logger = None: seen.append(bg.wait_prewarm(5))+ )+ monkeypatch.setattr(bg, "warm_triton_key", lambda logger = None: True)+ monkeypatch.setattr(bg, "warm_engage_imports", lambda logger = None: 0)+ assert bg.start_deferred_prewarm(LOG) is True+ assert bg.wait_prewarm(10) is True+ # Joining itself would deadlock: the thread's own call returns at once.+ assert seen == [True]+++def test_wait_prewarm_reports_a_thread_still_running(recorder):+ calls, release = recorder+ assert bg.start_deferred_prewarm(LOG) is True+ assert bg.wait_prewarm(0.05) is False+ release.set()+ assert bg.wait_prewarm(10) is True+++def _fake_triton(+ monkeypatch,+ *,+ runtime_key = None,+ compiler_key = None,+):+ triton = types.ModuleType("triton")+ runtime = types.ModuleType("triton.runtime")+ cache = types.ModuleType("triton.runtime.cache")+ compiler = types.ModuleType("triton.compiler")+ compiler_mod = types.ModuleType("triton.compiler.compiler")+ if runtime_key is not None:+ cache.triton_key = runtime_key+ if compiler_key is not None:+ compiler_mod.triton_key = compiler_key+ triton.runtime, runtime.cache = runtime, cache+ triton.compiler, compiler.compiler = compiler, compiler_mod+ for name, module in {+ "triton": triton,+ "triton.runtime": runtime,+ "triton.runtime.cache": cache,+ "triton.compiler": compiler,+ "triton.compiler.compiler": compiler_mod,+ }.items():+ monkeypatch.setitem(sys.modules, name, module)+++def test_warm_triton_key_fills_the_key(monkeypatch):+ calls: list = []+ _fake_triton(monkeypatch, runtime_key = lambda: calls.append("runtime") or "k")+ assert bg.warm_triton_key(LOG) is True+ assert calls == ["runtime"]+++def test_warm_triton_key_falls_back_to_the_compiler_module(monkeypatch):+ calls: list = []+ _fake_triton(monkeypatch, compiler_key = lambda: calls.append("compiler") or "k")+ assert bg.warm_triton_key(LOG) is True+ assert calls == ["compiler"]+++def test_warm_triton_key_never_raises(monkeypatch):+ def boom():+ raise OSError("libtriton unreadable")++ _fake_triton(monkeypatch, runtime_key = boom)+ assert bg.warm_triton_key(LOG) is False+ _fake_triton(monkeypatch)+ assert bg.warm_triton_key(LOG) is False+++def test_warm_triton_key_real_triton_is_cached():+ triton_cache = pytest.importorskip("triton.runtime.cache")+ key = getattr(triton_cache, "triton_key", None)+ if key is None or not hasattr(key, "cache_info"):+ pytest.skip("this Triton has no cached triton_key")+ assert bg.warm_triton_key(LOG) is True+ assert key.cache_info().currsize == 1+++def test_engage_imports_keep_going_and_leave_the_patch_helpers_alone(monkeypatch):+ from core.inference import diffusion_patch_backend++ from core.inference import diffusion_vae_fused++ monkeypatch.setattr(diffusion_patch_backend, "_HELPERS", None)+ # None in sys.modules makes the import raise ImportError: the step fails, the next one still runs+ monkeypatch.setitem(sys.modules, "unsloth_zoo.temporary_patches.utils", None)+ kernels: list = []+ monkeypatch.setattr(diffusion_vae_fused, "_kernels", lambda: kernels.append(1))+ assert bg.warm_engage_imports(LOG) == 1+ assert kernels == [1]+ # The 3rd image still runs the helpers' own resolution (and its import-unsloth retry).+ assert diffusion_patch_backend._HELPERS is None+++def _function(tree: ast.Module, cls: str, name: str) -> ast.FunctionDef:+ for node in ast.walk(tree):+ if isinstance(node, ast.ClassDef) and node.name == cls:+ for item in node.body:+ if isinstance(item, ast.FunctionDef) and item.name == name:+ return item+ raise AssertionError(f"{cls}.{name} not found")+++def _bg_calls(node: ast.AST) -> list:+ out = []+ for sub in ast.walk(node):+ if (+ isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Attribute)+ and isinstance(sub.func.value, ast.Name)+ and sub.func.value.id == "bg_compile"+ ):+ out.append((sub.func.attr, sub.lineno))+ return out+++def test_second_image_starts_the_side_warm_up():+ tree = ast.parse(DIFFUSION.read_text(encoding = "utf-8"))+ names = [n for n, _ in _bg_calls(_function(tree, "DiffusionBackend", "generate"))]+ assert "start_deferred_prewarm" in names+ assert "warm_compile_pool" not in names+++def test_engagement_joins_the_warm_up_before_patching():+ tree = ast.parse(DIFFUSION.read_text(encoding = "utf-8"))+ fn = _function(tree, "DiffusionBackend", "_engage_deferred_profile")+ waits = [line for n, line in _bg_calls(fn) if n == "wait_prewarm"]+ patches = [+ sub.lineno+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Attribute)+ and sub.func.attr == "install_patches"+ ]+ assert waits and patches and min(waits) < min(patches)