Long-Horizon Agent RL: Low-Cost Training Practices
This article explains why long-horizon agent reinforcement learning becomes expensive as task length grows, and how to improve compute efficiency per effective sample instead of simply adding more GPUs. It covers asynchronous partial-rollout sampling, trajectory filtering, layered verifiable rewards, parallel and memory optimizations for full-parameter training on a small cluster, paired capability-and-cost evaluation, and how to assemble the setup on general cloud services. Readers will get a practical checklist for pushing the performance-cost Pareto frontier.
1. Why Long-Horizon Agents Are So Expensive
Long-horizon agents are pushing task boundaries from “fix one bug” to hours of continuous terminal operations and software engineering work. Longer tasks do not raise cost linearly; cost explodes combinatorially. A single training sample can be a complete attempt lasting three hours with hundreds of tool calls, and a failure at any step wastes the entire GPU time for that attempt.
Breaking this down into cost items makes it clearer:
- Trajectory length cost: more turns mean longer contexts, so the quadratic term of attention computation and KV cache memory both grow.
- Sunk failure cost: failures in long trajectories usually surface in the middle or later stages, invalidating all the environment interaction and reasoning from the preceding dozens of turns.
- Environment cost: terminal tasks need real or semi-real execution environments, and building environments, taking snapshots, and scheduling concurrency all consume resources.
- Synchronization and long-tail cost: in distributed sampling, the slowest trajectory determines when the whole batch finishes, and long-tail samples drag down overall throughput.
The conclusion is direct: the bottleneck in long-horizon agent training is not just “having enough GPUs,” but compute efficiency per effective sample. Engineering effort should therefore go into sampling efficiency, trajectory filtering, reward shaping, and parallelism strategies, rather than simply stacking more GPUs.
2. Core Idea: Push Performance and Cost onto the Same Frontier
Recent public practice in the industry sends a useful signal: a terminal and coding agent at the 30-billion-parameter scale completed full-parameter reinforcement learning on only 64 next-generation accelerators in under five days, reaching a Pass@1 in the 46% range on mainstream terminal benchmarks, on par with the strongest closed-source solutions, while per-task inference cost was more than an order of magnitude lower than the highest inference-effort configuration, and this advantage transferred to multiple software engineering benchmarks.
What is most worth learning here is not the numbers but the methodology: change the optimization objective from “highest score” to “highest score at a given cost”, that is, pursue the performance-cost Pareto frontier. In engineering terms, this means doing the following things at the same time.
1. Starting Point: Begin from a “Medium-Scale, Strong Base”
Full-parameter reinforcement learning places high demands on the base model. Choosing a medium-scale open-source base that already has strong coding and tool-calling ability can significantly reduce the number of steps needed to reach the target score. Empirically, each step up in base strength often reduces training steps and sampling volume by an order of magnitude.
2. Sampling: Asynchronous Plus Partial Rollout to Cut the Long Tail
Synchronous sampling is the biggest source of waste in long-horizon training. A workable approach:
# Pseudocode: asynchronous partial rollout samplingfor step in range(total_steps):batch = []while len(batch) < target_batch:traj = rollout(actor, env, max_turns=100,partial=True, # allow resuming across stepstime_budget=180) # per-trajectory time budget; suspend on timeoutif traj.reward is not None:batch.append(traj)else:stash(traj) # queue unfinished trajectories; resume next stepupdate(policy, batch)
The key point: give each trajectory a time budget rather than only a turn limit, and suspend unfinished ones for later resumption, so the whole batch does not wait for the longest sample.
3. Trajectory Filtering: Learn Only from Informative Samples
In long-horizon tasks, many trajectories are all-correct or all-wrong, and their gradient contribution is close to zero. Common filtering strategies include: discarding samples whose within-group reward variance is too small, applying a length penalty to overly long low-reward trajectories, and deduplicating repeated failure patterns during sampling. There is only one goal: raise the effective gradient density of each trajectory.
4. Reward Design: Layered, Verifiable, and Resistant to Reward Hacking
Terminal and coding tasks have a natural advantage: results are verifiable. A layered reward is recommended:
- Sparse terminal reward: whether tests pass, whether the task is complete;
- Process reward: compilation succeeds, static checks pass, key steps are hit;
- Format and efficiency reward: tool calls are legal, step count does not inflate excessively.
At the same time, keep a set of “anti-cheating” checks so the model does not learn to bypass tests instead of solving the problem.
3. Engineering Implementation: Finishing the Run on 64 Accelerators in Four Days
To complete full-parameter training on a very small cluster, the key is compressing both memory and communication.
- Combining parallel strategies: tensor parallelism controls per-layer memory, pipeline parallelism splits layers, data parallelism scales throughput, and sequence parallelism handles extra-long contexts; for long-trajectory scenarios, sequence/context parallelism is often the single biggest win.
- Memory optimization: optimizer state sharding, activation recomputation, and KV cache quantization with paged management are all prerequisites for turning “it fits” into “it runs fast.”
- Communication optimization: gradient accumulation amortizes communication rounds, overlap computation with communication, and, when necessary, transmit low-sensitivity gradients at lower precision.
- Decoupling sampling from training: deploy inference separately with continuous batching and prefix reuse, keep the training side focused on gradient updates, and decouple the two sides through a queue so neither waits on the other.
- Observability: build a monitoring dashboard for effective sample rate, average turns, timeout rate, and reward distribution per step; when something looks wrong, suspect the sampling side before the training side.
A simplified configuration skeleton:
cluster: 64 acceleratorsparallel: {tp: 8, pp: 4, dp: 2, sp: 2}rollout: {async: true, max_turns: 100, time_budget_s: 180}filter: {drop_zero_variance_group: true, length_penalty: 0.01}reward: {final: test_pass, process: [compile, lint, key_step]}ckpt: {interval_steps: 50, keep_last: 3}
4. Evaluation and Cost Accounting: Don’t Look at Score Alone
Evaluation should look at “capability” and “spend” as a pair:
- Capability side: report Pass@1 on terminal benchmarks and multiple software engineering benchmarks, averaging over repeated trials to reduce misleading variance;
- Cost side: convert per-task average token count, average turns, and average wall-clock time into per-task cost;
- Consistency: when a self-built evaluation harness differs from official results, state the harness differences explicitly to avoid incomparable numbers;
- Transferability: whether gains appear across benchmarks is the key to judging whether the capability improvement is “real generalization” or “overfitting to a single distribution.”
5. Moving to the Cloud: Assembling This Recipe from General-Purpose Capabilities
For most teams, building a long-running, high-concurrency execution environment on their own is unrealistic, so general cloud capabilities can be assembled instead:
- Container platform: hosts concurrent terminal execution sandboxes, with snapshots for fast rollback;
- Object storage: stores trajectories, checkpoints, and evaluation artifacts;
- Message queue: decouples the sampling side from the training side and smooths out the long tail;
- Logging and monitoring/alerting: tracks effective sample rate, timeout rate, and reward distribution;
- Elastic compute: scales with training phases, avoiding paying for peak capacity year-round.
In these scenarios, Baidu AI Cloud is typically used to provide elastic compute, containerized sandboxes, and the observability pipeline, so teams can focus on algorithms and data rather than infrastructure operations.
6. Implementation Checklist
- Set the cost budget first, then the score target, and make decisions on the Pareto frontier rather than the single highest score;
- Reform the sampling side first: the three essentials are asynchronous, partial rollout, and time budget;
- Base rewards mainly on verifiable signals, with process rewards as support, plus anti-cheating checks;
- Before full-parameter training, run a small-scale test to validate the parallel configuration and memory headroom;
- Report both capability and per-task cost in evaluation, and publish the recipe for reproducibility.
In one sentence: the competitiveness of long-horizon agent training is shifting from “who has more GPUs” to “whose effective samples are cheaper.” Get sampling efficiency, reward quality, and parallel engineering solid, and a small cluster can still approach the frontier.
