学习世界模型与规划

Dive into Deep Learning · §15.6

基于模型的深度强化学习:学习世界模型与规划
动力学回归 · 推演累积误差 · 随机打靶 MPC · 热启动 · 策略蒸馏 · Dyna 与 MBPO

为何每条转移教给智能体的远不止一个标量价值

动机

  • 更丰富的监督信号:无模型 SAC 每步只提取 1 维标量评论员目标 y_t \in \mathbb{R},而世界模型向完整的 4 维物理向量 (s_{t+1} - s_t, r_t) \in \mathbb{R}^4 回归。
  • 从几千步缩减到几百步:在所学动力学模型 \hat{f}_\phi 中规划,只需 1 至 3 个回合(200–600 步真实交互) 即可甩起 Pendulum。

用最小二乘拟合神经动力学模型

世界模型回归

\min_{\phi} \sum_{i=1}^{N} \big\|\hat{f}_\phi(s_i, a_i) - (s'_i, r_i)\big\|^2

  • 1. 预测状态增量(s' - s):在 \Delta t = 0.05\text{ s} 内 s' \approx s;通过跳跃连接 \hat{s}' = s + \Delta\hat{s} 预测残差 \Delta s = s' - s,让网络容量聚焦于变化量。
  • 2. 坐标标准化:对每个输入和目标维度做 Z-score 标准化,防止高方差奖励 r \in [-16.2, 0] 主导 L_2 损失。

DynamicsModel 架构与标准化

模型实现

DynamicsModel 采用双层 64 单元平滑 SiLU 多层感知机,并将数据集的标准化统计量 (\mu_x, \sigma_x, \mu_y, \sigma_y) 直接保存在模块内:

class DynamicsModel(nn.Module):
    """(s', r) from (s, a): an MLP that maps standardized inputs to the
    standardized change of state and reward."""
    def __init__(self, obs_dim=3, act_dim=1, hidden=64):
        super().__init__()
        d_in, d_out = obs_dim + act_dim, obs_dim + 1
        self.net = nn.Sequential(nn.Linear(d_in, hidden), nn.SiLU(),
                                 nn.Linear(hidden, hidden), nn.SiLU(),
                                 nn.Linear(hidden, d_out))
        self.register_buffer('mu_x', torch.zeros(d_in))   # standardization
        self.register_buffer('sd_x', torch.ones(d_in))
        self.register_buffer('mu_y', torch.zeros(d_out))
        self.register_buffer('sd_y', torch.ones(d_out))

DynamicsModel 架构与标准化(续)

模型实现

forward 将网络输出映射回原始数据量纲,make_model 将模型与其 Adam 优化器配对:

    def forward(self, obs, act):
        x = (torch.cat([obs, act], -1) - self.mu_x) / self.sd_x
        y = self.net(x) * self.sd_y + self.mu_y   # (s' - s, r) in data units
        return obs + y[..., :-1], y[..., -1]

def make_model(seed, lr=1e-3):
    torch.manual_seed(seed)
    model = DynamicsModel()
    return model, torch.optim.Adam(model.parameters(), lr=lr)

DynamicsModel 架构与标准化(拟合)

模型实现

fit_model 将数据统计量拷贝进模块,随后在标准化后的输入和目标上回归网络:

def fit_model(model, opt, buffer, rng, num_steps=fit_steps, batch_size=256):
    """Least squares on all stored transitions, in standardized units."""
    x, y, stats = model_data(buffer)
    model.mu_x, model.sd_x, model.mu_y, model.sd_y = map(torch.as_tensor,
                                                         stats)
    mu_x, sd_x, mu_y, sd_y = stats
    x = torch.as_tensor((x - mu_x) / sd_x)
    y = torch.as_tensor((y - mu_y) / sd_y)
    for _ in range(num_steps):
        i = torch.as_tensor(rng.integers(len(x), size=batch_size))
        loss = ((model.net(x[i]) - y[i]) ** 2).mean()
        opt.zero_grad()
        loss.backward()
        opt.step()
    return float(loss.detach())

单个随机回合上的单步预测精度

单步验证

仅在一个随机回合(200 条转移) 上用 1{,}000 步 Adam 拟合 DynamicsModel,并在物理单位下检查转移 i = 100:

return of the random episode: -1072
final minibatch loss (standardized units): 0.0018
s        [-0.9407 -0.3394  5.6896] a = -0.0800
true s'  [-0.8154 -0.5789  5.4231] r = -11.0511
model s' [-0.8109 -0.584   5.436 ] r = -11.2768
angle error 0.386 degrees

在第 100 步(\vartheta = -160.2^\circ,\dot\vartheta = 5.69\text{ rad/s}),摆杆在 0.05\text{ s} 内转动 15.6^\circ;所学模型对下一角度的预测误差在 0.4^\circ 以内(0.30^\circ–0.39^\circ),对奖励(-11.05)的预测误差不到 0.25。

自回归推演与累积模型误差

视野瓶颈

为了评估由 n = 25 个力矩构成的候选序列,模型必须自回归(开环)推演,将每步预测的状态 \hat{s}_{t+1} 反馈为第 t+1 步的输入:

@torch.inference_mode()
def rollout_model(model, obs, actions):
    """Open-loop rollout in the model: obs (..., 3) and actions (..., n, 1)
    give the predicted states (..., n, 3) and rewards (..., n), numpy in
    and out."""
    s, actions = torch.as_tensor(obs), torch.as_tensor(actions)
    states, rewards = [], []
    for t in range(actions.shape[-2]):
        s, r = model(s, actions[..., t, :])
        states.append(s)
        rewards.append(r)
    return torch.stack(states, -2).numpy(), torch.stack(rewards, -1).numpy()

自回归推演与累积模型误差(续)

视野瓶颈

seed   k=1    k=5   k=10   k=25   (degrees, held-out random episode)
   0   0.44   1.91   2.52   1.51
   1   1.83   7.08   8.67  12.29
   2   0.53   2.37   3.65   5.51
   3   0.38   1.89   4.77  11.82
   4   0.04   0.12   0.13   0.33
  • 误差为何累积:模型只在真实状态上训练,从未见过自身略带扰动的预测;微小的角度误差改变预测的重力力矩,进而扰动角速度,在 k = 10 \to 25 步间滚雪球般放大。

随机打靶:在想象中为候选序列排序

搜索规划

在状态 s 处,随机打靶抽取 J 条候选动作序列 A^{(j)} = (a_0^{(j)}, \dots, a_{n-1}^{(j)}),在 \hat{f}_\phi 中并行推演所有 J 条序列,并以预测的 n 步回报 \hat{G}^{(j)} = \sum_{t=0}^{n-1} \hat{r}_t^{(j)} 打分:

first actions [ 0.55 -0.92 -1.84]  predicted  -174.2  true  -237.6
first actions [-0.47  1.99  1.92]  predicted  -173.8  true  -232.7
first actions [ 1.15 -1.04  1.51]  predicted  -174.3  true  -229.4
first actions [-0.3   0.48  1.98]  predicted  -170.7  true  -223.2
first actions [-0.08 -1.07  1.21]  predicted  -174.5  true  -242.4

排序与校准:从底部静止状态(\vartheta = \pi,静止悬垂 25 步损失 -247)出发,由于随机训练回合高速掠过底部,模型对每条序列都高估了 40–70 分——但模型仍然把真实最优序列排在了第一。

带移位热启动的滚动时域 MPC

模型预测控制

  • 滚动时域执行(MPC,§14.6):正如 §14.6 中的解析 MPC,只执行最优 25 步方案的第一个力矩 a_0^\star,观测真实下一状态 s_{t+1} 后重新规划——防止开环模型误差沿真实轨迹累积。
  • 热启动搜索:在第 t+1 步不再重抽 500 条全新随机序列,而是将第 t 步的胜出方案前移 1 步、末尾补 0,再叠加高斯噪声扰动(\sigma = c = 2,并保留未扰动的移位方案作为候选 0)。

实现向量化随机打靶搜索

搜索实现

对一批 B 个状态,plan 将初始 n 步动作序列扰动成 num_cand = 500 个候选(下标 0 保留原序列),将力矩截断到 [-c, c],并在单次批处理 rollout_model 调用中评估全部 B \times 500 \times 25 步:

def plan(model, obs, init, rng, noise=c, num_cand=num_cand, scale=c):
    """Random shooting around a plan for each of B states: obs (B, 3), init
    (B, n, 1). Each plan is perturbed into num_cand candidates (the plan
    itself is one), all are rolled out in the model, and the candidate with
    the highest predicted return is returned with that return."""
    B = len(obs)
    A = init[:, None] + noise * rng.standard_normal(
        (B, num_cand) + init.shape[1:], dtype=np.float32)
    A[:, 0] = init
    A = np.clip(A, -scale, scale)
    s = np.repeat(obs[:, None], num_cand, axis=1)          # (B, num_cand, 3)
    ret = rollout_model(model, s, A)[1].sum(-1)            # (B, num_cand)
    best = ret.argmax(1)
    return A[np.arange(B), best], ret[np.arange(B), best]

实现热启动滚动时域 MPC

MPC 控制器

mpc 在闭包中保存上一步的胜出方案,将其前移一步(plans[:, 1:] 后接零力矩),并仅执行新精炼方案的第一个力矩 plans[:, 0]:

def mpc(model, rng, horizon=horizon, noise=c):
    """Model-predictive control: at every step plan in the model, starting
    from the previous plan shifted by one step, and execute its first
    action."""
    plans = None
    def controller(obs):
        nonlocal plans
        if plans is None:
            plans = np.zeros((len(obs), horizon, 1), np.float32)
        shifted = np.concatenate([plans[:, 1:], np.zeros_like(plans[:, :1])],
                                 1)
        plans = plan(model, obs, shifted, rng, noise)[0]
        return plans[:, 0]
    return controller

在 600 步真实交互下的 5 个种子上,热启动将 10 起点测试回报从 [-555, -165](每步冷启动随机打靶)提升至 [-155, -115]。

仅用 200 至 600 步环境交互甩起倒立摆

少回合起摆

从 1 个随机回合(200 步)出发,mpc_run 交替在全部已采集转移上重拟合模型、在 10 个固定测试起点上评分 MPC 规划器,并用 MPC 采集 1 个新回合:

seed  episode returns: random, MPC x 3 |  test score at 200/400/600/800 steps
   0   -1072   -242   -118   -125  |    -181   -168   -168   -171
   1    -876   -264   -121   -123  |    -266   -201   -204   -180
   2    -966   -122   -125   -116  |    -337   -190   -168   -169
   3   -1501  -1287   -246     -2  |   -1464   -265   -191   -195
   4   -1703  -1576  -1323   -120  |   -1567  -1437   -171   -187
  • 10 起点基准(天花板 \approx -170):到 600 步真实交互(3 个回合) 时,每个种子得分均在 -165 到 -215 之间——其中 5 个种子里有 3 个仅凭单个随机回合(200 步) 就已成功起摆。

支撑集外外推与自我纠正

覆盖度分析

为什么种子 3 和 4 在首个随机回合(200 步)后得分仅 \sim -1{,}500,到 600 步却成功起摆?在规划器后续起摆轨迹上评估 200 步模型即可查明原因:

seed   k=1    k=5   k=10   k=25   (degrees, the planner's episodes)
   0    0.3    1.4    3.3   42.4
   1    0.4    1.5    2.6   40.2
   2    0.2    0.9    1.7   28.3
   3    6.8   41.3   61.5  138.8
   4   14.8   71.9   89.8  128.3

源于模型乐观的隐式探索:在种子 3 和 4 上,初始随机回合从未把摆杆抬过水平面,因此 200 步模型在上半平面仅 5 步内就有 40^\circ–72^\circ 的误差。然而哪怕失败的 MPC 起摆也会把摆杆推入未曾访问的上半角度并记录真实物理,从而让下一次重拟合大获成功。

经验与计算之争:MPC 规划器与 SAC 对比

系统权衡

  • 热启动 MPC 规划器:仅需 200–800 步真实交互即可解出 Pendulum,但测试期每步控制都要执行 500 \times 25 = 12{,}500 次模型调用(\sim\text{ms})。
  • 无模型 SAC(UTD = 1 至 10):需要 1{,}600–7{,}500 步真实交互,但把规划摊销进策略权重 \theta 中,测试期只需一次演员前向传播(\sim\mu\text{s})。

将搜索作为策略改进算子

演员引导搜索

  • \hat{f}_\phi 内的单调改进:将演员自身未扰动的推演方案设为 plan 的候选 0,保证胜出候选的预测回报至少不低于演员方案。
def actor_plan(model, actor, obs, horizon=horizon):
    """The actor's own deterministic plan for each state, imagined in the
    model: (B, n, 1)."""
    acts = []
    for _ in range(horizon):
        acts.append(actor.act_greedy(obs))
        obs = rollout_model(model, obs, acts[-1][:, None])[0][:, 0]
    return np.stack(acts, 1)

def improve(model, actor, obs, rng, noise=c):
    """Search seeded by the actor: the best first action for each state."""
    return plan(model, obs, actor_plan(model, actor, obs), rng, noise)[0][:, 0]

将搜索标签蒸馏进演员网络

策略蒸馏

  • 将搜索摊销进 \pi_\theta:以 L_2 损失(distill)将演员的确定性均值 c\tanh\mu_\theta(s) 向 500 候选搜索动作 improve(model, actor, obs) 回归。

将搜索标签蒸馏进演员网络(代码)

策略蒸馏

def make_actor(seed, lr=1e-3):
    actor = d2l.SquashedGaussianPolicy(3, 1, scale=c, seed=seed)
    return actor, torch.optim.Adam(actor.parameters(), lr=lr)

def distill(actor, opt, obs, labels, rng, num_steps=1_000, batch_size=256):
    """Regress the actor's mean action, scale * tanh(mean), onto labels."""
    obs, labels = torch.as_tensor(obs), torch.as_tensor(labels)
    for _ in range(num_steps):
        i = torch.as_tensor(rng.integers(len(obs), size=batch_size))
        a = actor.scale * torch.tanh(actor.policy(obs[i])[0])
        loss = ((a - labels[i]) ** 2).mean()
        opt.zero_grad()
        loss.backward()
        opt.step()
    return float(loss.detach())

迭代搜索与蒸馏(AlphaZero 循环)

搜索与蒸馏

  • search_and_distill 每轮重拟合 \hat{f}_\phi,用演员引导搜索 improve 标注 200 个缓冲区状态,将 \bar{a}_\theta(s) 向这些标签回归(distill),再用搜索决策采集 1 个回合。
  • 带搜索决策(蓝色):在 2–3 轮(400–600 步)内稳定起摆。
  • 仅靠演员(橙色):虽从 -1{,}400 升向 -200,但因协变量偏移(无 DAgger 聚合的模仿学习)与 500 样本打靶标签噪声而落后于实时搜索。

final score on the ten starts, acting with search: -191 -202 -222

Dyna 与 MBPO:想象转移与高 UTD 对比

模型生成数据

  • 短分支推演(Janner 等,2019):从真实缓冲区状态出发在 \hat{f}_\phi 中分支推演 k = 3 步,使合成数据紧贴真实状态分布而避免长视野漂移。
  • 匹配 UTD 消融(我们的实验):在相同 UTD = 10 下,95\% 想象批次达 -200 需 1{,}500–3{,}000 真实步,纯真实回放需 1{,}500–2{,}500 步:模型并未减少真实步数。无模型高 UTD 评论员集成(REDQ,Chen 等,2021)同样追平 MBPO。

概念检验:视野、增量与集成

检验理解

思考以下三道基于模型的设计题:

  1. 规划视野权衡:在 Pendulum(\Delta t = 0.05\text{ s})上,将随机打靶视野从 n = 25 缩短到 n = 5 会出什么问题?拉长到 n = 100 又会出什么问题?
  2. 为何预测状态增量? 为什么训练多层感知机预测标准化残差 (s' - s)/\sigma_{\Delta s},而不是在原始坐标下直接预测 s'?
  3. 模型集成:如果在种子 4 的单个随机回合上从不同随机初始化训练 M = 5 个动力学网络集成 \hat{f}_{\phi_1}, \dots, \hat{f}_{\phi_5},它们的预测在何处分歧最大?

解答:

  1. 在 n = 5(0.25\text{ s}) 时,规划器过于短视,看不到在底部蓄能会在 20 步后带来接近直立的高回报;在 n = 100(5.0\text{ s}) 时,开环累积误差使后期预测奖励沦为纯噪声。
  2. 当 \Delta t = 0.05\text{ s} 时 s' \approx s,直接预测会把大部分容量浪费在学习恒等映射 s' = s 上;且未标准化的均方误差会被奖励 r \in [-16, 0](\text{var} \sim 20)淹没,盖过 \Delta\cos\vartheta(\text{var} \sim 0.01)。
  3. 5 个网络在下半圆(训练数据所在处)高度一致,而在未访问的上半圆分歧巨大——使集成方差成为有效的认知不确定性信号(PETS;Chua 等,2018)。

小结:基于模型的深度强化学习

核心要点

方法 / 组件 数学机制 核心优势 主要局限
状态增量 MLP(\hat{f}_\phi) \hat{s}' = s + \sigma_{\Delta s} f_\phi((s,a-\mu_x)/\sigma_x) + \mu_{\Delta s} 凭 200 步学出全局物理 k 步推演存在累积误差
随机打靶 MPC \operatorname{argmax}_{A^{(j)}} \sum_{t=0}^{n-1} \hat{r}_t^{(j)},仅执行 a_0^\star 每步重规划阻断误差累积 测试期算力开销高(J \times n 次模型调用)
移位热启动 以第 t-1 步的 A^\star_{1:n} 为中心采样候选 跨时间延续优质多步方案 可能陷在局部轨迹模态中
搜索蒸馏 将演员 \bar{a}_\theta(s) 向演员引导的 improve(s) 回归 测试期 O(1) 快速策略推理 若不聚合标签(DAgger)会出现协变量偏移
Dyna / MBPO 推演 用短 k 步模型推演训练评论员 成倍扩充评论员更新数据 相同 UTD 下纯真实回放往往表现相当