Skip to content

5.4 Advantage Estimation and Reward Modeling

Section Overview

Core content

  • Two ends of advantage estimation: TD uses one-step information (low variance, biased); MC uses the full trajectory (unbiased, high variance)
  • GAE: a parameter that interpolates between TD and MC via exponential weighting
  • Reward Model: turns pairwise human preferences into a scalar reward via the Bradley-Terry model
  • Two new challenges in LLM alignment: sparse reward (one score for 500 generated tokens) and four models running at once

In the previous section we dissected PPO's clipping trick — replacing an explicit KL constraint with a clipped surrogate objective (review: Constraint Mechanisms for Policy Updates). But there is still one input in we have not unpacked: how is the advantage computed? That is what GAE is for. And in LLM alignment, the environment no longer hands us a reward — where does the reward come from? That is the Reward Model's job.

To make both questions concrete, this section uses one running example: a 5-step episode where only the last step earns reward , all others earn . Think of it as a miniature of an LLM generating 5 tokens and being scored only at the final token:

step immediate reward critic estimate terminal?
000.1no
100.2no
200.3no
300.5no
410.8yes

The next three sections all consume this table: first TD and MC each compute advantages on it, then GAE interpolates between them, and finally we return to the LLM setting and see why sparse reward makes this harder.

Prerequisites

Advantage Estimation: TD vs MC

Recall the definition (review: Section 6.1):

It measures how much better action is at state compared to the policy's average behavior. The difficulty is that is unknown — we cannot read the future, only estimate it.

Chapter 3 already compared the two classical estimators (review: DP/MC/TD). Here we compute both on the 5-step episode and look at the gap.

TD estimator: one-step signal

The TD estimator (review: critic training) uses one-step reward plus the critic's estimate at the next state:

Set and substitute the table row by row:

0
1
2
3
4

At the last step (episode ended). The TD advantage is exactly this column. Its variance is low — only one step of randomness is involved — but it is biased: if the critic's is inaccurate, the error flows directly into through .

MC estimator: full-trajectory return

The MC estimator (review: MC methods) waits until the episode ends, then subtracts from the full return starting at :

Accumulate from the end first ():

subsequent rewards
4
3
2
1
0

Then subtract :

0
1
2
3
4

MC does not depend on the critic — with enough samples, the estimate is unbiased in expectation. But contains all randomness from to the end, so its variance is large; and we must wait until the episode ends, which in LLM settings can mean thousands of steps.

Side by side, the gap is clear:

0
1
2
3
4

Same 5-step episode, yet TD assigns only of advantage to early steps while MC assigns the credit for the final reward gets crushed in the TD view, because the critic has not yet propagated that future reward backward. MC pushes the final reward all the way back to every step, at the cost of high variance and a long wait.

GAE: A Controlled Bias-Variance Tradeoff

GAE (Schulman et al., 2016) introduces a parameter that interpolates between TD and MC via exponential weighting:

where is the TD error. Three limiting cases:

  • : , reduces to one-step TD
  • : , reduces to MC
  • : later are down-weighted by

Computing it via the recursion

In practice we compute GAE backward (because depends on ):

Substitute the 5-step episode, :

4 (terminal)
3
2
1
0

Concrete numbers depend on . Here are four representative values ():

4
3
2
1
0

This table ties the whole section together:

  • The column is the TD estimator (left column of the earlier comparison)
  • The column is the MC estimator (right column of the earlier comparison)
  • sits between: near MC close to the end, increasingly suppressed toward the start by the exponential decay

As grows, the advantage at early steps climbs from toward credit propagates from the final step back to every step, at the cost of rising variance (more distant randomness is included). The PPO default is typically , leaning toward MC: a small bias in exchange for a substantial variance reduction.

Roughly equalsBiasVarianceWhen it tends to work
0.0pure TDhighlowcritic is weak, reward is noisy
0.9TD-leaningmediummedium-lowgeneral-purpose
0.95balancedlowermediumcommon PPO default
0.99MC-leaninglowhighercritic is accurate, fine evaluation
1.0pure MClowesthighshort episodes, plenty of data
python
# ==========================================
# A minimal GAE implementation (from scratch)
# ==========================================
import numpy as np

def compute_gae(rewards, values, dones, gamma=0.99, lam=0.95):
    """
    Compute GAE advantages.

    Args:
        rewards: list/array of r_t
        values: list/array of V(s_t)
        dones: list/array of episode termination flags (1 if done else 0)
        gamma: discount factor
        lam: GAE lambda

    Returns:
        advantages: A_hat_t
        returns: targets for critic training, i.e., advantages + values
    """
    advantages = []
    gae = 0.0

    for t in reversed(range(len(rewards))):
        next_value = 0.0 if (t == len(rewards) - 1) else values[t + 1]
        nonterminal = 1.0 - float(dones[t])

        delta = rewards[t] + gamma * next_value * nonterminal - values[t]
        gae = delta + gamma * lam * nonterminal * gae
        advantages.insert(0, gae)

    advantages = np.array(advantages, dtype=np.float32)
    returns = advantages + np.array(values[: len(rewards)], dtype=np.float32)
    return advantages, returns

# The 5-step episode from the running example
rewards = [0.0, 0.0, 0.0, 0.0, 1.0]
values  = [0.1, 0.2, 0.3, 0.5, 0.8]
dones   = [0,   0,   0,   0,   1  ]

advantages, returns = compute_gae(rewards, values, dones)
print("advantages:", advantages)
print("returns:", returns)

Reward Models

Classic RL environments (CartPole, LunarLander) hand us the reward directly through environment rules — upright gives positive reward, crash gives negative. LLM alignment has no such source: there is no objective answer to "how many points is this poem worth." The Reward Model (RM) is what turns human judgment into a scalar reward.

Subjective alignment vs objective reasoning

LLM alignment has two tracks:

  • Subjective alignment (politeness, safety, helpfulness): no objective ground truth, requires a reward model trained from human preferences
  • Objective reasoning (math, code): verifiable by rules, can use rule-based rewards directly (covered in Chapter 9: RLVR)

This chapter focuses on subjective alignment — the classic PPO-for-LLM use case.

Bradley-Terry model

Humans struggle to assign absolute scores ("I'd give this 87 points") but easily make comparisons ("A is better than B"). The Bradley-Terry model turns pairwise comparisons into absolute scores:

where is the RM's score for response to prompt , and is the sigmoid. The larger the score gap, the closer the probability that the higher-scored response wins.

A minimal training sketch

python
# ==========================================
# Reward model training sketch (simplified)
# ==========================================
def reward_model_loss(rm, prompt, chosen, rejected):
    """
    rm: reward model, maps (prompt, response) -> scalar score
    """
    r_chosen = rm(prompt, chosen)
    r_rejected = rm(prompt, rejected)
    loss = -torch.log(torch.sigmoid(r_chosen - r_rejected))
    return loss.mean()

Three practical pain points

Training a good RM is one of the heaviest parts of RLHF:

  1. Labeling cost: you need thousands of preference comparisons, each requiring trained annotators. OpenAI hired roughly 40 annotators and labeled tens of thousands of preferences for InstructGPT.

  2. Reward hacking: the RM often learns "what looks like a good answer" rather than "what is a good answer." The policy may learn to pad responses (the RM favors length), stack jargon (sounds more authoritative), or use formatting to mask hollow content. Reward climbs steadily while human evaluators see quality drop.

  3. Distribution shift: the RM is trained on responses from an earlier policy. After RL updates, the policy's response distribution drifts, and RM scores on these "new" responses become unreliable — the judge's training set no longer matches deployment.

Sparse Reward and Credit Assignment

An LLM response can be 500 tokens long — from an RL viewpoint, a 500-step sequential decision process. The RM typically produces a single scalar reward at the very end. This is the extreme sparse-reward case:

500 actions, 1 reward signal.

The 5-step running example is exactly this structure in miniature: reward appears only at , the first four steps all earn . Of those four early steps, which ones actually contributed to the final score of 1? This is the credit assignment problem.

Look back at the GAE comparison table with four values. At (pure TD), early-step advantages are just — barely connected to the final reward. At , the advantage at climbs to — the final reward has been propagated all the way back to the start. GAE is PPO's credit-assignment tool: controls how much of the final reward is distributed back to earlier tokens.

Formally, PPO's token-level policy gradient is

Each token's log probability is scaled by its advantage — tokens with high advantage are reinforced, tokens with low advantage are weakened. With a KL penalty against a reference model (to prevent drifting too far), PPO completes a relatively stable token-level credit assignment.

The Full PPO-for-LLM Picture

When PPO is used for LLM alignment, you typically run four models together — an engineering headache and a major resource sink:

Mermaid diagram

Each model's role:

ModelRoleSizeMemory
Actorlanguage model being trained7B-70Blargest
Criticvalue network, estimates response valuesame as Actorlarge
Referencefrozen baseline for KL penaltysame as Actorlarge
Reward Modelscorer trained from preferencesusually smallermedium

Four models in memory at once — that is the engineering weight of RLHF. A 7B model needs at least 4×A100 (80GB); a 70B model may need 16-32×A100. And that is before counting the earlier SFT and RM training stages.

PPO's core machinery is identical in games and in LLM alignment — clipping, GAE, importance sampling. But the LLM setting introduces three extra challenges:

  1. A trained RM is required — games have a built-in reward function, LLMs do not
  2. Sparse reward — 500 steps of generation, one reward signal
  3. Massive resource use — four large models running at once

The RM is the biggest engineering bottleneck: heavy labeling, vulnerable to hacking, and stale after every policy update. A natural question follows: can we skip the RM entirely?

Thought experiment: what happens if the RM is trained "too well" — perfectly separating winners from losers on the training set?

A perfect training-set RM is likely overfit. An overfit RM memorizes surface features of the training data ("any response containing 'glad to help' is good") instead of learning the underlying preference pattern.

Two problems follow:

  1. Reward hacking: the policy quickly discovers the RM's "preference patterns" (e.g., "longer responses score higher") and optimizes for those patterns instead of genuine quality. You see reward climb while human evaluators rate the responses as worse.

  2. Poor generalization: once the policy updates and produces out-of-distribution responses, the overfit RM may score them essentially at random — it has never seen this kind of response before.

This is why RM training must carefully control capacity and regularization — better a slightly "dull" RM than one that is "too clever."

The RM is the heaviest burden in PPO-for-LLM alignment — heavy to label, heavy to host, and risky to trust. Can we skip it? The next chapter gives DPO's answer: Chapter 9: DPO — Bypassing the Reward Model.

现代强化学习实战课程