Packing sequences for memory efficiency in GRPO and other preference learning implementations
Feature request
Similar to packing in SFT, we can apply packing to sequences in different generations of the same group. Sharing the prefix should save memory, especially in situations where prefix length >> completion length.
Some reference implementations:
- https://github.com/frankxwang/dpo-prefix-sharing
- https://github.com/li-plus/flash-preference/tree/main
Motivation
Many classes of problems involving large contexts end up being dominated by prompt length. This should help with memory savings in those situations
Your contribution
I would love to take a stab at a PR, but want to discuss the feasibility and interest in adding support for this in TRL
I would be nice! Do you have any idea how to do it? It sounds less easy compared to sft
Related https://github.com/huggingface/trl/pull/3495
prefix sharing repo with packing for DPO sounds nice, although it would require pretty complex custom packing + using flex attention for custom mask. Is flex attention used somewhere else in the trl codebase?
Since TRL uses the huggingface modelling interface, it supports switching attention backends. We can check if it the current value is one that supports a custom mask.
I believe the core logic should be somewhere right before / within _get_per_token_logps. Where we create a single input_ids, attention_mask and new position_ids tensor for a group. Using the appropriate mask and position IDs, we should naturally get the efficient way of obtaining the log probs. Post which we would need to unpack for computing the loss. Not sure if we'd need to modify any other path in the code, but this seems sufficient.
Sounds good, I think we do something very close here:
https://github.com/huggingface/trl/blob/c49c7b7d4e8dcbf71f881051d3a04352a9fc7ef3/trl/trainer/dpo_trainer.py#L1165-L1174
https://github.com/huggingface/trl/blob/c49c7b7d4e8dcbf71f881051d3a04352a9fc7ef3/trl/trainer/dpo_trainer.py#L1204-L1211
@RameshArvind wondering if you've had the chance to work on this, if you're too busy I can try taking it up and have a PR out some time next week.
I haven't had much time to tackle this yet, feel free to work on this @pramodith
@qgallouedec have preliminary draft PR, a couple of my test cases are failing I suspect this is because the tiny test models being loaded need to be configured to use an attention backend that supports flex-attention or any other attention that accepts position_ids as an input parameter. It'd be great to get some of your thoughts.
Hey @RameshArvind, apologies for the very long silence here, we are catching up on the backlog.
This is still a genuinely nice idea and it is well-motivated: the Prefix Grouper paper (arXiv:2506.05433) is essentially this for GRPO, and Accelerating DPO with Prefix Sharing (arXiv:2410.20305) reports ~1.3–1.6× throughput once combined with packing.
The catch is that the draft in #3642 (thanks @pramodith, I'll close to keep the queue tidy) has gone stale, grpo_trainer.py has had ~250 commits since then, so it no longer merges, and prefix-packing needs a custom attention mask via flex attention, which TRL does not use anywhere yet, so it is a non-trivial new surface. I would like to keep this open as a tracking thread: if you (or anyone watching) still want it, a +1 or a fresh draft PR against current main would really help us gauge demand and prioritize. No promises on timeline, but we are not opposed to the feature.
Quick update for anyone watching this thread. Since my last message, Unsloth shipped essentially this for GRPO (unslothai/unsloth#6871 -> unsloth/utils/prefix_grouper.py plus a FlexAttention shared-prefix kernel), so there is now a concrete reference design. It also confirms the shape of the work: prefix sharing is a block-mask/segment-table layer on top of an already-packed path, and TRL does not have that path yet (GRPO's forward is still padded-dense).
So the realistic order is padding-free/packed path first, prefix sharing second. Keeping this open as the tracking issue for that second half.
Half one of this issue is up as #7087: padding_free=True in GRPOConfig and RLOOConfig packs each chunk into one row for the per-token log-prob forward, with position-id resets doing the separation under Flash Attention. Prefix sharing across a group is the second half and stays open here.
Hey @qgallouedec @behroozazarkhalili I would like to pick up the second half, and I am working on a draft.
The idea is to pack each group in one row - [prompt | completion_1 | … | completion_G] and then to use a custom attention mask so that each completion sees itself + the prompt. I think we can already pass a 4D mask or BlockMask, so this should be doable.
After the forward pass, we can scatter the log probs back to the usual padded layout.
I checked Unsloth's prefix_grouper, same packing and scatter-back shape, but they need their own kernel since they patch models, going through transformers' mask pass-through will avoid that.
I did a sanity check on trl-internal-testing/tiny-Qwen2ForCausalLM-2.5 and packed vs naive per-token log probs are identical.
Hi @qgallouedec, @behroozazarkhalili — picking this up from the tracking thread, and I wanted to check the shape of the second half before opening a PR.
My reading of the current state:
- #7087 is the first half (
padding_freepacks each chunk's real tokens into one row and removes padding compute), and as its description says, prefix sharing across a group stays open here. The packed row in #7087 still forwards each sample's prompt tokens, so forP >> Cthe dominant cost — the prompt forwarded G times per group — is untouched. - #3642 showed the trap: FA2 + position ids alone do not separate the packed sequences, so a new attempt needs an explicit attention mask.
What I would like to implement, as a fresh PR against current main:
- Pack each group into one row,
[prompt | completion_1 | … | completion_G], with position ids restarting per completion and an explicit 4D causal block mask (each completion sees the prompt + itself, never another completion), then scatter the per-token log-probs/entropies back to the padded layout. This goes through transformers' mask pass-through, so no custom kernel — same shape @sky-2002 sketched here, and the same shape as Unsloth'sprefix_grouperminus their kernel. - Gated behind a new
prefix_sharingflag onGRPOConfig(andRLOOConfig, since the log-prob function is duplicated there), defaultFalse, mutually exclusive withpadding_freefor now.sdpa/eageronly — a 4D mask can't go through FA2 — and refused with liger / VLMs, mirroring #7087's guards. It does not depend on #7087 merging: it replaces the padded-dense forward directly. - Groups derived from identical prompt tokens rather than row position, since
_prepare_inputsshuffles rows. - Tests: packed vs dense per-token log-probs (and entropies) identical on a tiny model, gradient flows through the scatter-back, and the guards raise.
Three questions before I open it:
- Is this still wanted, and is a 4D-mask (
sdpa/eager) first version acceptable — or would you rather this wait for #7087 and land as a flex-attentionBlockMaskon top of it? - @sky-2002, you mentioned working on a draft of this — do you have a branch up, or should I go ahead? Happy to coordinate rather than duplicate.
- Any objection to the flag name
prefix_sharing, or would you prefer something else (e.g.group_packing)?
Thanks!
Thanks @eliem08 and @sky-2002. This is already in TRL: AsyncGRPOTrainer packs each group as a tree, the prompt once and each completion attending to the prompt and itself, in one varlen FlashAttention call, recurrent layers included:
https://github.com/huggingface/trl/blob/9488e5ced9774e3cbb3e52d80046d4a4165cac05/trl/trainer/async_grpo_trainer.py#L317-L365
That's where we want prefix sharing, so we won't add a second mechanism to GRPOTrainer and RLOOTrainer. Closing, plain packing for GRPO is #7087.