Actor-Critic Methods and Multi-Step Returns

Dive into Deep Learning · §15.1

Actor–Critic Methods and Generalized Advantage Estimation
TD error as advantage · semi-gradient critics · bias–variance trade-off · n-step returns · GAE backward scan

Why Wait for an Episode to End Before Updating?

Motivation

  • The Monte Carlo Bottleneck: Weighting by \hat{G}_t - \hat{V}(s_t) waits for termination and accumulates high tail variance over all remaining steps.
  • The Actor–Critic Synthesis: Since \hat{V}(s_{t+1}) already predicts \hat{G}_{t+1}, we substitute the critic’s prediction for the sampled tail—trading remaining-episode variance for young-critic bias.

Bootstrapping the Reward-to-Go with a Critic

The TD Advantage

Unrolling one step of the reward-to-go recurrence \hat{G}_t = r_t + \gamma \hat{G}_{t+1} and substituting \hat{V}(s_{t+1}) for \hat{G}_{t+1} transforms the baseline-subtracted weight \hat{G}_t - \hat{V}(s_t) into the temporal-difference (TD) error:

\delta_t = r_t + \gamma\, \hat{V}(s_{t+1}) - \hat{V}(s_t)

def td_target(self, bootstrap, gamma):
    """r_t + gamma (1 - terminated) V(s'), by a numpy bootstrap."""
    return self.rew + gamma * (1 - self.term) * bootstrap(self.next_obs)

Termination vs. Truncation: The bootstrap is zeroed out only when terminated is true (\hat{V}(s_{\textrm{term}}) = 0); at a 500-step time-limit truncated cut, the pole has not fallen and the future value is nonzero.

Tracing One Transition by Hand on CartPole

Concrete Intuition

  • Calibrated Critic (\hat{V}(s) = 100): Survival gives \delta_t = 1 + 0.99(100) - 100 = 0; dropping the pole (terminated) gives \delta_t = 1 + 0 - 100 = -99.
  • Freshly Initialized Critic (\hat{V}(s) \approx 0): Both survival and falling produce the exact same positive TD error \delta_t \approx +1, teaching the actor nothing until the critic catches up.

An Exact Critic Yields an Unbiased Advantage Sample

Theoretical Foundation

\mathbb{E}\big[\delta_t \mid s_t, a_t\big] = Q^\pi(s_t, a_t) - V^\pi(s_t) = A^\pi(s_t, a_t)

  • Current-state error vanishes: Error e(s_t) = \hat{V}(s_t) - V^\pi(s_t) depends only on s_t and averages to zero in the policy gradient.
  • Next-state coupling: Error \gamma e(s_{t+1}) depends on action a_t via s_{t+1} \sim P(\cdot \mid s_t, a_t) and biases the actor update.

Semi-Gradient Policy Evaluation in the Critic

Critic Mechanics

\Delta w = \alpha\, \delta_t\, \nabla_w \hat{V}_w(s_t)

  • Sampled Bellman backup: Regresses \hat{V}_w(s_t) toward the one-step target y_t = r_t + \gamma \hat{V}_w(s_{t+1}).
  • Why semi-gradient? td_target stops the gradient through y_t so derivatives are taken only through the prediction \hat{V}_w(s_t).

Bias–Variance Trade-off on a Ten-State Chain

Closed-Form Analysis

  • Consider a 10-state deterministic chain (s \to s+1, reward noise \sigma = 0.15, \gamma = 0.97) where a young critic has tapered error e(s) = 0.5(1 - s/9)^2.
  • An n-step target samples n rewards and bootstraps at state n: \textrm{Bias}(n) = \gamma^n e(n), \quad \textrm{Var}(n) = \sigma^2 \frac{1 - \gamma^{2n}}{1 - \gamma^2}
  • Interior Optimum (n = 4): \textrm{MSE} = \textrm{Bias}^2 + \textrm{Var} drops from 0.17 at n=1 to 0.10 at n=4, then rises back to 0.17 at n=10 (Monte Carlo).

Two Parameter Updates Driven by One Scalar

The Actor-Critic Loop

  • Every transition (s_t, a_t, r_t, s_{t+1}) produces a single scalar TD error \delta_t = r_t + \gamma \hat{V}_w(s_{t+1}) - \hat{V}_w(s_t) that drives both networks: w \leftarrow w + \alpha\, \delta_t\, \nabla_w \hat{V}_w(s_t) \theta \leftarrow \theta + \eta\, \delta_t\, \nabla_\theta \log \pi_\theta(a_t \mid s_t)
  • Two-Timescale Requirement (Konda & Tsitsiklis, 2000): If the actor moves faster than the critic, it climbs stale value estimates; the critic must update faster (critic_steps = 20 passes per batch) to track V^{\pi_\theta}.

Capping Actor Gradients Under Adam

Optimization Mechanics

We step the actor on raw (unnormalized) TD errors while capping the gradient norm at grad_clip = 0.5:

def actor_loss(ac, obs, act, weight):
    """-(1/n) sum_t w_t log pi(a_t|s_t), the loss of d2l.policy_step."""
    w, obs, act = (torch.as_tensor(x) for x in (weight, obs, act))
    return -(w * ac.log_prob(obs, act)).mean()

def policy_step_clip(ac, obs, act, weight, clip=grad_clip):
    """d2l.policy_step with the actor's gradient norm capped at `clip`;
    returns the norm measured before the cap."""
    loss = actor_loss(ac, obs, act, weight)
    ac.opt_pi.zero_grad()
    loss.backward()
    gnorm = nn.utils.clip_grad_norm_(ac.policy.parameters(), clip)
    ac.opt_pi.step()
    return float(gnorm)

Why raw \delta_t with Adam? As the critic converges, \textrm{std}(\delta_t) shrinks from \sim 3.0 to \le 0.1 (mostly critic noise). Because Adam divides by a long running average of squared gradients (\beta_2 = 0.999), shrinking raw TD errors naturally anneal the effective step size \sim 8\times near the ceiling, whereas batch-standardized TD errors would amplify late critic noise.

The Batched Fitted-TD Actor-Critic Loop

Implementation

Each update collects an 8-episode rollout, refits the critic for critic_steps = 20 passes against freshly recomputed one-step targets (fitted TD), and takes one clipped actor step:

def train(seed, ac, weight, num_updates=num_updates,
          batch_episodes=batch_episodes):
    """Batched policy gradient with the per-step weights weight(ac, b);
    yields (env steps, mean return of the batch, actor grad norm)."""
    rng, env = np.random.default_rng(seed), gym.make('CartPole-v1')
    env.reset(seed=seed)
    steps = 0
    for _ in range(num_updates):
        b = d2l.rollout(env, ac.act, batch_episodes, rng)
        gnorm = policy_step_clip(ac, b.obs, b.act, weight(ac, b))
        steps += len(b)
        yield steps, float(b.episode_returns().mean()), gnorm

def td_weight(ac, b):
    """Actor-critic: refit the critic toward its one-step target, then
    weight each step by the raw TD error of the refitted critic."""
    for _ in range(critic_steps):   # fresh target, one pass, repeat
        d2l.fit_value(ac, b.obs, b.td_target(ac.value_np, gamma))
    return b.td_target(ac.value_np, gamma) - ac.value_np(b.obs)

Three Systems Choices in Batched Actor-Critic

Design Decisions

  • 1. Refit critic before scoring actor: The 20 fitted-TD passes on b run before \delta_t is evaluated, so the actor’s weights carry less of the critic’s error.
  • 2. Recompute targets every pass: Calling b.td_target inside the 20-step loop propagates reward up to 20 steps backward per batch.
  • 3. Raw \delta_t + gradient cap 0.5: Avoids amplifying late critic noise while capping large early TD steps under Adam.

Bootstrapped vs. Monte Carlo Weights on CartPole

Experimental Comparison

  • To isolate the effect of the weight alone, mc_weight gives REINFORCE the exact same critic_steps = 20 regression passes and gradient norm cap 0.5.
  • Over 40 seeds, REINFORCE + baseline reaches a return of 450 first on at least 35 seeds, using 15\%–35\% fewer environment steps than one-step actor-critic.
  • The gradient cap triggers on 20\%–40\% of actor-critic updates (due to unnormalized early \delta_t) and 0\% of REINFORCE updates.

REINFORCE + baseline: 450 after 79, 64, 77 thousand steps; cap active 0%
        actor-critic: 450 after 113, 187, 112 thousand steps; cap active 29%

Why Young-Critic Bias Slows Early CartPole Learning

Diagnostic Analysis

  • Measuring both weights on the exact same trajectories confirms that the TD error’s variance is 25\times to 60\times smaller than the Monte Carlo advantage’s variance.
  • Why doesn’t lower variance win on CartPole? CartPole’s reward is a deterministic +1 per step, and bootstrapping at the 500-step truncation cut already removes the infinite tail variance.
  • With 8 episodes per batch, Monte Carlo variance is already manageable, whereas the young critic’s bias misdirects early actor updates.

first 10 updates: std of the TD error 2.69, of the MC advantage 7.69
 last 50 updates: std of the TD error 0.04, of the MC advantage 0.41
median variance ratio, MC over TD: 56x

Interpolating Horizons with n-Step Returns

Multi-Step Returns

\hat{G}^{(n)}_t = \sum_{l=0}^{n-1} \gamma^l r_{t+l} + \gamma^n\, \hat{V}(s_{t+n}) \hat{A}^{\textrm{GAE}}_t = (1 - \lambda) \sum_{n=1}^{\infty} \lambda^{n-1} \big( \hat{G}^{(n)}_t - \hat{V}(s_t) \big)

  • Endpoint \lambda = 0: Places all weight on n = 1, recovering the one-step TD error \delta_t.
  • Endpoint \lambda \to 1: Places all weight on the full episode return, recovering \hat{G}_t - \hat{V}(s_t).

Telescoping the Lambda-Return into TD Errors

Mathematical Derivation

\hat{A}^{\textrm{GAE}}_t = \sum_{l=0}^{\infty} (\gamma\lambda)^l\, \delta_{t+l}

  • Telescoping cancellation: Every n-step advantage \hat{G}^{(n)}_t - \hat{V}(s_t) collapses into \sum_{l=0}^{n-1} \gamma^l \delta_{t+l} as interior \pm \gamma^l \hat{V}(s_{t+l}) terms cancel in pairs.
  • Geometric sum: Term \gamma^l \delta_{t+l} appears in every depth n \ge l + 1 with total weight (1 - \lambda) \sum_{n > l} \lambda^{n-1} = \lambda^l.

Generalized Advantage Estimation in Two Lines

GAE Implementation

Because \hat{A}^{\textrm{GAE}}_t = \delta_t + \gamma\lambda\, \hat{A}^{\textrm{GAE}}_{t+1}, GAE is identical to the backward_scan used for reward-to-go in Chapter 14, run on \delta_t with discount factor \gamma\lambda:

def gae(self, value_fn, gamma, lam):
    """GAE(gamma, lam): the reward-to-go scan, run on the TD errors."""
    delta = self.td_target(value_fn, gamma) - value_fn(self.obs)
    return self.backward_scan(delta, gamma * lam)
lambda = 0 is the TD error; lambda = 1 is the Monte Carlo advantage

Sweeping Lambda on Short-Budget CartPole Runs

Empirical Sweep

  • With GAE, the critic fits the \lambda-return G^\lambda_t = \hat{A}^{\textrm{GAE}}_t + \hat{V}(s_t); the actor uses standardized advantages.
  • On a short budget (50 updates of 4 episodes, 5 seeds), heavily bootstrapped estimators (\lambda = 0 and \lambda = 0.5) stall at median returns of 150–250.
  • Longer-horizon mixtures (\lambda \in \{0.9, 0.95, 1.0\}) reach nearly 500, because downweighting the young critic’s bias outweighs the extra reward noise.

lambda =  0.0: best 20-update window, median 222.5, seeds [138. 198. 223. 283. 328.]
lambda =  0.5: best 20-update window, median 203.3, seeds [175. 179. 203. 218. 321.]
lambda =  0.9: best 20-update window, median 419.5, seeds [387. 400. 420. 454. 486.]
lambda = 0.95: best 20-update window, median 406.9, seeds [327. 367. 407. 444. 482.]
lambda =  1.0: best 20-update window, median 449.7, seeds [293. 385. 450. 464. 479.]

Measuring Gradient Bias and Variance at Frozen Policies

Frozen-Policy Probe

To decouple estimator quality from training dynamics, we freeze 8 partially trained agents (at 40 updates), draw 200 batches of 4 episodes each, and measure relative gradient bias and variance against the 200-batch mean of \lambda = 1:

lambda =  0.0: bias 1.19, variance 0.04, error / error at 1: 1.91
lambda =  0.5: bias 1.13, variance 0.05, error / error at 1: 1.61
lambda =  0.9: bias 0.84, variance 0.17, error / error at 1: 0.83
lambda = 0.95: bias 0.53, variance 0.32, error / error at 1: 0.61
lambda =  1.0: bias 0.00, variance 0.98, error / error at 1: 1.00
7 of 8 agents have their smallest error at lambda = 0.9 or 0.95

Across the 8 frozen agents, increasing \lambda from 0 to 1 drives bias to 0 while increasing variance more than 10\times (most sharply between 0.95 and 1.0, where the half-life of (\gamma\lambda)^l jumps from 11 steps to 69 steps). Total error \textrm{Bias}^2 + \textrm{Var} is minimized at \lambda \in [0.9, 0.95].

Why an Exact Critic Makes Lambda = 0 Optimal

Theory vs. Practice

  • Proposition (Exact Critic \hat{V} = V^\pi): Because \mathbb{E}[\delta_{t+l} \mid s_t, a_t, \delta_t, \dots, \delta_{t+l-1}] = 0 for all l \ge 1 by the Markov property, all cross terms vanish and: \mathbb{E}\big[(\hat{A}^{\textrm{GAE}}_t)^2 \mid s_t, a_t\big] = \sum_{l=0}^{\infty} (\gamma\lambda)^{2l}\, \mathbb{E}\big[\delta_{t+l}^2 \mid s_t, a_t\big] which is strictly minimized at \lambda = 0. Thus an interior optimum (\lambda \approx 0.95) exists solely because the critic is imperfect.
Estimator Architecture Reward Structure Episode Horizon Extra Cost Canonical Use Case
Learned Critic + GAE Dense per-step rewards Long or continuing Value network + critic bias Robotics, games, PPO (§15.2)
Group Baseline (GRPO) Single terminal verdict Single completion K parallel rollouts per prompt LLM reasoning with verifiers (§15.8)

Concept Check: TD Errors, GAE Horizons, and Critic Bias

Check Your Understanding

Work out these three diagnostic questions:

  1. Effective Horizon: At \gamma = 0.99, after how many steps l does the GAE weight (\gamma\lambda)^l decay to 0.5 when \lambda = 0.95 versus when \lambda = 1.0?
  2. Schedule Adaptation: Late in a long training run, your critic \hat{V}_w has become nearly exact across all visited states. Should you increase \lambda toward 1 or decrease it toward 0?
  3. Constant Overestimation: Suppose \hat{V}(s) = V^\pi(s) + c for a positive constant c > 0 at every nonterminal state (and \hat{V} = 0 at terminal states). Does \delta_t remain unbiased?

Answers:

  1. Half-life l_{1/2} = \ln 2 / (-\ln(\gamma\lambda)): for \lambda = 0.95 (\gamma\lambda = 0.9405), l_{1/2} \approx 11.3 steps; for \lambda = 1.0 (\gamma\lambda = 0.99), l_{1/2} \approx 69.0 steps.
  2. Decrease \lambda toward 0: once critic bias vanishes, future TD errors \delta_{t+l} (l \ge 1) have zero conditional mean and only add variance.
  3. Only on nonterminal transitions where \gamma c - c = (\gamma - 1)c is state-independent; at any state where one action risks termination (e(s') = 0), +c biases the actor against terminating.

Summary: Advantage Estimators Across the TD–MC Spectrum

Key Takeaways

Estimator Formula for Advantage Weight \hat{A}_t Bias (When \hat{V} \neq V^\pi) Single-Sample Variance Needs Finished Episode?
One-Step TD (\lambda = 0) \delta_t = r_t + \gamma \hat{V}(s_{t+1}) - \hat{V}(s_t) Highest (\gamma \mathbb{E}[e(s_{t+1})]) Lowest (1 transition) No (fully online / 1 step)
n-Step Return \sum_{l=0}^{n-1} \gamma^l r_{t+l} + \gamma^n \hat{V}(s_{t+n}) - \hat{V}(s_t) Decays as \gamma^n \mathbb{E}[e(s_{t+n})] Grows with horizon n No (n-step lookahead)
GAE (\lambda \in (0, 1)) \sum_{l=0}^{\infty} (\gamma\lambda)^l \delta_{t+l} (backward_scan) Tunable via 1 - \lambda Balanced at \lambda \approx 0.95 Segment cut + bootstrap
Monte Carlo (\lambda = 1) \hat{G}_t - \hat{V}(s_t) = \sum_{l=0}^{T-t-1} \gamma^l r_{t+l} - \hat{V}(s_t) Zero (exact baseline) Highest (full tail sum) Yes (or truncation cut)