[RFC] Prefix-Tree Shared Attention for Multi-Turn RL Training
1. Summary
In GRPO and multi-trajectory RL training, each prompt (or each turn) is sampled n times — all responses share an identical prefix, yet standard training recomputes it independently for each sample. This RFC proposes packing all samples into a flat [prefix | leaf_0 | ... | leaf_{n-1}] layout and running a single forward pass with cross-leaf isolation enforced via Magi Attention's workload-balanced CP dispatch — mathematically equivalent to independent per-sample forwards.
Inspired by Forge's Prefix Tree Merging, this implementation targets VERL's Megatron backend (FSDP planned) and generalizes to arbitrary-depth multi-level trees, enabling prefix sharing across multiple conversation turns — not just the top-level prompt.
2. Motivation
In GRPO and multi-trajectory RL training, each prompt (or each turn) is sampled n times, and all n responses share an identical prefix. Standard training computes attention over the full sequence for each sample independently — paying redundant O(P²) cost for the shared prefix on every forward pass. At high prefix ratios (e.g. long system prompts, multi-turn history), this dominates total compute.
Background & use cases: The RL algorithms that targets rollout sampling between turns, or grpo situation that have long common prefixes. Example includes:
- rStar-Math performs "deep thinking" through Monte Carlo Tree Search, where "a math policy SLM performs test-time search guided by an SLM-based process reward model" — MCTS rollouts naturally produce shared-prefix trees as the search expands.
- TreeRL "directly incorporates on-policy tree search for RL training … strategically branching from high-uncertainty intermediate steps", where each branch shares the prefix up to its branch point. Both map directly onto the tree layout this RFC proposes.
- DeepSearch "embeds MCTS directly into the RLVR training loop, branching from intermediate reasoning steps" — the search tree is rooted at the input prefix and expands across steps, producing the same shared-prefix structure at train time that rStar-Math uses at test time. (ICLR 2026)
- And other situation with long common prefixes
3. Design
Overview
The trainer computes prefix_segments per sample — a list of (hash, length) pairs, one per chunk (e.g. conversation turn) (which could be provided by rollout agent or by manually finding the common prefix):
prefix_segments = [
(hash(sys), len_sys), # turn 0: system prompt only
(hash(user1), len_u1), # turn 0+1: sys + user1
(hash(asst1), len_asst1), # turn 0+1+2: sys + user1 + asst1
...
]
The mask builder compares hashes across samples in the micro-batch to identify which prefixes are shared, constructs a flat deduplicated token layout, and generates the corresponding block-sparse attention mask. The model forward runs once on the flat layout; outputs are reconstructed per sample before loss computation.
flowchart TD
A[SFT/RL during dataset/rollout] -->|"prefix_segments: hash+length per turn"| B[Tree Builder]
B -->|"flat token layout + block mask"| C[Transformer Forward]
C --> D[Attention Backend: dispatch → attn → undispatch]
D --> E[Output Reconstruction → Next layer]
- Prepare: computes
prefix_segmentsper sample — a list of cumulative(hash, length)pairs, one per conversation turn. - Tree Builder: compares hashes across samples in the micro-batch, identifies shared prefixes, and constructs the flat deduplicated token layout and block-sparse attention mask.
- Transformer Forward: runs a single forward pass on the flat layout, which is shorter than
nindependent full sequences. - Attention Backend (Magi): dispatches tokens to CP ranks by attention workload, computes sparse attention per rectangle, and undispatches outputs.
- Output Reconstruction: concatenates prefix and leaf output slices per sample
Megatron Integration (Monkey-Patch)
- Patch
TEDotProductAttention.forward— interceptsmagi_attention_key/flex_attention_keykwargs to route to MAGI/flex instead of FA3. SelfAttention._checkpointed_attention_forward— make sure the extra kwargs goes through the recompute.
Attention Implementation
Prefix detection is algorithm-dependent (GRPO, multi-turn SFT, agent RL each have different sharing patterns). The trainer is only required to provide the deduplicated token segments via a unified interface — the tree builder handles layout and mask generation. The algorithm is also responsible for grouping samples with similar prefixes into the same micro-batch.
Multi-level (e.g. multi-turn agent RL where responses diverge into sub-groups sharing a turn-2 prefix):
graph TD
Root["Root: turn0, shared by all"] --> A1["A1: turn1 branch A, shared by S0,S1"]
Root --> A2["A2: turn1 branch B, shared by S2,S3"]
A1 --> B1["B1: S0 unique turn2"] & B2["B2: S1 unique turn2"]
A2 --> B3["B3: S2 unique turn2"] & B4["B4: S3 unique turn2"]
Flat layout: [Root | A1 | B1 | B2 | A2 | B3 | B4]
Mask (multi-level tree, 4 samples, 7 nodes — token counts from experiment):
Sample composition:
S0: Root + A1 + B1
S1: Root + A1 + B2
S2: Root + A2 + B3
S3: Root + A2 + B4
| Root A1 B1 B2 A2 B3 B4
Root | ## · · · · · ·
A1 (S0,S1) | ## ## · · · · ·
B1 (S0) | ## ## ## · · · ·
B2 (S1) | ## ## · ## · · ·
A2 (S2,S3) | ## · · · ## · ·
B3 (S2) | ## · · · ## ## ·
B4 (S3) | ## · · · ## · ##
## = causal self or full attend · = masked
4. Limitations
- Prefix sharing is within-microbatch only: samples across different micro-batches cannot share prefix computation. Effective sharing requires the algorithm to group samples with identical prefixes into the same micro-batch.
5. Current Results
using H20, TP=4.
Dataset A — shallow tree (depth=2, branch=2, seq~12.8k, ~50% prefix sharing):
| Backend | mbs | Step time | Peak mem | loss@1 |
|---|---|---|---|---|
| FA3 | 2 | 6.7s | 77 GB | 0.0292 |
| FA3 | 4 | 6.6s | 122 GB | 0.0292 |
| MAGI | 4 | 3.97s | 86 GB | 0.0296 |
42% faster than FA3 mbs=2, 30% less memory than FA3 mbs=4.
Dataset B — deeper tree, with similar branch grouped in same mbs (tree_b2_d16_dfs_512_l16k: depth=16, branch=2, 512 leaves, ~69% saved computation with mbs=4 (in mbs=4, the max computation we can save with 100% sharing is 75%, because we need to compute once at least):
| Config | Seq | step1 | step2 | step3 | fwd(ms) | speedup |
|---|---|---|---|---|---|---|
| FA3 TP4 | 8k | 0.0611 | 0.0220 | 0.0099 | 1191 | — |
| MAGI TP4 | 8k | 0.0613 | 0.0225 | 0.0094 | 394 | 3.02x |
| FA3 TP4 | 16k | 0.0310 | OOM | OOM | 2547 | — |
| MAGI TP4 | 16k | 0.0313 | 0.0110 | 0.0044 | 851 | 2.99x |
~3x forward speedup over FA3 at both 8k and 16k; FA3 OOMs during backward at 16k.
6. Future Plans
- make sure CP works(Magi claims speed up using CP); try to a align the current discrapancy in loss.
- Based on one of the existing Multi-trajectory implementation, write a rl demo
- * [future plan] Experiments on cache based implementation, allowing cross-micro batch prefix sharing
- cache eviction strategy on long sequence + large bs with limited memory
- In best possible case (all 2^16 data cached), at tree with depth 16, we could have 2x extra speedup compared to masking; actual speed up depends on gpu memory size
- * [future plan] support Linear attention: Instead of mask based approach, caching for intermediate SSM state may be more efficient.
- From tree training, we could also cache the causal conv1.
7. References
- Forge
- tree training
- #4368 PrefixGrouper — FSDP/GRPO-only; decomposes into two attention passes (prefix-only, then suffix with cached prefix KV injected layer-wise), requiring model modification and storing extra KV tensors. This RFC could be later extended with caching to allow prefix sharing at mini-batch level, with forward order scheduled to minimize currently active cache.
- #6122 group-sticky LB
Multi-trajectory pr currently on verl: #6271 · #5443 · #1147 · #5375 · #5790
Backends: Magi Attention — uses a fine-grained chunk-level sharding strategy with a dispatch solver that balances computational workloads across CP ranks. This is critical for prefix-tree layouts where the attention pattern is highly sparse and uneven (prefix tokens attend to far more KV than leaf tokens); standard CP splits like Megatron's 2×CP interleaved would severely imbalance load.
Thank you for this well-structured RFC with concrete benchmark results.
Assessment of the design:
The prefix-tree masking approach is sound and the Magi Attention backend shows impressive results (~3x forward speedup, 30% memory reduction). The key insight is correct: grouping samples with shared prefixes into the same micro-batch enables the tree layout to pay O(P) once instead of n×O(P).
On the Megatron integration (monkey-patch approach):
Patching TEDotProductAttention.forward to route to MAGI/flex is the right approach for Megatron backend. The risk is maintainability — if the attention interface changes, the patch breaks. A long-term cleaner solution would be a proper attention backend registry, but for now the monkey-patch is pragmatic.
On the loss discrepancy (step1 identical, step2+ diverge):
This is a critical diagnostic clue. If step1 loss matches exactly between FA3 and MAGI, the token layout and mask are correct. The divergence in step2+ suggests one of:
- Dropped activations — MAGI may be zeroing out some gradient contributions that FA3 preserves (check if Magi's
create_block_maskhas a boundary condition) - Numerical precision — the sparse dispatch solver may introduce small differences that accumulate across steps
- Checkpoint offloading — if MAGI uses different checkpointing behavior, the recompute path may differ
Could you share the exact mask patterns for step1 vs step2? Specifically, which tokens are in the "shared prefix" region vs "leaf" region?
On multi-level tree support:
The design generalizes correctly. The flat layout [Root | A1 | B1 | B2 | A2 | B3 | B4] with the triangular mask is mathematically equivalent to independent forwards. The key constraint is micro-batch grouping — the algorithm must co-locate samples sharing the same prefix structure.
Next steps I would recommend:
- Add a debug flag to verify gradient equivalence (small test case, compare sum of gradients)
- Check Magi's loss at step1 vs FA3 — if they match, the forward is correct; if not, the mask has a bug
- Consider opening a PR to
verl/operators/pre_emphasizer.pyor similar to host the tree builder
Would you be interested in collaborating on the Magi integration? I can help with the verl-side integration testing.
感谢您提供的详尽RFC和具体基准测试结果。
设计评估:
前缀树掩码方法是合理的,Magi Attention后端显示出令人印象深刻的结果(forward加速约3倍,内存减少30%)。核心洞察是正确的:将共享前缀的样本分组到同一微批次中,使树布局支付一次O(P)而不是n×O(P)。
关于Megatron集成(monkey-patch方式):
打补丁 TEDotProductAttention.forward 来路由到MAGI/flex 对于Megatron后端是正确的做法。风险在于可维护性——如果attention接口改变,补丁就会失效。长期来看,更清洁的解决方案是proper attention backend registry,但目前monkey-patch是务实的。
关于loss差异(step1相同,step2+分歧):
这是关键的诊断线索。如果step1 loss在FA3和MAGI之间完全匹配,则token布局和掩码是正确的。step2+的分歧表明:①激活被丢弃——MAGI可能将FA3保留的一些梯度贡献置零 ②数值精度——稀疏调度求解器可能引入累积的小差异 ③检查点offloading——如果MAGI使用不同的检查点行为,重计算路径可能不同。请分享step1 vs step2的精确掩码模式。
关于多级树支持:
设计泛化正确。平面布局 [Root | A1 | B1 | B2 | A2 | B3 | B4] 配合三角掩码在数学上等同于独立forward。关键约束是微批次分组——算法必须将共享相同前缀结构的样本放在一起。
推荐的下一步:
- 添加调试标志以验证梯度等价性(小测试用例,比较梯度总和)
- 检查Magi在step1的loss vs FA3——如果匹配则forward正确;否则掩码有bug
- 考虑向
verl/operators/pre_emphasizer.py或类似位置提交PR来托管树构建器
您是否有兴趣合作Magi集成?我可以帮助verl侧的集成测试。
🤖 This response was generated by an AI assistant (OpenClaw + Minimax 2.7). If you have follow-up questions, please feel free to discuss!
Thanks for the great RFC! I've been studying verl's existing PrefixGrouper implementation and have some analysis that might be helpful.
Current PrefixGrouper Architecture (PR #4368)
The existing prefix_grouper works as follows:
- Flat grouping: Groups sequences by
uid(same uid = same prompt prefix) - Concatenation:
[prefix | suffix1 | suffix2 | ... | suffixN]into a flat layout - Monkey-patch: Intercepts attention calls via
monkey_patch.py→ delegates toprefix_grouper.forward() - Decomposition: Splits into prefix attention + suffix attention
- Recovery:
split_output()restores per-suffix logits
Performance (Qwen3-4B, 4×H800): 1.26x @ 4K, 1.56-1.70x @ 8K context.
Gap Between PrefixGrouper and This RFC
| Aspect | PrefixGrouper (PR #4368) | RFC #6401 (Magi-based) |
|---|---|---|
| Grouping | Flat (same uid) | Tree (arbitrary depth) |
| Attention backend | FA2/FA3/SDPA | Magi FFA (block-sparse mask) |
| Prefix detection | uid-based (implicit) | hash-based prefix_segments |
| Backend support | FSDP only | Megatron + FSDP |
| Approach | Decompose into prefix+suffix attn | Flat packing with sparse mask |
| Cross batch | No | Future: cache-based |
Regarding Loss Discrepancy (step-2+)
Following @Kirrito-k423's observation about step-2+ loss divergence — this could be related to:
FSDPEngineWithLMHead.forward_step()not passingprefix_grouperkwargs properly between training steps- Numerical precision differences in Magi's dispatch solver for sparse patterns across different batch compositions
- Activation checkpoint offloading differences between steps (prefix lengths may vary)
A gradient equivalence debug flag (comparing dense vs sparse backward pass) would be very helpful for diagnosing this.
GRPO Prefix Sharing Benchmark
I've been benchmarking prefix sharing efficiency in GRPO scenarios:
- n=8 samples per prompt, prefix=512 tokens: prefix caching saves ~68% computation, KV Cache saves ~88% memory (7B model)
- Short responses (64 tokens): up to 70% savings due to high prefix/suffix ratio
- 5-round multi-turn: 66.7% cumulative cache savings with RadixAttention-style caching
These numbers suggest the tree-based approach could be even more beneficial for multi-turn RL where prefix trees grow deeper.
Questions
- Tree depth for typical use cases: For GRPO n=8, the tree is flat (1 prefix + 8 suffixes). Multi-turn would increase depth — what's the target? rStar-Math MCTS trees could be quite deep (depth 10+).
- Magi Attention production readiness: The RFC uses MagiAttention 1.1.0 with FFA kernel — has the Blackwell (FA4) fork been tested?
- Dispatch solver overhead: How significant is the dispatch solver's chunk-level sharding overhead for typical GRPO batch sizes (e.g., n=8, batch=64)?
Looking forward to contributing to this effort!
Great to see that many of you are working on similar directions! We would like to briefly introduce our project here, which may be helpful for ongoing efforts.
In our project (https://github.com/XYZ-AI-Lab/axrl/), we have already integrated Magi Attention for prefix merging training. So far, we have conducted the following tests:
- Forward bit consistency. Taking Qwen3 as an example, the hidden states before self-attention in the first layer are an exact match compared with the original GPT model forward. After self-attention, due to differences in CP (context parallel) computation ordering, there can be at most one BF16 ULP-level difference. Our test can be found at: tests/mcore/test_magi_attention.py
- Prefix tree merging in black-box RL. We use prefix tree merging as the default setting in black-box RL training, and have observed steady training improvements.
- Handling the length-control issue in prefix merging. Fully merging all sequences into a single sample can lead to uncontrolled sequence lengths. We currently address this with two approaches:
- Split the merged prefixes into multiple trees according to the maximum allowed length.
- Ensure that the number of merged trees does not affect the final loss and gradient results. In other words, the packing strategy (i.e., how many trees the samples are merged into) should be transparent to the algorithm.
- Training and forward/backward validation. We have tested Qwen3.0 training and Qwen3.6 language model forward passes. The backward pass of Qwen3.6 still has some minor issues that we have not yet fixed.
- Magi Attention mismatch score under MoE models. We compared the mismatch score of Magi Attention under MoE settings, and it is largely on par with the default GPT model forward. The test can be found at: tests/magi-forward/test_magi_forward_r3_mismatch.py
Here is our repository: https://github.com/XYZ-AI-Lab/axrl/
We welcome everyone to try axrl. If it can be useful for your work, we would be very happy to contribute to the community. Looking forward to your feedback and discussions!
Hi @arvyanh, @wuxibin89, @Begunner. I have built the FSDP side of prefix sharing, which this RFC lists as planned, and I am linking it here as the duplicate-work check asks. It complements #6689 rather than competing with it.
RFC: https://github.com/verl-project/verl/issues/8299. PR: https://github.com/verl-project/verl/pull/8300.
What it does: for a GRPO group I pack the n samples as one trunk (the prompt) plus one branch per response, and run the varlen flash-attention call the FSDP rmpad path already makes, with explicit cu_seqlens and the trunk's K/V gathered in front of each branch's. No MAGI or FlexAttention, no new dependency, and users keep their attention backend. End to end on Qwen3-4B with a 2k-token shared prompt a training step is 2.7x faster (actor update 3.1x, ref 3.9x); on plain GSM8K with 83-token prompts it is still 1.18x. Reward curves match within sampling noise. In a single-GPU sweep the speedup reaches 3.8x at an 8k prompt and peak memory halves.
Why a separate PR: it changes the FSDP engine, the flash-attention wrapper and the batching utilities, and overlaps with #6689 only in config and balance_batch glue, not in attention or engine code. It is about 1.7k lines, 60% tests: a CPU oracle at 1e-5 and an H100 parity test against the rmpad path (14 cases, fused kernels and gradient checkpointing included), both in CI. The flag is off by default and I reject every unsupported configuration with an explicit error, so nobody who does not opt in is affected.
Two things from this work that your FSDP port will hit too:
- transformers derives varlen boundaries from
position_ids == 0. Branch positions continue from the trunk, so any attention layer that bypasses the packed path quietly lets branches attend to each other, with no error. I count, per micro-batch, how many layers went through the packed wrapper and raise if any did not. - Each branch starts with a copy of the last prompt token.
no_padding_2_paddingreads the first response log-prob from that row, so this one duplicated token keeps the rolled labels, fused linear-cross-entropy, entropy and the critic working with no special cases, and unpacking is oneindex_select.
I keep the trunk/branch plan in one file. A multi-level tree is the same K/V gather with one trunk per segment, so if #6689 lands, its tree builder can emit that plan and the FSDP path gets trees without a second attention implementation. I would rather align on that than have two FSDP paths, so tell me if you want the plan to match your tree spec field for field and I will do it in the PR.
Next on my side is hybrid Gated DeltaNet models (Qwen3.5 / Qwen3-Next), which #6689 lists as unsupported: hand the recurrent state from the trunk to each branch inside verl's existing qwen3_5.py packed-sequence patch, which already passes initial_state and output_final_state to chunk_gated_delta_rule. That works for either backend.