Skip to content

GRPO PrefixGrouper: build the shared-prefix layout from one host copy instead of per-token loops and per-segment device fills - #15835

Merged
danielhanchen merged 7 commits into
mainfrom
perf/pgvec
Oct 29, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
perf/pgvec

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

What changes

GRPO's PrefixGrouper (on by default for GRPO without vLLM) rebuilds its shared-prefix layout on every microbatch, on the grad path and on the no-grad old log-prob path. build_group_layout read the device several times (cstart.tolist(), input_ids.tolist(), the contiguity bool(), first.tolist(), n_real.tolist(), left_pad.max().item()), walked every completion token in Python to build the index maps, sent each map to the device with its own torch.tensor(..., device=...), and build_seg_info_multigroup made three one-segment device tensors per prefix and per completion.

Now:

  • input_ids, the per-row completion start and the left pad counts come to the host in one copy.

  • Prompt and completion spans are computed per row from that copy; the byte-identical prompt check is one gather per group instead of per-token list compares.

  • The flat stream, positions, target rows / columns / predicting indices and the segment labels are built with repeat_interleave / cumsum on the host and go to the device in one copy. Each returned tensor gets its own storage (contiguous, offset 0), as before.

  • Rows that are not one contiguous real run (a pad id inside a prompt or completion), and inputs outside the covered types (int64 / int32 ids and left pad counts on the same device, a Python int logits_to_keep, num_generations and pad id, with the pad id inside the ids dtype's range), still take the previous token-by-token builder, kept as _build_group_layout_reference.

  • Every host-side table is created with device="cpu", so a script that calls torch.set_default_device("cuda") builds the same layout as main (covered by a test that builds under a meta default device).

The returned GroupLayout and PrefixSegInfo are identical to main's: same tensors, dtypes, shapes, devices, W, tok_r, signatures, and the same None (fall back to the packed path) decisions and exceptions.

Results

Device syncs and CUDA kernels per build_group_layout call (NVIDIA L4, torch 2.14.1, left-packed GRPO rows, torch.cuda.set_sync_debug_mode and the CUDA profiler):

B x (prompt + completion), G syncs main syncs this PR kernels main kernels this PR
8 x (256 + 256), G=8 14 2 64 13
16 x (512 + 512), G=8 13 2 91 13
32 x (1024 + 1024), G=16 13 2 139 13
64 x (2048 + 1024), G=8 13 2 254 13

Wall time per call with an idle GPU, median of 7 repeats of 10 calls (min / max), main measured twice (A/A):

shape main main again this PR
8 x 512 3.17 ms (3.16 / 3.24) 3.17 ms (3.16 / 3.22) 1.43 ms (1.42 / 1.47)
16 x 1024 8.51 ms (8.38 / 11.07) 8.48 ms (8.41 / 8.66) 2.11 ms (2.09 / 3.09)
32 x 2048 25.9 ms (25.6 / 27.4) 26.2 ms (25.7 / 27.8) 3.69 ms (3.67 / 3.78)
64 x 3072 65.4 ms (64.7 / 66.1) 65.3 ms (65.0 / 67.0) 9.40 ms (9.14 / 9.98)

The layout is built twice per GRPO microbatch (old log-probs and the grad forward), so a 32 x 2048 microbatch spends about 44 ms less on it.

End to end (tiny Qwen3 GRPO, jobs/grpo.py --tiny --backend unsloth --max-steps 20, L4, unsloth-zoo main), two batch shapes, each run as main vs this PR and main vs main in the same pass:

shape PrefixGrouper layout loss / grad norm / reward / KL, 20 steps main vs main Dynamo
4 generations, batch 4 1 group of 4 bit-identical bit-identical 0 graph breaks, 7 unique graphs, both arms
3 generations, batch 6 2 groups of 3 bit-identical bit-identical 0 graph breaks, 7 unique graphs, both arms

The PrefixGrouper was engaged on both arms (its first-use check against the full-row packed path logged the same max|d| on both, 0.0002 / 0.0001 and 0.0001). Step time at this size is about 95-107 ms on both arms and the difference is inside the main vs main spread; the layout there is a handful of short rows, where the saving is about a millisecond.

Tests

  • tests/test_prefix_grouper_layout.py (5 tests; the 3 parity and creation-count tests fail on main, where _build_group_layout_reference does not exist and device tensor creations grow per segment):

    • 400 generated batches (left-packed and left-padded rows, pad ids inside runs, prompts that differ inside a group, left pad counts that disagree with the ids, int32 inputs, wrong num_generations, tok_r gate on and off, sliding window caps): the layout equals the token-by-token reference field by field.
    • build_seg_info_multigroup matches a per-token construction, including empty completions and a prefix past one 128 pad block.
    • Device tensor creations do not grow with the number of groups or completions (main makes three per segment).
    • A float or numpy num_generations and a pad id outside the int32 range give the same error, signature types and layout as the reference.
    • On CUDA (L4): main's builder makes more than 2 syncs per call and this one at most 2.
  • Separate parity fuzz against main's module, every output field (values, dtype, device, shape, strides, storage offset) plus the None decision and the exception type and message: 74,000 generated cases on CPU (torch 2.14, and 8,000 on torch 2.6) and 5,000 on CUDA, covering all-pad rows, one-token rows, empty prompts, prompts filling the row, groups of 1, batches not divisible by num_generations, left and right padded prompts, the pad id used as a real token, eos inside completions, rows up to ~2,000 tokens, int64 / int32 / int16 / uint8 / float ids, numpy / tensor / None pad ids and left pad on another device: no mismatch.

  • unsloth_zoo tests/test_grpo_fused_route.py (loads this PrefixGrouper): 76 passed on main and on this branch. tests/test_context_parallel_rl.py: 38 passed on both.

  • Compiles on Python 3.9 and 3.10.

  • In real Unsloth GRPO training (tiny Qwen3, A100, beta=0.04 / num_iterations=2, 1, 2 and 4 groups), every build_group_layout call was also computed with main's builder: 36 calls, 12 shared-prefix layouts, 0 differences.

Not covered

  • Multi-GPU and ROCm / XPU runs were not made; the change is host side and only uses .cpu() / .to(device) copies.
  • The end to end run is a tiny model on one L4; the larger shapes above are measured on the builder alone.
  • One earlier main vs this PR pass on the 3 x 2 shape, run without a main vs main arm, showed a grad norm differing at a later step with loss, reward and KL bit-identical on all 20 steps; the rerun with both arms was bit-identical. The layout tensors are bit-identical by the fuzz above, so this reads as run-to-run accumulation order on the GPU, but it was not traced.
  • transformers / TRL version corners were not swept: the builder is pure torch and none of its inputs or call sites change; the end to end run used the remote's default stack.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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 ⚠️ Failed 2026-10-29T10:22:28.561276Z
We couldn’t complete this review. Comment @codex review to try again.
5a81ea1 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 chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 607b03bb7e

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

Comment thread unsloth/utils/prefix_grouper.py Outdated
keep = ids != pad_id
n_real = keep.sum(dim = 1)
first = torch.argmax(keep.to(torch.int8), dim = 1)
ar = torch.arange(L)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Explicitly place host-side factory tensors on the CPU

When a caller uses torch.set_default_device("cuda") or a CUDA device context, torch.arange(L) is allocated on CUDA even though first and keep were explicitly moved to CPU. The following comparison therefore raises a device-mismatch error instead of building the layout or returning the packed-path fallback. Previously, this factory explicitly used the input device alongside the other tensors. Specify device="cpu" for the new host-side factories throughout this builder and _seg_labels_host so that their placement does not depend on the ambient default device.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 59a71fc: every host-side factory in the fast path and _seg_labels_host now passes device="cpu", with a test that builds under torch.set_default_device("meta") and matches the reference.

@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. Already looking forward to the next diff.

Reviewed commit: 59a71fcbcb

ℹ️ 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 10:22
@danielhanchen
danielhanchen merged commit 9d26414 into main Oct 29, 2026
3 of 32 checks passed
@danielhanchen
danielhanchen deleted the perf/pgvec branch October 29, 2026 10:22
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).
danielhanchen added a commit that referenced this pull request Oct 29, 2026
…Grouper CUDA test on a real card (#15948)

## Summary

Two more checks are red on main itself, so every PR based on it today
inherits them (seen on staging for #15859 and #15936, neither of which
touches these files):

1.
`tests/security/test_lint_risky_loaders.py::test_the_tree_matches_the_baseline`
(workflow-trigger lint):
   ```
   1 risky loader call site(s) not in the baseline:
     unsloth/import_fixes.py:1040  [dynamic-import] import_module
   ```
#15850 added a fourth `importlib.import_module(module_name)` in
`unsloth/import_fixes.py` (the torchao import-time probe). The baseline
keys a call on its source text, so the existing entry for that text
(count 3) now sees 4 and reports the overflow at the first site. The new
call iterates the fixed `_TORCHAO_IMPORT_TIME_MODULES` tuple, so it is
the same trusted shape as the other three. The product is fine; the
baseline needed the count and the reason updated.

2.
`tests/python/test_accelerator_skip_guards.py::test_no_skip_guard_reads_a_spoofable_accelerator_probe`
(Repo tests, CPU):
   ```
   test_prefix_grouper_layout.py:199: torch.cuda.is_available()
   ```
#15835 added `test_cuda_layout_reads_the_device_once_and_copies_once`
gated on `torch.cuda.is_available()`, which
`tests/_zoo_aggressive_cuda_spoof.py` patches to `True` process-wide, so
on a CPU runner sharing a session with the compat suites the test
un-skips and calls `.cuda()`. Here the guard is right and the new test
was wrong: it now gates on `has_real_cuda()` like the other CUDA-only
tests.

## What changed

- `scripts/risky_loaders_baseline.json`: the `59e72c01edb14c86` entry
goes from count 3 to 4 (regenerated with `scripts/lint_risky_loaders.py
--update`, only that line moved), and its reason names
`_TORCHAO_IMPORT_TIME_MODULES` beside the other fixed tables.
- `tests/test_prefix_grouper_layout.py`: `skipif(not has_real_cuda(),
...)` instead of `skipif(not torch.cuda.is_available(), ...)`.

## Verification

- Base (main at `a4aee21490`): both tests fail as above.
- Head: `test_lint_risky_loaders.py`, `test_accelerator_skip_guards.py`
and `test_prefix_grouper_layout.py` give 75 passed, 1 skipped on a
CPU-only run.
- On a real GPU (torch 2.13 + CUDA 13.0) all 6 PrefixGrouper tests run,
including the CUDA one, so the new gate does not skip it on real
hardware.
- Each guard still fails without its fix: putting
`torch.cuda.is_available()` back makes the skip-guard test fail, and
putting the baseline count back to 3 makes the loader lint fail.
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