Efficient Training Practices for Long-Horizon AI Agents: A 300B Recipe on 64 Accelerators
This article breaks down a publicly shared training recipe for long-horizon AI agents, focusing on how to achieve flagship-level terminal and coding performance under a limited compute budget. It explains why long-horizon reinforcement learning is expensive on the training side, identifies four cost bottlenecks, and details six reusable engineering practices covering full-parameter RL, asynchronous rollout pipelines, tiered sampling, process-attributable rewards, memory engineering, and evaluation isolation. It also shows where a 30x per-task cost reduction comes from and offers practical guidance for enterprises building long-horizon agents with small compute budgets.
1. Background: Why Long-Horizon Agents Are Expensive to Train
Long-horizon agents are evolving from short interactions such as “fix a bug” into continuous terminal operations and software engineering work that can last for hours. As task chains grow longer, the sampling cost of reinforcement learning (RL) rises non-linearly: a single training sample may correspond to a complete attempt lasting three hours with hundreds of tool calls. If any intermediate step fails—a mistyped command, environment state drift, a timeout, or context overflow—the entire trajectory is wasted, and the accelerator time already consumed cannot be recovered.
The key tension in long-horizon agent RL is therefore not “whether compute exists,” but “compute efficiency per effective sample.” Frontier labs can scale across thousands of accelerators, but most teams must complete training within a budget of a few dozen accelerators. Using a publicly available training recipe as a guide, this article abstracts transferable engineering methods: with 64 accelerators and a budget of less than five days, a 300B-class terminal and coding agent was trained, reaching a Pass@1 of 46.2% on terminal benchmarks—on par with current mainstream flagship models—while keeping per-task inference cost more than 30x lower than the highest reasoning-effort tier, and transferring the capability to two classes of software engineering benchmarks.
2. Core Takeaway: Pushing the Performance–Cost Frontier Together
The value of this work lies not only in the scores, but in rewriting both the performance and cost coordinates at the same time:
- Performance: Pass@1 on terminal benchmarks matches flagship models (46.2%), showing that a small compute budget does not have to yield a merely “usable but lagging” model.
- Cost: a more than 30x reduction in per-task cost means agents can genuinely enter high-frequency usage scenarios rather than staying at the demo stage.
- Generalization: after transferring terminal capability to software engineering benchmarks (bug-fixing tasks and enterprise-level repository tasks), performance still improves, indicating that a transferable “long-horizon execution policy” was learned rather than benchmark overfitting.
- Reproducibility: the complete recipe is public, including data construction, rollout scheduling, optimizer, and evaluation criteria—the prerequisite for turning a “one-off success” into a “team-replicable capability.”
A methodological premise must be emphasized: the evaluation criteria must be stated clearly. Baseline scores are taken from official public results, while the new model is evaluated in a self-built harness; because the model is deployed by the team itself, cost is converted using the public pricing of the base model. This kind of “same-criteria declaration” is the foundation for credible cross-comparison and the first thing to align when reproducing experiments.
3. Four Cost Black Holes in Long-Horizon RL
3.1 Memory and Scheduling Pressure from Trajectory Length
A single trajectory contains hundreds of tool calls and observations, with a sequence length far exceeding ordinary conversational samples. If all trajectories are packed into a training batch at once, both memory usage and long-tail waiting explode simultaneously.
3.2 Serial Nature of Environment Interaction
Terminal environments are inherently stateful: the previous command changes the file system, and the next command depends on that state. This makes rollouts hard to parallelize fully as pure text generation would allow, and GPUs idle while waiting for the environment to return.
3.3 Sunk Cost of Failed Samples
In long-horizon tasks, failures often occur after dozens of turns. Without distinguishing “early failures” from “late failures,” the training signal is diluted by a large volume of low-value trajectories.
3.4 Underestimated Evaluation Cost
A single complete evaluation on a long-horizon benchmark is itself a small-scale training run: multiple tasks, multiple trials, long timeouts. If evaluation shares the same accelerators as training, the training window is severely squeezed.
4. A Reusable Training Recipe: Six Key Practices
4.1 Start from Full-Parameter Training, Not Lightweight Adaptation
In long-horizon tasks, the policy must simultaneously change reasoning habits, the rhythm of tool use, and error recovery behavior. Lightweight adaptation that tunes only a small number of parameters often changes surface formatting but struggles to shift the long-horizon decision distribution. Full-parameter RL extends the optimization signal across both planning and execution, which is a necessary condition for a capability leap; the cost is higher memory and optimizer-state overhead, so it must be paired with the scheduling designs below.
4.2 Decouple Rollout from Training with an Asynchronous Pipeline
Split “environment interaction” and “parameter updates” into two resource pools: one continuously produces trajectories and writes them to a queue, while the other pulls batches from the queue to update parameters. Key engineering points include:
# Pseudocode: decoupled asynchronous rollout and trainingrollout_pool = EnvironmentPool(size=256) # containerized terminal environmentsbuffer = ReplayBuffer(maxlen=4096) # trajectory bufferdef producer(step):task = sampler.sample_batch(32) # difficulty-stratified samplingtraj = rollout_pool.run(task, max_turns=120, timeout=10800)buffer.add(filter_and_score(traj)) # down-weight early-failure samplesdef trainer(step):batch = buffer.sample(64) # bucket by length to reduce paddingloss = policy_gradient(batch, clip=0.2)optimizer.step(loss)
The key points are: bucket by length to reduce wasted padding; down-weight early-failure trajectories rather than discarding them outright, preserving the “error recovery” signal; and set maximum turn counts and timeout limits to prevent a single trajectory from dragging on indefinitely.
4.3 Tiered Sampling and Curriculum-Style Task Difficulty
Stratify tasks by “turns required, types of tools involved, and whether cross-file reasoning is needed,” and prioritize sampling the medium-difficulty range. All-easy tasks fail to teach long-horizon planning, while all-hard tasks produce large numbers of zero-reward trajectories and waste compute. Curriculum-style progression (short chains first, then long chains) can significantly raise the proportion of effective gradients per unit of compute.
4.4 Reward Design Must Be “Process-Attributable”
When a long-horizon task offers only final success or failure, credit assignment is extremely difficult. A workable approach is to keep outcome reward as the main signal while adding verifiable process signals, such as whether a command executed successfully, whether tests passed, and whether irreversible damage occurred. Note that process rewards must be automatically判定-able—that is, automatically determinable—otherwise they introduce noise and incentivize the policy to game the system.
4.5 Memory Engineering for Full-Parameter Training
With a limited number of accelerators, combine optimizer-state sharding, activation recomputation, gradient accumulation, and mixed precision. In practice, putting “long-sequence samples” into a separate bucket and capping the maximum tokens per batch is more effective than simply shrinking the batch size, because it suppresses both peak memory and long-tail waiting at once.
4.6 Time Isolation Between Evaluation and Training
Place evaluation outside the training window, or run it on an independent small resource pool; use multiple trials averaged (such as 5 runs) to reduce variance, and fix the harness version and timeout settings. Otherwise, “train for 5 days” can easily be squeezed into “train for 3 days” by evaluation.
5. Where the 30x Cost Reduction Comes From
Per-task cost consists of three parts: input tokens, output tokens, and extra calls from failed retries. For long-horizon agents, the main cost is often not a single output length but repeated trial and error. The cost-reduction logic of this recipe can be summarized as:
- A more decisive policy: the trained model reduces unproductive exploration turns, lowering the number of turns needed to complete a task.
- Stronger error recovery: a single failure no longer forces the entire trajectory to restart, reducing repeated consumption.
- No need to max out reasoning effort: once capability is internalized, the highest reasoning tier is no longer required to buy accuracy, directly lowering the per-token price.
- Self-hosted deployment: self-deployment allows cost to be converted using the public pricing of the base model, avoiding high-multiplier inference premiums.
Only when these four factors stack together do you get a result of “matching performance at an order-of-magnitude lower cost.” The direct lesson for engineering teams is: to optimize agent cost, change the policy and scheduling first, rather than switching to a more expensive model tier.
6. Implementation Advice: How Enterprises Can Build Long-Horizon Agents with Small Compute
- Define evaluation criteria first: specify benchmarks, number of trials, timeouts, and harness version before discussing scores.
- Containerize environments: provide an isolated terminal environment for each rollout, with snapshot and fast rollback support to reduce state contamination.
- Stratify sampling: build a task-difficulty labeling system and use the medium-difficulty range to drive curriculum progression.
- Separate training and evaluation pools: avoid resource contention and keep the training window intact.
- Make cost observable: track turns, tokens, and retry counts per task to locate sources of cost anomalies.
- General-purpose cloud resource categories are sufficient: a container platform can host the environment pool, object storage can hold trajectories and checkpoints, a message queue can serve as the rollout buffer, and logging and monitoring with alerting can track long-tail tasks. Baidu AI Cloud can provide corresponding foundational capabilities in these general categories.
7. Limitations and Risks
- Benchmark transferability still needs validation across more scenarios; behavior beyond terminal and repository-level tasks is unknown.
- Poorly designed process rewards may induce “surface compliance” behavior.
- A self-built harness differs from official criteria, so cross-team comparison requires caution.
- Permission boundaries for long-horizon agents must be tightened; it is advisable to restrict network and file system access within isolated environments and retain complete audit logs.
8. Conclusion
The bottleneck of long-horizon agent RL has shifted from “whether the algorithm exists” to “how many effective gradients are produced per unit of compute.” Doing these five things well—asynchronizing rollouts, making tasks tiered and curriculum-based, making rewards process-attributable, refining memory engineering, and isolating evaluation from training in time—can turn a few dozen accelerators and a few days of budget into terminal and coding capability on par with flagship models, while pushing per-task cost down by an order of magnitude. For most teams, this is more realistic than waiting for larger-scale compute.
