verl icon indicating copy to clipboard operation
verl copied to clipboard

[RFC] Tree Prefix Reuse for Multi-Trajectories Training

Open 1903943257 opened this issue 3 months ago • 2 comments

Summary

In Agentic RL, multiple trajectories often originate from the same prompt or intermediate state. For example, GRPO samples multiple responses from the same prompt, resulting in substantial shared prefixes that can potentially be reused during training.This RFC proposes introducing Tree Prefix Reuse (TPR) into the Megatron training path in verl. TPR aims to eliminate redundant computation across Agent RL trajectories that share token-level exact prefixes.

The execution design of TPR is inspired by the Dynamic Tree Execution approach in AReaL-DTA. Trajectories with shared prefixes are organized into a Prefix Tree and executed according to the tree structure. Per-layer KV states of shared prefixes are retained and reused across branches. Gradients from different branches with respect to the shared Prefix KV are accumulated. When the execution of a Prefix is completed, its backward graph is recovered through recomputation, allowing the accumulated gradients to propagate to model parameters and further upstream Prefixes.

TPR is integrated as an optional execution path inside MegatronEngine. Normal training continues to use the original Megatron forward/backward schedule. TPR only changes the execution topology for Prefix Tree workloads and does not alter the original training semantics.

Motivation

For multiple trajectories sharing a common Prefix, the training path typically executes each complete trajectory independently. As a result, the shared Prefix is repeatedly computed during both forward and backward passes.

Unlike inference-time Prefix KV reuse, training-side reuse must also preserve backward propagation through the shared Prefix and aggregate gradient contributions from multiple trajectories. Therefore, existing inference-side KV Cache reuse mechanisms cannot be directly applied to training.

Prefix sharing in Agentic RL mainly comes from the following scenarios.

Trajectory Branching Introduced by Agent / Harness

  • Trajectory split: A Harness may rewrite or reorganize an existing context / trajectory and produce new trajectory branches. Existing approaches typically either train these trajectories independently, which repeatedly computes their token-level identical Prefixes, or mask parts of the split region, which may discard useful training signals. Representing these trajectories as a Prefix Tree allows each branch to preserve its original training semantics while reusing the still token-identical Prefix.
  • Explicit branching: An Agent may explicitly fork multiple branches, such as subagents or multi-attempt execution, where each branch continues generating its own trajectory independently.

Algorithm-Level Multi-Branch Sampling and Exploration

  • Group sampling: GRPO / GSPO and similar algorithms generate multiple independent responses from the same prompt or state.
  • Trajectory-level branching / search: Algorithms such as Tree-GRPO and BPO explicitly create multiple downstream branches within a trajectory.

More generally, whenever multiple trajectories contain token-level exact shared context, they can potentially be organized into a Prefix Tree and reused by TPR.

Architecture

The vLLM / UniAgent side is responsible for producing and organizing trajectory trees. The verl training side directly consumes the tree-structured trajectories together with their training metadata. TPR is implemented inside the Megatron execution path in verl.

+------------------------------------------------------+
| UniAgent Rollout / Harness                           |
|                                                      |
| Tree-structured Trajectories + Training Metadata     |
+-----------------------------+------------------------+
                              |
                              v
+------------------------------------------------------+
| verl Trainer                                         |
|                                                      |
|                MegatronEngine                        |
|                     |                                |
|          +----------+----------+                     |
|          |                     |                     |
|       Normal                 Tree                    |
|          |                     |                     |
|   Original Schedule      TPR Scheduler               |
|                                |                     |
|                                v                     |
|                         Megatron Model               |
+------------------------------------------------------+

TPR only changes the forward/backward execution topology of tree-structured trajectories inside Megatron and the lifecycle of Prefix States. It does not change the original training semantics.

Design

Prefix Tree and Segment

TPR takes a pre-organized Prefix Tree as its training input. Each node in the tree represents a contiguous sequence segment, referred to as a Segment:

              P
           /     \
          A       S3
        /   \
       S1   S2

Each Segment stores its tokens, positions, parent relationship, and corresponding training information such as loss mask, advantage, and old logprob.

The Prefix Tree only shares computation states and does not merge trajectory losses. At a branch point, next-token targets belonging to different trajectories are still computed independently.

Tree Execution

TPR executes Segments in DFS order and manages Prefix States through Push / Visit / Pop operations:

Push(P)
  |
  +-- Push(A)
  |     +-- Visit(S1)
  |     +-- Visit(S2)
  |     `-- Pop(A)
  |
  +-- Visit(S3)
  `-- Pop(P)

The operations have the following semantics:

  • Push: creates a reusable Prefix State for downstream branches;
  • Visit: executes the current leaf Segment;
  • Pop: performs gradient aggregation, recomputation, and backward for the corresponding Prefix.

With DFS execution, only Prefix States on the currently active path need to be maintained at any given time.

Prefix State Reuse

When executing the current Segment, computation is performed only for the current tokens, while already-computed per-layer KV states from ancestor Prefixes are reused:

Q = Q_current
K = [K_prefix, K_current]
V = [V_prefix, V_current]

The current Segment still uses its original positions in the complete trajectory, preserving the original causal and RoPE semantics.

The newly generated KV states of the current Segment can in turn be reused as Prefix States by downstream branches.

Backward and Gradient Aggregation

Different branches independently produce gradients with respect to the shared Prefix KV:

dKV_prefix = Σ dKV_branch

TPR does not retain the complete autograd graph of a Prefix throughout the lifetime of its entire subtree.

After the initial Prefix execution, only reusable Prefix States are retained, while the full backward graph is released. During branch backward, gradients with respect to the Prefix dKV are accumulated into a Gradient Buffer. When the corresponding Prefix is Pop-ed, the Prefix is recomputed to reconstruct its backward graph, and the accumulated dKV is then used to complete Prefix backward.

The resulting gradients continue propagating to model parameters and further upstream Prefixes.

Megatron Integration

TPR does not introduce a separate Trainer. Training still enters Megatron through:

MegatronEngine.forward_backward_batch()

The execution path is selected according to the request type:

                    request
                       |
             +---------+---------+
             |                   |
          normal                TPR
             |                   |
             v                   v
      original schedule     tree scheduler
             |                   |
             v             segmented F/B
      SelfAttention               |
                                  v
                         TPRSelfAttention

The main changes are:

  1. Patch McoreEngineConfig

    Add a tpr_enabled=False switch. The TPR path is entered only when explicitly enabled, leaving existing training behavior unchanged.

  2. Patch Megatron model construction

    Wrap the ModuleSpec provider and replace SelfAttention with TPRSelfAttention.

    When no tree context is present, execution falls back to the original SelfAttention.forward.

  3. Patch MegatronEngine.forward_backward_batch()

    Detect TPR requests and route them to the tree scheduler. Normal requests continue to use the original Megatron schedule.

Experimental Results

Experiments use a 0.6B, 32-layer Megatron GPTModel on Ascend NPU with BF16, comparing the standard Reference (normal) execution path against TPR.

Correctness

We perform an end-to-end comparison on a manually constructed Prefix Tree with P=1024, S=512, N=2:

Metric TPR vs. Reference
Loss relative diff 4.46e-5
Logprob relative L2 1.17e-3
Logprob cosine 0.9999993
Gradient relative L2 1.54e-2
Gradient cosine 0.9998819

We further run 20 consecutive training steps and observe no continuously growing numerical divergence. Selected steps are shown below:

Step Loss rel. Logprob rel. Grad rel. Grad cosine Param rel.
1 2.72e-5 4.10e-3 3.44e-2 0.999419 2.97e-5
10 1.47e-4 3.10e-3 2.02e-2 0.999819 3.41e-5
20 1.39e-4 2.58e-3 1.63e-2 0.999868 3.64e-5

Performance

With N=2 fixed, we compare different Prefix / Suffix ratios:

Prefix Suffix Reference TPR Speedup Ref Mem TPR Mem Mem Reduction
16k 2k 6.74s 4.22s 1.60× 24.22 GiB 24.09 GiB 0.53%
8k 8k 5.34s 4.34s 1.23× 21.54 GiB 13.54 GiB 37.15%
4k 8k 2.84s 2.70s 1.05× 16.48 GiB 13.05 GiB 20.81%

With P=16k, S=2k fixed, we increase the number of branches:

Branch Reference TPR Speedup Ref Mem TPR Mem Mem Reduction
2 6.74s 4.22s 1.60× 24.22 GiB 24.09 GiB 0.53%
4 13.53s 5.41s 2.50× 24.22 GiB 24.10 GiB 0.53%
8 27.84s 7.50s 3.71× 24.22 GiB 24.09 GiB 0.53%
16 56.17s 11.63s 4.83× 24.22 GiB 24.10 GiB 0.48%

With P=S=8k, where only 50% of the trajectory is shared, TPR still achieves a 1.23× speedup while reducing peak incremental memory usage by 37.15%.

With P=16k, S=2k fixed, increasing the number of branches from 2 to 16 improves the TPR speedup from 1.60× to 4.83×, while peak memory usage remains nearly constant as the number of branches increases.

Future Work

Future work will mainly extend TPR to distributed training and dynamic Agent trajectory scenarios.

Parallel Training

We will further validate and extend TPR under existing Megatron parallelism strategies, including CP, DP, TP, PP, and combinations of these parallel dimensions.

TPR will continue to keep Tree Scheduling decoupled from model-parallel execution:The Tree Scheduler manages Segment execution order and the lifecycle of Prefix States.Execution within each Segment continues to reuse existing Megatron parallelism mechanisms.

Dynamic Tree Construction

We will implement dynamic tree construction on the UniAgent rollout / harness side so that operations such as branch, fork, and trajectory split can directly produce and propagate tree metadata.

The TPR training path will use this metadata to maintain the Prefix Tree and Segment relationships, extending the training input from statically pre-constructed trees to dynamic trajectory trees produced during real Agent execution.

1903943257 avatar Aug 26 '26 10:08 1903943257

https://github.com/verl-project/verl/pull/6689

wuxibin89 avatar Aug 26 '26 11:08 wuxibin89

Hi, did you test on NPU? We were working on a similar topic and tested on both Ampere GPU and Ascend 910 NPU, with the same target but a minor different solution. I would like to have a more in‑depth discussions, feel free to contact me via e-mail :) (check it on my GitHub profile)

Jackie2049 avatar Aug 29 '26 02:08 Jackie2049