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: use the MPS SDPA prefill kernel per call on torch 2.13+ (#14941)
Long Yixing60c77158d9e6
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 1826ed1d41a..c18afa7f987 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -282,6 +282,7 @@ from .diffusion_attention import (begin_attention_run,report_attention_run,select_attention_backend,+ _dit_head_dims,_ensure_attention_backend_installed,)from . import diffusion_compile_cache as compile_cache@@ -2656,7 +2657,7 @@ def _quadratic_attention(except Exception: # noqa: BLE001return Falsetry:- if not sdpa_math_only(target):+ if not sdpa_math_only(target, _dit_head_dims(pipe)):return Falseexcept Exception: # noqa: BLE001 - a broken probe must never block a generationreturn Falsediff --git a/studio/backend/core/inference/diffusion_attention.py b/studio/backend/core/inference/diffusion_attention.pyindex 1f3caf1a787..cce596d2bd6 100644--- a/studio/backend/core/inference/diffusion_attention.py+++ b/studio/backend/core/inference/diffusion_attention.py@@ -250,15 +250,51 @@ def _enabled_sdpa_kernels(kernels: tuple[str, ...]) -> tuple[str, ...]:MPS_PREFILL_ATTENTION_OFF_ENV = "PYTORCH_MPS_DISABLE_PREFILL_ATTENTION"+MPS_PREFILL_HEAD_DIMS = frozenset((32, 64, 72, 80, 96, 128, 256))-def _mps_sdpa_kernels(torch: Any) -> tuple[str, ...]:- """MPS ignores ``sdpa_kernel``, so answer from the build: only torch 2.13+ has a fused (prefill) kernel."""- if _version_tuple(torch.__version__)[:2] < (2, 13):- return (SDPA_MATH,)+def mps_prefill_supported() -> bool:+ import torchif os.environ.get(MPS_PREFILL_ATTENTION_OFF_ENV, "0") != "0":- return (SDPA_MATH,)- return (SDPA_FLASH, SDPA_MATH)+ return False+ return _version_tuple(torch.__version__)[:2] >= (2, 13)+++def mps_prefill_attention(+ query: Any,+ key: Any,+ value: Any,+ attn_mask: Any = None,+ seq_dim: int = -2,+) -> bool:+ """Whether torch runs this SDPA call on the MPS prefill kernel rather than the MPSGraph path that materialises the+ score matrix. ``seq_dim`` is the query's sequence axis (1 for diffusers' ``[B, S, H, D]``)."""+ import torch++ if (+ getattr(getattr(query, "device", None), "type", None) != "mps"+ or not mps_prefill_supported()+ ):+ return False+ if query.dtype not in (torch.float32, torch.float16, torch.bfloat16):+ return False+ # torch converts a bool mask to an additive one in q's dtype; a float mask of another dtype falls back.+ if attn_mask is not None and attn_mask.dtype not in (torch.bool, query.dtype):+ return False+ if torch.is_grad_enabled() and any(t.requires_grad for t in (query, key, value)):+ return False+ return (+ query.shape[seq_dim] > 8+ and key.shape[seq_dim] > 0+ and query.shape[-1] == value.shape[-1]+ and query.shape[-1] in MPS_PREFILL_HEAD_DIMS+ )+++def _mps_sdpa_kernels() -> tuple[str, ...]:+ """MPS ignores ``sdpa_kernel``, so answer from the build: only torch 2.13+ has a fused (prefill) kernel. Shape-blind:+ callers that know the family's head dims pass them to ``sdpa_math_only``."""+ return (SDPA_FLASH, SDPA_MATH) if mps_prefill_supported() else (SDPA_MATH,)def _probe_sdpa_kernels(device: str, dtype: Any) -> tuple[str, ...]:@@ -275,7 +311,7 @@ def _probe_sdpa_kernels(device: str, dtype: Any) -> tuple[str, ...]:from core._torchao_stub import _module_is_rocmif device.split(":")[0] == "mps":- return _mps_sdpa_kernels(torch)+ return _mps_sdpa_kernels()if device.split(":")[0] == "cuda" and _module_is_rocm(torch):return _probe_rocm_sdpa_kernels(device, dtype)# Small enough to be free, but shaped like real attention: the fused kernels reject head_dim they cannot serve, and@@ -346,19 +382,31 @@ def _sdpa_capability(target: Any) -> tuple[str, ...]:return _SDPA_PROBE_CACHE.setdefault(key, available)-def sdpa_math_only(target: Any) -> bool:+def _family_sdpa_kernels(target: Any, head_dims: Any = None) -> tuple[str, ...]:+ kernels = available_sdpa_kernels(target)+ if (+ head_dims+ and _target_device(target).split(":")[0] == "mps"+ and not set(head_dims) <= MPS_PREFILL_HEAD_DIMS+ ):+ return tuple(k for k in kernels if k not in _SDPA_SUBQUADRATIC)+ return kernels+++def sdpa_math_only(target: Any, head_dims: Any = None) -> bool:"""True only when MATH ran and every sub-quadratic backend refused.+ ``head_dims`` (the family's; empty = unknown) narrows the shape-blind MPS answer.A probe that answered nothing at all returns False: silence is not evidence."""- available = available_sdpa_kernels(target)+ available = _family_sdpa_kernels(target, head_dims)if not available:return Falsereturn SDPA_MATH in available and not any(k in available for k in _SDPA_SUBQUADRATIC)-def sdpa_subquadratic_confirmed(target: Any) -> bool:+def sdpa_subquadratic_confirmed(target: Any, head_dims: Any = None) -> bool:"""True only when a sub-quadratic SDPA kernel was seen to run; an unanswered probe is False."""- return any(k in _SDPA_SUBQUADRATIC for k in available_sdpa_kernels(target))+ return any(k in _SDPA_SUBQUADRATIC for k in _family_sdpa_kernels(target, head_dims))SDPA_MATH_ONLY_MESSAGE = (@@ -370,18 +418,22 @@ SDPA_MATH_ONLY_MESSAGE = ()-def warn_if_sdpa_math_only(target: Any, logger: Any = None) -> bool:+def warn_if_sdpa_math_only(+ target: Any,+ logger: Any = None,+ head_dims: Any = None,+) -> bool:"""Log the math-only diagnosis at LOAD, not 70 seconds into a doomed generation.Returns whether the warning fired, so callers can carry it into their resolved controls."""- if not sdpa_math_only(target):+ if not sdpa_math_only(target, head_dims):return Falseif logger is not None:logger.warning("diffusion.attention.math_only: device=%s dtype=%s kernels=%s -- %s",getattr(target, "device", None),getattr(target, "dtype", None),- ",".join(available_sdpa_kernels(target)) or "none",+ ",".join(_family_sdpa_kernels(target, head_dims)) or "none",SDPA_MATH_ONLY_MESSAGE,)return True@@ -3346,7 +3398,7 @@ def _configure_native_attention(pipe: Any, target: Any, logger: Any) -> None:returnexcept Exception as exc:_warn(logger, "bounded Qwen-Image-2.1 math attention", exc)- warn_if_sdpa_math_only(target, logger)+ warn_if_sdpa_math_only(target, logger, _dit_head_dims(pipe))def apply_attention_backend(diff --git a/studio/backend/core/inference/diffusion_qwenimage21_math.py b/studio/backend/core/inference/diffusion_qwenimage21_math.pyindex 30204349721..eb151ec0b8e 100644--- a/studio/backend/core/inference/diffusion_qwenimage21_math.py+++ b/studio/backend/core/inference/diffusion_qwenimage21_math.py@@ -53,8 +53,12 @@ def _bounded_attention(**kwargs,):import torch+ from .diffusion_attention import mps_prefill_attentionrows = _query_rows(query, key, budget)+ if mps_prefill_attention(query, key, value, mask, seq_dim = 1):+ # Decided per call: the prefill kernel never builds the scores, so neither budget nor element cap applies.+ rows = max(1, query.shape[1])outputs = []for start in range(0, query.shape[1], rows):part = query[:, start : start + rows]diff --git a/studio/backend/core/inference/diffusion_speed.py b/studio/backend/core/inference/diffusion_speed.pyindex f4ab92ed373..cf73200ffe1 100644--- a/studio/backend/core/inference/diffusion_speed.py+++ b/studio/backend/core/inference/diffusion_speed.py@@ -563,7 +563,7 @@ def apply_speed_optims("int8_gemm": False,}mode = normalize_speed_mode(speed_mode)- if getattr(target, "backend", None) == "rocm":+ if getattr(target, "backend", None) in ("rocm", "mps"):# 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_chunksdiff --git a/studio/backend/core/inference/diffusion_vae_attn_chunked.py b/studio/backend/core/inference/diffusion_vae_attn_chunked.pyindex 47e3aacdb3c..ea0f91d1ac9 100644--- a/studio/backend/core/inference/diffusion_vae_attn_chunked.py+++ b/studio/backend/core/inference/diffusion_vae_attn_chunked.py@@ -1,7 +1,7 @@# 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.+"""Query-chunked VAE attention on ROCm and Apple MPS, 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 scorematrix (16 GiB for a 2048x2048 FLUX.1 decode). Unmasked query rows are independent, so chunking them is exact.@@ -19,6 +19,7 @@ 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+MPS_SCORE_BUDGET_MB = 256_PATCHED = "_unsloth_vae_attn_chunked"@@ -26,20 +27,24 @@ def chunking_disabled() -> bool:return os.environ.get(VAE_ATTN_CHUNK_ENV, "").strip().lower() in _FALSE-def score_budget_bytes() -> int:+def score_budget_bytes(default_mb: int = DEFAULT_SCORE_BUDGET_MB) -> int:raw = os.environ.get(VAE_ATTN_CHUNK_MB_ENV, "").strip()try:- mb = int(raw) if raw else DEFAULT_SCORE_BUDGET_MB+ mb = int(raw) if raw else default_mbexcept ValueError:- mb = DEFAULT_SCORE_BUDGET_MB+ mb = default_mbreturn max(1, mb) * 2**20def 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."""+ """Whether a fused SDPA kernel (CUDA, or MPS prefill) takes this call; other devices or query errors count as yes."""import torch- if getattr(q, "device", None) is None or q.device.type != "cuda":+ device_type = getattr(getattr(q, "device", None), "type", None)+ if device_type == "mps":+ from .diffusion_attention import mps_prefill_attention+ return mps_prefill_attention(q, k, v)+ if device_type != "cuda":return Truecb = torch.backends.cudatry:@@ -164,7 +169,7 @@ def _is_attention_module(module: Any) -> bool:return name == "Attention" or name.endswith(("AttentionBlock", "AttnBlock"))-def _patch(module: Any) -> None:+def _patch(module: Any, default_mb: int) -> None:import torchinner = module.forward@@ -172,7 +177,7 @@ def _patch(module: Any) -> None:def forward(*args: Any, **kwargs: Any) -> Any:if chunking_disabled() or torch.compiler.is_compiling():return inner(*args, **kwargs)- with chunked_attention_mode():+ with chunked_attention_mode(score_budget_bytes(default_mb)):return inner(*args, **kwargs)forward._unsloth_vae_attn_chunked = True@@ -184,8 +189,11 @@ def _patch(module: Any) -> None: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":+ backend = getattr(target, "backend", None)+ if target is not None and backend not in ("rocm", "mps"):return False+ if backend == "mps":+ return Truetry:import torchexcept Exception: # noqa: BLE001@@ -193,7 +201,7 @@ def wants_install(vae: Any, target: Any = None) -> bool:return is_rocm_torch(torch)-def patch_attention_modules(vae: Any) -> int:+def patch_attention_modules(vae: Any, default_mb: int = DEFAULT_SCORE_BUDGET_MB) -> int:"""Patch every attention module of ``vae`` (outermost only, idempotent). Returns the number newly patched."""n = 0covered: list = []@@ -205,7 +213,7 @@ def patch_attention_modules(vae: Any) -> int:covered.append(name)if getattr(module, _PATCHED, False):continue- _patch(module)+ _patch(module, default_mb)n += 1return n@@ -215,11 +223,11 @@ def install(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)+ mps = getattr(target, "backend", None) == "mps"+ n = patch_attention_modules(vae, MPS_SCORE_BUDGET_MB if mps else DEFAULT_SCORE_BUDGET_MB)if n and logger is not None:logger.info("diffusion.vae_attn_chunked: %d %s attention modules chunk SDPA calls no fused kernel takes",diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex 70808208d31..248d2e7e9ed 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -55,6 +55,7 @@ from .diffusion_attention import (attention_status_reason,install_hunyuan_attention_trim,sdpa_math_only,+ _dit_head_dims,begin_attention_run,report_attention_run,select_attention_backend,@@ -3888,7 +3889,9 @@ def _log_failed_generation(request_shape: Optional[dict[str, Any]], exc: BaseExcif (_is_out_of_memory(exc)and request_shape.get("attention_backend") is None- and sdpa_math_only(_probe_target(request_shape))+ and sdpa_math_only(+ _probe_target(request_shape), request_shape.get("attention_head_dims")+ )):logger.error("video.generate_failed_request: %s", SDPA_MATH_ONLY_MESSAGE)except Exception: # noqa: BLE001 - diagnostics never mask the real failure@@ -3921,7 +3924,9 @@ def video_failure_detail(exc: BaseException, request_shape: Optional[dict[str, Aif (request_shape is not Noneand request_shape.get("attention_backend") is None- and sdpa_math_only(_probe_target(request_shape))+ and sdpa_math_only(+ _probe_target(request_shape), request_shape.get("attention_head_dims")+ )):return f"{VIDEO_GENERATION_FAILED_MSG} {SDPA_MATH_ONLY_MESSAGE}"return (@@ -12029,6 +12034,7 @@ class VideoBackend:"dtype": state.dtype,"offload": state.offload_policy,"attention_backend": state.attention_backend,+ "attention_head_dims": sorted(_dit_head_dims(state.pipe)),}self._last_request_shape = request_shapediff --git a/studio/backend/tests/test_diffusion_attention.py b/studio/backend/tests/test_diffusion_attention.pyindex 944fc4e2c6f..c90bfefa297 100644--- a/studio/backend/tests/test_diffusion_attention.py+++ b/studio/backend/tests/test_diffusion_attention.py@@ -886,6 +886,94 @@ def test_mps_answers_from_the_torch_build_not_an_execution_probe(version, env, fassert att.sdpa_math_only(target) is not fused+def _mps_tensor(+ shape,+ dtype,+ requires_grad = False,+):+ return types.SimpleNamespace(+ device = types.SimpleNamespace(type = "mps"),+ shape = shape,+ dtype = dtype,+ requires_grad = requires_grad,+ )+++ "change, prefill",+ [+ ({}, True),+ ({"q_len": 9}, True),+ ({"q_len": 8}, False),+ ({"head_dim": 72}, True),+ ({"head_dim": 48}, False),+ ({"head_dim": 160}, False),+ ({"v_dim": 64}, False),+ ({"dtype": "float32"}, True),+ ({"dtype": "float64"}, False),+ ({"mask": "bool"}, True),+ ({"mask": "bfloat16"}, True),+ ({"mask": "float32"}, False),+ ({"grad": True}, False),+ ({"device": "cpu"}, False),+ ({"version": "2.12.1"}, False),+ ],+)+def test_mps_prefill_attention_follows_the_torch_dispatch(change, prefill, monkeypatch):+ # The rule torch 2.13-2.15 applies in _scaled_dot_product_attention_math_mps: anything else builds the scores.+ torch = pytest.importorskip("torch")+ monkeypatch.setattr(torch, "__version__", change.get("version", "2.14.1"))+ monkeypatch.delenv(att.MPS_PREFILL_ATTENTION_OFF_ENV, raising = False)+ dtype = getattr(torch, change.get("dtype", "bfloat16"))+ head_dim = change.get("head_dim", 128)+ q = _mps_tensor((1, 24, change.get("q_len", 4096), head_dim), dtype, change.get("grad", False))+ k = _mps_tensor((1, 24, 4096, head_dim), dtype)+ v = _mps_tensor((1, 24, 4096, change.get("v_dim", head_dim)), dtype)+ if "device" in change:+ q.device = types.SimpleNamespace(type = change["device"])+ mask = (+ _mps_tensor((1, 1, 1, 4096), getattr(torch, change["mask"])) if "mask" in change else None+ )+ with torch.enable_grad():+ assert att.mps_prefill_attention(q, k, v, mask) is prefill+ q.shape = (q.shape[0], q.shape[2], q.shape[1], q.shape[3])+ k.shape = (k.shape[0], k.shape[2], k.shape[1], k.shape[3])+ with torch.enable_grad():+ assert att.mps_prefill_attention(q, k, v, mask, seq_dim = 1) is prefill+++ "device, version, head_dims, math_only",+ [+ ("mps", "2.14.1", None, False),+ ("mps", "2.14.1", {128}, False),+ ("mps", "2.14.1", {64, 128}, False),+ ("mps", "2.14.1", {128, 160}, True),+ ("mps", "2.12.1", {128}, True),+ ("cuda", "2.14.1", {160}, False),+ ],+)+def test_family_head_dims_narrow_the_mps_answer(device, version, head_dims, math_only, monkeypatch):+ # A family whose head dim has no prefill instance builds the scores on every call, whatever the torch build.+ torch = pytest.importorskip("torch")+ monkeypatch.setattr(torch, "__version__", version)+ monkeypatch.delenv(att.MPS_PREFILL_ATTENTION_OFF_ENV, raising = False)+ if device == "cuda":+ _stub_probe(monkeypatch, ("flash", "math"))+ target = _target(device)+ assert att.sdpa_math_only(target, head_dims) is math_only+ assert att.sdpa_subquadratic_confirmed(target, head_dims) is not math_only+ records = []+ logger = types.SimpleNamespace(warning = lambda *a: records.append(a))+ config = {"attention_head_dim": sorted(head_dims or ())}+ pipe = types.SimpleNamespace(transformer = types.SimpleNamespace(config = config))+ att._configure_native_attention(pipe, target, logger)+ assert any("math_only" in record[0] for record in records) is math_only+ from core.inference.diffusion import _quadratic_attention++ assert _quadratic_attention(target, None, pipe) is math_only++def test_an_unanswerable_probe_is_not_a_math_only_verdict(monkeypatch):_stub_probe(monkeypatch, ())assert att.sdpa_math_only(_target()) is Falsediff --git a/studio/backend/tests/test_diffusion_attention_rocm_flash.py b/studio/backend/tests/test_diffusion_attention_rocm_flash.pyindex d7aec268eea..f0abfa8fbe6 100644--- a/studio/backend/tests/test_diffusion_attention_rocm_flash.py+++ b/studio/backend/tests/test_diffusion_attention_rocm_flash.py@@ -1877,7 +1877,7 @@ def test_memory_guard_budgets_quadratic_when_flash_can_hand_calls_to_native(_guarded_flash(monkeypatch)_apply_env(monkeypatch)monkeypatch.setattr(att, "_time_rocm_flash_block", _timer([]))- monkeypatch.setattr(diffusion, "sdpa_math_only", lambda target: True)+ monkeypatch.setattr(diffusion, "sdpa_math_only", lambda target, *_: True)import core.inference.diffusion_qwenimage21_math as qmmonkeypatch.setattr(qm, "bounded_math_attention", lambda pipe: False)diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.pyindex 35f7d4d2de9..34e9c6ba97e 100644--- a/studio/backend/tests/test_diffusion_backend.py+++ b/studio/backend/tests/test_diffusion_backend.py@@ -11110,7 +11110,7 @@ def test_generate_upscale_refuses_when_the_vae_tiling_does_not_engage(def test_quadratic_attention_follows_the_engaged_backend(monkeypatch):from core.inference import diffusion as dmod- monkeypatch.setattr(dmod, "sdpa_math_only", lambda target: True)+ monkeypatch.setattr(dmod, "sdpa_math_only", lambda target, *_: True)assert dmod._quadratic_attention(object()) is Trueassert dmod._quadratic_attention(object(), None) is Trueassert dmod._quadratic_attention(object(), "native") is True@@ -11124,7 +11124,7 @@ def test_generate_upscale_with_an_engaged_backend_on_a_math_only_device_runs_tilfrom core.inference import diffusion as dmodbackend = _loaded_backend_on_a_16g_card(tmp_path, monkeypatch)- monkeypatch.setattr(dmod, "sdpa_math_only", lambda target: True)+ monkeypatch.setattr(dmod, "sdpa_math_only", lambda target, *_: True)vae = _TilingVae()monkeypatch.setattr(_FakeImg2ImgPipe, "vae", vae, raising = False)with pytest.raises(ValueError, match = "2048x2048"):diff --git a/studio/backend/tests/test_diffusion_learned_peaks.py b/studio/backend/tests/test_diffusion_learned_peaks.pyindex be1a4c88bb8..215764e4387 100644--- a/studio/backend/tests/test_diffusion_learned_peaks.py+++ b/studio/backend/tests/test_diffusion_learned_peaks.py@@ -2042,8 +2042,10 @@ def test_attention_scaling_unknown_render_is_not_recorded(store, monkeypatch):)monkeypatch.setattr(diffusion, "_conditioning_cache_hits", lambda pipe: 0)answers = {"math": False, "fused": False}- monkeypatch.setattr(diffusion, "sdpa_math_only", lambda target: answers["math"])- monkeypatch.setattr(diffusion, "sdpa_subquadratic_confirmed", lambda target: answers["fused"])+ monkeypatch.setattr(diffusion, "sdpa_math_only", lambda target, *_: answers["math"])+ monkeypatch.setattr(+ diffusion, "sdpa_subquadratic_confirmed", lambda target, *_: answers["fused"]+ )target = types.SimpleNamespace(device = "cuda:0")assert not diffusion._attention_scaling_known(target, "native") # the probe answered nothingassert not diffusion._attention_scaling_known(None, None)diff --git a/studio/backend/tests/test_diffusion_qwenimage21_math.py b/studio/backend/tests/test_diffusion_qwenimage21_math.pyindex 75dafbb7678..9364a696180 100644--- a/studio/backend/tests/test_diffusion_qwenimage21_math.py+++ b/studio/backend/tests/test_diffusion_qwenimage21_math.py@@ -46,9 +46,45 @@ def test_bounded_attention_matches_full_math_with_masks(mask_kind):assert [c[:2] for c in calls] == [(512, 833), (257, 833)][email protected]("prefill", [False, True])+def test_prefill_eligible_calls_run_unsplit(monkeypatch, prefill):+ # torch 2.13+'s MPS prefill kernel never builds the scores; anything it does not take keeps the MPS split.+ torch.manual_seed(5)+ q, k, v = torch.randn(1, 4096, 2, 8), torch.randn(1, 4352, 2, 8), torch.randn(1, 4352, 2, 8)+ mask = torch.ones(1, 1, 1, 4352, dtype = torch.bool)+ seen = []++ def eligible(+ query,+ key,+ value,+ attn_mask = None,+ seq_dim = -2,+ ):+ seen.append((query.shape[seq_dim], attn_mask is mask))+ return prefill++ monkeypatch.setattr(attention, "mps_prefill_attention", eligible)+ calls = []++ def dispatch(q, k, v, **kw):+ calls.append(q.shape[1])+ return qmod.dispatch_attention_fn(q, k, v, backend = "native", **kw)++ expected = dispatch(q, k, v, attn_mask = mask, dropout_p = 0.0)+ calls.clear()+ actual = bounded._bounded_attention(q, k, v, dispatch, mask = mask, budget = 2 * 4352 * 4 * 1000)+ torch.testing.assert_close(actual, expected)+ assert seen == [(4096, True)]+ assert calls == ([4096] if prefill else [1000] * 4 + [96])++[email protected]("prefill", [False, True])@pytest.mark.parametrize("padded", [False, True])-def test_segmented_prefill_and_cached_decode_match_stock(monkeypatch, padded):+def test_segmented_prefill_and_cached_decode_match_stock(monkeypatch, padded, prefill):torch.manual_seed(7)+ # Unsplit (prefill-eligible) calls are the stock calls exactly: causal text segment, padded keys, cached decode.+ monkeypatch.setattr(attention, "mps_prefill_attention", lambda *a, **k: prefill)attn = qmod.QwenImage21Attention(dim = 16, heads = 2, dim_head = 8)stock, patched = qmod.QwenImage21AttnProcessor(), bounded._processor_class()()states = torch.randn(2, 1800, 16)@@ -80,7 +116,10 @@ def test_segmented_prefill_and_cached_decode_match_stock(monkeypatch, padded):torch.testing.assert_close(actual, expected)torch.testing.assert_close(caches[0].k, caches[1].k, atol = 0, rtol = 0)torch.testing.assert_close(caches[0].v, caches[1].v, atol = 0, rtol = 0)- assert max(calls) == 512 and len(calls) >= 6+ if prefill:+ assert torch.equal(actual, expected) and calls == [600, 530, 670]+ else:+ assert max(calls) == 512 and len(calls) >= 6target = states[:, 1130:]key_mask = mask[:, None, None, :] if padded else Noneexpected = stock(@@ -91,6 +130,8 @@ def test_segmented_prefill_and_cached_decode_match_stock(monkeypatch, padded):)torch.testing.assert_close(actual, expected)assert caches[1].k.shape[1] == 1130+ if prefill:+ assert torch.equal(actual, expected) and calls[3:] == [670]def make_pipe():@@ -106,8 +147,8 @@ def test_native_load_installs_fallback_and_guard_tracks_actual_processors(monkeypipe, modules = make_pipe()target = SimpleNamespace(backend = "rocm", device = "cuda:0", dtype = torch.bfloat16)- monkeypatch.setattr(attention, "sdpa_math_only", lambda t: True)- monkeypatch.setattr("core.inference.diffusion.sdpa_math_only", lambda t: True)+ monkeypatch.setattr(attention, "sdpa_math_only", lambda t, *_: True)+ monkeypatch.setattr("core.inference.diffusion.sdpa_math_only", lambda t, *_: True)monkeypatch.setattr(attention, "_is_cuda_rocm", lambda t: True)monkeypatch.setattr(attention, "guard_rocm_fused_sdpa", lambda *a: ())assert _quadratic_attention(target, None, pipe)@@ -124,7 +165,7 @@ def test_native_load_installs_fallback_and_guard_tracks_actual_processors(monkey@pytest.mark.parametrize("change", ["parallel", "custom", "non_native"])def test_guard_never_credits_uncovered_processors(monkeypatch, change):pipe, modules = make_pipe()- monkeypatch.setattr(attention, "sdpa_math_only", lambda t: True)+ monkeypatch.setattr(attention, "sdpa_math_only", lambda t, *_: True)assert bounded.install(pipe, SimpleNamespace(backend = "rocm"))if change == "parallel":modules[0].processor._parallel_config = object()@@ -137,9 +178,9 @@ def test_guard_never_credits_uncovered_processors(monkeypatch, change):def test_healthy_fused_install_and_non_rocm_keep_stock(monkeypatch):pipe, modules = make_pipe()- monkeypatch.setattr(attention, "sdpa_math_only", lambda t: False)+ monkeypatch.setattr(attention, "sdpa_math_only", lambda t, *_: False)assert not bounded.install(pipe, SimpleNamespace(backend = "rocm"))- monkeypatch.setattr(attention, "sdpa_math_only", lambda t: True)+ monkeypatch.setattr(attention, "sdpa_math_only", lambda t, *_: True)assert not bounded.install(pipe, SimpleNamespace(backend = "cuda"))assert all(type(m.processor) is qmod.QwenImage21AttnProcessor for m in modules)@@ -159,7 +200,7 @@ def test_causal_chunk_offsets_include_preceding_segments():def test_failed_bounded_processor_inspection_keeps_quadratic_guard(monkeypatch):from core.inference import diffusion- monkeypatch.setattr(diffusion, "sdpa_math_only", lambda t: True)+ monkeypatch.setattr(diffusion, "sdpa_math_only", lambda t, *_: True)def failed(pipe):raise RuntimeError("processor unavailable")@@ -184,7 +225,7 @@ def test_mps_installs_bounded_attention_without_trusting_the_probe(monkeypatch):pipe, modules = make_pipe()target = SimpleNamespace(backend = "mps", device = "mps", dtype = torch.bfloat16)# MPS SDPA ignores sdpa_kernel, so the probe reports fused kernels it does not run.- monkeypatch.setattr(attention, "sdpa_math_only", lambda t: False)+ monkeypatch.setattr(attention, "sdpa_math_only", lambda t, *_: False)warned = []monkeypatch.setattr(attention, "warn_if_sdpa_math_only", lambda *a, **k: warned.append(a))attention.apply_attention_backend(pipe, None, target = target)@@ -205,7 +246,7 @@ def test_mps_installs_bounded_attention_without_trusting_the_probe(monkeypatch):],)def test_bounded_attention_targets(monkeypatch, target, math_only, expected):- monkeypatch.setattr(attention, "sdpa_math_only", lambda t: math_only)+ monkeypatch.setattr(attention, "sdpa_math_only", lambda t, *_: math_only)assert bounded.needs_bounded_attention(target) is expecteddiff --git a/studio/backend/tests/test_diffusion_vae_attn_chunked.py b/studio/backend/tests/test_diffusion_vae_attn_chunked.pyindex e99c4b9bb53..4fff83267a0 100644--- a/studio/backend/tests/test_diffusion_vae_attn_chunked.py+++ b/studio/backend/tests/test_diffusion_vae_attn_chunked.py@@ -143,6 +143,20 @@ def test_fused_query_is_stock_off_cuda():assert C.fused_sdpa_available(q, q, q) is True[email protected]("head_dim, fused", [(512, False), (384, False), (128, True)])+def test_fused_query_on_mps_asks_the_prefill_kernel(monkeypatch, head_dim, fused):+ # No MPS fused kernel takes the VAE's head dim 384 / 512, whatever the torch build.+ monkeypatch.setattr(torch, "__version__", "2.14.1")+ monkeypatch.delenv("PYTORCH_MPS_DISABLE_PREFILL_ATTENTION", raising = False)+ q = types.SimpleNamespace(+ device = types.SimpleNamespace(type = "mps"),+ dtype = torch.bfloat16,+ shape = (1, 1, 16384, head_dim),+ requires_grad = False,+ )+ assert C.fused_sdpa_available(q, q, q) is fused++def _tiny_vae(name):diffusers = pytest.importorskip("diffusers")torch.manual_seed(0)@@ -193,6 +207,28 @@ def test_vae_decode_peak_bounded_and_equal(rocm, monkeypatch, name):torch.testing.assert_close(out, ref, atol = 1e-4, rtol = 1e-4)+ "backend, env, budget_mb", [("rocm", None, 1024), ("mps", None, 256), ("mps", "64", 64)]+)+def test_install_budget_follows_the_device(rocm, monkeypatch, backend, env, budget_mb):+ # MPSGraph holds several score-sized buffers, so a 1 GiB FLUX.1 tile is chunked there but not on ROCm.+ if env is not None:+ monkeypatch.setenv(C.VAE_ATTN_CHUNK_MB_ENV, env)+ else:+ monkeypatch.delenv(C.VAE_ATTN_CHUNK_MB_ENV, raising = False)+ monkeypatch.setattr(torch.version, "hip", None if backend == "mps" else "7.2.0", raising = False)+ vae = _tiny_vae("AutoencoderKL")+ assert C.install(vae, types.SimpleNamespace(backend = backend, device = backend)) == 2+ budgets = []+ real = C.chunked_attention_mode+ monkeypatch.setattr(+ C, "chunked_attention_mode", lambda budget = None: budgets.append(budget) or real(budget)+ )+ with torch.no_grad():+ vae.decode(torch.randn(1, 4, 8, 8))+ assert budgets == [budget_mb * 2**20]++def test_install_gates(monkeypatch, rocm):vae = _tiny_vae("AutoencoderKL")assert C.install(vae, types.SimpleNamespace(backend = "cuda", device = "cuda")) == 0@@ -230,7 +266,7 @@ def test_kill_switch_at_call_time(rocm, monkeypatch):assert probe.max_bytes >= 48 * 48 * 48 * 48 * 4-def test_speed_layer_installs_on_rocm_even_when_off(rocm, monkeypatch):+def test_speed_layer_installs_on_rocm_and_mps_even_when_off(rocm, monkeypatch):from core.inference import diffusion_speed as Svae = _tiny_vae("AutoencoderKL")@@ -243,6 +279,15 @@ def test_speed_layer_installs_on_rocm_even_when_off(rocm, monkeypatch):speed_mode = S.SPEED_OFF,)assert sum(getattr(m, C._PATCHED, False) for m in vae.modules()) == 2+ mac = _tiny_vae("AutoencoderKL")+ S.apply_speed_optims(+ types.SimpleNamespace(vae = mac),+ types.SimpleNamespace(backend = "mps", device = "mps", dtype = torch.bfloat16),+ is_gguf = False,+ family = types.SimpleNamespace(),+ speed_mode = S.SPEED_OFF,+ )+ assert sum(getattr(m, C._PATCHED, False) for m in mac.modules()) == 2nvidia = _tiny_vae("AutoencoderKL")S.apply_speed_optims(types.SimpleNamespace(vae = nvidia),diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.pyindex b74b64b94d1..50d827a6004 100644--- a/studio/backend/tests/test_video_backend.py+++ b/studio/backend/tests/test_video_backend.py@@ -8732,7 +8732,7 @@ def test_a_failed_generation_logs_the_resolved_request(fake_runtime, tmp_path, m# Log the request shape behind an OOM (#8225).backend, video_mod = _shared_setup_1(tmp_path)_shared_setup_6(backend, monkeypatch)- monkeypatch.setattr(video_mod, "sdpa_math_only", lambda target: False)+ monkeypatch.setattr(video_mod, "sdpa_math_only", lambda target, *_: False)records = _capture_generate_failures(monkeypatch)with pytest.raises(RuntimeError):@@ -8770,7 +8770,7 @@ def test_the_failure_log_carries_no_prompt_text(fake_runtime, tmp_path, monkeypamonkeypatch.setattr(type(backend._state.pipe), "__call__", _failing_pipe_call(RuntimeError("kaboom")))- monkeypatch.setattr(video_mod, "sdpa_math_only", lambda target: False)+ monkeypatch.setattr(video_mod, "sdpa_math_only", lambda target, *_: False)records = _capture_generate_failures(monkeypatch)with pytest.raises(RuntimeError):@@ -8785,7 +8785,7 @@ def test_an_oom_on_a_math_only_device_names_the_quadratic_cost(fake_runtime, tmp# With no fused kernel, an OOM should carry the score-matrix diagnosis.backend, video_mod = _shared_setup_1(tmp_path)_shared_setup_6(backend, monkeypatch)- monkeypatch.setattr(video_mod, "sdpa_math_only", lambda target: True)+ monkeypatch.setattr(video_mod, "sdpa_math_only", lambda target, *_: True)records = _shared_setup_10(backend, monkeypatch)assert len(records) == 2@@ -8800,7 +8800,7 @@ def test_a_non_oom_failure_does_not_blame_attention(fake_runtime, tmp_path, monk"__call__",_failing_pipe_call(RuntimeError("scheduler produced NaN sigmas")),)- monkeypatch.setattr(video_mod, "sdpa_math_only", lambda target: True)+ monkeypatch.setattr(video_mod, "sdpa_math_only", lambda target, *_: True)records = _shared_setup_10(backend, monkeypatch)assert len(records) == 1@@ -8846,7 +8846,7 @@ def test_a_broken_diagnostic_never_replaces_the_real_failure(fake_runtime, tmp_pbackend, video_mod = _shared_setup_1(tmp_path)_shared_setup_6(backend, monkeypatch)- def _boom(target):+ def _boom(target, *_):raise RuntimeError("the probe itself is broken")monkeypatch.setattr(video_mod, "sdpa_math_only", _boom)@@ -8886,7 +8886,7 @@ def test_the_oom_diagnosis_is_skipped_when_an_external_backend_ran()probed: list = []- def _never(target):+ def _never(target, *_):probed.append(target)return True@@ -8908,8 +8908,12 @@ def test_the_oom_probe_uses_the_dtype_the_run_actually_used(fake_runtime, tmp_pabackend._state = replace(backend._state, dtype = "float32", attention_backend = None)_shared_setup_6(backend, monkeypatch)seen: list = []- monkeypatch.setattr(video_mod, "sdpa_math_only", lambda target: seen.append(target) or True)+ monkeypatch.setattr(+ video_mod, "sdpa_math_only", lambda target, *a: seen.append((target, *a)) or True+ )+ monkeypatch.setattr(video_mod, "_dit_head_dims", lambda pipe: {128})records = _shared_setup_10(backend, monkeypatch)+ assert [a for _, *a in seen] == [[[128]]]assert any("dtype=float32" in line for line in records)assert len(seen) == 1