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
44 changes: 43 additions & 1 deletion install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4365,6 +4365,9 @@ TORCHVISION_CONSTRAINT="torchvision>=0.19,<${_TORCHVISION_CEILING}"
TORCHAUDIO_CONSTRAINT="torchaudio>=2.4,<${_TORCHAUDIO_CEILING}"
_CU130_TORCH_CEILING="2.15.0"
_CU130_NEW_INSTALL_TORCH="torch>=2.13.0,<2.14.0"
# Apple Silicon: 2.13 is the first with fused MPS attention (mflux needs >=2.13); 2.15 lacks cp310/torchvision.
_MACOS_TORCH_CEILING="2.15.0"
_MACOS_NEW_INSTALL_TORCH="torch>=2.13.0,<2.14.0"

# ── Resolve repo root (for --local installs) ──
_REPO_ROOT="$(cd "$(dirname "$0" 2>/dev/null || echo ".")" && pwd)"
Expand Down Expand Up @@ -5941,6 +5944,28 @@ _cu130_torch213_platform() {
[ "$_ctr_py" = "3.13" ] && echo "yes" || echo "no"
}

# /cpu leaf on arm64 macOS with a Python 2.13 has wheels for; alone sets the preservation window.
_macos_torch213_platform() {
[ "$(_torch_index_url_leaf "$1")" = "cpu" ] || { echo "no"; return; }
[ "$OS" = "macos" ] && [ "$_ARCH" = "arm64" ] || { echo "no"; return; }
_mtr_py=$("$VENV_DIR/bin/python" -c "import sys; print('%d.%d' % sys.version_info[:2])" 2>/dev/null || echo "")
case "$_mtr_py" in 3.10|3.11|3.12|3.13|3.14) echo "yes" ;; *) echo "no" ;; esac
}

_macos_product_major() {
_mpm=$(sw_vers -productVersion 2>/dev/null) || _mpm=""
_mpm="${_mpm%%.*}"
case "$_mpm" in ''|*[!0-9]*) echo "" ;; *) echo "$_mpm" ;; esac
}

# New installs only: torch 2.13's macOS wheels are macosx_14_0 and it has no cp313t build.
_macos_torch213_host_ok() {
_mth_major=$(_macos_product_major)
[ -n "$_mth_major" ] && [ "$_mth_major" -ge 14 ] 2>/dev/null || { echo "no"; return; }
_mth_gil=$("$VENV_DIR/bin/python" -c "import sysconfig; print('gil-disabled' if sysconfig.get_config_var('Py_GIL_DISABLED') else 'gil-enabled')" 2>/dev/null || echo "")
[ "$_mth_gil" = "gil-enabled" ] && echo "yes" || echo "no"
}

# `studio update` runs the installed release's setup, which would downgrade a newer torch;
# any failure answers "no".
_pypi_unsloth_admits_torch() {
Expand Down Expand Up @@ -6984,6 +7009,7 @@ fi # _torch_index_pinned guard (Radeon + Strix reroute)
# New installs on this route get 2.13; preservation keeps 2.4-2.14 installs on their release.
_PRESERVE_TORCH_CONSTRAINT="$TORCH_CONSTRAINT"
_CU130_NEW_INSTALL_ROUTE=false
_MACOS_NEW_INSTALL_ROUTE=false
if [ "$SKIP_TORCH" = false ] && [ "$(_cu130_torch213_platform "$TORCH_INDEX_URL")" = "yes" ]; then
_PRESERVE_TORCH_CONSTRAINT="torch>=2.4,<${_CU130_TORCH_CEILING}"
# An existing home never takes 2.13 unasked, even when its torch could not be read or kept.
Expand All @@ -6994,13 +7020,25 @@ if [ "$SKIP_TORCH" = false ] && [ "$(_cu130_torch213_platform "$TORCH_INDEX_URL"
&& [ "$(_pypi_unsloth_admits_torch "2.13.0")" = "yes" ]; then
_CU130_NEW_INSTALL_ROUTE=true
fi
elif [ "$SKIP_TORCH" = false ] && [ "$(_macos_torch213_platform "$TORCH_INDEX_URL")" = "yes" ]; then
# Same policy as cu130: keep a resident 2.4-2.14, move only a fresh home (or an explicit upgrade).
_PRESERVE_TORCH_CONSTRAINT="${TORCH_CONSTRAINT%%,*},<${_MACOS_TORCH_CEILING}"
if [ "$(printf '%s' "$PACKAGE_NAME" | tr '[:upper:]' '[:lower:]')" = "unsloth" ] \
&& { [ "$_EXISTING_INSTALL" = false ] || [ "${UNSLOTH_TORCH_UPGRADE:-0}" = "1" ]; } \
&& [ "${_torch_index_pinned:-false}" = false ] \
&& [ "$(_macos_torch213_host_ok)" = "yes" ] \
&& [ "$(_pypi_unsloth_admits_torch "2.13.0")" = "yes" ]; then
# an index set with UNSLOTH_TORCH_INDEX_URL (a mirror or snapshot) may not carry 2.13: only the chosen one moves
_MACOS_NEW_INSTALL_ROUTE=true
fi
fi
_PREV_TORCH_PIN=""
_PREV_FALLBACK_CONSTRAINT="$TORCH_CONSTRAINT"
if [ "$SKIP_TORCH" = false ]; then
_prev_pin=$(_previous_torch_pin "$_PREV_TORCH_VER" "$_PRESERVE_TORCH_CONSTRAINT")
if [ -z "$_prev_pin" ] && [ "${UNSLOTH_TORCH_UPGRADE:-0}" = "1" ] \
&& [ "$_CU130_NEW_INSTALL_ROUTE" = false ] && [ -n "$_PREV_TORCH_VER" ] \
&& [ "$_CU130_NEW_INSTALL_ROUTE" = false ] && [ "$_MACOS_NEW_INSTALL_ROUTE" = false ] \
&& [ -n "$_PREV_TORCH_VER" ] \
&& [ "$(_torch_release_in_window "${_PREV_TORCH_VER%%+*}" "$TORCH_CONSTRAINT")" != "yes" ]; then
_prev_pin=$(_previous_torch_pin "$_PREV_TORCH_VER" "$_PRESERVE_TORCH_CONSTRAINT" keep)
fi
Expand All @@ -7014,6 +7052,10 @@ if [ -z "$_PREV_TORCH_PIN" ] && [ "$_CU130_NEW_INSTALL_ROUTE" = true ]; then
TORCH_CONSTRAINT="$_CU130_NEW_INSTALL_TORCH"
TORCHVISION_CONSTRAINT="torchvision>=0.28.0,<0.29.0"
fi
if [ -z "$_PREV_TORCH_PIN" ] && [ "$_MACOS_NEW_INSTALL_ROUTE" = true ]; then
TORCH_CONSTRAINT="$_MACOS_NEW_INSTALL_TORCH"
TORCHVISION_CONSTRAINT="torchvision>=0.28.0,<0.29.0"
fi

_TAURI_TORCH_INDEX_FAMILY=$(_tauri_torch_index_family "$TORCH_INDEX_URL")
if [ "$_amd_gpu_radeon" = true ] && [ "$SKIP_TORCH" = false ]; then
Expand Down
225 changes: 225 additions & 0 deletions studio/backend/tests/test_mps_attention_families.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

"""MPS SDPA vs a CPU reference at each image family's attention shape.

torch <2.13 MPSGraph SDPA is wrong past a size (pytorch#179352); 2.13+ uses a fused prefill kernel.
Large cells run on CI or with UNSLOTH_MPS_LARGE_ATTENTION=1 (0 disables).
"""

from __future__ import annotations

import math
import os
import warnings

import pytest

torch = pytest.importorskip("torch")

from core.inference import diffusion_attention as attention

# (heads, head_dim, text tokens) of each family's joint attention; patch 2 on an 8x VAE = 16 px per token.
FAMILIES = {
"z-image": (30, 128, 128),
"flux2-klein-4b": (24, 128, 512),
"flux1": (24, 128, 512),
"qwen-image": (24, 128, 256),
"qwen-image-2.1": (32, 128, 256),
"sd3.5-large": (38, 64, 333),
"wan2.2-14b": (40, 128, 512),
"ltx-video": (32, 64, 128),
}
LARGE = (
os.environ.get("UNSLOTH_MPS_LARGE_ATTENTION")
or ("1" if os.environ.get("GITHUB_ACTIONS") == "true" else "0")
) == "1"
# Elements Studio measured wrong on macOS 15 / torch 2.11 (diffusion_qwenimage21_math.MPS_SCORE_ELEMENTS doc).
STUDIO_WRONG_FROM = int(0.9 * 2**29)
# pytorch#179352: head h of a B=1 call is wrong once h * T * T reaches this.
UPSTREAM_WRONG_FROM = 2**32

mps = pytest.mark.skipif(
not (getattr(torch.backends, "mps", None) is not None and torch.backends.mps.is_available()),
reason = "needs MPS",
)


def _tokens(px: int, text: int) -> int:
return (px // 16) ** 2 + text


def _qkv(
heads,
tokens,
head_dim,
dtype,
seed = 0,
):
g = torch.Generator().manual_seed(seed)
return [
torch.randn((1, heads, tokens, head_dim), generator = g, dtype = torch.float32).to(dtype)
for _ in range(3)
]


def _reference_rows(q, k, v, heads, rows):
q = q[:, heads][:, :, rows].double()
scores = q @ k[:, heads].double().transpose(-1, -2) / math.sqrt(q.shape[-1])
return torch.softmax(scores, dim = -1) @ v[:, heads].double()


def _cos(a, b):
return float(
torch.nn.functional.cosine_similarity(a.flatten().double(), b.flatten().double(), dim = 0)
)


DEVICE = "mps"


def _dev(*tensors):
return [t.to(DEVICE) for t in tensors]


def _sync():
if DEVICE == "mps":
torch.mps.synchronize()


def _mps_attention(
q,
k,
v,
attn_mask = None,
):
with torch.inference_mode():
out = torch.nn.functional.scaled_dot_product_attention(*_dev(q, k, v), attn_mask = attn_mask)
_sync()
return out


def _driver_growth(fn):
if DEVICE != "mps":
return fn(), 0
torch.mps.synchronize()
torch.mps.empty_cache()
base = torch.mps.driver_allocated_memory()
out = fn()
torch.mps.synchronize()
return out, torch.mps.driver_allocated_memory() - base


def _record(
family,
px,
dtype,
tokens,
heads,
prefill,
cos,
grown = None,
):
elements = heads * tokens * tokens
line = (
f"MPS-ATTN torch={torch.__version__} family={family} px={px} dtype={str(dtype).split('.')[-1]} "
f"tokens={tokens} score_elements={elements} (2^{math.log2(elements):.2f}) prefill={prefill} "
f"cos={cos:.6f}" + ("" if grown is None else f" grown_mib={grown / 2**20:.0f}")
)
print(line)
warnings.warn(line, UserWarning, stacklevel = 2)


TOL = {torch.float32: 0.99999, torch.float16: 0.9995, torch.bfloat16: 0.998}


@mps
@pytest.mark.parametrize("family", sorted(FAMILIES))
@pytest.mark.parametrize("px", (256, 512))
@pytest.mark.parametrize("dtype", (torch.float32, torch.float16, torch.bfloat16), ids = str)
def test_small_sizes_match_cpu(family, px, dtype):
heads, head_dim, text = FAMILIES[family]
tokens = _tokens(px, text)
q, k, v = _qkv(heads, tokens, head_dim, dtype)
out = _mps_attention(q, k, v).cpu()
prefill = attention.mps_prefill_attention(*_dev(q, k, v))
rows = torch.arange(0, tokens, max(1, tokens // 256))
picked = list(range(heads))
ref = _reference_rows(q, k, v, picked, rows)
cos = _cos(out[:, picked][:, :, rows], ref)
_record(family, px, dtype, tokens, heads, prefill, cos)
assert bool(torch.isfinite(out).all())
assert cos >= TOL[dtype]


@mps
def test_key_padding_mask_matches_cpu():
"""Z-Image pads its caption and masks the padding with a bool key mask."""
heads, head_dim, text = FAMILIES["z-image"]
tokens = _tokens(512, text)
q, k, v = _qkv(heads, tokens, head_dim, torch.bfloat16)
mask = torch.ones((1, 1, 1, tokens), dtype = torch.bool)
mask[..., -text // 2 :] = False
out = _mps_attention(q, k, v, attn_mask = mask.to(DEVICE)).cpu()
ref = torch.nn.functional.scaled_dot_product_attention(
q.double(), k.double(), v.double(), attn_mask = mask
)
cos = _cos(out, ref)
_record("z-image+mask", 512, torch.bfloat16, tokens, heads, "n/a", cos)
assert cos >= TOL[torch.bfloat16]


@mps
def test_prefill_engagement_follows_the_torch_version():
heads, head_dim, text = FAMILIES["flux2-klein-4b"]
tokens = _tokens(1024, text)
q, k, v = _dev(*_qkv(heads, tokens, head_dim, torch.bfloat16))
prefill = attention.mps_prefill_attention(q, k, v)
assert prefill == (attention._version_tuple(torch.__version__)[:2] >= (2, 13))
_, grown = _driver_growth(lambda: _mps_attention(q, k, v))
scores = heads * tokens * tokens * 2
_record("flux2-klein-4b", 1024, torch.bfloat16, tokens, heads, prefill, float("nan"), grown)
if not prefill:
assert grown >= scores // 2
elif os.environ.get("UNSLOTH_MPS_EXPECT_PREFILL", "1") == "1":
# Set UNSLOTH_MPS_EXPECT_PREFILL=0 on a GPU without the features the kernel needs, to record only.
assert grown < scores // 4


def _large_cell(family, target_elements):
heads, head_dim, _ = FAMILIES[family]
tokens = int(math.ceil(math.sqrt(target_elements / heads)))
q, k, v = _qkv(heads, tokens, head_dim, torch.bfloat16, seed = 1)
out, grown = _driver_growth(lambda: _mps_attention(q, k, v))
out = out.cpu()
# The last heads sit at the largest offsets, where pytorch#179352 goes wrong first.
picked = sorted({0, heads // 2, heads - 2, heads - 1})
rows = torch.linspace(0, tokens - 1, 192).long()
ref = _reference_rows(q, k, v, picked, rows)
worst = min(_cos(out[:, [h]][:, :, rows], ref[:, [i]]) for i, h in enumerate(picked))
prefill = attention.mps_prefill_attention(*_dev(q, k, v))
_record(family, -1, torch.bfloat16, tokens, heads, prefill, worst, grown)
return worst


@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_past_the_studio_measured_threshold(family):
"""Just past where Studio saw wrong values on macOS 15 / torch 2.11: does every family hit it?"""
assert _large_cell(family, int(1.15 * STUDIO_WRONG_FROM)) >= TOL[torch.bfloat16]


@mps
@pytest.mark.skipif(not LARGE, reason = "UNSLOTH_MPS_LARGE_ATTENTION=1 or CI")
def test_past_the_upstream_threshold_on_the_prefill_kernel():
"""Above 2^32 elements only the prefill kernel fits a CI runner: it never builds the scores."""
heads, head_dim, _ = FAMILIES["qwen-image-2.1"]
probe = _dev(*_qkv(heads, 16, head_dim, torch.bfloat16))
if not attention.mps_prefill_attention(*probe):
pytest.skip(
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]
75 changes: 75 additions & 0 deletions tests/python/test_macos_torch213_pins.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.

"""The Apple Silicon torch 2.13 route in install.sh agrees with the pins Studio installs beside it."""

from __future__ import annotations
import re
import sys
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[2]
INSTALL_SH = (REPO_ROOT / "install.sh").read_text(encoding = "utf-8")


def _assignment(name: str) -> str:
match = re.search(rf'^{name}="([^"]*)"$', INSTALL_SH, re.MULTILINE)
assert match, name
return match.group(1)


def _ips():
sys.path.insert(0, str(REPO_ROOT / "studio"))
try:
import install_python_stack
finally:
sys.path.pop(0)
return install_python_stack


def _route_body() -> str:
match = re.search(
r'^if \[ -z "\$_PREV_TORCH_PIN" \] && \[ "\$_MACOS_NEW_INSTALL_ROUTE" = true \]; then\n(.*?)^fi$',
INSTALL_SH,
re.MULTILINE | re.DOTALL,
)
assert match
return match.group(1)


def test_macos_route_is_one_minor_with_its_torchvision():
assert _assignment("_MACOS_NEW_INSTALL_TORCH") == "torch>=2.13.0,<2.14.0"
# torchvision 0.N pairs with torch 2.(N - 15).
assert 'TORCHVISION_CONSTRAINT="torchvision>=0.28.0,<0.29.0"' in _route_body()
# torchaudio keeps the shared window: 2.11 is the last release and pairs with every newer torch.
assert "TORCHAUDIO_CONSTRAINT" not in _route_body()
assert _assignment("_TORCHAUDIO_CEILING") == "2.12.0"


def test_macos_preservation_ceiling_matches_cu130():
assert _assignment("_MACOS_TORCH_CEILING") == _assignment("_CU130_TORCH_CEILING") == "2.15.0"
assert _ips()._CU130_PRESERVE_TORCH_CEILING_MINOR == 15


def test_generic_ceiling_is_unchanged():
assert _assignment("_TORCH_CEILING") == "2.12.0"
assert _ips()._CUDA_TORCH_PKG_SPEC[0] == "torch>=2.4,<2.12.0"


def test_torchcodec_on_the_macos_route_is_abi_stable_and_macos_14():
ips = _ips()
for version in ("2.13.0", "2.14.1"):
assert ips._select_torchcodec_spec(version) == ips._TORCHCODEC_ABI_STABLE_SPEC
# 0.12+ wheels are macosx_14_0, which is the route's own macOS floor.
assert ips._TORCHCODEC_MACOS_14_ONLY_FROM == (0, 12, 0)
assert "-ge 14" in INSTALL_SH.split("_macos_torch213_host_ok() {", 1)[1].split("\n}", 1)[0]


def test_mflux_pin_floor_is_met_by_the_route():
# mflux 0.20.0+ declares torch>=2.13.0 (installed --no-deps); the route is what satisfies it.
pins = _ips()._MLX_DIFFUSION_PINS
assert pins and pins[0].startswith("mflux==")
version = tuple(int(p) for p in pins[0].split("==", 1)[1].split(".")[:2])
if version >= (0, 20):
floor = _assignment("_MACOS_NEW_INSTALL_TORCH").split(",", 1)[0]
assert floor == "torch>=2.13.0"
Loading