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: latch failed fused fp16 RoPE and AdaLN launches for the load (#14583)
Daniel Handb6e30944624
diff --git a/studio/backend/core/inference/diffusion_flux2_rope.py b/studio/backend/core/inference/diffusion_flux2_rope.pyindex 8f5f73bd904..7e5a5d6536b 100644--- a/studio/backend/core/inference/diffusion_flux2_rope.py+++ b/studio/backend/core/inference/diffusion_flux2_rope.py@@ -11,6 +11,7 @@ Kill switch: ``UNSLOTH_DIFFUSION_FLUX2_FUSED_ROPE=0``.from __future__ import annotationsimport functools+import loggingimport osimport threadingfrom typing import Any, Callable, Optional@@ -22,6 +23,8 @@ _LOCK = threading.Lock()_STOCK: dict = {}# Survives uninstall so a forward that looked up the patch just before teardown still reaches stock._ORIGINAL: list = [None]+# Set by the first failed launch (JIT / driver / PTX): the rest of the load runs stock, not one failing JIT per call.+_FAILED = [False]def disabled() -> bool:@@ -162,6 +165,17 @@ def _eligible(return True+def _log_failed(exc: BaseException) -> None:+ try:+ logging.getLogger(__name__).warning(+ "diffusion.flux2_rope: fused fp16 RoPE launch failed (%s: %s); stock RoPE for the rest of this load",+ type(exc).__name__,+ exc,+ )+ except Exception: # noqa: BLE001+ pass++def _fused_apply_rotary_emb(x,freqs_cis,@@ -181,12 +195,13 @@ def _fused_apply_rotary_emb(use_real_unbind_dim = use_real_unbind_dim,sequence_dim = sequence_dim,)- launch = _kernel()+ launch = None if _FAILED[0] else _kernel()if launch is not None and _eligible(x, freqs_cis, use_real, use_real_unbind_dim, sequence_dim):try:return launch(x, freqs_cis[0], freqs_cis[1])- except Exception: # noqa: BLE001 -- never fail a render over the fast path- pass+ except Exception as exc: # noqa: BLE001 -- never fail a render over the fast path+ _FAILED[0] = True+ _log_failed(exc)return stock(x,freqs_cis,@@ -208,6 +223,7 @@ def install(import importlibwith _LOCK:+ _FAILED[0] = Falseif _ATTR in _STOCK:return Truetry:@@ -245,6 +261,7 @@ def install_for_pipe(def uninstall() -> None:import syswith _LOCK:+ _FAILED[0] = Falsestock = _STOCK.pop(_ATTR, None)if stock is None:returndiff --git a/studio/backend/core/inference/diffusion_rocm_fused.py b/studio/backend/core/inference/diffusion_rocm_fused.pyindex 92788912bb2..8029575547b 100644--- a/studio/backend/core/inference/diffusion_rocm_fused.py+++ b/studio/backend/core/inference/diffusion_rocm_fused.py@@ -13,6 +13,7 @@ speedup and not bit-identical).from __future__ import annotationsimport functools+import loggingimport osimport sysimport threading@@ -36,6 +37,21 @@ _ADALN_ORIGINAL: dict = {}COUNTS = {"rope_fused": 0, "rope_stock": 0, "adaln_fused": 0, "adaln_stock": 0}# Set by the first failed RoPE launch (JIT / driver / PTX): the rest of the load runs stock, not one failing JIT per call._ROPE_FAILED = [False]+# Same latch for the fused AdaLN modulation launch.+_ADALN_FAILED = [False]+++def _log_failed(path: str, exc: BaseException) -> None:+ try:+ logging.getLogger(__name__).warning(+ "diffusion.rocm_fused: fused %s launch failed (%s: %s); stock %s for the rest of this load",+ path,+ type(exc).__name__,+ exc,+ path,+ )+ except Exception: # noqa: BLE001+ passdef _mode(env: str) -> str:@@ -102,7 +118,6 @@ def wanted(return _adaln_kernel() is not None-# ----------------------------------------------------------------------------------------------------------------- RoPE@functools.lru_cache(maxsize = 1)def _rope_kernel() -> Optional[Callable]:from .diffusion_flux2_rope import _kernel@@ -162,8 +177,9 @@ def _make_rope(module_name: str) -> Callable:out = launch(x, freqs_cis[0], freqs_cis[1])COUNTS["rope_fused"] += 1return out- except Exception: # noqa: BLE001 -- never fail a render over the fast path+ except Exception as exc: # noqa: BLE001 -- never fail a render over the fast path_ROPE_FAILED[0] = True+ _log_failed("RoPE", exc)COUNTS["rope_stock"] += 1return stock(x,@@ -219,7 +235,6 @@ def uninstall_rope() -> None:setattr(mod, _ROPE_ATTR, stock)-# ----------------------------------------------------------------------------------------------------------------- AdaLN@functools.lru_cache(maxsize = 1)def _adaln_kernel() -> Optional[Callable]:try:@@ -293,12 +308,10 @@ def _plain_layer_norm(norm: Any) -> Optional[float]:return float(norm.eps)-def _fused_modulate(norm: Any, x: Any, scale: Any, shift: Any) -> Optional[Any]:- """``norm(x) * (1 + scale[:, None]) + shift[:, None]`` in one kernel, or None when not eligible."""+def _adaln_eligible(norm: Any, x: Any, scale: Any, shift: Any) -> Optional[float]:+ """The LayerNorm eps when the fused kernel can take this call, else None."""import torch- if torch.compiler.is_compiling():- return Noneeps = _plain_layer_norm(norm)if eps is None or not torch.is_tensor(x) or not x.is_cuda or x.dim() != 3:return None@@ -324,12 +337,26 @@ def _fused_modulate(norm: Any, x: Any, scale: Any, shift: Any) -> Optional[Any]:return Noneif t.stride(1) != 1:return None+ return eps+++def _fused_modulate(norm: Any, x: Any, scale: Any, shift: Any) -> Optional[Any]:+ """``norm(x) * (1 + scale[:, None]) + shift[:, None]`` in one kernel, or None when not eligible."""+ import torch++ if torch.compiler.is_compiling() or _ADALN_FAILED[0]:+ return None+ eps = _adaln_eligible(norm, x, scale, shift)+ if eps is None:+ return Nonelaunch = _adaln_kernel()if launch is None:return Nonetry:return launch(x, scale, shift, eps)- except Exception: # noqa: BLE001 -- never fail a render over the fast path+ except Exception as exc: # noqa: BLE001 -- never fail a render over the fast path+ _ADALN_FAILED[0] = True+ _log_failed("AdaLN", exc)return None@@ -464,6 +491,7 @@ def install_adaln(dtype: Any, device: Any = "cuda") -> int:def uninstall_adaln() -> None:with _LOCK:+ _ADALN_FAILED[0] = Falsefor cls, prev in list(_ADALN_PREV.items()):# Not ours on top (deferred eager patch): keep the entry for the uninstall after that layer's.if cls.__dict__.get("forward") in _FORWARDS.values():@@ -471,7 +499,6 @@ def uninstall_adaln() -> None:del _ADALN_PREV[cls]-# ------------------------------------------------------------------------------------------------------------- lifecycledef install_for_pipe(pipe: Any,dtype: Any,diff --git a/studio/backend/tests/test_diffusion_flux2_rope.py b/studio/backend/tests/test_diffusion_flux2_rope.pyindex 252b243c26b..6bb7a7ffe52 100644--- a/studio/backend/tests/test_diffusion_flux2_rope.py+++ b/studio/backend/tests/test_diffusion_flux2_rope.py@@ -243,3 +243,31 @@ def test_call_after_uninstall_reaches_stock(fake_kernel):x = torch.randn(1, 4, 2, 8)freqs = (torch.ones(4, 8), torch.zeros(4, 8))assert torch.equal(patched(x, freqs, sequence_dim = 1), x)+++def test_a_failed_launch_disables_the_fused_path_for_the_load(monkeypatch):+ calls = []++ def failing_launch(x, cos, sin):+ calls.append(1)+ raise RuntimeError("PTX JIT compilation failed")++ monkeypatch.setattr(fr, "_kernel", lambda: failing_launch)+ monkeypatch.setattr(fr, "_eligible", lambda *a, **k: True)+ monkeypatch.setattr(torch.version, "hip", None, raising = False)+ assert fr.install_for_pipe(_Flux2Like(), torch.float16, "cuda")+ x = torch.randn(1, 6, 2, 8)+ pos = torch.randn(6, 4, dtype = torch.float64)+ freqs = (pos.cos().repeat_interleave(2, -1).float(), pos.sin().repeat_interleave(2, -1).float())+ want = stock_rope(x, freqs, sequence_dim = 1)+ for _ in range(4):+ assert torch.equal(fmod.apply_rotary_emb(x, freqs, sequence_dim = 1), want)+ assert len(calls) == 1+ # The next load re-arms, whether or not the previous one was torn down first.+ assert fr.install_for_pipe(_Flux2Like(), torch.float16, "cuda")+ fmod.apply_rotary_emb(x, freqs, sequence_dim = 1)+ assert len(calls) == 2+ fr.uninstall()+ fr.install_for_pipe(_Flux2Like(), torch.float16, "cuda")+ fmod.apply_rotary_emb(x, freqs, sequence_dim = 1)+ assert len(calls) == 3diff --git a/studio/backend/tests/test_diffusion_rocm_fused.py b/studio/backend/tests/test_diffusion_rocm_fused.pyindex f653c96abf6..92332188bf5 100644--- a/studio/backend/tests/test_diffusion_rocm_fused.py+++ b/studio/backend/tests/test_diffusion_rocm_fused.py@@ -249,7 +249,6 @@ def test_stock_lines_still_present_in_diffusers():).read_text("utf-8")-# ---------------------------------------------------------------------------------------------------------------- GPUdef _freqs(S, D, device):pos = torch.randn(S, D // 2, dtype = torch.float64, device = device) * 50return (pos.cos().repeat_interleave(2, -1).float(), pos.sin().repeat_interleave(2, -1).float())@@ -485,3 +484,32 @@ def test_a_failed_rope_launch_disables_the_fused_path_for_the_load(monkeypatch):rf.install_for_pipe(_PipeLike(), torch.bfloat16, "cuda")fmod.apply_rotary_emb(x, freqs, sequence_dim = 1)assert len(calls) == 2+++def test_a_failed_adaln_launch_disables_the_fused_path_for_the_load(monkeypatch):+ calls = []++ def failing_launch(x, scale, shift, eps):+ calls.append(1)+ raise RuntimeError("PTX JIT compilation failed")++ monkeypatch.setattr(rf, "_adaln_kernel", lambda: failing_launch)+ monkeypatch.setattr(rf, "_rope_kernel", lambda: (lambda x, cos, sin: None))+ monkeypatch.setattr(rf, "_adaln_eligible", lambda norm, x, scale, shift: float(norm.eps))+ monkeypatch.setattr(torch.version, "hip", "7.2.0", raising = False)+ monkeypatch.setenv(rf.FUSED_ADALN_ENV, "1")+ assert rf.install_for_pipe(_PipeLike(), torch.bfloat16, "cuda")["adaln"] == 3+ torch.manual_seed(0)+ norm = nm.AdaLayerNormContinuous(8, 8, elementwise_affine = False, eps = 1e-6)+ x = torch.randn(2, 5, 8)+ cond = torch.randn(2, 8)+ with torch.no_grad():+ want = _STOCK_FWD["AdaLayerNormContinuous"](norm, x, cond)+ for _ in range(4):+ assert torch.equal(norm(x, cond), want)+ assert len(calls) == 1+ rf.uninstall()+ rf.install_for_pipe(_PipeLike(), torch.bfloat16, "cuda")+ with torch.no_grad():+ norm(x, cond)+ assert len(calls) == 2