Skip to content

Add PrefixGrouper for GRPO: dedup the shared prompt across a group's completions - #6871

Merged
danielhanchen merged 45 commits into
mainfrom
grpo-prefixgrouper
Jul 6, 2026
Merged

danielhanchen merged 45 commits into
mainfrom
grpo-prefixgrouper

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Jul 4, 2026 •

Copy link
Copy Markdown
Member

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) to P+G*R tokens. 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

  • New unsloth/utils/prefix_grouper_kernel.py (FlexAttention shared-prefix kernel, dtype-aware block sizes, cached block mask) and unsloth/utils/prefix_grouper.py (layout builder, completion-logp index map, env helpers).
  • attention_dispatch.py: a shared resolve_prefix_seg_info helper (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.
  • The per-arch attention forward threads prefix_seg_info through: 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.
  • Gated behind 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 by tok_r so it never slows a low-tok_r batch. The FlexAttention kernel compiles with dynamic shapes so the varying GRPO length does not retrigger a recompile per batch.
  • Also fixes a latent UNSLOTH_ENABLE_LOGGING NameError 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.

danielhanchen and others added 19 commits June 29, 2026 05:50
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.
@danielhanchen

Copy link
Copy Markdown
Member Author

Benchmark and correctness

Notation: for a group of G completions sharing a prompt of length P with mean completion length R, let tok_r = G*(P+R) / (P + G*R). PrefixGrouper forwards P + G*R tokens instead of G*(P+R), so memory tracks tok_r and the trunk forward speeds up with it.

Correctness (Qwen2.5-0.5B and a real-model check):

  • FlexAttention shared-prefix kernel vs the SDPA oracle and the per-row forward: fp64 bit-exact, fp32 <= 6.5e-5, bf16 first-completion-token bit-exact.
  • Backward vs the oracle: fp64 ~1e-15, fp32 ~1e-6. GQA (enable_gqa) equals manual KV-repeat, bit-exact.
  • Negative controls (a leaky cross-suffix mask, a truncated prefix) are both detected at 4-5 nats, so the parity test has teeth.

Isolated training forward + backward on a real model (Qwen3-4B, tok_r = 3.33):

metric full-row PrefixGrouper ratio
fwd+bwd time 1.00x 0.39x 2.55x faster
peak memory 1.00x 0.30x 3.37x less

Kernel micro-benchmark (attention op, swept over P, R, G): memory always wins and tracks tok_r; the speed win grows with tok_r. Long shared prompt with big G (P=1024, R=256, G=16): 1.93x forward, 1.99x fwd+bwd, 3.98x memory.

Honest note on end-to-end: with a colocated vLLM rollout (fast_inference), generation is 77-94% of a GRPO step and PrefixGrouper does not touch it, so the end-to-end step speedup on a short-prompt notebook is small (about 1.03-1.04x) and it is memory-first there. The win is real end-to-end for long-prompt / large-G / long-context GRPO, for num_iterations > 1, and on the multi-GPU / FSDP2 path where the training forward is on the critical path. Default off, and auto-gated by tok_r so it never slows a low-tok_r batch.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

Gemini encountered an error creating the review. You can try again by commenting /gemini review.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment on lines +143 to +196
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

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 groups
References
  1. To improve efficiency, avoid redundant data iterations. Combine checks and transformations into a single loop and return computed values for callers to reuse.

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.

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.

Comment on lines +228 to +239
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

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.

Suggested change
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)

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 427d3448f1

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

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

No verdict came back on the previous trigger, re-running on the current head.

@codex review

@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: 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".

Comment on lines +174 to +180
A = flex_shared_prefix_attention(
Q.transpose(1, 2),
K.transpose(1, 2),
V.transpose(1, 2),
context.prefix_seg_info,
scale = scale,
)

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 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 👍 / 👎.

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.

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.

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.

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.

Comment on lines +337 to +341
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),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

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.

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.

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.

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.

Comment thread unsloth/models/mistral.py
# 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)

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 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 👍 / 👎.

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.

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.

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.

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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 350cadf2a3

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

Copy link
Copy Markdown
Member Author

Benchmarks

All numbers are Qwen3-4B LoRA GRPO on a single H200-class GPU, num_generations = 8, completion length 256, measured with a steady-state StatisticsCallback (median over 11 steady steps), so first-step compile/warmup is excluded. PrefixGrouper (PG) only touches the policy/reference logprob forward, so the relevant axis is the update-step time and the training-forward peak memory, not generation.

1. FlexAttention recompilation (the enabler for default-on)

GRPO changes the packed length T almost every batch. Compiling the FlexAttention kernel with dynamic = False keys the compiled artifact on shape, so a new T recompiled from scratch every step. Switching to dynamic = True compiles twice during warmup and is then recompile-free on new shapes.

kernel compile first call on a NEW T_pad repeat call (same shape) new/repeat ratio
dynamic = False 14672 ms 0.4 ms 41681x
dynamic = True 1.4 ms 0.4 ms 3.5x

After the two warmup compiles, every subsequent new shape is ~1.3-1.5 ms with dynamo_compiles += 0. A different mask layout at the same T_pad does not recompile (0.3-0.7 ms), so only the padded length matters.

2. End-to-end GRPO step (PG on vs off)

config update step median step peak memory
fast_inference=False, PG off 415.7 ms 452.1 ms 10.19 GB
fast_inference=False, PG on 314.5 ms 333.3 ms 8.54 GB
fast_inference=True, PG off 374.0 ms 378.8 ms 116.8 GB
fast_inference=True, PG on 361.6 ms 2084.5 ms 121.5 GB
  • On the transformers path (fast_inference=False) PG cuts the logprob-forward update step by 1.32x (415.7 to 314.5 ms) and peak training-forward memory by ~16% (10.19 to 8.54 GB).
  • Under a colocated vLLM rollout (fast_inference=True) the memory is dominated by vLLM's reservation and the first-use self-verify runs the full-row path too, so PG is net negative there. It is therefore auto-disabled when use_vllm is set (the numbers above confirm the gate is the right call).

3. Correctness / parity

  • First-use self-verify of the shared-prefix forward vs the full-row packed reference over the exact loss mask: max|d| = 0.24 nats (grad path), well under the 0.7 trust tolerance; re-verified whenever T or the longest segment grows.
  • Isolated kernel vs the SDPA oracle and a per-row forward: fp64 bit-exact, fp32 <= 6.5e-5, bf16 first-completion-token bit-exact. Backward fp64 ~1e-15, fp32 ~1e-6; GQA equals manual KV-repeat bit-exact. Negative controls (a leaky cross-suffix mask, a truncated prefix) are detected at 4-5 nats.

4. Isolated training forward + backward (where the trunk forward is on the critical path)

For a group of G completions sharing a prompt of length P with mean completion length R, let tok_r = G*(P+R) / (P + G*R); PG forwards P + G*R tokens instead of G*(P+R).

Qwen3-4B, tok_r = 3.33 full-row PrefixGrouper ratio
fwd+bwd time 1.00x 0.39x 2.55x faster
peak memory 1.00x 0.30x 3.37x less

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 tok_r; the speed win grows with tok_r.

The win is real end-to-end for long-prompt / large-G / long-context GRPO, for num_iterations > 1, and on the multi-GPU / FSDP path where the training forward is on the critical path. On short-prompt vLLM runs it is memory-first, which is why it is gated off under vLLM. Auto-gated by tok_r so it never slows a low-tok_r batch.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: a1a62f6192

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

Copy link
Copy Markdown
Member Author

pre-commit.ci run

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 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".

Comment on lines +1534 to +1538
except Exception as _pg_err:
_pg_result = None
_pg_use = False
_pg_skip_pk = False
_pg_forward_fn = None

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 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 👍 / 👎.

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.

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())

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 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 👍 / 👎.

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.

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.

Comment thread unsloth/utils/prefix_grouper_kernel.py Outdated
Comment on lines +313 to +315
mask_mod = _make_mask_mod(
seg.group_of_kv.to(device), seg.is_prefix.to(device), seg.suffix_of_kv.to(device)
)

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 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 👍 / 👎.

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.

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

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 6d6e3839d4

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

Base automatically changed from grpo-sequence-packing to main July 6, 2026 12:17
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@danielhanchen
danielhanchen merged commit 08e133c into main Jul 6, 2026
47 of 50 checks passed
@danielhanchen
danielhanchen deleted the grpo-prefixgrouper branch July 6, 2026 12:26
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.

2 participants