Long-Horizon Agent RL on 100 GPUs in Five Days
This article explains how to run full-parameter reinforcement learning for long-horizon agents on a hundred-GPU cluster within days. It covers why long-horizon agent training is expensive and unstable, then breaks the approach into three executable parts: difficulty-balanced task environments, an RL recipe tailored to long, stale, and low-precision rollouts, and a shared harness for both training and evaluation. It also outlines cluster resource orchestration, cost accounting, evaluation metrics, and practical deployment recommendations. Readers will learn how to keep reward signals reliable, tolerate distribution shift during training, and compare performance against cost on a Pareto frontier.
1. Why Long-Horizon Agent Training Is Expensive and Hard
Over the past year, terminal-operation and software-engineering agents have moved quickly from demos into production. Unlike single-turn question answering, these agents must maintain a goal across dozens or even hundreds of interactions: reading code, editing files, running tests, inspecting errors, and fixing them. Once the task horizon grows, reinforcement learning (RL) training runs into three difficulties at the same time.
The first is sparse and delayed signals. Whether a task succeeds is often revealed only at the end, leaving dozens of intermediate steps without a clear reward. Credit assignment becomes extremely difficult.
The second is stale and expensive rollouts. Sampling a single long task can take minutes to tens of minutes. Under asynchronous parallelism, the samples used for an update may come from a behavior policy that is several parameter versions old, pushing the importance sampling ratio away from 1 and destabilizing training.
The third is the tension between precision and throughput. Low-precision inference is commonly used to raise sampling throughput, but the distribution gap between low-precision rollouts and a higher-precision training policy amplifies the staleness problem.
So the core question for the industry is not whether training is possible, but: under limited compute, how do you extract maximum value from every rollout while pushing per-task inference cost into a usable range?
2. Overall Approach: Breaking the Frontier into Three Executable Pieces
One approach that has repeatedly proven effective is to start from an existing mid-size “lightning-class” base model and run full-parameter RL on it, rather than pretraining from scratch. The key engineering judgments come down to three points:
- Environment filtering before algorithm tuning: match each task to a suitable difficulty so reward signals stay reliable and discriminative;
- A custom RL recipe for long, stale, and low-precision rollouts: make training tolerant of distribution shift;
- One shared programming harness for training and evaluation: eliminate the mismatch between “behavior during training” and “behavior during evaluation.”
Each point is expanded below.
3. Point One: Difficulty Balancing for Agent RL Environments
The environment is the fuel for long-horizon RL. A common mistake is to pile up large numbers of tasks, only to find that most are either solved instantly or fail completely, leaving almost no information in the gradients. A more reliable approach is to build a difficulty-tiered task pool:
- Solvability range control: prioritize tasks whose pass rate under the current policy sits in a middle band (for example, neither close to 0 nor close to 1), keeping the variance of the advantage function manageable;
- Verifiability first: rewards should come from automatically checkable outcomes, such as whether unit tests pass, command exit codes, or file-state assertions, reducing noise from human or model review;
- De-leaking and de-memorization: rotate tasks regularly and remove samples highly similar to the training set so the agent cannot “memorize the answers”;
- Stratified sampling: bucket tasks by repository size, dependency complexity, and number of interaction turns required, keeping the difficulty distribution stable within each batch.
The filtering logic can be sketched as:
# Pseudocode: difficulty balancing by current-policy pass ratedef select_tasks(pool, policy, k=8, low=0.1, high=0.9):kept = []for task in pool:passes = sum(run(policy, task) for _ in range(k))rate = passes / kif low <= rate <= high: # mid-difficulty tasks carry the most informationkept.append((task, rate))# Stratified sampling so no single difficulty bucket dominates the batchreturn stratified_sample(kept, per_bucket=32)
Engineering also requires environment isolation and replayability: each task runs in its own container with fixed filesystem, network, and dependency versions, and failure scenes can be fully replayed. Otherwise reward noise will drown out the training signal.
4. Point Two: An RL Recipe for Long, Stale, and Low-Precision Rollouts
When rollouts diverge from the training policy, naive policy gradients blow up quickly. A combination that is common and effective in practice includes:
- Clipped importance sampling: clip the policy ratio above and below to limit the magnitude of each update;
- Token-level rather than sequence-level importance correction: in long tasks, sequence-level correction lets individual tokens dominate the gradient; token-level is more stable;
- Asynchronous sampling with version constraints: limit sample “age,” for example accepting only trajectories produced no more than N parameter versions ago;
- Low-precision consistency handling: when sampling uses low precision and training uses higher precision, recompute logits or probabilities under a unified convention to avoid a systematic bias in the ratio;
- Length and entropy regularization: apply a length penalty or segmented rewards to overly long trajectories, and constrain entropy gently to prevent premature convergence to a single pattern.
A simplified update sketch:
# Pseudocode: stale samples + clipped importance samplingfor batch in async_stream(max_age=N):ratio = exp(logp_train(batch) - logp_rollout(batch)) # token levelratio = clip(ratio, 1 - eps, 1 + eps)loss = -min(ratio * batch.adv, clip(ratio, 1-eps, 1+eps) * batch.adv)loss = loss + beta * length_penalty(batch) - gamma * entropy(batch)loss.backward(); opt.step()
In practice, reward shaping matters just as much: supplementing the sparse terminal reward of “tests pass” with intermediate signals such as successful compilation, passing static checks, and satisfied key assertions can significantly reduce the number of steps needed to reach the goal.
5. Point Three: One Harness for Training and Evaluation
The harness (the agent runtime framework) determines what the model “sees” and “can do.” If training uses a simplified toolset and evaluation switches to another, performance is badly distorted. Sharing one harness yields three benefits:
- Consistent conventions: tool signatures, error-message formats, and context truncation policies are identical;
- Reproducibility: the same task behaves consistently across machines, making regression checks easier;
- A closed optimization loop: harness improvements (better error summaries, clearer directory views) immediately benefit both training and evaluation.
A minimal toolset typically includes reading files, writing files, listing directories, executing commands, and searching. The key is structuring returned content and controlling its budget, for example truncating long output by keeping the head and tail:
def truncate(text, head=4000, tail=2000):if len(text) <= head + tail: return textreturn text[:head] + "\n...[truncated]...\n" + text[-tail:]
6. Compute and Cost: The Reality of a Hundred-GPU Cluster
Completing one full-parameter RL run on hundreds of accelerators over several days requires careful resource orchestration:
- Decouple sampling from training: scale the sampling cluster by task concurrency while the training side consumes samples on the gradient-synchronization schedule;
- Checkpoints and resume-from-failure: long jobs must support minute-level recovery so a single failure does not cost hours;
- Observability: turn reward curves, trajectory length, pass rate, and ratio distributions into a monitoring and alerting dashboard that halts training automatically on anomalies;
- Unified cost accounting: self-hosted deployments should be converted at equivalent public prices so they can be compared with external inference services on the same “performance–cost” chart.
Evaluation should report both Pass@1 (averaged over multiple trials) and average cost per task, and plot the Pareto frontier on log axes. Only then can you tell whether the conclusion “cheaper and no worse” actually holds.
7. Transferability and Deployment Recommendations
The gains from long-horizon RL usually extend beyond a single benchmark. The “read–edit–verify” loop learned on terminal tasks transfers to software-engineering tasks such as defect fixing and patch generation. For deployment:
- Validate the harness and reward pipeline on a small task pool first, then scale up;
- Make difficulty balancing an automated pipeline that refreshes the task pool weekly;
- Run a small grid search over staleness limits, clipping coefficients, and length penalties rather than blindly increasing batch size;
- Use a container platform for environment isolation, object storage for trajectories and checkpoints, and logging plus monitoring and alerting for training observability;
- When serving externally, combine elastic containers with a message queue for task queuing and concurrency control to keep per-task cost stable.
8. Conclusion
The focus of competition in long-horizon agent RL is shifting from “who has more GPUs” to “whose environments are cleaner, whose recipe is more stable, and whose harness is more unified.” Get these three things right, and a hundred-GPU cluster approaching the performance–cost frontier within days is an entirely achievable engineering goal. Unifying the conventions of training and evaluation, and unifying how cost is accounted for, is the prerequisite for making that conclusion credible.
