Skip to content

Studio: use the MPS SDPA prefill kernel per call on torch 2.13+ - #14941

Merged
danielhanchen merged 7 commits into
unslothai:mainfrom
Lyxot:feat/mps-sdpa-prefill
Oct 23, 2026
Merged

danielhanchen merged 7 commits into
unslothai:mainfrom
Lyxot:feat/mps-sdpa-prefill

Conversation

@Lyxot

@Lyxot Lyxot commented Oct 23, 2026

Copy link
Copy Markdown
Collaborator

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:

  • The capability answer (Studio: stop the SDPA probe reporting fused attention on MPS #14488) is per build, not per shape: on torch >= 2.13 a family whose head_dim is outside the prefill set is reported fused although it still materialises the scores, which feeds the load-time math-only warning, _quadratic_attention and the video OOM diagnosis.
  • Qwen-Image-2.1's bounded attention always splits on MPS to keep each call under 2^28 score elements, even when the call would run on the prefill kernel: 33 calls instead of 1 per attention at 2048x2048.
  • VAE attention on MPS was never chunked: fused_sdpa_available treated 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 and PYTORCH_MPS_DISABLE_PREFILL_ATTENTION unset 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_confirmed and warn_if_sdpa_math_only take the family's DiT head dims, and the load warning, _quadratic_attention and the video OOM guards pass them.
  • Qwen-Image-2.1's bounded processor runs a prefill-eligible call unsplit; everything else keeps the bounded split.
  • VAE attention chunking installs on MPS too, with fused_sdpa_available asking mps_prefill_attention and a 256 MB default score budget on MPS (ROCm keeps 1024 MB; UNSLOTH_VAE_ATTN_CHUNK_MB overrides 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, --stable timing (median of 7).

Qwen-Image-2.1, one real-size attention module (32 heads, head_dim 128), Studio's processor:

torch    case     res    before (split): calls / MiB / ms   after: calls / MiB / ms   output
2.10.0   decode   2048   33 / 5136 / 1701.7                  33 / 5136 / 1703.7        identical
2.14.1   decode   1024    3 /    0 /   81.3                   1 /    0 /   80.7        identical
2.14.1   decode   2048   33 / 1024 /  682.9                   1 / 1024 /  607.5        identical
2.14.1   prefill  2048   34 / 1024 /  667.7                   2 / 1024 /  593.5        identical
2.15.0   decode   2048   33 / 1024 /  682.3                   1 / 1024 /  606.9        identical
2.15.0   prefill  2048   34 / 1024 /  666.8                   2 / 1024 /  594.0        identical

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):

VAE          res    unchunked MiB / s   chunked MiB / s   output
FLUX.1       1024   8195 / 1.45         6659 / 1.36       bitwise equal
FLUX.1       2048   9219 / 7.49         7683 / 7.54       bitwise equal
FLUX.2       1024   8195 / 1.38         6659 / 1.35       bitwise equal
Qwen-Image   1024   unchanged (1024-token tiles, nothing over budget)
cd studio/backend
python -m pytest -q tests/test_diffusion_attention.py tests/test_diffusion_qwenimage21_math.py tests/test_diffusion_vae_attn_chunked.py

The 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 current main.

Lyxot added 3 commits October 23, 2026 14:53
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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-23T16:10:43.364179Z 7e4976c Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: fa982c973a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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".

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: f16482ed14

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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".

@Lyxot

Lyxot commented Oct 23, 2026

Copy link
Copy Markdown
Collaborator Author

Review and CI summary for f16482ed14

  • Codex: Didn't find any major issues on f16482ed14 (round 3).
  • CI: staging run with the same head and base in a fork (Lyxot/unsloth#195): 14 workflows passed, 1 skipped (Kaggle GPU), 2 failed, none from this change:
    • Backend CI: Python 3.13 a-k shard 33,022 passed, 1 failed, test_diffusion_offload_step_graphs.py::test_releasing_an_offloaded_step_graph_frees_its_capture_stream_workspace, which also fails on current main; the CPU repo-test shard fails 19 core save / push / Triton tests outside studio/.
    • Core: the _unmerge_flags_on_error failures in tests/saving/test_save_method_lora_routing.py (also on main) and unsloth_zoo CPU tests at its pinned revision.
    • The earlier run at fa982c973a additionally failed unrelated frontend / infra jobs (startup bundle budget 0.2 KB over, also on main; UI parity; apt and agent-CLI install timeouts); this PR changes no frontend code.
  • Changed during review (tests only, no production change):
    • fa982c973a: two sdpa_math_only test doubles in test_diffusion_backend.py now accept the head-dim argument (Codex P1).
    • f16482ed14: test_family_head_dims_narrow_the_mps_answer counts only the math-only warning. Without diffusers installed (as on the CI runner) the load also logs an unrelated "bounded Qwen-Image-2.1 math attention unavailable" warning, which the old assertion took for the math-only diagnosis.

@danielhanchen danielhanchen self-assigned this Oct 23, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 7e4976ca45

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from Lyxot Oct 23, 2026
@unslothai unslothai deleted a comment from Lyxot Oct 23, 2026
@unslothai unslothai deleted a comment from Lyxot Oct 23, 2026
@unslothai unslothai deleted a comment from Lyxot Oct 23, 2026
@danielhanchen

Copy link
Copy Markdown
Member

pre-commit.ci run

@danielhanchen
danielhanchen merged commit 60c7715 into unslothai:main Oct 23, 2026
35 of 42 checks passed
danielhanchen added a commit to unslothai/unsloth-zoo that referenced this pull request Oct 23, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants