Step-Level Credit Assignment in Long-Horizon Agent Training

    Long-horizon agent tasks involve dozens of sequential decisions with sparse, outcome-only rewards, making it hard to identify which step caused success or failure. This article explains why outcome-based rewards produce coarse credit assignment, why naive per-step scoring is impractical, and presents feasible technical routes—including learned process rewards, Monte Carlo value estimation, and counterfactual branch evaluation—along with code examples, engineering practices, evaluation metrics, and a recommended rollout plan for teams training long-horizon agents.

    1. Why Long-Horizon Tasks Are Hard to Train

    Long-horizon agent tasks are scenarios where a model must make dozens of consecutive decisions to reach a goal—for example, reading a code repository, locating a defect, modifying the implementation, running tests, and iterating based on feedback. These tasks typically share two characteristics. First, there are many intermediate actions, and the impact of a single interaction often only becomes visible much later. Second, rewards are sparse: the environment usually only returns a success or failure signal at the end of the task.

    Sparse rewards are not the problem in themselves. The real difficulty is this: when the final result is zero, the training algorithm cannot tell which step went wrong and which steps were done well.

    2. The Credit Assignment Defect of Outcome Rewards

    Credit assignment refers to the process of distributing the final return appropriately across individual decisions. Consider a trajectory of 80 steps: the first 78 steps of localization and analysis are all accurate, but at step 79 the model mistypes a variable name while editing code, and at step 80 the test fails, returning a reward of 0.

    In policy gradient methods that rely solely on the whole-trajectory outcome, all 80 steps share the same negative advantage signal. The valuable exploration in the first 78 steps gets its probability suppressed along with everything else. Over time, three consequences accumulate:

    1. Useful exploration is suppressed. The model tends to try less and modify less, preferring caution over risk.
    2. The training signal is noisy. The same good behavior may receive negative feedback due to an accidental mistake later in the trajectory.
    3. Ineffective interactions increase. To avoid failure risk, the model repeatedly re-checks its work, driving token consumption up.

    These phenomena show that the problem is not that outcome rewards are “wrong,” but that their granularity is too coarse.

    3. Why Not Simply Score Every Step

    A natural idea is to assign an immediate score to each step. In practice, however, several difficulties arise.

    • Step quality is hard to define. A search that looks correct may contribute nothing to later localization.
    • Manual annotation is expensive. Every step of a long-horizon task requires judgment from a domain expert, which does not scale.
    • Automatic scorers are biased. If the scoring model has systematic errors, the policy will learn to please the scorer rather than actually complete the task—the well-known reward hacking problem.

    Therefore, per-step scoring should not be treated as a one-shot labeling project. A more feasible approach is to proceed in layers: first use outcome signals to keep the training direction correct, then gradually supplement step-level information through verifiable intermediate checkpoints, local evaluations, and counterfactual estimation.

    4. Feasible Technical Routes

    4.1 Learned Process Scoring

    Train a process reward model that predicts, for each intermediate state, the probability of reaching the goal. Its advantage is low inference overhead. Its drawbacks are the need for large amounts of labeled trajectories and the risk that the policy exploits the scorer itself.

    4.2 Monte Carlo Value Estimation

    At a given state, run the current policy from that state to task completion multiple times, and use the success rate to estimate the state’s value. This approach requires no additional model and produces interpretable results, at the cost of heavy sampling overhead.

    4.3 Counterfactual Branch Evaluation

    The core idea of counterfactual branch evaluation is: keep the context before step k unchanged, vary only the subsequent sampling, and compare the success rates from that step onward. If the same policy achieves a significantly higher success rate from step k than the baseline, the decision at that step was likely of high quality; otherwise, that step may have introduced a problem.

    1. def estimate_state_value(snapshot, policy, env, n_branches=16):
    2. """Sample multiple rollouts from the same snapshot to estimate the state's success rate."""
    3. successes = 0
    4. for _ in range(n_branches):
    5. state = env.restore(snapshot) # Restore the identical environment state
    6. trajectory = policy.rollout(state) # Independently sample subsequent actions
    7. successes += int(env.is_success(trajectory))
    8. return successes / n_branches

    Two points deserve attention. First, the number of samples determines estimation accuracy. With a success rate of 0.5, 16 branches yield a standard error of about 0.125, which can only distinguish states with fairly large differences. Second, environment snapshots must be reliable; otherwise, unintended differences leak in between branches.

    Step advantage can be defined as the difference between adjacent state values:

    Ak = V(s_k) - V(s{k-1})

    where V denotes the state value estimate. A positive A_k means step k raised the success probability; a negative value means it lowered it.

    5. Mapping Step Signals into Training

    Once step-level advantages are obtained, they need to be assigned to the corresponding tokens. The following example code shows the basic mapping:

    1. import numpy as np
    2. def assign_token_advantages(num_tokens, steps, step_advantages):
    3. token_adv = np.zeros(num_tokens, dtype=np.float32)
    4. for step, adv in zip(steps, step_advantages):
    5. token_adv[step.token_start:step.token_end] = adv
    6. return token_adv

    In practice, step advantages are often combined with group normalization to prevent scale differences across tasks from distorting training.

    6. Engineering Practices

    1. Branch only at critical nodes. Code edits, test executions, and key judgment points carry the most information; there is no need to branch at every step.
    2. Control snapshot costs. If environment restoration depends on full replay, costs grow quickly—prefer incrementally saved states.
    3. Parallelize sampling. Branches are independent of one another and suit distributed execution, but ensure isolation to avoid shared files or network state.
    4. Set budget caps. Limit the maximum number of branches and interaction rounds per trajectory to prevent evaluation costs from spiraling.
    5. Validate regularly on held-out tasks. If step scores improve on training tasks but remain flat on held-out tasks, watch out for scorer overfitting.

    Beyond task success rate, it is advisable to track the following metrics:

    • Average number of interaction rounds and token consumption, to measure efficiency;
    • Effective edit rate, i.e., the proportion of edits that pass tests;
    • Success rates stratified by task difficulty, to avoid improving only on easy tasks;
    • The distribution of step advantages, to judge whether scoring is overly concentrated or dispersed.

    8. Practical Recommendations

    Teams training long-horizon agents can proceed in the following order: first establish a baseline with outcome rewards; then run counterfactual branching on sampled failure trajectories to identify frequently occurring critical steps; next, train a lightweight scorer on those steps and calibrate it against Monte Carlo estimates. The entire process should remain reproducible—record the sampling settings and evaluation results for every change.