Post-Training Long-Horizon Agents: Advantage Estimation and Context Compression
This article discusses the key challenges in reinforcement learning (RL) post-training for long-horizon AI agents, focusing on two critical directions: the evolution of advantage estimation from GRPO to critic-based and adaptive methods, and the integration of context compression into the RL optimization loop (CompactionRL). It covers practical engineering considerations, algorithmic trade-offs, and a debugging case study, providing a structured framework for combining these methods in production training systems.
Why Agentic RL Post-Training Is Harder
Compared with mathematical or coding tasks, agentic tasks present several training difficulties:
- Long-horizon nature: A single task often requires dozens or even hundreds of tool calls, producing trajectories far longer than typical dialogues.
- Sparse and delayed rewards: Rewards are usually only given at the end of the task, making it difficult to judge the correctness of intermediate steps.
- Continuously expanding context: Observations and tool return values accumulate, increasing memory and compute costs during training.
- Credit assignment difficulty: Final rewards must be traced back to specific actions, which increases the variance of policy gradients.
These four points are interrelated. Longer trajectories lead to sparser rewards, and longer contexts make each update more expensive. As a result, post-training methods for agents typically need to address both advantage estimation and context management simultaneously.
This article focuses on two directions. First, the evolution of advantage estimation—from GRPO to critic-based methods—and the broader idea of adaptive approaches such as SAO. Second, CompactionRL, which incorporates context compression into the reinforcement learning optimization loop.
From GRPO to Critic-Based: Evolution of Advantage Estimation
What GRPO Trades Off
GRPO removes the explicit value network. It samples a group of trajectories for the same problem, normalizes them using the mean and standard deviation of rewards within the group, and assigns an advantage to each trajectory. This approach avoids training a critic comparable in scale to the policy, reducing memory pressure and simplifying implementation. For short trajectories and tasks with dense verifiable rewards, it usually works well.
Its drawbacks are concrete:
- When all trajectories in a group are entirely correct or entirely wrong, all rewards are identical, making the normalized advantage near zero. Such groups produce almost no gradient. A common workaround is dynamic sampling: filter out such prompts or resample, spending compute budget on problems with discriminative signal.
- A single scalar advantage is shared by the entire trajectory. For long trajectories, this signal cannot distinguish which steps were effective and which were not.
Returning to Critic-Based Methods
For agent tasks with long trajectories and sparse rewards, the second drawback of GRPO is amplified. Therefore, many recent works return to critic-based methods, which can be viewed as modern variants of PPO. These train a value network V(s) to estimate state values, then propagate rewards back step-by-step using temporal difference residuals. The common form of Generalized Advantage Estimation (GAE) is:
δt = r_t + γV(s{t+1}) − V(s_t)
At = Σ_l (γλ)^l δ{t+l}
This approach introduces three engineering issues:
- Training signal for the value network: When rewards are sparse, the value regression target itself is noisy. A common approach is to incorporate verifiable intermediate signals, such as whether a tool call succeeded or whether the output format is compliant.
- Compute overhead: The critic’s parameter count is usually comparable to the policy, significantly increasing training cost. Parameter sharing and lower critic update frequency are common compromises.
- Training stability: The GAE truncation length, value clipping, and entropy regularization for long trajectories all require careful tuning.
SAO: The Idea of Adaptive Advantage
The core idea of SAO is to avoid applying the same advantage computation and update strength to all samples. Instead, adjustments are made based on trajectory characteristics. Different implementations vary, but the common direction can be summarized as follows (without specific formulas or hyperparameters):
- Distinguish successful and failed samples by trajectory outcome, adjusting the advantage scaling to reduce update bias from difficulty imbalance.
- Segment long trajectories into steps and introduce step-level advantages to mitigate the information loss of a single scalar advantage.
- Use dynamic sampling to prioritize prompts with high reward variance and high learning value.
These designs share a common goal: allocate limited training compute to samples with high gradient signal-to-noise ratio. Their applicability is bounded. Step-level advantages depend on estimates of intermediate states, which may be noisy. If the reward verifier is unreliable, adaptive adjustments can amplify incorrect signals. Specific results should be validated against the ablation studies in the original papers.
CompactionRL: Incorporating Context Compression into the RL Loop
Problem Definition
After multiple rounds of interaction, the context can easily reach tens of thousands of tokens. During training, if every update performs forward and backward passes on the full context, attention computation scales quadratically with length, causing costs to rise quickly. Inference deployment faces the same long-context overhead.
The most direct solutions are truncation or sliding windows, but truncation loses early task objectives and key conclusions. Fixed-template summaries do not lose template fields but cannot adapt content retention to the task. CompactionRL addresses a third direction: letting the model decide what to compress and learning compression quality through rewards.
Two Compression Modes Determine Learnability
It is important to distinguish two types of compression:
- Rule-based compression, such as truncation, sliding windows, or fixed templates. The compression action is not generated by the policy, has no sampleable parameters, and cannot be optimized through policy gradients.
- Model-generated compression. The policy itself outputs a summary; every token in the summary has a sampling probability. Only this type of compression behavior can be directly adjusted by reinforcement learning.
Thus, “learnable compression” requires that the compression is generated by the policy and the log-probabilities of compressed tokens are recorded.
How Compression Enters the Policy Gradient
A model-generated summary is also a sequence of actions. Training requires handling recording, segmentation, and credit assignment separately.
- Recording: Save the log-probability of each token during summary generation, treating the summary as one action in the trajectory.
- Segmentation: The context changes before and after compression, so the trajectory must be split into multiple segments. Each segment stores its own input context, generated tokens, and log-probabilities. During training, each segment’s input must match the sampling-time context; otherwise, the policy gradient is computed against the wrong conditional distribution.
- Credit assignment: One approach is to assign the entire trajectory advantage to all segments, including the summary segment. This gives the compression behavior only indirect benefit or penalty, providing a coarse signal. Another approach is to add an auxiliary loss, for example, having the model answer historical probe questions based only on the summary, using probe accuracy as direct supervision on compression quality. The effectiveness of these two approaches must be compared on your own task; there is no unified conclusion yet.
How to Define “Key Information”
The phrase “preserve task objectives, key conclusions, and pending status” is easy to state abstractly. In practice, it can be implemented as follows:
- Structured summary template: Fixed fields including task objective, confirmed facts, key tool return values (preserve raw text or IDs), and unfinished items.
- Probe set: Extract questions with clear answers from history, such as “What file path did the last query return?” After compression, let the model answer based only on the summary, and compute the accuracy to obtain the key-fact retention rate.
- Evaluation metrics: In addition to task success rate, record average compression ratio, number of compression events per trajectory, extra tokens generated for compression, and key-fact retention rate.
Training Data Flow Skeleton
The following code only demonstrates the data flow; it is not a runnable implementation. The policy, env, verifier, and count_tokens functions must be provided by your own training framework.
from dataclasses import dataclass@dataclassclass Segment:kind: str # "act" or "compact"input_ids: list # full input context at sampling timeoutput_ids: list # generated tokens for this segmentlogprobs: list # logprob for each generated tokendef run_episode(policy, env, prompt, threshold, max_turns, max_summary_tokens):segments = []context = [prompt] # initialize contextobs = env.reset(prompt)context.append(obs)action_text = Nonefor _ in range(max_turns):if count_tokens(context) > threshold:summary = policy.generate(context, max_new_tokens=max_summary_tokens,mode="summary")segments.append(Segment("compact", summary.input_ids,summary.output_ids, summary.logprobs))context = [prompt, summary.text] # replace history with summaryact = policy.generate(context, mode="action")segments.append(Segment("act", act.input_ids,act.output_ids, act.logprobs))action_text = act.textif act.is_final:breakobs, done = env.step(action_text) # act first, then interact with envcontext.append(action_text)context.append(obs)if done:breakreward = verifier(env, action_text) # final rewardreturn segments, rewarddef update(policy, batch_episodes):# Normalize within the same prompt group to get episode-level advantage,# then assign it to all segments of that episode.for episode_segments, advantage in batch_episodes:for seg in episode_segments:policy.accumulate_pg_loss(seg, advantage)policy.optimizer_step()
Several implementation details deserve attention:
- The
thresholdshould not be too low. Otherwise, summaries are triggered too frequently, key information is repeatedly compressed, and errors accumulate. It should not be too high either, because compression would barely save memory. A reasonable starting point is about half the model’s window size, adjusted based on success rate and memory curve. This is only a starting point for tuning, not an empirically optimal value. max_summary_tokensmust be limited to prevent the summary itself from becoming a long text and defeating the purpose of compression.- In early training, compression capability is usually weak. A common practice is to pre-train with high-quality summaries via supervised fine-tuning as a warm start, then proceed to the RL stage.
- The context used during training must match the context sampled by the inference engine. Numerical differences between the inference engine and the training framework can cause log-probabilities to not match exactly; monitor the importance ratio for anomalies.
A Debugging Case
During one training run, the success rate after compression dropped noticeably. Inspecting trajectories revealed that the summary preserved the task objective but lost the file path returned by a tool call. Subsequent actions repeatedly referenced a non-existent path, the environment returned errors, and the model fell into a retry loop.
Such issues are hard to detect from overall success rate alone; they require probing the probe set trajectory by trajectory. Here is the debugging procedure:
- Extract compressed and uncompressed contexts from failed trajectories and compare whether key facts are preserved.
- Compute retention rates by tool type to identify which types of return values are most likely lost.
- For such return values, force retention of raw text or place them in structured fields, then rerun the probe set.
This example illustrates that compression quality must be measured separately. Looking only at the final reward cannot identify whether the problem lies in the compression step or the decision step.
How to Combine the Two Approaches
SAO-style ideas and CompactionRL address two different issues. The former targets the low gradient signal-to-noise ratio under sparse rewards; the latter targets the high compute cost of long-trajectory training and inference. In a complete post-training system, they are typically used together. A reference order is as follows:
- Construct verifiable rewards: Dense signals such as unit tests, sandbox execution, and format validation should be prioritized.
- Collect trajectories asynchronously: Tool call time is usually much higher than the model forward pass; asynchronous rollouts improve GPU utilization.
- Use curriculum difficulty scheduling: Start with medium-difficulty tasks to avoid the model lacking useful gradients for long periods.
- Apply dynamic sampling and advantage filtering: Remove prompts with all-correct or all-wrong groups.
- Execute compression during rollout and record log-probs of compression segments.
- Compute per-segment losses and continuously monitor key metrics.
Recommended metrics to monitor include: task success rate, average trajectory length, compression count, key-fact retention rate, proportion of zero-variance groups, policy entropy, and value loss when using a critic.
Summary
Agentic RL post-training is shifting from direct transfer of general RL algorithms to customized designs that address long horizons, sparse rewards, and context bloat. The evolution of advantage estimation addresses how to make updates more effective under sparse rewards. Context compression addresses how to train long-horizon interactions within acceptable compute budgets while staying consistent with the inference distribution.
The method descriptions in this article are based on a review of existing materials. The specific algorithms of SAO and the experimental results of CompactionRL should be referenced from the original papers. Context compression also carries clear risks: it can lose information, and improperly set thresholds can directly degrade performance. On your own tasks, verify compression quality with a probe set before scaling up training.
