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 diffusion: faster returning first render and first clip (reuse tuned reductions, warm video compile keys) (#16981)
Daniel Han06766f7914e6
diff --git a/studio/backend/core/inference/diffusion_aot_cache.py b/studio/backend/core/inference/diffusion_aot_cache.pyindex 2e61e607ac8..efd31727f10 100644--- a/studio/backend/core/inference/diffusion_aot_cache.py+++ b/studio/backend/core/inference/diffusion_aot_cache.py@@ -7,7 +7,9 @@ priority order is keyed into the cache. UNSLOTH_DIFFUSION_SDPA_AOT_CACHE=0 disabfrom __future__ import annotations+import hashlibimport os+import threadingfrom typing import Anyfrom . import diffusion_compile_config as compile_config@@ -124,3 +126,91 @@ def pin_triton_libdevice(logger: Any = None) -> Any:"diffusion.aot_cache: libdevice not pinned (%s: %s)", type(exc).__name__, exc)return None+++# Compile workers save ``.best_config`` under torch's default ``cache_key_tag``; this process carries Unsloth's tags,+# so every returning start missed and re-benchmarked its reductions (SDXL L4: ~40 kernels, 9.5 s). The kernel source+# hash is already in the key. UNSLOTH_DIFFUSION_AUTOTUNE_KEY_PIN=0 disables it.+_AUTOTUNE_KEY_ENV = "UNSLOTH_DIFFUSION_AUTOTUNE_KEY_PIN"+_TORCH_TAG_ENV = "TORCH_COMPILE_CACHE_KEY_TAG"+_AUTOTUNE_KEY_LOCK = threading.Lock()+++def autotune_key_pin_enabled() -> bool:+ raw = (os.environ.get(_AUTOTUNE_KEY_ENV) or "").strip().lower()+ return raw not in ("0", "false", "no", "off")+++def worker_cache_key_tag() -> str:+ """A fresh compile worker's ``cache_key_tag``: torch's env default."""+ return os.environ.get(_TORCH_TAG_ENV, "")+++def _autotune_key(filename: str, tag: str) -> str:+ """torch's ``AutotuneCache._prepare_key`` formula."""+ return hashlib.sha256(f"{os.path.basename(filename)}:{tag}".encode("utf-8")).hexdigest()+++def _workers_get_parent_tag() -> bool:+ """True when torch passes its ``cache_key_tag`` to the workers (none up to 2.14): pinning would split them."""+ try:+ import importlib.util+ for name in (+ "torch._inductor.async_compile",+ "torch._inductor.runtime.compile_tasks",+ "torch._inductor.compile_worker.subproc_pool",+ ):+ spec = importlib.util.find_spec(name)+ origin = getattr(spec, "origin", None) if spec is not None else None+ if origin and os.path.isfile(origin):+ with open(origin, encoding = "utf-8") as fh:+ if "cache_key_tag" in fh.read():+ return True+ except Exception: # noqa: BLE001+ return False+ return False+++def pin_autotune_key(logger: Any = None) -> bool:+ """Key this process's autotune lookups as the workers key their saves (idempotent, process-wide). Never raises."""+ if not autotune_key_pin_enabled():+ return False+ try:+ import torch.compiler.config as cconfig+ from torch._inductor.runtime import autotune_cache++ cls = getattr(autotune_cache, "AutotuneCache", None)+ raw = getattr(cls, "__dict__", {}).get("_prepare_key")+ if not isinstance(raw, staticmethod):+ return False+ with _AUTOTUNE_KEY_LOCK:+ if getattr(raw.__func__, "_unsloth_worker_tag", False):+ return True+ stock = raw.__func__+ tag = getattr(cconfig, "cache_key_tag", None)+ probe = os.path.join("probe", "cunslothprobe.py")+ if not isinstance(tag, str) or stock(probe) != _autotune_key(probe, tag):+ return False+ if _workers_get_parent_tag():+ return False++ def _prepare_key(filename: str) -> str:+ return _autotune_key(filename, worker_cache_key_tag())++ _prepare_key._unsloth_worker_tag = True+ _prepare_key.__wrapped__ = stock+ cls._prepare_key = staticmethod(_prepare_key)+ if logger is not None:+ logger.info(+ "diffusion.aot_cache: autotune results keyed as the compile workers key them "+ "(tag %r, this process %r)",+ worker_cache_key_tag(),+ tag,+ )+ return True+ except Exception as exc: # noqa: BLE001 - optimisation only+ if logger is not None:+ logger.debug(+ "diffusion.aot_cache: autotune key not pinned (%s: %s)", type(exc).__name__, exc+ )+ return Falsediff --git a/studio/backend/core/inference/diffusion_compile_cache.py b/studio/backend/core/inference/diffusion_compile_cache.pyindex 4c4a912797d..baacc49d799 100644--- a/studio/backend/core/inference/diffusion_compile_cache.py+++ b/studio/backend/core/inference/diffusion_compile_cache.py@@ -593,6 +593,11 @@ def begin(os.environ["TORCHINDUCTOR_CACHE_DIR"] = inductor_direxcept Exception as exc: # noqa: BLE001_warn(logger, f"could not set TORCHINDUCTOR_CACHE_DIR: {exc}")+ try:+ from .diffusion_aot_cache import pin_autotune_key+ pin_autotune_key(logger)+ except Exception as exc: # noqa: BLE001 - optimisation only+ _warn(logger, f"compile-cache: autotune key not pinned: {exc}")# The manifest is the commit point and only names a fully written bundle.published = _read_manifest(ctx.manifest_path)diff --git a/studio/backend/core/inference/diffusion_speed.py b/studio/backend/core/inference/diffusion_speed.pyindex 2da47de952a..4ed08924c40 100644--- a/studio/backend/core/inference/diffusion_speed.py+++ b/studio/backend/core/inference/diffusion_speed.py@@ -1202,6 +1202,7 @@ def _compile_repeated_blocks(try:from . import diffusion_aot_cachediffusion_aot_cache.install(logger)+ diffusion_aot_cache.pin_autotune_key(logger)except Exception as exc: # noqa: BLE001 - optimisation only_warn(logger, "sdpa aot cache", exc)if unet is not None:diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex 7fa2a2c39cf..a4b73440e8b 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -1263,6 +1263,39 @@ def _settle_bg_compile(bg: Any, *, i2v: bool) -> None:# Shared with the image backend's first compiled render._float_seed_dits = diffusion_bg_compile.float_seed_dits+_COMPILE_PREWARM_LOCK = threading.Lock()+_COMPILE_PREWARM_STARTED = False+++def _start_compile_prewarm(logger: Any = None) -> bool:+ """Once per process, on a side thread: inductor's compile workers, Triton's and inductor's keys (1.5 s of Triton+ install hashing landed in a returning LTX-2.5 first clip on an L4). Never raises; False when already started."""+ global _COMPILE_PREWARM_STARTED+ if not diffusion_bg_compile.prewarm_enabled():+ return False+ with _COMPILE_PREWARM_LOCK:+ if _COMPILE_PREWARM_STARTED:+ return False+ _COMPILE_PREWARM_STARTED = True++ def run() -> None:+ for warm in (+ diffusion_bg_compile.warm_compile_pool,+ diffusion_bg_compile.warm_triton_key,+ diffusion_bg_compile.warm_inductor_key,+ ):+ try:+ warm(logger)+ except Exception: # noqa: BLE001 - the first compile does it inline as before+ pass++ try:+ threading.Thread(target = run, name = "unsloth-video-compile-prewarm", daemon = True).start()+ except Exception: # noqa: BLE001+ return False+ return True++_seed_before_first_forward = diffusion_bg_compile.seed_before_first_forward@@ -10517,6 +10550,9 @@ class VideoBackend:speed_optims += ("hv15_vae_vector_mask",)if wan_fused_engaged:speed_optims += ("wan_fused_adaln",)+ if "compiled" in speed_optims and getattr(target, "device", None) == "cuda":+ # The first clip compiles inline: start the workers and hash the keys while the load finishes.+ _start_compile_prewarm(logger)with self._generate_lock:# A cancelled load must not place weights on a GPU the arbiter may have reassigned.if _load_token is not None and _load_token != self._load_token:diff --git a/studio/backend/tests/test_diffusion_autotune_key_pin.py b/studio/backend/tests/test_diffusion_autotune_key_pin.pynew file mode 100644index 00000000000..01321b5b828--- /dev/null+++ b/studio/backend/tests/test_diffusion_autotune_key_pin.py@@ -0,0 +1,159 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The parent looks up a kernel's tuned config under the key a fresh compile worker saved it with."""++from __future__ import annotations++import ast+import json+import os+import subprocess+import sys+from pathlib import Path++import pytest++torch = pytest.importorskip("torch")+autotune_cache = pytest.importorskip("torch._inductor.runtime.autotune_cache")++import torch.compiler.config as cconfig # noqa: E402++from core.inference import diffusion_aot_cache as aot # noqa: E402++BACKEND = Path(__file__).resolve().parents[1]+PARENT_TAG = "unsloth/rope_embedding.py:0123456789abcdef"+_WORKER = """+import json, sys+from torch._inductor.runtime.autotune_cache import AutotuneCache+cache = AutotuneCache.create({}, sys.argv[1], "h")+print(json.dumps(cache.local_cache[1]))+"""++if not hasattr(autotune_cache.AutotuneCache, "_prepare_key"):+ pytest.skip(+ reason = "this torch has no AutotuneCache._prepare_key: pin_autotune_key returns False, nothing to pin",+ allow_module_level = True,+ )++[email protected](autouse = True)+def _restore(monkeypatch):+ raw = autotune_cache.AutotuneCache.__dict__["_prepare_key"]+ if getattr(+ raw.__func__, "_unsloth_worker_tag", False+ ): # pinned by an earlier test in this process+ autotune_cache.AutotuneCache._prepare_key = staticmethod(raw.__func__.__wrapped__)+ tag = cconfig.cache_key_tag+ monkeypatch.delenv("TORCH_COMPILE_CACHE_KEY_TAG", raising = False)+ monkeypatch.delenv("UNSLOTH_DIFFUSION_AUTOTUNE_KEY_PIN", raising = False)+ yield+ autotune_cache.AutotuneCache._prepare_key = raw+ cconfig.cache_key_tag = tag+++def _kernel(tmp_path: Path) -> str:+ path = tmp_path / "ab" / "cabcdefghijklmnop.py"+ path.parent.mkdir(parents = True, exist_ok = True)+ path.write_text("# kernel\n")+ return str(path)+++def _parent_path(filename: str) -> str:+ return autotune_cache.AutotuneCache.create({}, filename, "h").local_cache[1]+++def _worker_path(filename: str, env_tag = None) -> str:+ """What a compile worker computes: a fresh interpreter, torch's default tag."""+ env = {k: v for k, v in os.environ.items() if k != "TORCH_COMPILE_CACHE_KEY_TAG"}+ if env_tag is not None:+ env["TORCH_COMPILE_CACHE_KEY_TAG"] = env_tag+ out = subprocess.run(+ [sys.executable, "-c", _WORKER, filename],+ capture_output = True,+ text = True,+ env = env,+ check = True,+ timeout = 300,+ )+ return json.loads(out.stdout.strip().splitlines()[-1])+++def test_tagged_parent_reads_what_the_worker_saved(tmp_path):+ kernel = _kernel(tmp_path)+ worker = _worker_path(kernel)+ cconfig.cache_key_tag = PARENT_TAG+ assert _parent_path(kernel) != worker # the defect: every returning start missed+ assert aot.pin_autotune_key() is True+ assert _parent_path(kernel) == worker+ # The parent's own tag is untouched: FX graph cache keys still carry it.+ assert cconfig.cache_key_tag == PARENT_TAG+++def test_untagged_parent_key_unchanged(tmp_path):+ kernel = _kernel(tmp_path)+ before = _parent_path(kernel)+ assert aot.pin_autotune_key() is True+ assert _parent_path(kernel) == before == _worker_path(kernel)+++def test_env_tag_is_the_workers_tag(tmp_path, monkeypatch):+ kernel = _kernel(tmp_path)+ monkeypatch.setenv("TORCH_COMPILE_CACHE_KEY_TAG", "site")+ worker = _worker_path(kernel, env_tag = "site")+ cconfig.cache_key_tag = "site," + PARENT_TAG+ assert aot.pin_autotune_key() is True+ assert _parent_path(kernel) == worker+++def test_idempotent(tmp_path):+ assert aot.pin_autotune_key() is True+ first = autotune_cache.AutotuneCache.__dict__["_prepare_key"]+ assert aot.pin_autotune_key() is True+ assert autotune_cache.AutotuneCache.__dict__["_prepare_key"] is first+++def test_kill_switch(tmp_path, monkeypatch):+ monkeypatch.setenv("UNSLOTH_DIFFUSION_AUTOTUNE_KEY_PIN", "0")+ raw = autotune_cache.AutotuneCache.__dict__["_prepare_key"]+ assert aot.pin_autotune_key() is False+ assert autotune_cache.AutotuneCache.__dict__["_prepare_key"] is raw+++def test_missing_hook_is_a_no_op(monkeypatch):+ monkeypatch.delattr(autotune_cache.AutotuneCache, "_prepare_key")+ assert aot.pin_autotune_key() is False+++def test_unknown_key_formula_is_left_alone(monkeypatch):+ other = staticmethod(lambda filename: "not-the-known-formula")+ monkeypatch.setattr(autotune_cache.AutotuneCache, "_prepare_key", other)+ assert aot.pin_autotune_key() is False+ assert autotune_cache.AutotuneCache.__dict__["_prepare_key"] is other+++def test_torch_that_hands_workers_its_tag_is_left_alone(monkeypatch):+ raw = autotune_cache.AutotuneCache.__dict__["_prepare_key"]+ monkeypatch.setattr(aot, "_workers_get_parent_tag", lambda: True)+ assert aot.pin_autotune_key() is False+ assert autotune_cache.AutotuneCache.__dict__["_prepare_key"] is raw+++def _calls(path: Path, func: str) -> set:+ tree = ast.parse(path.read_text(encoding = "utf-8"))+ for node in ast.walk(tree):+ if isinstance(node, ast.FunctionDef) and node.name == func:+ return {+ getattr(c.func, "attr", getattr(c.func, "id", None))+ for c in ast.walk(node)+ if isinstance(c, ast.Call)+ }+ raise AssertionError(func)+++def test_wired_into_both_compile_entry_points():+ inference = BACKEND / "core" / "inference"+ assert "pin_autotune_key" in _calls(+ inference / "diffusion_speed.py", "_compile_repeated_blocks"+ )+ assert "pin_autotune_key" in _calls(inference / "diffusion_compile_cache.py", "begin")diff --git a/studio/backend/tests/test_video_compile_prewarm.py b/studio/backend/tests/test_video_compile_prewarm.pynew file mode 100644index 00000000000..eaa677252f1--- /dev/null+++ b/studio/backend/tests/test_video_compile_prewarm.py@@ -0,0 +1,71 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A compiled video load warms the compile workers and keys on a side thread, once per process. CPU only."""++from __future__ import annotations++import ast+import threading+from pathlib import Path++import pytest++from core.inference import diffusion_bg_compile as bg+from core.inference import video++VIDEO = Path(__file__).resolve().parents[1] / "core" / "inference" / "video.py"+++def calls(monkeypatch):+ seen: list = []+ done = threading.Event()++ def make(name, fail = False):+ def warm(logger = None):+ seen.append((name, threading.current_thread().name))+ if name == "inductor_key":+ done.set()+ if fail:+ raise RuntimeError("boom")+ return True++ return warm++ monkeypatch.setattr(video, "_COMPILE_PREWARM_STARTED", False)+ monkeypatch.delenv(bg.PREWARM_ENV, raising = False)+ monkeypatch.setattr(bg, "warm_compile_pool", make("pool", fail = True))+ monkeypatch.setattr(bg, "warm_triton_key", make("triton_key"))+ monkeypatch.setattr(bg, "warm_inductor_key", make("inductor_key"))+ return seen, done+++def test_warms_pool_and_keys_off_the_caller_once(calls):+ seen, done = calls+ assert video._start_compile_prewarm() is True+ assert done.wait(10)+ # A failing step does not stop the next one.+ assert [n for n, _ in seen] == ["pool", "triton_key", "inductor_key"]+ assert all(t == "unsloth-video-compile-prewarm" for _, t in seen)+ assert video._start_compile_prewarm() is False+ assert len(seen) == 3+++def test_kill_switch(calls, monkeypatch):+ seen, _ = calls+ monkeypatch.setenv(bg.PREWARM_ENV, "0")+ assert video._start_compile_prewarm() is False+ assert seen == []+++def test_load_starts_it_only_for_a_compiled_cuda_load():+ tree = ast.parse(VIDEO.read_text(encoding = "utf-8"))+ gates = []+ for node in ast.walk(tree):+ if isinstance(node, ast.If) and any(+ isinstance(c, ast.Call) and getattr(c.func, "id", None) == "_start_compile_prewarm"+ for c in ast.walk(node)+ ):+ gates.append(ast.unparse(node.test))+ assert gates == ["'compiled' in speed_optims and getattr(target, 'device', None) == 'cuda'"]