Skip to content

PrefixGrouper: run the strict compile check per padded length on ROCm - #18975

Merged
danielhanchen merged 3 commits into
mainfrom
rocm-prefixgrouper-per-length-check
Nov 23, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
rocm-prefixgrouper-per-length-check

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

What

Follow-up to #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 #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 (#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.

The first-call strict compile check was keyed on (device, dtype, heads,
kv_heads, head_dim, scale). On ROCm, grad-bearing calls use a
dynamic=False flex compile, so every new padded length compiles a new
kernel, and only the first one ran under the check. A later length whose
compile failed was swallowed by unsloth_zoo's suppress_errors and ran
eager flex with full T x T scores.

On the ROCm static path the key now includes T_pad, so each new padded
length gets the strict real call plus forward and backward check, and a
failure turns PrefixGrouper off with the usual message. The dynamic
kernel (CUDA builds, ROCm no-grad calls) is still checked once.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 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-23T05:30:29.653688Z 3578f20 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. Keep it up!

Reviewed commit: 54611d2af2

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

… graph

The dynamic=False compile of the ROCm static entry is inlined when a caller
already traces the attention call, so the padded length stayed symbolic in
that graph. Specialize the Q / K / V sequence sizes at trace time with
unsloth_zoo's specialize_flex_shapes, and drop a caller's dynamic marks on
eager calls, which win over dynamic=False.

[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. More of your lovely PRs please.

Reviewed commit: a8f9d4f8db

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

…nside a graph

The per-length strict check is Dynamo-disabled, so a caller compiling
flex_shared_prefix_attention with fullgraph=True failed with Unsupported on
every padded length it had not seen eagerly, and on a grad call after a
no-grad warm-up at the same length. The merge base keyed the check on the
setup only and passed both.

Inside an enclosing graph, an unseen ROCm padded length now reuses the verdict
of any passed check for the same setup (and its one-stage choice). The eager
check could not test the kernel inlined into that graph anyway. Calls outside
a graph still run the check per padded length.

[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. Chef's kiss.

Reviewed commit: 3578f207c5

ℹ️ 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 03c989b into main Nov 23, 2026
@danielhanchen
danielhanchen deleted the rocm-prefixgrouper-per-length-check branch November 23, 2026 07:24
danielhanchen added a commit that referenced this pull request Nov 23, 2026
…le for Dynamo (#19034)

## Summary

`Repo tests (CPU, rest-2)` fails on PR runs rebased past #18975 (for
example the staging run for #19000), and the same two tests fail on a
local checkout of current `main`:

```
tests/test_prefix_grouper_compile_check.py::test_rocm_new_padded_length_inside_a_fullgraph_compile[grad]
tests/test_prefix_grouper_compile_check.py::test_rocm_new_padded_length_inside_a_fullgraph_compile[no_grad]
E   torch._dynamo.exc.InternalTorchDynamoError: ModuleNotFoundError: No module named '_pg_check_pkg_under_test'
```

Both tests were added by #18975 and already fail at its merge commit
(`03c989b0a7`) with torch 2.10 CPU, the same as CI.

## Root cause

The test, not the kernel. `_load()` imports `prefix_grouper.py` under a
throwaway package and removes it from `sys.modules` straight away. These
two tests are the only ones in the file that wrap the kernel in
`torch.compile(fullgraph=True)`, and Dynamo resolves a traced function's
globals by importing its module by name
(`symbolic_convert._import_module`), so the compile dies on the missing
package before reaching the code under test.

Keeping the package registered exposed a second problem:
`_import_module` is `functools.cache`d for the process, so with one
fixed package name the `[no_grad]` compile resolved the `[grad]` test's
kernel module and guarded on its `_COMPILE_CHECKED` (`Guard failed on
the same frame it was created`). Each parametrization passes on its own.

## Fix

`tests/test_prefix_grouper_compile_check.py` only:

- `_load(monkeypatch)` registers the package and both modules through
`monkeypatch`, so they stay importable for the whole test and are
removed at teardown.
- Each load uses its own package name (`_pg_check_pkg_under_test_<n>`),
so Dynamo's import cache can never hand one test another test's kernel
state.

No change to `unsloth/utils/prefix_grouper_kernel.py`.

## Testing

- `tests/test_prefix_grouper_compile_check.py`: 18 passed (was 2
failed), also under `-n 3`.
- All `tests/test_prefix_grouper*.py`: 100 passed, 3 skipped.
- No `_pg_check_pkg_under_test*` module is left in `sys.modules` after
the file runs.
- Sabotage: removing the kernel's in-graph reuse (`if in_graph_reuse:
needs_check = False`) makes both tests fail, so they now check the
kernel instead of failing before it.
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