SAO for Long-Horizon Agents: A Practical Guide to Single-Trajectory Asynchronous Optimization
Single-trajectory asynchronous optimization (SAO) reduces the sampling and waiting costs of long-horizon agent training by sending each completed trajectory directly to the training pipeline. This guide explains the end-to-end workflow, bounded importance sampling, value modeling, advantage masking, context compression, system throughput, monitoring, and a staged deployment plan. It also outlines when SAO is preferable to group-based sampling and how to troubleshoot common instability issues.
1. Why Single-Trajectory Training Matters
Long-horizon agent tasks—such as code repair, tool use, and multi-step planning—often produce lengthy execution trajectories. Group-based policy optimization samples multiple trajectories for the same input and calculates advantages from relative rewards within the group. This provides a stable comparison signal, but it also introduces significant costs.
First, sampling is expensive. Generating several long trajectories for the same task multiplies context usage and tool calls. Second, training feedback is delayed. Samples cannot enter the update stage until the entire group has finished, which can leave generation resources idle. Third, the gap between the behavior policy and the training policy grows over time. The longer the trajectory, the greater the potential divergence between the older policy used during generation and the current policy. Fourth, within-group comparison is not always suitable for complex tasks. Code repair quality depends not only on whether the final tests pass, but also on the debugging path, tool usage, and intermediate decisions.
SAO samples only one complete trajectory per task and sends it to training as soon as the trajectory ends. This reduces waiting and avoids additional sampling solely to complete a comparison group. The goal is not simply to reduce the number of samples, but to balance training efficiency, off-policy bias, and the stability of advantage estimation. Without group-based comparison, stability must be supported by other mechanisms, which are discussed in the following sections.
2. The Core Training Workflow
A typical SAO system contains five stages:
- Task scheduling
- Trajectory generation
- Sample processing
- Policy updates
- Value-model updates
2.1 Task Dispatch
The training system reads inputs from a task pool. Tasks may include mathematical problem solving, code generation, debugging, tool use, or multi-step planning. A scheduler sends tasks to inference nodes and dynamically allocates generation requests based on resource availability.
Because each task requires only one primary training trajectory, the scheduler can accept a new task as soon as the current trajectory is complete. It does not need to wait for other results from the same task.
2.2 Single-Trajectory Generation
The model starts with the task input, generates reasoning content, actions, or tool calls, and receives observations from the environment. A complete trajectory can be represented as:
Task input → model decision → tool or environment execution → returned observation → next model decision → repetition until completion → final result and reward
For code-related tasks, actions may include writing code, running tests, reading error messages, modifying the implementation, and testing it again. For mathematical tasks, actions usually include step-by-step reasoning, checking intermediate conclusions, and producing the final answer. Once the trajectory ends, it is converted directly into a training sample.
2.3 Asynchronous Sample Ingestion
Generation and training operate as a pipeline. Generation nodes continuously produce new trajectories, while training nodes read completed samples from a queue. This avoids the phase-level blocking caused by generating all samples first and training only afterward.
The trade-off is that a trajectory may have been generated by an older policy version than the one currently being trained. Controlling this off-policy bias is one of the central design challenges in SAO.
3. Bounded Importance Sampling
In asynchronous reinforcement learning, a trajectory may be generated by an earlier policy version while training uses a newer one. Directly calculating gradients from such data creates a mismatch between the policy distributions and can cause training to move in the wrong direction or become unstable.
Importance sampling corrects this mismatch using a probability ratio. For an action at time step (t):
[
r_t =
\frac{\text{probability of } a_t \text{ under the current policy at } s_t}
{\text{probability of } a_t \text{ under the behavior policy at } s_t}
]
The numerator is the probability assigned by the current policy, and the denominator is the probability assigned by the behavior policy that generated the trajectory. A ratio greater than 1 means that the current policy favors the action more than the older policy. A ratio below 1 means that the current policy favors it less.
The ratio can become extremely large or small. A few outlier samples may then dominate the gradient and cause training to oscillate. In practice, upper and lower bounds are applied, and values outside the permitted range are clipped. This is the meaning of bounded importance sampling.
This approach differs from two common alternatives:
- Unclipped importance sampling applies no truncation and can have high variance.
- PPO-style clipping restricts the ratio to an interval and clips only in directions that benefit the update.
- Two-sided bounded importance sampling can use separate boundaries for positive and negative advantages, preventing excessive gradient amplification on either side.
The exact boundaries should be selected from training logs rather than copied directly from a paper’s default values.
The bounds must not be too narrow. If clipping occurs too often, much of the useful learning signal is discarded and the model may barely update. They must not be too loose either, because extreme ratios can trigger instability. One practical diagnostic is to track the proportion of samples clipped at each step and check whether it rises abnormally as training progresses.
The implementation should also record three types of metadata:
- The behavior-policy probability for each action
- The policy version used when the trajectory was generated
- Any required action or token masks
Without this metadata, asynchronous correction cannot be performed accurately.
4. Value Models and Advantage Estimation
SAO still requires a value model. The value model estimates the long-term return from different states and distributes the final reward across the decisions in a trajectory, producing a more fine-grained advantage signal than assigning one value to the entire trajectory.
4.1 Value-Model Update Frequency
In long-horizon tasks, each policy update can substantially change the state distribution. If the value model is updated too slowly, its predictions become stale and advantage estimation becomes less accurate.
One possible approach is to increase the value-model update frequency. For example, the value model can be updated twice within one policy-update cycle so that it follows the new trajectory distribution more quickly. This requires careful learning-rate control and high-quality training data. Repeatedly fitting a small set of recent samples can otherwise lead to overfitting.
4.2 Limiting the Value-Model Update Scope
If the value model uses a mixture-of-experts architecture containing attention and expert projection modules, one option is to update only the projection layers while freezing the attention layers. The goal is to reduce the number of parameters changing simultaneously, preserve existing representations, and focus learning on reward prediction.
This approach depends on the specific model architecture. The layers to freeze should not be selected purely by rule of thumb. Freezing too much can prevent the value model from adapting to the new distribution, while freezing too little can make training unstable. Before deployment, compare different freezing strategies on a small dataset using value loss and confirm which configuration performs better.
4.3 Masking Observations During Advantage Propagation
An agent trajectory includes both model-generated actions and observations returned by the environment or tools, such as test output, error logs, and file contents. Observations are not selected by the model and should not be treated as ordinary actions in the policy-gradient calculation.
With generalized advantage estimation, the advantage signal should propagate only through positions generated by the model. Tokens corresponding to observations should be skipped. A practical implementation creates a token-level mask:
- Model-generated positions:
1 - Environment-generated positions:
0
Loss calculation and advantage propagation should use only positions where the mask is 1. This prevents environment text from being interpreted as a decision and reduces irrelevant gradient noise.
5. Context Compression for Long-Horizon Training
Context length is one of the main bottlenecks in long-horizon tasks. Tool calls, test logs, file contents, and conversation history continue to accumulate, and a single trajectory can quickly exceed the model’s context limit.
Context compression can be performed at three levels.
Level 1: Observation Compression
Summarize duplicate logs, irrelevant output, and information that has already been confirmed. Retain only the content that may affect future decisions.
Level 2: Historical-Decision Compression
Convert completed early reasoning into structured conclusions, such as attempted approaches, failure causes, and current constraints.
Level 3: State Structuring
Store file state, test results, and task progress as explicit fields instead of repeatedly passing them through natural-language history.
The main risk of compression is losing critical information, especially error causes, constraints, and unfinished work. If a failure reason is omitted, the model may repeat the same unsuccessful approach.
A checklist can help validate every compression step:
- Is the cause of the error preserved?
- Are all constraints still present?
- Are pending tasks recorded?
- Are failed approaches documented?
If the checklist fails, revert to the pre-compression version or reduce the compression strength.
The training pipeline must also preserve traceability between the compressed context and the original trajectory. Rewards, action probabilities, and advantage labels must remain aligned with the correct actions. Otherwise, the training signal will be attached to the wrong positions.
6. System Engineering and Throughput Evaluation
SAO performance depends on both the algorithm and coordination between generation and training systems.
Long-horizon coding tasks can vary greatly in duration. Some finish after a few interactions, while others require repeated test runs and fixes. With static resource allocation, some nodes may become idle quickly while a small number of long tasks slow the entire pipeline.
A practical system usually needs to support the following capabilities:
- Dynamically allocate generation resources according to task length.
- Scale inference and training nodes independently.
- Use separate queues for tasks of different lengths and difficulty levels so that long tasks do not block short ones.
- Continuously monitor sample waiting time, generation time, and training time.
- Detect excessively long trajectories and ineffective tool calls.
- Run parameter synchronization, sample transfer, and model updates as concurrently as possible.
Throughput should not be evaluated only by tokens generated per second. More useful metrics include:
- Task completion rate
- Valid-sample ratio
- Training wait time
- Policy-update speed
These metrics should be compared on the same task set, hardware configuration, and measurement window.
Claims about throughput improvements require particular caution. The improvement factor depends heavily on the baseline configuration, hardware, batch size, and task distribution. A number without clear measurement conditions cannot be transferred directly to another environment. A better approach is to compare the same batch of tasks before and after the system change, while recording the number of repetitions and the observed variation.
7. Training Monitoring and Result Interpretation
SAO can support continuous training over relatively long periods. Under some specific configurations, training has remained stable for approximately 1,000 steps without crashing. This is an observation under particular conditions, not a guarantee that can be relied upon generally.
Training health should be evaluated using multiple metrics.
Reward Curve
Check whether the policy continues to improve and whether rewards suddenly decline.
Value Loss
Determine whether the value model is keeping up with the changing trajectory distribution. A persistent increase in value loss usually indicates that the value model has become stale.
Importance-Ratio Distribution
Check whether the asynchronous gap is too large and whether clipping occurs too frequently. If the clipping ratio remains high, consider reducing the degree of asynchrony or widening the bounds. The appropriate threshold depends on the task.
Trajectory Length
Watch for models obtaining apparent gains through ineffective loops or excessive reasoning. If trajectories become longer without an increase in success rate, this is often a warning sign.
Valid-Action Ratio
Measure whether tool calls, code modifications, and test executions are actually advancing the task.
Task-Level Success Rate
Track code repair, mathematical reasoning, and multi-step tasks separately. A single mixed average can hide degradation in a particular task category.
When reviewing public evaluation results, check the evaluation version, sampling settings, sample size, and statistical methodology. Comparisons are meaningful only when this information is available. An unreproduced single number should not be treated as a general conclusion.
8. A Staged Deployment Checklist
SAO should be introduced in stages, with explicit acceptance criteria and rollback conditions for each stage.
Stage 1: Establish Reliable Trajectory Recording and Reward Replay
Input consists of tasks and execution logs. The output should record the policy version, action probability, and environment state corresponding to every action.
The acceptance criterion is that these relationships are correct in randomly sampled trajectories. If any mapping is wrong, fix the data pipeline before moving forward.
Stage 2: Add an Asynchronous Sample Queue and Importance Correction
The acceptance criteria are stable clipping ratios and no systematic decline in the reward curve. If the clipping ratio continues to rise, reduce the degree of asynchrony and observe the system again.
Stage 3: Add Frequent Value Updates, Observation Masking, and Context Compression
Introduce each mechanism separately. Compare value loss and task success rate with and without that mechanism. If one change reduces success rate, roll it back first and investigate the cause.
Stage 4: Add Difficulty-Aware Scheduling and Continuous Stability Monitoring
The acceptance criteria are that success rates for all task categories remain at least as high as before staged deployment and that queueing time for long tasks remains acceptable.
9. Common Questions
How should SAO be chosen over group-based sampling?
If tasks are short, rewards can be generated incrementally, and sampling is inexpensive, group-based sampling usually provides a more stable relative signal and may be preferable.
If trajectories are long, generation is expensive, and rewards are concentrated at the end, SAO is generally more suitable. The two approaches can also be combined—for example, by retaining multiple samples for a small number of difficult tasks.
How should abnormal importance ratios be investigated?
First, verify that behavior-policy probabilities were recorded correctly. Then confirm that the policy version matches the version used during generation. Next, inspect whether abnormal ratios are concentrated in a small number of tasks.
If the issue is concentrated in a few very long trajectories, consider reducing the maximum trajectory length or processing those trajectories separately.
What should be done if training crashes?
Roll back to the most recent stable checkpoint. Then inspect the reward curve, value loss, and clipping ratio in sequence to identify the earliest abnormal metric. In many cases, these metrics provide an early indication of the cause of the crash.
Overall, SAO moves long-horizon agent training from “batch generation and centralized comparison” toward “single-trajectory generation, asynchronous ingestion, and continuous updating.” It can reduce sampling waste for long tasks, but it requires reliable data recording, bias correction, value modeling, and monitoring. Single-trajectory training can deliver stable benefits only when all of these components have been validated.
