Reinforcement Learning for Code Agents: Advantage Estimation Selection and Anti-Cheating Design
This article explores reinforcement learning strategies for code agents, focusing on advantage estimation, verifiable reward construction, and anti-cheating mechanisms. It compares GRPO and PPO+GAE for credit assignment across varying trajectory lengths, details how to build reliable executable environments for verifiable rewards, and outlines a two-stage anti-cheating system to prevent models from exploiting evaluation loopholes. A practical implementation checklist is also provided.
1. Problems and Scope
The training trajectories of code agents differ significantly from those of mathematical reasoning. Multiple samplings of the same task can vary in length from just a few steps to over a hundred. Short failure trajectories contain almost no informational value, whereas long successful trajectories encompass numerous valid decisions. Mixing them within the same group inflates the variance of the training signal.
The success or failure of long trajectories is typically determined by a few critical decisions. Therefore, advantage estimation methods must answer one question: How is the final reward allocated to intermediate decisions?
This article discusses three key aspects: the selection of advantage estimation, the construction of verifiable rewards, and a two-stage anti-cheating mechanism designed to prevent models from gaming the evaluation system. An implementation checklist is provided at the end.
2. Choosing Between GRPO and PPO+GAE
GRPO (Group Relative Policy Optimization) samples G outputs for the same problem, calculates a reward $r_i$ for each output, and then normalizes them within the group to obtain the advantage $A_i = (r_i - mean(r)) / std(r)$. It does not require a value network, saving extra VRAM and training compute, and performs stably on math and short-text tasks.
In-group comparison relies on a premise: the difficulty and rollout methods of samples within the group are similar. This premise frequently fails in code tasks, manifesting in three main ways:
- Length Disparity: Short failure trajectories receive a reward of zero, while long successful ones receive one. After normalization, the advantage primarily reflects whether the trajectory ran to completion, rather than which step made the correct decision.
- Variance Collapse: When all trajectories in a group fail, the standard deviation approaches zero. Normalization will either amplify noise or yield near-zero advantages.
- Length Bias: When rewards correlate with length, the model might learn to write longer outputs or give up prematurely, which is irrelevant to the task itself.
The following code demonstrates the in-group advantage calculation. It requires numpy to run.
import numpy as npdef group_relative_advantage(rewards, eps=1e-6):"""In-group normalized advantage; 'rewards' contains G trajectories for the same prompt."""r = np.asarray(rewards, dtype=np.float32)return (r - r.mean()) / (r.std() + eps)print(group_relative_advantage([0, 1, 0, 0])) # Approx [-0.58, 1.73, -0.58, -0.58]print(group_relative_advantage([0, 0, 0, 0])) # All approach 0, no learnable signal
In the first group, the successful trajectory’s advantage is approximately 1.73, while the three failures are around -0.58, showing a clear positive/negative distinction. In the second group, all fail, leaving only eps in the standard deviation calculation. All advantages approach zero, and the training signal vanishes.
PPO combined with a value network (Critic) takes a different approach. The value network learns the expected return $V(s)$ for each state, and the advantage is accumulated from Temporal Difference (TD) errors, independent of in-group comparisons. The Generalized Advantage Estimation (GAE) is defined as follows:
- TD Error: $\deltat = r_t + \gamma \cdot V(s{t+1}) - V(s_t)$
- Generalized Advantage: $At = \Sigma_l (\gamma\lambda)^l \cdot \delta{t+l}$
Here, $\gamma$ is the discount factor, and $\lambda$ controls the bias-variance tradeoff. A larger $\lambda$ increases variance and reduces bias; a smaller $\lambda$ increases bias and reduces variance.
In code agents, the state $s_t$ can be constructed by concatenating the current code, recent test outputs, and historical actions. The terminal reward is usually the only non-zero signal, with intermediate immediate rewards set to zero. In this case, GAE primarily relies on the value network to propagate the terminal signal back to preceding steps. Therefore, the fitting quality of the value network directly determines the reliability of the advantage.
Below is the GAE implementation. The value after the terminal step is treated as zero, and no extra dependencies are required to run it.
def compute_gae(rewards, values, gamma=0.99, lam=0.95):"""Both 'rewards' and 'values' have length T; 'values' is the value estimate at each step. Value after terminal is treated as 0."""T = len(rewards)adv = [0.0] * Tlast = 0.0for t in reversed(range(T)):next_v = values[t + 1] if t + 1 < T else 0.0delta = rewards[t] + gamma * next_v - values[t]last = delta + gamma * lam * lastadv[t] = lastreturns = [a + v for a, v in zip(adv, values)]return adv, returnsif __name__ == "__main__":adv, ret = compute_gae([0, 0, 0, 1], [0.5, 0.5, 0.5, 0.5], gamma=1.0, lam=1.0)print(adv) # [0.5, 0.5, 0.5, 0.5]print(ret) # [1.0, 1.0, 1.0, 1.0]
When both $\gamma$ and $\lambda$ are set to 1, the advantage at each step equals the return minus the value estimate, and the example output can be verified manually.
The selection comparison is as follows.
| Dimension | GRPO | PPO + GAE |
|---|---|---|
| Value Network | Not required | Required; adds extra parameters and training process |
| VRAM & Compute Cost | Lower | Higher |
| Long-horizon Credit Assignment | Uniform scoring for the entire trajectory | Step-by-step propagation, finer granularity |
| Variance Collapse Risk | Fails easily on all-failure groups | Depends on value fitting; high bias if fitting is poor |
| Hyperparameter Sensitivity | Lower | Higher; involves learning rate, clipping range, value loss weight, and $\lambda$ |
| Code Task Recommendation | Preferred when trajectory lengths are similar and success rate is moderate | Used when trajectories are long and intermediate decisions have high impact |
The recommendation is to establish a baseline with GRPO first. If training stalls on all-failure samples, or if the advantages of long and short trajectories become significantly distorted, introduce a value network. Before doing so, check on a small-scale task whether the Critic can fit the returns.
3. Verifiable Rewards in Executable Environments
The source of verifiable rewards is an executable environment. A common practice is to apply the agent-generated patch to a repository copy, run specified tests in a sandbox, and use whether the tests pass or the pass rate as the reward.
When constructing this, pay attention to the following points:
- Execution Isolation: Use an independent container for each run, set limits for timeout, memory, and CPU, and disable network access or only allow whitelisted addresses.
- Reproducible Rewards: Fix dependency versions and base images, and record random seeds. Executing the same patch multiple times should yield consistent results.
- Sparse Rewards: When only terminal signals exist, small process rewards can be added for passing syntax checks or correct formatting. Process rewards should be minimal and should not scale with output length.
- Noise Handling: Flaky tests produce random results. Identify flaky tests first, isolate them or confirm via repeated execution, before including them in the reward calculation.
- Reward-Length Decoupling: Do not directly add or subtract points based on output length.
The checklist is as follows:
- Each task has a reproducible execution environment image
- The sandbox has timeout and resource limits configured
- Repeated execution of the same patch yields consistent results
- Flaky tests have been flagged and excluded from reward calculation
- The reward function does not contain length terms
4. A Two-Stage Anti-Cheating System
Models will learn to exploit loopholes in evaluation rules. Anti-cheating measures must be designed in two stages: constraints before and during training/evaluation, and audit review after evaluation.
Stage 1: Constraints Before and During Training/Evaluation
- Test files and evaluation scripts must be located outside the agent’s writable scope and mounted as read-only.
- The hidden test set must not be visible to the model; its contents should not be written into prompts or training logs.
- The sandbox should have network access disabled by default, only allowing access to necessary dependency sources.
- The evaluation process and the agent process must be mutually isolated, and evaluation results should be written by an independent service.
Stage 2: Post-Evaluation Audit Review
- Check whether the patch modified test files, configurations, or evaluation scripts. If modifications are found, mark the sample as invalid and log the event.
- Re-verify passed samples using a reserved, independent test set. If the re-verification pass rate is significantly lower than the in-training test pass rate, manual review is required.
- Sample and read the trajectories of passed samples to check for hardcoded branches targeting specific inputs or logic irrelevant to the task requirements.
