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)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
Motivation
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)
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.
Concrete Intuition
terminated) gives \delta_t = 1 + 0 - 100 = -99.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)
Critic Mechanics
\Delta w = \alpha\, \delta_t\, \nabla_w \hat{V}_w(s_t)
td_target stops the gradient through y_t so derivatives are taken only through the prediction \hat{V}_w(s_t).Closed-Form Analysis
The Actor-Critic Loop
critic_steps = 20 passes per batch) to track V^{\pi_\theta}.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.
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)Design Decisions
b run before \delta_t is evaluated, so the actor’s weights carry less of the critic’s error.b.td_target inside the 20-step loop propagates reward up to 20 steps backward per batch.Experimental Comparison
mc_weight gives REINFORCE the exact same critic_steps = 20 regression passes and gradient norm cap 0.5.REINFORCE + baseline: 450 after 79, 64, 77 thousand steps; cap active 0%
actor-critic: 450 after 113, 187, 112 thousand steps; cap active 29%
Diagnostic Analysis
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
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)
Mathematical Derivation
\hat{A}^{\textrm{GAE}}_t = \sum_{l=0}^{\infty} (\gamma\lambda)^l\, \delta_{t+l}
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:
lambda = 0 is the TD error; lambda = 1 is the Monte Carlo advantage
Empirical Sweep
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.]
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].
Theory vs. Practice
| 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) |
Check Your Understanding
Work out these three diagnostic questions:
Answers:
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) |