Repository navigation
Studio: stop the SDPA probe reporting fused attention on MPS - #14488
Conversation
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).
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. Nice work! 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". |
## 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.
…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.
[skip ci]
|
Codex Review: Didn't find any major issues. Chef's kiss. 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 + reproduction evidencePinned review: I reproduced the probe and its two user-facing effects on the merge base
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. |
…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]>

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 ignoressdpa_kernel(and thetorch.backends.cudaSDP toggles), so on Apple Silicon every backend "runs" and the probe reported flash / mem-efficient / cuDNN. As a resultsdpa_subquadratic_confirmed(mps)was True andsdpa_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):
diffusion.attention.math_onlywarning never fired._quadratic_attention/_attention_scaling_knownreturned 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:
PYTORCH_MPS_DISABLE_PREFILL_ATTENTIONset to anything but"0"(torch's own rule):mathonly.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_kernelsalso stops filtering the MPS answer throughtorch.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):Z-Image-Turbo transformer forward on MPS, torch 2.10, bf16 (non-Qwen family, head_dim 128):
The probe on the same machine (torch 2.10): before
["flash", "mem_efficient", "cudnn", "math"],_quadratic_attentionFalse; after["math"],_quadratic_attentionTrue.cd studio/backend python -m pytest -q tests/test_diffusion_attention.py -k mps_answersThe 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 withflash_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_processfails on this machine with and without this change.