Skip to content

Windows ROCm: run attention heads wider than 256 on SDPA math (Gemma 4 NaN) - #17976

Merged
danielhanchen merged 6 commits into
mainfrom
fix-core-windows-rocm-wide-head-sdpa
Nov 16, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
fix-core-windows-rocm-wide-head-sdpa

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

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 sdpa for 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 unsloth so scripts and notebooks are covered too.

Change

  • unsloth/import_fixes.py: fix_rocm_windows_wide_head_sdpa(), called from _gpu_init.py right after fix_rocm_windows_fused_sdpa(). On Windows with a ROCm torch only, it wraps torch.nn.functional.scaled_dot_product_attention so 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=1 turns it off.
  • The wrapper goes through torch's __torch_function__ override path, so hooks that match func is F.scaled_dot_product_attention (diffusers' layer skip, Studio's VAE chunked attention, tp_native) still match it.
  • The switch to math is one graph node under torch.compile, so it restores the caller's backend settings at run time; no graph break and no extra recompile.
  • It carries the same marker as Studio's guard from Studio on Windows AMD: run attention heads wider than 256 on SDPA math (Gemma 4 output was wrong) #17960, so whichever installs first, the other does nothing.
  • diffusion_vae_attn_chunked.py: its hook also accepts torch._C._nn.scaled_dot_product_attention, for wrappers that call the builtin directly.
  • It does not extend 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:

sdpa vs eager top-1 agreement forward loss sdpa / eager LoRA loss with sdpa, step 1 to 20 attention op at head 512
Windows main 0.0 NaN / 0.883 10.89, NaN from step 3 flash
Windows this PR 0.994 0.893 / 0.883 1.787 to 0.145 (eager 1.778 to 0.148) math
Linux main and this PR 0.996 0.895 / 0.883 1.788 to 0.141 math, guard not installed

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:

Windows main Windows this PR Linux main and this PR
guard installed no yes no
top-1 agreement sdpa vs eager 0.0 0.99365 0.99561
forward loss sdpa / eager NaN / 0.883 0.893 / 0.883 0.895 / 0.883
LoRA loss with sdpa, step 1 to 20 10.89, NaN from step 3 1.787 to 0.145 (eager 1.778 to 0.148) 1.788 to 0.141
op at head 512 flash math math

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 match F.scaled_dot_product_attention; under torch.compile no 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

  • Training with torch.compile on Windows (the runner has no C++ compiler); compile is covered by CPU tests.
  • The speed cost of math at head 512 on Windows (shared GPU, one sample: 38.9 s vs 32.8 s for 20 steps).
  • A hook active inside a compiled region sees the builtin, not the wrapper.
  • Once AMD fixes its kernels, heads above 256 stay on math until the guard is removed or the opt-out is set.

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

chatgpt-codex-connector Bot commented Nov 16, 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-16T12:56:17.029703Z 31b96c2 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 chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread unsloth/import_fixes.py Outdated
Comment on lines +8494 to +8495
with sdpa_kernel([SDPBackend.MATH]):
return _ROCM_WINDOWS_WIDE_HEAD_ORIGINALS[token](query, key, value, *args, **kwargs)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 656b6a8189

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

… 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]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 31b96c2cbf

ℹ️ 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 123028c into main Nov 16, 2026
@danielhanchen
danielhanchen deleted the fix-core-windows-rocm-wide-head-sdpa branch November 16, 2026 14:43
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 17, 2026
…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]>
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 17, 2026
…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.
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