Skip to content

Studio: stop the SDPA probe reporting fused attention on MPS - #14488

Merged
danielhanchen merged 2 commits into
unslothai:mainfrom
Lyxot:fix/mps-sdpa-probe
Oct 22, 2026
Merged

danielhanchen merged 2 commits into
unslothai:mainfrom
Lyxot:fix/mps-sdpa-probe

Conversation

@Lyxot

@Lyxot Lyxot commented Oct 21, 2026

Copy link
Copy Markdown
Collaborator

Problem

Unsloth Studio decides whether diffusion attention is sub-quadratic by running a tiny SDPA call under torch.nn.attention.sdpa_kernel([backend]) for each backend. MPS ignores sdpa_kernel (and the torch.backends.cuda SDP toggles), so on Apple Silicon every backend "runs" and the probe reported flash / mem-efficient / cuDNN. As a result sdpa_subquadratic_confirmed(mps) was True and sdpa_math_only(mps) was False on every Mac, although MPS SDPA before torch 2.13 always materialises the full score matrix.

User-visible impact on a Mac (torch < 2.13):

  • A video generation that runs out of memory got the generic "device ran out of memory" message instead of the quadratic-attention diagnosis that names the real cause (resolution x frames, squared).
  • The load-time diffusion.attention.math_only warning never fired.
  • _quadratic_attention / _attention_scaling_known returned the wrong answer (no current Mac code path acts on them: the image activation guard skips unified memory, learned peaks and calibrated activations are CUDA-only).

Fix

MPS is no longer execution-probed. The answer comes from the torch build:

  • torch < 2.13, or PYTORCH_MPS_DISABLE_PREFILL_ATTENTION set to anything but "0" (torch's own rule): math only.
  • torch >= 2.13: flash + math. torch 2.13 added an MPS flash-style prefill kernel used for head_dim 32/64/72/80/96/128/256 with no mask or a bool / same-dtype mask, which covers the diffusion transformers Studio runs.

available_sdpa_kernels also stops filtering the MPS answer through torch.backends.cuda.*_sdp_enabled(), since MPS dispatch does not honour those toggles. CUDA, ROCm, XPU and CPU paths are unchanged.

Tradeoff: the probe is shape-less, so on torch >= 2.13 a model whose head_dim is outside the prefill set (or that passes a float mask of another dtype) is still quadratic but reported fused. On a Mac the only consequence is a missing diagnostic.

Validation

One SDPA call per fresh process, B=1 H=24 N=8192 bf16, torch.mps.driver_allocated_memory() growth (M3 Max):

torch 2.10.0  any head_dim / dtype / mask, FLASH-only included   +15368 MiB  (5.0x the 3072 MiB score matrix)
torch 2.13.0  D=64/128, fp16/bf16/fp32, no mask or bool mask     ~0 MiB
torch 2.14.1  same                                               ~0 MiB
torch 2.13/14 D=48, D=160, fp32 mask with bf16 q                 +15368 MiB
torch 2.14.1  enable_flash_sdp(False)                            ~0 MiB   (toggle ignored)
torch 2.14.1  PYTORCH_MPS_DISABLE_PREFILL_ATTENTION= "" / false / 1  +15368 MiB;  "0"  ~0 MiB

Z-Image-Turbo transformer forward on MPS, torch 2.10, bf16 (non-Qwen family, head_dim 128):

1024x1024   4224 tokens  +10956 MiB
1536x1536   9344 tokens  +51356 MiB   -> 4.69x memory for 2.21x tokens (quadratic predicts 4.89x)

The probe on the same machine (torch 2.10): before ["flash", "mem_efficient", "cudnn", "math"], _quadratic_attention False; after ["math"], _quadratic_attention True.

cd studio/backend
python -m pytest -q tests/test_diffusion_attention.py -k mps_answers

The new parametrized test covers torch 2.10 / 2.12 / 2.13 / 2.14, the env var values "0", "", "false", "1", asserts no SDPA call is made on MPS, and runs with flash_sdp_enabled() off. It fails if the MPS branch is removed, the version threshold moves to 2.12, the env check is dropped or narrowed to "1", the CUDA toggle filter is applied to MPS, or 2.13+ never reports fused.

test_a_hidden_xformers_is_not_reinstalled_in_the_same_process fails on this machine with and without this change.

MPS ignores torch.nn.attention.sdpa_kernel and the torch.backends.cuda SDP toggles, so the execution probe saw flash, mem_efficient, cudnn and math all run and reported sub-quadratic attention on every Mac. Answer MPS from the torch build instead: math only before torch 2.13 or when PYTORCH_MPS_DISABLE_PREFILL_ATTENTION is set to anything but "0", flash otherwise (torch 2.13 added an MPS prefill kernel for the head_dims diffusion transformers use).
@Lyxot
Lyxot requested a review from danielhanchen as a code owner October 21, 2026 10:47
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 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-21T19:28:09.573096Z 77f2414 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

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 7e194480ac

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

danielhanchen added a commit that referenced this pull request Oct 21, 2026
## Problem

Five checks fail on main, so the `Repo tests (CPU, studio)`, `Repo tests
(CPU, rest)` and `workflow-trigger lint` shards are red on every open PR
(for example #14472, #14482, #14488, #14490 and #14494). All five
reproduce on main `4d7ebf5cea`.

| Test | Introduced by | Fault |
|---|---|---|
|
`tests/security/test_lint_risky_loaders.py::test_the_tree_matches_the_baseline`
| #14437 | Baseline. Two new dynamic-import sites: `import_module` in
`studio/backend/core/rag/embeddings.py`, and a third
`import_from_string` in `unsloth/models/sentence_transformer.py`
(`_require_word_tokenizer`). Both are safe, see below. |
|
`tests/studio/test_tauri_branding_contract.py::test_desktop_surfaces_do_not_restore_studio_branding`
| #14473 | Product. "Studio" became "Unsloth Studio" in the Markdown
import errors and the Tauri webview reject message. The desktop contract
allows "Unsloth" there, never "Unsloth Studio". "Unsloth" meets both
#14473's rule (no bare "Studio") and this one. |
|
`tests/studio/test_usage_examples_model_source_contract.py::test_auto_switch_section_sits_above_the_usage_examples`
| #14455 | Test. The redesign moved the usage examples above the monitor
link on purpose, and its own `api-settings-tab.test.ts` pins that. |
|
`tests/studio/test_usage_examples_model_source_contract.py::test_monitor_can_unload_the_loaded_model`
| #14455 | Test. Unloading moved from a standalone button on the page
into the model picker's eject (`ApiModelLoadControls`). The `/unload`
path itself is unchanged. |
|
`tests/studio/test_settings_compact_overflow_contract.py::test_api_monitor_entries_and_expanded_text_can_shrink`
| #14455 | Test. Entry rows are now rounded cards (no `border-b`), and
the prompt/reply box's `rounded-lg` became conditional, so the class
literals the test matched are gone. The overflow guards themselves are
still in the source. |

## Fix

- **Risky loaders:** two baseline entries with reasons.
- `embeddings.py` imports only the three `sentence_transformers.models`
paths written out in a literal tuple, to wrap their `import_from_string`
with the trust gate.
- `_require_word_tokenizer` imports only after its caller has refused
any `tokenizer_class` outside `sentence_transformers.*`, and only dotted
identifiers.
- **Branding:** "Unsloth Studio" to "Unsloth" in those seven Markdown
import errors and the Rust reject message.
`conversation-markdown-import.test.ts` now matches `/Unsloth Markdown/`.
- **#14455 contracts:** rewritten to guard what the redesign keeps:
- the auto-switch section still follows the monitor link, and the usage
examples come before both;
- the page passes `unloadActiveModel` to the load controls as
`onUnloadActive`, and eject is withheld while `busy` (`modelLoading ||
unloading`, #11223's rule);
  - the `/unload` call still reads the internal id from status;
  - entry rows keep `w-full min-w-0`;
  - the prompt/reply box keeps `max-h-72 overflow-auto break-words`;
  - the model id keeps `min-w-0 break-all`.

## Verification

- The four Python files: 78 passed (5 failed on main).
- `studio/frontend/tests/conversation-markdown-import.test.ts`: 20
passed.
- Sabotage, each run against the rewritten tests, each failing exactly
one test:
- removing `min-w-0` from the entry row, or `break-words` from the text
box: the overflow test fails;
- dropping `unloading` from `busy`, or passing `onEject` while busy: the
unload test fails;
- putting the auto-switch section above the monitor link: the order test
fails.
@NilayYadav NilayYadav self-assigned this Oct 21, 2026
danielhanchen added a commit that referenced this pull request Oct 21, 2026
…utoopt parity checks (#14522)

## Problem

#14473 renamed user-facing "Studio" to "Unsloth" in the backend
messages, but three tests still expect the old wording. They fail on
main and on open PRs (for example #14494 and #14488):

| Test | Expects | Product now says |
|---|---|---|
|
`test_sandbox_linux.py::test_an_interpreter_symlinked_out_of_the_workdir_fails_the_call`
| `Python that runs Studio` | `Python that runs Unsloth`
(`sandbox_linux.py`) |
|
`test_diffusion_attention.py::test_a_hidden_xformers_is_not_reinstalled_in_the_same_process`
| `restart Studio` | `restart Unsloth` (`diffusion_attention.py`) |
| `test_diffusion_autoopt_parity.py` (two tests) | `the Studio fast step
that replays decode steps from tensors`, 16 times in
`fixtures/diffusion_autoopt_parity.json` | `the Unsloth fast step ...`
(`diffusion_capture_safe.py`) |

The rename was intended, so the tests are what is out of date.

## Fix

Test only. Both assertions and the 16 recorded reasons in the parity
fixture now use "Unsloth". Those 16 strings were the only "Studio" in
the fixture. Nothing else in it changes.

## Verification

- `test_sandbox_linux.py` and `test_diffusion_attention.py`: both target
tests fail on main and pass with this change.
- The one remaining local failure,
`test_active_attention_backend_reads_tuple_return`, is an `ImportError`
from this host's `huggingface_hub` and fails the same way on main.
- `test_diffusion_autoopt_parity.py` (CPU torch 2.10, diffusers
0.41.0.dev0):
  - with main's fixture: 2 failed, 1 passed;
  - with this change: 3 passed.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 77f2414f83

ℹ️ 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 Lyxot Oct 21, 2026
@NilayYadav

Copy link
Copy Markdown
Collaborator

Review + reproduction evidence

Pinned review: 77f2414f8392 (your 7e194480 plus a comment-only trim). No blocking findings.

I reproduced the probe and its two user-facing effects on the merge base 4962983 (Apple M5 Pro, macOS, torch 2.11.0, which is the band Mac installs get):

  • Before: the probe answers flash, mem_efficient, cudnn, math after 4 SDPA calls, while an SDPA call pinned to FLASH_ATTENTION still grows the driver allocation by 2560 MiB for a 512 MiB score matrix (B=1 H=8 N=4096 D=128 bf16). A tiny Flux load logs nothing, and a real MPS out-of-memory in attention ("Tried to allocate 12.00 GiB") turns into "Video generation failed. The device ran out of memory. Try a smaller resolution, fewer frames, or fewer steps."
  • PR head: the probe answers math with 0 SDPA calls, the load logs diffusion.attention.math_only: device=mps dtype=torch.bfloat16 kernels=math, and the same OOM gets the score-matrix explanation.

PR 14488 before/after: Settings > Logs filtered on diffusion.attention

  • torch 2.13.0 and 2.14.1 on the same Mac: the head answers flash, math and default SDPA grows 0 MiB; with PYTORCH_MPS_DISABLE_PREFILL_ATTENTION=1 it answers math and growth is 2560 MiB again, so the version and env rules match what torch actually does.
  • In a real Studio install on the same Mac, Settings > Logs filtered on diffusion.attention shows nothing on the merge base and the math_only warning on the PR after loading the same tiny Flux model.
  • CUDA is unchanged: on an L4 with torch 2.11.0+cu128, 9 of 9 dtype and toggle combinations give the same kernels, math-only and sub-quadratic answers before and after.
  • The tiny Flux render is pixel-identical before and after; the new test fails 7/7 on the merge base and passes on the head. The 8 red CI jobs on this PR are the same failures seen on unrelated PRs and on main pushes from the same hour.

Conclusion: real Mac defect, fixed, no regression found on CUDA or in the render path. A Mac-specific remedy line in the shared math-only message would be a nice follow-up.

@danielhanchen danielhanchen self-assigned this Oct 22, 2026
@danielhanchen
danielhanchen merged commit caf7fe7 into unslothai:main Oct 22, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 23, 2026
…othai#14941)

## 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 (unslothai#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:

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

```text
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)
```

```bash
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`.

---------

Co-authored-by: Daniel Han <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants