Repository navigation
Studio: use the MPS SDPA prefill kernel per call on torch 2.13+ - #14941
Conversation
torch 2.13 added an MPS SDPA prefill kernel that never builds the score matrix, but only for long queries, head dims 32/64/72/80/96/128/256, fp32/fp16/bf16, and masks that are bool or the query's dtype; every other call still goes through the MPSGraph path that materialises it. Add `mps_prefill_attention`, a per-call predicate that mirrors torch's MPS dispatch (including PYTORCH_MPS_DISABLE_PREFILL_ATTENTION and the grad rule), and let `sdpa_math_only`, `sdpa_subquadratic_confirmed` and `warn_if_sdpa_math_only` take the family's head dims, so a family whose head dim has no prefill instance is reported as math-only on MPS even on torch 2.13+. The load-time warning and `_quadratic_attention` pass the denoiser's head dims; video records them in the request shape so the OOM diagnosis answers for the family that ran. Non-MPS devices and torch < 2.13 answer exactly as before.
On Apple MPS the bounded Qwen-Image-2.1 processor splits every attention call by a score budget and an MPSGraph element cap, because the MPSGraph path builds the full score matrix. On torch 2.13+ the prefill kernel serves every call this model makes (head dim 128, bool or no mask) without building it, so the split only adds calls. Decide per call: a call `mps_prefill_attention` accepts runs as one dispatch, the same call the stock processor makes; anything else, and every call on older torch or with the prefill kernel disabled, keeps the split. ROCm is unaffected. Measured on an M3 Max, macOS 26.5.1, one real-size attention module: torch 2.14.1 / 2.15.0 output is bitwise equal to the stock processor and to the split path, driver memory is unchanged, and a 2048x2048 call takes 1 dispatch instead of 33 and is about 12% faster; torch 2.10 runs the identical split as before.
VAE mid-block attention is single-head with head dim 384 / 512, which no MPS fused kernel serves (torch 2.13+'s prefill kernel stops at 256), so it always runs on the MPSGraph path that holds several score-sized buffers. Studio tiles the VAE on MPS, but a FLUX.1 / SDXL / FLUX.2 tile is still one 16384-token attention: 1 GiB of fp32 scores, exactly the 1024 MB chunk budget, so the existing ROCm query chunking would not split it. Install the existing chunking on MPS targets too, with a 256 MB default budget there (ROCm keeps 1024 MB; UNSLOTH_VAE_ATTN_CHUNK_MB still overrides both), and let `fused_sdpa_available` answer MPS calls from the prefill-kernel rules instead of treating every non-CUDA call as fused. Splitting unmasked query rows is exact. Measured on an M3 Max (macOS 26.5.1, torch 2.10, bf16) through Studio's tiled decode: VAE decode driver-memory growth drops from 8195 to 6659 MiB at 1024x1024 and from 9219 to 7683 MiB at 2048x2048 for the FLUX.1 VAE (FLUX.2 the same), wall time unchanged, output bitwise identical. Qwen-Image-family VAEs tile at 1024 tokens and are unchanged.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
Review and CI summary for
|
[skip ci]
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
pre-commit.ci run |
…A router chain (#2042) In unsloth's `Core zoo (HF=default + TRL=default)` job, `tests/test_pad_token_resize_not_inference.py::test_pad_token_resize_under_inference_mode_is_trainable` fails with `RecursionError: maximum recursion depth exceeded`. It happened on unslothai/unsloth#14941 and again on a staging run of unslothai/unsloth#14991. The test passes on its own. The traceback alternates between `_sdpa_maybe_muse_glimmer_banded` and `_sdpa_maybe_flash_sliding`: the two SDPA routers had ended up wrapping each other. ## Cause Each router guards against re-wrapping by reading a sentinel off the installed `ALL_ATTENTION_FUNCTIONS["sdpa"]` entry. When the Muse Glimmer router wraps gemma-4's, it copies `_unsloth_gemma4_flash` onto itself, so gemma-4 still sees its own sentinel on the next pass. `test_patch_preserves_wrapped_router_sentinels` cleans up with `vars(mg._sdpa_maybe_muse_glimmer_banded).pop("_unsloth_gemma4_flash", None)`. That is fine in a fresh process. But when the process has already installed the real chain (unsloth's import does), it strips the real sentinel. The next `TEMPORARY_PATCHES` pass then wraps gemma-4 around the Muse Glimmer router while the Muse Glimmer router still wraps gemma-4, so any SDPA model recurses. Reproduced locally: - run `tests/test_muse_glimmer_banded_attention.py`, then a test that re-runs `patch_gemma4_flash_sliding()` and `patch_muse_glimmer_banded_sliding_attention()`; - after that, `gf._ORIG_SDPA[0] is mg._sdpa_maybe_muse_glimmer_banded` and `mg._ORIG_SDPA[0] is gf._sdpa_maybe_flash_sliding`. Production does not strip the sentinel, so this is test isolation only. ## Fix - The sentinel test snapshots the wrapper's attributes and restores them exactly, instead of popping one. - New `test_sentinel_test_leaves_a_live_chain_intact`: 1. installs the real chain the way unsloth does, with gemma-4's router under the Muse Glimmer one; 2. runs the sentinel test inside it; 3. runs both patches again, and asserts neither router re-wrapped. ## Verification - `tests/test_muse_glimmer_banded_attention.py`, `tests/test_gemma4_flash_sliding.py` and `tests/test_pad_token_resize_not_inference.py`: 23 passed, 1 skipped. - The muse-then-repatch sequence above no longer produces a cycle. - Sabotage check: putting the `pop` back fails the new test.
Problem
torch 2.13 added a flash-style MPS SDPA prefill kernel (and an MPP variant from 2.14) that never materialises the score matrix. Unsloth Studio's MPS attention handling did not take advantage of it per call:
_quadratic_attentionand the video OOM diagnosis.fused_sdpa_availabletreated every non-CUDA device as fused, and VAE attention (single head, head_dim 384-512) is never prefill-eligible. FLUX.1 / FLUX.2 / SDXL VAE tiles are 128 latents, one 16384-token attention per tile, 1 GiB of fp32 scores.Audit of every attention call of the supported image / video families as Studio runs them on MPS: every DiT / U-Net call is already prefill-eligible (bf16, head_dim 64/96/128/256, no / bool / same-dtype masks, no grad) except calls with 8 or fewer query rows (short Qwen-Image-2.1 edit text segments, very short LTX-2 audio), which are tiny. No VAE attention is eligible. So there is no mask or layout change to make.
Fix
mps_prefill_attention(query, key, value, attn_mask, seq_dim)mirrors torch 2.13-2.15's MPS dispatch per call: MPS device, torch >= 2.13 andPYTORCH_MPS_DISABLE_PREFILL_ATTENTIONunset or"0", fp32/fp16/bf16, mask none / bool / q's dtype, no grad through the inputs, more than 8 query rows, q and v head_dim equal and in {32, 64, 72, 80, 96, 128, 256}.sdpa_math_only,sdpa_subquadratic_confirmedandwarn_if_sdpa_math_onlytake the family's DiT head dims, and the load warning,_quadratic_attentionand the video OOM guards pass them.fused_sdpa_availableaskingmps_prefill_attentionand a 256 MB default score budget on MPS (ROCm keeps 1024 MB;UNSLOTH_VAE_ATTN_CHUNK_MBoverrides both). CUDA and ROCm behaviour is unchanged.On torch 2.13 with macOS 26: pytorch#191794 fixes the MPP variant only; v2.13.0 has no MPP code and the fix is in v2.14.0. Measured on macOS 26.5.1, 2.13 prefill is within about one bf16 ulp of an fp32 reference (head dims 32-256, bf16/fp16, odd lengths, bool masks: max abs error 0.0079 bf16 vs 0.0019 on 2.14/2.15), so 2.13 needs no special case.
Validation
M3 Max, macOS 26.5.1, random-init weights from real configs, bf16, driver memory growth per fresh process,
--stabletiming (median of 7).Qwen-Image-2.1, one real-size attention module (32 heads, head_dim 128), Studio's processor:
On 2.14 / 2.15 the unsplit output equals stock diffusers' processor bitwise (decode and segmented prefill, 1024 and 2048); torch 2.10 is unchanged.
Wan 2.1 one real-width block (12 heads, head_dim 128), 832x480x17 frames: torch 2.10 +6998 MiB / 195.0 ms, torch 2.14.1 / 2.15.0 0 MiB / ~107 ms, with Studio's per-family answer math-only on 2.10 and fused on 2.14+ (and math-only for a head_dim 160 family).
VAE decode through Studio's MPS install (torch 2.10, tiled as Studio runs it):
cd studio/backend python -m pytest -q tests/test_diffusion_attention.py tests/test_diffusion_qwenimage21_math.py tests/test_diffusion_vae_attn_chunked.pyThe tests cover the per-call predicate against torch's dispatch rules (both
[B, H, S, D]and[B, S, H, D]layouts), the family head-dim narrowing through the warning and_quadratic_attention, the video OOM guards receiving the head dims, Qwen-Image-2.1 running prefill-eligible calls unsplit (bitwise equal to stock, segmented and cached decode included), and the MPS VAE chunking install, budget and fused query; hand-written mutations of each rule are caught.Attention, Qwen-Image-2.1, VAE chunking, ROCm flash, learned-peaks, video backend and speed test files: 1190 passed; the 4
test_h3_modular_load_*failures also fail on currentmain.