Repository navigation
Add PrefixGrouper for GRPO: dedup the shared prompt across a group's completions - #6871
Conversation
Add an opt-in sequence-packing fast path to _get_per_token_logps_and_entropies, enabled with UNSLOTH_GRPO_SEQ_PACKING=1. When the batch is text-only, the padded [B, Lmax] per-chunk forward is replaced by a single varlen [1, sum L] forward (BlockDiagonalCausalMask via packed_seq_lengths with reset position_ids). Per-token logps use the same float32 chunked_hidden_states_selective_log_softmax as the padded path, so the old and reference logps are bit-for-bit identical. Safety: the packed path is self-verified once against the padded ground truth on a batch that has at least two rows with real completion tokens (self._unsloth_seq_packing_nograd_ok), so cross-sample contamination would actually manifest; a degenerate all-pad / fully tool-masked batch leaves the verdict unset and re-verifies later. If a backend silently ignores packed_seq_lengths (flat batch run under a normal causal mask, samples leaking across boundaries), the packed logps will not match and packing is disabled instead of corrupting logps. It also forces use_cache=False (a populated past_key_value disables varlen packing), skips packing when a sliding window is shorter than the packed stream, runs the same GPT-OSS offload device_synchronize the padded loop uses, and falls back on any exception (UNSLOTH_GRPO_SEQ_PACKING_DEBUG=1 prints the reason). Default off, so existing behavior is unchanged. Pairs with the matching gradient-path change in unsloth_zoo so the full GRPO logp + loss + backward can run packed.
- Cache the packed-vs-padded verdict per unwrapped model instead of on the trainer, so a separately forwarded reference model is verified on its own forward path rather than inheriting the policy model's verdict. - Force the padded path when token_type_ids or mm_token_type_ids are present, matching the extra vision kwargs the padded loop forwards. - Require the xformers varlen backend before packing. Without it the packed mask falls back to a dense O(T^2) SDPA mask that can OOM on the flattened batch, so we keep the padded loop in that case. - On any packed-forward failure (missing backend, OOM, unsupported forward) empty the cache on OOM, disable packing for that model, and fall back to the chunked padded loop instead of retrying every step.
Redesign of the optional sequence-packing fast path for the no-grad old/ref logprob recompute, after establishing that the packed forward is the exact per-row computation and the padded batch forward is the side that mis-positions left-padded rows on long completions. - Default the packing on (UNSLOTH_GRPO_SEQ_PACKING, disable with 0). - Verify the packed logprobs against the per-row clean forward (each row's real tokens alone, reset 0-based positions, no padding), not the padded batch which is itself wrong for left-padding. Cross-sample contamination (a backend ignoring packed_seq_lengths) shows up as a large mismatch and falls back to the padded loop. - Make the trust decision shape and RoPE aware: re-verify whenever the packed total length or the longest segment grows past what was verified, so a later batch crossing a LongRoPE short/long cache boundary is re-checked instead of trusted blindly. - Run lm_head only on completion-prediction positions instead of every packed prompt token, so long-prompt/short-completion batches do not pay for projecting the whole packed prompt. - Drop the hard xformers import so the path also runs in FlashAttention-only environments; the per-row verification guards correctness regardless of backend.
When the per-row verification fails, distinguish the two failure modes by magnitude instead of by sequence length: - A large mismatch (>= 1.5) is the cross-sample contamination signature: the model's attention does not honor the block-diagonal packed mask (seen on some MoE / custom-attention models, e.g. qwen2_moe). Disable packing entirely for the model so later batches do not pay the verification cost again. - A moderate mismatch is more likely a length-boundary effect (a LongRoPE short/long cache switch): keep marking just that length region unsafe so packing still runs for smaller shapes. Validated: Qwen1.5-MoE falls back after a single verification (grad and no-grad ok flags go False, no re-verify on later steps); dense Llama-3.2 and Qwen3 still verify and engage packing.
… rows The completion-target selection used a single global boundary (col >= L - logits_to_keep). After left-packing, each row's completion starts at (L - logits_to_keep) - left_pad[row], so for left-padded rows the first left_pad completion tokens fall below the global boundary and were dropped, leaving 0 logprobs at real completion positions that the loss mask keeps. Use the per-row boundary so packed coverage matches create_completion_attention_mask exactly, and widen the self-verify mask to the full per-row completion region so it can catch coverage gaps.
Count active rows via create_completion_attention_mask (the same mask the loss uses) instead of any non-pad token in the packed window. Prompt-only rows carry prompt-overflow tokens in the window and could otherwise satisfy the >= 2 verification guard, letting a batch with a single real completion row cache a trust decision. This matches the gradient path, which already gates on the completion mask. The same mask is reused for the self-verify comparison.
Use the shared UNSLOTH_ENABLE_LOGGING global (import_fixes, re-exported by _utils) instead of a bespoke UNSLOTH_GRPO_SEQ_PACKING_DEBUG env var for the packing debug prints, matching the rest of the codebase.
…function _get_per_token_logps_and_entropies is copied verbatim into the generated GRPO trainer via inspect.getsource, and that module never imported UNSLOTH_ENABLE_LOGGING, so the default-on packing verify path raised NameError (and the except handler re-raised it). Import the flag locally, before the try, so the name is defined in the generated module too. Drop it from the now-unused module-level import.
…ck cleanup Three fixes to the no-grad logp packing path, mirroring the grad path: - skip the packed forward for known-unsafe lengths by reading unsafe_T and gating on it before the forward, instead of running the full packed pass and the result build only to discard them (wastes a pass, can OOM at large T) - only widen the verified T/seg envelope when >= 2 completion rows actually exercised cross-sample packing; a < 2 row batch cannot expose leakage, so it must not extend the trusted shape that later multi-row batches skip verify for - drop the packed intermediates (hidden/sel/result/ref) before the padded fallback loop so it does not run with the flattened hidden state still resident
The packed path built a single [1, sum L] forward over every row before any size check, so a large batch could exceed the memory the padded path bounds per mini-batch. Gate packing on _pk_T <= _pk_cap (B * seq_len, one padded mini-batch's token budget); larger batches fall back to the chunked padded loop.
…n guard The packed path leaves masked prompt/pad logprob columns at 0, which only stays finite if unsloth_zoo grpo_compute_loss zeroes them before exp() (zoo#840). An older unsloth_zoo without that guard would NaN. Detect the guard once (cached on the model) via inspect.getsource and gate packing on it, so #6738 is safe with any unsloth_zoo version and re-enables packing automatically once a guarded zoo is installed, independent of the pinned lower bound.
Benchmark and correctnessNotation: for a group of G completions sharing a prompt of length P with mean completion length R, let Correctness (Qwen2.5-0.5B and a real-model check):
Isolated training forward + backward on a real model (Qwen3-4B,
Kernel micro-benchmark (attention op, swept over P, R, G): memory always wins and tracks Honest note on end-to-end: with a colocated vLLM rollout ( |
|
Warning Gemini encountered an error creating the review. You can try again by commenting |
|
@codex review |
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces PrefixGrouper, a feature designed to optimize GRPO training by deduplicating shared prompt prefixes using a custom FlexAttention kernel. This optimization is integrated across several model architectures and the RL training pipeline. The review feedback highlights a performance bottleneck in unsloth/utils/prefix_grouper.py, where nested list comprehensions over the sequence length L are performed on the CPU. The reviewer suggests computing the number of real tokens per row on the GPU instead, which avoids these redundant CPU iterations and significantly improves efficiency.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| def _build_groups(ids_cpu, real_cols_cpu, cstart_cpu, num_generations, total_rows): | ||
| """CPU-side grouping. Returns group dicts or None. Mirrors the packed _pk_* partition. | ||
|
|
||
| A row's REAL tokens are the columns where input != pad. Its completion region (what | ||
| the packed path scatters, then completion_mask masks) is the real columns with | ||
| original col >= cstart_r, where cstart_r = (L - logits_to_keep) - left_pad_r. The | ||
| prompt is the real columns < cstart_r. Within a GRPO group all G rows share the same | ||
| prompt => same left_pad => same cstart => the prompt real columns are BYTE-IDENTICAL | ||
| across the group (the shared prefix). We require that byte-identity (falls back | ||
| otherwise). No prompt-tail special-casing: every suffix token is scattered exactly | ||
| like the packed path; completion_mask masks the leading prompt-tail positions. | ||
| """ | ||
| G = num_generations | ||
| if G is None or G < 2 or total_rows % G != 0: | ||
| return None | ||
| groups = [] | ||
| for g0 in range(0, total_rows, G): | ||
| rows = list(range(g0, g0 + G)) | ||
| prompt_cols_per_row = [] # real cols < cstart | ||
| prompt_toks_per_row = [] | ||
| comp_cols_per_row = [] # real cols >= cstart (the completion region packed scatters) | ||
| for r in rows: | ||
| cs = cstart_cpu[r] | ||
| rc = real_cols_cpu[r] | ||
| p_cols = [c for c in rc if c < cs] | ||
| c_cols = [c for c in rc if c >= cs] | ||
| prompt_cols_per_row.append(p_cols) | ||
| prompt_toks_per_row.append([ids_cpu[r][c] for c in p_cols]) | ||
| comp_cols_per_row.append(c_cols) | ||
| if any(len(p) == 0 for p in prompt_toks_per_row): | ||
| return None | ||
| # require BYTE-IDENTICAL prompts across the group (shared-prefix precondition). | ||
| P = len(prompt_toks_per_row[0]) | ||
| if any(len(prompt_toks_per_row[k]) != P for k in range(1, G)): | ||
| return None | ||
| p0 = prompt_toks_per_row[0] | ||
| if any(prompt_toks_per_row[k] != p0 for k in range(1, G)): | ||
| return None | ||
| if P == 0: | ||
| return None | ||
| R_list = [len(c) for c in comp_cols_per_row] | ||
| if sum(R_list) == 0: | ||
| return None | ||
| groups.append( | ||
| dict( | ||
| rows = rows, | ||
| P = P, | ||
| prefix_cols = prompt_cols_per_row[0], # shared prompt real columns (row0) | ||
| prefix_row = rows[0], | ||
| R_list = R_list, | ||
| suf_cols = comp_cols_per_row, # per-row completion-region real columns | ||
| ) | ||
| ) | ||
| return groups |
There was a problem hiding this comment.
Since input_ids is guaranteed to be left-packed when build_group_layout is called (as PrefixGrouper is only engaged when pixel_values is None, where input_ids is left-packed beforehand), the real non-pad tokens for any row r always form a contiguous range starting at column 0 up to num_real_tokens[r].
Converting the entire keep tensor to a Python list and performing nested list comprehensions over L (which can be 4096 or 8192) for every row is highly inefficient and causes a significant CPU-GPU synchronization and CPU overhead.
We can optimize this by computing the number of real tokens per row on the GPU using keep.sum(dim=1).tolist(), and then constructing p_cols and c_cols directly using range on the CPU. This completely avoids the nested list comprehensions over L. Additionally, we combine the prompt validation checks and transformations into a single loop to avoid redundant iterations over the rows.
def _build_groups(ids_cpu, num_real_tokens, cstart_cpu, num_generations, total_rows):
"""CPU-side grouping. Returns group dicts or None. Mirrors the packed _pk_* partition.
A row's REAL tokens are the columns where input != pad. Its completion region (what
the packed path scatters, then completion_mask masks) is the real columns with
original col >= cstart_r, where cstart_r = (L - logits_to_keep) - left_pad_r. The
prompt is the real columns < cstart_r. Within a GRPO group all G rows share the same
prompt => same left_pad => same cstart => the prompt real columns are BYTE-IDENTICAL
across the group (the shared prefix). We require that byte-identity (falls back
otherwise). No prompt-tail special-casing: every suffix token is scattered exactly
like the packed path; completion_mask masks the leading prompt-tail positions.
"""
G = num_generations
if G is None or G < 2 or total_rows % G != 0:
return None
groups = []
for g0 in range(0, total_rows, G):
rows = list(range(g0, g0 + G))
prompt_cols_per_row = [] # real cols < cstart
comp_cols_per_row = [] # real cols >= cstart (the completion region packed scatters)
p0 = None
P = 0
valid = True
for i, r in enumerate(rows):
cs = cstart_cpu[r]
n_real = num_real_tokens[r]
p_cols = list(range(cs))
c_cols = list(range(cs, n_real))
prompt_cols_per_row.append(p_cols)
p_toks = ids_cpu[r][:cs]
if len(p_toks) == 0:
valid = False
break
if i == 0:
p0 = p_toks
P = len(p0)
else:
if len(p_toks) != P or p_toks != p0:
valid = False
break
comp_cols_per_row.append(c_cols)
if not valid or P == 0:
return None
R_list = [len(c) for c in comp_cols_per_row]
if sum(R_list) == 0:
return None
groups.append(
dict(
rows = rows,
P = P,
prefix_cols = prompt_cols_per_row[0], # shared prompt real columns (row0)
prefix_row = rows[0],
R_list = R_list,
suf_cols = comp_cols_per_row, # per-row completion-region real columns
)
)
return groupsReferences
- To improve efficiency, avoid redundant data iterations. Combine checks and transformations into a single loop and return computed values for callers to reuse.
There was a problem hiding this comment.
The inefficiency is real but the suggested code is not safe at this call site: the no-grad path input is left-padded (prompt) plus right-padded (completion), so the real run does not start at column 0 and range(cs) would classify leading pad columns as prompt tokens (only the grad path in unsloth-zoo passes left-packed ids). Applied a variant instead: derive the contiguous run [first, first+n) per row on GPU with a vectorized contiguity check, falling back to the general scan for non-contiguous rows. Both layouts verified equivalent to the old scan.
| device = input_ids.device | ||
| total_rows, L = input_ids.shape | ||
| keep = input_ids != pad_id | ||
| # completion start column per row (matches create_completion_attention_mask / _pk_cstart). | ||
| cstart = ((L - logits_to_keep) - left_pad_tokens_per_prompt).to(torch.long) | ||
| cstart_cpu = cstart.tolist() | ||
| ids_cpu = input_ids.tolist() | ||
| keep_cpu = keep.tolist() | ||
| # per-row list of ORIGINAL real (non-pad) columns, ascending. | ||
| real_cols_cpu = [[c for c in range(L) if keep_cpu[r][c]] for r in range(total_rows)] | ||
|
|
||
| groups = _build_groups(ids_cpu, real_cols_cpu, cstart_cpu, num_generations, total_rows) |
There was a problem hiding this comment.
Corresponding optimization in build_group_layout to compute num_real_tokens on the GPU and pass it to _build_groups, completely avoiding the nested list comprehension over L.
| device = input_ids.device | |
| total_rows, L = input_ids.shape | |
| keep = input_ids != pad_id | |
| # completion start column per row (matches create_completion_attention_mask / _pk_cstart). | |
| cstart = ((L - logits_to_keep) - left_pad_tokens_per_prompt).to(torch.long) | |
| cstart_cpu = cstart.tolist() | |
| ids_cpu = input_ids.tolist() | |
| keep_cpu = keep.tolist() | |
| # per-row list of ORIGINAL real (non-pad) columns, ascending. | |
| real_cols_cpu = [[c for c in range(L) if keep_cpu[r][c]] for r in range(total_rows)] | |
| groups = _build_groups(ids_cpu, real_cols_cpu, cstart_cpu, num_generations, total_rows) | |
| device = input_ids.device | |
| total_rows, L = input_ids.shape | |
| keep = input_ids != pad_id | |
| # completion start column per row (matches create_completion_attention_mask / _pk_cstart). | |
| cstart = ((L - logits_to_keep) - left_pad_tokens_per_prompt).to(torch.long) | |
| cstart_cpu = cstart.tolist() | |
| ids_cpu = input_ids.tolist() | |
| num_real_tokens = keep.sum(dim=1).tolist() | |
| groups = _build_groups(ids_cpu, num_real_tokens, cstart_cpu, num_generations, total_rows) |
|
Codex Review: Didn't find any major issues. Keep it up! 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". |
|
@codex review |
|
No verdict came back on the previous trigger, re-running on the current head. @codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f2ba5cbfb1
ℹ️ 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".
| A = flex_shared_prefix_attention( | ||
| Q.transpose(1, 2), | ||
| K.transpose(1, 2), | ||
| V.transpose(1, 2), | ||
| context.prefix_seg_info, | ||
| scale = scale, | ||
| ) |
There was a problem hiding this comment.
Preserve attention dropout in PrefixGrouper
When PrefixGrouper is used while the model is in training mode with nonzero attention dropout, this FlexAttention path drops the configured dropout entirely, so it no longer matches the normal attention computation. For example, Granite sets dropout_p = self.config.attention_dropout if self.training else 0 and passes it through the regular SDPA/xFormers configs in unsloth/models/granite.py, but this branch only forwards scale; a dropout-enabled Granite/PG training forward (including companion grad-path callers that pass prefix_seg_info) will therefore train on different activations/gradients rather than a deduplicated equivalent. Please thread the configured dropout into the FlexAttention call or disable PrefixGrouper for dropout-enabled training configs.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and I had this wrong on the earlier round. Granite (and the other threaded arches) set dropout_p = config.attention_dropout when training and pass it to the dense flash/sdpa/xformers configs, but the shared-prefix FlexAttention path is deterministic. Fixed in 350cadf by gating PrefixGrouper off when config.attention_dropout is nonzero, alongside the softcap and hybrid-SSM/MoE exclusions, so those configs stay on the normal packed path. Apologies for the earlier thumbs-down; re-verified against granite.py and this is right.
There was a problem hiding this comment.
Correct, and I had this wrong on the earlier round. Granite (and the other threaded arches) set dropout_p = config.attention_dropout when training and pass it to the dense flash/sdpa/xformers configs, but the shared-prefix FlexAttention path is deterministic. Fixed in 350cadf by gating PrefixGrouper off when config.attention_dropout is nonzero, alongside the softcap and hybrid-SSM/MoE exclusions, so those configs stay on the normal packed path. Apologies for the earlier thumbs-down; re-verified against granite.py and this is right.
| prefix_seg_info = seg, | ||
| tgt_rows = torch.tensor(tgt_rows, device = device, dtype = torch.long), | ||
| tgt_cols = torch.tensor(tgt_cols, device = device, dtype = torch.long), | ||
| tgt_pred = torch.tensor(tgt_pred, device = device, dtype = torch.long), | ||
| tgt_flat = torch.tensor(tgt_flat, device = device, dtype = torch.long), |
There was a problem hiding this comment.
Move prefix layout tensors to consumer devices
With a sharded/model-parallel GRPO run, these layout tensors remain pinned to the original input_ids.device, but their consumers are not guaranteed to run there: FlexAttention builds masks on each layer's Q.device, and extract_logps indexes hidden states after they have been moved to the lm-head/last-layer device. Unlike get_packed_info_from_kwargs, which copies packed metadata to Q.device, PrefixGrouper reuses these tensors as-is, so any decoder layer or lm head on another GPU will hit cross-device indexing; move/copy the segment and target index tensors to the current consumer device before use.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct. The layout/mask tensors were pinned to input_ids.device while the FlexAttention mask builds on Q.device and extract_logps indexes hidden on the lm-head device. Fixed in 350cadf: get_block_mask now moves the seg label tensors to the consumer device (cache is keyed on (signature, device) so it copies once per device), and extract_logps moves the target index maps to hidden.device, mirroring how the packed path moves its metadata. Verified with a two-GPU test (layout on cuda:0, hidden/lm_head on cuda:1) matching the same-device result exactly.
There was a problem hiding this comment.
Correct. The layout/mask tensors were pinned to input_ids.device while the FlexAttention mask builds on Q.device and extract_logps indexes hidden on the lm-head device. Fixed in 350cadf: get_block_mask now moves the seg label tensors to the consumer device (cache is keyed on (signature, device) so it copies once per device), and extract_logps moves the target index maps to hidden.device, mirroring how the packed path moves its metadata. Verified with a two-GPU test (layout on cuda:0, hidden/lm_head on cuda:1) matching the same-device result exactly.
| # PrefixGrouper: shared-prefix segment table rides in **kwargs from the GRPO logprob | ||
| # forward. resolve_prefix_seg_info hardens the misuse case (KV cache / padding mask -> | ||
| # raise). None => byte-identical default. | ||
| _pg_seg = resolve_prefix_seg_info(kwargs, past_key_value, attention_mask) |
There was a problem hiding this comment.
Bypass synthetic masks for Mistral PrefixGrouper
For Mistral eval/no-grad runs when xFormers is unavailable or disabled, MistralForCausalLM_fast_forward creates an internal causal attention_mask even when the caller passed none. This added resolver then treats that internally-created mask as a PrefixGrouper misuse and raises, so the advertised Mistral PrefixGrouper path always falls back to the full packed/padded forward on those setups; resolve before synthesizing the mask or skip that mask when prefix_seg_info is present.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct. On the no-xFormers path MistralForCausalLM_fast_forward synthesized an internal causal attention_mask even when the caller passed none, which resolve_prefix_seg_info then treated as misuse and forced a fallback. Fixed in 350cadf by skipping that synthesis when prefix_seg_info is present, so PrefixGrouper supplies its own shared-prefix mask via FlexAttention. Non-PG forwards still synthesize the mask as before.
There was a problem hiding this comment.
Correct. On the no-xFormers path MistralForCausalLM_fast_forward synthesized an internal causal attention_mask even when the caller passed none, which resolve_prefix_seg_info then treated as misuse and forced a fallback. Fixed in 350cadf by skipping that synthesis when prefix_seg_info is present, so PrefixGrouper supplies its own shared-prefix mask via FlexAttention. Non-PG forwards still synthesize the mask as before.
Addresses three review findings on the shared-prefix path: - Skip PrefixGrouper when the model sets a nonzero attention_dropout. The normal backends apply config.attention_dropout while training (e.g. Granite dense flash/sdpa/xformers), but the FlexAttention shared-prefix path is deterministic, so gate PG off for those configs rather than train on mismatched activations. - Move the shared-prefix mask labels to the consumer (Q) device in get_block_mask and the target index maps to hidden.device in extract_logps, mirroring the packed path moving its metadata to the consumer device. Prevents cross-device indexing when the model is sharded across GPUs. - Do not synthesize a causal attention_mask in the Mistral forward when prefix_seg_info is present. On the no-xFormers path that synthetic mask tripped resolve_prefix_seg_info and forced PG to always fall back to the packed forward.
|
@codex review |
|
Codex Review: Didn't find any major issues. 🎉 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". |
BenchmarksAll numbers are Qwen3-4B LoRA GRPO on a single H200-class GPU, 1. FlexAttention recompilation (the enabler for default-on)GRPO changes the packed length
After the two warmup compiles, every subsequent new shape is ~1.3-1.5 ms with 2. End-to-end GRPO step (PG on vs off)
3. Correctness / parity
4. Isolated training forward + backward (where the trunk forward is on the critical path)For a group of
Kernel micro-benchmark, long shared prompt with big G (P=1024, R=256, G=16): 1.93x forward, 1.99x fwd+bwd, 3.98x memory. Memory always wins and tracks The win is real end-to-end for long-prompt / large-G / long-context GRPO, for |
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! 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". |
|
pre-commit.ci run |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ae37fa7395
ℹ️ 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".
| except Exception as _pg_err: | ||
| _pg_result = None | ||
| _pg_use = False | ||
| _pg_skip_pk = False | ||
| _pg_forward_fn = None |
There was a problem hiding this comment.
Disable PrefixGrouper after runtime failures
When the PrefixGrouper forward raises at runtime (for example a FlexAttention/Triton compile failure on the current GPU or an OOM), this handler only clears the current result and falls back for this batch; it never marks PG unsafe or flips a model-level disable flag. The next old/ref logprob call will rebuild the same layout and retry the same failing PG path before falling back again, unlike the sequence-packing handler below which sets _unsloth_seq_packing_nograd_ok = False; persistently disabling PG on exceptions would avoid repeated OOM/compile failures.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good point. The PG runtime handler only fell back for the batch and never persistently disabled, unlike the seq-packing handler which sets _unsloth_seq_packing_nograd_ok = False. Since a FlexAttention/Triton compile failure or an OOM here is GPU-wide rather than layout-specific, retrying it every step just re-pays the failure, so I added a model-level _unsloth_prefix_grouper_nograd_disabled flag set in the handler and checked in the engage gate. The packed/padded fallback still produces the exact result.
| ).float() | ||
| _pg_a = _pg_result[:, -_pg_W2:].float() | ||
| _pg_b = _pk_result[:, -_pg_W2:].float() | ||
| _pg_diff = float(((_pg_a - _pg_b).abs() * _pg_cm).max()) |
There was a problem hiding this comment.
Move PrefixGrouper verification tensors to one device
In model-parallel/device-map runs where the LM head is on a different CUDA device from the input batch, GroupLayout.extract_logps() builds _pg_result on hidden.device/the LM-head device, while _pk_result and _pg_cm are built on input_ids.device. This subtraction then raises a cross-device error during first-use verification, so PrefixGrouper can never become trusted for those multi-GPU batches and falls back every step; move the packed result and mask to _pg_a.device before comparing.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The L1766 subtraction only runs inside the if _pk_use and _pk_result is not None branch, and _pk_use can only be True when the packed forward succeeded, whose _pk_hidden[...][_pk_ctgt] boolean index and index_put onto input_ids.device both require the model hidden output to be on input_ids.device. The PG forward shares that same forward path, so extract_logps returns _pg_result on that same device and the compare is never cross-device. When the LM head genuinely lives on another device the packed path raises first and this branch is skipped, so PG just falls back rather than erroring.
| mask_mod = _make_mask_mod( | ||
| seg.group_of_kv.to(device), seg.is_prefix.to(device), seg.suffix_of_kv.to(device) | ||
| ) |
There was a problem hiding this comment.
Copy block-mask labels outside inference mode
In sharded GRPO runs where later layers run on a different CUDA device than input_ids, these .to(device) calls execute while the old/ref forward is inside torch.inference_mode(), before the guard that is meant to keep the cached BlockMask autograd-safe. The copied label tensors for that device are therefore inference tensors feeding create_block_mask, so the cached mask can later fail when the policy/backward PrefixGrouper path reuses it; move these device copies inside the torch.inference_mode(False) block.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed, and it directly contradicts the invariant the get_block_mask docstring documents as CRITICAL. When the mask is first built under the no-grad old/ref forward's inference_mode and the consumer device differs from seg.device (a model-parallel shard), the .to(device) label copies are inference tensors that mask_mod captures, so the cached BlockMask later fails when the grad training forward reuses it. I moved the three .to(device) copies inside the inference_mode(False) block so the labels are normal tensors in the sharded case too. Confirmed on a 2-GPU repro (mask built cross-device under inference_mode, then reused in a grad forward+backward): the old layout raises "Inference tensors cannot be saved for backward" and the fix passes.
…k-mask labels with inference mode disabled - rl_replacements: on a PG forward exception (FlexAttention/Triton compile failure or OOM), set a model-level _unsloth_prefix_grouper_nograd_disabled flag and consult it in the engage gate, mirroring the seq-packing handler, so a GPU-wide failure is not retried and re-paid every step. - prefix_grouper_kernel: move the .to(device) label copies inside the inference_mode(False) block so a cross-device (model-parallel shard) first build does not capture inference tensors, which otherwise cannot be saved for backward when the grad training forward reuses the cached BlockMask.
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! 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". |
…n; PrefixGrouper on top)
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
What
PrefixGrouper (GRPO shared-prompt dedup). In GRPO every prompt spawns G = num_generations completions that share the prompt prefix. The sequence-packed logp forward currently packs G full rows, forwarding the identical prefix G times, then masks it out of the loss. PrefixGrouper stores the prefix once and concatenates only the G suffixes, with a shared-prefix attention mask (each suffix attends to the whole shared prefix and causally within itself), cutting the trunk forward from
G*(P+R)toP+G*Rtokens. It benefits all three logp forwards (policy, old, and reference when beta != 0).Stacked on #6738 (it builds on the no-grad sequence-packing there). Companion grad-path change: unslothai/unsloth-zoo#868.
This PR
unsloth/utils/prefix_grouper_kernel.py(FlexAttention shared-prefix kernel, dtype-aware block sizes, cached block mask) andunsloth/utils/prefix_grouper.py(layout builder, completion-logp index map, env helpers).attention_dispatch.py: a sharedresolve_prefix_seg_infohelper (raises if combined with a KV cache or an attention mask, since the shared-prefix stream is not a plain causal sequence) and a PREFIX_GROUPER attention path.prefix_seg_infothrough: llama, mistral, qwen3, gemma2, cohere, granite, falcon_h1 (qwen2 and gemma inherit llama's forward). MoE and llama4 do not use this dispatch and stay on the full-row path (the layout self-verify falls them back).rl_replacements.py: the no-grad old/ref path gets the PrefixGrouper branch with a first-use self-verify against the full-row packed result (fall back and mark the shape unsafe on mismatch), so a mask or isolation regression cannot ship silently.UNSLOTH_GRPO_PREFIX_GROUPER(default on; set 0 to disable). Auto-disabled under vLLM (fast_inference=True) since the colocated rollout dominates the step there, and auto-gated bytok_rso it never slows a low-tok_rbatch. The FlexAttention kernel compiles with dynamic shapes so the varying GRPO length does not retrigger a recompile per batch.UNSLOTH_ENABLE_LOGGINGNameError in the sequence-packing no-grad verify path (the name was referenced but not defined in the generated trainer cache).Result
2.55x faster and 3.37x lower-memory training forward at favorable prompt:completion ratios; fp64 bit-exact, backward and GQA verified. Numbers in a comment below. Best for long-prompt / large-G / long-context GRPO,
num_iterations > 1, and the multi-GPU path; memory-first and roughly neutral on short-prompt colocated runs, where generation dominates the step.