Part V · 第 20 章 强化学习 · 20.4Part V · Ch. 20 Reinforcement Learning · 20.4

Actor-Critic:PPO 与 SACActor-Critic: PPO & SAC

策略梯度会告诉策略往哪里改,但它用整段回报来打分,噪声大得惊人。Actor-Critic 方法再训练一个"评论家"(critic)网络来估计价值,用它给每一步打分,噪声就小多了。本节先看评论家怎样用 GAE 在偏差和方差之间折中,再看今天机器人学习里最常用的两个算法:PPO 用截断的概率比限制每次更新的步子,靠成百上千个并行仿真环境吃饱数据;SAC 最大化"奖励 + 熵",用重放缓冲区反复利用旧数据,再用双评论家压住高估。两个算法都在你的浏览器里实时训练同一个关节到达任务,最后讨论什么时候用哪一个。 A policy gradient tells the policy which way to change, but it scores every action with a whole noisy return. Actor-critic methods train a second network, the critic, to estimate values and score each step with them, which removes most of that noise. This lesson first shows how the critic trades bias against variance through GAE, then the two algorithms that dominate robot learning today: PPO, which clips a probability ratio so that each update stays small and feeds on hundreds or thousands of parallel simulated environments, and SAC, which maximizes reward plus entropy, reuses old data from a replay buffer and holds down overestimation with twin critics. Both train live in your browser on the same joint-reaching task, and the lesson ends with when to use which.

约 50 分钟~50 min 前置:20.1 MDP 与 Bellman 方程 · 20.2 Q-learning 与 DQN · 20.3 策略梯度 · 4.11 熵与 KL · 6.3 AdamPrereqs: 20.1 MDPs & Bellman · 20.2 Q-learning & DQN · 20.3 Policy gradients · 4.11 Entropy & KL · 6.3 Adam 6 个交互6 interactives

    1为什么机器人需要它Why robots need this

    20.3 节的 REINFORCE 已经能训练一个连续动作的高斯策略:采一整段轨迹,用回报 \(G_t\) 乘以 \(\nabla_\theta\log\pi_\theta(a_t|s_t)\) 求平均。它是无偏的,但在机器人任务上几乎用不起来,原因有三个:

    • 方差太大。一条腿式机器人的轨迹有上千步,\(G_t\) 混进了之后每一步的随机性:脚下一滑、一次碰撞,都会让同一个动作得到完全不同的分数。要把噪声平均掉,需要海量轨迹。
    • 步长难定。梯度只在当前策略附近有意义。步子小了学得慢,步子大了策略一下子变坏,而变坏的策略又采回更坏的数据,可能再也爬不回来。
    • 数据只用一次。策略梯度要求数据来自当前策略,策略一更新,旧数据就作废了。在仿真里还能忍;在真机上,每一个样本都是电机磨损和实验员的时间。

    Actor-Critic 的思路是再训练一个评论家:一个估计价值 \(V_\phi(s)\) 或 \(Q_\phi(s,a)\) 的网络(20.1–20.2 节的价值函数,换成神经网络并在线学习)。演员(actor,也就是策略 \(\pi_\theta\))用评论家给出的"这一步比平均好多少"(优势)来更新,而不是用整段回报。在这个框架上,两个算法分别解决了后两个问题:

    • PPO(Proximal Policy Optimization,Schulman 等,2017):同策略(on-policy),用"截断的概率比"把每次更新限制在旧策略附近,可以放心地在同一批数据上做多轮梯度;数据多就用并行环境去采。这是 Isaac Gym / Isaac Lab 里训练腿式机器人的主力。
    • SAC(Soft Actor-Critic,Haarnoja 等,2018):异策略(off-policy),把所有经验存进重放缓冲区反复使用;目标里加上策略的熵,让探索自动发生;用两个评论家取较小值,压住 Q 值的高估。它的样本效率高,适合直接在真机上学习。

    本节用同一个小任务贯穿全篇:一个受重力作用的单关节手臂,必须在 2 秒内转到随机给定的目标角度并保持住(这需要学会重力补偿),动作是归一化的电机力矩 \(a\in[-1,1]\)。PPO 和 SAC 都在浏览器里从零开始训练它。

    Lesson 20.3's REINFORCE can already train a Gaussian policy for continuous actions: sample whole trajectories and average the return \(G_t\) times \(\nabla_\theta\log\pi_\theta(a_t|s_t)\). It is unbiased, but on robot tasks it is nearly unusable, for three reasons:

    • The variance is huge. A legged robot's trajectory has thousands of steps, and \(G_t\) mixes in the randomness of every later step: a slipping foot or a collision gives the same action a completely different score. Averaging that noise away takes an enormous number of trajectories.
    • The step size is hard to choose. The gradient is only meaningful near the current policy. Small steps learn slowly; a large step can ruin the policy, the ruined policy collects even worse data, and it may never climb back.
    • Data is used once. The policy gradient needs data from the current policy, so every update throws the old data away. In simulation that is tolerable; on hardware every sample costs motor wear and an experimenter's time.

    The actor-critic idea is to train a second network, the critic, that estimates a value \(V_\phi(s)\) or \(Q_\phi(s,a)\) (the value functions of Lessons 20.1–20.2, now neural networks learned online). The actor (the policy \(\pi_\theta\)) is updated with the critic's estimate of "how much better than average this step was" (the advantage) instead of the whole return. On top of this framework, two algorithms address the last two problems:

    • PPO (Proximal Policy Optimization, Schulman et al., 2017) is on-policy. A "clipped probability ratio" keeps each update close to the old policy, so it can safely take several gradient epochs on one batch, and it gets large batches from parallel environments. It is the workhorse for training legged robots in Isaac Gym / Isaac Lab.
    • SAC (Soft Actor-Critic, Haarnoja et al., 2018) is off-policy. It keeps all experience in a replay buffer and reuses it, adds the policy's entropy to the objective so that exploration happens by itself, and takes the smaller of two critics to hold down Q-value overestimation. It is sample-efficient and suits learning directly on real robots.

    One small task runs through the whole page: a single arm joint under gravity must turn to a random target angle within 2 seconds and hold it there (which requires learning gravity compensation); the action is a normalized motor torque \(a\in[-1,1]\). PPO and SAC both train it from scratch in your browser.

    2直觉:评论家给每一步打分Intuition: the critic scores each step

    20.3 节已经看到,从回报里减去一个只依赖状态的基线 \(b(s_t)\) 不改变梯度的期望,却能大大降低方差,最好的基线接近 \(V^\pi(s_t)\)。Actor-Critic 把这件事推进一步:既然有了一个学出来的 \(V_\phi\),就连回报本身也可以用它来估计。最短的版本只看一步,叫时序差分误差(TD error,20.2 节):

    Lesson 20.3 showed that subtracting a state-only baseline \(b(s_t)\) from the return leaves the expected gradient unchanged and cuts the variance a lot, and that the best baseline is close to \(V^\pi(s_t)\). Actor-critic takes one more step: once we have a learned \(V_\phi\), we can use it to estimate the return itself. The shortest version looks one step ahead and is the temporal-difference (TD) error of Lesson 20.2:

    $$ \hl{delta}{\delta_t} \;=\; r_{t+1}+\gamma\,\hl{Vhat}{V_\phi}(s_{t+1})-\hl{Vhat}{V_\phi}(s_t). $$

    "这一步拿到的奖励,加上评论家对下一状态的估值,减去评论家对这一状态的估值":如果 \(V_\phi=V^\pi\),它的期望正好是优势 \(A^\pi(s_t,a_t)=Q^\pi(s_t,a_t)-V^\pi(s_t)\)。它只含一步的随机性,方差很小;代价是一旦评论家估错,误差会原样漏进来,产生偏差。另一头是蒙特卡洛:把整段回报 \(G_t\) 减去 \(V_\phi(s_t)\),没有偏差(评论家只当基线用),但方差最大。广义优势估计 GAE(Schulman 等,2016)用一个旋钮 \(\lambda\in[0,1]\) 在两者之间连续插值:

    "The reward of this step, plus the critic's value of the next state, minus its value of this state": if \(V_\phi=V^\pi\), its expectation is exactly the advantage \(A^\pi(s_t,a_t)=Q^\pi(s_t,a_t)-V^\pi(s_t)\). It contains the randomness of one step only, so its variance is small; the price is that any error in the critic leaks straight in as bias. At the other end is Monte Carlo: the whole return \(G_t\) minus \(V_\phi(s_t)\), unbiased (the critic serves only as a baseline) but with the largest variance. Generalized advantage estimation, GAE (Schulman et al., 2016), interpolates continuously between the two with one knob \(\lambda\in[0,1]\):

    $$ \hat A_t^{\mathrm{GAE}(\gamma,\hl{lam}{\lambda})}=\sum_{l=0}^{\infty}(\gamma\hl{lam}{\lambda})^{l}\,\hl{delta}{\delta_{t+l}},\qquad \lambda=0:\ \hat A_t=\delta_t,\qquad \lambda=1:\ \hat A_t=G_t-V_\phi(s_t). $$

    下图用一个能精确算出真值的小例子来看这个折中。一个送货机器人在 10 格走廊里,从第 2 格出发去第 9 格的充电桩:每走一步奖励 \(-1\),到达充电桩额外 \(+10\);它的策略以 0.6 的概率向右、0.4 的概率向左,每次移动有 0.2 的概率打滑原地不动,\(\gamma=0.95\)。我们要估计"在起点向右走"的价值 \(Q^\pi(s_0,\rightarrow)\),等价于估计它的优势(两者只差一个常数 \(V_\phi(s_0)\))。评论家 \(V_\phi\) 等于真值加上每格一个固定的随机误差(标准差 \(\sigma_V\))。估计量的均值和方差都是精确算出来的(两条 Bellman 式递推,见第 5 节),直方图是 1500 条采样轨迹的实际估计值。

    The figure looks at this trade-off on a small example whose true values can be computed exactly. A delivery robot in a 10-cell corridor starts in cell 2 and heads for the charging dock in cell 9: every step gives reward \(-1\) and arriving at the dock gives an extra \(+10\). Its policy goes right with probability 0.6 and left with 0.4, every move slips (the robot stays put) with probability 0.2, and \(\gamma=0.95\). We estimate the value of "going right at the start", \(Q^\pi(s_0,\rightarrow)\), which is the same as estimating its advantage (the two differ by the constant \(V_\phi(s_0)\)). The critic \(V_\phi\) is the true value plus a fixed random error in each cell (standard deviation \(\sigma_V\)). The estimator's mean and variance are computed exactly (two Bellman-style recursions, Section 5); the histogram shows the actual estimates from 1500 sampled trajectories.

    FIG 1GAE:评论家的误差 vs 回报的噪声GAE: critic error vs return noise
    走廊、价值与估计值分布CORRIDOR · VALUES · ESTIMATES
    偏差²、方差、均方误差 vs λ(对数)BIAS², VARIANCE, MSE vs λ (log)
    左上:绿色柱是真值 \(V^\pi\)(第 9 格是充电桩,价值为 0),紫色空心圆是评论家 \(V_\phi\),琥珀色圆点是机器人的起点。左下:青色直方图是 1500 条轨迹上 \(\lambda\)-回报(GAE 优势加 \(V_\phi(s_0)\))的分布,绿色竖线是真值 \(Q^\pi(s_0,\rightarrow)\),琥珀色竖线是估计量的精确均值。右:红线 = 偏差²,蓝线 = 方差,琥珀色粗线 = 均方误差(两者之和),竖虚线是当前 \(\lambda\),空心圆是均方误差最小处。"换一组评论家误差"重新抽每格的误差方向。 Top left: green bars are the true values \(V^\pi\) (cell 9 is the dock, value 0), hollow purple circles are the critic \(V_\phi\), and the amber dot is the robot's start. Bottom left: the cyan histogram is the \(\lambda\)-return (GAE advantage plus \(V_\phi(s_0)\)) over 1500 trajectories; the green line is the true \(Q^\pi(s_0,\rightarrow)\) and the amber line the estimator's exact mean. Right: red = bias², blue = variance, thick amber = mean squared error (their sum); the dashed line is the current \(\lambda\) and the hollow circle marks the smallest MSE. "New critic error" redraws the direction of each cell's error.
    试一试Try this
    • 把评论家误差 \(\sigma_V\) 调到 0(完美的评论家),再把 \(\lambda\) 调到 1。偏差两端都是 0,但 \(\lambda=1\) 的方差约是 \(\lambda=0\) 的多少倍?Set the critic error \(\sigma_V\) to 0 (a perfect critic), then set \(\lambda\) to 1. The bias is 0 at both ends, but roughly how many times larger is the variance at \(\lambda=1\) than at \(\lambda=0\)?
    • 把 \(\sigma_V\) 设为 1.5 或更大,找出均方误差最小的 \(\lambda\):读数里的均方误差要在最小值的 10% 以内(读数会显示"✓ 接近最优")。再按"换一组评论家误差",最优的 \(\lambda\) 会变吗?With \(\sigma_V\) at 1.5 or more, find the \(\lambda\) with the smallest mean squared error: the readout's MSE must be within 10% of the minimum (the readout shows "✓ near best"). Then press "New critic error": does the best \(\lambda\) move?
    核心洞见Key insight

    评论家是用偏差换方差。完美的评论家下,\(\lambda=0\) 只看一步、方差约为蒙特卡洛的百分之一,又没有偏差;评论家越不准,越要靠更长的真实回报(更大的 \(\lambda\))来稀释它的误差。实践里评论家是边学边用的,误差不大不小,所以 PPO 常用 \(\lambda\approx0.95\)、\(\gamma\approx0.99\):大部分噪声已经消掉,评论家的误差也被几十步的真实奖励冲淡了。注意这里的最优 \(\lambda\) 依赖评论家误差的具体形状,并不是一个普适常数。

    The critic trades variance for bias. With a perfect critic, \(\lambda=0\) looks one step ahead, has about one hundredth of the Monte Carlo variance and no bias at all; the worse the critic, the more you must dilute its errors with longer real returns (larger \(\lambda\)). In practice the critic is learned while it is used and is moderately wrong, so PPO typically uses \(\lambda\approx0.95\) with \(\gamma\approx0.99\): most of the noise is gone, and the critic's errors are washed out by tens of steps of real rewards. Note that the best \(\lambda\) here depends on the particular shape of the critic's error; it is not a universal constant.

    3动手玩:PPO,步子迈小一点Play: PPO, keep each step small

    有了优势估计 \(\hat A_t\),最直接的做法是对 \(\hat A_t\log\pi_\theta(a_t|s_t)\) 做一步梯度上升,然后把数据扔掉。这太浪费:采数据很贵,更新却很便宜。能不能在同一批数据上多走几步?问题是数据来自旧策略 \(\pi_{\theta_k}\),策略一变,"新策略下的期望"就要靠重要性采样(4.9 节)来纠正,权重就是概率比(这里记作 \(\rho\),因为 \(r\) 已经表示奖励;PPO 原文记作 \(r_t\)):

    With advantage estimates \(\hat A_t\) in hand, the most direct move is one gradient-ascent step on \(\hat A_t\log\pi_\theta(a_t|s_t)\), after which the data is discarded. That is wasteful: collecting data is expensive and updates are cheap. Can we take several steps on the same batch? The catch is that the data came from the old policy \(\pi_{\theta_k}\); once the policy changes, expectations under the new policy have to be corrected with importance sampling (Lesson 4.9), whose weight is the probability ratio (written \(\rho\) here because \(r\) is the reward; the PPO paper calls it \(r_t\))

    $$ \begin{gathered} \hl{ratio}{\rho_t(\theta)}=\frac{\pi_\theta(a_t|s_t)}{\pi_{\theta_k}(a_t|s_t)},\qquad L^{\text{PG}}(\theta)=\hat{\mathbb E}_t\big[\hl{ratio}{\rho_t(\theta)}\,\hat A_t\big],\\ L^{\text{CLIP}}(\theta)=\hat{\mathbb E}_t\Big[\min\big(\hl{ratio}{\rho_t}\hat A_t,\ \hl{clip}{\operatorname{clip}(\rho_t,1-\epsilon,1+\epsilon)}\,\hat A_t\big)\Big]. \end{gathered} $$

    \(L^{\text{PG}}\) 在 \(\theta=\theta_k\) 处的梯度正好是策略梯度(\(\nabla\rho_t=\nabla\log\pi_\theta\)),但离旧策略越远,它越是建立在少数几个权重很大的样本上,估计值就越不可信,而优化器恰恰会利用这种不可信:哪里估计虚高就往哪里冲。PPO 的 \(L^{\text{CLIP}}\) 做了一件很简单的事:一个样本的概率比一旦超出 \([1-\epsilon,1+\epsilon]\),并且继续变化只会让目标"更好看",它对梯度的贡献就变成零。好动作的概率最多涨到 \(1+\epsilon\) 倍,坏动作的概率最多降到 \(1-\epsilon\) 倍;反方向(把坏动作变得更可能)则照常受罚,不被截断。

    下图是一个只有动作没有状态的例子,正好能把"真实的改进"精确算出来。动作 \(a\) 是推关节的力度:推得越猛越好,可是超过 0.9 会触发安全停机,优势骤降 3。旧策略是 \(\mathcal N(0,0.4^2)\),它的 16 个样本里没有一个落在停机区,所以数据根本看不见这个悬崖。新策略 \(\mathcal N(m,0.4^2)\),拖动琥珀色手柄(或在右图里点击)改变 \(m\)。

    At \(\theta=\theta_k\) the gradient of \(L^{\text{PG}}\) is exactly the policy gradient (\(\nabla\rho_t=\nabla\log\pi_\theta\)), but the further the policy moves, the more the estimate rests on a few samples with huge weights and the less it can be trusted, and the optimizer exploits exactly that: it rushes to wherever the estimate is inflated. PPO's \(L^{\text{CLIP}}\) does something very simple: once a sample's ratio leaves \([1-\epsilon,1+\epsilon]\) in the direction that would make the objective look even better, that sample stops contributing gradient. A good action's probability can grow by at most \(1+\epsilon\), a bad action's can shrink to at most \(1-\epsilon\) of its old value; the opposite direction (making a bad action more likely) is still penalized in full and never clipped.

    The figure is an example with actions but no states, so the true improvement can be computed exactly. The action \(a\) is how hard to push the joint: the harder the better, but beyond 0.9 a safety stop trips and the advantage drops by 3. The old policy is \(\mathcal N(0,0.4^2)\), and none of its 16 samples lands in the stop zone, so the data cannot see the cliff at all. The new policy is \(\mathcal N(m,0.4^2)\): drag the amber handle (or click in the right panel) to change \(m\).

    FIG 2截断代理目标:为什么不能一步走太远The clipped surrogate: why not to step too far
    动作空间:拖动新策略均值 mACTION SPACE · drag the new mean m
    代理目标 vs m(点击设置 m)SURROGATE vs m (click to set m)
    每个样本的贡献 ÷ |Â| vs 概率比 ρPER-SAMPLE TERM ÷ |Â| vs RATIO ρ
    左:青色曲线是旧策略,琥珀色曲线是新策略,竖线是 16 个样本的(归一化)优势,绿色为正、红色为负;顶端实心 = 仍有梯度,空心 = 已被截断;淡红色区域是停机区。右:紫色 = 不截断的 \(L^{\text{PG}}\),琥珀色 = \(L^{\text{CLIP}}\),绿色虚线 = 真实的改进 \(\mathbb E_{\pi_m}[A]-\mathbb E_{\pi_{\theta_k}}[A]\)(与优势同样归一化;算法看不到它)。下:每个样本的项除以 \(|\hat A|\) 后只有两条曲线,绿色是 \(\hat A>0\),红色是 \(\hat A<0\),点是 16 个样本当前的位置,空心点没有梯度,竖虚线是 \(1\pm\epsilon\)。读数里的"有效样本数"是 \((\sum\rho_i)^2/\sum\rho_i^2\)。 Left: the cyan curve is the old policy and the amber curve the new one; the stems are the 16 samples' (normalized) advantages, green positive and red negative; a filled tip still has gradient, a hollow tip is clipped; the light red zone is the safety stop. Right: purple = unclipped \(L^{\text{PG}}\), amber = \(L^{\text{CLIP}}\), green dashed = the true improvement \(\mathbb E_{\pi_m}[A]-\mathbb E_{\pi_{\theta_k}}[A]\) (normalized like the advantages; the algorithm never sees it). Bottom: divided by \(|\hat A|\), every sample's term lies on one of two curves, green for \(\hat A>0\) and red for \(\hat A<0\); the dots are the 16 samples now, hollow dots have no gradient, and the dashed lines are \(1\pm\epsilon\). The readout's "effective sample size" is \((\sum\rho_i)^2/\sum\rho_i^2\).
    试一试Try this
    • 把 \(m\) 往右拖,找一个"不截断的估计还许诺超过 0.5 的改进,而真实改进已经是负数"的位置。这时有效样本数还剩几个?Drag \(m\) to the right until the unclipped estimate still promises an improvement above 0.5 while the true improvement is already negative. How many effective samples are left there?

    在 \(\epsilon=0.2\) 时 \(L^{\text{CLIP}}\) 的最高点在 \(m\approx0.15\)(KL 约 0.07),真实改进约 +0.25;真正的最优在 \(m\approx0.30\)(+0.36)。不截断的 \(L^{\text{PG}}\) 却在 \(m\approx0.53\) 达到 +0.66,那里的真实改进只剩 +0.09;到 \(m=0.8\) 它仍许诺 +0.52,真实值已是 \(-0.99\)。截断给出的是一个保守但可靠的小步;多走几步,用新数据再截断,比一步跳到估计值的顶点安全得多。

    现在把这一切放进完整的算法里。PPO 的一次迭代:(1) 用当前策略在 \(N\) 个并行环境里各跑 \(H=40\) 步;(2) 用评论家算 GAE 优势,在这一批里归一化;(3) 把这 \(NH\) 个样本打乱成大小 128 的小批量,在 \(L^{\text{CLIP}}\) 和评论家的回归损失上做 \(K\) 轮 Adam;(4) 扔掉数据,回到 (1)。演员和评论家都是 3→32→32→1 的 tanh 网络,策略是均值由网络给出、标准差是一个可学习参数的高斯分布,\(\gamma=0.97\),\(\lambda=0.95\)。每次迭代后,用确定性策略(取均值)在 24 组固定的(起点,目标)上评估:曲线是 2 秒结束时与目标的平均角度误差。

    At \(\epsilon=0.2\) the top of \(L^{\text{CLIP}}\) is at \(m\approx0.15\) (KL about 0.07), where the true improvement is about +0.25; the true optimum is at \(m\approx0.30\) (+0.36). The unclipped \(L^{\text{PG}}\) instead peaks at \(m\approx0.53\) with +0.66, where the true improvement is only +0.09; at \(m=0.8\) it still promises +0.52 while the truth is \(-0.99\). Clipping gives a conservative but reliable small step; several such steps, each with fresh data and its own clipping, are far safer than one jump to the top of the estimate.

    Now put this into the full algorithm. One PPO iteration: (1) run the current policy for \(H=40\) steps in each of \(N\) parallel environments; (2) compute GAE advantages with the critic and normalize them over the batch; (3) shuffle the \(NH\) samples into minibatches of 128 and run \(K\) epochs of Adam on \(L^{\text{CLIP}}\) and on the critic's regression loss; (4) discard the data and go back to (1). Actor and critic are 3→32→32→1 tanh networks; the policy is a Gaussian whose mean comes from the network and whose standard deviation is a learned parameter; \(\gamma=0.97\), \(\lambda=0.95\). After each iteration the deterministic policy (its mean) is evaluated on 24 fixed (start, target) pairs: the curve is the mean angle error to the target at the end of the 2 seconds.

    FIG 3PPO 实时训练:N 个并行的关节PPO training live: N joints in parallel
    并行环境(当前策略,含探索噪声)PARALLEL ENVS (current policy, with exploration noise)
    评估误差(°,对数)与每次迭代的 KLEVAL ERROR (°, log) and KL per iteration
    左:每个小格是一个环境,琥珀色是手臂,绿色虚线是目标角度(从竖直向下量起),格子按当前策略实时回放(每个回合 2 秒后换一组起点和目标),最多画 16 个。右上:琥珀色是这次训练的评估误差,紫色虚线是上一次训练(换设置或重置之前),横轴是环境步数。右下:每次迭代结束后新旧策略之间的 KL(对数刻度),青色虚线标出 0.02。读数里的"最大概率比"是这一批样本里 \(\max(\rho,1/\rho)\):截断并不保证它停在 \(1\pm\epsilon\) 内。 Left: each tile is one environment; the amber line is the arm and the green dashed line the target angle (measured from hanging straight down). The tiles replay the current policy in real time (a new start and target every 2 s), at most 16 of them. Top right: amber is this run's evaluation error, the purple dashed line is the previous run (before the last setting change or reset); the horizontal axis is environment steps. Bottom right: the KL between the old and new policy after each iteration (log scale), with a cyan dashed line at 0.02. The readout's "max ratio" is \(\max(\rho,1/\rho)\) over the batch: clipping does not keep it inside \(1\pm\epsilon\).
    试一试Try this
    • 用默认设置(\(N=16\),\(\epsilon=0.2\),\(K=4\))按"训练",直到评估误差低于 3°。用了多少次迭代、多少环境步?With the defaults (\(N=16\), \(\epsilon=0.2\), \(K=4\)) press "Train" until the evaluation error drops below 3°. How many iterations and environment steps did it take?
    • 把截断关掉(\(\epsilon\) 选"关"),轮数 \(K=10\),训练到某次迭代的 KL 超过 0.5。误差曲线发生了什么?再换回 \(\epsilon=0.2\) 比较。Turn clipping off (\(\epsilon\) = "off") with \(K=10\) epochs and train until one iteration's KL exceeds 0.5. What happens to the error curve? Switch back to \(\epsilon=0.2\) and compare.
    • 选 \(N=64\)(每次迭代 2560 个样本),训练到误差低于 3°,要求不超过 12 次迭代。和 \(N=16\) 相比,迭代次数和环境步数各自怎么变?Choose \(N=64\) (2560 samples per iteration) and get the error below 3° within at most 12 iterations. Compared with \(N=16\), how do the number of iterations and the number of environment steps change?
    核心洞见Key insight

    在种子 1 下,默认设置第 7 次迭代(4480 步)第一次低于 3°,之后在 1°–8° 之间起伏,大约 30 次迭代后稳定在 1° 左右;\(N=64\) 只要 6 次迭代,却用了 15 360 步。也就是说,并行环境不省样本,省的是迭代次数:在 GPU 上一次推进几千个仿真环境的时间和推进一个差不多,所以真实耗时由迭代次数决定。关掉截断、做 10 轮时,每次迭代的 KL 从 0.002–0.05 跳到约 0.2–15,误差可能跳回 100° 以上。截断后的 KL 小而稳定,这才是"近端"(proximal)的意思。

    With seed 1, the default run first drops below 3° at iteration 7 (4480 steps), then wanders between 1° and 8° and settles near 1° after about 30 iterations; \(N=64\) needs only 6 iterations but 15,360 steps. In other words, parallel environments do not save samples, they save iterations: stepping thousands of simulated environments on a GPU takes about as long as stepping one, so wall-clock time is set by the number of iterations. With clipping off and 10 epochs, the KL per iteration jumps from 0.002–0.05 to roughly 0.2–15 and the error can leap back above 100°. With clipping the KL stays small and steady, which is what "proximal" means.

    4第二个视角:SAC,异策略加最大熵A second view: SAC, off-policy and maximum entropy

    PPO 的每个样本只服务于采它的那个策略。另一条路是学 \(Q(s,a)\):Bellman 方程 \(Q(s,a)=r+\gamma\,\mathbb E[V(s')]\) 对任何行为策略收集的转移 \((s,a,r,s')\) 都成立(20.2 节的 Q-learning 正是这样),所以旧数据可以存进重放缓冲区一直用下去。DQN 在离散动作上取 \(\max_a\);连续动作取不了 max,就让演员网络去找让 \(Q\) 大的动作,这就是 DDPG(Lillicrap 等,2016)和它的改进 TD3(Fujimoto 等,2018)的做法。SAC 在此之上改了目标本身:

    Each PPO sample serves only the policy that collected it. The other road is to learn \(Q(s,a)\): the Bellman equation \(Q(s,a)=r+\gamma\,\mathbb E[V(s')]\) holds for transitions \((s,a,r,s')\) collected by any behaviour policy (that is how Q-learning works in Lesson 20.2), so old data can live in a replay buffer and be reused indefinitely. DQN takes \(\max_a\) over discrete actions; with continuous actions there is no max to take, so an actor network learns to find actions with large \(Q\). That is DDPG (Lillicrap et al., 2016) and its refinement TD3 (Fujimoto et al., 2018). SAC goes further and changes the objective itself:

    $$ J(\pi)=\sum_t\mathbb E\Big[r_{t+1}+\hl{alpha}{\alpha}\,\hl{H}{\mathcal H\big(\pi(\cdot|s_t)\big)}\Big],\qquad \pi^\star(a|s)\;\propto\;\exp\!\big(\hl{Qa}{Q^\star(s,a)}/\hl{alpha}{\alpha}\big). $$

    每一步除了奖励,还奖励策略的熵 \(\mathcal H\)(4.11 节):在同样好的动作之间保持随机。温度 \(\alpha\) 决定熵值多少钱。这个"软"目标的最优策略是 Q 值的玻尔兹曼分布:\(\alpha\to0\) 时退化为 \(\arg\max\),\(\alpha\) 很大时接近均匀。SAC 的演员是一个 tanh 压缩的高斯(输出 \(\mu,\log\sigma\),\(a=\tanh(\mu+\sigma\varepsilon)\)),它在每个状态上最小化 \(\mathrm{KL}\big(\pi\,\|\,\pi^\star\big)\),等价于最小化 \(\mathbb E[\alpha\log\pi(a|s)-Q(s,a)]\),梯度靠重参数化(19.1 节)穿过采样。

    下图把状态拿掉,只看一个固定的 \(Q(a)\):抓取一个物体有两个好的接近角度,左边的稍好(1.0),右边的稍差(0.8)。拖动 \(\alpha\),看玻尔兹曼目标怎么变;按"训练",看单峰的演员怎样去拟合它。

    Besides the reward, every step also rewards the policy's entropy \(\mathcal H\) (Lesson 4.11): stay random among equally good actions. The temperature \(\alpha\) sets the price of entropy. The optimal policy of this "soft" objective is the Boltzmann distribution of the Q-values: it tends to \(\arg\max\) as \(\alpha\to0\) and becomes nearly uniform for large \(\alpha\). SAC's actor is a tanh-squashed Gaussian (it outputs \(\mu,\log\sigma\), and \(a=\tanh(\mu+\sigma\varepsilon)\)); in each state it minimizes \(\mathrm{KL}\big(\pi\,\|\,\pi^\star\big)\), which is the same as minimizing \(\mathbb E[\alpha\log\pi(a|s)-Q(s,a)]\), with the gradient passed through the sampling by reparameterization (Lesson 19.1).

    The figure drops the state and looks at one fixed \(Q(a)\): there are two good approach angles for grasping an object, the left one slightly better (1.0) and the right one slightly worse (0.8). Drag \(\alpha\) to see how the Boltzmann target changes; press "Train" to watch a single-peaked actor fit it.

    FIG 4软策略与温度 αThe soft policy and the temperature α
    动作 a(接近角度,归一化)ACTION a (approach angle, normalized)
    蓝线是 \(Q(a)\)(右侧刻度),绿色填充是软最优策略 \(\pi^\star\propto e^{Q/\alpha}\),琥珀色填充是演员(tanh 高斯)的密度,两者共用左侧刻度。紫色空心圆是演员的起点:拖动它会把演员重置到那里(标准差 0.5)。每步用 64 个重参数化样本做一次 Adam。读数里的熵和 KL 是用数值积分精确算的,不是采样估计。打开"自动 α"后,温度按 \(\min_\alpha\mathbb E[-\alpha(\log\pi+\bar{\mathcal H})]\) 自己调节,使演员的熵逼近目标熵 \(\bar{\mathcal H}\)。 The blue line is \(Q(a)\) (right scale), the green fill is the soft-optimal policy \(\pi^\star\propto e^{Q/\alpha}\), and the amber fill is the actor's (tanh-Gaussian) density, both on the left scale. The hollow purple circle is the actor's start: dragging it resets the actor there (standard deviation 0.5). Each step is one Adam update on 64 reparameterized samples. The entropy and KL in the readout are computed exactly by quadrature, not estimated from samples. With "auto α" on, the temperature adjusts itself by \(\min_\alpha\mathbb E[-\alpha(\log\pi+\bar{\mathcal H})]\) so that the actor's entropy approaches the target \(\bar{\mathcal H}\).
    试一试Try this
    • 保持 \(\alpha\le0.05\)(不开自动 α),把紫色起点拖到 \(a\ge0.6\)(右边那个稍差的峰上),训练至少 300 步。演员会翻过去找左边更好的峰吗?KL 是多少?Keep \(\alpha\le0.05\) (auto α off), drag the purple start to \(a\ge0.6\) (onto the slightly worse right peak) and train for at least 300 steps. Does the actor cross over to the better left peak? What is the KL?
    • 把 \(\alpha\) 调到 0.3 以上并训练至少 200 步:演员的熵超过 0.5,同时罩住两个峰。这时玻尔兹曼目标长什么样?Raise \(\alpha\) above 0.3 and train for at least 200 steps: the actor's entropy exceeds 0.5 and it covers both peaks. What does the Boltzmann target look like now?
    • 打开"自动 α",目标熵选 −1.5,训练到演员的熵连续 100 步都在目标的 ±0.1 以内。\(\alpha\) 最后停在多少?Turn on "auto α" with target entropy −1.5 and train until the actor's entropy stays within ±0.1 of the target for 100 consecutive steps. Where does \(\alpha\) settle?

    两件事值得记住。第一,\(\mathrm{KL}(\pi\|\pi^\star)\) 是寻模(mode-seeking)的:单峰的演员只会选一个峰,从右边出发就停在右边(\(\alpha=0.05\) 时 KL ≈ 3.7,而停在左峰时低于 0.1),这是 tanh 高斯表达能力的限制,也是 19.3 节提到用 flow 做策略的动机。第二,好的 \(\alpha\) 取决于奖励的尺度:奖励乘以 10,同样的 \(\alpha\) 就相当于小了 10 倍。这正是自动温度的用处:与其猜 \(\alpha\),不如指定"想要多少熵"(默认 \(\bar{\mathcal H}=-\dim\mathcal A\)),让 \(\alpha\) 自己去满足它。

    SAC 的第二个部件对付 20.2 节的老问题:高估。评论家有误差,演员又专门去找 Q 最大的动作,于是它找到的往往是误差最大的地方,\(\mathbb E[\max_a\hat Q]\ge\max_a\mathbb E[\hat Q]\)。这个虚高被写进下一次的自举目标,一步步累积。TD3 和 SAC 的对策是训练两个独立初始化的评论家,目标里取较小值。下图把这件事单独拿出来看:真实的 \(Q(s',a)\) 是一条最大值为 1 的抛物线,两个评论家各自加上一条随机的平滑误差曲线(标准差 \(\sigma\),"粗糙度"是误差曲线的最高频率)。

    Two things are worth remembering. First, \(\mathrm{KL}(\pi\|\pi^\star)\) is mode-seeking: a single-peaked actor picks one peak, and starting on the right it stays on the right (at \(\alpha=0.05\) the KL is about 3.7, against less than 0.1 on the left peak). That is a limit of the tanh-Gaussian's expressiveness, and the motivation for flow-based policies mentioned in Lesson 19.3. Second, a good \(\alpha\) depends on the scale of the reward: multiply the reward by 10 and the same \(\alpha\) is effectively 10 times smaller. That is what automatic temperature is for: instead of guessing \(\alpha\), specify how much entropy you want (by default \(\bar{\mathcal H}=-\dim\mathcal A\)) and let \(\alpha\) adjust to deliver it.

    SAC's second component addresses an old problem from Lesson 20.2: overestimation. The critic has errors and the actor deliberately seeks the action with the largest Q, so it tends to find where the error is largest: \(\mathbb E[\max_a\hat Q]\ge\max_a\mathbb E[\hat Q]\). The inflated value is written into the next bootstrap target and accumulates step by step. TD3 and SAC train two independently initialized critics and take the smaller one in the target. The figure isolates this effect: the true \(Q(s',a)\) is a parabola with maximum 1, and each of two critics adds its own random smooth error curve (standard deviation \(\sigma\); "roughness" is the highest frequency in the error curve).

    FIG 5高估与双评论家Overestimation and twin critics
    一次抽样:真实 Q 与两个评论家ONE DRAW · true Q and two critics
    400 次抽样:目标值的误差分布400 DRAWS · error of the target value
    左:绿线是真实的 \(Q(s',a)\),红线是评论家 1,蓝线是评论家 2,琥珀色虚线是两者的较小值。演员选评论家 1 最大的动作 \(a^\star\)(红色竖线);红色实心点是单评论家给出的目标值 \(\hat Q_1(a^\star)\),琥珀色实心点是双评论家的 \(\min(\hat Q_1,\hat Q_2)(a^\star)\),绿色空心圆是真实最大值。右:400 次独立抽样下,两种目标值减去真实最大值 1 的直方图(红 = 单评论家,琥珀 = 双评论家),竖线是均值。 Left: the green line is the true \(Q(s',a)\), red is critic 1, blue is critic 2 and the amber dashed line their minimum. The actor picks the action \(a^\star\) where critic 1 is largest (red vertical line); the filled red dot is the single-critic target \(\hat Q_1(a^\star)\), the filled amber dot the twin target \(\min(\hat Q_1,\hat Q_2)(a^\star)\), and the hollow green circle the true maximum. Right: over 400 independent draws, histograms of the two targets minus the true maximum 1 (red = single critic, amber = twin), with vertical lines at the means.
    试一试Try this
    • 把误差 \(\sigma\) 调到 0.3 以上、粗糙度调到 10 以上(坑坑洼洼的评论家):单评论家的平均高估超过 0.2,而双评论家的平均值低于 0。Set the error \(\sigma\) above 0.3 and the roughness above 10 (a bumpy critic): the single critic overestimates by more than 0.2 on average, while the twin average is below 0.
    • 保持 \(\sigma\ge0.3\),把粗糙度降到 2 或以下(误差几乎是一个常数偏移):单评论家的平均误差不到双评论家低估量的一半,而双评论家低估超过 0.1。为什么?Keep \(\sigma\ge0.3\) and lower the roughness to 2 or less (the error is nearly a constant offset): the single critic's mean error is less than half of the twin's underestimate, and the twin underestimates by more than 0.1. Why?

    高估来自"挑选":误差越崎岖,演员越容易挑中一个虚高的尖峰(\(\sigma=0.3\)、粗糙度 12 时单评论家平均高估约 0.30,双评论家约 \(-0.12\))。取两个独立估计的较小值把它压了下去,代价是系统性地偏低:两个独立 \(\mathcal N(0,\sigma^2)\) 误差的较小值,期望是 \(-\sigma/\sqrt\pi\approx-0.56\sigma\)。低估比高估好,因为演员不会去"利用"一个被低估的动作。真实系统里两个评论家用同样的数据和目标训练,误差是相关的,低估比这里温和。

    最后把完整的 SAC 放到同一个关节任务上。只有一个环境(像一台真机),前 400 步随机动作预热,之后每走一步就从重放缓冲区(容量 20 000)抽 32 个转移,做一次评论家更新和一次演员更新;目标网络用 \(\tau=0.02\) 的 Polyak 平均跟随;自动温度,目标熵 \(-1\);网络大小与 PPO 相同。右图同时画出 PPO 在 \(N=16\) 与 \(N=64\) 下的参考曲线(种子 1,与 FIG 3 同一份代码),以及你在 FIG 3 里最近一次的 PPO 训练。

    Overestimation comes from selection: the more rugged the error, the more easily the actor picks an inflated spike (at \(\sigma=0.3\) and roughness 12 the single critic overestimates by about 0.30 on average, the twin by about \(-0.12\)). Taking the smaller of two independent estimates pushes this down, at the price of a systematic low bias: the minimum of two independent \(\mathcal N(0,\sigma^2)\) errors has expectation \(-\sigma/\sqrt\pi\approx-0.56\sigma\). Underestimation is the lesser evil because the actor never "exploits" an underestimated action. In a real system the two critics are trained on the same data and targets, so their errors are correlated and the underestimation is milder than here.

    Finally, run full SAC on the same joint task. There is one environment (like a real robot). The first 400 steps use random actions as warm-up; after that, every environment step draws 32 transitions from the replay buffer (capacity 20,000) for one critic update and one actor update; target networks follow by Polyak averaging with \(\tau=0.02\); the temperature is automatic with target entropy \(-1\); the networks are the same size as PPO's. The right panel also shows PPO reference curves for \(N=16\) and \(N=64\) (seed 1, the same code as FIG 3) and your latest PPO run from FIG 3.

    FIG 6SAC 实时训练,与 PPO 比较SAC training live, compared with PPO
    唯一的训练环境(加速显示)THE ONE TRAINING ENV (sped up)
    评估误差(°)vs 横轴(均为对数)EVAL ERROR (°) vs x (both log)
    左:SAC 正在采数据的那一个环境,琥珀色是手臂,绿色虚线是目标;底部条是重放缓冲区的填充程度。它的速度取决于训练有多快,比真实时间快。右:琥珀色 = SAC(每 250 步评估一次),紫色虚线 = PPO \(N=16\),青色虚线 = PPO \(N=64\),红色虚线 = 你在 FIG 3 的 PPO(若有)。右上角切换横轴:环境步数(真机要付出的代价)或并行仿真步数(所有并行环境同时前进一步记为 1,PPO 为 环境步数 ÷ \(N\),单环境的 SAC 不变)。评估与 FIG 3 相同。 Left: the single environment SAC is collecting data in; amber is the arm and the green dashed line the target; the bar at the bottom shows how full the replay buffer is. It runs as fast as training allows, faster than real time. Right: amber = SAC (evaluated every 250 steps), purple dashed = PPO \(N=16\), cyan dashed = PPO \(N=64\), red dashed = your PPO run from FIG 3 (if any). The top-right selector switches the horizontal axis between environment steps (the cost on a real robot) and parallel sim steps (one step of all parallel environments counts as 1: environment steps ÷ \(N\) for PPO, unchanged for single-environment SAC). Evaluation is the same as in FIG 3.
    试一试Try this
    • 按"训练",让 SAC 在 3000 个环境步以内把评估误差降到 8° 以下。PPO(\(N=16\))第一次降到 8° 以下用了多少步?Press "Train" and get SAC's evaluation error below 8° within 3000 environment steps. How many steps did PPO (\(N=16\)) need to first get below 8°?
    一个任务,两种代价One task, two prices

    种子 1 下,SAC 在约 1000 个环境步(其中 400 步是随机预热)时误差第一次低于 8°,种子 1–6 都在 1000–1750 步之间;PPO \(N=16\) 要 4480 步,\(N=64\) 要 12 800 步。按环境步数算,SAC 在这个小任务上省了几倍到十几倍的数据。但 SAC 之后一直在晃,多数时候在 3°–15° 之间,而 PPO 能稳定到 1° 左右:价值梯度给出的动作修正很小又带噪声。换成并行仿真步数,PPO \(N=64\) 只要 240 步(6 次迭代 × 40)就低于 3°,SAC 一步也没法并行。这就是选算法时最重要的问题:你付的是样本,还是时间?

    With seed 1, SAC first drops below 8° at about 1000 environment steps (400 of them random warm-up), and seeds 1–6 all land between 1000 and 1750; PPO needs 4480 steps with \(N=16\) and 12,800 with \(N=64\). Counted in environment steps, SAC saves a factor of several to over ten on this small task. But afterwards SAC keeps wobbling, mostly between 3° and 15°, while PPO settles near 1°: the action corrections from a value gradient are small and noisy. Counted in parallel sim steps, PPO with \(N=64\) is below 3° after only 240 of them (6 iterations × 40), while SAC cannot parallelize a single step. That is the most important question when choosing: are you paying in samples or in time?

    5再看数学The math

    提示:把鼠标悬停在公式中带底色的符号上,对应的图元素会被高亮:\(\lambda\) 加粗 FIG 1 右图的 λ 竖线,\(V_\phi\) 放大 FIG 1 的紫色圆,\(\delta_t\) 加粗 FIG 1 的直方图,\(\rho_t\) 放大 FIG 2 下图的样本点,clip 加粗 FIG 2 的 \(L^{\text{CLIP}}\) 曲线与 \(1\pm\epsilon\) 线,\(\alpha\) 加粗 FIG 4 的绿色目标,\(\mathcal H\) 加粗 FIG 4 的琥珀色演员,\(Q\) 加粗 FIG 4 的蓝线,min 加粗 FIG 5 的琥珀色虚线。Tip: hover the highlighted symbols in the formulas and the matching figure element lights up: \(\lambda\) thickens the λ line in FIG 1 (right), \(V_\phi\) enlarges FIG 1's purple circles, \(\delta_t\) outlines FIG 1's histogram, \(\rho_t\) enlarges the sample dots in FIG 2 (bottom), clip thickens FIG 2's \(L^{\text{CLIP}}\) curve and the \(1\pm\epsilon\) lines, \(\alpha\) thickens FIG 4's green target, \(\mathcal H\) thickens FIG 4's amber actor, \(Q\) thickens FIG 4's blue line, and min thickens FIG 5's amber dashed line.

    策略梯度里的优势,与评论家的损失The advantage in the policy gradient, and the critic's loss

    20.3 节的策略梯度定理可以写成优势的形式:\(\nabla_\theta J=\mathbb E\big[\sum_t\nabla_\theta\log\pi_\theta(a_t|s_t)\,A^\pi(s_t,a_t)\big]\)。任何满足 \(\mathbb E[\hat A_t|s_t,a_t]\approx A^\pi(s_t,a_t)\) 的估计都可以代入。TD 误差满足 \(\mathbb E[\delta_t|s_t,a_t]=\mathbb E[r_{t+1}|s_t,a_t]+\gamma\mathbb E[V(s_{t+1})]-V(s_t)=Q^\pi-V^\pi=A^\pi\),前提是 \(V=V^\pi\)。把 \(k\) 步的估计 \(\hat A_t^{(k)}=\sum_{l<k}\gamma^l r_{t+l+1}+\gamma^kV(s_{t+k})-V(s_t)=\sum_{l<k}\gamma^l\delta_{t+l}\)(裂项相消)按权重 \((1-\lambda)\lambda^{k-1}\) 平均,就得到 GAE:

    Lesson 20.3's policy gradient theorem can be written with the advantage: \(\nabla_\theta J=\mathbb E\big[\sum_t\nabla_\theta\log\pi_\theta(a_t|s_t)\,A^\pi(s_t,a_t)\big]\). Any estimate with \(\mathbb E[\hat A_t|s_t,a_t]\approx A^\pi(s_t,a_t)\) can be plugged in. The TD error satisfies \(\mathbb E[\delta_t|s_t,a_t]=\mathbb E[r_{t+1}|s_t,a_t]+\gamma\mathbb E[V(s_{t+1})]-V(s_t)=Q^\pi-V^\pi=A^\pi\), provided \(V=V^\pi\). Averaging the \(k\)-step estimates \(\hat A_t^{(k)}=\sum_{l<k}\gamma^l r_{t+l+1}+\gamma^kV(s_{t+k})-V(s_t)=\sum_{l<k}\gamma^l\delta_{t+l}\) (the sum telescopes) with weights \((1-\lambda)\lambda^{k-1}\) gives GAE:

    $$ \hat A_t=\sum_{l\ge0}(\gamma\hl{lam}{\lambda})^l\hl{delta}{\delta_{t+l}}=\hl{delta}{\delta_t}+\gamma\hl{lam}{\lambda}\,\hat A_{t+1},\qquad \hat G_t=\hat A_t+\hl{Vhat}{V_\phi}(s_t),\qquad L_V(\phi)=\hat{\mathbb E}_t\big[(V_\phi(s_t)-\hat G_t)^2\big]. $$

    右边的递推就是代码里从轨迹末尾往回扫的那一行。\(\hat G_t\) 叫 \(\lambda\)-回报,评论家对它做回归(PPO 的做法)。如果回合因为时间上限被截断而不是真的结束,最后一步要用 \(V_\phi(s_T)\) 自举,而不是当作 0(误区 1);本页的关节任务就是这样处理的。FIG 1 的精确均值和方差来自两条递推:设 \(c=r+\gamma(1-\lambda)V_\phi(s')\),则 \(G=c+\gamma\lambda G'\),于是 \(U(s)=\mathbb E[G|s]=\mathbb E[c+\gamma\lambda U(s')]\),\(W(s)=\mathbb E[G^2|s]=\mathbb E[c^2+2c\gamma\lambda U(s')+\gamma^2\lambda^2W(s')]\),都是压缩映射,迭代即收敛。

    The recursion on the right is the one line in the code that sweeps backward from the end of a trajectory. \(\hat G_t\) is the \(\lambda\)-return, and the critic regresses onto it (as PPO does). If an episode is cut by a time limit rather than truly ending, the last step must bootstrap with \(V_\phi(s_T)\) instead of treating it as 0 (Pitfall 1); the joint task on this page does exactly that. FIG 1's exact mean and variance come from two recursions: with \(c=r+\gamma(1-\lambda)V_\phi(s')\) we have \(G=c+\gamma\lambda G'\), so \(U(s)=\mathbb E[G|s]=\mathbb E[c+\gamma\lambda U(s')]\) and \(W(s)=\mathbb E[G^2|s]=\mathbb E[c^2+2c\gamma\lambda U(s')+\gamma^2\lambda^2W(s')]\); both are contractions and converge by iteration.

    从信赖域到截断:PPOFrom trust regions to clipping: PPO

    为什么"别离旧策略太远"是对的?性能差引理(Kakade & Langford,2002)给出精确的改进量:

    Why is "do not stray far from the old policy" the right rule? The performance difference lemma (Kakade & Langford, 2002) gives the exact improvement:

    $$ J(\pi')-J(\pi)=\frac{1}{1-\gamma}\,\mathbb E_{s\sim d^{\pi'}}\,\mathbb E_{a\sim\pi'}\big[A^\pi(s,a)\big]\;\approx\;\frac{1}{1-\gamma}\,\mathbb E_{s\sim d^{\pi}}\,\mathbb E_{a\sim\pi}\big[\hl{ratio}{\rho(\theta)}\,A^\pi(s,a)\big]. $$

    右边把新策略的状态分布 \(d^{\pi'}\) 换成旧的 \(d^\pi\),于是可以用旧数据估计,这就是代理目标 \(L^{\text{PG}}\);只有当 \(\pi'\) 离 \(\pi\) 不远时这个替换才可靠(状态分布的差距可以用两策略间的 KL 来界定)。TRPO(Schulman 等,2015)直接求解带约束的问题 \(\max L^{\text{PG}}\ \text{s.t.}\ \mathbb E_s[\mathrm{KL}(\pi_{\theta_k}\|\pi_\theta)]\le\delta\),需要共轭梯度和线搜索。PPO 用 \(\min(\rho\hat A,\operatorname{clip}(\rho)\hat A)\) 的一阶近似代替约束,只要普通的小批量 SGD。完整的损失通常是

    The right-hand side replaces the new policy's state distribution \(d^{\pi'}\) by the old one \(d^\pi\), so it can be estimated from old data: that is the surrogate \(L^{\text{PG}}\). The replacement is reliable only while \(\pi'\) stays close to \(\pi\) (the gap in state distributions can be bounded by the KL between the policies). TRPO (Schulman et al., 2015) solves the constrained problem \(\max L^{\text{PG}}\ \text{s.t.}\ \mathbb E_s[\mathrm{KL}(\pi_{\theta_k}\|\pi_\theta)]\le\delta\) directly, with conjugate gradients and a line search. PPO replaces the constraint with the first-order device \(\min(\rho\hat A,\operatorname{clip}(\rho)\hat A)\) and needs only ordinary minibatch SGD. The full loss is usually

    $$ \mathcal L(\theta,\phi)=-L^{\text{CLIP}}(\theta)+c_1\,L_V(\phi)-c_2\,\hat{\mathbb E}_t\big[\mathcal H(\pi_\theta(\cdot|s_t))\big],\qquad \log\pi_\theta(a|s)=-\frac{(a-\mu_\theta(s))^2}{2\sigma^2}-\log\sigma-\tfrac12\log2\pi . $$

    逐个样本看 \(\min(\rho\hat A,\operatorname{clip}(\rho,1-\epsilon,1+\epsilon)\hat A)\):\(\hat A>0\) 时它等于 \(\min(\rho,1+\epsilon)\hat A\),\(\rho>1+\epsilon\) 后对 \(\theta\) 的梯度为 0;\(\hat A<0\) 时它等于 \(\max(\rho,1-\epsilon)\hat A\),\(\rho<1-\epsilon\) 后梯度为 0。另一侧(\(\hat A>0\) 而 \(\rho<1-\epsilon\),或 \(\hat A<0\) 而 \(\rho>1+\epsilon\))仍是 \(\rho\hat A\),梯度照常把策略拉回来,这正是 FIG 2 下图里两条曲线的形状。本页 PPO 的 \(c_2=0\),演员和评论家分开两个网络;读数中的 KL 用估计式 \(\hat{\mathbb E}[(\rho-1)-\log\rho]\),它对每个样本都非负。

    Look at \(\min(\rho\hat A,\operatorname{clip}(\rho,1-\epsilon,1+\epsilon)\hat A)\) per sample: for \(\hat A>0\) it equals \(\min(\rho,1+\epsilon)\hat A\), whose gradient in \(\theta\) is 0 once \(\rho>1+\epsilon\); for \(\hat A<0\) it equals \(\max(\rho,1-\epsilon)\hat A\), with zero gradient once \(\rho<1-\epsilon\). On the other side (\(\hat A>0\) with \(\rho<1-\epsilon\), or \(\hat A<0\) with \(\rho>1+\epsilon\)) it is still \(\rho\hat A\) and the gradient pulls the policy back as usual: exactly the shape of the two curves in FIG 2's bottom panel. This page's PPO uses \(c_2=0\) and separate actor and critic networks; the readout's KL uses the estimator \(\hat{\mathbb E}[(\rho-1)-\log\rho]\), which is non-negative for every sample.

    软 Bellman 方程与 SAC 的三个损失The soft Bellman equation and SAC's three losses

    在最大熵目标下,价值里也要算上未来的熵,于是有软 Bellman 方程 \(Q(s,a)=r+\gamma\,\mathbb E_{s'}[V(s')]\),\(V(s)=\mathbb E_{a\sim\pi}[Q(s,a)-\alpha\log\pi(a|s)]\)。SAC 用两个评论家 \(Q_{\phi_1},Q_{\phi_2}\)、它们的目标网络 \(\bar\phi_j\leftarrow\tau\phi_j+(1-\tau)\bar\phi_j\) 和重放缓冲区 \(\mathcal D\):

    Under the maximum-entropy objective the value also counts future entropy, which gives the soft Bellman equation \(Q(s,a)=r+\gamma\,\mathbb E_{s'}[V(s')]\), \(V(s)=\mathbb E_{a\sim\pi}[Q(s,a)-\alpha\log\pi(a|s)]\). SAC uses two critics \(Q_{\phi_1},Q_{\phi_2}\), their target networks \(\bar\phi_j\leftarrow\tau\phi_j+(1-\tau)\bar\phi_j\), and a replay buffer \(\mathcal D\):

    $$ \begin{aligned} y&=r+\gamma\Big(\hl{min}{\min_{j=1,2}}Q_{\bar\phi_j}(s',\tilde a')-\hl{alpha}{\alpha}\log\pi_\theta(\tilde a'|s')\Big),\quad \tilde a'\sim\pi_\theta(\cdot|s'), & L_Q(\phi_j)&=\mathbb E_{\mathcal D}\big[(Q_{\phi_j}(s,a)-y)^2\big],\\ L_\pi(\theta)&=\mathbb E_{s\sim\mathcal D,\ \varepsilon}\Big[\hl{alpha}{\alpha}\log\pi_\theta(\tilde a|s)-\hl{min}{\min_j}\hl{Qa}{Q_{\phi_j}(s,\tilde a)}\Big],\quad \tilde a=\tanh(\mu_\theta(s)+\sigma_\theta(s)\varepsilon), & L(\alpha)&=\mathbb E\big[-\alpha\big(\log\pi_\theta(\tilde a|s)+\bar{\mathcal H}\big)\big]. \end{aligned} $$

    目标 \(y\) 里的 \(\tilde a'\) 是从当前策略新采的,不是缓冲区里存的旧动作,这就是它能异策略的原因:Bellman 方程只需要 \((s,a,r,s')\),而 \(s'\) 之后的行为由当前策略决定。tanh 压缩改变了密度,要加上雅可比修正 \(\log\pi(a|s)=\log\mathcal N(u;\mu,\sigma^2)-\log(1-\tanh^2u)\)。演员损失对 \(\theta\) 的梯度通过 \(\tilde a\) 传进评论家(\(\partial Q/\partial a\)),这就是"价值梯度":动作沿着 Q 增大的方向被推。温度损失的梯度 \(-(\log\pi+\bar{\mathcal H})\) 在熵低于目标时让 \(\alpha\) 增大,反之减小(本页用 \(\log\alpha\) 作参数)。

    The \(\tilde a'\) in the target \(y\) is freshly sampled from the current policy, not the old action stored in the buffer; that is why the method is off-policy: the Bellman equation only needs \((s,a,r,s')\), and what happens after \(s'\) is decided by the current policy. The tanh squashing changes the density and needs the Jacobian correction \(\log\pi(a|s)=\log\mathcal N(u;\mu,\sigma^2)-\log(1-\tanh^2u)\). The actor loss's gradient in \(\theta\) flows through \(\tilde a\) into the critic (\(\partial Q/\partial a\)): this is the "value gradient", pushing the action in the direction in which Q grows. The temperature loss's gradient \(-(\log\pi+\bar{\mathcal H})\) raises \(\alpha\) when the entropy is below the target and lowers it otherwise (this page parameterizes \(\log\alpha\)).

    为什么演员损失是 KL?对固定状态,\(\mathrm{KL}(\pi\|\pi^\star)=\mathbb E_\pi[\log\pi-Q/\alpha]+\log Z=\tfrac1\alpha\mathbb E_\pi[\alpha\log\pi-Q]+\log Z\),\(\log Z\) 与 \(\theta\) 无关,所以两者最小值相同。FIG 4 的读数正是这样算 KL 的。

    Why is the actor loss a KL? For a fixed state, \(\mathrm{KL}(\pi\|\pi^\star)=\mathbb E_\pi[\log\pi-Q/\alpha]+\log Z=\tfrac1\alpha\mathbb E_\pi[\alpha\log\pi-Q]+\log Z\), and \(\log Z\) does not depend on \(\theta\), so both have the same minimizer. FIG 4's readout computes the KL exactly this way.

    TD3:确定性演员的三个技巧TD3: three tricks for a deterministic actor

    DDPG 的演员是确定性的 \(a=\mu_\theta(s)\),由确定性策略梯度 \(\nabla_\theta J=\mathbb E_s\big[\nabla_aQ(s,a)|_{a=\mu_\theta(s)}\nabla_\theta\mu_\theta(s)\big]\)(Silver 等,2014)更新,探索靠给动作加噪声。它在实践中很容易被评论家的高估带偏。TD3(Fujimoto 等,2018)加了三个修正:(1) 截断双 Q:目标取两个评论家的较小值(FIG 5);(2) 目标策略平滑:目标里的动作加上截断的高斯噪声 \(\tilde a'=\mu_{\bar\theta}(s')+\operatorname{clip}(\mathcal N(0,\tilde\sigma^2),-c,c)\),让评论家在动作邻域里平滑,不给尖峰留机会;(3) 延迟更新:评论家每更新 2 次,演员和目标网络才更新 1 次。SAC 也用第 (1) 条(两篇论文几乎同时发表);它的随机策略和熵项起到了与 (2) 类似的平滑作用。

    DDPG's actor is deterministic, \(a=\mu_\theta(s)\), updated by the deterministic policy gradient \(\nabla_\theta J=\mathbb E_s\big[\nabla_aQ(s,a)|_{a=\mu_\theta(s)}\nabla_\theta\mu_\theta(s)\big]\) (Silver et al., 2014), with exploration from noise added to the action. In practice it is easily led astray by the critic's overestimation. TD3 (Fujimoto et al., 2018) adds three fixes: (1) clipped double Q: the target takes the smaller of two critics (FIG 5); (2) target policy smoothing: the target action gets clipped Gaussian noise, \(\tilde a'=\mu_{\bar\theta}(s')+\operatorname{clip}(\mathcal N(0,\tilde\sigma^2),-c,c)\), so the critic is smooth over a neighbourhood of actions and spikes have no room; (3) delayed updates: the actor and the target networks are updated once per 2 critic updates. SAC uses the same fix (1) (the two papers appeared at almost the same time); its stochastic policy and entropy term smooth the target much like (2).

    6机器人中的它:什么时候用哪一个In robotics: when to use which

    FIG 6 的结论可以推广:先问数据从哪里来、付的是样本还是时间。

    The conclusion of FIG 6 generalizes: first ask where the data comes from, and whether you pay in samples or in time.

    PPOSAC
    数据Data同策略:每批只用 \(K\) 轮就扔掉On-policy: each batch is used for \(K\) epochs, then discarded异策略:重放缓冲区,每个样本被反复使用Off-policy: replay buffer, every sample reused many times
    并行Parallelism天然适合几千个并行环境,大批量、少迭代Natural fit for thousands of parallel envs: large batches, few iterations每个环境步配一次(或几次)梯度更新,难以大规模并行One (or a few) gradient updates per env step; hard to parallelize at scale
    动作Actions离散或连续都行Discrete or continuous为连续动作设计(有离散变体)Designed for continuous actions (discrete variants exist)
    稳定性Stability稳,对超参数相对不敏感;但实现细节影响很大Stable and fairly robust to hyperparameters, though implementation details matter a lot评论家的自举可能失稳;自动温度和双 Q 让它比 DDPG 稳得多Critic bootstrapping can diverge; automatic temperature and twin Q make it far steadier than DDPG
    典型用途Typical useGPU 并行仿真中的腿式运动、灵巧手,然后 sim-to-realLegged locomotion and dexterous hands in GPU-parallel simulation, then sim-to-real直接在真机上学习、样本昂贵的任务;离线到在线的微调Learning directly on hardware, tasks where samples are expensive; offline-to-online fine-tuning
    真实系统里In real systems

    PPO + 大规模并行仿真:Rudin、Hoeller、Reist 与 Hutter(CoRL 2021)在单张 GPU 上同时仿真数千个 ANYmal 四足机器人,用 PPO 在 4 分钟以内学会平地行走、约 20 分钟学会崎岖地形,并迁移到真机;他们开源的 legged_gym 和 rsl_rl 成了后来很多腿式与人形机器人工作的起点,如今在 Isaac Lab 中延续(rsl_rl 默认用 \(\epsilon=0.2\)、\(\lambda=0.95\),并按目标 KL 自适应调学习率)。OpenAI 的灵巧手魔方实验(2019)也用 PPO 在大规模随机化仿真中训练(9.3 节)。仿真里的评论家还可以看到真机拿不到的特权信息(地形高度、摩擦系数),只给演员用真实传感器,这就是非对称 actor-critic,详见 23.1 节。SAC 直接在真机上学:Haarnoja、Ha、Zhou、Tan、Tucker 与 Levine(RSS 2019)用带自动温度的 SAC 让 Minitaur 四足机器人在真实世界里从零学会行走,大约用了 2 小时的真机数据;Smith、Kostrikov 与 Levine(arXiv 2022,RSS 2023)用每个环境步做多次评论家更新的同类异策略方法,让 A1 四足在约 20 分钟的真机训练里学会在多种地面上行走。软件:Stable-Baselines3 与 CleanRL 提供 PPO、SAC、TD3 的参考实现;rsl_rl、rl_games、skrl 面向 GPU 并行仿真。往后看:从固定数据集学习时,异策略评论家会被数据外的动作骗到,这是 20.5 节的主题;把评论家和学到的世界模型结合起来,就是 24.3 节的 Dreamer 与 TD-MPC。

    PPO + massively parallel simulation: Rudin, Hoeller, Reist and Hutter (CoRL 2021) simulated thousands of ANYmal quadrupeds at once on a single GPU and used PPO to learn flat-terrain walking in under four minutes and rough terrain in about twenty, then transferred the policies to the real robot; their open-source legged_gym and rsl_rl became the starting point of much later legged and humanoid work and live on in Isaac Lab (rsl_rl defaults to \(\epsilon=0.2\), \(\lambda=0.95\), and adapts the learning rate to a target KL). OpenAI's Rubik's-cube hand (2019) was also trained with PPO in heavily randomized simulation (Lesson 9.3). In simulation the critic may also see privileged information the real robot lacks (terrain heights, friction coefficients) while the actor uses only real sensors: the asymmetric actor-critic of Lesson 23.1. SAC directly on hardware: Haarnoja, Ha, Zhou, Tan, Tucker and Levine (RSS 2019) used SAC with automatic temperature to teach a Minitaur quadruped to walk from scratch in the real world with about two hours of real data; Smith, Kostrikov and Levine (arXiv 2022, RSS 2023) used an off-policy method of the same family, with many critic updates per environment step, to teach an A1 quadruped to walk on several surfaces in about 20 minutes of real-world training. Software: Stable-Baselines3 and CleanRL provide reference PPO, SAC and TD3 implementations; rsl_rl, rl_games and skrl target GPU-parallel simulation. Looking ahead: when learning from a fixed dataset, an off-policy critic is fooled by actions outside the data, the topic of Lesson 20.5; combining a critic with a learned world model gives the Dreamer and TD-MPC of Lesson 24.3.

    7常见误区Common pitfalls

    误区 1:把时间上限当成终止状态Pitfall 1: treating a time limit as a terminal state

    机器人仿真几乎总有回合时长上限(本页是 2 秒)。时间到了,机器人并没有"死",它此后的价值不是 0。如果在 GAE 或 SAC 的目标里把这一步当成终止(乘以 \(1-\text{done}\)),评论家就会学到"快到 2 秒时价值突然跳变"(本页奖励为负,跳向 0),而它的输入里根本没有时间,只能把这种噪声抹平到所有状态上。正确做法是区分 terminated(真的结束:摔倒、到达)与 truncated(时间到),对后者照常用 \(V(s_T)\) 或 \(Q(s',\tilde a')\) 自举。Gymnasium 的 step 返回值就是这样把两者分开的。

    Robot simulations almost always have an episode time limit (2 seconds on this page). When time runs out the robot has not "died", and its future value is not 0. If GAE or the SAC target treats that step as terminal (multiplying by \(1-\text{done}\)), the critic learns that "value jumps near 2 seconds" (towards 0 here, where rewards are negative), but time is not among its inputs, so it can only smear this noise over every state. The fix is to separate terminated (a real end: a fall, reaching a goal) from truncated (time is up), and to keep bootstrapping with \(V(s_T)\) or \(Q(s',\tilde a')\) for the latter. Gymnasium's step returns the two flags separately for exactly this reason.

    误区 2:以为截断把概率比限制在 \(1\pm\epsilon\) 内Pitfall 2: thinking clipping keeps the ratio inside \(1\pm\epsilon\)

    截断只让超出范围的那些样本不再贡献梯度;神经网络是共享参数的,其余样本的梯度照样会把被截断样本的概率继续推远。FIG 3 读数里的"最大概率比"即使在 \(\epsilon=0.2\) 时也通常在 1.5 到 4 之间,偶尔超过 10,远在 \(1.2\) 之外。轮数 \(K\) 越多、学习率越大,越明显。所以实践里要监控每次迭代的 KL:rsl_rl 按目标 KL 调学习率,另一些实现在 KL 超过阈值时提前停止这一批的训练。

    Clipping only stops the out-of-range samples from contributing gradient; the network shares parameters, so the gradients of the remaining samples keep pushing the clipped samples' probabilities further. Even at \(\epsilon=0.2\) the "max ratio" in FIG 3's readout is usually between 1.5 and 4 and now and then above 10, far outside \(1.2\). The more epochs \(K\) and the larger the learning rate, the worse. So in practice you monitor the KL per iteration: rsl_rl adapts the learning rate to a target KL, and other implementations stop training on a batch early once the KL crosses a threshold.

    误区 3:忽略奖励和观测的尺度Pitfall 3: ignoring the scale of rewards and observations

    SAC 的固定 \(\alpha\) 是相对奖励尺度而言的:同一个 \(\alpha=0.2\),在每步奖励约为 1 的任务里是适度探索,在每步奖励约为 100 的任务里几乎等于没有熵项。PPO 对优势做了归一化,对奖励尺度不那么敏感,但评论家仍要回归原始尺度的回报,太大的回报会让价值损失主导梯度。常见做法:用自动温度;归一化观测(运行均值与方差);把奖励缩放到每步 \(O(1)\)。这些"细节"在 PPO 上影响很大(Engstrom 等,2020;Andrychowicz 等,2021)。

    SAC's fixed \(\alpha\) is relative to the reward scale: the same \(\alpha=0.2\) is moderate exploration when rewards are about 1 per step and practically no entropy bonus when they are about 100. PPO normalizes advantages and is less sensitive to reward scale, but its critic still regresses returns at the raw scale, and huge returns let the value loss dominate the gradient. Common practice: use automatic temperature, normalize observations (running mean and variance), and scale rewards to \(O(1)\) per step. Such "details" matter a lot for PPO (Engstrom et al., 2020; Andrychowicz et al., 2021).

    误区 4:认为双评论家"修好了"价值估计Pitfall 4: believing twin critics "fix" the value estimate

    取较小值把高估换成了低估(FIG 5 中约 \(-0.56\sigma\)),只是因为演员不会去追逐被低估的动作,这个偏差才比较无害。评论家仍然处在 20.2 节"致命三角"(函数逼近 + 自举 + 异策略)里:更新太快、目标网络跟得太紧、每步更新次数太多,都可能让 Q 值发散。监控评论家的 Q 估计与实际回报之差,是调 SAC 时最有用的诊断之一。

    Taking the minimum trades overestimation for underestimation (about \(-0.56\sigma\) in FIG 5); it is only fairly harmless because the actor does not chase underestimated actions. The critic still lives in the "deadly triad" of Lesson 20.2 (function approximation + bootstrapping + off-policy data): updating too fast, a target network that tracks too tightly, or too many updates per step can all make the Q-values diverge. Comparing the critic's Q estimates with the actual returns is one of the most useful diagnostics when tuning SAC.

    误区 5:用训练时的随机策略评估,或只看一种代价Pitfall 5: evaluating the noisy training policy, or counting only one cost

    PPO 和 SAC 训练时都在采样动作,部署时一般用均值动作(本页的评估曲线就是这样做的),两者的表现可能差得很多;报告结果时要说明用的是哪一个。比较算法时也要说明横轴:环境步数、并行仿真步数、梯度更新次数还是墙钟时间。FIG 6 里同一组曲线,换一个横轴,胜负就倒过来了。

    PPO and SAC both sample actions during training, while deployment usually takes the mean action (as this page's evaluation curves do), and the two can perform very differently; say which one you report. When comparing algorithms, also say what the horizontal axis is: environment steps, parallel sim steps, gradient updates, or wall-clock time. In FIG 6 the same curves swap winners when the axis changes.

    8小练习Check yourself

    1. 关于 GAE 的 \(\lambda\),下列哪个说法是对的?1. Which statement about GAE's \(\lambda\) is correct?
    选项 C。\(\lambda=0\) 时 \(\hat A_t=\delta_t\),只含一步随机性,但 \(V_\phi(s_{t+1})\) 的误差直接进入估计;\(\lambda=1\) 时 \(\hat A_t=G_t-V_\phi(s_t)\),评论家只作基线,没有偏差,方差最大。选项 A 和 B 正好把两端说反了。选项 D 错:FIG 1 中 \(\sigma_V=0\) 时偏差处处为 0,但方差从 0.32 增长到约 33。Option C. At \(\lambda=0\), \(\hat A_t=\delta_t\) contains one step of randomness, but the error in \(V_\phi(s_{t+1})\) enters directly; at \(\lambda=1\), \(\hat A_t=G_t-V_\phi(s_t)\) uses the critic only as a baseline, so it is unbiased with the largest variance. Options A and B swap the two ends. Option D is wrong: in FIG 1 with \(\sigma_V=0\) the bias is 0 everywhere but the variance grows from 0.32 to about 33.
    2. PPO 中某个样本的 \(\hat A_t=-1\),当前概率比 \(\rho_t=0.7\),\(\epsilon=0.2\)。这个样本对演员梯度的贡献是?2. In PPO a sample has \(\hat A_t=-1\) and current ratio \(\rho_t=0.7\), with \(\epsilon=0.2\). What does this sample contribute to the actor's gradient?
    选项 B。\(\min(\rho\hat A,\operatorname{clip}(\rho)\hat A)=\min(-0.7,-0.8)=-0.8\),取的是常数项,梯度为零:坏动作的概率已经降到旧值的 0.8 倍以下,这一批数据不再继续压它。选项 A 是不截断的 \(L^{\text{PG}}\) 的行为;选项 C 不会发生(在另一侧,即 \(\hat A<0\) 且 \(\rho>1+\epsilon\) 时,梯度是把概率往下压);评论家的损失与演员梯度无关。Option B. \(\min(\rho\hat A,\operatorname{clip}(\rho)\hat A)=\min(-0.7,-0.8)=-0.8\), the constant term, so the gradient is zero: the bad action's probability is already below 0.8 of its old value, and this batch stops pushing it. Option A is what the unclipped \(L^{\text{PG}}\) would do; option C does not happen (on the other side, \(\hat A<0\) with \(\rho>1+\epsilon\), the gradient pushes the probability down); the critic's loss does not enter the actor's gradient.
    3. 为什么 SAC 可以反复使用很久以前的数据,而 PPO 不能?3. Why can SAC keep reusing old data while PPO cannot?
    选项 D。软 Bellman 目标里下一步的动作 \(\tilde a'\) 从当前策略重新采样,旧转移 \((s,a,r,s')\) 本身不依赖策略;PPO 的 \(\rho_t\hat A_t\) 是重要性采样,离旧策略越远方差越大(FIG 2 的有效样本数),而且优势是相对旧策略算的。熵项与此无关(选项 B),PPO 当然有评论家(选项 C),网络大小也不是原因(选项 A)。Option D. In the soft Bellman target the next action \(\tilde a'\) is resampled from the current policy, and an old transition \((s,a,r,s')\) does not depend on the policy; PPO's \(\rho_t\hat A_t\) is importance sampling, whose variance grows as the policy moves away (FIG 2's effective sample size), and its advantages are relative to the old policy. The entropy term has nothing to do with it (option B), PPO certainly has a critic (option C), and network size is not the reason (option A).
    4. 两个评论家的误差独立、都无偏、标准差为 \(\sigma\)。在某个固定动作上取 \(\min(\hat Q_1,\hat Q_2)\),它的期望误差约是?4. Two critics have independent, unbiased errors with standard deviation \(\sigma\). At one fixed action, what is the expected error of \(\min(\hat Q_1,\hat Q_2)\)?
    选项 A。两个独立 \(\mathcal N(0,\sigma^2)\) 的较小值,期望为 \(-\sigma/\sqrt\pi\approx-0.564\sigma\),这就是 FIG 5 在粗糙度很低(误差接近常数偏移)时看到的低估。取最小是一个非线性操作,不保持无偏(选项 B)。TD3 与 SAC 接受这个低估,因为演员会利用高估、不会利用低估。Option A. The smaller of two independent \(\mathcal N(0,\sigma^2)\) variables has mean \(-\sigma/\sqrt\pi\approx-0.564\sigma\), the underestimate FIG 5 shows at low roughness (where the error is nearly a constant offset). Taking a minimum is nonlinear and does not preserve unbiasedness (option B). TD3 and SAC accept this underestimate because the actor exploits overestimates but not underestimates.
    5. 一个实验室只有一台真实的机械臂,大约能承受 1–2 小时的交互,没有可靠的仿真器。最自然的起点是?5. A lab has a single real robot arm, can afford about 1–2 hours of interaction, and has no reliable simulator. What is the most natural starting point?
    选项 B。只有一台真机时付的是样本,异策略方法反复利用每个样本,样本效率最高,这也是 Minitaur 和 A1 真机行走实验的路线。选项 A 需要几千个并行环境,只在仿真里才有;选项 C 方差最大、最费样本;选项 D 正是 FIG 3 里 KL 失控的设置。Option B. With one real robot you pay in samples, and an off-policy method that reuses every sample is the most sample-efficient; it is the route taken by the Minitaur and A1 real-world walking experiments. Option A needs thousands of parallel environments, which exist only in simulation; option C has the highest variance and wastes the most samples; option D is exactly the setting where FIG 3's KL runs away.

    9延伸阅读Further reading

    • R. S. Sutton & A. G. Barto, Reinforcement Learning: An Introduction, 2nd ed., MIT Press, 2018, Ch. 12–13 — 资格迹与 \(\lambda\)-回报、策略梯度与 actor-criticEligibility traces and \(\lambda\)-returns, policy gradients and actor-critic
    • V. R. Konda & J. N. Tsitsiklis, Actor-Critic Algorithms, NIPS 1999 — 两时间尺度 actor-critic 的经典分析The classic two-timescale analysis of actor-critic
    • S. Kakade & J. Langford, Approximately Optimal Approximate Reinforcement Learning, ICML 2002 — 性能差引理与保守策略迭代The performance difference lemma and conservative policy iteration
    • J. Schulman, S. Levine, P. Abbeel, M. Jordan & P. Moritz, Trust Region Policy Optimization, ICML 2015 — TRPO
    • J. Schulman, P. Moritz, S. Levine, M. Jordan & P. Abbeel, High-Dimensional Continuous Control Using Generalized Advantage Estimation, ICLR 2016 — GAE
    • J. Schulman, F. Wolski, P. Dhariwal, A. Radford & O. Klimov, Proximal Policy Optimization Algorithms, arXiv:1707.06347, 2017 — PPO
    • V. Mnih et al., Asynchronous Methods for Deep Reinforcement Learning, ICML 2016 — A3C/A2C:多个并行工作者的 actor-criticA3C/A2C: actor-critic with many parallel workers
    • D. Silver, G. Lever, N. Heess, T. Degris, D. Wierstra & M. Riedmiller, Deterministic Policy Gradient Algorithms, ICML 2014; T. P. Lillicrap et al., Continuous Control with Deep Reinforcement Learning, ICLR 2016 — DPG, DDPG
    • H. van Hasselt, Double Q-learning, NIPS 2010; S. Fujimoto, H. van Hoof & D. Meger, Addressing Function Approximation Error in Actor-Critic Methods, ICML 2018 — 高估与 TD3Overestimation and TD3
    • T. Haarnoja, A. Zhou, P. Abbeel & S. Levine, Soft Actor-Critic: Off-Policy Maximum Entropy Deep Reinforcement Learning with a Stochastic Actor, ICML 2018; T. Haarnoja et al., Soft Actor-Critic Algorithms and Applications, arXiv:1812.05905, 2018 — SAC 与自动温度SAC and automatic temperature
    • T. Haarnoja, S. Ha, A. Zhou, J. Tan, G. Tucker & S. Levine, Learning to Walk via Deep Reinforcement Learning, RSS 2019 — Minitaur 在真实世界中学走路A Minitaur learning to walk in the real world
    • N. Rudin, D. Hoeller, P. Reist & M. Hutter, Learning to Walk in Minutes Using Massively Parallel Deep Reinforcement Learning, CoRL 2021 — GPU 并行仿真 + PPO(legged_gym)GPU-parallel simulation + PPO (legged_gym)
    • L. Smith, I. Kostrikov & S. Levine, A Walk in the Park: Learning to Walk in 20 Minutes With Model-Free Reinforcement Learning, RSS 2023 (arXiv:2208.07860, 2022) — 真机上的高效异策略学习Sample-efficient off-policy learning on hardware
    • L. Engstrom et al., Implementation Matters in Deep Policy Gradients: A Case Study on PPO and TRPO, ICLR 2020; M. Andrychowicz et al., What Matters in On-Policy Reinforcement Learning? A Large-Scale Empirical Study, ICLR 2021 — PPO 的实现细节有多重要How much PPO's implementation details matter