Skip to content

Studio: split large MPS attention calls into query chunks for every family on Apple Silicon - #18783

Merged
danielhanchen merged 3 commits into
mainfrom
nov21-sdcpp-mac-studio
Nov 22, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
nov21-sdcpp-mac-studio

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

Below torch 2.13, every MPS scaled_dot_product_attention call 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 with UNSLOTH_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

  • New core/_mps_sdpa_guard.py. On Apple Silicon with MPS it wraps torch.nn.functional.scaled_dot_product_attention. An MPS call that has more than 2^28 score elements (the bound diffusion_qwenimage21_math.MPS_SCORE_ELEMENTS already uses) and that the prefill kernel would not take (mps_prefill_attention) runs in query-row chunks, which are then concatenated.
    • Every query row is independent, so the result is the same as one call.
    • Masks whose query axis is the full length are sliced with the rows. is_causal becomes the matching top-left-aligned bool mask for each chunk.
    • scale, dropout_p and enable_gqa are passed through.
    • Calls under the cap, calls the prefill kernel serves (torch 2.13+) and all non-MPS calls go to SDPA unchanged.
    • UNSLOTH_MPS_ATTENTION_GUARD=0 turns it off.
  • diffusion_attention._apply_attention_backend_impl installs 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:
    • The split matches one fp64 call for bool and float masks of shapes [B,H,Sq,Sk], [B,1,Sq,Sk], [1,1,1,Sk], [B,1,1,Sk], [Sq,Sk] and [1,Sk].
    • It also matches for is_causal with Sq = Sk, Sq > Sk and Sq < Sk, for GQA with a custom scale, for 3-D inputs, and through autograd.
    • Calls under the cap, prefill calls and off-MPS calls are untouched.
    • The install gating works.
    • Mutation check: dropping the mask slicing fails 6 tests, and dropping the causal mask fails 3.
  • tests/test_mps_attention_families.py: test_the_guard_fixes_the_studio_measured_threshold runs the same past-threshold cells as test_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.py and 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):

family torch 2.11 main torch 2.11 this PR torch 2.13 main torch 2.13 this PR
z-image cos 0.000000, 2436 MiB cos 0.999999, 204 MiB cos 0.999992, 1024 MiB cos 0.999992, 1024 MiB
flux2-klein-4b cos 0.000000, 2084 MiB cos 0.999999, 1032 MiB cos 0.999992, 1024 MiB cos 0.999992, 1024 MiB
qwen-image-2.1 cos 0.000000, 2090 MiB cos 0.999999, 1024 MiB cos 0.999992, 1024 MiB cos 0.999992, 1024 MiB
sd3.5-large cos 0.000000, 2078 MiB cos 0.999999, 1032 MiB cos 0.999995, 1024 MiB cos 0.999995, 1024 MiB
  • On torch 2.11, the guard split each of these calls once (chunked_calls=1). On torch 2.13 it split none (chunked_calls=0), because the prefill kernel takes them.
  • The head selection was 79 passed on both torch versions: the small-size cells for 8 families x 2 sizes x 3 dtypes, the key-padding mask cell, the 25 guard tests and the guarded large cells.
  • On main, torch 2.11 failed the 4 past-threshold cells, and torch 2.13 passed them.

Not proven here

  • These are GitHub's virtual Apple Silicon runners. They prove correctness, not speed on real Macs. Chunking can add some per-call overhead on torch 2.11, and that was not timed.
  • No full image render on torch 2.11 was compared before and after. The proof is the attention call at each family's shape.
  • macOS 14 and torch versions between 2.11 and 2.13 (2.12) did not run.

…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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-21T19:32:07.001645Z bd0ee08 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: dccb34d12f

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

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: bd0ee08d45

ℹ️ 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
danielhanchen merged commit 2d43133 into main Nov 22, 2026
@danielhanchen
danielhanchen deleted the nov21-sdcpp-mac-studio branch November 22, 2026 01:57
danielhanchen added a commit that referenced this pull request Nov 23, 2026
…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.
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.

1 participant