Repository navigation
GRPO PrefixGrouper: import cleanly on torch 2.6 and keep it off below 2.7 with a log line - #15836
Merged
Merged
Conversation
danielhanchen
added a commit
to danielhanchen/unsloth-staging-2
that referenced
this pull request
Oct 28, 2026
Member
Author
|
@codex review |
1 similar comment
Member
Author
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Didn't find any major issues. Can't wait for the next one! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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
marked this pull request as ready for review
October 29, 2026 10:14
danielhanchen
added a commit
to danielhanchen/unsloth-staging-2
that referenced
this pull request
Oct 29, 2026
…and stop its silent eager fallback (unslothai#15854) ## 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 (unslothai#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 unslothai#15835 and unslothai#15836: `prefix_grouper_enabled()` keeps unslothai#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).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
unsloth/utils/prefix_grouper_kernel.pyraises dynamo's recompile limits at import by writingtorch._dynamo.config.recompile_limitandaccumulated_recompile_limit. Those names only exist from torch 2.7. On torch 2.6, which is still the supported floor, dynamo's config refuses unknown names, so the import raises:Both callers import the kernel inside
try/except Exception(rl_replacements.pyfor the GRPO PrefixGrouper gate, plus the matching block in the generated GRPO trainer, andattention_dispatch.pyforflex_shared_prefix_attention). The error never reaches the user, and PrefixGrouper is silently off on torch 2.6.Off is the right outcome on torch 2.6, it just happens for the wrong reason. On a torch 2.6 GPU (L4, torch 2.6.0+cu124, triton 3.2.0) neither compiled callable in the kernel builds:
torch.compile(create_block_mask, dynamic=True)fails in inductor codegen withZeroDivisionError.torch.compile(flex_attention, dynamic=True)with the kernel's block sizes fails withNameError: name 's20' is not defined(the symbolic block sizes leak into the generated code).unsloth_zoo sets
torch._dynamo.config.suppress_errors = True, so both failures fall back to eagerflex_attentionwithout any message. Eager flex builds the full T x T score matrix. That is the cost PrefixGrouper exists to avoid: at bf16, 16 heads, head dim 128, a forward plus backward peaks at 6247 MiB at T=4024 against 134 MiB for the compiled kernel on torch 2.8 (about 47x, and it grows with T squared). Simply fixing the import would turn this slow path on for every torch 2.6 GRPO user.Fix
recompile_limitif it exists, otherwisecache_size_limit(same for the accumulated limit), the pattern_block_compile.pyand_decision_fast.pyalready use.prefix_grouper_kernel.pygetstorch_supports_prefix_grouper()(major.minor oftorch.__version__>= 2.7; an unparsable version counts as supported, so nightlies like2.7.0a0+git...stay on). Below 2.7:prefix_grouper_enabled()returns False and prints one line, once per process, the first time GRPO asks:Unsloth: GRPO PrefixGrouper is off on torch 2.6.0+cu124 (needs torch >= 2.7: its flex attention kernel does not compile there); using the packed path.This is the single gate every caller consults: the GRPO trainer in
rl_replacements.py, the copy of that block in the generated trainer cache, and unsloth_zoo's grad path (grpo_accumulated_lossimports and callsunsloth.utils.prefix_grouper.prefix_grouper_enabled), so unsloth-zoo needs no change.attention_dispatch.pykeeps its pre-resolved kernel atNone, as on main.Nothing is printed when
UNSLOTH_GRPO_PREFIX_GROUPER=0or sequence packing is off, or for users who never run GRPO.On torch 2.7 and newer nothing changes: the gate is open, the same limits are raised to the same values (256 / 2048, never lowered), and
prefix_grouper_enabled()returns exactly what it returned before.What torch 2.6 users see after this change:
import unslothno longer has a swallowedAttributeErrorbehind it, and the first GRPO step prints the line above. Training takes the same packed path as on main.Tests
tests/test_prefix_grouper_dynamo_limits.pyloads the kernel andprefix_grouper.pyfrom their files, without importing all of unsloth:test_import_raises_the_old_names_when_only_they_exist: with a dynamo config that only has the old names and refuses unknown writes, the import succeeds and raisescache_size_limit/accumulated_cache_size_limit.test_import_raises_the_new_names_when_present: torch 2.7+ still gets 256 / 2048, and a higher user-set limit is not lowered.test_torch_version_gate:2.6.0+cu124,2.5.1,1.13.1are off;2.7.0a0+git1234,2.7.1,2.10.0,3.0.0and an unparsable version are on.test_torch_26_import_is_clean_and_leaves_dynamo_alone: withtorch.__version__set to2.6.0+cu124and the old-style config, the import succeeds and both limits keep their values (8 / 256).test_torch_26_prefix_grouper_off_with_one_log: same simulated torch 2.6. Nothing is printed at import,prefix_grouper_enabled()is False, and exactly one line is printed on the first call and none on the second.test_torch_26_env_off_stays_quiet: withUNSLOTH_GRPO_PREFIX_GROUPER=0there is no log.test_torch_27_plus_unchanged(2.7.1, 2.8.0, 2.14.1):prefix_grouper_enabled()is True with no output, and False when sequence packing is off, the same as main.tests/test_block_compile.py,test_context_parallel_rl.py,test_grpo_legacy_trl_vision.py,test_grpo_width_dispatch_sites.pyandtest_ulysses.pygive the same result on main and on this branch: 111 passed, 11 skipped, andtest_block_compile.py::test_sm_count_is_read_outside_the_tracefails on both.GPU run (torch 2.6)
Colab L4, torch 2.6.0+cu124, triton 3.2.0, transformers 4.57.6, TRL 0.22.2, PEFT 0.18.0, current unsloth-zoo main. The job is a tiny Qwen3 GRPO run with the unsloth backend: 20 steps, 4 generations, batch 4, seed 3407. Arms: main default, this branch default, main default again (A/A), and main with
UNSLOTH_GRPO_PREFIX_GROUPER=0. A wrapper counts kernel imports and flex calls.AttributeError(swallowed)AttributeError(swallowed)... does not compile there); using the packed path.lineMedian step time over steps 3-20 was within about 1 ms across the arms (94.9 to 95.7 ms on a shared card).
GPU probe (torch 2.6 vs 2.7.1 vs 2.8, A100)
Colab A100-SXM4-40GB, the kernel file from this branch,
suppress_errors=False, fp32 and bf16, forward plus backward throughflex_shared_prefix_attentionon two packed groups:TORCH_SUPPORTS_PREFIX_GROUPERBackendCompilerFailed/BackendCompilerFailedSo the torch 2.6 compile failure is not L4 specific. The dynamic block mask compiled at this shape on 2.6; the flex kernel did not.
Regression run (torch 2.13, A100)
Switchboard base vs head at
326523f8b: Studio auth / settings / crawl journeys show no functional change, andjobs/grpo.pyon a Colab A100 is NO_REGRESSION (all checks hold, step time -8.1%, peak memory and compile graph counts unchanged; step 1 and 3 losses move with GRPO sampling, step 2 identical).Not covered
regression_smokedid not run for this head (no local GPU in that session).shared memory 104448 > 101376) and silently runs eager today. That needs a compile check rather than a version gate and is handled in a follow-up.