Repository navigation
Windows ROCm: run attention heads wider than 256 on SDPA math (Gemma 4 NaN) - #17976
Conversation
…s ROCm AMD's Windows torch 2.11.0+rocm7.14.0 on gfx1151 accepts head dim 512 in its flash and efficient SDPA kernels and computes it wrong: at Gemma 4's global-layer shapes the forward and dq / dk / dv are off fp64 math by relative error 1 to 1e20 or non-finite, while math is right. Linux ROCm refuses those kernels and already runs math. On gemma-4-E2B-it at 2048 tokens, sdpa agreed with eager on 1.5% of top-1 tokens (loss 10.87 vs 0.11). import unsloth now wraps torch.nn.functional.scaled_dot_product_attention on Windows ROCm only so a call whose query or value head is wider than 256 runs under sdpa_kernel([MATH]); heads up to 256 keep their fused kernels. The wrapper carries the same flag as Studio's worker guard and checks the whole __wrapped__ chain, so whichever installs first wins and the other is a no-op. Compiled, the decision is a shape read: fullgraph, no added recompile, and the traced graph decomposes to math. UNSLOTH_ALLOW_ROCM_WIDE_HEAD_FUSED_SDPA=1 opts out.
…ct under the wide-head guard The Windows ROCm wide-head guard replaces F.scaled_dot_product_attention, so a TorchFunctionMode that matches `func is F.scaled_dot_product_attention` (diffusers layer_skip, Studio's VAE chunking, tp_native) saw torch's builtin instead and silently stopped matching in any process that imports unsloth. The wrapper now re-dispatches torch functions like torch's Python functionals, so modes see the wrapper itself. Studio's VAE chunking mode also accepts the builtin, for wrappers that do not. The math switch is now one allow_in_graph node: compiled, an inlined sdpa_kernel exit restored the backends Dynamo saw while tracing rather than the caller's.
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 |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 11c3111c9f
ℹ️ 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".
| with sdpa_kernel([SDPBackend.MATH]): | ||
| return _ROCM_WINDOWS_WIDE_HEAD_ORIGINALS[token](query, key, value, *args, **kwargs) |
There was a problem hiding this comment.
Coordinate backend switching across concurrent wide-head calls
On Windows ROCm, overlapping wide-head calls from different threads can defeat this guard because sdpa_kernel changes process-wide backend flags. If call A enters first and call B enters before A exits, B saves the math-only settings; A then restores the fused backends while B is still executing, allowing B to dispatch to the corrupt kernel. When B exits, it restores its saved math-only settings, potentially leaving fused attention disabled for subsequent narrow-head calls. Coordinate overlapping calls with a lock/refcount and restore the original settings only after the last guarded call finishes, as the existing cuDNN guard in this module does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 656b6a8: the first wide-head call in flight saves the caller's backends and pins math, the last restores them (refcount under a lock, as the cuDNN guard does), in both the core guard and Studio's. New tests run two overlapping calls on two threads with the first returning first; both fail before the change.
…ping calls sdpa_kernel saves and restores process-wide backend flags per call, so with two wide-head calls in flight the first to return put the fused kernels back under the second, and the second then restored the math-only state it had saved. The first call in flight now saves the caller's backends and pins math, and the last restores them, in both the core guard and Studio's. [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! 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". |
… so nested jagged tensors keep working The wrapper re-dispatched every __torch_function__ input with func = the wrapper. Nested jagged tensors route SDPA only when func is torch's builtin, so on Windows ROCm their SDPA fell through to the dense kernel and raised at any head size. Tensor subclasses now go through the builtin as on stock torch; modes still see F.scaled_dot_product_attention. [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9e0a0c2a2d
ℹ️ 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".
|
|
||
| def _math_on() -> None: | ||
| from torch.nn.attention import SDPBackend, _cur_sdpa_kernel_backends, _sdpa_kernel | ||
| with _LOCK: |
There was a problem hiding this comment.
Keep Studio's math guard opaque to Dynamo
On Windows ROCm with compilation enabled, compiling a wide-head attention call through Studio's guard now makes Dynamo trace into with _LOCK, which is an unsupported threading-lock context manager. This causes a graph break, or an error with fullgraph=True. Studio's inference/worker.py installs this guard before loading the model, and the shared marker makes the subsequently imported core fix leave it unchanged, so the core wrapper's allow_in_graph protection does not help this path. Keep the lock and backend-switching operations inside an opaque graph callable in Studio as well.
Useful? React with 👍 / 👎.
The backend flags are process-wide, so another thread's sdpa_kernel could change them while a wide call held the pin, and a wide call starting after that ran under the other thread's backends. Each entry now pins math again; the first still saves and the last still restores the caller's backends. [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? 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". |
…32 upcast (unslothai#18016) (unslothai#18077) ## Summary Fixes unslothai#18016. ROCm cards without native bf16 (gfx103x and older) run the VAE in fp16. The Z-Image / FLUX.1 VAE's decoder mid-block attention (head dim 512) produces scores of 1e6 to 5e7 on real latents, past fp16's 65504. The half-math SDPA stored every score as inf, and softmax returned NaN for every row. - Half-math VAE attention now runs only for bf16, which has fp32's exponent range. fp16 takes the fp32-upcast math SDPA, the same path as `UNSLOTH_VAE_ATTN_HALF_MATH=0`. - The first version of this PR routed every Linux ROCm head wider than 256 to fp32. That also dropped half math for bf16 VAEs on gfx11 / gfx1151, adding about 26% to VAE decode time, so the dtype gate replaces it. - Windows ROCm head-width handling (unslothai#17976) is unchanged. ## Scores per VAE (real latents, decoder attention) | VAE | head dim | score range | fp16 half math | |---|---|---|---| | Z-Image / FLUX.1 | 512 | 1e6 to 5e7 | all NaN | | FLUX.2 | 512 | -18 to 16 | finite | | SDXL fp16-fix | 512 | -36 to 125 | finite | | Qwen-Image | 384 | -20 to 29 | finite | | Qwen-Image 2.1 | 1152 | -4 to 12 | finite | ## Verification **CPU tests** in `test_diffusion_vae_attn_chunked.py`: - An fp16 call with FLUX.1-scale scores at the real 512 px shape [1, 1, 4096, 512] is finite and equal to the kill-switch output. It fails before the fix, and first checks that the half-math call alone returns all NaN on these inputs. - bf16 at the same scores keeps half math. This passes before the fix and fails on the first version of this PR. **AMD CI, gfx1151, real Z-Image VAE:** - **Linux, fp16:** before, every output pixel is NaN at 512 and 1024 px. After, the output is finite and bitwise equal to `UNSLOTH_VAE_ATTN_HALF_MATH=0` (LPIPS 4e-6 against fp32). - **Linux, bf16 decode at 1024 px:** 819 ms before, 814 ms after, with identical output and within the 3% noise. The fp32 upcast takes 1032 ms. - **Windows:** the same fp16 fix, and the same bf16 decode speed and output. **NVIDIA T4:** this path is ROCm-only and is not installed there; the output is identical before and after. ## Not covered - No gfx103x card was available. The NaN was reproduced on a gfx1151 forced to fp16, and in a CPU emulation. - fp16 VAEs whose scores do fit (SDXL, FLUX.2, Qwen-Image on gfx103x) go back to the fp32 upcast they used before half math was added. Their speed on gfx103x was not measured. --------- Co-authored-by: Josh <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Daniel Han <[email protected]>
…mpile without a graph break (unslothai#18122) Both changes remove a Python lock from code that a whole-model `torch.compile` traces. On main each one makes a fullgraph compile fail with `Unsupported context manager`, and a default compile drop the call to eager. 1. **Windows ROCm wide-head SDPA guard (unslothai#17976).** `studio/backend/core/_rocm_windows_sdpa.py` pins the math backend under a `threading.Lock`. Studio installs its guard before unsloth's, and unsloth's compile-safe guard (`unsloth/import_fixes.py`, `_sdpa_math_only` under `allow_in_graph`) sees the shared marker and keeps Studio's wrapper, so a compiled Gemma 4 global layer (head dim 512) on Windows ROCm reaches the lock. The pin now runs in an `allow_in_graph` helper keyed by a string token, as in `unsloth.import_fixes`. 2. **ROCm TunableOp tune hooks (unslothai#17299).** With `UNSLOTH_DIFFUSION_ROCM_TUNABLEOP=tune`, forward hooks on the denoiser root hold an `RLock` and flip the process-wide tuning switch. The max tier compiles an SDXL U-Net whole (`Module.compile`, fullgraph), which traces those hooks and fails at the first forward, with no eager fallback. The hooks now return early under `torch.compiler.is_compiling()`, so compiled calls only read the tuning table and tuning stays with eager calls. ### GPU results on gfx1151 (Radeon 8060S), base (main 62d66cb) vs this branch, same job and runner per fix | fix | runner | check | base | this branch | |---|---|---|---|---| | wide-head guard | Windows 11, torch 2.11.0+rocm7.14.0 | bf16 head-512 causal attention, `fullgraph=True` with eager / aot_eager / inductor | all three fail: `Unsupported context manager ... lock` | all three compile, no break reasons | | wide-head guard | same | compiled vs guarded eager output | n/a | rel L2 0.0 / 0.0 / 2.6e-05; eager vs fp32 reference 0.00158 in both arms; no fused attention kernel ran; backend flags restored | | tune hooks | Linux, torch 2.11.0+rocm7.13.0 | small bf16 GEMM module, hooks installed in tune mode, `fullgraph=True` with eager / aot_eager / inductor | all three fail: `Unsupported context manager ... RLock` | all three compile, rel L2 0.0 vs eager | | tune hooks | same | `fullgraph=False` | 3 unsupported, 23 of 26 frames compiled (module call dropped to eager) | 0 unsupported, 3 of 3 frames | | tune hooks | same | eager tuning still runs | tuning switch on then off, results file written | tuning switch on then off, TunableOp results 25 to 27, results file written (27 rows) | ### Tests - `studio/backend/tests/test_rocm_windows_wide_head_sdpa.py`: `test_guarded_wide_head_compiles_fullgraph[aot_eager|inductor]` compiles the real Studio wrapper with `fullgraph=True`; fails on main. The inductor case skips on Windows when MSVC (`cl`) is not on PATH, since Inductor's CPU backend needs it. - `studio/backend/tests/test_diffusion_rocm_tunableop.py`: new compile test; fails on main. - CPU (torch 2.14.1): base 2 failed / 9 passed and 1 failed / 19 passed; this branch 31 passed across both files. - gfx1151 runners: Windows suite base 9 passed, this branch 10 passed and the inductor case failed with `Compiler: cl is not found` (the skip above was added after that run); Linux TunableOp suite base 19 passed, this branch 20 passed. ### Not covered - The wide-head guard ran on Windows only and the TunableOp hooks on Linux only; discrete RDNA / CDNA cards and multi-GPU hosts were not tested. - The full SDXL max-tier U-Net compile with tune mode was not run end to end; the check used a small module with the same hooks.
Summary
On Windows with AMD ROCm (gfx1151, AMD's torch 2.11.0+rocm7.14.0), plain Unsloth trains Gemma 4 into NaN with the default attention. AMD's Windows wheel accepts head dim 512 in its flash and efficient SDPA kernels and computes it wrong; Gemma 4's global attention layers use head dim 512, and Unsloth picks
sdpafor Gemma 4 there. Head dims up to 256 are correct, and Linux ROCm refuses those kernels at 512 and already runs math.Studio's LLM workers got the same guard in #17960; this puts it in
import unslothso scripts and notebooks are covered too.Change
unsloth/import_fixes.py:fix_rocm_windows_wide_head_sdpa(), called from_gpu_init.pyright afterfix_rocm_windows_fused_sdpa(). On Windows with a ROCm torch only, it wrapstorch.nn.functional.scaled_dot_product_attentionso a call whose query or value head is wider than 256 runs on the math backend; narrower heads keep the fused kernels. Everywhere else it does nothing.UNSLOTH_ALLOW_ROCM_WIDE_HEAD_FUSED_SDPA=1turns it off.__torch_function__override path, so hooks that matchfunc is F.scaled_dot_product_attention(diffusers' layer skip, Studio's VAE chunked attention,tp_native) still match it.torch.compile, so it restores the caller's backend settings at run time; no graph break and no extra recompile.diffusion_vae_attn_chunked.py: its hook also acceptstorch._C._nn.scaled_dot_product_attention, for wrappers that call the builtin directly.fix_rocm_windows_fused_sdpa: that switches flash and efficient off for the whole process, which would slow every correct head 256 call, and it decides from a single probe shape, while the head 512 corruption depends on sequence length, mask and GQA layout.Runs (AMD CI gfx1151, base = main, head = main + this change)
Plain Unsloth,
unsloth/gemma-4-E2B-it, 16-bit LoRA r=8, 20 steps:Final head on hardware (AMD CI gfx1151, base = merge base, head = this PR's final diff, same job)
The guard now refcounts the backend switch across overlapping calls (the first call in flight saves the caller's backends, every call re-pins math, the last restores) and re-dispatches only to TorchFunctionModes, so nested jagged tensors keep working. Rerun on that code:
Head-256 layers stay on flash in every arm. Linux base and head are identical.
Tests
New
tests/test_rocm_windows_wide_head_sdpa.py(19): heads above 256 run on math with the forward matching fp64 math; narrower heads and other platforms keep the stock dispatch; install only on Windows ROCm and only once; the opt-out; hooks still matchF.scaled_dot_product_attention; undertorch.compileno graph break, no recompile, math in the traced graph at head 512, and the caller's backends restored. The file fails on main. Studio's VAE chunked attention tests pass, with a new case for a wrapper that calls the builtin.Not covered
torch.compileon Windows (the runner has no C++ compiler); compile is covered by CPU tests.