Skip to content

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.

Studio ROCm VAE attention: math SDPA in the VAE's bf16/fp16 dtype, not an fp32 upcast (#17252)

Daniel Han1caab2b08fb9
diff --git a/studio/backend/core/inference/diffusion_vae_attn_chunked.py b/studio/backend/core/inference/diffusion_vae_attn_chunked.py
index 0b6bc7b9034..5dee9e9f0a8 100644
--- a/studio/backend/core/inference/diffusion_vae_attn_chunked.py
+++ b/studio/backend/core/inference/diffusion_vae_attn_chunked.py
@@ -1,16 +1,20 @@
# SPDX-License-Identifier: AGPL-3.0-only
# 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."""
+"""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)."""
from __future__ import annotations
import os
+from contextlib import contextmanager, nullcontext
from typing import Any, Optional
from .rocm_bf16 import is_rocm_torch
VAE_ATTN_CHUNK_ENV = "UNSLOTH_VAE_ATTN_CHUNKED"
VAE_ATTN_CHUNK_MB_ENV = "UNSLOTH_VAE_ATTN_CHUNK_MB"
+VAE_ATTN_HALF_MATH_ENV = "UNSLOTH_VAE_ATTN_HALF_MATH"
_FALSE = ("0", "false", "no", "off")
# fp32 score bytes per chunk; a full matrix at or under this runs unchunked (FLUX.1 1024x1024 is exactly 1 GiB).
DEFAULT_SCORE_BUDGET_MB = 1024
@@ -22,6 +26,39 @@ def chunking_disabled() -> bool:
return os.environ.get(VAE_ATTN_CHUNK_ENV, "").strip().lower() in _FALSE
+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."""
+ 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)
+ try:
+ yield True
+ finally:
+ put(prev)
+
+
+def _half_math_call(q: Any) -> bool:
+ import torch
+ return (
+ getattr(getattr(q, "device", None), "type", None) == "cuda"
+ and q.dtype in (torch.bfloat16, torch.float16)
+ and is_rocm_torch(torch)
+ and half_math_enabled()
+ )
+
+
def score_budget_bytes(default_mb: int = DEFAULT_SCORE_BUDGET_MB) -> int:
raw = os.environ.get(VAE_ATTN_CHUNK_MB_ENV, "").strip()
try:
@@ -127,6 +164,7 @@ def _mode_class() -> Any:
super().__init__()
self.budget = budget
self.chunked = 0
+ self.half = 0
def __torch_function__(
self,
@@ -140,9 +178,14 @@ def _mode_class() -> Any:
call = _plain_call(args, kwargs)
if call is not None:
q, k, v, scale = call
- if _score_bytes(q, k) > self.budget and not fused_sdpa_available(q, k, v):
- self.chunked += 1
- return chunked_sdpa(func, q, k, v, self.budget, scale)
+ if 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)
return func(*args, **kwargs)
return ChunkedVaeAttentionMode
diff --git a/studio/backend/tests/test_diffusion_vae_attn_chunked.py b/studio/backend/tests/test_diffusion_vae_attn_chunked.py
index 4fff83267a0..88413453874 100644
--- a/studio/backend/tests/test_diffusion_vae_attn_chunked.py
+++ b/studio/backend/tests/test_diffusion_vae_attn_chunked.py
@@ -16,8 +16,7 @@ from torch.utils._python_dispatch import TorchDispatchMode # noqa: E402
from core.inference import diffusion_vae_attn_chunked as C # noqa: E402
-# A CUDA build's version tag: Studio reads ROCm from the "+rocm" tag too (AMD SDK / Radeon wheels leave
-# torch.version.hip unset), so a test that fakes NVIDIA clears both.
+# CUDA version tag: Studio also reads ROCm from "+rocm" (AMD wheels leave torch.version.hip unset).
_CUDA_TORCH_VERSION = TorchVersion(str(torch.__version__).split("+")[0] + "+cu130")
@@ -81,7 +80,7 @@ def test_mode_bounds_the_score_tile(rocm):
probe = _LargestTensor()
with probe:
ref = F.scaled_dot_product_attention(q, q, q)
- assert probe.max_bytes >= full # the math kernel materialises every score
+ assert probe.max_bytes >= full
mode = C.chunked_attention_mode(budget)
probe = _LargestTensor()
with mode, probe:
@@ -97,7 +96,6 @@ def test_mode_chunks_keyword_calls(rocm):
ref = F.scaled_dot_product_attention(q, q, q, scale = 0.2)
mode = C.chunked_attention_mode(512 * 512 * 4 // 8)
with mode:
- # the call shape of diffusers' native dispatch_attention_fn
out = F.scaled_dot_product_attention(
query = q,
key = q,
@@ -119,7 +117,7 @@ def test_mode_leaves_fused_small_masked_and_causal_calls_alone(monkeypatch):
real = C.chunked_sdpa
monkeypatch.setattr(C, "chunked_sdpa", lambda *a, **k: calls.append(1) or real(*a, **k))
q = torch.randn(1, 1, 256, 16)
- big = 1024 # bytes: every call here is over budget
+ big = 1024
mask = torch.ones(256, 256, dtype = torch.bool)
with _math():
ref = F.scaled_dot_product_attention(q, q, q)
@@ -297,3 +295,63 @@ def test_speed_layer_installs_on_rocm_and_mps_even_when_off(rocm, monkeypatch):
speed_mode = S.SPEED_OFF,
)
assert not any(getattr(m, C._PATCHED, False) for m in nvidia.modules())
+
+
+_HALF_FLAG = getattr(torch.backends.cuda, "fp16_bf16_reduction_math_sdp_allowed", None)
+
+
[email protected](_HALF_FLAG is None, reason = "torch < 2.5 has no fp32 upcast to skip")
[email protected]("chunk", [False, True])
+def test_half_math_keeps_dtype_scoped_and_close(rocm, monkeypatch, chunk):
+ 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, 1024, 512, generator = g).to(torch.bfloat16) for _ in range(3))
+ ref32 = F.scaled_dot_product_attention(q.float(), k.float(), v.float())
+ before = _HALF_FLAG()
+ with _math():
+ upcast = F.scaled_dot_product_attention(q, k, v)
+ torch.backends.cuda.allow_fp16_bf16_reduction_math_sdp(True)
+ try:
+ want = F.scaled_dot_product_attention(q, k, v)
+ finally:
+ torch.backends.cuda.allow_fp16_bf16_reduction_math_sdp(before)
+ mode = C.chunked_attention_mode(1024 * 1024 * 4 // 4 if chunk else 1 << 40)
+ with mode:
+ out = F.scaled_dot_product_attention(q, k, v)
+ assert _HALF_FLAG() == before
+ assert mode.half == 1 and mode.chunked == int(chunk)
+ if not chunk:
+ assert torch.equal(out, want)
+ assert not torch.equal(out, upcast)
+ torch.testing.assert_close(out.float(), ref32, atol = 2e-2, rtol = 2e-2)
+
+
[email protected](_HALF_FLAG is None, reason = "torch < 2.5")
+def test_half_math_restores_the_flag_on_error():
+ before = _HALF_FLAG()
+ with pytest.raises(RuntimeError):
+ with C.half_reduction_math():
+ assert _HALF_FLAG() is True
+ raise RuntimeError("boom")
+ assert _HALF_FLAG() == before
+
+
+def test_half_math_gates(monkeypatch):
+ cuda_bf16 = types.SimpleNamespace(
+ device = types.SimpleNamespace(type = "cuda"), dtype = torch.bfloat16
+ )
+ cuda_fp32 = types.SimpleNamespace(
+ device = types.SimpleNamespace(type = "cuda"), dtype = torch.float32
+ )
+ cpu_bf16 = types.SimpleNamespace(device = types.SimpleNamespace(type = "cpu"), dtype = torch.bfloat16)
+ monkeypatch.setattr(torch.version, "hip", "7.2.0", raising = False)
+ monkeypatch.delenv(C.VAE_ATTN_HALF_MATH_ENV, raising = False)
+ assert C._half_math_call(cuda_bf16)
+ assert not C._half_math_call(cuda_fp32)
+ assert not C._half_math_call(cpu_bf16)
+ monkeypatch.setenv(C.VAE_ATTN_HALF_MATH_ENV, "0")
+ assert not C._half_math_call(cuda_bf16)
+ monkeypatch.delenv(C.VAE_ATTN_HALF_MATH_ENV)
+ monkeypatch.setattr(torch.version, "hip", None, raising = False)
+ monkeypatch.setattr(torch, "__version__", _CUDA_TORCH_VERSION)
+ assert not C._half_math_call(cuda_bf16)