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: compute ROCm VAE half-math SDPA per call instead of flipping the global flag (#17350)
Daniel Han3d4605c9e01a
diff --git a/studio/backend/core/inference/diffusion_vae_attn_chunked.py b/studio/backend/core/inference/diffusion_vae_attn_chunked.pyindex 5dee9e9f0a8..9243360bd3d 100644--- a/studio/backend/core/inference/diffusion_vae_attn_chunked.py+++ b/studio/backend/core/inference/diffusion_vae_attn_chunked.py@@ -2,13 +2,14 @@# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0"""Query-chunked VAE attention on ROCm/MPS, where no fused SDPA takes head dim 384/512; exact. On ROCm a bf16 / fp16-VAE's math SDPA keeps its own dtype (``allow_fp16_bf16_reduction_math_sdp``, scoped to the call) instead of upcasting-q / k / v and the score matrix to fp32 (UNSLOTH_VAE_ATTN_HALF_MATH=0 keeps the fp32 upcast)."""+VAE's math SDPA keeps its own dtype (what ``allow_fp16_bf16_reduction_math_sdp`` runs, computed per call without that+process-wide flag) instead of upcasting q / k / v and the score matrix to fp32 (UNSLOTH_VAE_ATTN_HALF_MATH=0 keeps the+fp32 upcast)."""from __future__ import annotations+import mathimport os-from contextlib import contextmanager, nullcontextfrom typing import Any, Optionalfrom .rocm_bf16 import is_rocm_torch@@ -30,23 +31,34 @@ def half_math_enabled() -> bool:return os.environ.get(VAE_ATTN_HALF_MATH_ENV, "").strip().lower() not in _FALSE-@contextmanager-def half_reduction_math():- """Math SDPA in the inputs' half dtype for this block (fp32 GEMM accumulation either way), then restore."""+def half_math_sdpa(+ q: Any,+ k: Any,+ v: Any,+ scale: Optional[float] = None,+) -> Any:+ """Math SDPA as with ``allow_fp16_bf16_reduction_math_sdp(True)``, without touching that process-global flag."""import torch- cb = torch.backends.cuda- get = getattr(cb, "fp16_bf16_reduction_math_sdp_allowed", None)- put = getattr(cb, "allow_fp16_bf16_reduction_math_sdp", None)- if get is None or put is None: # torch < 2.5 never upcast- yield False- return- prev = bool(get())- put(True)+ s = 1.0 / math.sqrt(q.shape[-1]) if scale is None else scale+ root = math.sqrt(abs(s))+ attn = torch.matmul(q * (-root if s < 0 else root), k.transpose(-2, -1) * root)+ # torch < 2.5 has no _safe_softmax; its math SDPA used plain softmax+ softmax = getattr(torch.ops.aten, "_safe_softmax", None)+ attn = softmax(attn, -1) if softmax is not None else attn.softmax(-1)+ return torch.matmul(attn, v)+++def _autocast_dtype(device_type: str) -> Any:+ import torchtry:- yield True- finally:- put(prev)+ return (+ torch.get_autocast_dtype(device_type)+ if torch.is_autocast_enabled(device_type)+ else None+ )+ except (AttributeError, TypeError): # torch without per-device autocast queries+ return Nonedef _half_math_call(q: Any) -> bool:@@ -156,6 +168,7 @@ def _plain_call(args: tuple, kwargs: dict) -> Optional[tuple]:def _mode_class() -> Any:+ import torchimport torch.nn.functional as Ffrom torch.overrides import TorchFunctionMode@@ -179,13 +192,19 @@ def _mode_class() -> Any:if call is not None:q, k, v, scale = callif not fused_sdpa_available(q, k, v):- half = _half_math_call(q)- self.half += int(half)- with half_reduction_math() if half else nullcontext():- if _score_bytes(q, k) > self.budget:- self.chunked += 1- return chunked_sdpa(func, q, k, v, self.budget, scale)- return func(*args, **kwargs)+ if _half_math_call(q):+ self.half += 1+ cast = _autocast_dtype(q.device.type)+ if cast is not None:+ q, k, v = (t.to(cast) for t in (q, k, v))+ with torch.autocast(q.device.type, enabled = False):+ if _score_bytes(q, k) > self.budget:+ self.chunked += 1+ return chunked_sdpa(half_math_sdpa, q, k, v, self.budget, scale)+ return half_math_sdpa(q, k, v, scale)+ if _score_bytes(q, k) > self.budget:+ self.chunked += 1+ return chunked_sdpa(func, q, k, v, self.budget, scale)return func(*args, **kwargs)return ChunkedVaeAttentionModediff --git a/studio/backend/tests/test_diffusion_vae_attn_chunked.py b/studio/backend/tests/test_diffusion_vae_attn_chunked.pyindex 88413453874..f2865cd7958 100644--- a/studio/backend/tests/test_diffusion_vae_attn_chunked.py+++ b/studio/backend/tests/test_diffusion_vae_attn_chunked.py@@ -3,6 +3,7 @@"""Query-chunked VAE attention where no fused SDPA takes the head dim; the score tile is bounded."""+import threadingimport typesimport pytest@@ -327,13 +328,95 @@ def test_half_math_keeps_dtype_scoped_and_close(rocm, monkeypatch, chunk):@pytest.mark.skipif(_HALF_FLAG is None, reason = "torch < 2.5")-def test_half_math_restores_the_flag_on_error():[email protected]("scale", [None, 0.3, -0.3])+def test_half_math_sdpa_matches_the_flag(scale):+ g = torch.Generator().manual_seed(1)+ q, k, v = (torch.randn(2, 3, 200, 64, generator = g).to(torch.bfloat16) for _ in range(3))before = _HALF_FLAG()- with pytest.raises(RuntimeError):- with C.half_reduction_math():- assert _HALF_FLAG() is True- raise RuntimeError("boom")+ with _math():+ torch.backends.cuda.allow_fp16_bf16_reduction_math_sdp(True)+ try:+ want = F.scaled_dot_product_attention(q, k, v, scale = scale)+ finally:+ torch.backends.cuda.allow_fp16_bf16_reduction_math_sdp(before)+ assert torch.equal(C.half_math_sdpa(q, k, v, scale), want)+++class _BlockFirstOp(TorchDispatchMode):+ """Parks this thread at its first aten op until released (dispatch modes are per thread)."""++ def __init__(self):+ super().__init__()+ self.inside = threading.Event()+ self.release = threading.Event()++ def __torch_dispatch__(+ self,+ func,+ types_,+ args = (),+ kwargs = None,+ ):+ if not self.inside.is_set():+ self.inside.set()+ assert self.release.wait(10)+ return func(*args, **(kwargs or {}))++[email protected](_HALF_FLAG is None, reason = "torch < 2.5")+def test_half_math_leaves_other_threads_and_the_flag_alone(rocm, monkeypatch):+ monkeypatch.setattr(C, "_half_math_call", lambda q: q.dtype == torch.bfloat16)+ g = torch.Generator().manual_seed(0)+ q, k, v = (torch.randn(1, 1, 64, 64, generator = g).to(torch.bfloat16) for _ in range(3))+ other = torch.randn(1, 1, 32, 64, generator = g).to(torch.bfloat16)++ def unrelated():+ with _math():+ return F.scaled_dot_product_attention(other, other, other)++ before = _HALF_FLAG()+ reference = unrelated()+ modes, blocks, errors = [], [], []++ def vae_call(mode, block):+ try:+ with mode, block:+ F.scaled_dot_product_attention(q, k, v)+ except BaseException as exc: # noqa: BLE001+ errors.append(exc)+ finally:+ block.inside.set()++ threads = []+ try:+ for _ in range(2): # two overlapping VAE calls, as image and video decodes can be+ modes.append(C.chunked_attention_mode(1 << 40))+ blocks.append(_BlockFirstOp())+ threads.append(threading.Thread(target = vae_call, args = (modes[-1], blocks[-1])))+ threads[-1].start()+ assert blocks[-1].inside.wait(10)+ assert _HALF_FLAG() == before+ assert torch.equal(unrelated(), reference)+ finally:+ for block, thread in zip(blocks, threads):+ block.release.set()+ thread.join(10)+ assert not errors and not any(t.is_alive() for t in threads)+ assert [m.half for m in modes] == [1, 1]assert _HALF_FLAG() == before+ assert torch.equal(unrelated(), reference)+++def test_half_math_runs_in_the_autocast_dtype(rocm, monkeypatch):+ monkeypatch.setattr(C, "_half_math_call", lambda q: q.dtype in (torch.bfloat16, torch.float16))+ g = torch.Generator().manual_seed(0)+ q, k, v = (torch.randn(1, 1, 128, 64, generator = g).to(torch.bfloat16) for _ in range(3))+ want = C.half_math_sdpa(q, k, v)+ mode = C.chunked_attention_mode(1 << 40)+ with torch.autocast("cpu", dtype = torch.bfloat16), mode:+ out = F.scaled_dot_product_attention(q, k.float(), v.float())+ assert mode.half == 1 and out.dtype == torch.bfloat16+ assert torch.equal(out, want)def test_half_math_gates(monkeypatch):