Long-Horizon RL for LLMs: Adaptive Optimization (SAO) for Coding and Cybersecurity Agents

    This article examines why long-horizon tasks have become a critical testbed for large language model (LLM) capabilities, and why traditional reinforcement learning (RL) methods struggle with sparse rewards and global gradient penalties in such settings. It introduces Adaptive Optimization (SAO), an approach inspired by AlphaZero-style self-play and Monte Carlo Tree Search, which decomposes long trajectories into local subproblems and estimates step-level value through local success rates. The article explains the method with pseudocode, reviews reported gains on DeepSWE, CyberGym, and Agents Last Exam, and discusses practical challenges such as environment cloning cost, compatibility with PPO/GRPO-style frameworks, and hyperparameter tuning.

    1. Background: Long-Horizon Tasks as a Testbed for LLM Capability

    Competition among large models has shifted from short question answering to complex multi-step tasks. Real-world scenarios such as software development and cybersecurity often require a model to reason continuously, call tools, and revise strategies across dozens of interaction rounds. In advanced software engineering benchmarks, such as commonly used DeepSWE-style tasks, a model must understand requirements, locate code defects, generate patches, and run tests to verify them. The entire process may involve 30 to 80 interaction rounds. Similarly, cybersecurity evaluations such as CyberGym-like environments require the model to simulate penetration testing, vulnerability analysis, and defense strategy formulation. Each step depends on previous results, and accumulated errors can cause the final objective to fail.

    Traditional evaluation metrics, such as single-step accuracy, struggle to reflect this long-horizon decision-making ability. The industry has begun to use “task success rate” as a core metric: the probability that a model ultimately achieves the goal across a complete trajectory. Public data shows that a new generation of large models improved from 62.7 to 66.9 on DeepSWE, from 83.3 to 84.5 on CyberGym, and from 25.7 to 28.5 on another general agent benchmark, Agents Last Exam. Behind these numbers lies a deeper shift in reinforcement learning (RL) training paradigms.

    2. Critical Limitations of Traditional RL in Long-Horizon Training

    2.1 Sparse Rewards and Global Gradient Penalties

    In long-horizon reinforcement learning, the most commonly used algorithms, such as PPO (Proximal Policy Optimization) or GRPO (Group Relative Policy Optimization), often provide reward signals only at the end of a trajectory: 1 for success and 0 for failure. Suppose a task contains 80 interaction rounds, and the model makes a key incorrect decision at step 77, causing all subsequent actions to lead toward failure. When updating the policy, traditional algorithms treat all tokens in the entire trajectory, from step 1 to step 80, as negative samples and apply penalty gradients to every action.

    This one-size-fits-all penalty has serious problems. In the first 77 steps, most of the model’s decisions may have been correct, or at least locally reasonable, but the task ultimately failed because of an early deviation or an environmental surprise. The algorithm nonetheless suppresses all steps indiscriminately, making the model extremely conservative. It tends to choose “safe but inefficient” actions and avoid any exploration that might introduce risk, ultimately making little progress on complex tasks.

    2.2 A Vicious Cycle of Training Efficiency and Token Consumption

    Worse still, long-trajectory training requires storing and computing probability ratios and advantage functions for every step. Memory usage and computation grow linearly with trajectory length. When the model is forced to repeatedly adjust its strategy within 80 steps, gradient variance increases, and more sampling batches are needed for convergence. In practice, this leads to extremely high token consumption and multiplied training costs, while model capability may fall into a trap of becoming worse with more training, because the penalty signal is too coarse for the model to distinguish which step caused the failure.

    3. Adaptive Optimization (SAO): Borrowing AlphaZero’s Self-Play Idea

    3.1 Core Idea: Decomposing Long Trajectories into Local Strong Solutions

    Much of AlphaZero’s success in Go comes from combining Monte Carlo Tree Search (MCTS) with neural network policies. Given the current board position, it can simulate multiple future game lines and evaluate the long-term value of different moves. Crucially, it does not need to perform global gradient updates over the entire game. Instead, it focuses on subproblems around the current position.

    Adaptive Optimization (SAO) borrows this idea. For a complete trajectory of length N, at a given time step t, for example step 77, the model does not evaluate whether the entire trajectory succeeded. Instead, it preserves the context and environment of the first t-1 steps, meaning the “board position,” and then clones multiple virtual environment copies. Each copy starts from step t, and the model independently explores subsequent actions. In this way, an 80-step task is converted into multiple short tasks that start from step t. Each short task may involve only 3 to 50 steps, and the reward signal becomes denser and clearer.

    3.2 How to Identify a “Good Move”: Based on Local Success Rate

    The key question is how to determine whether the action at step t is good or bad. SAO uses the following method: starting from step t, the same model, maintaining the same capability level, performs multiple independent explorations, and the success rates of these exploration tasks are counted. If the success rate starting from step 78 is significantly higher than the success rate starting from step 77, then the action at step 77 was actually a “good move” because it created a more favorable subsequent state. Conversely, if the success rate decreases, the action needs adjustment.

    This is similar to solving life-and-death problems in Go. The board position after the first 77 moves is kept unchanged, and from move 78 onward, all possible responses are simulated to see whether the opponent’s group can ultimately be captured. If victory is possible regardless of the response, then move 78 is a good move.

    3.3 Training Optimization: Local Value Instead of Global Win/Loss

    Based on the local success rates above, SAO constructs a finer-grained reward signal. During training, the model is no longer required to score an entire trajectory. Instead, it gradually learns the value function of each state. A specific implementation can follow the pseudocode below:

    1. def train_step(env, policy, value_net, trajectory):
    2. # Preserve the environment state after the first t steps
    3. for t in range(len(trajectory)-1):
    4. clone_state = env.clone_state()
    5. # Starting from step t+1, explore K times with the current policy
    6. success_rates = []
    7. for _ in range(K):
    8. success = rollout(clone_state, policy, max_steps=remaining_steps)
    9. success_rates.append(success)
    10. local_reward = mean(success_rates)
    11. # Update the value network so that V(s_t) approximates local_reward
    12. value_loss = MSE(value_net(s_t), local_reward)
    13. # The policy gradient uses the advantage function A_t = local_reward - V(s_t)
    14. policy_loss = -log_prob(a_t) * A_t.detach()
    15. # Backpropagate, but update only parameters relevant to step t

    Under this mechanism, the model can identify key turning points in a trajectory and apply more precise gradients to them. If early steps are indeed effective, the value network will assign them higher predictions and avoid incorrect penalties.

    4. Results: Explicit Gains in Coding and Cybersecurity

    4.1 Coding: From “Can Write” to “Can Debug”

    In DeepSWE-style benchmarks, tasks usually contain multiple subgoals: understanding repository structure, locating defects, generating patches, and running tests. Traditional RL models often fail in the first few steps because of premature decisions. With SAO, the model can maintain its state more stably between step 30 and step 50, because it learns to evaluate whether the current modification brings the code closer to passing tests. For example, in a bug-fixing task, the model generates an incomplete patch at step 20. Traditional methods would penalize all tokens in that patch because the final test fails. SAO, however, detects that starting from step 21, given this patch, the model has a 35% probability of succeeding by adjusting variable names. If a different patch is used directly from step 20, the success rate is only 20%. SAO therefore judges step 20 as a “good attempt” and encourages the model to continue exploring similar patterns.

    4.2 Cybersecurity: From “Script Invocation” to “Strategy Planning”

    In cybersecurity evaluations, the model needs to scan ports, identify vulnerable services, and try specific attack payloads like a real attacker. Such tasks have many steps and contain significant noise. The target system may return messages such as “404” or “timeout,” and the model must distinguish whether these are real responses or traps. SAO’s local exploration mechanism allows the model, when encountering a suspected trap, to quickly simulate multiple subsequent operations, such as switching to another port or adjusting URL encoding, to judge the value of the current action. In the CyberGym environment, the model attempts a login brute-force attack at step 60. Traditional RL penalizes this operation because the account is subsequently locked. SAO finds that starting from step 61, if a proxy is used to reconnect, the success rate is as high as 80%, and therefore identifies the attempt at step 60 as necessary reconnaissance. This capability raises the cybersecurity task success rate from 83.3 to 84.5. Although the absolute increase is modest, it is significant progress in a high-intensity adversarial environment.

    4.3 Generalization and Robustness: Gains on Agent Benchmarks

    In more general agent evaluations such as Agents Last Exam, task types cover search, arithmetic, tool invocation, and multi-turn dialogue. SAO models handle scenarios in which one wrong step can still be recovered. For example, when invoking a calculator tool, the model first enters “sqrt(-1)” and receives an error. Traditional methods penalize that input, causing the model to avoid complex-number operations. SAO preserves the state after that input and tries “abs(-1)” to obtain a correct result. The model thus learns that the “sqrt” function has limitations, but absolute value calculation is feasible. This helps the model learn to use error information for correction, raising the overall score from 25.7 to 28.5, a 10.9% increase.

    5. Key Practical Challenges and Directions

    5.1 Cloning Cost and Memory Management

    Cloning the environment state at each step and executing K rollouts requires considerable compute. In engineering practice, the following optimizations can be used:

    • Key-step sampling: Instead of cloning at every step, select high-impact steps based on uncertainty in the value network or action probability entropy, such as points where action probabilities change sharply.
    • Shared exploration pool: Rollouts from multiple steps can reuse the same batch of parallel environments, using vectorization to reduce repeated environment initialization.

    5.2 Compatibility with Existing RL Frameworks

    SAO can be used as a reward shaping mechanism on top of PPO or GRPO without changing the underlying optimizer. It only requires computing an additional local value function before each policy update. In practice, many mainstream reinforcement learning libraries support custom reward functions, so developers can easily implement the pseudocode above.

    5.3 Hyperparameter Tuning: The Value of K and Temperature

    The number of exploration runs K is a core hyperparameter. If K is too small, the success-rate estimate has high variance. If K is too large, computation increases. Experiments show that K=8 achieves results close to K=16 while halving computation. In addition, the policy used during exploration should maintain the same randomness as during training, namely the temperature parameter; otherwise, it may overfit to a deterministic policy.

    6. Future Outlook: From Automation to Adaptivity

    SAO essentially transforms the problem of trajectory-level credit assignment into state-level value estimation. This is closer to how humans solve complex problems: we do not reject every step in a process because the final outcome failed. Instead, we review how much each step contributed to the result. As the reasoning capabilities of large models improve, SAO may extend to broader domains, such as robot control for long-horizon manipulation tasks and scientific experiments involving multi-step hypothesis validation.

    At the same time, the emergence of cybersecurity capabilities raises a further question: when a model can autonomously evaluate each attack action, can it also dynamically adjust defense strategies based on environmental feedback? In the future, SAO-based adversarial training may become a foundation for large-model safety, allowing models to learn to identify malicious instructions and vulnerability exploitation in virtual attack-defense games, thereby building more reliable agents.

    In summary, Adaptive Optimization is not a simple algorithmic patch but a shift in the reinforcement learning paradigm, from outcome-oriented to process-oriented. It enables large models to stop being overly cautious in long-horizon tasks, to dare to try and correct errors, and ultimately to unlock greater potential in complex real-world applications.