Repository navigation
Studio: split large MPS attention calls into query chunks for every family on Apple Silicon - #18783
Conversation
…ake into query chunks torch below 2.13 runs every MPS SDPA call on the MPSGraph path, which returns wrong values (cosine 0) past about 0.9 * 2^29 score elements per call. Only Qwen-Image-2.1 was guarded; existing Apple Silicon homes keep their torch. Wrap scaled_dot_product_attention on Apple Silicon so those calls run in query-row chunks of at most 2^28 scores. Calls the prefill kernel takes, calls under the cap and non-MPS calls are unchanged. UNSLOTH_MPS_ATTENTION_GUARD=0 turns it off.
Codex Review Summary: ✅ CompletedThis 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 |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. 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". |
…MPS fallback runs on CPU tensors [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. 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". |
…ile and count broadcast K/V batch dims (#18979) ## Summary The Apple Silicon attention guard from #18783 replaces `F.scaled_dot_product_attention` for the whole process once an MPS image model loads. Two parts of the wrapper were not traceable by Dynamo, so any compiled caller on MPS paid for it even on calls far under the chunking threshold: 1. `chunk_rows` computed the batch size with `math.prod(int(d) for d in q_shape[:-2])`. Dynamo cannot pass a generator to `math.prod`, so `torch.compile(fullgraph=True)` failed on every MPS SDPA call (`Unsupported: Failed to convert args/kwargs to proxy`), and the default mode graph-broke there. 2. `stats["chunked_calls"] += 1` ran inside traced code. Dynamo guarded on the counter value, so every split call with an unchanged shape recompiled until `recompile_limit` (8) and then ran eager. Studio's own MPS image path is eager today (`supports_default_torch_compile=False` on the MPS target), so no shipped render was affected. This keeps the wrapper safe for any compiled code that runs in the same process. ## Changes - `studio/backend/core/_mps_sdpa_guard.py`: the leading-dim product is a plain loop with no `int()` casts, so sizes stay symbolic under `dynamic=True`. The counter only moves in eager (`torch.compiler.is_compiling()`). - The score count now uses the broadcast Q / K batch dims (and Q's head count under GQA). Before, a K / V batch wider than Q's was not counted, so such a call could pass the cap unsplit. - Eager outputs are unchanged. The split path, mask handling and kill switch are the same. ## Tests New tests in `studio/backend/tests/test_mps_large_attention_guard.py` use CPU tensors routed through the MPS branch, the same technique as the existing tests: | Test | main | this branch | |---|---|---| | `fullgraph=True` below, at and above the cap (4 sizes) | fail | pass | | `dynamic=True` fullgraph, 4 sizes under the cap, one graph | fail | pass | | 12 identical split calls under `error_on_recompile`, one graph | fail | pass | | K / V batch wider than Q is counted and split | fail | pass | `test_mps_large_attention_guard.py`, `test_mps_attention_families.py` and `test_mps_attention_guard_on_load.py`: 36 passed (the Mac-only cases skip on Linux). The guard file passes on torch 2.6.0 and 2.12.1. On torch 2.11.0 the standalone repro gives the same results (fullgraph traces, one graph for 12 repeated split calls). Not covered here: a real Metal run. The new code makes no kernel calls, but the macOS 15 runner on staging CI should run `tests/test_mps_attention_families.py` to confirm the large-call parity still holds.
Below torch 2.13, every MPS
scaled_dot_product_attentioncall runs on the MPSGraph path, which builds the full score matrix. Past about 0.9 * 2^29 score elements per call (macOS 15), that path returns wrong values: cosine 0.000 against an fp64 reference (pytorch#179352). #18428 moved new Apple Silicon installs to torch 2.13, whose prefill kernel never builds the scores. Existing homes keep their torch unless the user runs a repair withUNSLOTH_TORCH_UPGRADE=1, and only Qwen-Image-2.1 had a bound of its own. A single 1024 px FLUX call (24 heads x 4608 tokens, 2^28.92 elements) is right at that edge. Z-Image, FLUX.2 klein, SD3.5 and Qwen-Image go past it at the resolutions Studio offers.Change
core/_mps_sdpa_guard.py. On Apple Silicon with MPS it wrapstorch.nn.functional.scaled_dot_product_attention. An MPS call that has more than 2^28 score elements (the bounddiffusion_qwenimage21_math.MPS_SCORE_ELEMENTSalready uses) and that the prefill kernel would not take (mps_prefill_attention) runs in query-row chunks, which are then concatenated.is_causalbecomes the matching top-left-aligned bool mask for each chunk.scale,dropout_pandenable_gqaare passed through.UNSLOTH_MPS_ATTENTION_GUARD=0turns it off.diffusion_attention._apply_attention_backend_implinstalls it for MPS image and video loads. The training worker does not need it: its Apple Silicon fallback without a usable MLX stack runs on CPU tensors, where the guard never splits. It is idempotent and a no-op off macOS.diffusers' native backend, its SDPA processors and transformers all look up the function on every call, so this covers every family. Qwen-Image-2.1 keeps its own bounded processor (segmented prefill, cached decode). Its calls are already under the cap, so they pass straight through.
Tests
tests/test_mps_attention_guard_on_load.py(CPU): an MPS load wraps SDPA once, the wrapped function stays bit-identical off MPS, and CPU / CUDA loads keep the stock function. Fails on main, passes here.tests/test_mps_large_attention_guard.py(CPU, with CPU tensors standing in for MPS and a small cap), 25 tests:[B,H,Sq,Sk],[B,1,Sq,Sk],[1,1,1,Sk],[B,1,1,Sk],[Sq,Sk]and[1,Sk].is_causalwith Sq = Sk, Sq > Sk and Sq < Sk, for GQA with a custom scale, for 3-D inputs, and through autograd.tests/test_mps_attention_families.py:test_the_guard_fixes_the_studio_measured_thresholdruns the same past-threshold cells astest_past_the_studio_measured_threshold, with the guard installed. It asserts that the guard split the call on torch < 2.13 and left it alone on 2.13+.test_differential.py: DISCRIMINATING, head_fail=0.tests/test_diffusion_attention*.py,tests/test_rocm_windows_wide_head_sdpa.pyand the new files: 557 passed, 2 skipped on CPU.macOS 15 runner (GitHub Apple Silicon, main vs this branch, same job)
Past-threshold cells (2^29.05 score elements, bf16, worst cosine against fp64 over 4 heads x 192 rows; growth is the MPS driver allocation during the call):
chunked_calls=1). On torch 2.13 it split none (chunked_calls=0), because the prefill kernel takes them.Not proven here