Baselines and Variance Reduction

Dive into Deep Learning · §14.8

Baselines and Variance Reduction
zero-mean score identity · reward-to-go · control-variate baselines · advantage & learned V · RLOO & GRPO group normalization

Why Raw Return Weighting Is Too Noisy

Motivation & Mental Model

\hat{u} = \frac{1}{n}\sum_{i=1}^n R(\tau_i) \sum_{t=0}^{T_i-1} \nabla_\theta \log \pi_\theta(a_t^i \mid s_t^i)

  • All-or-nothing weights: Nonnegative returns R(\tau) \in \{0, \gamma^{T-1}\} push wasteful loops inside winning episodes up, while fatal steps into holes get weight 0 and are never pushed down.
  • Control-variate solution: Subtracting b(s_t) pushes above-average actions up and below-average actions down without altering \mathbb{E}[\hat{u}].

The Zero-Mean Score Lemma and Prefix Identity

Why Subtracting a Baseline Is Unbiased

\mathbb{E}_{a \sim \pi_\theta(\cdot \mid s)}\big[\nabla_\theta \log \pi_\theta(a \mid s)\big] = \nabla_\theta \sum_{a \in \mathcal{A}} \pi_\theta(a \mid s) = \mathbf{0}

  • Conditional prefix identity: For any quantity c(s_{0:t}, a_{0:t-1}) determined before a_t is sampled, \mathbb{E}[c\,\nabla_\theta \log \pi_\theta(a_t \mid s_t)] = \mathbf{0}.
  • Admissibility rule: Any prefix quantity may be subtracted without bias; anything depending on a_t or s_{t+1} biases the expectation.

Causality and Reward-to-Go

Dropping Past Rewards via Backward Scan

Dropping the prefix \sum_{t'<t} \gamma^{t'} r_{t'} of R(\tau) (zero expected product with step-t’s score) leaves the reward-to-go:

\hat{G}_t = \sum_{t'=t}^{T-1} \gamma^{t'-t}\,r_{t'} = r_t + \gamma\,\hat{G}_{t+1}

def backward_scan(self, x, factor):
    """y_t = x_t + factor * y_{t+1}, restarted at every episode boundary."""
    y = np.zeros_like(x)
    for ep in self.episodes():
        running = 0.0
        for t in reversed(range(ep.start, ep.stop)):
            running = x[t] + factor * running
            y[t] = running
    return y

def reward_to_go(self, gamma):
    """G_t: the discounted return of the rest of its episode, by one scan."""
    return self.backward_scan(self.rew, gamma)
  • Practical convention vs. exact \gamma^t\hat{G}_t: Most implementations weight step t by \hat{G}_t rather than \gamma^t\hat{G}_t (counting late visits as heavily as early visits, tilting the mean by \approx 8^\circ at our frozen probe).

Baselines as Statistical Control Variates

Minimizing Estimator Variance

In Monte Carlo estimation of \mathbb{E}[X], subtracting a zero-mean correlated variable c\,(Y - \mathbb{E}[Y]) leaves the mean unchanged while reducing variance to a parabola in c:

\textrm{Var}\big(X - c(Y - \mathbb{E}[Y])\big) = \textrm{Var}(X) - 2c\,\textrm{Cov}(X, Y) + c^2\,\textrm{Var}(Y)

  • Optimal coefficient c^* = \textrm{Cov}(X, Y)/\textrm{Var}(Y): Cuts the variance to (1 - \textrm{corr}^2)\,\textrm{Var}(X) (a 5\times reduction when \textrm{corr} = 0.9).
  • Policy-gradient specialization: Setting X = \hat{G}_t\nabla_\theta \log \pi_\theta(a_t \mid s_t) and Y = \nabla_\theta \log \pi_\theta(a_t \mid s_t) (where \mathbb{E}[Y \mid s_t] = \mathbf{0}) yields the state-dependent baseline estimator: \hat{u} = \frac{1}{n}\sum_{i=1}^n \sum_{t=0}^{T_i-1} \big(\hat{G}_t^i - b(s_t^i)\big)\,\nabla_\theta \log \pi_\theta(a_t^i \mid s_t^i)

Visualizing Variance Reduction on a 1-Step Task

Causality and the Variance Parabola

On the 1-step Gaussian problem a \sim \mathcal{N}(\mu, 1) at \mu = 0 with reward R(a) = 0.4 + 2e^{-(a-2)^2/2} (\mathbb{E}[R] = 0.92, exact gradient 0.52), subtracting a constant baseline b shrinks the estimator spread dramatically:

  • Over 4\times variance reduction: Raw R(a)\,a has standard deviation 1.34; subtracting the mean reward b = 0.92 halves the spread to 0.69, and the score-weighted optimum b^* = \mathbb{E}[R(a)a^2]/\mathbb{E}[a^2] = 1.18 leaves only 23\% of the original variance.

State Values and the Advantage Function

Learning a State-Dependent Baseline

A^\pi(s, a) = Q^\pi(s, a) - V^\pi(s), \qquad \mathbb{E}_{a \sim \pi}\big[A^\pi(s, a)\big] = 0

  • Sampled advantage \hat{G}_t - V^{\pi_\theta}(s_t): Subtracting V^{\pi_\theta}(s_t) centers every state around zero—pushing actions with Q^\pi(s_t, a_t) > V^\pi(s_t) up and worse actions down.
  • Online value-table baseline: Maintain \hat{V}(s) updated after each batch via \hat{V}(s_t) \leftarrow \hat{V}(s_t) + \eta_V(\hat{G}_t - \hat{V}(s_t)).

Batch Centering vs. Standard-Deviation Scaling

Separating Baseline Subtraction from Step-Size Rescaling

Practitioners frequently standardize all reward-to-go weights within each batch via \tilde{G}_t^i = (\hat{G}_t^i - \bar{R})/(\sigma + 10^{-8}):

def standardize(x, eps=1e-8):
    """Center a NumPy batch of weights and divide by its standard deviation
    (NumPy's std, which divides by the batch size)."""
    return (x - x.mean()) / (x.std() + eps)
  • Subtracting \bar{R} is a baseline: Shifts relative weights so below-average trajectories receive negative weights (with a small (n-1)/n self-inclusion shrink factor).
  • Dividing by \sigma is an adaptive step-size multiplier: Multiplies the entire batch gradient by 1/\sigma; on FrozenLake where \hat{G}_t \in [0, 1], \sigma \leq 0.5, so dividing by \sigma enlarges SGD steps by \approx 3\times.

Leave-One-Out (RLOO) Eliminates Centering Bias

Exact Unbiased Batch Centering

Because the batch mean \bar{R} = \frac{1}{n}\sum_{j=1}^n R_j includes trajectory i’s own return R_i, plain centering shrinks the expected gradient by (n-1)/n; Leave-One-Out (RLOO) (Kool et al., 2019; Ahmadian et al., 2024) uses the mean of the other n-1 trajectories:

b_i = \frac{1}{n - 1}\sum_{j \neq i} R(\tau_j), \qquad R_i - b_i = \frac{n}{n - 1}\big(R_i - \bar{R}\big)

E[leave-one-out] equals the exact gradient: True
E[centered] equals (n-1)/n of it:           True
  • Exact unbiasedness for any n \geq 2: Since independent trajectories j \neq i do not depend on \tau_i’s actions, \mathbb{E}[b_i \nabla_\theta \log P(\tau_i; \theta)] = \mathbf{0} holds exactly.

Group Relative Policy Optimization (GRPO)

Critic-Free Baselines for Language Models

In LLM post-training, each prompt x has its own difficulty p_x, so GRPO (Shao et al., 2024) samples a group of K responses to prompt x and uses the group’s own mean and spread as the baseline:

\hat{A}_j = \frac{r(x, y_j) - \bar{R}_x}{\sigma_x + 10^{-8}}, \qquad \text{binary rewards } (k \text{ of } K \text{ right}): \quad +\sqrt{\frac{1-\hat{p}}{\hat{p}}} \;\;\text{vs.}\;\; -\sqrt{\frac{\hat{p}}{1-\hat{p}}}

K =  1: success of a sampled response 0.062
K =  2: success of a sampled response 0.500
K =  4: success of a sampled response 0.500
K =  8: success of a sampled response 0.500
K = 32: success of a sampled response 0.500
  • Why K = 1 never learns and K \geq 2 hits the ceiling: At K = 1, r_1 - \bar{R}_x = 0 identically; for any K \geq 2, group centering pushes wrong answers down (-k/K) and right answers up (1 - k/K), reaching the 0.500 ceiling without a value network.

How the Loss Divisor Affects Direction and Scale

Episodes vs. Total Steps vs. Per-Episode Length

When summing weighted scores across episodes of varying lengths T_i (N = \sum_{i=1}^n T_i total steps), four common divisors behave differently:

episode lengths [ 8 20  8 11], successes 3
    episodes: |grad| = 0.868, cos to episodes = 1.000
  own length: |grad| = 0.082, cos to episodes = 0.937
 total steps: |grad| = 0.074, cos to episodes = 1.000
  a constant: |grad| = 0.109, cos to episodes = 1.000
  • Three parallel, one tilted: Dividing by episodes n, total steps N (DAPO), or a fixed constant (Dr. GRPO) produces parallel gradients (cos = 1.000) differing only in scale, whereas dividing each episode by its own length T_i (GRPO) reweights short vs. long episodes and tilts the direction (cos = 0.937).

Benchmarking Six Estimators at a Frozen Policy

Scale, Direction, and Relative Variance

Evaluating 2{,}000 4-episode batches at our frozen probe (J = 0.313, where exact \nabla_\theta J and V^{\pi_\theta} are known via linear solve) compares bias and relative noise \textrm{tr}(\textrm{Cov})/\|\textrm{mean}\|^2:

     lake         return: |mean|/|grad J| = 0.99, cos = 0.998, noise =  13.6
     lake         causal: |mean|/|grad J| = 0.99, cos = 0.998, noise =  13.6
     lake   reward-to-go: |mean|/|grad J| = 1.38, cos = 0.987, noise =  12.4
     lake       centered: |mean|/|grad J| = 1.11, cos = 0.986, noise =   7.6
     lake     normalized: |mean|/|grad J| = 3.28, cos = 0.982, noise =   7.5
     lake value baseline: |mean|/|grad J| = 1.38, cos = 0.990, noise =   5.7
step cost         return: |mean|/|grad J| = 0.98, cos = 0.996, noise =  19.5
step cost         causal: |mean|/|grad J| = 1.00, cos = 0.999, noise =   5.8
step cost   reward-to-go: |mean|/|grad J| = 1.29, cos = 0.989, noise =   5.4
step cost       centered: |mean|/|grad J| = 1.07, cos = 0.985, noise =   5.6
step cost     normalized: |mean|/|grad J| = 2.12, cos = 0.980, noise =   5.8
step cost value baseline: |mean|/|grad J| = 1.28, cos = 0.989, noise =   3.0

Interpreting the Frozen-Policy Variance Table

What Drops Noise and When Causality Helps

  • State value baseline is quietest: Subtracting V^{\pi_\theta}(s_t) more than halves relative noise (from about 12 to under 6) while preserving mean scale (1.38) and direction (cos = 0.990).
  • Centering vs. normalization: Batch centering cuts noise by \approx 40\% with (n-1)/n shrink; dividing by \sigma leaves relative noise unchanged (7.5) while tripling step length (3.28).
  • Dropping past rewards: With a -0.1 per-step charge, causality cuts noise more than 3\times (19.5 \to 5.8).

Disentangling Step Size from Variance in Training

Shared Small Step Size vs. Large Step Size

Comparing all six estimators under plain SGD at \eta = 2 (20 seeds) vs. the three equal-mean estimators at \eta = 16 (100 seeds) exposes the step-size confound:

eta = 2
        return: to 90%: median  63.0 [ 42, 108], never  0, |step| 0.43
  reward-to-go: to 90%: median  51.0 [ 29, 109], never  0, |step| 0.53
      centered: to 90%: median  58.5 [ 39, 119], never  0, |step| 0.32
    normalized: to 90%: median  32.0 [ 15,  85], never  0, |step| 0.93
value baseline: to 90%: median  52.0 [ 38,  97], never  0, |step| 0.37
exact baseline: to 90%: median  50.5 [ 33,  96], never  0, |step| 0.40
eta = 16
  reward-to-go: to 90%: median  35.0 [ 11, 150], never 15, |step| 1.46
value baseline: to 90%: median  26.0 [ 11, 150], never  5, |step| 1.30
exact baseline: to 90%: median  20.5 [ 10,  41], never  0, |step| 1.68
  • At \eta = 2, normalization wins purely by taking 3\times larger steps: Normalization reaches 90\% success in a median of 32.0 updates because its step norm is 0.93 vs. 0.32 for centered and 0.53 for reward-to-go.

Lower Variance Unlocks Larger, Stable Step Sizes

Why the Value Baseline Wins at eta = 16

Holding the expected update vector identical across reward-to-go, value baseline (learned \hat{V}), and exact baseline (V^{\pi_\theta}) at \eta = 16 shows what variance reduction actually buys:

  • Faster convergence without stalling: At \eta = 16, exact baseline reaches 90\% success in a median of about 20 updates with 0/100 stalled runs.
  • Catastrophic stalling without a baseline: reward-to-go fails to reach 90\% in about one run in seven because a noisy large step locks the policy onto a zero-return loop where all future weights are 0.

Policy Entropy Collapse Under Large Step Sizes

Diagnosing Stalled Runs via On-Batch Entropy

Tracking the Shannon entropy \mathcal{H}(\pi_\theta(\cdot \mid s)) = -\sum_a \pi_\theta(a \mid s)\log\pi_\theta(a \mid s) averaged along visited states shows how quickly large steps make the policy deterministic:

  • From uniform (\ln 4 \approx 1.39 nats) to deterministic (< 0.1 nats): Within 20 to 40 updates at \eta = 16, both arms collapse onto a nearly deterministic trajectory.
  • Why stalled runs never recover: A stalled reward-to-go run is just as deterministic (\approx 0 nats) as a winning run—repeating a loop into a hole with zero entropy and zero gradient.

Concept Check: Baselines and Variance Reduction

Check Your Understanding

Test your understanding of admissible baselines, RLOO, and step-size confounds:

  1. Admissible baselines: Which of the following may be subtracted from \hat{G}_t at step t without biasing the expected gradient: (a) the step index t, (b) the remaining episode length T - t, or (c) an action-value estimate \hat{Q}(s_t, a_t)?
  2. Centering vs. RLOO: In a batch of n = 4 episodes where one reaches the goal (R_1 = 0.77) and three hit holes (R_2 = R_3 = R_4 = 0), what weights do batch centering (R_i - \bar{R}) and RLOO (R_i - b_i) assign to the winning and losing episodes?
  3. Evaluating normalization: At \eta = 2, why is it a mistake to conclude that normalized is a lower-variance gradient estimator than value baseline just because it reaches 90\% success in fewer updates?

Answers:

  1. Only (a) the step index t is admissible because it is determined before a_t is sampled; both T - t and \hat{Q}(s_t, a_t) depend on the sampled action a_t and bias the expectation.
  2. With \bar{R} = 0.77/4 = 0.1925, batch centering assigns +0.5775 to the win and -0.1925 to each loss; RLOO scales these by \frac{n}{n-1} = \frac{4}{3}, assigning 0.77 - 0 = +0.77 to the win and 0 - 0.77/3 = -0.2567 to each loss.
  3. Dividing by \sigma \leq 0.5 multiplies the effective SGD learning rate by \approx 3\times; at the frozen probe, normalized actually has higher relative noise (7.5) than value baseline (5.7).

Summary: Policy-Gradient Variance Reduction

Key Takeaways

Estimator / Technique Weighting Formula w_t^i Expectation & Variance Properties
Trajectory Return R(\tau_i) = \sum_{t'=0}^{T_i-1} \gamma^{t'} r_{t'}^i Unbiased (\nabla_\theta J); highest variance over full trajectory
Causal Reward-to-Go \gamma^t \hat{G}_t^i with \hat{G}_t^i = \sum_{t' \geq t} \gamma^{t'-t} r_{t'}^i Unbiased (\nabla_\theta J); drops past rewards r_{<t} via zero-mean lemma
State Value Baseline \hat{G}_t^i - V(s_t^i) (sampled advantage A_t^i) Preserves expectation; cuts relative variance by \approx 50\% on Lake
Leave-One-Out (RLOO) R(\tau_i) - \frac{1}{n-1}\sum_{j \neq i} R(\tau_j) = \frac{n}{n-1}(R_i - \bar{R}) Unbiased batch/group centering without the (n-1)/n shrink factor
GRPO Group Weight (r(x, y_j) - \bar{R}_x)/(\sigma_x + \varepsilon) over K \geq 2 draws Critic-free per-prompt baseline + adaptive \sigma_x^{-1} step scaling