Efficient Training Recipes for Long-Horizon Agentic Reinforcement Learning

    Long-horizon agentic RL changes the cost structure of training: trajectories span hundreds of tool calls, feedback is sparse, and a single failed run can burn hours of accelerator time. This article breaks down where the compute actually goes, summarizes the key findings of a publicly released full-parameter RL recipe for terminal and coding agents (dozens of next-generation AI accelerators, under five days, roughly 46% Pass@1 on terminal benchmarks, and cost more than an order of magnitude below the highest-reasoning-effort baseline), and lays out six reusable engineering practices: base model choice and full-parameter updates, task curricula, verifiable rewards, asynchronous streaming rollouts with prefix reuse, sandbox isolation and determinism, and training stability. It closes with how to evaluate and account for cost properly, a pragmatic rollout order, and three common pitfalls.

    1. Where the Problem Starts: Long-Horizon Agents Change the Cost Structure of RL

    Early work on agentic reinforcement learning mostly targeted short tasks: a single tool call, one code completion, a single-turn question. Sampled trajectories were typically tens to a few hundred tokens, and the cost of one training sample stayed manageable. Once agents began taking on “continuous terminal operation and software engineering tasks lasting hours,” the cost structure changed qualitatively:

    • Extremely long single trajectories: one complete attempt may contain hundreds of tool calls, dozens of process starts and stops, and repeated file reads and writes. Context keeps accumulating, and the sampling phase itself becomes the dominant consumer of compute.
    • Extremely sparse feedback: reward is often given only at the end of the task (success/failure), with no dense signal for intermediate steps, so more trajectories are needed to estimate a usable advantage.
    • Amplified environment instability: terminal environments involve dependency installation, compilation, and test execution. Any single timeout, network hiccup, or image mismatch can invalidate hours of sampling.
    • Failures cannot be amortized: a failed short task costs seconds of compute; a failed long task costs hours of accelerator time, and it often happens after training is already well underway.

    The result: frontier teams can throw thousands of accelerators at sampling scale, while for most teams one sample is a three-hour real attempt, and the trial-and-error budget is squeezed to the point where iteration is nearly impossible. So the question worth asking is not “can we do long-horizon RL,” but how to get long-horizon agentic RL to a usable performance level within a time box of a few days on a few dozen accelerators.

    2. Key Takeaways from a Public Recipe

    A research team recently published a full-parameter reinforcement learning recipe for terminal and coding agents. Its core conclusions can be abstracted into three points:

    1. A small cluster is viable: training used only a few dozen next-generation AI accelerators and took less than five days, which suggests the barrier to long-horizon RL comes mainly from engineering efficiency rather than absolute compute scale.
    2. Capabilities transfer: the recipe reaches roughly 46% Pass@1 (averaged over multiple trials) on terminal benchmarks, in the same range as flagship models of the same period. The gain is not a single-point overfit: improvements were also observed on two software engineering benchmarks.
    3. Cost sits on the Pareto frontier: viewed in two dimensions of average Pass@1 versus average cost per task (log scale on the cost axis), the recipe’s per-task cost is more than an order of magnitude lower than the baseline at the highest reasoning effort.

    One caveat: numbers like these depend heavily on the evaluation harness, the image environment, and the number of samples, so direct cross-method comparison is not rigorous. What actually transfers is the underlying cost-performance Pareto methodology: do not report accuracy alone; treat “the amortized inference and training cost paid per solved task” as a first-class metric.

    3. Where the Cost Goes: Attribute First, Optimize Second

    Before changing the recipe, do a cost attribution pass over the sampling phase and break accelerator hours into observable buckets:

    1. total GPU hours = rollout GPU hours + optimizer step GPU hours
    2. + environment GPU hours (sandbox/compile/test) + failed retry GPU hours

    In practice, sampling and environment time usually dominate for long-horizon tasks. The optimization directions follow directly:

    • Sampling side: raise concurrency, shorten unproductive trajectories, reuse common prefixes;
    • Environment side: pre-warm images, cache dependencies, reuse process pools;
    • Failure side: separate “environment failures” from “policy failures”; the former should not count toward reward and should not trigger a full re-sample.

    4. Six Reusable Engineering Practices

    4.1 Base Model Choice and Full-Parameter Updates

    Starting from a mid-sized base model with manageable inference cost and doing full-parameter RL is usually more cost-effective than parameter-efficient fine-tuning on a very large base: per-task inference is cheaper, sampling throughput is higher, and full-parameter updates genuinely change the model’s tool-use habits. If memory is constrained, validate the reward and data pipeline with a parameter-efficient method first, then switch to full-parameter.

    4.2 Task Curriculum and Difficulty Tiering

    Tier tasks by number of steps, dependency complexity, and whether multi-file edits are required. Early in training, use short-horizon tasks to establish a stable tool-call format, then gradually introduce long-horizon tasks. The point of the curriculum is to keep advantage estimates from being all zeros early on, so that large amounts of sampling are not wasted.

    4.3 Prefer Verifiable Rewards

    The biggest advantage of terminal and coding settings is that reward can be verified programmatically: whether the build passes, whether all tests are green, whether the target artifact exists, whether the command exit code is 0. Replacing model-based scoring with verifiable reward substantially reduces reward noise.

    1. reward:
    2. type: verifiable
    3. checks:
    4. - build_exit_code: 0
    5. - unit_tests_passed: true
    6. - target_artifact_exists: true
    7. partial_credit:
    8. per_test_case: 0.05 # denser signal to mitigate sparse reward
    9. env_error: ignore # environment errors do not count toward reward; retry separately

    4.4 Asynchronous Streaming Sampling and Prefix Reuse

    Sampling long trajectories must be asynchronous: pipeline generation, tool execution, and reward computation instead of waiting on them serially. Reusing the KV cache for common prefixes such as the system prompt and repository context also cuts repeated prefill overhead significantly. For very long trajectories, use “segment-wise expansion plus advantage backpropagation” so that a single trajectory does not have to run to completion in one pass.

    1. # Pseudocode: skeleton of asynchronous streaming sampling
    2. async def rollout_worker(task, policy, env_pool, max_steps):
    3. prefix = build_prefix(task) # common prefix, cacheable
    4. traj = []
    5. async with env_pool.acquire() as env: # reuse pooled environments, avoid repeated init
    6. for step in range(max_steps):
    7. action = await policy.generate(prefix, traj)
    8. result = await env.step(action) # tool execution overlaps with generation
    9. if result.env_error:
    10. return Retryable(result) # retry environment errors separately
    11. traj.append((action, result))
    12. if result.done:
    13. break
    14. return Trajectory(traj, reward=verify(task, env))

    4.5 Sandbox Isolation and Determinism

    Give every rollout its own sandbox, with a pinned image version, pre-installed dependencies, and an explicit network policy, and constrain randomness where necessary. A reproducible environment is a prerequisite for long-horizon RL: otherwise you cannot tell whether a performance swing came from the policy or from the environment.

    4.6 Training Stability

    Common problems with long-sequence RL are entropy collapse and length explosion. Practical measures include length-normalizing advantages, capping the maximum number of steps per trajectory and applying a truncation penalty to over-long trajectories, monitoring entropy and clipping ratios, and using a moderate reference-policy constraint to prevent drift. Put these metrics on a training dashboard, and when something looks wrong, roll back the data mixture first rather than tuning the learning rate.

    5. How to Evaluate and Account for Cost Properly

    • Average over multiple trials: single-run Pass@1 has high variance; use at least 3 to 5 runs.
    • Fix the harness: the tool set, timeouts, images, and maximum step count must be stated in the report.
    • Two cost dimensions: report both amortized training cost and per-task inference cost, and convert self-hosted models using public prices so results stay comparable.
    • Plot the Pareto curve: log-scale per-task cost on the x-axis, Pass@1 on the y-axis, frontier as a dashed line. The value of any method shows up in whether it pushes the frontier outward.

    6. Practical Advice and Common Pitfalls

    For most teams, the pragmatic order is: get verifiable rewards and the sandbox pool working first, then do cost attribution, then validate the pipeline on short-horizon tasks, and finally add a curriculum to scale to long horizons. There are three common pitfalls: treating environment errors as policy failures, which pollutes the reward signal; running sampling and training serially, which keeps accelerator utilization low over the long run; and watching accuracy without watching cost, which ends in a method that cannot be deployed in production.

    At the infrastructure level, this kind of work usually needs only a combination of general-purpose capabilities: a container platform to host the sandbox pool and elastic concurrency, object storage for trajectories and image artifacts, a message queue to decouple sampling from training, and logging plus monitoring and alerting for cost attribution and anomaly detection. Baidu AI Cloud offers corresponding capabilities in these general categories and can serve as a reference when choosing a foundation for your own agentic RL pipeline.

    The bottom line: competition in long-horizon agentic RL has shifted from “piling up accelerators” to “useful information per accelerator hour.” Make rewards verifiable, make sampling asynchronous and streaming, and make cost accountable, and a small cluster can get close to the frontier.