verl icon indicating copy to clipboard operation
verl copied to clipboard

[RFC] Shared-prefix packing for the FSDP engine (trunk + branches), with a path to hybrid linear-attention models

Open DeeproChoudhury opened this issue 1 month ago • 0 comments

1. Summary

In GRPO-style RL in verl every prompt is sampled rollout.n times, so the actor, reference and critic each run a forward pass over every (prompt, response) pair and process the same prompt n times per group. This RFC adds shared-prefix packing to the FSDP engine, where the n samples of a prompt are packed as one trunk (the prompt) plus one branch per response. Each branch's keys and values are the trunk's followed by its own, so the varlen flash-attention call verl already makes per layer gives every branch the trunk plus its own causal prefix, and nothing else, with no new kernel or mask. The prompt is only computed once; we get the same log-probs, entropy, values and gradients as the current rmpad path, verified on an H100 against that path. In end-to-end GRPO training on Qwen3-4B with a 2k-token shared prompt, a training step is 2.7x faster (actor update 3.1x, reference pass 3.9x); on plain GSM8K with 83-token prompts, close to the worst case for the method, it is still 1.18x faster. Reward curves match within sampling noise and peak allocated memory is unchanged in both runs. In a single-GPU actor forward+backward the gain grows with prompt length, reaching 3.8x at an 8k-token prompt, and peak memory never rises; in fact at 8k it falls from 35.8 to 18.7 GB.

PR: https://github.com/verl-project/verl/pull/8300

today (rmpad):   [ prompt | resp_1 ] [ prompt | resp_2 ] ... [ prompt | resp_n ]      n (P + R) tokens
this RFC:        [ prompt[:-1] ] [ x | resp_1 ] [ x | resp_2 ] ... [ x | resp_n ]      (P - 1) + n (R + 1) tokens
                   ^ trunk          ^ branch: duplicated last prompt token x, then the response
                 branch_i attends to: trunk + its own tokens (causal); never another branch

What is new here, relative to what verl has or has in flight:

  1. Exact, with no new attention backend. We make one flash_attn_varlen_func call per layer with explicit cu_seqlens and a key/value gather, through the flash-attention entry point verl already patches. No MAGI, no FlexAttention, no dense masks, so it runs on every existing verl install and keeps sliding windows, softcap and FA3 dispatch. We test parity against a brute-force oracle at 1e-5 in fp32 on CPU, and against verl's own rmpad path in bf16 on an H100 (log-probs and entropy within 1e-2, gradient cosine > 0.999), across fused kernels, gradient checkpointing, sliding window and the critic.
  2. The first prefix-sharing path that composes with rmpad, fused kernels and gradient checkpointing. PrefixGrouper (#4368) forked and rewrote the actor forward pass and required padding left in (use_remove_padding=False), which is why nothing has called it since verl's engine refactor. Our trick is to start each branch with a copy of the last prompt token; verl (no_padding_2_padding) already reads the first response log-prob from the last prompt row, so that one duplicated token makes the existing torch.roll labels, the fused linear-cross-entropy path, entropy, Σπ² and the critic all correct with zero special cases. We unpack with a single index_select, and we change nothing downstream of the model forward.
  3. A silent-failure mode in transformers, identified and guarded. Hugging Face transformers derives varlen boundaries from position_ids == 0. Our branch positions continue from the trunk, so they have no position 0. Any attention layer that bypasses the packed wrapper would see one long sequence and quietly let branches attend to each other, so training would degrade with no error. Any prefix-sharing implementation on HF models, including an FSDP port of #6689, has to handle this. We count, per micro-batch, how many attention layers went through the packed wrapper and raise an exception if any did not. We reject VLMs and hybrid models earlier, at model build; the counter is the backstop for anything that gets past that check. We test that the engine raises when a layer is missing, and on GPU that an sdpa model leaves the counter at zero.
  4. Dynamic batching that budgets by packed length. verl splits work into micro-batches by token budget. We give rearrange_micro_batches variable-size atomic groups budgeted by packed, not unpacked, tokens, so it no longer rejects a group that only fits once packed, and groups stay whole within a micro-batch. This is what lets the end-to-end runs turn the 3.65x token reduction into a 3.1x actor speedup. We leave force_group_size unchanged.
  5. A concrete path to hybrid linear-attention models (Qwen3.5, Qwen3-Next), which no verl implementation supports: we hand the recurrent state across the trunk boundary inside verl's existing packed-sequence patch for those layers, reusing the mechanism qwen3_5.py already has for context parallelism (Section 6).

2. Why a separate PR rather than a change to #6689

#6401 / #6689 is a good general design (multi-level trees, MAGI or FlexAttention). This RFC is a different piece of work that fits next to it rather than competing with it. Four reasons:

  • Different engine. #6689 is Megatron-only (verl/workers/engine/megatron/) and lists FSDP as planned. We change the FSDP engine, the flash-attention wrapper and the batching utilities. The only files both PRs touch are shared glue: ray_trainer.py / trainer_base.py (balance_batch), workers/engine/utils.py (micro-batching) and workers/config/engine.py plus its generated yaml (one flag each). The attention and engine code do not overlap.
  • Different attention mechanism. #6689 encodes a block-sparse rectangle spec for MAGI or a FlexAttention mask. We use the plain varlen flash-attention call the FSDP rmpad path already runs, plus a K/V gather. Users add no dependency and do not switch attention backends.
  • Smaller, and zero risk to anyone who does not opt in. #6689 is 5.5k lines, has merge conflicts and has been in review for four months; the maintainers asked for unit tests and Flex end-to-end runs. This PR is about 1.7k lines, 60% of it tests, with CPU and GPU parity tests wired into CI. The flag is off by default, and every configuration we do not support is rejected with an explicit error, so a user who does not set the flag runs the same code as today. It can be reviewed and merged on its own.
  • Composable with #6689 later. We keep group detection and the trunk/branch plan in one file, verl/workers/utils/prefix_packing.py. A multi-level tree is the same K/V gather with one trunk per segment, so if #6689 lands, its tree builder can emit the same plan structure and the FSDP path picks it up without a second attention implementation. The hybrid-model follow-up (Section 6), which #6689 lists as unsupported, applies to either backend.

Prior art, and why this is not a repeat of it: PrefixGrouper (#4368) packed the same way but forked the old dp_actor.py forward and required use_remove_padding=False, so the engine refactor (#6067) left it with no caller. #7202 tried to revive that fork and was closed in favour of #6689. This PR is not a revival of the fork: it sits in the engine, on the rmpad path, with fused kernels and gradient checkpointing, which is what #6689 says it will do for FSDP and has not started. #7561 proposes per-segment K/V reuse with a tree scheduler, Megatron only.

Motivation in numbers

With use_remove_padding=True a group costs n (P + R) tokens for a prompt of length P and responses of length R; packed it costs (P - 1) + n (R + 1). The saving is the duplicated prompt work: every linear layer and the prompt's self-attention run once instead of n times.

Workload P R n Tokens: unpacked packed ratio
GSM8K (measured, Section 5) 83 625 8 5664 5090 1.1x
GSM8K + 2k system prompt (measured, Section 5) 2090 425 8 20120 5497 3.7x
Long system prompt / RAG 2048 512 8 20480 6151 3.3x
Long-context QA 16384 1024 8 139264 24583 5.7x
DAPO-style math (long response) 200 4000 16 67200 64215 1.05x

The gain is large when the prompt is long relative to the response, which is the agentic and multi-turn case (long system prompts with tool schemas, long histories), and small for short-prompt math RL.

3. Design

3.1 Layout

For a group of n samples with prompt length P:

[ trunk = prompt[0 : P-1] ] [ branch_1 = prompt[P-1] + response_1 ] ... [ branch_n = prompt[P-1] + response_n ]

Every branch starts with the duplicated last prompt token. A model predicts token t+1 from row t, so the log-prob of the first response token lives on the last prompt row, and verl's no_padding_2_padding reads it from there once per sample. Giving every branch that row means the ordinary torch.roll(-1) labels are correct on every row that is read back, and the fused-kernel path (shift_labels), entropy, Σπ² and the critic are correct with no special cases. We do not renumber positions: every token keeps the position it had in its own sample, gathered by index, so branch positions continue from the trunk. We convert outputs back to the per-sample layout with one index_select per output tensor (log-probs, entropy, Σπ², values). That is the whole change below the model forward: every loss, metric and the critic head, plus nested_tensor_from_jagged, no_padding_2_padding and batch_num_tokens, run unchanged.

3.2 Attention

Per layer, we call flash_attn_varlen_func through transformers' _flash_attention_forward with our own explicit segment boundaries (cu_seq_lens_q, cu_seq_lens_k, max_length_q, max_length_k). For a branch segment the queries are the branch tokens and the keys/values are [trunk ; branch], built with an index gather after the K/V projection and RoPE. Flash-attention's causal rule when keys outnumber queries is "align to the bottom-right", so branch token i sees all of the trunk plus branch tokens <= i, which is exactly what it would see unpacked. In the backward pass the gather sums each branch's gradient contribution into the trunk, which is the gradient of the unpacked computation.

We pass the boundaries explicitly because transformers otherwise derives them from position_ids == 0, which our branches do not have; relying on positions would silently merge the branches into one causal sequence. The boundaries travel as a model kwarg, not a global, so non-reentrant gradient checkpointing replays the same boundaries on recompute. This is what lets packing compose with gradient checkpointing and fused kernels, which PrefixGrouper could not. We also count, per micro-batch, how many attention layers went through the wrapper, and raise if any did not. We reject VLMs and hybrid models earlier, at model build; the counter catches anything else that bypasses the wrapper (sdpa, a custom attention override), so it fails with a clear error instead of attending across branches.

3.3 Group detection and batching

We decide groups by comparing the prompt token ids of adjacent samples, not by uid or any other metadata. This makes packing exact by construction: two samples whose prompts differ in any token are never packed, fragmented groups and padding duplicates stay correct, and nothing depends on the sampler or the dataloader order. PrefixGrouper grouped by uid and trusted that the prompts matched; #6689 matches token ids too, through a trie. We never reorder samples, and we never share a prompt shorter than two tokens, so the trunk is never empty. When a micro-batch has no sharing we build no plan and run the plain rmpad path, so leaving the flag on for an unshared batch costs one token comparison.

With the flag on, balance_batch in both trainers keeps each prompt's samples on one rank with equal sample counts per rank. Dynamic batch size keeps each group in one micro-batch, budgeted by packed length; we split a group over the budget, and each part keeps its own trunk.

3.4 Config

actor_rollout_ref.actor.fsdp_config.use_prefix_packing: false (ref follows the actor; critic via critic.fsdp.use_prefix_packing). Off by default.

Requirements, checked once at model build: use_remove_padding=True, ulysses_sequence_parallel_size=1, flash_attention_2/3 on CUDA with flash-attn >= 2.1 (bottom-right causal alignment), text-only models, and not a model that takes cu_seqlens directly (Qwen3.5 hybrids). Checked per micro-batch and rejected with an explicit error: top-k distillation, score centering, router replay, multi-modal inputs / mRoPE, and batches without prompts. A user who hits any of these gets the error at startup or on the first micro-batch, never a silently wrong result.

4. Correctness

We test packed-equals-unpacked by two independent routes.

  • CPU, exact. We run a tiny fp32 Qwen2 through a second attention implementation: SDPA with a dense tree mask we build by hand, and we first check that mask against a brute-force per-sample forward. We then require packed and unpacked log-probs, entropy, values and every parameter gradient to match at atol=1e-5, including with per-sample temperature. Around that we unit-test every piece: pack/unpack round trips, label alignment on every read row, group detection edge cases (nested prompts, padding duplicates, one-token prompts, non-adjacent duplicates, empty batch), tail padding, the engine wiring (we pack when prompts are shared and run plain rmpad when nothing is shared), every rejection check, the layer guard, the counter surviving FSDP's kwarg copy, and micro-batch grouping (groups stay whole, we split over-budget groups). We name these files *_on_cpu.py, so cpu_unit_tests.yml runs them with no workflow change.
  • GPU, the real path. In tests/models/test_prefix_packing.py we compare the production path (bf16, varlen flash-attention, the packed wrapper) against verl's existing rmpad forward on the same weights: 12 actor cases (Qwen2, Qwen2 with sliding window, Qwen3; fused kernels on and off; gradient checkpointing on and off), the critic, and an sdpa model that must leave the layer counter at zero. We require log-probs and entropy to match at atol=1e-2, rtol=1e-5 and gradient cosine > 0.999, which is bf16 tolerance. All 14 pass on an H100 80GB (driver 575.57, torch 2.8.0+cu128, flash-attn 2.8.3, transformers 5.12.1), and tests/models/test_transformer.py still passes 4/4. We add the test to model.yml next to test_transformer.py, so CI also runs it on L20s.

The CPU oracle and the GPU path use different attention implementations, so when they agree, neither can be hiding a bug it shares with the other.

5. Results

End-to-end GRPO training, Qwen3-4B, 2x H100 80GB, FSDP + vLLM, rollout.n=8, 128 prompts per step, 20 steps, same seed; times are averages over steps 5-20, the only difference between runs is the flag.

Long shared prompt (GSM8K with a ~2,090-token system prompt, the agentic / long-instruction case; responses ~425 tokens):

stage baseline (rmpad) packed speedup
actor log-probs (timing_s/old_log_prob) 44.8 s 14.3 s 3.13x
reference log-probs (timing_s/ref) 60.5 s 15.6 s 3.88x
actor update (timing_s/update_actor) 158.4 s 51.2 s 3.09x
rollout generation (timing_s/gen, not packed) 23.9 s 24.3 s 0.99x
whole step (timing_s/step) 289.5 s 107.1 s 2.70x

Tokens per micro-batch drop 3.65x (logged as actor/prefix_packing_token_ratio); the actor phases reach ~85% of that and the ref exceeds it. Generation is 8% of the baseline step, so if the three packed phases had sped up by exactly 3.65x the step would be 2.95x faster; we measure 2.70x. A 20-step run goes from about 97 to 36 minutes.

Short prompt (plain GSM8K, ~83-token prompts, ~625-token responses, close to the worst case for the method):

stage baseline packed speedup
actor log-probs 15.8 s 13.3 s 1.19x
reference log-probs 17.1 s 11.1 s 1.54x
actor update 69.2 s 59.3 s 1.17x
whole step 123.0 s 104.4 s 1.18x

Tokens drop only 1.10x here, yet every phase speeds up more than that, because dynamic batching now budgets by packed length and runs fewer, fuller micro-batches. The token ratio is a floor on the speedup, not an estimate of it.

Training is unchanged: reward curves match within sampling noise in both workloads (per-step difference: mean -0.003, sd 0.009 with the long prompt; mean +0.010, sd 0.013 with the short one; the binomial standard error of a 1024-sample mean is about 0.01). Peak allocated memory is 38.25 GB per GPU in all four runs, packed or not, long prompt or short, so at this batch size the peak is set by something independent of the batch (weights, optimizer state or the vLLM weight sync), and packing neither raises nor lowers it. The forward+backward saving shows up once that fixed floor is exceeded, as in the scaling runs below.

Scaling with prompt length (single H100, forward + backward of the actor, Qwen3-4B, fused kernels and gradient checkpointing, 8 samples x 1,024 response tokens):

shared prompt 64 256 1,024 2,048 4,096 8,192
token ratio (unpacked / packed) 1.05x 1.21x 1.78x 2.40x 3.33x 4.50x
speedup 1.06x 1.19x 1.67x 2.18x 2.94x 3.81x
peak memory, GB (unpacked → packed) 18.5 → 18.4 19.2 → 18.4 18.3 → 16.9 20.0 → 17.1 23.6 → 17.6 35.8 → 18.7

The gain grows with the shared prompt length, the speedup stays at least 84% of the token ratio across the sweep, and packing never makes a step slower in these runs. At 8k the packed forward+backward uses about half the memory of the unpacked one, so the same GPU holds roughly twice the response tokens per micro-batch, or the same workload fits on a smaller GPU. Rollout generation is untouched, so the whole-step speedup is bounded by the share of time spent in generation (Amdahl).

6. Next steps (not in this PR)

  1. Hybrid Gated DeltaNet models (Qwen3.5, Qwen3-Next). Their recurrent layers ignore attention masks, so a branch would inherit the recurrent state of the branches before it. The plan: run the trunk segments with output_final_state=True, start each branch from its trunk's final state (initial_state in chunk_gated_delta_rule, whose backward sums the branch gradients into the trunk state), and prepend the last conv_kernel_size - 1 trunk tokens before the causal convolution, the same mechanism verl/models/transformers/qwen3_5.py already uses for context parallelism. That file already owns cu_seqlens for these layers and already passes initial_state=None, output_final_state=False to chunk_gated_delta_rule, so the change is those two kwargs plus a gather index, contained in that file.
  2. Ulysses sequence parallelism: a global-coordinate gather index after the sequence-to-heads all-to-all.
  3. Sharing beyond the prompt (identical early response tokens, multi-turn branching rollouts) via a trie, reusing the tree layout from #6689 if it lands.
  4. Removing the dead PrefixGrouper code in a separate PR.

7. Questions for maintainers

We propose to merge this as it stands, as the FSDP side of prefix sharing, and we would like decisions on three points:

  1. Alignment with #6689. We propose to keep the plan structure in verl/workers/utils/prefix_packing.py as the FSDP interface now, and to have #6689's tree builder emit that structure if and when it lands, so that the FSDP path gains multi-level trees without a second attention implementation. If you would rather we match #6689's tree spec field-for-field in this PR, tell us which fields and we will do it before merge.
  2. Where the flag lives. We put it at actor.fsdp_config.use_prefix_packing (ref follows, critic has its own). If you prefer one knob on the model config next to use_remove_padding, so every engine reads the same flag, we will move it.
  3. Hybrid follow-up target. We will do Qwen3.5 first unless you would rather have Qwen3-Next; the mechanism is the same and the choice is only which model we validate on.

DeeproChoudhury avatar Oct 20 '26 17:10 DeeproChoudhury