Repository navigation
Studio MPS: keep the large-attention guard traceable under torch.compile and count broadcast K/V batch dims - #18979
Merged
Merged
Conversation
The MPS SDPA guard from #18783 wraps F.scaled_dot_product_attention for the whole process on Apple Silicon. Two parts of it were not Dynamo friendly: - chunk_rows used math.prod over a generator, which Dynamo cannot trace, so fullgraph=True failed on every MPS call, including calls under the cap. - stats["chunked_calls"] += 1 ran inside traced code, so Dynamo guarded on the counter value and recompiled on every split call until recompile_limit. The shape arithmetic is now plain loops with no int() casts (sizes stay symbolic) and the counter only moves in eager. The score count also uses the broadcast Q / K batch dims, since SDPA builds that many score matrices when K / V carry a wider batch than Q. Eager outputs are unchanged.
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. |
Member
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. Swish! 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". |
danielhanchen
added a commit
that referenced
this pull request
Nov 23, 2026
…cess, INT8 attention and MPS guard changes (#19005) ## Summary Follow-ups to #18965, #18968, #18979 and #18981 from a recheck of the merged kernel and compile changes. There is one commit per PR. Each fix is small and backwards compatible. The default bf16 / fp32 paths produce the same outputs as before. ### #18965: Windows ROCm per-tap Conv3d - Under CPU bf16 autocast, fp32 inputs came back as fp32 instead of the autocast dtype. Autocast calls now stay on stock `Conv3d`; bf16, fp16 and fp32 calls outside autocast keep the per-tap path. fp16 stays on it on purpose: on Windows gfx1151 the real LTX-2.3 fp16 decode is finite there, and stock `Conv3d` was 2.4x slower (35.7 s vs 87.0 s) with a 7.1 GiB higher peak. - `torch.compiler.is_compiling()` is now checked before the env switch. Before this, flipping `UNSLOTH_VIDEO_VAE_ROCM_PERTAP` inside a compiled region added an env guard and forced a recompile. ### #18968: Lanczos reference preprocess - The int32 guard bounds a single image. The identity-resize and vertical-first normalize launches run flat over the whole NHWC batch, so a `[24, 8192, 8192, 3]` batch wrapped the int32 index. `_normalize_rgb` now widens the program offset to int64 before the multiply. The TTIR now shows an `i64` multiply and `i64` pointer offsets. - If the load-time probe hit a transient OOM, GPU reference preprocessing stayed off on that device until restart. Now an OOM takes the CPU path for that call only, and the next request probes again. Other probe failures are still cached. ### #18981: INT8 attention kernel switches - Flipping the residual-fold, sink-order or native-P switch built a new launch plan. The plan's `decision` key left the switches out, so the new kernel reused the old kernel's accuracy and timing verdict without racing. The decision key now carries the same switch tuple as the plan key. ### #18979: MPS large-attention guard - The prefill check parsed `torch.__version__` with `re.match`. On a cold regex cache, Dynamo traced into the pattern compiler and failed `fullgraph=True`. The pattern is now compiled at import. ## Tests Each new test fails on `origin/main` and passes here: - `test_video_vae_rocm_pertap.py`: `test_autocast_keeps_stock_output_dtype`, `test_compiled_kill_switch_flip_does_not_recompile` (plus `test_fp16_outside_autocast_still_takes_pertap`) - `test_diffusion_ref_preprocess.py`: `test_batched_normalize_uses_64_bit_offsets`, `test_probe_oom_is_not_cached` - `test_diffusion_int8_attention_resid_fold.py`: `test_a_flipped_switch_races_its_own_kernel` - `test_mps_large_attention_guard.py`: `test_cold_prefill_check_traces_under_fullgraph` The touched suites and their neighbours (per-tap VAE, reference preprocess, MPS guard and families, ROCm contiguous q/k/v and k/v, CUTLASS race key, attention install, every INT8 attention suite) give 657 passed, 175 skipped (GPU / Mac only) on Linux CPU, torch 2.12.1, Triton 3.7.1. ## Not changed - #18966: the 2,560-token q/k/v gate splits a dynamic range into two graphs. That is bounded: 8 lengths from 1,024 to 4,096 under `fullgraph=True, dynamic=True` compiled 2 graphs. Studio's trainer never marks a dynamic range across the threshold. - #18979: over-cap query lengths still specialize the chunk loop under compile. Studio never compiles on MPS (training compiles on CUDA only, and the MPS target defaults to eager). ## GPU, Windows ROCm and Mac checks Same host and job for both arms, base = the merge base. | platform | check | base | this PR | |---|---|---|---| | A100 40 GB | Lanczos normalize of a `[24, 8192, 8192, 3]` uint8 batch | illegal memory access | 24 of 24 images equal to the torch reference | | A100 40 GB | real OOM in the load-time probe, then memory freed | GPU path off for the process | probes again, GPU path on | | A100 40 GB | GPU Pillow parity, 6 sizes; INT8 `-m gpu` tests | 6/6; 6 passed | 6/6; 6 passed | | L4 | flip the residual-fold switch in one loaded process | 1 race, same decision key | 2 races, keys differ | | Windows gfx1151 | bf16 1920x1088x121 LTX-2.3 decode | 10 per-tap calls | 10 per-tap calls, bit-identical, time within the base A/A spread | | macos-15 | MPS guard suites with `UNSLOTH_MPS_LARGE_ATTENTION=1` | 4 failed, 90 passed | same 4 failed (stock attention past the threshold, the bug the guard exists for), 92 passed | On Metal, a V batch wider than Q and K does not broaden the attention, so the guard keeps counting Q and K only.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
The Apple Silicon attention guard from #18783 replaces
F.scaled_dot_product_attentionfor 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:chunk_rowscomputed the batch size withmath.prod(int(d) for d in q_shape[:-2]). Dynamo cannot pass a generator tomath.prod, sotorch.compile(fullgraph=True)failed on every MPS SDPA call (Unsupported: Failed to convert args/kwargs to proxy), and the default mode graph-broke there.stats["chunked_calls"] += 1ran inside traced code. Dynamo guarded on the counter value, so every split call with an unchanged shape recompiled untilrecompile_limit(8) and then ran eager.Studio's own MPS image path is eager today (
supports_default_torch_compile=Falseon 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 noint()casts, so sizes stay symbolic underdynamic=True. The counter only moves in eager (torch.compiler.is_compiling()).Tests
New tests in
studio/backend/tests/test_mps_large_attention_guard.pyuse CPU tensors routed through the MPS branch, the same technique as the existing tests:fullgraph=Truebelow, at and above the cap (4 sizes)dynamic=Truefullgraph, 4 sizes under the cap, one grapherror_on_recompile, one graphtest_mps_large_attention_guard.py,test_mps_attention_families.pyandtest_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.pyto confirm the large-call parity still holds.