Lecture 6 · 强化学习与控制 · Reinforcement Learning & Control

Machine Learning · Lecture 06。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

对应 Maps to:Stanford CS229 Autumn 2018(Andrew Ng)Lecture 16 后半–20(MDPs & Value/Policy Iteration; Continuous State MDP & Model Simulation; Reward Model & Linear Dynamical System; RL Debugging and Diagnostics),以及 CS229 main notes(Andrew Ng & Tengyu Ma)Chapters 15–17(Reinforcement learning; LQR, DDP and LQG; Policy gradient)。 CS229 当前学期的课表需要 Stanford 登录才能看,所以本讲以公开的讲义和 2018 年的录像为准。这是 CS229 的最后一讲;更深入的 RL(TD、Q-learning、DQN、PPO、offline RL、探索理论)见同目录的 CS234。 配套代码 Code:code/lecture06/(numpy;5 个脚本,最长的约 20 秒) 预计阅读时间:2.5–3 小时(含运行代码)。这是一份复习讲义:假设你见过 MDP 和 value iteration,重点放在”为什么”、“什么时候会失效”和”它和前五讲的联系”上。


0. 本讲导航 · How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. 用 MDP 的语言描述一个序贯决策问题,写出 VπV^\pi 和 V⋆V^\star 的 Bellman 方程,并说清它们一个是线性方程、一个是带 max 的不动点方程。
  2. Explain why value iteration converges (γ-contraction), why it is often much faster than the γk\gamma^k bound, and why policy iteration needs only a handful of iterations (it is Newton’s method).
  3. Name the two traps of learning a model from experience: planning on an estimated model is overconfident (the optimizer’s curse), and acting greedily on it may never discover what it hasn’t tried.
  4. For continuous states, compare discretization (curse of dimensionality) and fitted value iteration (regression inside VI — and why it may not converge).
  5. 推出 LQR 的关键一步(二次函数经过线性动力学再取 min 仍是二次函数),解释 Riccati 增益为什么收敛到常数、certainty equivalence、LQG 的分离原理,以及 DDP / iLQR 在解决什么问题。
  6. Derive REINFORCE from the likelihood-ratio trick, recognize the score function as the GLM gradient of Lecture 1, and explain what reward-to-go and baselines do to the variance.
  7. Diagnose an RL system that “doesn’t work” with Ng’s three questions: is it the simulator, the RL algorithm, or the reward?

0.2 默认你已经会的 / 本讲会省略的

默认你已经会 Assumed本讲省略或只给结论 Skipped
MDP、策略、价值函数的定义最优策略存在且可取为确定性、平稳策略的证明
动态规划的基本思想Bellman 算子收缩性的完整证明(只给关键一步)
第 1 讲的最小二乘、softmax 回归、GLM 梯度Riccati 方程和 Kalman 滤波的完整代数(只给关键一步和结果)
高斯分布的条件分布公式DDP 的二阶展开细节、iLQR 的正则化与 line search
梯度上升策略梯度定理的严格证明(给 likelihood-ratio 的推导);PEGASUS;POMDP 理论
TD learning、Q-learning、DQN、actor-critic、PPO(见 CS234,§7 有对照表)

0.3 本讲地图 Map

§1  RL 问题:从监督学习到序贯决策;MDP;Bellman 方程
§2  有限 MDP:价值迭代(收缩)/ 策略迭代(Newton)/ 奖励定义最优 / 学模型 / 探索     ← 代码 01、02
§3  连续状态:模拟器 / 离散化与维数灾难 / fitted value iteration 及其不稳定性         ← 代码 03
§4  LQR:Riccati 递推 / vs 手调 / certainty equivalence / 线性化与 DDP / Kalman 与 LQG ← 代码 04 演示 1–4
§5  Policy gradient:REINFORCE / 得分函数 = GLM 梯度 / reward-to-go 与 baseline      ← 代码 05
§6  RL debugging:模拟器、算法还是奖励?                                              ← 代码 04 演示 5
§7  CS229 讲了什么、没讲什么(与 CS234 的对照)
§8–12 小结、常见误区、练习、延伸阅读、课程总结

0.4 Notation(和 CS229 main notes 一致)

符号含义
(S,A,{Psa},γ,R)(\mathcal{S}, \mathcal{A}, \{P_{sa}\}, \gamma, R)MDP:状态集、动作集、转移概率 Psa(s′)P_{sa}(s')、折扣因子 γ∈[0,1)\gamma \in [0, 1)、奖励
R(s)R(s)状态奖励。CS229 讲义大部分地方让奖励只依赖状态,本讲照做(R(s,a)R(s, a) 的推广是平凡的)
π\pi;VπV^\pi、V⋆V^\star、QQ策略;策略 π\pi 的价值、最优价值、动作价值
TTBellman 最优算子:(TV)(s)=R(s)+max⁡aγ∑s′Psa(s′)V(s′)(TV)(s) = R(s) + \max_a \gamma\sum_{s'}P_{sa}(s')V(s')
A,BA, B;U,WU, WLQR 的线性动力学矩阵;状态 / 动作的代价矩阵(控制论教材写作 Q,RQ, R,这里 RR 已经是奖励了)
KtK_t、PtP_tLQR 的反馈增益(at=−Ktsta_t = -K_t s_t)和 cost-to-go 矩阵(Vt(s)=s⊤Pts+ctV_t(s) = s^\top P_t s + c_t)
η(θ)\eta(\theta);τ\tau;GtG_t;bb策略的期望回报;轨迹;reward-to-go;baseline

符号上的一个约定:§1–3、§5 说”奖励”、最大化;§4(LQR)说”代价”、最小化,代价 = −奖励。CS229 讲义的 LQR 写成奖励 −(s⊤Us+a⊤Wa)-(s^\top U s + a^\top W a)、价值 s⊤Φts+Ψts^\top\Phi_t s + \Psi_t(Φt⪯0\Phi_t \preceq 0),本讲的 Pt=−ΦtP_t = -\Phi_t。两种写法的结果完全相同。

0.5 关于数字

讲义里所有实验数字都来自配套代码的实际输出(固定随机种子,python3 -W error 下运行两次逐字相同)。环境都是合成的小问题:Ng 的 4×3 网格、走廊、mountain car、双积分器、倒立摆。我们知道”真相”(能精确算出 V⋆V^\star、∇η\nabla\eta、期望代价),所以能检查算法有没有学对;但数字本身不代表任何真实系统。


1. The RL problem · 从监督学习到强化学习

1.1 What changes when there are no labels

前五讲都有一个”正确答案”可以比较:标签 yy(监督学习),或者数据本身(无监督学习)。Andrew Ng 讲 RL 时用的例子是自主直升机:在每个时刻该把操纵杆推多少?没有人能给出每一时刻的”正确”动作,但我们能说出飞得好不好(稳不稳、有没有坠毁)。RL 的设定就是:只给一个奖励信号,让算法自己找出动作。

这带来三个监督学习里没有的困难:

  • Delayed reward / credit assignment:坠机是因为刚才那一下,还是 10 秒前的某个决定?
  • Sequential decisions:现在的动作改变了将来的状态,所以不能把每一步当作独立样本。
  • The data depend on your own actions:你只看得到你走过的地方的后果(§2.5 的探索问题)。第 3 讲的 i.i.d. 假设在这里不成立。

1.2 Markov decision processes

An MDP is a tuple (S,A,{Psa},γ,R)(\mathcal{S}, \mathcal{A}, \{P_{sa}\}, \gamma, R). Start in s0s_0, choose a0a_0, move to s1∼Ps0a0s_1 \sim P_{s_0a_0}, choose a1a_1, and so on. The return is

R(s0)+γR(s1)+γ2R(s2)+⋯R(s_0) + \gamma R(s_1) + \gamma^2 R(s_2) + \cdots

Why discount? Three levels of answer: (1) mathematically it keeps the infinite sum finite (at most Rmax⁡/(1−γ)R_{\max}/(1-\gamma)) and makes the Bellman operator a contraction (§2.1); (2) economically, a dollar today is worth more than a dollar tomorrow; (3) as a model, 1−γ1-\gamma can be read as a per-step probability that the world ends. 1/(1−γ)1/(1-\gamma) is roughly how many steps ahead the agent “looks”.

策略 π:S→A\pi: \mathcal{S} \to \mathcal{A} 的价值 Vπ(s)V^\pi(s) 是从 ss 出发、按 π\pi 行动的期望回报。最优价值 V⋆(s)=max⁡πVπ(s)V^\star(s) = \max_\pi V^\pi(s)。一个重要的事实(这里不证明):存在一个策略 π⋆\pi^\star 同时在所有状态上达到最优,而且可以取成确定性的。

1.3 Bellman equations

把回报拆成”这一步的奖励 + 折扣后的将来”:

Vπ(s)=R(s)+γ∑s′Psπ(s)(s′) Vπ(s′),V⋆(s)=R(s)+max⁡a∈Aγ∑s′Psa(s′) V⋆(s′),π⋆(s)=arg⁡max⁡a∑s′Psa(s′) V⋆(s′)V^\pi(s) = R(s) + \gamma\sum_{s'}P_{s\pi(s)}(s')\,V^\pi(s'), \qquad V^\star(s) = R(s) + \max_{a\in\mathcal{A}}\gamma\sum_{s'}P_{sa}(s')\,V^\star(s'), \qquad \pi^\star(s) = \arg\max_a \sum_{s'}P_{sa}(s')\,V^\star(s')

Two equations, two very different objects:

  • 第一个是线性方程组:∣S∣|\mathcal{S}| 个未知数、∣S∣|\mathcal{S}| 个方程,Vπ=(I−γPπ)−1RV^\pi = (I - \gamma P_\pi)^{-1}R。这就是 policy evaluation。
  • 第二个因为有 max⁡\max,是非线性的不动点方程 V⋆=TV⋆V^\star = TV^\star。没有封闭解,要迭代 —— 这就是 §2 的两个算法。

本讲的实现约定:终止状态(如网格世界的 ±1 出口)进入时拿到 R(s)R(s),之后什么也没有;代码里把它的转移概率行设成全 0,Bellman 方程在那里自动变成 V(s)=R(s)V(s) = R(s)。


2. Finite MDPs · 有限 MDP:规划、学模型与探索

2.1 Value iteration and the contraction argument

Value iteration just applies TT repeatedly: Vk+1=TVkV_{k+1} = TV_k. Why does this converge, from any starting point? The key step is one inequality. For any two value functions V,UV, U and any state ss,

∣(TV)(s)−(TU)(s)∣≤max⁡aγ∣∑s′Psa(s′)(V(s′)−U(s′))∣≤γ ∥V−U∥∞|(TV)(s) - (TU)(s)| \le \max_a \gamma\Big|\sum_{s'}P_{sa}(s')\big(V(s') - U(s')\big)\Big| \le \gamma\,\lVert V - U\rVert_\infty

(第一步用了 ∣max⁡af(a)−max⁡ag(a)∣≤max⁡a∣f(a)−g(a)∣|\max_a f(a) - \max_a g(a)| \le \max_a|f(a) - g(a)|,第二步用了”概率加权平均不超过最大值”。)所以 TT 是 ∞\infty-范数下的 γ\gamma-收缩(contraction),由 Banach 不动点定理,V⋆V^\star 唯一,而且

∥Vk−V⋆∥∞≤γk ∥V0−V⋆∥∞\lVert V_k - V^\star\rVert_\infty \le \gamma^k\,\lVert V_0 - V^\star\rVert_\infty

这是最坏情况的保证。代码 01_value_policy_iteration.py 演示 1 在 Ng 课上的 4×3 网格世界(转移 0.8 / 0.1 / 0.1,每步 R=−0.02R = -0.02,γ=0.99\gamma = 0.99)上比较实际误差和上界:

kk12510152030100200
R=−0.02R = -0.02:∥Vk−V⋆∥∞\lVert V_k - V^\star\rVert_\infty0.9520.9360.8780.1120.0186×10−46\times10^{-4}3×10−73\times10^{-7}已收敛已收敛
R=+0.02R = +0.02:∥Vk−V⋆∥∞\lVert V_k - V^\star\rVert_\infty1.981.961.901.381.161.020.8420.3950.144
R=+0.02R = +0.02 的上界 γk∥V0−V⋆∥\gamma^k\lVert V_0 - V^\star\rVert1.981.961.901.811.721.641.480.7320.268
每步奖励VI 收敛步数(tol 10−1010^{-10})ρ(γPπ⋆)\rho(\gamma P_{\pi^\star})贪心策略从第几步起已是最优
−0.02410.43311
+0.0218420.99013

γ=0.99\gamma = 0.99 时上界要约 2300 步才降到 10−1010^{-10},可 R=−0.02R = -0.02 时 VI 只用了 41 步。原因是回合会结束:最优策略下 agent 很快走到出口,后期误差每步乘以 γPπ⋆\gamma P_{\pi^\star} 的谱半径 0.433,而不是 γ\gamma。“每一步有一定概率终止”等价于一个更小的有效折扣。R=+0.02R = +0.02 时活着本身有奖励,最优策略是永远不进出口:回合不结束,前几步的误差恰好等于上界,后期速率 0.990 ≈ γ\gamma,要 1842 步。

两个实践要点:

  • The greedy policy converges long before the values. 从第 11 步起,对 VkV_k 贪心的策略已经是最优的,而 V11V_{11} 的误差还有 0.08。我们要的是策略,价值只是中间产物。
  • The stopping rule is not the error. ∥Vk+1−Vk∥<ε\lVert V_{k+1} - V_k\rVert < \varepsilon 只保证 ∥Vk+1−V⋆∥≤γε/(1−γ)\lVert V_{k+1} - V^\star\rVert \le \gamma\varepsilon/(1-\gamma)。γ\gamma 接近 1 时这个放大很可观(下一节表格的第 4 列)。

2.2 Policy iteration is Newton’s method

Policy iteration alternates exact evaluation Vπk=(I−γPπk)−1RV^{\pi_k} = (I - \gamma P_{\pi_k})^{-1}R with greedy improvement. The policy improvement theorem guarantees Vπk+1≥VπkV^{\pi_{k+1}} \ge V^{\pi_k} everywhere, and there are finitely many deterministic policies, so it terminates. But “finite” is ∣A∣∣S∣|\mathcal{A}|^{|\mathcal{S}|} — why does it take only a handful of steps in practice?

The answer is that policy iteration is Newton’s method on the Bellman equation (Puterman & Brumelle, 1979). Let F(V)=TV−VF(V) = TV - V; we want F(V)=0F(V) = 0. TT is piecewise linear: near VV, TV=R+γPπVVTV = R + \gamma P_{\pi_V}V where πV\pi_V is greedy with respect to VV, so the Jacobian of FF is γPπV−I\gamma P_{\pi_V} - I. One Newton step gives

Vnew=V−(γPπV−I)−1(R+γPπVV−V)=(I−γPπV)−1R=VπVV_{\text{new}} = V - (\gamma P_{\pi_V} - I)^{-1}\big(R + \gamma P_{\pi_V}V - V\big) = (I - \gamma P_{\pi_V})^{-1}R = V^{\pi_V}

— exactly “act greedily, then evaluate exactly”. Value iteration is the fixed-point iteration V←TVV \leftarrow TV, the analogue of fixed-step GD in Lecture 1: linear convergence at the contraction rate. 代码 01 演示 2 在一个随机 MDP(200 个状态、4 个动作、没有终止状态)上把 γ\gamma 推向 1:

γ\gammaVI 步数(tol 10−810^{-8})PI 轮数VI 结果的实际误差PI 各轮的误差 ∥Vπk−V⋆∥∞\lVert V^{\pi_k} - V^\star\rVert_\infty
0.917058.6×10−88.6\times10^{-8}9 → 3 → 0.6 → 0.06 → 0
0.99176959.9×10−79.9\times10^{-7}70 → 20 → 4 → 0.06 → 0
0.9991775861.0×10−51.0\times10^{-5}700 → 200 → 30 → 0.6 → 0.007 → 0

VI 的步数 ∝1/(1−γ)\propto 1/(1-\gamma),PI 几乎不变;PI 的误差越到后面缩得越快(Newton 的超线性收敛,对照第 1 讲 §3.7)。在 4×3 网格上,PI 从”全部向下”出发,改进 4 轮就找到最优策略(第 5 轮评估只是确认不再需要改),在 49=2621444^9 = 262144 个确定性策略里只看了 5 个。

代价也和 Newton 一样:每轮要解 ∣S∣×∣S∣|\mathcal{S}|\times|\mathcal{S}| 的线性方程组(O(∣S∣3)O(|\mathcal{S}|^3)),VI 每步只要 O(∣S∣2∣A∣)O(|\mathcal{S}|^2|\mathcal{A}|)。状态很多时用折中的 modified policy iteration:评估时只做几次迭代。

2.3 The reward defines what “optimal” means

Same grid, same dynamics, only the per-step reward R(s)R(s) changes (code 01, demo 3, γ=0.99\gamma = 0.99):

R(s)R(s)Behavior of π⋆\pi^\starV⋆V^\star(start)
−2Living hurts: from (3,2) and (4,1) it dives straight into the −1 exit−10.56
−0.4Shortest route, accepting some risk of slipping into −1−1.59
−0.04(2,1) switches to going left, around the long way0.65
−0.02 (Ng’s value)(3,1) also switches to left: a big detour along the top row0.78
0Bumps into the wall at (3,2) and the border at (4,1): can never slip into −1, leaves only via the 10% slips0.93
+0.02Living is rewarded: avoids even the +1 exit and never finishes2.00

一个看起来无害的小数字能完全改变行为。奖励函数不是”告诉 agent 怎么做”,而是”定义什么叫好”—— §6 的调试流程里第三个问题就是”奖励函数是不是错了”。(CS234 第 2 讲的 05_gridworld.py 在同一个网格上把 γ\gamma 和噪声也扫了一遍。)

2.4 Learning a model from experience

So far PsaP_{sa} and RR were given. CS229’s answer when they aren’t is the simplest possible one: count.

P^sa(s′)=#{在 s 做 a 之后到了 s′}#{在 s 做了 a},分母为 0 时用均匀分布 1/∣S∣\hat P_{sa}(s') = \frac{\#\{\text{在 } s \text{ 做 } a \text{ 之后到了 } s'\}}{\#\{\text{在 } s \text{ 做了 } a\}}, \qquad \text{分母为 0 时用均匀分布 } 1/|\mathcal{S}|

这就是第 1 讲的 MLE:每个 (s,a)(s, a) 的下一状态服从一个 categorical 分布,它的 MLE 是频率。然后在 P^\hat P 上做 VI,执行得到的策略,收集更多数据,再估计 …… 这是最朴素的 model-based RL。 代码 02_model_based_rl.py 演示 1 在 4×3 网格里随机乱走,学模型、规划,再在真实环境里评估(每行 50 次重复的平均,V⋆(start)=0.780V^\star(\text{start}) = 0.780):

回合数转移数试过的 (s,a)(s,a)TV 误差模型认为的 V^\hat V(start)真实的 Vπ^V^{\hat\pi}(start)regretP(最优)
13442%0.272−0.064−0.0750.8550.02
310676%0.2240.5310.2710.5090.12
1032098%0.1550.7910.6650.1160.16
30976100%0.0840.7920.7560.0240.46
1003204100%0.0450.7870.7780.0020.84
100032331100%0.0140.7830.7800.0001.00

两件值得记住的事:

  • 不需要把模型学得很准:100 个回合时 TV 误差还有 0.045,84% 的情况已经得到最优策略。和 §2.1 一样,只要动作的排序对了就行。
  • 在学到的模型上规划会过度自信(optimizer’s curse):V^−Vπ^\hat V - V^{\hat\pi} = +0.260(3 个回合)、+0.127(10 个)、+0.009(100 个)。在有噪声的估计上取 max,会系统性地挑中那些”恰好被高估”的动作(练习 3)。这是所有”先学模型再优化”方法的通病,§3.4 的 fitted VI 里还会以 maximization bias 的形式再出现一次。

2.5 The exploration problem (briefly)

CS229 的循环是”执行当前最优策略 → 更新模型 → 重新规划”。它有一个致命的盲点:数据是 agent 自己的行为产生的。演示 2 是一条走廊:从状态 2 出发,左边 2 步是 +1 的出口,右边 7 步是 +10 的出口(γ=0.95\gamma = 0.95,最优是向右,V⋆=6.983V^\star = 6.983;向左只有 0.9020.902)。每个 agent 先随机走一个回合,再按计划走 30 个回合,独立跑 200 次(第 ii 次运行时三个 agent 的随机回合相同):

agent随机回合碰巧到 +10曾经到过 +10最终计划向右最后 10 回合的平均回报总步数
greedy(CS229 的循环)0.2000.2000.2002.119103.5
ε-greedy,ε = 0.10.2000.2000.2002.052113.2
optimistic(R-max 式)0.2001.0001.0006.983232.2
  • greedy 只有在第一个随机回合碰巧走到右边时才学会向右(随机游走先到 9 的概率是 2/9 ≈ 0.22,200 次的标准误约 0.03)。否则模型只见过 +1,计划就是”向左”,执行”向左”又只会看到 +1 —— 永远不会知道右边有什么。模型没有估计错;它只是从来没有关于右边的数据。
  • ε-greedy 一次也没帮上:200 次运行里靠随机动作多找到 +10 的次数是 0。要连续很多步”恰好”随机地向右,概率随距离指数下降。这种”抖动式”探索(dithering)在需要深度探索的问题上几乎无效。
  • 乐观(optimism in the face of uncertainty):把没试过的 (s,a)(s, a) 当成”通往一个每步都拿 Rmax⁡R_{\max} 的天堂”。agent 会有计划地去试每个没试过的动作,试过之后乐观自动消失。代价是前期多走一倍的路。

CS229 只点到为止。Regret、UCB、Thompson sampling、R-max、PSRL 这些系统的探索理论见 CS234 第 11–13 讲。


3. Continuous states · 连续状态

3.1 Simulators

直升机的状态是连续的(位置、姿态、速度、角速度,12 维),表格 V(s)V(s) 存不下。CS229 的思路是先有一个模拟器(simulator / model):给定 (st,at)(s_t, a_t),返回 st+1s_{t+1} 或它的一个样本。模拟器从哪来?

  • Physics:刚体动力学、空气动力学的方程。准确,但写起来费力,而且总有没建模的效应。
  • Learned from data:让人类飞一会儿,记录 (st,at,st+1)(s_t, a_t, s_{t+1}),然后拟合 st+1=Ast+Bats_{t+1} = As_t + Ba_t(就是第 1 讲的线性回归,每个输出维度一个)。Ng 的直升机就是这样做的,再在线性模型上加噪声 ϵt∼N(0,Σ)\epsilon_t \sim \mathcal{N}(0, \Sigma) 让它变成随机的。Ng 课上的建议:训练时用随机模拟器,否则策略会利用模拟器”过于完美”的地方,到了真实世界就脆弱。

有了模拟器,有两条路:离散化,或者用函数逼近 VV。

3.2 Discretization and the curse of dimensionality

把状态空间切成格子,每个格子当作一个离散状态,转移概率从模拟器采样估计(§2.4 的计数法,只是数据来自模拟器),然后做 VI。代码 03_continuous_fitted_vi.py 演示 1 用 mountain car:一辆动力不足的小车要开上右边的山顶,必须先往左倒车蓄势 —— “先远离目标才能到达目标”,需要向前看很多步。状态 = (位置, 速度),每步奖励 −1,γ=0.99\gamma = 0.99;评估 100 个固定起点的平均到达步数(上限 1000):

每维格子数 NN510204080160
格子总数251004001600640025600
平均步数1000(全部失败)16215510898.898.6

N=5N = 5 太粗,表示不出”先倒车”这种精细的策略;N≥80N \ge 80 基本饱和。两个代价:

  1. Resolution:VV 和 π\pi 在一个格子内是常数(piecewise constant),真实的 VV 却在格子内部变化。
  2. Curse of dimensionality:每维 NN 段,dd 维要 NdN^d 个格子。每维 20 段时,2 维 400 个,4 维(cart-pole)16 万,6 维 6400 万,12 维的直升机 4×10154\times10^{15}。CS229 讲义的经验法则:1–2 维离散化很好用,3–4 维要小心地设计格子,6 维以上基本不行。

3.3 Fitted value iteration

The fix is the same as everywhere else in ML: replace the table by a parametric function V(s)≈θ⊤ϕ(s)V(s) \approx \theta^\top\phi(s), with a number of parameters that doesn’t grow like NdN^d. Fitted value iteration (CS229 main notes, Ch. 15):

  1. Sample states s(1),…,s(m)s^{(1)}, \dots, s^{(m)} once.
  2. Repeat:
    • For each ii and each action aa, sample kk next states s1′,…,sk′∼Ps(i)as'_1, \dots, s'_k \sim P_{s^{(i)}a} from the simulator and set q(a)=R(s(i))+γ1k∑jV(sj′)q(a) = R(s^{(i)}) + \gamma\frac{1}{k}\sum_j V(s'_j).
    • y(i)=max⁡aq(a)y^{(i)} = \max_a q(a) — one Bellman backup on the samples.
    • θ:=arg⁡min⁡θ∑i(θ⊤ϕ(s(i))−y(i))2\theta := \arg\min_\theta \sum_i\big(\theta^\top\phi(s^{(i)}) - y^{(i)}\big)^2 — least squares from Lecture 1.
  3. Act greedily, using the simulator to look one step ahead.

So FVI is VI where each sweep is a supervised regression problem: the Bellman backup produces the labels, least squares fits them. Demo 2 (m=2000m = 2000, 1000 sweeps, no regularization; mountain car is deterministic so k=1k = 1; the true VV lies in [−100,−1][-100, -1]):

Features#paramslast ∥Δθ∥∞\lVert\Delta\theta\rVert_\inftyrange of VV on samplesmean stepsfailed
polynomial, degree 261.4×10−101.4\times10^{-10}[−64.5, 18.4]90489%
polynomial, degree 4154.0×10−84.0\times10^{-8}[−64.1, 12.7]2019%
polynomial, degree 6281.1×10−51.1\times10^{-5}[−61.8, 34.2]1290%
RBF 5×5264.8×10−74.8\times10^{-7}[−61.0, 1.7]1250%
RBF 9×98217[−65.8, 1.2]1080%
RBF 15×152260.89[−60.9, 3.0]1190%

(For comparison: discretization with N=80N = 80, 6400 cells → 98.8 steps.)

  • Low-degree polynomials are too rigid to represent the shape of VV. RBFs are local features, and 82 of them come close to what 6400 cells achieve. But 15×15 is no better than 9×9: more features did not buy a better policy.
  • Every row has positive values of VV, although the truth is ≤−1\le -1. Function approximation has errors, but the greedy policy only asks which action has the larger V(s′)V(s'), so the policy can be fine while VV is wrong — and FVI’s VV should not be read as “steps to go”.
  • For RBF 9×9 and 15×15, θ is still changing after 1000 sweeps. Exact VI always converges; FVI may not settle.

3.4 Fitted VI need not converge

演示 3 跟踪 RBF 15×15 的迭代过程(各记录点上的 ∥Δθ∥∞\lVert\Delta\theta\rVert_\infty,以及贪心策略的失败率):

第 kk 轮103010030010002000
无正则化,m=2000m = 2000:∥Δθ∥\lVert\Delta\theta\rVert5.1288.7190.890.0072
  max∣θj∣\lvert\theta_j\rvert / 失败率32 / 100%364 / 100%780 / 100%739 / 100%833 / 0%833 / 0%
无正则化,m=10000m = 10000:∥Δθ∥\lVert\Delta\theta\rVert5.8146.61.00.0256.5×10−56.5\times10^{-5}
  失败率100%100%100%28%8%8%
ridge λ=10−4\lambda = 10^{-4},m=2000m = 2000:∥Δθ∥\lVert\Delta\theta\rVert0.660.410.110.00215.9×10−105.9\times10^{-10}2.4×10−142.4\times10^{-14}
  max∣θj∣\lvert\theta_j\rvert / 失败率7.3 / 100%18 / 100%27 / 0%26 / 0%26 / 0%26 / 0%

不加正则化时,θ\theta 的变化量忽大忽小,几百轮都没有稳定的下降趋势,系数大到 833(高度重叠的 RBF 用大的正负系数互相抵消),前 300 轮的贪心策略全部失败;最后慢慢停下来。多采样没有治好它:m=10000m = 10000 同样乱跳了几百轮,最后停在一个更差的地方(8% 失败)。加一点 ridge,∥Δθ∥\lVert\Delta\theta\rVert 就像收缩映射一样单调下降,第 100 轮的策略已经全部成功。

Why? Exact VI is a contraction in ∥⋅∥∞\lVert\cdot\rVert_\infty. Least-squares fitting is a projection that is optimal in (sample-weighted) ∥⋅∥2\lVert\cdot\rVert_2 — it can make the error larger at some states (extrapolation, wild cancelling coefficients). The composition “fit ∘ backup” need not be a contraction in any norm, so errors can be amplified from one sweep to the next, oscillate, or settle somewhere that depends on details (Tsitsiklis & Van Roy, 1996). Gordon (1995) showed that if the regressor is an averager — prediction = a weighted average of training targets, as in kk-NN or discretization — FVI does converge. Ridge doesn’t make least squares an averager, but it tames the large coefficients.

Ridge 修好的是”不稳定”,不是”高估”。三种设置下 VV 的最大值都在山顶旁边(p≈0.45p \approx 0.45–0.5),而且那里的回归目标本身就是正的(3.14、12.13、4.33)。机制:山顶是一个悬崖(再走一步就到的状态 V=−1V = -1,山顶本身为 0 且不在回归样本里),光滑的特征在悬崖边冲过头;bootstrapping 把高估喂进邻居的目标 y=−1+γV(s′)y = -1 + \gamma V(s'),max⁡\max 又专挑被高估的那个动作 —— 高估一轮轮传开。这就是 maximization bias,和 §2.4 的 optimizer’s curse 是同一件事。它的后代 DQN 有同样的问题(Double DQN 就是为它设计的),“函数逼近 + bootstrapping + off-policy”会发散的现象叫 deadly triad(CS234 第 4–5 讲)。


4. Linear quadratic regulation · LQR、DDP 与 LQG

4.1 The one continuous case with an exact solution

st+1=Ast+Bat+wt,wt∼N(0,Σw),cost=∑t=0T−1(st⊤Ust+at⊤Wat)+sT⊤UfsTs_{t+1} = As_t + Ba_t + w_t,\quad w_t \sim \mathcal{N}(0, \Sigma_w), \qquad \text{cost} = \sum_{t=0}^{T-1}\big(s_t^\top Us_t + a_t^\top Wa_t\big) + s_T^\top U_f s_T

Linear dynamics, quadratic cost, finite horizon. Why care about such a special case?

  • 任何光滑的非线性系统在平衡点附近都近似线性,任何光滑的代价在最小值附近都近似二次。“让直升机悬停在原地”、“让倒立摆保持竖直”都是这个形状(§4.4)。
  • 它有精确解:VV 恰好是二次函数,最优策略恰好是线性反馈 at=−Ktsta_t = -K_ts_t。连续状态、无穷多个状态,却只需要一个 n×nn\times n 矩阵 —— 不需要离散化,也不需要 FVI。

4.2 The Riccati recursion

动态规划从 t=Tt = T 往回做。关键一步:假设 Vt+1(s)=s⊤Pt+1s+ct+1V_{t+1}(s) = s^\top P_{t+1}s + c_{t+1},那么

Vt(s)=min⁡a[s⊤Us+a⊤Wa+E Vt+1(As+Ba+w)]V_t(s) = \min_a\Big[s^\top Us + a^\top Wa + \mathbb{E}\,V_{t+1}(As + Ba + w)\Big]

括号里对 aa 是凸二次函数(W≻0W \succ 0),令导数为 0 得 a⋆=−Ktsa^\star = -K_ts,代回去仍是 ss 的二次函数 —— “二次函数经过线性动力学、再对动作取 min,还是二次函数”,所以归纳成立:

Kt=(W+B⊤Pt+1B)−1B⊤Pt+1A,Pt=U+A⊤Pt+1A−A⊤Pt+1B(W+B⊤Pt+1B)−1B⊤Pt+1A,ct=ct+1+tr⁡(ΣwPt+1)K_t = (W + B^\top P_{t+1}B)^{-1}B^\top P_{t+1}A, \qquad P_t = U + A^\top P_{t+1}A - A^\top P_{t+1}B(W + B^\top P_{t+1}B)^{-1}B^\top P_{t+1}A, \qquad c_t = c_{t+1} + \operatorname{tr}(\Sigma_wP_{t+1})

PtP_t 的递推叫 (discrete-time) Riccati equation。它就是线性-二次情形下的价值迭代:每一步 backup 都能用一个矩阵精确表示。

代码 04_lqr_lqg.py 演示 1 用双积分器(直线上的小车,ss = [位置, 速度],aa = 力,dt=0.1dt = 0.1,U=diag(1,0.1)U = \text{diag}(1, 0.1),W=0.1W = 0.1,T=100T = 100):

时刻 tt050809095979899
剩余步数1005020105321
KtK_t[2.762, 2.508][2.762, 2.508][2.718, 2.485][2.475, 2.047][1.084, 0.830][0.428, 0.388][0.195, 0.229][0.049, 0.104]
时域 TT12510203050
∥K0−K∞∥\lVert K_0 - K_\infty\rVert2.72.61.70.460.0440.00481.9×10−51.9\times10^{-5}
  • 离终点很远时 KtK_t 是常数 K∞K_\infty,只有最后十来步迅速变小:快结束时,“现在用力、以后享受小偏差”的买卖不划算了。
  • 时域每多 10 步,∥K0−K∞∥\lVert K_0 - K_\infty\rVert 大约缩小 10 倍:Riccati 递推本身是一个收缩的不动点迭代(又是 §2.1)。所以无限时域 LQR = 迭代 Riccati 到不动点(discrete algebraic Riccati equation, DARE),实践中常常直接用 K∞K_\infty。
  • 从 s0=[1,0]s_0 = [1, 0] 出发,预测代价 s0⊤P0s0=9.077561s_0^\top P_0s_0 = 9.077561,实际执行的代价也是 9.077561,逐位相同:VtV_t 是精确的,不是近似。

4.3 LQR vs hand tuning; certainty equivalence

A PD controller a=−(kp⋅position+kd⋅velocity)a = -(k_p\cdot\text{position} + k_d\cdot\text{velocity}) is exactly a linear feedback a=−[kp,kd] sa = -[k_p, k_d]\,s. Demo 2 computes expected costs exactly by propagating covariances (s0∼N(0,diag(1,0.25))s_0 \sim \mathcal{N}(0, \text{diag}(1, 0.25)), no sampling error):

ControllerGains (kp,kd)(k_p, k_d)E[cost] with process noiseE[cost] without noise
LQR (time-varying KtK_t)[2.76, 2.51]12.3399.769
LQR stationary K∞K_\infty[2.76, 2.51]12.4249.769
hand-tuned PD(1, 1)18.43512.930
hand-tuned PD(3, 2)13.00210.274
hand-tuned PD(10, 4)27.52923.730
hand-tuned PD(30, 10)123.029112.761

A brute-force search over kp,kd∈{0.5,0.75,…,6}k_p, k_d \in \{0.5, 0.75, \dots, 6\} finds the best PD gains to be (2.75, 2.50) both with and without noise — that is K∞K_\infty. Two lessons:

  • LQR does the tuning for you — given UU and WW. The hand-tuning problem doesn’t disappear; it moves into choosing the cost matrices. That is reward design again (§2.3, §6).
  • Certainty equivalence:过程噪声让每一行的代价都变大,但不改变最优增益。Riccati 递推里 KtK_t 根本不含 Σw\Sigma_w;噪声只贡献一个和策略无关的常数 c0=∑ttr⁡(ΣwPt+1)=2.570c_0 = \sum_t\operatorname{tr}(\Sigma_wP_{t+1}) = 2.570(预测 tr⁡(P0Σ0)+c0=9.769+2.570=12.339\operatorname{tr}(P_0\Sigma_0) + c_0 = 9.769 + 2.570 = 12.339,和精确计算一致)。直觉:加性高斯噪声是”不管你怎么做都会被吹偏这么多”,它对任何策略都一样。(这个结论依赖线性 + 二次 + 加性高斯;有约束或非线性时不成立。)

4.4 Nonlinear dynamics: linearization, DDP and iLQR

For a nonlinear simulator st+1=f(st,at)s_{t+1} = f(s_t, a_t), the simplest move is to linearize around a point you want to stay near (e.g. hover, or the upright pendulum): f(s,a)≈f(sˉ,aˉ)+∇sf (s−sˉ)+∇af (a−aˉ)f(s, a) \approx f(\bar s, \bar a) + \nabla_sf\,(s - \bar s) + \nabla_af\,(a - \bar a), then run LQR. Demo 3 uses an inverted pendulum (θ¨=gsin⁡θ+u\ddot\theta = g\sin\theta + u, θ=0\theta = 0 upright, mgl=9.81mgl = 9.81), linearized at the top, started at rest from angle θ0\theta_0 (1 = stabilized after 6 s):

Torque limit umax⁡u_{\max}θ0\theta_0 = 0.10.30.50.81.01.52.02.53.0
∞ (peak torque used: 68.5)111111111
20, 10111111111
5111000000
3110000000

结果和”离线性化点远了就失效”的简单说法不完全一样:力矩不限时,线性化的 LQR 从 3.0 rad(离竖直向下只差 8°)都能救回来,代价是约 7 倍 mglmgl 的峰值力矩 —— 力气够大时,“偏了就往回推”这条线性规则在很大范围内都对。力矩上限低于 mglmgl 时,成功的边界(0.5、0.3)几乎正好是”静止撑住”的极限 arcsin⁡(umax⁡/mgl)=0.53\arcsin(u_{\max}/mgl) = 0.53、0.310.31。再远,任何控制器都没法直接推上去,必须先往反方向摆、一来一回地荡上去(swing-up)。这是一个非线性的计划,线性模型根本表示不出来:在线性模型里,θ\theta 再大也只是”多推一点”。

这就是 DDP(differential dynamic programming)/ iLQR 的动机:不在一个固定点线性化,而是沿着当前猜测的轨迹 (sˉt,aˉt)(\bar s_t, \bar a_t) 线性化(DDP 还保留动力学的二阶项),解一个时变 LQR 得到改进的轨迹,再沿新轨迹线性化 …… 迭代到收敛。每一轮都是 §4.2 的 Riccati 递推,所以它继承了 LQR 的效率;加上动作约束(control-limited DDP),它能找到 swing-up 这样的轨迹。它是机器人轨迹优化和 MPC 的主力。

4.5 Partial observability: Kalman filter and LQG

Real sensors are noisy and incomplete: we observe yt=Cst+vty_t = Cs_t + v_t, vt∼N(0,Σv)v_t \sim \mathcal{N}(0, \Sigma_v), not sts_t. In the linear-Gaussian world the belief about sts_t stays Gaussian, so it’s enough to track a mean and a covariance — the Kalman filter:

predict:st+1∣t=Ast∣t+Bat,Σt+1∣t=AΣt∣tA⊤+Σw\text{predict:}\quad s_{t+1|t} = As_{t|t} + Ba_t,\quad \Sigma_{t+1|t} = A\Sigma_{t|t}A^\top + \Sigma_w update:K=Σt+1∣tC⊤(CΣt+1∣tC⊤+Σv)−1,st+1∣t+1=st+1∣t+K(yt+1−Cst+1∣t),Σt+1∣t+1=(I−KC)Σt+1∣t\text{update:}\quad K = \Sigma_{t+1|t}C^\top\big(C\Sigma_{t+1|t}C^\top + \Sigma_v\big)^{-1},\quad s_{t+1|t+1} = s_{t+1|t} + K\big(y_{t+1} - Cs_{t+1|t}\big),\quad \Sigma_{t+1|t+1} = (I - KC)\Sigma_{t+1|t}

(这里的 KK 是 Kalman gain,不是 LQR 的增益。)修正量 = gain × “观测比预测多出来的部分”(innovation):观测噪声大 → 更相信预测;当前不确定性大 → 更相信观测。数学上它就是”联合高斯分布的条件分布”(第 5 讲 factor analysis 的 E 步用的也是它)在时间上的递推。

LQG = Kalman filter + LQR: plug the estimate into the controller, at=−Ktst∣ta_t = -K_ts_{t|t}. In the linear-quadratic-Gaussian setting this is not merely a reasonable heuristic but optimal (the separation principle: estimation and control can be designed separately — the other face of certainty equivalence). Demo 4 observes only the position (y=p+N(0,σ2)y = p + \mathcal{N}(0, \sigma^2)); 2000 simulations per setting, with the same random numbers for all three controllers:

σ\sigmaoracle (sees true state)LQG (Kalman + LQR)naive (velocity by differencing)Kalman velocity errordifferencing velocity error
0.112.5918.22161.580.2281.330
0.312.5925.871345.070.2993.976
1.012.5953.4314806.770.40113.248

(oracle 的精确期望代价是 12.339;表中平均值的标准误约 0.3。)差分 (yt−yt−1)/dt(y_t - y_{t-1})/dt 把观测噪声放大了约 2/dt≈14\sqrt2/dt \approx 14 倍,LQR 拿着这么吵的速度去用力,代价是 oracle 的上百倍。Kalman 滤波利用动力学模型把历史观测融合起来:σ=0.3\sigma = 0.3 时位置误差 0.148,小于观测本身的噪声,LQG 的代价是 oracle 的 2.1 倍、naive 的 1/52。看不到真实状态总要付出代价,但模型能把这个代价压得很低。


5. Policy gradient · 策略梯度

5.1 Why search over policies directly?

Sections 2–4 all compute VV (or a model) first and derive the policy from it. The alternative is to parameterize the policy πθ\pi_\theta and run gradient ascent on the expected return η(θ)\eta(\theta). Why would we?

  • Continuous / high-dimensional actions: max⁡aQ(s,a)\max_a Q(s, a) over a continuous action is itself an optimization problem.
  • Simple policies can be good even when VV is complicated: mountain car’s VV has cliffs and spiral boundaries, yet “push in the direction you are moving” is a very simple policy.
  • Stochastic policies are sometimes optimal (partial observability), and they make η(θ)\eta(\theta) differentiable even when the dynamics aren’t.
  • No model needed (next subsection). Ng’s helicopter used policy search on a learned simulator (PEGASUS: fix the simulator’s random seeds so that η(θ)\eta(\theta) becomes a deterministic function you can optimize).

5.2 REINFORCE and the likelihood-ratio trick

η(θ)=Eτ∼pθ[f(τ)]\eta(\theta) = \mathbb{E}_{\tau\sim p_\theta}[f(\tau)],τ=(s0,a0,s1,a1,… )\tau = (s_0, a_0, s_1, a_1, \dots),f(τ)f(\tau) 是总回报。直接对期望求导的困难是:θ\theta 在分布里,不在被积函数里。Likelihood-ratio(score function)技巧:

∇θ η(θ)=∇θ∫pθ(τ)f(τ) dτ=∫pθ(τ) ∇θlog⁡pθ(τ) f(τ) dτ=Eτ∼pθ[∇θlog⁡pθ(τ) f(τ)]\nabla_\theta\,\eta(\theta) = \nabla_\theta\int p_\theta(\tau)f(\tau)\,d\tau = \int p_\theta(\tau)\,\nabla_\theta\log p_\theta(\tau)\,f(\tau)\,d\tau = \mathbb{E}_{\tau\sim p_\theta}\big[\nabla_\theta\log p_\theta(\tau)\,f(\tau)\big]

而 log⁡pθ(τ)=log⁡p(s0)+∑t[log⁡πθ(at∣st)+log⁡Pstat(st+1)]\log p_\theta(\tau) = \log p(s_0) + \sum_t\big[\log\pi_\theta(a_t \mid s_t) + \log P_{s_ta_t}(s_{t+1})\big],动力学那一项和 θ\theta 无关,求导时消失:

∇θ η(θ)=E[(∑t∇θlog⁡πθ(at∣st))⋅f(τ)]\nabla_\theta\,\eta(\theta) = \mathbb{E}\Big[\Big(\sum_t\nabla_\theta\log\pi_\theta(a_t \mid s_t)\Big)\cdot f(\tau)\Big]

所以只要能采样轨迹,就能无偏地估计梯度,不需要知道 PP,也不需要 ff 可导。这就是 REINFORCE(Williams, 1992)。

The score function is a GLM gradient. 代码 05_policy_gradient.py 演示 1:

  • Softmax policy πθ(a∣s)∝exp⁡(θa⊤ϕ(s))\pi_\theta(a \mid s) \propto \exp(\theta_a^\top\phi(s)):∇θlog⁡πθ(a∣s)=ϕ(s) (ea−πθ(⋅∣s))⊤\nabla_\theta\log\pi_\theta(a \mid s) = \phi(s)\,(e_a - \pi_\theta(\cdot \mid s))^\top —— 和第 1 讲 §4.6 softmax 回归单个样本的梯度 x (y−p)⊤x\,(y - p)^\top 一模一样,只是”标签”换成了自己刚做的动作。
  • Gaussian policy a∼N(θ⊤x,σ2)a \sim \mathcal{N}(\theta^\top x, \sigma^2):∇θlog⁡π=(a−θ⊤x) x/σ2\nabla_\theta\log\pi = (a - \theta^\top x)\,x/\sigma^2 —— 线性回归的”误差 × 输入”。

So REINFORCE is return-weighted maximum likelihood on your own actions: fit a GLM to the actions you took, weighting each by how well things went afterwards. 代码里 reinforce_grad 就是这么写的:g^=X⊤diag(w)(Y−P)/M\hat g = X^\top\text{diag}(w)(Y - P)/M,XX = one-hot 状态,YY = one-hot 动作,ww = 回报。第 1 讲的主线”loss = −log-likelihood”在 RL 里变成了”objective = 回报加权的 log-likelihood”。

还有一个性质撑起了下一节:得分函数的期望为 0,Ea∼π[∇log⁡π(a)]=∇∑aπ(a)=∇1=0\mathbb{E}_{a\sim\pi}[\nabla\log\pi(a)] = \nabla\sum_a\pi(a) = \nabla 1 = 0。演示 1 中 softmax 的情形精确为 0,高斯的情形 20 万个样本的平均是 −0.0023(标准误 0.0026)。

5.3 Variance: reward-to-go and baselines

REINFORCE 无偏,但方差很大。两个几乎免费的改进(CS229 main notes Ch. 17):

  1. Reward-to-go:动作 ata_t 影响不了它之前(和当时)的奖励,把 f(τ)f(\tau) 换成 Gt=∑j>tR(sj)G_t = \sum_{j>t}R(s_j)。去掉的部分期望为 0,只贡献噪声。
  2. Baseline:再减去任何不依赖 ata_t 的 b(st)b(s_t):E[∇log⁡π(at∣st) b(st)]=b(st)⋅E[∇log⁡π]=0\mathbb{E}[\nabla\log\pi(a_t \mid s_t)\,b(s_t)] = b(s_t)\cdot\mathbb{E}[\nabla\log\pi] = 0,期望不变。好的 baseline 让权重变成”比平均好多少”(advantage)。

演示 2 用一条 5 个状态的走廊(状态 4 每步 +1,10% 滑动,固定时域 H=10H = 10,表格 softmax,θ=0\theta = 0),精确算出 ∇η\nabla\eta 后比较四种估计量(每种 20000 条轨迹)。再给每一步奖励加一个常数 cc:时域固定时所有轨迹的回报都多 cHcH,最优策略和 ∇η\nabla\eta 都不变:

cc估计量∥mean−∇η∥\lVert\text{mean} - \nabla\eta\rVert预期抽样误差tr⁡Cov\operatorname{tr}\text{Cov}10 条轨迹的估计与 ∇η\nabla\eta 的 cos
0全回报 G0G_00.0180.0218.880.583
0reward-to-go GtG_t0.0120.0165.060.715
0Gt−btG_t - b_t(时间 baseline)0.0110.0143.980.760
0Gt−Vt(st)G_t - V_t(s_t)(状态 baseline)0.0100.0123.040.803
1全回报 G0G_00.1680.169568.030.078
1reward-to-go GtG_t0.0710.092170.440.152
1Gt−btG_t - b_t0.0110.0143.980.760
1Gt−Vt(st)G_t - V_t(s_t)0.0100.0123.040.803

All four estimators are unbiased (the deviation is of the same size as the expected sampling error). With c=1c = 1 the variance of the full-return estimator grows 64×, and a 10-trajectory estimate is nearly uncorrelated with the true gradient: every ∇log⁡π\nabla\log\pi is multiplied by a large positive number ≈ cHcH, so “every action taken gets reinforced”, and the useful signal (which action was better than which) drowns. The two baseline rows are identical to their c=0c = 0 counterparts: the baseline subtracts the constant exactly. Using a learned V(s)V(s) as the baseline is actor-critic (CS234 Lecture 7).

5.4 What the variance does to learning

Demo 3: 10 trajectories per update, learning rate 0.1, 20 independent runs, evaluated with the exact η(θ)\eta(\theta) (the table shows η−cH\eta - cH; η⋆=4.730\eta^\star = 4.730):

ccMethodkk = 0102550100200worst run @200
—exact gradient0.6251.2892.7703.9384.4114.589—
0full return0.6251.3342.7543.9024.3834.5904.548
0reward-to-go0.6251.3192.7793.9094.3984.5934.554
0reward-to-go + LOO baseline0.6251.3432.8173.9594.4164.5874.564
1full return0.6251.0911.3632.1613.2503.7040.082
1reward-to-go0.6251.0481.8802.9973.8834.5113.043
1reward-to-go + LOO baseline0.6251.3432.8173.9594.4164.5874.564

(LOO = leave-one-out: trajectory ii‘s baseline is the average GtG_t of the other trajectories in the batch, which does not depend on its own actions, so it is unbiased. In RL fine-tuning of LLMs this is called RLOO; GRPO’s “group mean” is the same idea.)

  • c=0c = 0 时 baseline 几乎没有影响:三条曲线几乎重合,都跟着精确梯度走。方差只差约 2 倍,被 200 步平均掉了。这和预想的”baseline 一定明显加速”不一样 —— baseline 不是在任何问题上都有显著效果。
  • c=1c = 1 时差别就出来了。全回报平均只到 3.704,最差的一次 0.082:训练结束时它在起点向右的概率只剩 0.008(一直往墙上撞),∥∇η∥\lVert\nabla\eta\rVert 从 0.663 缩到 0.052,几乎出不来了 —— 高方差的更新把 softmax 推进了一个很差的、几乎确定性的策略(premature convergence)。加 baseline 后的曲线和 c=0c = 0 时一样。奖励的”零点”在 RL 里本来是任意的(每步 +1 存活奖励、每步 −1 时间惩罚都很常见),好的估计量不应该被它左右。
  • 精确梯度 200 轮后也只到 4.589:softmax 越接近确定性,梯度越小(π(1−π)\pi(1-\pi) 因子),普通梯度上升在最后一段很慢。Natural policy gradient / TRPO / PPO 改的就是这个几何问题(CS234 第 7 讲)。

6. RL debugging and diagnostics · 是模拟器、算法还是奖励?

Ng 在 2018 年最后一讲用直升机讲了一个调试流程。系统由三个部件组成,各带一个假设:

  1. Simulator:模拟器足够准确,在模拟器里飞得好的策略在现实里也飞得好。
  2. RL algorithm:算法能在模拟器里找到(近似)最大化奖励的策略。
  3. Reward function:最大化这个奖励 ⇔ 飞得好。

RL 策略 πRL\pi_{\text{RL}} 在现实里飞得不好时,按顺序问三个能用数字回答的问题(πhuman\pi_{\text{human}} 是飞得好的人类驾驶员):

  1. πRL\pi_{\text{RL}} 在模拟器里飞得好、在现实里飞得不好?→ 模拟器的问题。
  2. 否则,比较奖励:VπRL(s0)<Vπhuman(s0)V^{\pi_{\text{RL}}}(s_0) < V^{\pi_{\text{human}}}(s_0)?存在一个奖励更高的策略,RL 却没找到 → RL 算法的问题。
  3. 否则 VπRL(s0)≥Vπhuman(s0)V^{\pi_{\text{RL}}}(s_0) \ge V^{\pi_{\text{human}}}(s_0):RL 把奖励优化得比人还好,却飞得更差 → 奖励函数的问题。

代码 04 演示 5 在双积分器上分别注入三种错误(“飞行质量” qq = 位置误差的 RMS,是我们真正关心的东西;人类 = PD (3, 2),q=0.261q = 0.261;q≤1.25×0.261q \le 1.25\times0.261 算飞得好;JJ = 按 RL 用的代价函数在真实系统上的期望代价):

场景qsim(πRL)q_{\text{sim}}(\pi_{\text{RL}})qreal(πRL)q_{\text{real}}(\pi_{\text{RL}})J(πRL)J(\pi_{\text{RL}})J(πhuman)J(\pi_{\text{human}})诊断
一切正确0.2700.27012.3413.00nothing to fix
模拟器把质量估成 0.1(真实 1)0.1740.36719.4613.00simulator
算法只往前看 3 步0.6790.67949.5913.00RL algorithm
代价函数忘了惩罚位置1.0351.0354.5616.71cost / reward
  • 模拟器以为飞行器轻 10 倍,LQR 选了偏软的增益:模拟器里比人还好(0.174),现实里软绵绵的(0.367)。该做的是收集真实数据重新拟合动力学(§3.1 的回归),而不是去调算法或奖励。
  • 短视的规划器在模拟器和现实里一样差(模拟器没问题);人类的代价 13.00 远低于 RL 的 49.59 —— 有更好的策略它没找到。
  • 忘了位置的代价函数:RL 的代价 4.56 比人类的 16.71 还低,它完美地完成了”最小化这个代价”,却只学会了刹车、停在哪儿算哪儿。

The value of the procedure is that it turns a vague complaint (“it doesn’t fly well”) into comparisons you can compute, so you don’t spend months improving the wrong component. It is the same idea as the ML diagnostics of Lecture 3 (“is it the optimization algorithm or the objective?”): check whether a solution you know to be better is actually better under your objective.


7. What CS229 covers, and where to go next · 与 CS234 的关系

CS229’s treatment of RL is model-centric: with a known model, plan (VI / PI / LQR); without one, learn the model first (counting, regression) or use a simulator. It says almost nothing about the large family of methods that learn values directly from experience without a model. CS234, in the same folder, fills that in:

TopicCS229 (this lecture)CS234 (same folder)
MDPs, VI, PI, contraction§1–2.2Lecture 2: more derivations, finite horizon, Mars rover example
Learning values from experience (model-free)—L3 MC / TD; L4 SARSA, Q-learning, Double Q
Function approximation§3.3–3.4 fitted VIL5 linear FA, deadly triad, DQN
Policy gradient§5 REINFORCE + baselineL6 REINFORCE; L7 actor-critic, GAE, TRPO / PPO
Exploration§2.5 (one example)L11–13 bandits, UCB, Thompson sampling, R-max, PSRL
Model-based RL§2.4, §3L15 Dyna, compounding model error
Learning from humansthe human pilot as a reference in §6L8 imitation learning / IRL (Abbeel & Ng’s helicopter aerobatics used apprenticeship learning); L9 RLHF / DPO
Offline RL, search—L10 offline RL; L14 MCTS / AlphaZero
Continuous control: LQR / DDP / LQG§4not covered — this part is unique to CS229

8. 小结 · Summary

MethodWhat you needWhat it learns / computesThe optimizer underneathMain pitfallCode
Value iterationPP, RRV⋆V^\starfixed-point iteration (γ\gamma-contraction)iterations ∝1/(1−γ)\propto 1/(1-\gamma) when episodes don’t end; stopping rule ≠ error01
Policy iterationPP, RRπ⋆\pi^\starNewton’s methodO(∣S∣3)O(\lvert\mathcal{S}\rvert^3) per iteration01
Counting + planningability to sampleP^\hat P (MLE), then planfrequencies + VIoptimizer’s curse; no exploration, no data02
Discretizationsimulator, low dimensionVV on a gridsampled transitions + VIresolution; NdN^d03
Fitted VIsimulatorV≈θ⊤ϕV \approx \theta^\top\phibackup + least squaresmay not converge; overestimation; needs regularization03
LQR / LQGlinear dynamics, quadratic cost (Gaussian noise, linear observations)KtK_t, Kalman estimateRiccati recursion (exact VI)only as good as the linearization04
DDP / iLQRsmooth nonlinear modelone optimal trajectory + local feedbackrepeated time-varying LQR along a trajectorylocal optima; needs a decent initial trajectory(§4.4)
REINFORCEability to sample trajectoriesπθ\pi_\thetareturn-weighted log-likelihood gradient ascentvariance; premature convergence05

Six takeaways:

  1. Bellman equations are fixed-point equations: VI is fixed-point iteration (a γ\gamma-contraction, often much faster when episodes end), PI is Newton’s method, and the Riccati recursion is VI when VV is exactly quadratic.
  2. Optimizing over an estimate is biased upward. Planning on a learned model, or taking max⁡\max over a fitted VV, systematically overestimates (optimizer’s curse, maximization bias).
  3. Your data depend on your actions. Greedy and ε-greedy can miss what they never try; optimism explores on purpose.
  4. Function approximation inside dynamic programming is not just regression. Errors feed back through bootstrapping; FVI may oscillate or settle in the wrong place, and regularization (Lecture 3) helps.
  5. REINFORCE is weighted maximum likelihood on your own actions, with a GLM score function from Lecture 1. Baselines don’t change the expectation but can change the variance by orders of magnitude.
  6. The reward/cost is part of the design. It defines “optimal” (grid world), replaces hand-tuning (LQR), and is one of the three things to check when a system fails (§6).

9. 常见误区 · Common pitfalls

  • “VI needs γk\gamma^k to be tiny before the policy is right.” The bound is worst case; with termination it can be orders of magnitude faster, and the greedy policy is usually optimal long before VV converges.
  • “‖V_{k+1} − V_k‖ is small, so V is accurate.” The error can be γ/(1−γ)\gamma/(1-\gamma) times larger — 1000× at γ=0.999\gamma = 0.999.
  • “The learned model says this plan is worth 0.53, so it is.” Planning on an estimated model overestimates (0.531 promised vs 0.271 actual with 3 episodes).
  • “ε-greedy takes care of exploration.” Not when the reward is many deliberate steps away; it found the far exit 0 extra times in 200 runs.
  • “Fitted VI is VI with a regressor, so it converges like VI.” It may not; watch Δθ\Delta\theta and the range of VV (positive values when all rewards are negative are a red flag).
  • “Noise should change the LQR gains.” Not for additive Gaussian noise in the LQ setting (certainty equivalence) — it only adds a constant cost. It does matter with constraints, nonlinearity, or multiplicative noise.
  • “Adding a constant to every reward is harmless.” With termination it changes the optimal policy (§2.3); in policy gradient without a baseline it inflates the variance (64× for c=1c = 1 in §5.3).
  • “The RL policy fails, so let’s tune the reward.” Ask the three questions in order first (§6).

10. 练习 · Exercises

Exercise 1 (Contraction and iteration counts). (a) Prove ∥TV−TU∥∞≤γ∥V−U∥∞\lVert TV - TU\rVert_\infty \le \gamma\lVert V - U\rVert_\infty. (b) Starting from V0=0V_0 = 0 with ∣R∣≤Rmax⁡|R| \le R_{\max}, how many iterations guarantee ∥Vk−V⋆∥∞≤ε\lVert V_k - V^\star\rVert_\infty \le \varepsilon? (c) In code 01 with γ=0.99\gamma = 0.99 and step reward −0.02-0.02, VI needed only 41 iterations. Use “each step has some probability of terminating” to explain why the actual rate is ρ(γPπ⋆)\rho(\gamma P_{\pi^\star}) rather than γ\gamma.

参考答案 Answer

(a) For each ss: ∣max⁡af(a)−max⁡ag(a)∣≤max⁡a∣f(a)−g(a)∣|\max_af(a) - \max_ag(a)| \le \max_a|f(a) - g(a)| with f(a)−g(a)=γ∑s′Psa(s′)(V−U)(s′)f(a) - g(a) = \gamma\sum_{s'}P_{sa}(s')(V - U)(s'), whose absolute value is at most γ∥V−U∥∞\gamma\lVert V - U\rVert_\infty (a probability-weighted average never exceeds the maximum). (b) ∥V0−V⋆∥∞≤Rmax⁡/(1−γ)\lVert V_0 - V^\star\rVert_\infty \le R_{\max}/(1-\gamma), so we need γkRmax⁡/(1−γ)≤ε\gamma^kR_{\max}/(1-\gamma) \le \varepsilon, i.e. k≥log⁡Rmax⁡ε(1−γ)/log⁡1γ≈11−γlog⁡Rmax⁡ε(1−γ)k \ge \log\frac{R_{\max}}{\varepsilon(1-\gamma)}\big/\log\frac1\gamma \approx \frac{1}{1-\gamma}\log\frac{R_{\max}}{\varepsilon(1-\gamma)}. (c) Once the greedy policy has settled on π⋆\pi^\star, the error propagates as ek+1=γPπ⋆eke_{k+1} = \gamma P_{\pi^\star}e_k among non-terminal states. Terminal rows are zero, so Pπ⋆P_{\pi^\star} is sub-stochastic — probability mass leaks out every step — and its spectral radius is below 1, giving the effective rate ρ(γPπ⋆)=0.433<γ\rho(\gamma P_{\pi^\star}) = 0.433 < \gamma. When the agent never wants to finish (+0.02 per step), Pπ⋆P_{\pi^\star} is stochastic on the non-terminal states, its spectral radius is 1, and the rate returns to γ\gamma.

练习 2(PI = Newton). 设 F(V)=TV−VF(V) = TV - V。证明:在 VV 处对 FF 做一步 Newton 法(用贪心策略 πV\pi_V 给出的 Jacobian γPπV−I\gamma P_{\pi_V} - I),得到的正是 VπVV^{\pi_V}。为什么 PI 的误差序列(9 → 3 → 0.6 → 0.06 → 0)越到后面缩得越快?

参考答案

V−(γPπ−I)−1(R+γPπV−V)=V+(I−γPπ)−1(R−(I−γPπ)V)=(I−γPπ)−1R=VπV - (\gamma P_\pi - I)^{-1}(R + \gamma P_\pi V - V) = V + (I - \gamma P_\pi)^{-1}\big(R - (I - \gamma P_\pi)V\big) = (I - \gamma P_\pi)^{-1}R = V^\pi。TT 是有限个仿射函数的上包络(每个确定性策略一个),所以 FF 是凸的分段线性函数。Newton 法在分段线性函数上:一旦当前点落在”正确的那一段”(贪心策略 = π⋆\pi^\star),下一步就精确落到根上。这就是为什么 PI 在有限步内精确终止,而不只是渐近收敛;越到后面,贪心策略和 π⋆\pi^\star 的差别越小,误差缩得越快。

Exercise 3 (The optimizer’s curse). There are KK actions, all with true value 0, and estimates Q^a=ϵa\hat Q_a = \epsilon_a, ϵa∼iidN(0,σ2)\epsilon_a \overset{\text{iid}}{\sim}\mathcal{N}(0, \sigma^2). (a) For K=2K = 2, compute E[max⁡aQ^a]\mathbb{E}[\max_a\hat Q_a]. (b) If we pick a^=arg⁡max⁡aQ^a\hat a = \arg\max_a\hat Q_a, what is its true value, and what is the expected “believed minus true” value? (c) Relate this to the table of code 02: why does the gap shrink with more data?

参考答案 Answer

(a) max⁡(ϵ1,ϵ2)=ϵ1+ϵ22+∣ϵ1−ϵ2∣2\max(\epsilon_1, \epsilon_2) = \frac{\epsilon_1 + \epsilon_2}{2} + \frac{|\epsilon_1 - \epsilon_2|}{2} with ϵ1−ϵ2∼N(0,2σ2)\epsilon_1 - \epsilon_2 \sim \mathcal{N}(0, 2\sigma^2) and E∣⋅∣=2σ22/π\mathbb{E}|\cdot| = \sqrt{2\sigma^2}\sqrt{2/\pi}, so Emax⁡=σ/π≈0.56σ\mathbb{E}\max = \sigma/\sqrt\pi \approx 0.56\sigma; it grows with KK (roughly σ2log⁡K\sigma\sqrt{2\log K}). (b) The true value is 0, so the expected overconfidence is σ/π>0\sigma/\sqrt\pi > 0 even though every individual estimate is unbiased. (c) More data means a smaller error in P^\hat P (a smaller σ\sigma), hence a smaller overestimate: +0.260 with 3 episodes → +0.009 with 100. Remedies: cross-fitting (choose the action with one half of the data, evaluate it with the other — the idea behind Double Q-learning), or pessimism where uncertainty is high (offline RL, CS234 Lecture 10).

练习 4(Scalar LQR). st+1=st+ats_{t+1} = s_t + a_t,代价 ∑t(st2+ρat2)\sum_t(s_t^2 + \rho a_t^2)。(a) 求稳态 Riccati 方程的解 pp 和增益 KK。(b) 讨论 ρ→0\rho \to 0 和 ρ→∞\rho \to \infty 的极限,并给出直觉。(c) 闭环系统 st+1=(1−K)sts_{t+1} = (1 - K)s_t 一定稳定吗?

参考答案

(a) A=B=U=1A = B = U = 1,W=ρW = \rho:p=1+p−p2ρ+pp = 1 + p - \frac{p^2}{\rho + p},即 p2=ρ+pp^2 = \rho + p,取正根 p=1+1+4ρ2p = \frac{1 + \sqrt{1 + 4\rho}}{2};K=pρ+p=pp2=1pK = \frac{p}{\rho + p} = \frac{p}{p^2} = \frac1p。(b) ρ→0\rho \to 0(用力免费):p→1p \to 1,K→1K \to 1,一步把状态推到 0(deadbeat control)。ρ→∞\rho \to \infty(用力很贵):p≈ρp \approx \sqrt\rho,K≈1/ρ→0K \approx 1/\sqrt\rho \to 0,慢慢地、温柔地往回推。代码 04 演示 1 里 KtK_t 在时域末尾变小是同一个直觉的时间版本:剩下的步数少,“用力”的回报就少。(c) 1−K=1−1/p∈[0,1)1 - K = 1 - 1/p \in [0, 1),所以一定稳定(单调收敛,不振荡)。

练习 5(Baselines). (a) 证明对任何只依赖 sts_t 的 b(st)b(s_t),E[∇θlog⁡πθ(at∣st) b(st)]=0\mathbb{E}\big[\nabla_\theta\log\pi_\theta(a_t \mid s_t)\,b(s_t)\big] = 0。为什么 bb 不能依赖 ata_t?(b) 只考虑一步问题(一个 ∇log⁡π\nabla\log\pi、一个回报 GG),在所有常数 bb 里,使 E∥∇log⁡π (G−b)∥2\mathbb{E}\lVert\nabla\log\pi\,(G - b)\rVert^2 最小的 bb 是什么?它和”平均回报”有什么不同?(c) 解释代码 05 里为什么减去 baseline 后 c=0c = 0 和 c=1c = 1 的结果完全相同。

参考答案

(a) 先对 ata_t 取条件期望:Eat∼π(⋅∣st)[∇log⁡π(at∣st)] b(st)=0⋅b(st)\mathbb{E}_{a_t\sim\pi(\cdot\mid s_t)}[\nabla\log\pi(a_t \mid s_t)]\,b(s_t) = 0 \cdot b(s_t)。如果 bb 依赖 ata_t,就不能提到期望外面,一般不为 0(会引入偏差)。(b) 对 bb 求导令其为 0:b⋆=E[∥∇log⁡π∥2G] / E[∥∇log⁡π∥2]b^\star = \mathbb{E}[\lVert\nabla\log\pi\rVert^2G]\,/\,\mathbb{E}[\lVert\nabla\log\pi\rVert^2] —— 按得分函数的大小加权的平均回报。实践中直接用平均回报(或学一个 V(s)V(s)),差别通常不大。(c) 时域固定、没有终止状态时,cc 让每条轨迹的 GtG_t 都加上同一个数 c⋅(H−1−t)c\cdot(H - 1 - t);时间 baseline(或 LOO baseline)在同一个 tt 上也加上同一个数,相减后权重完全不变,所以梯度估计(以及整个训练过程,在相同随机数下)不变。

练习 6(Diagnose it). 一个机械臂在模拟器里用 RL 训练,奖励 = −(手到杯子的距离)。部署后,模拟器里和真实环境里它都能很快抓到杯子,但经常把旁边的水瓶撞倒。人类操作员也能抓到杯子而且不撞水瓶,但按这个奖励算,人类的回报比 RL 低(动作慢)。按 §6 的流程,问题出在哪?如果换一种情况:RL 在真实环境里的回报比人类低,而模拟器和真实环境里的表现一致呢?

参考答案

第一种:问题 1——模拟器和现实一致(都能抓到、都撞瓶子),不是模拟器的问题。问题 2——RL 的回报高于人类,算法确实把这个奖励优化得很好。所以是奖励函数的问题:奖励里没有表达”别撞倒东西”(加一个碰撞惩罚,或者用人类示范学奖励,即 inverse RL,CS234 第 8 讲)。第二种:模拟器没问题,而人类在同一个奖励下得分更高,说明存在更好的策略 RL 没找到 —— 是 RL 算法的问题(训练不够、探索不足、函数逼近能力不够、规划时域太短 ……)。

代码相关的练习(“动手改一改”)见 code/lecture06/README.md。


11. 延伸阅读 · Further reading

  • CS229 main notes(Ng & Ma),Ch. 15–17:本讲的主要来源(MDP、VI / PI、learning a model、continuous states、fitted VI;LQR、DDP、LQG;REINFORCE)。
  • CS229 Autumn 2018 lectures 16–20(YouTube):Andrew Ng 讲 MDP、模拟器、直升机、RL 调试的原版。
  • Sutton & Barto, Reinforcement Learning: An Introduction(2nd ed., 2018):Ch. 3–4(MDP、动态规划)、Ch. 9–11(函数逼近与 deadly triad)、Ch. 13(policy gradient)。
  • Puterman, Markov Decision Processes(1994);Puterman & Brumelle(1979):“On the convergence of policy iteration in stationary dynamic programming”:PI = Newton。
  • Gordon(1995),“Stable function approximation in dynamic programming”;Tsitsiklis & Van Roy(1996),“Feature-based methods for large scale dynamic programming”:§3.4 的收敛与发散。
  • Bertsekas, Dynamic Programming and Optimal Control:LQR、Kalman、certainty equivalence 的标准教材。
  • Jacobson & Mayne(1970),Differential Dynamic Programming;Li & Todorov(2004),iLQR;Tassa, Mansard & Todorov(2014),control-limited DDP。
  • Williams(1992),“Simple statistical gradient-following algorithms for connectionist reinforcement learning”:REINFORCE。
  • Ng & Jordan(2000),PEGASUS;Ng et al.(2004),“Autonomous inverted helicopter flight via reinforcement learning”;Abbeel, Coates & Ng(2010),“Autonomous helicopter aerobatics through apprenticeship learning”:直升机的故事。
  • Brafman & Tennenholtz(2002),R-max;Smith & Winkler(2006),“The optimizer’s curse”。

12. 课程总结 · Wrapping up CS229

这是 CS229 复习的最后一讲。回头看,大纲开头的三个想法贯穿了全部 6 讲,在本讲里也各自出现了一次:

  1. Loss = negative log-likelihood. 第 1 讲:选损失 = 选噪声模型,所有 canonical GLM 的梯度都是 (target − prediction) × input;第 2 讲:GDA 和 Naive Bayes 是生成模型的 MLE;第 5 讲:EM 最大化似然的下界。本讲:REINFORCE 的梯度就是”按回报加权的 log-likelihood 梯度”,得分函数恰好是第 1 讲的 GLM 梯度;计数估计 P^sa\hat P_{sa} 是 categorical 分布的 MLE;Kalman 滤波是高斯的条件分布。
  2. Model + loss + optimizer are independent choices. 第 1 讲的 normal equation / GD / Newton,第 2 讲的 SMO,第 5 讲的 EM,本讲的 VI(不动点迭代)、PI(Newton)、Riccati(精确的 DP)、policy gradient(随机梯度上升)—— 同一个目标可以换优化器;fitted VI 把”VI”和”第 1 讲的最小二乘”拼在一起。
  3. Fitting the training data is not the goal; generalizing is. 第 3 讲的 bias–variance、正则化、交叉验证。本讲:在学到的模型上规划会过度自信(optimizer’s curse),FVI 需要 ridge 才稳定,在模拟器里飞得好不代表在现实里飞得好(§6 的第一个问题就是在检查”对模拟器过拟合”)。

接下来学什么(都在同一个目录里):

  • CS234(强化学习):本讲 §7 的表格列出了对应关系。从第 3–5 讲(TD、Q-learning、DQN)开始,补上 CS229 没讲的 model-free 方法;第 6–7 讲接着本讲 §5 讲 actor-critic 和 PPO。
  • CS224N(NLP 与深度学习):第 4 讲的 MLP + backprop 之后的下一步 —— word vectors、RNN、Transformer、预训练。第 1 讲 §4.7 的”输出层 = GLM”在那里每天都在用。
  • CS336(从零构建语言模型):把 Transformer、分布式训练、scaling laws、对齐(RLHF / GRPO —— 正是本讲 §5 的 policy gradient 加上 baseline)落到工程上。
  • CS329H(从人类偏好中学习):Bradley–Terry 奖励模型(第 1 讲的逻辑回归)+ RLHF(本讲的 policy gradient),把第 1 讲和第 6 讲连在一起。
← 返回课程目录