Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
142 changes: 142 additions & 0 deletions studio/backend/core/_mps_sdpa_guard.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

"""Apple Silicon: split large SDPA calls that do not take the MPS prefill kernel into query-row chunks.

Below torch 2.13, MPS SDPA always runs the MPSGraph path, which builds the full score matrix and returns wrong values
(cosine 0.000 against fp64) from about 0.9 * 2^29 score elements per call on macOS 15 (pytorch#179352). New Apple
Silicon installs take torch 2.13, whose prefill kernel never builds the scores, but existing homes keep their torch.
Each query row of an attention call is independent, so running at most MPS_SCORE_ELEMENTS scores per call and
concatenating the rows is the same computation; it also caps the score memory. Calls the prefill kernel serves, calls
under the cap and every non-MPS call go to SDPA unchanged. ``UNSLOTH_MPS_ATTENTION_GUARD=0`` turns it off."""

from __future__ import annotations

import functools
import logging
import math
import os
import sys
from typing import Any, Optional

# Same bound as Qwen-Image-2.1's bounded attention (diffusion_qwenimage21_math.MPS_SCORE_ELEMENTS): half the size
# where macOS 15 / torch 2.11 SDPA starts returning wrong values.
MPS_SCORE_ELEMENTS = 2**28
GUARD_ENV = "UNSLOTH_MPS_ATTENTION_GUARD"
_GUARD_ATTR = "_unsloth_mps_large_attention_guard"
_ARG_NAMES = ("attn_mask", "dropout_p", "is_causal", "scale", "enable_gqa")

logger = logging.getLogger(__name__)

# Calls split into chunks since the guard was installed (a test / status hook).
stats = {"chunked_calls": 0}


def _is_mps(t: Any) -> bool:
return getattr(getattr(t, "device", None), "type", None) == "mps"


def _prefill_serves(query: Any, key: Any, value: Any, attn_mask: Any) -> bool:
try:
from core.inference.diffusion_attention import mps_prefill_attention
return bool(mps_prefill_attention(query, key, value, attn_mask, seq_dim = -2))
except Exception: # noqa: BLE001 -- cannot tell: chunking is exact, so split
return False


def chunk_rows(query: Any, key: Any) -> Optional[int]:
"""Query rows per call when ``query`` x ``key`` exceeds the score cap, else None (one call)."""
q_shape, k_shape = tuple(query.shape), tuple(key.shape)
if len(q_shape) < 2 or len(k_shape) < 2:
return None
sq, sk = int(q_shape[-2]), int(k_shape[-2])
lead = math.prod(int(d) for d in q_shape[:-2])
if sq <= 1 or lead * sq * sk <= MPS_SCORE_ELEMENTS:
return None
return max(1, MPS_SCORE_ELEMENTS // max(lead * sk, 1))


def _split(sdpa: Any, query: Any, key: Any, value: Any, rows: int, kwargs: dict) -> Any:
import torch

sq, sk = int(query.shape[-2]), int(key.shape[-2])
mask = kwargs.pop("attn_mask", None)
causal = bool(kwargs.pop("is_causal", False))
sliced_mask = mask is not None and mask.dim() >= 2 and int(mask.shape[-2]) != 1
outputs = []
for start in range(0, sq, rows):
end = min(start + rows, sq)
part_mask = mask[..., start:end, :] if sliced_mask else mask
if causal:
# SDPA's is_causal is top-left aligned: query row i sees keys 0..i.
part_mask = (
torch.arange(sk, device = query.device)[None, :]
<= torch.arange(start, end, device = query.device)[:, None]
)
outputs.append(sdpa(query[..., start:end, :], key, value, attn_mask = part_mask, **kwargs))
return torch.cat(outputs, dim = -2)


def guard_sdpa(sdpa: Any) -> Any:
"""``sdpa`` with every MPS call past the score cap that the prefill kernel does not take split by query rows."""
if getattr(sdpa, _GUARD_ATTR, False):
return sdpa

@functools.wraps(sdpa)
def guarded(query: Any, key: Any, value: Any, *args: Any, **kwargs: Any) -> Any:
if not _is_mps(query) or getattr(query, "is_nested", False) or len(args) > len(_ARG_NAMES):
return sdpa(query, key, value, *args, **kwargs)
rows = chunk_rows(query, key)
if rows is None:
return sdpa(query, key, value, *args, **kwargs)
bound = dict(zip(_ARG_NAMES, args))
if set(bound) & set(kwargs):
return sdpa(query, key, value, *args, **kwargs)
bound.update(kwargs)
mask = bound.get("attn_mask")
if mask is not None and (
bool(bound.get("is_causal", False))
or mask.dim() < 2
or int(mask.shape[-2]) not in (1, int(query.shape[-2]))
):
return sdpa(query, key, value, *args, **kwargs)
if _prefill_serves(query, key, value, mask):
return sdpa(query, key, value, *args, **kwargs)
stats["chunked_calls"] += 1
return _split(sdpa, query, key, value, rows, bound)

setattr(guarded, _GUARD_ATTR, True)
guarded.__wrapped__ = sdpa # type: ignore[attr-defined]
return guarded


def _disabled() -> bool:
return os.environ.get(GUARD_ENV, "").strip().lower() in ("0", "false", "no", "off")


def install_mps_large_attention_guard(log: Any = None) -> bool:
"""Wrap ``torch.nn.functional.scaled_dot_product_attention`` on an Apple Silicon host with MPS; idempotent; never
raises. Callers look the function up per call (diffusers' native backend, its SDPA processors, transformers), so
models loaded later are covered. True when the guard is in place."""
if sys.platform != "darwin" or _disabled():
return False
try:
import torch
import torch.nn.functional as F

mps = getattr(torch.backends, "mps", None)
if mps is None or not mps.is_available():
return False
if getattr(F.scaled_dot_product_attention, _GUARD_ATTR, False):
return True
F.scaled_dot_product_attention = guard_sdpa(F.scaled_dot_product_attention)
(log or logger).info(
"Apple Silicon: MPS attention calls past %d score elements without the prefill kernel run in "
"query chunks (torch %s)",
MPS_SCORE_ELEMENTS,
torch.__version__,
)
return True
except Exception: # noqa: BLE001 -- stock SDPA stays rather than failing the load
logger.debug("MPS large-attention guard not installed", exc_info = True)
return False
3 changes: 3 additions & 0 deletions studio/backend/core/inference/diffusion_attention.py
Original file line number Diff line number Diff line change
Expand Up @@ -4122,6 +4122,9 @@ def _apply_attention_backend_impl(
except Exception as exc:
_warn(logger, "ROCm fused SDPA check", exc)
install_rocm_contiguous_kv(target)
if _target_device(target).split(":")[0] == "mps":
from core._mps_sdpa_guard import install_mps_large_attention_guard
install_mps_large_attention_guard(logger)
setters = [
s
for s in (getattr(t, "set_attention_backend", None) for t in _attention_dits(pipe))
Expand Down
25 changes: 25 additions & 0 deletions studio/backend/tests/test_mps_attention_families.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,3 +223,28 @@ def test_past_the_upstream_threshold_on_the_prefill_kernel():
f"torch {torch.__version__} has no MPS prefill kernel: the full matrix would be > 8 GB"
)
assert _large_cell("qwen-image-2.1", int(1.1 * UPSTREAM_WRONG_FROM)) >= TOL[torch.bfloat16]


@mps
@pytest.mark.skipif(
not LARGE, reason = "UNSLOTH_MPS_LARGE_ATTENTION=1 or CI (GBs of scores on torch < 2.13)"
)
@pytest.mark.parametrize("family", ("z-image", "flux2-klein-4b", "qwen-image-2.1", "sd3.5-large"))
def test_the_guard_fixes_the_studio_measured_threshold(family, monkeypatch):
"""The same cells with Studio's MPS large-attention guard installed: right on every torch."""
from core import _mps_sdpa_guard as guard

monkeypatch.setattr(
torch.nn.functional,
"scaled_dot_product_attention",
torch.nn.functional.scaled_dot_product_attention,
)
monkeypatch.setitem(guard.stats, "chunked_calls", 0)
assert guard.install_mps_large_attention_guard() is True
assert _large_cell(family, int(1.15 * STUDIO_WRONG_FROM)) >= TOL[torch.bfloat16]
prefill = attention._version_tuple(torch.__version__)[:2] >= (2, 13)
print(
f"MPS-GUARD torch={torch.__version__} family={family} chunked_calls={guard.stats['chunked_calls']}"
)
# torch 2.13+ takes the prefill kernel, so nothing is split; below it the call must have been split.
assert (guard.stats["chunked_calls"] == 0) == prefill
58 changes: 58 additions & 0 deletions studio/backend/tests/test_mps_attention_guard_on_load.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

"""An image or video load on Apple Silicon (MPS) leaves torch's SDPA wrapped by the large-attention guard: torch below
2.13 returns wrong MPS attention past about 2^29 score elements, and only Qwen-Image-2.1 had its own bound.
Other devices keep the stock function."""

from __future__ import annotations

import sys
import types

import pytest

torch = pytest.importorskip("torch")

from core.inference import diffusion_attention as A # noqa: E402

F = torch.nn.functional


@pytest.fixture
def mac(monkeypatch):
original = F.scaled_dot_product_attention
monkeypatch.setattr(sys, "platform", "darwin")
monkeypatch.setattr(torch.backends, "mps", types.SimpleNamespace(is_available = lambda: True))
monkeypatch.setattr(A, "guard_rocm_fused_sdpa", lambda *a, **k: None)
monkeypatch.setattr(A, "install_rocm_contiguous_kv", lambda *a, **k: False)
yield original
F.scaled_dot_product_attention = original


def _load(device):
target = types.SimpleNamespace(device = device, backend = device, torch_device = device)
A._apply_attention_backend_impl(types.SimpleNamespace(transformer = None), None, target = target)


def test_mps_load_wraps_sdpa(mac):
_load("mps")
wrapped = F.scaled_dot_product_attention
assert wrapped is not mac
assert getattr(wrapped, "__wrapped__", None) is mac
# A later load does not wrap twice.
_load("mps")
assert F.scaled_dot_product_attention is wrapped


def test_guarded_sdpa_is_exact_off_mps(mac):
_load("mps")
g = torch.Generator().manual_seed(0)
q, k, v = (torch.randn(1, 4, 300, 32, generator = g) for _ in range(3))
assert torch.equal(F.scaled_dot_product_attention(q, k, v), mac(q, k, v))


@pytest.mark.parametrize("device", ["cpu", "cuda"])
def test_other_devices_keep_stock_sdpa(mac, device):
_load(device)
assert F.scaled_dot_product_attention is mac
Loading