Repository navigation
Studio ROCm VAE attention: math SDPA in the VAE's bf16/fp16 dtype, not an fp32 upcast - #17252
Merged
Merged
Conversation
…not an fp32 upcast No fused SDPA on ROCm takes head dim 384 / 512, so VAE mid-block attention runs the math path, which upcasts q / k / v and the full score matrix to fp32 by default. Scope allow_fp16_bf16_reduction_math_sdp to those calls (fp32 GEMM accumulation is kept) and restore it after. UNSLOTH_VAE_ATTN_HALF_MATH=0 keeps the fp32 upcast.
Member
Author
|
@codex review |
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: Didn't find any major issues. Bravo. 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
to danielhanchen/unsloth-staging-2
that referenced
this pull request
Nov 10, 2026
…the global flag (unslothai#17350) ## Summary The ROCm VAE attention half-reduction math from unslothai#17252 now runs per call and no longer touches the process-wide `torch.backends.cuda.allow_fp16_bf16_reduction_math_sdp` flag. On gfx1151 the speed-up stays the same and outputs are bit-identical to before (results below). `UNSLOTH_VAE_ATTN_HALF_MATH=0` still keeps the fp32 upcast. ## Root cause unslothai#17252 added `half_reduction_math()`. This helper saved the flag, set it to `True` around the VAE SDPA call, then restored the saved value. The flag is stored in `at::globalContext()`, so every thread in the process shares it: - Image and video generation use separate locks, so two decodes can run at once. With two overlapping scopes, the restores can happen in the wrong order: A enters (saves `False`), B enters (saves `True`), A exits (sets `False` while B is still inside), B exits (sets `True`). The flag then stays `True` after both calls have finished. - While a scope is active, any other math SDPA call in the process runs with reduced precision. On CPU, a bf16 math SDPA call made after the leak changed 2661 of 4096 output elements. ## Fix - New `half_math_sdpa(q, k, v, scale)` runs the same ATen ops as PyTorch's math SDPA with the flag on, in the same order and in the input dtype: scale q and k by sqrt(scale), bmm, `_safe_softmax`, bmm. On torch < 2.5, where `_safe_softmax` does not exist, it uses plain softmax. - The VAE attention mode calls this function directly for the half path, both chunked and unchunked. The global flag is never read or written. - Under autocast, inputs are first cast to the autocast dtype, as autocast would do for SDPA. The function then runs with autocast off, so the softmax output is not promoted to fp32. - The gates are unchanged: ROCm torch, a CUDA-device bf16 / fp16 query, no fused kernel available, and the `UNSLOTH_VAE_ATTN_HALF_MATH` kill switch. The fp32 path and the chunking budget are also unchanged. Equivalence on CPU (torch 2.12.1, bf16, 1x1x1024x512, the FLUX VAE head dim): - Output is bit-identical to `F.scaled_dot_product_attention` under the math backend with the flag on. - The ATen op trace is the same: the same two `bmm` calls and the same `_safe_softmax`, with the same shapes, dtypes and strides. The only difference is that the scaling multiply records as `mul.Tensor` instead of `mul.Scalar`, which is the same kernel with a wrapped scalar. GEMM work and intermediate allocations therefore match the merged version. ## Flip test `studio/backend/tests/test_diffusion_vae_attn_chunked.py::test_half_math_leaves_other_threads_and_the_flag_alone` The test runs two VAE attention calls in two threads. A per-thread dispatch mode parks each thread inside its half-math call. While both are parked, the test checks that the global flag still has its original value and that an unrelated math SDPA call in the main thread is bit-identical to its reference. It then releases the threads first in, first out and checks the flag and the unrelated call again. - origin/main: FAILED with `assert True == False` (`where True = _HALF_FLAG()`) - this branch: passed Other new tests: - `test_half_math_sdpa_matches_the_flag[None|0.3|-0.3]`: bit-identical to flag-on math SDPA, including a negative scale. - `test_half_math_runs_in_the_autocast_dtype`: under bf16 autocast with fp32 k / v, the result is bf16 and equal to the direct half path. - The existing `test_half_math_keeps_dtype_scoped_and_close` still passes. It checks that the unchunked output is bit-equal to flag-on SDPA, differs from the upcast path, and is close to the fp32 reference. ## Tests run - `test_diffusion_vae_attn_chunked.py`: 49 passed. - `test_diffusion_vae_attn_chunked.py`, `test_diffusion_rocm_tag_detect.py`, `test_diffusion_speed.py`, `test_diffusion_device.py`, `test_video_vae_bf16_decode_rocm.py` and `test_diffusion_attention.py`, run with `-o addopts= -m "not server and not native_mxc"`: 502 passed, 1 skipped. ## gfx1151 results (Strix Halo, Linux, torch 2.11.0+rocm7.13.0, exclusive GPU) Both arms ran in the same job on the same machine. Base is current main (with unslothai#17252), head is main plus this change. Each arm is the median of 7 interleaved reps after 2 warm-up reps. The half path engaged in every unit, the kill switch did not, and no fused SDPA kernel takes head dim 512. | unit | base half ms | head half ms | kill switch (fp32 upcast) ms | head/base | outputs base vs head | global flag True during half call | |---|---|---|---|---|---|---| | attention S=16384 | 64.2 | 64.5 | 273 to 287 | 1.005 | bit-identical | base 16 of 16 ops, head 0 of 16 | | attention S=32768 (chunked) | 375.4 | 383.0 | 1250 to 1262 | 1.020 (A/A noise 3%) | bit-identical | base 77 of 77, head 0 of 77 | | VAE decode 1024x1024 | 816.9 | 814.4 | 1045 to 1053 | 0.997 | bit-identical | base 16 of 182, head 0 of 182 | - Decode uses an AutoencoderKL with the FLUX.1 VAE layout and seeded random weights. - Compared with an fp32 decode, the half path gives max abs 0.0838, PSNR 46.6 dB and LPIPS 0.00100; the fp32 upcast gives 0.0850, 46.6 dB and 0.00104. Base and head are identical. - Peak memory of the half attention path: 1280 MiB on head vs 1296 MiB on base at S=16384, and 2945 MiB for the decode on both. - The harness verdict is CONFIRMED: base flips the process-wide flag for the duration of the call, head never does, and head keeps the speed and output. ## Not proven - Windows: on Windows 11 gfx1151 with Studio's pinned torch 2.11.0+rocm7.14.0, a fused SDPA kernel takes head dim 512. The half-math path therefore never engages there, in base or head, and the Windows run could not compare it. That run was INCONCLUSIVE by design. - The decode used random weights, not real FLUX weights, so image-quality figures come from a synthetic decoder. - The two-thread overlap is proven on CPU only. On the GPU, base was shown to flip the global flag during the call.
1 of 5 tasks
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
On ROCm, the VAE mid-block attention (head dim 384 / 512) has no fused SDPA kernel, so it runs PyTorch's math SDPA. Since torch 2.5 that path upcasts bf16 / fp16 q, k, v and the score matrix to fp32 unless
torch.backends.cuda.allow_fp16_bf16_reduction_math_sdp(True)is set. On gfx1151 that makes a FLUX.3 klein 1024x1024 decode spend about 280 ms in two fp32 GEMMs (QK^T and PV at 16384 tokens).This PR keeps the math SDPA in the VAE's own half dtype, the same way the baseline single-file stack runs it:
diffusion_vae_attn_chunked), a bf16 / fp16 SDPA call that no fused kernel takes runs withallow_fp16_bf16_reduction_math_sdp(True).is_rocm_torchand a CUDA-device tensor). MPS and NVIDIA never reach this code, and calls a fused kernel takes are untouched.UNSLOTH_VAE_ATTN_HALF_MATH=0keeps the fp32 upcast.Results (AMD Strix Halo gfx1151, torch 2.11.0+rocm7.13.0, exclusive GPU)
FLUX.3 klein VAE, 1024x1024 decode, same weights and latent, a fresh process per arm, two interleaved rounds, median of 5 decodes each:
UNSLOTH_VAE_ATTN_HALF_MATH=0Falseafter every run.Tests
studio/backend/tests/test_diffusion_vae_attn_chunked.py: 3 new tests.