Skip to content

GRPO PrefixGrouper: fit the flex kernel on 101 KB shared-memory GPUs and stop its silent eager fallback - #15854

Merged
danielhanchen merged 7 commits into
mainfrom
fix/prefix-grouper-compile-check
Oct 29, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
fix/prefix-grouper-compile-check

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

What

GRPO PrefixGrouper runs shared-prefix attention through torch.compile(flex_attention, dynamic=True) and torch.compile(create_block_mask, dynamic=True) in unsloth/utils/prefix_grouper_kernel.py. unsloth_zoo sets torch._dynamo.config.suppress_errors = True, so when Inductor cannot build that kernel, dynamo prints a warning and quietly runs eager flex_attention. Eager flex materialises the full T x T score matrix, which is the cost PrefixGrouper exists to avoid, and the first-step self-verify still passes because eager flex is numerically fine.

Why the kernel does not compile

Two root causes, both reproduced on GPU:

  1. 3-stage tiles overflow shared memory on 101,376 B cards (sm86 / sm89 / sm120: A10, RTX 3090 / 4090, L4, L40S, RTX PRO 6000). On torch 2.7 and 2.8 Inductor sends every sm8x+ card to the A100 config table, which for bf16 head_dim 128 is (BLOCK_M 128, BLOCK_N 64, 8 warps, 3 stages). PrefixGrouper passes BLOCK_M=128, BLOCK_N=64 and inherits the 3 stages, which need 104,448 B:

    No valid triton configs. OutOfResources: out of resource: shared memory, Required: 104448, Hardware limit: 101376.
    

    On torch 2.7.1 this is the silent eager fallback. On torch 2.8.0 it surfaces as a hard error on every call, so the callers' fallback turns PrefixGrouper off. Torch's own default tile and 64 / 64 fail the same way. num_stages=1 fits on 2.7.1 and 2.8.0. Torch 2.15 compiles every tile.

  2. torch 2.7 Inductor fails when the first compiled block mask is a single 128 block (ZeroDivisionError: integer division or modulo by zero, seen on G4 with first calls at T = 40, 100 and 128; a first compile at T >= 129 works, and later small T work after that). Short GRPO rollouts (tiny models, short prompts) hit it on the first step.

Fix

  • The first compiled call per setup (device, dtype, heads, KV heads, head dim, scale) runs inside torch._dynamo.config.patch(suppress_errors=False): the real call, including the block mask build, plus a forward and backward on detached copies of the same inputs. Both use the trainer's shapes, dtype and grad mode, so they build the graphs the following calls reuse.
  • If that strict call fails with "out of resource", it is retried once with num_stages=1; on success that setup keeps one-stage tiles for the process.
  • A block mask that is a single 128 block (T_pad == 128) is built eagerly; that mask is one 128 x 128 block, so this costs microseconds.
  • Any other compile failure records the reason, prints one line, raises PrefixGrouperCompileError, and prefix_grouper_enabled() returns False for the rest of the process. Every PrefixGrouper call site already falls back to the packed path on any exception (the GRPO no-grad pass in rl_replacements.py, its copy in the generated trainer, and unsloth_zoo's grad path, which also gates on prefix_grouper_enabled()). unsloth-zoo needs no change.

Properties: one-time per setup and memoised; suppress_errors restored by the patch context manager on success and failure; no RNG use; the eager compiled=False path is untouched; a CUDA OOM during the check (also one wrapped in BackendCompilerFailed) is re-raised and not cached; UNSLOTH_GRPO_PREFIX_GROUPER_COMPILE_CHECK=0 turns the check off.

GPU runs

Kernel level: prefix_grouper_kernel.py from main and from this branch, suppress_errors=True as unsloth_zoo sets it, bf16, 16 heads, 8 KV heads, head dim 128, multi-group layouts. Per shape: an inference-mode forward, then a forward plus backward. Shapes run in order T = 100, 2830, 4024, every arm in a fresh process, two reps in ABBA order. Error is max |out - fp32 eager reference|.

torch / GPU (smem per block) arm outcome peak MiB T=2830 / 4024 max err out, T=2830
2.7.1 / RTX PRO 6000 (101,376 B) main silent eager fallback (OutOfResources ... 104448) 3325 / 6341 0.0243
2.7.1 / RTX PRO 6000 branch compiles with one-stage tiles 126 to 216 / 133 0.0079
2.8.0 / RTX PRO 6000 main No valid triton configs raised on every call
2.8.0 / RTX PRO 6000 branch compiles with one-stage tiles 123 to 214 / 133 0.0079
2.15.0 / RTX PRO 6000 both compiles, no retry 0.0079
  • The branch's outputs and grads hash identically across both reps and across torch 2.7.1 and 2.8.0.
  • On torch 2.15 main and branch are bit-identical at all three shapes (same sha256 of outputs and grads). The branch compiles one graph fewer (8 vs 7), the T=100 block mask.

Tile sweep on the same inputs (strict compile, forward plus backward, T=2830, median of 5):

torch / GPU 128 / 64 (PrefixGrouper) 128 / 64, num_stages=1 64 / 64 torch default
2.7.1 / L4 fails, 104,448 B 26.2 ms fails, 106,304 B fails, 104,448 B
2.15.0 / L4 2.42 ms 2.76 ms 2.52 ms 2.42 ms
2.7.1 / RTX PRO 6000 fails 3.06 ms fails fails
2.8.0 / RTX PRO 6000 fails 2.99 ms fails fails
2.15.0 / RTX PRO 6000 0.98 ms 1.02 ms 1.04 ms 1.02 ms

Every tile that compiled gave the same max error against the fp32 reference (0.0082 output, 0.0125 dQ on L4).

Block mask sweep (strict compile of the block mask, compared with the eager mask, T = 40 to 2830 ascending then descending, fresh process each): every T compiles and matches the eager mask on L4 2.7.1, L4 2.15, G4 2.8.0 and G4 2.15, and on CPU torch 2.7.1 and 2.14.1. G4 2.7.1 ascending fails at T = 40, 100 and 128 with ZeroDivisionError, which the eager single-block mask avoids.

End to end: jobs/grpo.py base vs head through the regression switchboard on a Colab A100: NO_REGRESSION.

Earlier end-to-end runs of the first version of this change (jobs/grpo.py --tiny --backend unsloth --max-steps 20, tiny Qwen3, seed 3407, transformers 4.57.6, TRL 0.22.2, PEFT 0.18.0): on 2.7.1 / L4, main ran eager PrefixGrouper (median step 228 / 263 ms over two runs) while the branch fell back to the packed path (103 ms, bit-identical to UNSLOTH_GRPO_PREFIX_GROUPER=0); on 2.8 and 2.14 / L4 main and branch were bit-identical over all 20 steps with the same compiled graphs.

Tests

tests/test_prefix_grouper_compile_check.py loads the kernel and prefix_grouper.py from their files and swaps the compiled callables for eager stand-ins, so it runs on CPU:

  • test_success_runs_the_check_once_and_keeps_numerics, test_first_call_under_inference_mode, test_new_head_layout_is_checked_once
  • test_compile_failure_turns_prefix_grouper_off_once, test_backward_compile_failure_is_caught, test_real_dynamo_failure_is_silent_without_the_check
  • test_shared_memory_overflow_retries_with_one_stage: a 3-stage overflow retries with num_stages=1, PrefixGrouper stays on, later calls keep one stage.
  • test_single_block_mask_is_built_eagerly: T_pad == 128 builds the mask eagerly, larger masks compile.
  • test_oom_while_compiling_is_not_cached, test_oom_in_the_check_is_not_cached, test_eager_path_skips_the_check, test_kill_switch.
main this branch
tests/test_prefix_grouper_compile_check.py, torch 2.14.1 CPU fails 12 passed
same, torch 2.7.1 CPU 12 passed
tests/test_context_parallel_rl.py + the file above 50 passed

Not covered

  • torch 2.6: PrefixGrouper stays off below 2.7 (GRPO PrefixGrouper: import cleanly on torch 2.6 and keep it off below 2.7 with a log line #15836). Not run on this branch.
  • H100 / B200 / A100 were not rerun after the one-stage retry; on those cards the retry never triggers (the default tiles fit), and the A100 switchboard GRPO job shows no regression.
  • ROCm, Windows, multi-GPU: the check and retry are generic, but only NVIDIA L4, A100 and RTX PRO 6000 were exercised.
  • Real models at long sequence lengths: kernel-level numbers use realistic head counts up to T=4024.
  • One-stage tiles on torch 2.7.1 / L4 run 26 ms forward plus backward at T=2830, about 10x slower than 2.15 on the same card. Unmeasured against the packed path end to end on that corner.
  • An error on the first call that is not a compile error (other than CUDA OOM) also turns PrefixGrouper off for the process: the conservative direction.
  • The check runs once per setup, not per shape. If a later shape forced a recompile that failed, that call would fall back silently, as on main.
  • On the first call the check holds detached copies of q / k / v plus a forward and backward, so that call peaks like a training attention call even on the no-grad pass. An OOM there goes to the caller, whose no-grad handler turns no-grad PrefixGrouper off for the run (as main does for any PrefixGrouper error).
  • torch._dynamo.config.patch changes a process-wide setting while the check runs, so another thread compiling at that moment would also run strict.
  • Merged with main after GRPO PrefixGrouper: build the shared-prefix layout from one host copy instead of per-token loops and per-segment device fills #15835 and GRPO PrefixGrouper: import cleanly on torch 2.6 and keep it off below 2.7 with a log line #15836: prefix_grouper_enabled() keeps GRPO PrefixGrouper: import cleanly on torch 2.6 and keep it off below 2.7 with a log line #15836's torch >= 2.7 gate and log line and also requires compile_check_failed() is None.
  • tests/utils/test_grpo_host_syncs.py::test_build_group_layout_single_read_same_inputs fails on CPU on main and on this branch alike (pre-existing).

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-10-29T11:06:01.141093Z 902841a Draft marked ready
ℹ️ 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. Delightful!

Reviewed commit: 1d7cc6d36f

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

…, build single-block masks eagerly

[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. Delightful!

Reviewed commit: 834675eb71

ℹ️ 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 changed the title GRPO: turn PrefixGrouper off when its flex kernel fails to compile instead of silently running eager flex GRPO PrefixGrouper: fit the flex kernel on 101 KB shared-memory GPUs and stop its silent eager fallback Oct 29, 2026
# Conflicts:
#	unsloth/utils/prefix_grouper.py
#	unsloth/utils/prefix_grouper_kernel.py
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 902841ac8c

ℹ️ 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 marked this pull request as ready for review October 29, 2026 11:05
@danielhanchen
danielhanchen merged commit 98c3114 into main Oct 29, 2026
3 of 31 checks passed
@danielhanchen
danielhanchen deleted the fix/prefix-grouper-compile-check branch October 29, 2026 11:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant