Skip to content

Studio: compute ROCm VAE half-math SDPA per call instead of flipping the global flag - #17350

Merged
danielhanchen merged 2 commits into
mainfrom
studio-vae-half-math-local
Nov 10, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
studio-vae-half-math-local

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

The ROCm VAE attention half-reduction math from #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

#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 #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.

…the global flag

The fp16/bf16 reduction flag for math SDPA is process-global, so scoping it
around a VAE attention call leaked to other threads and could stay enabled
after two overlapping calls. Run the same math SDPA ops in the input dtype
directly; outputs are bit-identical to SDPA with the flag on.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 10, 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-10T04:48:00.094926Z 4fba4eb 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. 👍

Reviewed commit: 4fba4ebadd

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

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