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: chunked VAE attention on ROCm when no fused kernel takes head dim 512 (fixes FLUX.1 2048x2048 OOM) (#12702)
Daniel Han86fa7f3f104d
diff --git a/studio/backend/core/inference/diffusion_speed.py b/studio/backend/core/inference/diffusion_speed.pyindex 5a1de2936a2..f5230978fe2 100644--- a/studio/backend/core/inference/diffusion_speed.py+++ b/studio/backend/core/inference/diffusion_speed.py@@ -460,6 +460,13 @@ def apply_speed_optims("int8_gemm": False,}mode = normalize_speed_mode(speed_mode)+ if getattr(target, "backend", None) == "rocm":+ # Memory, not speed, so before the `off` return: ROCm has no fused SDPA for the VAE's head dim 384 / 512.+ try:+ from .diffusion_vae_attn_chunked import install as install_vae_attn_chunks+ install_vae_attn_chunks(getattr(pipe, "vae", None), target, logger)+ except Exception as exc: # noqa: BLE001 - keep stock attention+ _warn(logger, "vae attention chunks", exc)# TF32 (max) and cudnn.benchmark (any non-off CUDA load) are process-global; the caller restores them so a later# `off` load never inherits them.if mode == SPEED_OFF:diff --git a/studio/backend/core/inference/diffusion_vae_attn_chunked.py b/studio/backend/core/inference/diffusion_vae_attn_chunked.pynew file mode 100644index 00000000000..36ba2de0500--- /dev/null+++ b/studio/backend/core/inference/diffusion_vae_attn_chunked.py@@ -0,0 +1,232 @@+# 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, where no fused SDPA kernel takes head dim 384 / 512.++AOTriton caps gfx11 at head dim 256, so SDPA falls back to the math kernel and materialises the full fp32 score+matrix (16 GiB for a 2048x2048 FLUX.1 decode). Unmasked query rows are independent, so chunking them is exact.+``UNSLOTH_VAE_ATTN_CHUNKED=0`` disables it; ``UNSLOTH_VAE_ATTN_CHUNK_MB`` sets the per-chunk fp32 score budget.+"""++from __future__ import annotations++import os+from typing import Any, Optional++VAE_ATTN_CHUNK_ENV = "UNSLOTH_VAE_ATTN_CHUNKED"+VAE_ATTN_CHUNK_MB_ENV = "UNSLOTH_VAE_ATTN_CHUNK_MB"+_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+_PATCHED = "_unsloth_vae_attn_chunked"+++def chunking_disabled() -> bool:+ return os.environ.get(VAE_ATTN_CHUNK_ENV, "").strip().lower() in _FALSE+++def score_budget_bytes() -> int:+ raw = os.environ.get(VAE_ATTN_CHUNK_MB_ENV, "").strip()+ try:+ mb = int(raw) if raw else DEFAULT_SCORE_BUDGET_MB+ except ValueError:+ mb = DEFAULT_SCORE_BUDGET_MB+ return max(1, mb) * 2**20+++def fused_sdpa_available(q: Any, k: Any, v: Any) -> bool:+ """Whether flash, memory-efficient or cuDNN SDPA takes this call; non-CUDA tensors or query errors count as yes."""+ import torch++ if getattr(q, "device", None) is None or q.device.type != "cuda":+ return True+ cb = torch.backends.cuda+ try:+ try:+ params = cb.SDPAParams(q, k, v, None, 0.0, False, False)+ except TypeError: # torch without the enable_gqa field+ params = cb.SDPAParams(q, k, v, None, 0.0, False)+ for name in (+ "can_use_flash_attention",+ "can_use_efficient_attention",+ "can_use_cudnn_attention",+ ):+ fn = getattr(cb, name, None)+ if fn is not None and fn(params, False):+ return True+ except Exception: # noqa: BLE001 - unknown: keep the stock kernel+ return True+ return False+++def _score_bytes(q: Any, k: Any) -> int:+ rows = 1+ for s in q.shape[:-1]:+ rows *= int(s)+ return rows * int(k.shape[-2]) * 4+++def chunked_sdpa(+ sdpa: Any,+ q: Any,+ k: Any,+ v: Any,+ budget: int,+ scale: Optional[float] = None,+) -> Any:+ """``sdpa(q, k, v)`` over query-row chunks whose fp32 score tile stays within ``budget`` bytes."""+ import torch++ length = int(q.shape[-2])+ per_row = max(1, _score_bytes(q, k) // max(1, length))+ rows = max(1, min(length, budget // per_row))+ kw = {} if scale is None else {"scale": scale}+ out = torch.empty((*q.shape[:-1], v.shape[-1]), dtype = q.dtype, device = q.device)+ for i in range(0, length, rows):+ out[..., i : i + rows, :] = sdpa(q[..., i : i + rows, :], k, v, **kw)+ return out+++def _plain_call(args: tuple, kwargs: dict) -> Optional[tuple]:+ """(q, k, v, scale) for an unmasked, dropout-free, non-causal, non-GQA call; else None."""+ if len(args) > 4:+ return None+ extra = dict(kwargs)+ # diffusers' dispatch_attention_fn passes query= / key= / value= by keyword+ qkv = list(args[:3])+ for name in ("query", "key", "value")[len(qkv) :]:+ if name not in extra:+ return None+ qkv.append(extra.pop(name))+ q, k, v = qkv+ if len(args) == 4:+ extra["attn_mask"] = args[3]+ scale = extra.pop("scale", None)+ if extra.pop("attn_mask", None) is not None:+ return None+ if extra.pop("dropout_p", 0.0) not in (0, 0.0):+ return None+ if extra.pop("is_causal", False):+ return None+ if extra.pop("enable_gqa", False) or extra:+ return None+ if q.ndim < 3 or q.ndim != k.ndim or k.ndim != v.ndim or q.shape[:-2] != k.shape[:-2]:+ return None+ if q.requires_grad or k.requires_grad or v.requires_grad:+ return None+ return q, k, v, scale+++def _mode_class() -> Any:+ import torch.nn.functional as F+ from torch.overrides import TorchFunctionMode++ class ChunkedVaeAttentionMode(TorchFunctionMode):+ def __init__(self, budget: int):+ super().__init__()+ self.budget = budget+ self.chunked = 0++ def __torch_function__(+ self,+ func: Any,+ types: Any,+ args: tuple = (),+ kwargs: Any = None,+ ) -> Any:+ kwargs = kwargs or {}+ if func is F.scaled_dot_product_attention:+ 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)+ return func(*args, **kwargs)++ return ChunkedVaeAttentionMode+++_MODE_CLS: Any = None+++def chunked_attention_mode(budget: Optional[int] = None) -> Any:+ global _MODE_CLS+ if _MODE_CLS is None:+ _MODE_CLS = _mode_class()+ return _MODE_CLS(score_budget_bytes() if budget is None else budget)+++def _is_attention_module(module: Any) -> bool:+ name = type(module).__name__+ # diffusers Attention (AutoencoderKL, FLUX.2) and the single-head blocks of Wan / Qwen-Image / HunyuanImage VAEs+ return name == "Attention" or name.endswith(("AttentionBlock", "AttnBlock"))+++def _patch(module: Any) -> None:+ import torch++ inner = module.forward++ def forward(*args: Any, **kwargs: Any) -> Any:+ if chunking_disabled() or torch.compiler.is_compiling():+ return inner(*args, **kwargs)+ with chunked_attention_mode():+ return inner(*args, **kwargs)++ forward._unsloth_vae_attn_chunked = True+ forward._unsloth_vae_attn_inner = inner+ module.forward = forward+ setattr(module, _PATCHED, True)+++def wants_install(vae: Any, target: Any = None) -> bool:+ if vae is None or chunking_disabled() or not callable(getattr(vae, "modules", None)):+ return False+ if target is not None and getattr(target, "backend", None) != "rocm":+ return False+ try:+ import torch+ except Exception: # noqa: BLE001+ return False+ return bool(getattr(torch.version, "hip", None))+++def patch_attention_modules(vae: Any) -> int:+ """Patch every attention module of ``vae`` (outermost only, idempotent). Returns the number newly patched."""+ n = 0+ covered: list = []+ for name, module in vae.named_modules():+ if not _is_attention_module(module):+ continue+ if any(name.startswith(prefix + ".") for prefix in covered):+ continue+ covered.append(name)+ if getattr(module, _PATCHED, False):+ continue+ _patch(module)+ n += 1+ return n+++def install(+ vae: Any,+ target: Any = None,+ logger: Any = None,+) -> int:+ """Chunk the VAE attention on ROCm, where no fused SDPA kernel takes head dim > 256. Never raises."""+ try:+ if not wants_install(vae, target):+ return 0+ n = patch_attention_modules(vae)+ if n and logger is not None:+ logger.info(+ "diffusion.vae_attn_chunked: %d %s attention modules chunk SDPA calls no fused kernel takes",+ n,+ type(vae).__name__,+ )+ return n+ except Exception as exc: # noqa: BLE001 - stock attention on any failure+ if logger is not None:+ logger.warning("diffusion.vae_attn_chunked: not installed (%s)", exc)+ return 0diff --git a/studio/backend/tests/test_diffusion_vae_attn_chunked.py b/studio/backend/tests/test_diffusion_vae_attn_chunked.pynew file mode 100644index 00000000000..ad27617a316--- /dev/null+++ b/studio/backend/tests/test_diffusion_vae_attn_chunked.py@@ -0,0 +1,252 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""diffusion_vae_attn_chunked: query-chunked VAE attention where no fused SDPA kernel takes the head dim (ROCm).++CPU only: the math SDPA backend stands in for ROCm's fallback, and a dispatch-mode probe records the largest+tensor any op produces, so the bound on the score tile is checked without a GPU."""++import types++import pytest++torch = pytest.importorskip("torch")+F = torch.nn.functional+attention = pytest.importorskip("torch.nn.attention")+from torch.utils._python_dispatch import TorchDispatchMode # noqa: E402++from core.inference import diffusion_vae_attn_chunked as C # noqa: E402+++def _math():+ return attention.sdpa_kernel(attention.SDPBackend.MATH)+++class _LargestTensor(TorchDispatchMode):+ def __init__(self):+ super().__init__()+ self.max_bytes = 0++ def __torch_dispatch__(+ self,+ func,+ types_,+ args = (),+ kwargs = None,+ ):+ out = func(*args, **(kwargs or {}))+ for t in out if isinstance(out, (tuple, list)) else (out,):+ if isinstance(t, torch.Tensor):+ self.max_bytes = max(self.max_bytes, t.numel() * t.element_size())+ return out+++def rocm(monkeypatch):+ """Pretend to be ROCm with a math-only SDPA: the fused-kernel query says no for every call."""+ monkeypatch.setattr(torch.version, "hip", "7.2.0", raising = False)+ monkeypatch.setattr(C, "fused_sdpa_available", lambda q, k, v: False)+ monkeypatch.delenv(C.VAE_ATTN_CHUNK_ENV, raising = False)+ return types.SimpleNamespace(backend = "rocm", device = "cuda")++[email protected]("dtype,tol", [(torch.float32, 1e-5), (torch.bfloat16, 2e-2)])[email protected]("shape", [(1, 1, 1000, 64), (2, 300, 32), (1, 2, 517, 16)])[email protected]("budget_rows", [1, 64, 333, 10_000])+def test_chunked_equals_full_softmax(dtype, tol, shape, budget_rows):+ g = torch.Generator().manual_seed(0)+ q, k, v = (torch.randn(*shape, generator = g).to(dtype) for _ in range(3))+ rows = 1+ for s in shape[:-2]:+ rows *= s+ budget = budget_rows * rows * shape[-2] * 4+ with _math():+ ref = F.scaled_dot_product_attention(q, k, v)+ out = C.chunked_sdpa(F.scaled_dot_product_attention, q, k, v, budget)+ ref_s = F.scaled_dot_product_attention(q, k, v, scale = 0.3)+ out_s = C.chunked_sdpa(F.scaled_dot_product_attention, q, k, v, budget, scale = 0.3)+ assert out.dtype == ref.dtype and out.shape == ref.shape+ torch.testing.assert_close(out, ref, atol = tol, rtol = tol)+ torch.testing.assert_close(out_s, ref_s, atol = tol, rtol = tol)+++def test_mode_bounds_the_score_tile(rocm):+ q = torch.randn(1, 1, 2048, 64)+ full = 2048 * 2048 * 4+ budget = full // 16+ with _math():+ probe = _LargestTensor()+ with probe:+ ref = F.scaled_dot_product_attention(q, q, q)+ assert probe.max_bytes >= full # the math kernel materialises every score+ mode = C.chunked_attention_mode(budget)+ probe = _LargestTensor()+ with mode, probe:+ out = F.scaled_dot_product_attention(q, q, q)+ assert mode.chunked == 1+ assert probe.max_bytes <= budget+ torch.testing.assert_close(out, ref, atol = 1e-5, rtol = 1e-5)+++def test_mode_chunks_keyword_calls(rocm):+ q = torch.randn(1, 1, 512, 32)+ with _math():+ 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,+ value = q,+ attn_mask = None,+ dropout_p = 0.0,+ is_causal = False,+ scale = 0.2,+ enable_gqa = False,+ )+ mixed = F.scaled_dot_product_attention(q, key = q, value = q, scale = 0.2)+ assert mode.chunked == 2+ torch.testing.assert_close(out, ref, atol = 1e-5, rtol = 1e-5)+ torch.testing.assert_close(mixed, ref, atol = 1e-5, rtol = 1e-5)+++def test_mode_leaves_fused_small_masked_and_causal_calls_alone(monkeypatch):+ calls = []+ 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+ mask = torch.ones(256, 256, dtype = torch.bool)+ with _math():+ ref = F.scaled_dot_product_attention(q, q, q)+ # fused kernel available (the CPU answer, and NVIDIA's for head dim 512): the stock call, bit-identical+ with C.chunked_attention_mode(big) as mode:+ assert torch.equal(F.scaled_dot_product_attention(q, q, q), ref)+ assert mode.chunked == 0+ monkeypatch.setattr(C, "fused_sdpa_available", lambda q, k, v: False)+ with C.chunked_attention_mode(big) as mode:+ F.scaled_dot_product_attention(q, q, q, attn_mask = mask)+ F.scaled_dot_product_attention(q, q, q, mask)+ F.scaled_dot_product_attention(q, q, q, is_causal = True)+ F.scaled_dot_product_attention(q, q, q, dropout_p = 0.1)+ with C.chunked_attention_mode(256 * 256 * 4) as small:+ assert torch.equal(+ F.scaled_dot_product_attention(q, q, q), ref+ ) # at the budget: unchunked+ assert mode.chunked == 0 and small.chunked == 0 and calls == []+++def test_fused_query_is_stock_off_cuda():+ q = torch.randn(1, 1, 8, 512)+ assert C.fused_sdpa_available(q, q, q) is True+++def _tiny_vae(name):+ diffusers = pytest.importorskip("diffusers")+ torch.manual_seed(0)+ if name == "AutoencoderKL":+ return diffusers.AutoencoderKL(+ in_channels = 3,+ out_channels = 3,+ down_block_types = ("DownEncoderBlock2D", "DownEncoderBlock2D"),+ up_block_types = ("UpDecoderBlock2D", "UpDecoderBlock2D"),+ block_out_channels = (32, 64),+ layers_per_block = 1,+ latent_channels = 4,+ norm_num_groups = 8,+ ).eval()+ if name == "AutoencoderKLWan":+ return diffusers.AutoencoderKLWan(+ base_dim = 16, z_dim = 4, dim_mult = [1, 2], num_res_blocks = 1, temperal_downsample = [False]+ ).eval()+ if name == "AutoencoderKLQwenImage":+ return diffusers.AutoencoderKLQwenImage(+ base_dim = 16, z_dim = 4, dim_mult = [1, 2], num_res_blocks = 1, temperal_downsample = [False]+ ).eval()+ raise AssertionError(name)++[email protected]("name", ["AutoencoderKL", "AutoencoderKLWan", "AutoencoderKLQwenImage"])+def test_vae_decode_peak_bounded_and_equal(rocm, monkeypatch, name):+ vae = _tiny_vae(name)+ if name == "AutoencoderKL":+ z = torch.randn(1, 4, 48, 48)+ else:+ z = torch.randn(1, 4, 1, 48, 48)+ tokens = 48 * 48+ full = tokens * tokens * 4+ with torch.no_grad(), _math():+ probe = _LargestTensor()+ with probe:+ ref = vae.decode(z).sample+ assert probe.max_bytes >= full+ monkeypatch.setenv(+ C.VAE_ATTN_CHUNK_MB_ENV, "1"+ ) # 1 MiB of scores per chunk, well under the 21 MiB matrix+ assert C.install(vae, rocm) >= 1+ probe = _LargestTensor()+ with probe:+ out = vae.decode(z).sample+ assert probe.max_bytes < full // 4+ torch.testing.assert_close(out, ref, atol = 1e-4, rtol = 1e-4)+++def test_install_gates(monkeypatch, rocm):+ vae = _tiny_vae("AutoencoderKL")+ assert C.install(vae, types.SimpleNamespace(backend = "cuda", device = "cuda")) == 0+ monkeypatch.setenv(C.VAE_ATTN_CHUNK_ENV, "0")+ assert C.install(vae, rocm) == 0+ monkeypatch.delenv(C.VAE_ATTN_CHUNK_ENV)+ monkeypatch.setattr(torch.version, "hip", None, raising = False)+ assert C.install(vae, rocm) == 0+ assert not any(getattr(m, C._PATCHED, False) for m in vae.modules())+ assert C.install(None, rocm) == 0+++def test_install_patches_encoder_and_decoder_once(rocm):+ vae = _tiny_vae("AutoencoderKL")+ assert C.install(vae, rocm) == 2+ assert C.install(vae, rocm) == 0+ # a processor reset (fuse_qkv_projections) keeps the module-level patch+ for m in vae.modules():+ if type(m).__name__ == "Attention":+ m.set_processor(type(m.processor)())+ assert m.forward._unsloth_vae_attn_chunked+++def test_kill_switch_at_call_time(rocm, monkeypatch):+ vae = _tiny_vae("AutoencoderKL")+ monkeypatch.setenv(C.VAE_ATTN_CHUNK_MB_ENV, "1")+ C.install(vae, rocm)+ monkeypatch.setenv(C.VAE_ATTN_CHUNK_ENV, "off")+ z = torch.randn(1, 4, 48, 48)+ with torch.no_grad(), _math():+ probe = _LargestTensor()+ with probe:+ vae.decode(z)+ assert probe.max_bytes >= 48 * 48 * 48 * 48 * 4+++def test_speed_layer_installs_on_rocm_even_when_off(rocm, monkeypatch):+ from core.inference import diffusion_speed as S++ vae = _tiny_vae("AutoencoderKL")+ pipe = types.SimpleNamespace(vae = vae)+ S.apply_speed_optims(+ pipe,+ types.SimpleNamespace(backend = "rocm", device = "cuda", dtype = torch.bfloat16),+ is_gguf = False,+ family = types.SimpleNamespace(),+ speed_mode = S.SPEED_OFF,+ )+ assert sum(getattr(m, C._PATCHED, False) for m in vae.modules()) == 2+ nvidia = _tiny_vae("AutoencoderKL")+ S.apply_speed_optims(+ types.SimpleNamespace(vae = nvidia),+ types.SimpleNamespace(backend = "cuda", device = "cuda", dtype = torch.bfloat16),+ is_gguf = False,+ family = types.SimpleNamespace(),+ speed_mode = S.SPEED_OFF,+ )+ assert not any(getattr(m, C._PATCHED, False) for m in nvidia.modules())