Skip to content

GRPO PrefixGrouper: group rows by prompt, gate on saved prompt tokens - #18405

Merged
danielhanchen merged 5 commits into
mainfrom
prefix-grouper-by-prompt
Nov 18, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
prefix-grouper-by-prompt

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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:

  1. groups rows by prompt content instead of by position, so TRL's shuffled micro-batches can use PrefixGrouper;
  2. adds a saved-token cost gate, measured on Colab L4, so short prompts stay on the packed path;
  3. keys the first-use self-verify on a coarse structural class and rounds its length envelope up to a power of two, so the verify forward runs about once per class instead of on about half of all steps.

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

  • Unsloth's GRPO default is gradient_accumulation_steps = 2, so TRL's steps_per_generation is 2, and TRL shuffles the generation batch before splitting it (shuffle_sequence_dict in GRPOTrainer._prepare_inputs).
  • A 4-row micro-batch with num_generations = 4 therefore holds rows like A, B, B, A. build_group_layout assumed rows g*G .. g*G+G-1 share one prompt and declined: 0 layouts in 4 calls on a tiny Qwen3 run, about 6% of micro-batches in real runs.
  • The existing token-reuse gate (tok_r >= 1.3) passes GSM8K-length prompts (about 150 tokens), where the shared-prefix forward costs more than it saves.

Changes

  • build_group_layout and 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_sizes keeps the exact structure.
  • Cost gate: a layout must also save at least UNSLOTH_GRPO_PREFIX_GROUPER_MIN_SAVED (default 1024) prompt tokens per call, (rows - 1) * P summed 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.
  • The no-grad verified envelope (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)

Model prompt tokens saved tokens per call trainer phase on / off (s) change
Qwen3-0.6B 136 172 0.672 / 0.542 +24%
Qwen3-0.6B 1149 2230 0.820 / 1.235 -34%
Qwen3-0.6B 2149 4250 1.46 / 2.42 -40%
Qwen2.5-1.5B 136 94 0.833 / 0.566 +47%
Qwen2.5-1.5B 1149 2147 1.396 / 2.316 -40%
Qwen2.5-1.5B 2149 3255 1.957 / 4.567 -57%

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:

Prompt Arm step s (per run) trainer phase s peak GB layouts / calls verify steps
136 tokens (default) main 1.767, 1.787 0.525, 0.526 8.65 4 / 40 1
this PR 1.671, 1.742 0.518, 0.526 8.64 0 / 40 0
2149 tokens main 4.328, 4.569 2.371, 2.427 9.30 4 / 40 1
this PR 3.618, 3.532 1.483, 1.428 9.15 to 9.18 38-40 / 40 3
  • Default config: within main's A/A spread (1.1%), no regression; the gate declines every micro-batch.
  • 2149-token prompts: step 19.6% faster (median 3.575 vs 4.449 s, main A/A spread 5.4%), trainer phase 39% faster, peak memory 1.4% lower.
  • Without the power-of-two envelope the same config re-verified on 6 to 10 of 20 steps; with it, 3 (one per structural class).

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 main this PR
test_shuffled_micro_batch_still_groups_by_prompt FAIL (None) PASS
test_cost_gate_declines_short_prompts_even_when_reuse_is_high FAIL (main engages at tok_r 1.82) PASS
test_shuffled_group_mixes_share_one_verify_signature FAIL PASS
test_nograd_verify_envelope_is_rounded_up_to_a_power_of_two FAIL PASS
test_layout_semantics_on_random_cases (every target token, predictor, position) PASS PASS
rest of 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.py - 68 passed, 1 CUDA skip, 2 s

The 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

  • Multi-GPU, AMD and T4 / fp16 were not run.
  • Qwen2.5-1.5B was measured before the power-of-two envelope and its win is inside main's A/A spread.
  • Loss and grad-norm parity across arms is not checkable from these runs (vLLM sampling differs between processes); parity rests on the self-verify.

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 18, 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-18T23:06:30.591625Z ad6a9b5 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. Already looking forward to the next diff.

Reviewed commit: ad6a9b5a1f

ℹ️ 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 beec0a3 into main Nov 18, 2026
@danielhanchen
danielhanchen deleted the prefix-grouper-by-prompt branch November 18, 2026 23:56
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.
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