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
演员–评论员方法与广义优势估计
TD 误差即优势 · 半梯度评论员 · 偏差–方差权衡 · n 步回报 · GAE 反向扫描
动机
TD 优势
将未来回报递推式 \hat{G}_t = r_t + \gamma \hat{G}_{t+1} 展开一步,并用 \hat{V}(s_{t+1}) 替换 \hat{G}_{t+1},减去基线的权重 \hat{G}_t - \hat{V}(s_t) 就变成时序差分(TD)误差:
\delta_t = r_t + \gamma\, \hat{V}(s_{t+1}) - \hat{V}(s_t)
终止与截断:仅当 terminated 为真时才将自举置零(\hat{V}(s_{\textrm{term}}) = 0);在 500 步时间上限的 truncated 截断处,杆并未倒下,未来价值不为零。
具体直觉
terminated)给出 \delta_t = 1 + 0 - 100 = -99。理论基础
\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)
评论员机制
\Delta w = \alpha\, \delta_t\, \nabla_w \hat{V}_w(s_t)
td_target 阻断穿过 y_t 的梯度,使导数仅通过预测值 \hat{V}_w(s_t) 计算。闭式分析
演员–评论员循环
critic_steps = 20 轮遍历)以紧跟 V^{\pi_\theta}。优化机制
我们用原始(未标准化)TD 误差更新演员,并将梯度范数上限截断在 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)为何在 Adam 下使用原始 \delta_t? 随着评论员收敛,\textrm{std}(\delta_t) 从 \sim 3.0 缩小到 \le 0.1(主要为评论员噪声)。由于 Adam 除以平方梯度的长滑动平均(\beta_2 = 0.999),不断缩小的原始 TD 误差会在接近上限时自然把有效步长退火 \sim 8\times;而批内标准化的 TD 误差则会放大后期的评论员噪声。
实现
每次更新采集 8 回合轨迹,针对每轮新重算的一步目标对评论员执行 critic_steps = 20 轮重新拟合(拟合时序差分),再执行一次带梯度截断的演员更新:
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)设计决策
b 上执行 20 轮拟合 TD 遍历再评估 \delta_t,从而减少演员权重中的评论员误差。b.td_target,每批最多可将奖励信息向前传播 20 步。实验对比
mc_weight 给 REINFORCE 配备了完全相同的 critic_steps = 20 轮回归遍历和梯度范数上限 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%
诊断分析
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
多步回报
\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)
数学推导
\hat{A}^{\textrm{GAE}}_t = \sum_{l=0}^{\infty} (\gamma\lambda)^l\, \delta_{t+l}
GAE 实现
由于 \hat{A}^{\textrm{GAE}}_t = \delta_t + \gamma\lambda\, \hat{A}^{\textrm{GAE}}_{t+1},GAE 与第 14 章计算未来回报所用的 backward_scan 完全一致,只需对 \delta_t 以折扣因子 \gamma\lambda 运行即可:
lambda = 0 is the TD error; lambda = 1 is the Monte Carlo advantage
经验扫描
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.]
冻结策略探针
为了将估计器质量与训练动态解耦,我们冻结 8 个部分训练好的智能体(40 次更新处),各抽取 200 个 4 回合批次,对照 \lambda = 1 的 200 批均值测量相对梯度偏差与方差:
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
在这 8 个冻结智能体上,将 \lambda 从 0 增至 1 会把偏差压到 0,同时使方差增大 10\times 以上(在 0.95 到 1.0 之间增幅最剧烈,那里 (\gamma\lambda)^l 的半衰期从 11 步跃升至 69 步)。总误差 \textrm{Bias}^2 + \textrm{Var} 在 \lambda \in [0.9, 0.95] 处取最小。
理论与实践
| 估计器架构 | 奖励结构 | 回合长度 | 额外开销 | 典型应用场景 |
|---|---|---|---|---|
| 学习评论员 + GAE | 密集单步奖励 | 长回合或持续任务 | 价值网络 + 评论员偏差 | 机器人控制、游戏、PPO(§15.2) |
| 组基线(GRPO) | 单一终端裁决 | 单次生成补全 | 每个提示并行 K 条采样 | 带验证器的大语言模型推理(§15.8) |
检验理解
思考以下三个诊断问题:
解答:
核心要点
| 估计器 | 优势权重 \hat{A}_t 公式 | 偏差(当 \hat{V} \neq V^\pi 时) | 单样本方差 | 是否需要完整回合? |
|---|---|---|---|---|
| 一步 TD(\lambda = 0) | \delta_t = r_t + \gamma \hat{V}(s_{t+1}) - \hat{V}(s_t) | 最高(\gamma \mathbb{E}[e(s_{t+1})]) | 最低(1 条转移) | 否(完全在线 / 1 步) |
| n 步回报 | \sum_{l=0}^{n-1} \gamma^l r_{t+l} + \gamma^n \hat{V}(s_{t+n}) - \hat{V}(s_t) | 按 \gamma^n \mathbb{E}[e(s_{t+n})] 衰减 | 随视野 n 增长 | 否(n 步前瞻) |
| GAE(\lambda \in (0, 1)) | \sum_{l=0}^{\infty} (\gamma\lambda)^l \delta_{t+l}(backward_scan) |
通过 1 - \lambda 可调 | 在 \lambda \approx 0.95 处平衡 | 片段截断 + 自举 |
| 蒙特卡洛(\lambda = 1) | \hat{G}_t - \hat{V}(s_t) = \sum_{l=0}^{T-t-1} \gamma^l r_{t+l} - \hat{V}(s_t) | 零(精确基线) | 最高(完整尾部和) | 是(或截断处自举) |