Skip to content

PrefixGrouper on ROCm: static flex compile for calls whose backward runs - #18881

Merged
danielhanchen merged 1 commit into
mainfrom
amd-health-prefix-grouper-rocm-static
Nov 22, 2026
Merged

danielhanchen merged 1 commit into
mainfrom
amd-health-prefix-grouper-rocm-static

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

On gfx1151 (torch 2.11, ROCm 7.13 / 7.14), flex_attention compiled with a symbolic sequence length returns inf / NaN gradients (see unslothai/unsloth-zoo#2663 for the zoo side). PrefixGrouper compiles flex with dynamic = True, so GRPO with PrefixGrouper on ROCm trains on bad gradients.

Fix

unsloth/utils/prefix_grouper_kernel.py: on a ROCm build, a GPU call whose backward will run goes through a dynamic = False compile of its own entry point (its own code object, so its graphs keep their own recompile budget). No-grad calls, CPU tensors and CUDA builds keep the existing dynamic = True compile, so CUDA is unchanged. UNSLOTH_ROCM_FLEX_STATIC=0 keeps the dynamic kernel.

The cost is one compile per padded length for training calls on ROCm, the same trade the zoo flex path makes in #2663.

Tests

tests/test_prefix_grouper_rocm_static_flex.py (5 tests, CPU with a simulated ROCm build): routing for grad / no-grad / CPU / CUDA builds and the opt-out. The routing test fails on main and passes here.

…c shapes

flex_attention compiled with a symbolic sequence length returned inf / NaN gradients on gfx1151 (torch 2.11,
ROCm 7.13 / 7.14; unslothai/unsloth-zoo#2663). On a ROCm build, a call on the GPU whose backward runs uses a
dynamic=False compile of its own entry point; no-grad calls, CPU tensors and CUDA builds keep the dynamic=True
compile. UNSLOTH_ROCM_FLEX_STATIC=0 keeps the dynamic kernel.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 22, 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-22T11:38:46.714897Z fbcab70 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. Breezy!

Reviewed commit: fbcab70994

ℹ️ 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 93cb7e8 into main Nov 22, 2026
@danielhanchen
danielhanchen deleted the amd-health-prefix-grouper-rocm-static branch November 22, 2026 23:25
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-zoo-staging-2 that referenced this pull request Nov 23, 2026
…hai#2663)

On AMD gfx1151 (Linux ROCm 7.13 and Windows ROCm 7.14, torch 2.11.0,
transformers 5.23.0), all 15 `test_save_merge.py[gemma3_vlm-*]`
regression cases fail when the other gemma3_vlm case files run before
them in the same process. The export training records `train_losses
[12.49, nan, nan]`. The same file run alone passes 15 / 15, and the
whole gemma3_vlm set in one process passes 29 / 29 on an NVIDIA L4
(torch 2.14.1).

### Root cause

transformers compiles `flex_attention` once with
`torch.compile(flex_attention)`, i.e. with automatic dynamic shapes. The
first call at a second sequence length recompiles it with a symbolic
length. On gfx1151 that recompiled kernel returns inf / NaN gradients.
The earlier case files train or step at 32 / 40 tokens, then the export
training runs at 24, and its first backward already has non-finite LoRA
grads.

Bisected on the runner with one process, two loads of the tiny Gemma-3
VLM (load 1 takes one step, load 2 runs the export training):

| load 1 seq | variant | export losses | step 1 grad norm |
|---|---|---|---|
| 24 | default | 12.49, 12.47, 12.43 | 4.99 |
| 32 | default | 12.49, nan, nan (rerun: 12.49, 12.49, 12.50) | nan
(rerun: inf) |
| 32 | `UNSLOTH_COMPILE_DISABLE=1` | 12.49, 12.44, nan | 3659 |
| 32 | no gradient checkpointing on load 1 | 12.49, 12.41, nan | 3988 |
| 32 | `attn_implementation="eager"` | 12.49, 12.48, 12.44 | 4.96 |
| 32 | `torch._dynamo.config.automatic_dynamic_shapes = False` | 12.49,
12.47, 12.43 | 4.99 |
| 32 | `torch._dynamo.reset()` between the loads | 12.49, 12.47, 12.43 |
4.99 |
| 32 | block mask built eagerly (`_compile=False`) | 12.49, nan, nan |
nan |
| 32 | flex compiled with `dynamic=False` | 12.49, 12.47, 12.43 | 4.99 |
| 32 | flex eager (not compiled) | 12.49, 12.48, 12.42 | 4.99 |

So the block mask is fine and the only bad piece is the dynamic-shape
recompile of the flex kernel. A standalone flex call with the same
shapes (heads 4, kv heads 2, head dim 256, 32 then 24 tokens, no LSE)
was correct, so a minimal upstream repro still needs the model's exact
call (LSE output, padding mask_mod).

### Fix

On ROCm only,
`transformers.integrations.flex_attention.compile_friendly_flex_attention`
is replaced by the same function compiled with `dynamic=False` (one
compile per training flag, reused). Inside a compiled graph it calls
flex directly, as transformers does. torch 2.6 training keeps
transformers' `max-autotune-no-cudagraphs` workaround. CUDA, XPU and CPU
are untouched. A new sequence length costs a recompile on ROCm; zoo
already sets the recompile limit to 1024.

### Tests

New `tests/test_flex_rocm_static_compile.py` (CPU, `torch.compile`
recorded, never called) fails at base and passes at head:

* `test_rocm_compiles_flex_with_static_shapes`: with `torch.version.hip`
set, flex is compiled with `dynamic=False`, once per training flag, and
kwargs pass through.
* `test_cuda_and_cpu_keep_transformers_compile`: without hip,
transformers' function is left as is.
* `test_patch_is_idempotent`

CPU: base 2 failed, 1 passed; head 3 passed.
`tests/test_flex_mask_recompiles.py` still passes.

### AMD evidence (same job and machine per OS; base = zoo main, head =
main + this change, unsloth main)

| | gemma3_vlm regression, all 29 cases in one process | two-load repro,
export losses | new test file |
|---|---|---|---|
| Linux gfx1151 base | 13 passed, 15 failed, 1 skipped (378 s) | 12.49,
12.48, 12.48, grad norms 1732 / inf / 2659 | 2 failed, 1 passed |
| Linux gfx1151 head | 28 passed, 1 skipped (351 s) | 12.49, 12.47,
12.43, grad norms 4.99 / 3.16 / 2.23 | 3 passed |
| Windows gfx1151 base | 13 passed, 15 failed, 1 skipped (446 s) |
12.49, nan, nan | 2 failed, 1 passed |
| Windows gfx1151 head | 28 passed, 1 skipped (411 s) | 12.49, 12.48,
12.42 | 3 passed |

The 15 base failures are exactly the `test_save_merge.py[gemma3_vlm-*]`
cases. `test_flex_mask_recompiles.py` passes 4 / 4 on both arms and both
OSes. No slowdown on this suite (head wall time is lower on both OSes,
shared GPU).

Not covered: other ROCm GPUs (MI300, RDNA4), torch versions other than
2.11, and long variable-length runs where the per-length recompiles add
compile time.


## Update (1622ab0)

- Only a ROCm GPU call whose backward will run gets the static compile.
No-grad calls, including growing-KV decode, keep the normal compile, so
decode no longer recompiles per length.
- The change now lives in `unsloth_zoo/rocm_flex_static.py`. It patches
`WrappedFlexAttention.__call__` and the module's `flex_attention`
instead of replacing the helper, so an early-imported helper and the
saved-attention wrapper stay intact. It covers the shared flex compile,
sparse attention and the DeepSeek-V4 sparse flex compile, with the
recompile budget raised to at least 1024 for these.
- It stays ROCm-wide with `UNSLOTH_ROCM_FLEX_STATIC=0` as the opt-out; a
static compile is numerically safe everywhere. The PrefixGrouper side is
unslothai/unsloth#18881.
- Tests: 18 of the 22 tests in the new file fail on the previous head
and pass now. 40 flex-related zoo test files give the same result on
both arms.
- gfx1151, gemma3_vlm (29 cases in one process): Linux 13 passed / 15
failed -> 28 / 0, Windows 13 / 15 -> 28 / 0. The two-load repro on
Windows went from NaN losses to 12.49, 12.48, 12.42. The
decode-recompile change is covered by a CPU test only.
ouyang-2019 pushed a commit to ouyang-2019/unsloth that referenced this pull request Nov 23, 2026
…unslothai#18975)

## What

Follow-up to unslothai#18881. On ROCm, grad-bearing PrefixGrouper flex calls use
a `dynamic=False` compile, so every new padded length compiles a new
kernel. The first-call strict compile check (`_checked_first_call`) was
keyed on `(device, dtype, heads, kv_heads, head_dim, scale)`, so only
the first padded length ever ran under it.

This PR adds `T_pad` to the key, but only on the ROCm static path. Every
new padded length then gets the strict real call plus the forward +
backward check on copies. A failure turns PrefixGrouper off with the
usual one-line message, and callers fall back to the packed path.

The routing condition moves into `_uses_static_flex(q, k, v)`, so the
dispatcher and the check key use the same predicate. CUDA builds (where
`_flex_attention_static` is None) and ROCm no-grad calls still use the
one dynamic kernel and are still checked once.

## Why

The check exists because unsloth_zoo sets Dynamo's `suppress_errors`,
and a flex kernel that fails to compile then silently runs eager flex,
which materialises the full T x T scores. After unslothai#18881 that safety net
only covered the first length on ROCm. A later length whose static
compile failed would fall back to eager T x T with no message.

The cost is one extra strict forward + backward per new padded length,
on ROCm only. Each new padded length already compiles a static kernel,
which the file's own comment puts at about 14 s, so the extra probe is
small next to that.

## Tests

`tests/test_prefix_grouper_compile_check.py` gains 3 tests:
- `test_rocm_static_kernel_is_checked_per_padded_length`: grad-bearing
calls at padded lengths 128, 384, 384.
  - Main: 4 flex calls and one strict check (128 only).
  - This PR: 5 calls, strict at 128 and at 384, none for the repeat.
- `test_rocm_later_length_compile_failure_is_caught`: the kernel works
at 128 and fails to compile at 384.
- Main: no `PrefixGrouperCompileError` (DID NOT RAISE). The failure goes
unchecked, which is the silent eager fallback in a real run.
  - This PR: PrefixGrouper turns off with its message.
- `test_dynamic_kernel_is_checked_once_across_padded_lengths`: the CUDA
and no-grad path keeps one check across lengths. It passes on both arms,
as a regression guard.

`test_prefix_grouper_compile_check.py` +
`test_prefix_grouper_rocm_static_flex.py` (CPU):

| torch | main | this PR |
|---|---|---|
| 2.11.0+cpu | 2 failed (the two ROCm tests above), 19 passed | 21
passed |
| 2.14.1 | 2 failed (the two ROCm tests above), 19 passed | 21 passed |
| 2.15.0 | 2 failed (the two ROCm tests above), 19 passed | 21 passed |

The full `tests/test_prefix_grouper_*.py` suite plus
`tests/test_grpo_prefix_grouper_capability.py` on this PR, torch 2.14.1:
118 passed, 1 skipped.

## AMD CI (gfx1151, Linux, torch 2.11.0+rocm7.13.0), base vs head

Each state loaded its own `prefix_grouper_kernel.py` and ran
grad-bearing bf16 `flex_shared_prefix_attention` at T_pad 128, 256, 384,
384, each compared against the same call with `compiled=False`. The ROCm
static path was built and used at all three lengths in both states.

| | main | this PR |
|---|---|---|
| strict checks run | [128] | [128, 256, 384] (none for the repeated
384) |
| all rows finite | yes | yes |
| worst rel out / dq / dk / dv | 2.81e-3 / 3.45e-3 / 4.00e-3 / 2.87e-3 |
identical per row |
| `compile_check_failed()` | None | None |
| PrefixGrouper tests on GPU | 18 passed | 21 passed |

The GPU was shared, so no timing is claimed.

Rerun on gfx1151 with both commits applied: same verdict (CONFIRMED),
same graph / check counts, identical per-row errors, head pytest green.

## Static length inside an enclosing graph (second commit)

`torch.compile(_rocm_static_flex_entry, dynamic = False)` only keeps the
length static when it is the outermost compile. If a caller already
traces the attention call, Dynamo inlines the inner compile and the
padded length stays symbolic in the caller's graph, which is the kernel
that gave inf / NaN gradients on gfx1151. `_flex_attention_compiled` now
does two things on the ROCm static path:
- Inside a trace, it calls
`unsloth_zoo.rocm_flex_static.specialize_flex_shapes`, which makes the Q
/ K / V sequence sizes concrete at trace time (one graph per padded
length; batch, heads and head dim keep the caller's policy). If that
import fails, the call goes on as before.
- On eager calls, it drops a caller's `mark_dynamic` /
`maybe_mark_dynamic` marks with a view, because those marks win over
`dynamic = False`.

CUDA builds do not import anything new, because
`_specialize_flex_shapes` is only resolved when `_ROCM_FLEX_STATIC` is
set.

In practice Unsloth's block compile already keeps the stock forward for
layers that get `prefix_seg_info` (`_block_compile.py`), so this
protects a user's own `torch.compile` around the model rather than a
shipped route.

Two new tests in `tests/test_prefix_grouper_rocm_static_flex.py` use
real Dynamo with a recording backend, and a math stand-in for flex so
they run on CPU:
- `test_rocm_static_length_inside_an_enclosing_graph`: an outer
`torch.compile(fullgraph = True, dynamic = True)` over padded lengths
128, 256, 384. Before: 1 graph with a symbolic length. After: 3 graphs,
each with a concrete length, and finite gradients.
- `test_rocm_static_entry_ignores_a_callers_dynamic_marks`: inputs with
`mark_dynamic` on the length go to the static entry. Before: 1 symbolic
graph. After: 3 static graphs.

`test_prefix_grouper_rocm_static_flex.py` +
`test_prefix_grouper_compile_check.py`, with unsloth_zoo from
unsloth-zoo#2690:

| torch | before this commit | this commit |
|---|---|---|
| 2.11.0+cpu | 2 failed (the two tests above), 21 passed | 23 passed |
| 2.14.1 | 2 failed (the two tests above), 21 passed | 23 passed |
| 2.15.0 | 2 failed (the two tests above), 21 passed | 23 passed |

With zoo main (unslothai#2663, which specializes every Q / K / V size) the two
tests also pass. Full `tests/test_prefix_grouper_*.py` +
`tests/test_grpo_prefix_grouper_capability.py` on torch 2.14.1: 120
passed, 1 skipped.

## Not covered

- A real static compile failure at a later length on ROCm, and the
resulting eager T x T memory, cannot be triggered on demand. The flip
test injects the failure on CPU.
- gfx942 / gfx950.
- A GRPO run with PrefixGrouper across many rollout lengths.
- The in-graph route was not run on gfx1151. It uses the same
static-length flex kernel that the per-length rows above exercise.
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