Long-Horizon Agent RL: A Low-Cost Training Guide
This article breaks down why reinforcement learning for long-horizon agents is expensive and how small teams can train terminal and coding agents on a limited budget. It covers the four cost drivers, five key recipe decisions (base model choice, full-parameter training, verifiable rewards, curriculum design, and sampling), stability engineering practices, and a three-dimension evaluation approach, ending with a practical action checklist for teams with limited compute.
1. Why Long-Horizon Agents Are Expensive to Train
Long-horizon agents are moving beyond short interactions like “fix a single bug” toward terminal operations and software engineering work that runs for hours. As task chains get longer, the cost structure of reinforcement learning (RL) training changes fundamentally: one training sample is no longer a question-answer exchange of a few dozen turns, but potentially a complete attempt that lasts hours and involves hundreds of tool calls.
This leads to three direct consequences:
- High sample generation cost: A single rollout requires a real execution environment, compilation, testing, and file system operations, with time costs measured in hours.
- Pronounced failure amplification: If any step in the chain fails (a command error, a missing dependency, a test timeout), the entire trajectory is discarded, wasting hours of compute.
- Steep compute barrier: Frontier labs can scale RL across thousands of accelerators, while most teams operate at a scale of only a few dozen cards.
The core question this article addresses is: Within a budget of a few dozen accelerators and a few days, can you train a terminal and coding agent on the same scale as a high-end general-purpose coding tool? Public technical reports suggest the answer is yes: one research team started from a lightweight reasoning base model in the 300B class, applied full-parameter reinforcement learning, and reached a Pass@1 of around 46% on mainstream terminal task benchmarks, on par with top closed-source solutions while achieving significantly lower per-task inference cost. Training used only 64 next-generation accelerators over less than 5 days, and the full recipe was published. The sections below abstract this result into a reusable engineering method.
2. Cost Breakdown: Where the Money Actually Goes
To reduce cost, you first need to understand the cost distribution. The total overhead of long-horizon agent RL breaks down into four parts:
- Environment execution cost: Creating containers/sandboxes, installing dependencies, compiling, and running tests.
- Inference generation cost: The policy model generates actions at each turn, with repeated prefill over long contexts.
- Training update cost: Forward passes, backward passes, and optimizer state communication during full-parameter updates.
- Wasted sample cost: Failed trajectories, duplicate trajectories, and overly long non-converging trajectories.
In practice, items 1 and 4 account for the largest share in long-horizon tasks and are the easiest to compress with engineering effort. The recommended optimization order is: first throttle data and environment, then purify the sampling strategy, and only then squeeze parallelism and memory.
3. Training Recipe Design: Five Key Decisions
3.1 Base Model: Prefer “Lightweight Reasoning” Over “Largest Dense”
Long-horizon tasks require stable instruction following, tool call formatting, and long-context retention. Choosing a base model with moderate parameter count and high inference efficiency lets you allocate more compute to rollouts rather than parameter updates under the same budget. A common practice is to first measure “format compliance rate” and “tool call success rate” on a small task set before deciding on the investment.
3.2 Full-Parameter Training vs. Parameter-Efficient Fine-Tuning
Parameter-efficient methods (such as low-rank adaptation) save memory but tend to suffer from insufficient capacity on long-horizon tasks with strong distribution shift. Full-parameter RL is more expensive but allows the model to genuinely absorb long-chain feedback. The compromise is: full-parameter updates + stricter sample filtering, trading data quality for training steps.
3.3 Verifiable Rewards: Turning “Right or Wrong” into a Computable Signal
Coding and terminal tasks have a natural advantage: rewards are verifiable through unit test pass/fail, command return codes, and file state differences. A layered reward design is recommended:
r_total = w1 * r_test_pass+ w2 * r_format_valid+ w3 * r_progress- w4 * r_step_penalty- w5 * r_timeout
Here, r_progress mitigates sparse rewards (e.g., “tests going from all failing to partially passing”), while r_step_penalty discourages meaningless long chains that pad step counts.
3.4 Curriculum and Task Tiering
Bucket tasks by chain length: short tasks (≤20 turns), medium tasks (20–60 turns), and long tasks (60+ turns). Early in training, use medium and short tasks to establish a stable policy, then gradually introduce long tasks to avoid a large number of hour-long wasted rollouts early on.
3.5 Sampling and Batching
Use a group sampling + within-group normalization advantage estimation approach: sample multiple trajectories for the same task, compute advantages from within-group relative performance, and reduce sensitivity to the absolute reward scale. At the same time, set dual thresholds for maximum turns and maximum wall-clock time; truncate immediately on timeout and mark the sample as invalid.
4. Stability Engineering: Keeping a 5-Day Run from Crashing
Long training runs fear one thing most: “it crashed on day 3.” Key practices include:
- Environment snapshots and reuse: Pre-build images for each task type with dependencies pre-installed, avoiding repeated installation for every trajectory.
- Trajectory-level caching: Cache identical initial states and identical action prefixes to reduce repeated prefill.
- Layered checkpoints: Save policy and optimizer states at fixed step intervals, supporting minute-level rollback.
- Anomaly circuit breakers: Automatically lower the learning rate or roll back when format compliance or test pass rates decline consecutively.
- Observability: Set up monitoring and alerts for rollout length, truncation rate, invalid sample rate, and per-task duration; stop the loss first, then diagnose when anomalies occur.
A schematic training loop skeleton:
for step in range(total_steps):batch = sample_tasks(step) # curriculum-tiered samplingtrajs = rollout(batch, max_turns=T, # dual-threshold truncationmax_wallclock=H)trajs = filter_invalid(trajs) # deduplicate/remove timeouts/remove format errorsadv = group_normalized_advantage(trajs) # within-group normalized advantageloss = policy_loss(adv) + beta * kl_penaltyloss.backward(); optimizer.step()if metrics_degraded(): rollback_and_adjust()if step % ckpt_every == 0: save_checkpoint()
5. Evaluation and Transfer: Don’t Look at Just One Leaderboard
Evaluation should cover three dimensions:
- In-distribution capability: Pass@1 on terminal task benchmarks, reflecting the policy’s own success rate.
- Near-domain transfer: More software-engineering-oriented benchmarks (such as repository-level bug fixing) to validate long-chain generalization.
- Cost efficiency: Average token consumption, average turns, and average wall-clock time per task, converted into “cost per task.”
Public results show that the improvements from this type of training transfer to multiple software engineering benchmarks, indicating the gains are not leaderboard overfitting but a genuine enhancement of long-horizon execution capability. Engineering-wise, it is recommended to use the “cost-capability” curve as the primary metric rather than a single-point score.
6. Action Checklist for Teams with Limited Compute
- Start with baseline measurement: tally the average turns, failure step distribution, and per-task duration of your existing task set.
- Build an environment pool: containerize, pre-install dependencies, and make state rollback-able; this is the first step to reducing cost.
- Adopt verifiable rewards: prioritize tests and return codes to reduce manual labeling.
- Use curriculum + dual-threshold truncation to push the invalid sample rate into an acceptable range.
- When doing full-parameter training, always pair it with checkpoints and circuit breakers to ensure long-run stability.
- Iterate with cost per task as the core metric rather than chasing a single score.
7. Conclusion
The competition in long-horizon agents is shifting from “who has more cards” to “whose recipe is more efficient.” By solidly handling environment engineering, reward design, curriculum sampling, and stability safeguards, a few dozen accelerators and a few days are enough to train a terminal and coding agent approaching front-line quality. For most teams, this is both a realistic path under compute constraints and the most cost-effective starting point for building in-house agent capabilities; combined with cloud-based general-purpose container platforms, object storage, logging services, and monitoring and alerting, environment reuse and observability can be further standardized into a pipeline.
