Repository navigation
GRPO PrefixGrouper: group rows by prompt, gate on saved prompt tokens - #18405
Merged
Merged
Conversation
TRL shuffles the generation batch before it splits it into gradient accumulation micro-batches, and Unsloth's GRPO default is gradient_accumulation_steps = 2, so a micro-batch holds a prompt's completions in any order and count. build_group_layout assumed rows g*G .. g*G+G-1 share one prompt and declined every such batch, so the shared-prefix forward never ran in the default config. Group rows by prompt content instead (first-appearance order, batch order inside a group), in both the fast builder and the reference.
Member
Author
|
@codex review |
Codex Review Summary: ✅ CompletedThis 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. Already looking forward to the next diff. 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". |
[skip ci]
danielhanchen
added a commit
to unslothai/unsloth-zoo
that referenced
this pull request
Nov 19, 2026
…r the tiny fixture (#2598) ## Summary `tests/test_grpo_fused_route.py::test_prefix_grouper_forward_matches_log_prob_route` fails all four cases (grpo, dapo, cispo, sapo) against current unsloth main: ``` tests/test_grpo_fused_route.py:251: in test_prefix_grouper_forward_matches_log_prob_route E assert (2 == 2 and False) E + where 2 = len([None, None]) ``` Seen in both unsloth "Core zoo" jobs (HF default + TRL default, and HF 4.57.6 + TRL<1) on the staging run for unslothai/unsloth#18355, which is on current unsloth main. ## Cause unslothai/unsloth#18405 (the companion to #2596) adds a saved-token cost gate to PrefixGrouper. `build_group_layout` returns `None` when a call would save fewer than `UNSLOTH_GRPO_PREFIX_GROUPER_MIN_SAVED` prompt tokens (default 1024, from L4 break-even measurements), so short prompts stay on the faster packed path. That is intended behaviour. This test's fixture is 2 prompts of 4 tokens with 3 completions each, so it saves only a handful of tokens. The gate now declines both layouts, and the test's own assertion (both arms grouped the batch) fails. The test checks that the grouped forward matches the log-prob route. It does not test the gate. Bisected: | unsloth | zoo | result | |---|---|---| | `beec0a3800^` (before #18405) | `11c88bac1` | 4 passed | | `beec0a3800` (#18405) | `11c88bac1` | 4 failed | | `beec0a3800` | `e9728df56` (before #2590 .. #2597) | 4 failed | So the zoo commits are not involved. ## Fix Test-only. `_prefix_grouper_funcs` sets unsloth's `_MIN_SAVED` floor to 0, through `monkeypatch`, when the loaded `prefix_grouper` has one. Older unsloth without the gate is untouched. The test still asserts that both arms built a layout and ran the shared-prefix forward, so if grouping stops engaging for any other reason it still fails. ## Verification `tests/test_grpo_fused_route.py`, all 76 tests: | unsloth | this branch | |---|---| | main (`beec0a3800`, with the gate) | 76 passed (before: 4 failed) | | before #18405 (no gate) | 76 passed | ruff is clean.
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.
Companion to unslothai/unsloth-zoo#2596 (grad-path self-verify envelope).
GRPO PrefixGrouper (the shared-prompt forward) almost never engaged with Unsloth's default GRPO settings, and where it did engage on short prompts it was slower than the packed path. This PR:
Companion unsloth-zoo change: the same power-of-two envelope on the grad path. With an older zoo this PR still works, it only re-verifies more often.
Root cause
gradient_accumulation_steps = 2, so TRL'ssteps_per_generationis 2, and TRL shuffles the generation batch before splitting it (shuffle_sequence_dictinGRPOTrainer._prepare_inputs).num_generations = 4therefore holds rows likeA, B, B, A.build_group_layoutassumed rowsg*G .. g*G+G-1share one prompt and declined: 0 layouts in 4 calls on a tiny Qwen3 run, about 6% of micro-batches in real runs.tok_r >= 1.3) passes GSM8K-length prompts (about 150 tokens), where the shared-prefix forward costs more than it saves.Changes
build_group_layoutand the reference builder group by prompt content. Groups are numbered by first appearance and rows keep batch order, so an already grouped batch gives the same layout as before.layout.group_sizeskeeps the exact structure.UNSLOTH_GRPO_PREFIX_GROUPER_MIN_SAVED(default 1024) prompt tokens per call,(rows - 1) * Psummed over groups. Chosen from the sweep below: break-even is about 670 saved tokens (Qwen3-0.6B) and 560 (Qwen2.5-1.5B).layout.signature(the self-verify / unsafe key) is now("pg", several groups, has a single-row group), at most 4 classes per model, instead of one per group-size mix.(T, longest segment)is stored rounded up to a power of two.Cost gate sweep (Colab L4, PrefixGrouper forced on vs off, self-verify off, GSM8K with a reference text prepended to the prompt)
A/B (Colab L4, main 4071f40 vs this PR, one VM per table, arms interleaved, medians over steps 4 onwards)
Config: Unsloth GRPO defaults (per_device_train_batch_size 4, gradient_accumulation_steps 2, num_generations 4), LoRA r 32, bf16, beta 0, completions up to 256 tokens, 20 steps. torch 2.13.0, transformers 5.17.0, TRL 1.15.0, vLLM 0.29.0.
Qwen3-0.6B, fast_inference=True:
Qwen3-0.6B, fast_inference=False (HF generate), 1149-token prompts, 12 steps: step 5.67 / 5.72 s vs main 6.02 / 6.10 s (6.0% faster, A/A 1.3%), trainer phase 34% faster. Default prompts: 2.388 vs 2.412 s.
Qwen2.5-1.5B, fast_inference=True, 1149-token prompts (before the power-of-two envelope): step 4.403 / 4.627 s vs main 4.785 / 5.282 s (about 10% faster on medians, but main's A/A spread was 10% here). Default prompts: 3.173 vs 3.197 s.
Tests
test_shuffled_micro_batch_still_groups_by_promptNone)test_cost_gate_declines_short_prompts_even_when_reuse_is_hightest_shuffled_group_mixes_share_one_verify_signaturetest_nograd_verify_envelope_is_rounded_up_to_a_power_of_twotest_layout_semantics_on_random_cases(every target token, predictor, position)tests/test_prefix_grouper_layout.py,tests/test_grpo_prefix_grouper_vllm.py,tests/utils/test_grpo_host_syncs.py,tests/test_prefix_grouper_dynamo_limits.py,tests/test_grpo_prefix_grouper_capability.pyThe random layout cases were cut from 400 to 120 smaller ones (slowest test 15 s before, under 1 s now). On one GPU the self-verify against the full-row packed forward passed for every structural class (max abs diff 0.10 to 0.17 nats at T about 2.5K, tolerance 0.7).
Not covered