Skip to content

Studio on Windows AMD: run attention heads wider than 256 on SDPA math (Gemma 4 output was wrong) - #17960

Merged
danielhanchen merged 1 commit into
mainfrom
fix-windows-rocm-wide-head-sdpa
Nov 16, 2026
Merged

danielhanchen merged 1 commit into
mainfrom
fix-windows-rocm-wide-head-sdpa

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

On Windows with AMD ROCm (gfx1151, AMD's torch 2.11.0+rocm7.14.0), Gemma 4 run through transformers' SDPA attention is unusable: on unsloth/gemma-4-E2B-it at 2048 tokens, sdpa agrees with eager on the top-1 token only 1.5% of the time (KL 10.9; next-token loss 10.87 vs 0.11). Linux ROCm agrees exactly (top-1 1.0, KL 0.0002).

Cause: 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. Measured at Gemma 4's shapes (head 512, causal, GQA 8:1 and 16:2, bf16, 128 / 2048 / 8192 tokens), every flash and efficient path, and the default dispatch that picks them, is wrong in the forward and in dq / dk / dv (relative error 1 to 1e20 against fp64 math, or non-finite). The math backend is correct (about 0.003). Linux ROCm refuses those kernels at head 512 and already runs math there. Head dims up to 256 are correct on Windows.

Change

core/_rocm_windows_sdpa.py: on Windows ROCm only, torch.nn.functional.scaled_dot_product_attention is wrapped so a call whose head is wider than 256 runs under sdpa_kernel([SDPBackend.MATH]); narrower heads keep their fused kernels. It is installed once in the Studio inference and training workers, next to the existing Windows ROCm torchao stub, before any model loads; transformers looks the function up per call, so every model loaded after it is covered. Idempotent, never raises, and a no-op on every other platform.

GGUF chat through llama.cpp does not use torch attention and is unaffected.

Runs (AMD CI gfx1151, base = main, head = main + this change)

main this PR
Windows: kernel cases wrong vs fp64 math at Gemma 4 shapes (forward + backward, all backends) 32 0
Windows: Gemma 4 E2B, sdpa vs eager, 2048 tokens top-1 1.5%, loss 10.87 vs 0.11 top-1 1.0, loss 0.10955 vs 0.10953
Linux: same probes correct unchanged

Tests

New tests/test_rocm_windows_wide_head_sdpa.py (8): heads above 256 on a CUDA device run under the math backend; narrower heads and other devices keep the stock dispatch; the install wraps SDPA on Windows ROCm only (and only once); both LLM workers install it. The file fails on main (the module does not exist).

Not covered

  • Plain Unsloth outside Studio on Windows ROCm still reaches the fused kernels; the same guard would need to live in unsloth / unsloth_zoo.
  • Not checked under torch.compile (compile on Windows needs a C++ compiler, which the runners lack).
  • Math attention memory grows with the square of the context length at head 512, as it already does on Linux ROCm.

…n Windows ROCm

AMD's Windows torch 2.11.0+rocm7.14.0 on gfx1151 takes head dim 512 in flash and efficient SDPA and
computes it wrong. At Gemma 4's global-layer shapes (causal, GQA, bf16, 128 to 8192 tokens) the
forward and dq / dk / dv are off fp64 math by relative error 1 to 1e20 or non-finite; math is right.
Linux ROCm refuses those kernels and already runs math. Pin such calls to math in the LLM inference
and training workers; heads up to 256 keep their fused kernels.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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-16T10:42:11.393319Z df306e4 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: df306e493a

ℹ️ 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 1c7d378 into main Nov 16, 2026
@danielhanchen
danielhanchen deleted the fix-windows-rocm-wide-head-sdpa branch November 16, 2026 11:21
danielhanchen added a commit that referenced this pull request Nov 16, 2026
…ameter name (#17972)

## Summary


`tests/test_cp_ulysses_media_towers_gloo.py::test_gemma4_with_towers_matches_one_process`
(from #17930) has failed in four of the last gloo shard runs on
unrelated PRs (staging runs of #17957, #17960, #17831 and #17966),
always as:

```
E   AssertionError: model.language_model.layers.0.self_attn.q_proj.weight
```

and it passes locally every time (5 of 5 standalone, and 53 of 53 with
all five `test_cp_*gloo*.py` files in one process, so it is not state
left by an earlier test in the worker). The assertion passes `msg =
name`, which replaces torch's whole mismatch report with the parameter
name, so the CI logs do not say how many elements are off or by how
much. Without that there is no way to tell a float32 reduction-order
difference on the CI runners' CPUs (a tolerance question) from a real
context parallel gradient bug.

## Change

Test only. The gradient `assert_close` calls in
`test_cp_ulysses_media_towers_gloo.py` and
`test_cp_ulysses_generic_gloo.py` pass `msg` as a callable that prefixes
the parameter name to torch's report instead of replacing it:

```
model.language_model.layers.0.self_attn.q_proj.weight: Tensor-likes are not close!

Mismatched elements: ...
Greatest absolute difference: ... (up to ... allowed)
Greatest relative difference: ... (up to ... allowed)
```

Tolerances are unchanged. The next CI failure will carry the numbers
needed to decide whether the tolerance or the code is wrong.

## Testing

- Both files (2-rank gloo, CPU): 24 passed.
- The message form checked directly against `torch.testing.assert_close`
(output above).
danielhanchen added a commit that referenced this pull request Nov 16, 2026
…4 NaN) (#17976)

## 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 #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.
danielhanchen added a commit that referenced this pull request Nov 20, 2026
… kept, nested-safe SDPA guard (#18582)

Three fixes to the Windows ROCm attention routing added in #17953 and
#17960, found in a recheck of the kernel PRs. Each is its own commit.

## 1. VAE decode compile is dropped only for wide-head VAEs

#17953 keeps the Windows ROCm VAE decode eager so a compiled decode
cannot skip the attention routing that keeps head dim 512 off the fused
SDPA kernels. But `_vae_decode_compile_allowed` returned False on the
platform alone, before looking at the VAE or the
`UNSLOTH_DIFFUSION_COMPILE_VAE` setting. A VAE with no attention head
wider than 256 (attention-free video VAEs, or a narrow AutoencoderKL)
lost decode compilation too, even when the env asked for it.

- `diffusion_vae_attn_chunked.py`: new `vae_has_untrusted_head(vae)`. It
walks the same attention modules the routing patches and reads each head
dim (`inner_dim // heads` on diffusers `Attention`). Any head wider than
256, any attention module whose head dim it cannot read (the single-head
blocks of Wan, Qwen-Image and HunyuanImage), and any VAE it cannot
inspect count as wide.
- `diffusion_speed.py`: on Windows ROCm `_vae_decode_compile_allowed`
returns False only when `vae_has_untrusted_head` is True. The check
still runs before the U-Net shortcut and the env override, so a
wide-head VAE never compiles past the routing there.

Studio's own AutoencoderKL and AutoencoderKLFlux2 VAEs have a
single-head mid-block at 512, so they stay eager on Windows ROCm exactly
as before.

## 2. fp64 stays fp64 in the wide-head math path

`fp32_math_sdpa` ran `.float()` on Q, K and V and cast only the result
back, so an fp64 call was silently reduced to fp32. With fp64 `[1, 1, 3,
512]` operands filled with `1e20`, stock SDPA returns finite output
while the routed path overflowed and returned NaN. It now upcasts only
fp16 and bf16; fp32 and fp64 run in their own precision. Half inputs
keep the existing fp32 upcast, so `UNSLOTH_VAE_ATTN_HALF_MATH=0` is
unchanged. Studio loads VAEs in fp16, bf16 or fp32, so this only matters
to code handing a double VAE to the routed attention.

## 3. The SDPA guard checks the device before the query shape

The Windows ROCm SDPA wrapper's `_wide_cuda_head` read `query.shape`
before checking the device. A strided NestedTensor raises
`NestedTensorImpl doesn't support sizes` on `.shape`, so a valid CPU
nested SDPA call failed inside the wrapper. It now returns False for any
non-CUDA query without touching the shape, judges a nested CUDA query by
`size(-1)`, and sends the call to the stock dispatch if even that
raises. Dense CUDA queries are judged as before.

## Tests

CPU only, Windows ROCm faked:

- `tests/test_diffusion_windows_rocm_wide_head.py`:
-
`test_windows_rocm_keeps_decode_compile_unless_the_vae_has_a_wide_head`,
with tiny real diffusers AutoencoderKL VAEs: the head-64 and
no-attention cases fail on main and pass here. The two head-512 cases
(with and without the env forcing compile) are still refused, passing on
both.
- `test_windows_rocm_fp64_wide_head_keeps_fp64_precision[1073741824|16]`
(unchunked and chunked): fail on main (NaN), pass here.
- The existing `test_vae_decode_compile_stays_eager_on_windows_rocm` (an
uninspectable `vae=object()` stays eager) passes on both.
- `tests/test_rocm_windows_wide_head_sdpa.py`:
`test_a_nested_cpu_query_reaches_the_stock_dispatch` and
`test_a_nested_cuda_query_is_judged_by_its_head[128-False|512-True]`
fail on main and pass here.

Base vs head over both files: 7 tests fixed, 31 unchanged, 0 failing on
this branch. Wider suite (`test_diffusion_vae_attn_chunked.py`,
`test_diffusion_speed.py`, `test_diffusion_vae_fused.py`,
`test_diffusion_vae_regional_compile.py`): no failures on main or here
apart from the new tests on main.

## Windows gfx1151 (AMD CI)

Real Windows ROCm (torch 2.11.0+rocm7.14.0, gfx1151), base = main, head
= this branch, two tiny AutoencoderKL VAEs (head dim 64 and 512) on the
real GPU:

| state | narrow VAE: U-Net / env forced | wide VAE: U-Net / env forced
| compiled narrow decode finite | rel L2 to eager |
|---|---|---|---|---|
| base | refused / refused | refused / refused | yes | 8.7e-7 |
| head | allowed / allowed | refused / refused | yes | 8.7e-7 |

CONFIRMED: main refuses decode compile for the narrow VAE, this branch
allows it, the compiled decode matches eager, and the head-512 VAE is
still refused.

## Not proven here

- The speed gain for an unaffected VAE was not measured.
- fp64 and nested CUDA tensors on a real Windows card were not run.
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