import gymnasium as gym15.6 学习世界模型与规划
柔性演员–评论员只用几千条转移就将倒立摆甩了起来,但它对待每条转移的方式完全相同:仅作为评论员单次回归的一个标量目标——即时奖励加上下一状态的折扣价值。然而一条转移记录的信息远不止于此。它展示了摆杆在特定力矩下的运动方式,而支配这一运动的物理规律在每次访问中都完全相同。在秋千上被人推过几次的孩子,就能预判片刻之后秋千会荡到哪里、该用多大力气才能推得更高。智能体能否在没有评论员也没有策略的情况下,仅从几百步交互中学出摆杆的物理规律,并借此规划出起摆方案?
14.3 节 在冰湖上正是这么做的:它通过计数将所见转移汇总成估计模型,并把该估计当作精确模型运行价值迭代。14.6 节 则利用已知物理方程在 Pendulum 的连续状态上通过 iLQR 求导规划,并借助滚动时域模型预测控制(MPC)每步重规划。当物理规律未知时,Pendulum 的连续状态无法靠计数统计,于是回归取代了计数:由神经网络根据当前状态和力矩预测下一状态与即时奖励。滚动时域搜索则取代了价值迭代或 iLQR:智能体在所学模型中尝试大量力矩序列,并执行最优序列的第一个力矩。Sutton 于 1990 年提出的 Dyna 架构便将学习模型与规划结合 (Sutton 1990年),而按此方式搜索神经网络模型的方法仅凭几分钟经验就能控制仿真机器人 (Nagabandi 等 2018年)。
模型让智能体能够以计算换经验:每走一步真实交互,都可以跟随数千步想象推演。搜索还可以从策略的提议出发,再把搜索结果反哺回策略。AlphaZero 与 MuZero 正是借此在下棋中超越人类顶尖水平 (Silver 等 2018年; Schrittwieser 等 2020年),而由学习策略引导的搜索也是语言模型在测试期投入额外算力的方式之一。本节先从单个随机回合拟合 Pendulum 的动力学模型,测量其误差如何沿规划视野累积,接着用模型做规划,再将搜索转化为更好的策略。一个核心问题贯穿始终:在远离训练数据之处,模型究竟能被信任多远?
# Deterministic XLA kernels. On an accelerator XLA otherwise picks each
# matrix product's kernel by timing candidates, and kernels that add in
# different orders differ in the last bits; training runs at large step
# sizes can turn such differences into different outcomes. JAX reads
# XLA_FLAGS once, when it starts, so this cell runs before the imports.
import os
os.environ['XLA_FLAGS'] = (os.environ.get('XLA_FLAGS', '') +
' --xla_gpu_deterministic_ops=true').strip()import gymnasium as gymtorch.set_num_threads(1)15.6.1 从数据学习动力学模型
15.6.1.1 以回归取代计数
Pendulum(Pendulum-v1)是 14.6 节 在已知物理规律下引入、又在 14.9 节 与 15.5 节 中以无模型方法求解的连续控制基准。一根摆杆悬挂在电机驱动的枢轴上;状态为 \(s = (\cos\vartheta, \sin\vartheta, \dot\vartheta)\)(\(\vartheta\) 为偏离竖直向上的夹角),动作为力矩 \(a \in [-2, 2]\)。每步奖励为 \(-(\vartheta^2 + 0.1\,\dot\vartheta^2 + 0.001\,a^2)\)(\(\vartheta\) 折回到 \([-\pi, \pi]\)),每回合长 200 步。静止悬垂在底部的摆杆每步损失 \(\pi^2 \approx 9.9\),整回合损失约 \(2{,}000\);随机力矩损失约 \(900\) 到 \(1{,}700\);而能甩起并平衡的控制器可跨过 14.6 节 与 14.9 节 的 \(-200\) 门槛,视起始位置不同损失零到数百分。
环境的模型预测环境的响应。记参数为 \(\phi\) 的网络 \(\hat f_\phi\) 将状态与动作映射为预测的下一状态和奖励:
\[(\hat s', \hat r) = \hat f_\phi(s, a). \tag{15.6.1}\]
在冰湖上模型是一张频率表,每个表项仅由对应状态–动作对的访问次数估计。神经网络跨状态共享参数,因此某个角度处的一条转移也能教会模型附近角度的规律。我们在存储转移 \((s_i, a_i, r_i, s'_i)\) 上通过最小二乘拟合它:
\[ \min_\phi \sum_i \big\| \hat f_\phi(s_i, a_i) - (s'_i, r_i) \big\|^2. \tag{15.6.2}\]
拟合要求模型复现每条存储转移记录的下一状态和奖励。若用表格代替网络,每个状态–动作对处的极小化结果就是那里观测到的结果均值——即 14.3 节 的计数模型简化为均值。Pendulum 是确定性环境,因此平均结果就是确切结果;而随机环境则需要像冰湖计数那样对整个下一状态分布建模。
两项设计让回归变得轻松。第一,网络预测状态变化量 \(s' - s\) 而非 \(s'\) 本身,因为在 0.05 秒的单步内摆杆位移很小,真正值得学习的是增量。第二,在存储数据上将每个输入和目标坐标标准化为零均值、单位方差,因为各坐标量纲悬殊:余弦和正弦落在 \([-1, 1]\),角速度在 \([-8, 8]\),而奖励大约在 \([-16, 0]\)。不做标准化的话,最小二乘几乎只会去拟合奖励。
先设定全节共用参数:力矩上限 \(c = 2\)、规划深度 \(n = 25\)、搜索尝试的候选方案数、每次模型拟合的 Adam 步数、随机种子数,以及固定测试起始状态的种子。
c, horizon, num_cand = 2.0, 25, 500 # torque bound, depth n, candidates
fit_steps, num_seeds, test_seed = 1_000, 5, 1_000c, horizon, num_cand = 2.0, 25, 500 # torque bound, depth n, candidates
fit_steps, num_seeds, test_seed = 1_000, 5, 1_000数据按完整回合采集。run_episode 在向量化环境(Gymnasium 中同步推进多个 Pendulum 副本的容器)中行动,单次调用即可同时从十个起始状态运行控制器。控制器是任意将一批观测映射为一批动作的函数,random_controller 返回抽取均匀随机力矩的控制器。score 在环境种子 1000 到 1009 对应的十个固定起始状态上运行控制器一个回合并返回平均回报,作为本节所有控制器的统一测试分。转移存入 15.5 节 的浮点动作经验回放池 d2l.ReplayBufferC,这里只把它当作数组存储器,不从中抽样小批量。
def run_episode(envs, controller, buffer=None, seed=None, num_steps=200):
"""One episode in every environment of a vector env, acting by
controller(obs) -> actions. Returns the returns; records transitions."""
obs, total = envs.reset(seed=seed)[0], 0.0
for _ in range(num_steps):
act = controller(obs)
next_obs, rew, term, _, _ = envs.step(act)
for i in range(envs.num_envs if buffer is not None else 0):
buffer.add(obs[i], act[i], rew[i], next_obs[i], float(term[i]))
obs, total = next_obs, total + rew
return total
def random_controller(rng, scale=c):
"""Uniformly random torques: the data of the first episode."""
return lambda obs: rng.uniform(-scale, scale, (len(obs), 1)).astype(
np.float32)
def score(controller, num_starts=10, seed=test_seed):
"""Mean return of a controller over ten fixed Pendulum starts."""
envs = gym.make_vec('Pendulum-v1', num_envs=num_starts,
vectorization_mode='sync')
return run_episode(envs, controller, seed=seed).mean()def run_episode(envs, controller, buffer=None, seed=None, num_steps=200):
"""One episode in every environment of a vector env, acting by
controller(obs) -> actions. Returns the returns; records transitions."""
obs, total = envs.reset(seed=seed)[0], 0.0
for _ in range(num_steps):
act = controller(obs)
next_obs, rew, term, _, _ = envs.step(act)
for i in range(envs.num_envs if buffer is not None else 0):
buffer.add(obs[i], act[i], rew[i], next_obs[i], float(term[i]))
obs, total = next_obs, total + rew
return total
def random_controller(rng, scale=c):
"""Uniformly random torques: the data of the first episode."""
return lambda obs: rng.uniform(-scale, scale, (len(obs), 1)).astype(
np.float32)
def score(controller, num_starts=10, seed=test_seed):
"""Mean return of a controller over ten fixed Pendulum starts."""
envs = gym.make_vec('Pendulum-v1', num_envs=num_starts,
vectorization_mode='sync')
return run_episode(envs, controller, seed=seed).mean()model_data 将存储的转移整理为回归的输入 \((s, a)\) 与目标 \((s' - s, r)\),并计算各自的均值和标准差。
def model_data(buffer):
"""Inputs (s, a) and targets (s' - s, r) of the stored transitions,
with their means and standard deviations."""
n = buffer.size
x = np.concatenate([buffer.obs[:n], buffer.act[:n]], -1)
y = np.concatenate([buffer.next_obs[:n] - buffer.obs[:n],
buffer.rew[:n, None]], -1)
return x, y, (x.mean(0), x.std(0) + 1e-6, y.mean(0), y.std(0) + 1e-6)def model_data(buffer):
"""Inputs (s, a) and targets (s' - s, r) of the stored transitions,
with their means and standard deviations."""
n = buffer.size
x = np.concatenate([buffer.obs[:n], buffer.act[:n]], -1)
y = np.concatenate([buffer.next_obs[:n] - buffer.obs[:n],
buffer.rew[:n, None]], -1)
return x, y, (x.mean(0), x.std(0) + 1e-6, y.mean(0), y.std(0) + 1e-6)DynamicsModel 是一个两层 64 单元、采用平滑 SiLU 激活(4.1 节)的多层感知机。它将标准化统计量与参数一同保存为模块状态;前向传播先对输入做标准化,再对输出反标准化,并将预测的状态增量加回当前状态。fit_model 根据全部已存数据重算统计量,再在 256 条转移的小批量上执行 Adam 更新。优化器随模型在 make_model 中一并创建,因此后续每次重新拟合都接着上次参数继续,而非从头开始。
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))
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)
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())class DynamicsModel(nnx.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, rngs=None):
d_in, d_out = obs_dim + act_dim, obs_dim + 1
self.net = nnx.Sequential(
d2l.Linear(d_in, hidden, rngs=rngs), jax.nn.silu,
d2l.Linear(hidden, hidden, rngs=rngs), jax.nn.silu,
d2l.Linear(hidden, d_out, rngs=rngs))
self.stats = nnx.Variable((jnp.zeros(d_in), jnp.ones(d_in),
jnp.zeros(d_out), jnp.ones(d_out)))
def __call__(self, obs, act):
mu_x, sd_x, mu_y, sd_y = self.stats.get_value()
x = (jnp.concatenate([obs, act], -1) - mu_x) / sd_x
y = self.net(x) * sd_y + mu_y # (s' - s, r) in data units
return obs + y[..., :-1], y[..., -1]
def make_model(seed, lr=1e-3):
model = DynamicsModel(rngs=nnx.Rngs(seed))
return model, nnx.Optimizer(model, optax.adam(lr), wrt=nnx.Param)
@nnx.jit
def model_step(model, opt, x, y):
loss = lambda m: ((m.net(x) - y) ** 2).mean()
value, grads = nnx.value_and_grad(loss)(model)
opt.update(model, grads)
return value
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.stats.set_value(tuple(jnp.asarray(v) for v in stats))
mu_x, sd_x, mu_y, sd_y = stats
x, y = (x - mu_x) / sd_x, (y - mu_y) / sd_y
step = nnx.cached_partial(model_step, model, opt)
for _ in range(num_steps):
i = rng.integers(len(x), size=batch_size)
loss = step(x[i], y[i])
return float(loss)网络层采用 d2l.Linear,与这两章所有 JAX 网络的初始化方式一致(14.9 节)。统计量保存在 nnx.Variable 中,使下文编译函数在每次重拟合后读取最新值。model_step 是编译后的单步 Adam 更新,nnx.cached_partial 在每次拟合时将模型与优化器一次性绑定到它上面。
我们用种子 0 采集一个随机力矩回合,并在其 200 条转移上拟合模型:
env = gym.make_vec('Pendulum-v1', num_envs=1, vectorization_mode='sync')
rng = np.random.default_rng(0)
buffer = d2l.ReplayBufferC(200, 3, 1)
print(f'return of the random episode: '
f'{run_episode(env, random_controller(rng), buffer, seed=0)[0]:.0f}')
model, opt = make_model(0)
print(f'final minibatch loss (standardized units): '
f'{fit_model(model, opt, buffer, rng):.4f}')return of the random episode: -1072
final minibatch loss (standardized units): 0.0018
env = gym.make_vec('Pendulum-v1', num_envs=1, vectorization_mode='sync')
rng = np.random.default_rng(0)
buffer = d2l.ReplayBufferC(200, 3, 1)
print(f'return of the random episode: '
f'{run_episode(env, random_controller(rng), buffer, seed=0)[0]:.0f}')
model, opt = make_model(0)
print(f'final minibatch loss (standardized units): '
f'{fit_model(model, opt, buffer, rng):.4f}')return of the random episode: -1072
final minibatch loss (standardized units): 0.0013
随机回合大约损失一千,而拟合结束时的损失仅占标准化后目标方差(为 1)的很小一部分。
15.6.1.2 手算一步预测
训练损失很小并不直接说明模型预测得怎样。我们在原问题的物理量纲下检视该回合中的一条转移。rollout_model 将一个状态和一串动作喂入模型,每步把预测状态送作下一步输入;传入单个动作时就是单步预测。
@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()@nnx.jit
def _rollout_model(model, obs, actions):
def step(s, a):
s, r = model(s, a)
return s, (s, r)
_, (states, rewards) = jax.lax.scan(step, obs,
jnp.moveaxis(actions, -2, 0))
return jnp.moveaxis(states, 0, -2), jnp.moveaxis(rewards, 0, -1)
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."""
return jax.tree.map(np.asarray, _rollout_model(model, obs, actions))rollout_model 在编译函数 _rollout_model 中用 jax.lax.scan 逐步推进,按输入形状各编译一次,而本节只用到寥寥几种形状;结果与另一标签页一样以 NumPy 数组返回。
def angle(s):
"""Angle from upright in degrees, from states (cos, sin, velocity)."""
return np.degrees(np.arctan2(s[..., 1], s[..., 0]))
i = 100
pred, r_hat = rollout_model(model, buffer.obs[i], buffer.act[i][None])
print('s ', buffer.obs[i].round(4), f'a = {buffer.act[i, 0]:.4f}')
print("true s' ", buffer.next_obs[i].round(4), f'r = {buffer.rew[i]:.4f}')
print("model s'", pred[0].round(4), f'r = {r_hat[0]:.4f}')
print(f'angle error {abs(angle(pred[0]) - angle(buffer.next_obs[i])):.3f} '
f'degrees')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
def angle(s):
"""Angle from upright in degrees, from states (cos, sin, velocity)."""
return np.degrees(np.arctan2(s[..., 1], s[..., 0]))
i = 100
pred, r_hat = rollout_model(model, buffer.obs[i], buffer.act[i][None])
print('s ', buffer.obs[i].round(4), f'a = {buffer.act[i, 0]:.4f}')
print("true s' ", buffer.next_obs[i].round(4), f'r = {buffer.rew[i]:.4f}')
print("model s'", pred[0].round(4), f'r = {r_hat[0]:.4f}')
print(f'angle error {abs(angle(pred[0]) - angle(buffer.next_obs[i])):.3f} '
f'degrees')s [-0.9407 -0.3394 5.6896] a = -0.0800
true s' [-0.8154 -0.5789 5.4231] r = -11.0511
model s' [-0.8115 -0.5825 5.4327] r = -11.1913
angle error 0.295 degrees
在第 100 步,摆杆位于 \(\vartheta = \operatorname{atan2}(-0.3394, -0.9407) = -2.795\) 弧度(偏离竖直向上约 \(160\) 度),以每秒 \(5.69\) 弧度的速度摆动,此时力矩几乎为零。即时奖励为 \(-(2.795^2 + 0.1 \cdot 5.690^2 + 0.001 \cdot 0.08^2) = -11.05\),与打印值吻合。在单步 0.05 秒内,角度转至 \(\operatorname{atan2}(-0.5789, -0.8154) = -144.6\) 度,约转动 \(5.6 \times 0.05 = 0.28\) 弧度即 16 度,模型将该位移预测到了零点几度以内,奖励误差也不到零点三。单步预测很容易:它只是对模型刚见过的状态做一次微小修正。
15.6.1.3 累积误差
规划绝非一步之遥。为了给一串力矩打分,模型必须向前预测 25 步,且从第二步起输入的就是它自己上一步的预测。模型只在真实状态上训练过,从未见过自己略带偏差的预测状态,因此一步的误差会篡改下一步的输入:角度的一点误差改变重力力矩,进而改变角速度,再进一步放大角度误差。我们通过开环推演来测量这种效应——严格按回合记录的动作序列推进,同时让模型自行预测状态——并比较 \(k\) 步后的预测角度与真实角度。
kstep_error 从回合中每个距末尾至少还有 25 步的时刻发起推演,并报告 \(k = 1, 5, 10, 25\) 步后角度的均方根误差(按圆周折回,使 \(+179\) 度与 \(-179\) 度相差 2 度)。
def kstep_error(model, buffer, first=0, ks=(1, 5, 10, 25), T=200):
"""RMS angle error (degrees) of open-loop model rollouts along the
recorded actions, from every step of the stored T-step episodes (rows
first onward) that leaves max(ks) steps before the episode ends."""
n = max(ks)
ep = lambda x: x[first:buffer.size].reshape(-1, T, *x.shape[1:])
obs, act, nxt = ep(buffer.obs), ep(buffer.act), ep(buffer.next_obs)
windows = lambda x: np.stack([x[:, t:t + n]
for t in range(T - n + 1)], 1)
pred = rollout_model(model, obs[:, :T - n + 1], windows(act))[0]
d = np.radians(angle(pred) - angle(windows(nxt)))
d = np.arctan2(np.sin(d), np.cos(d)) # wrapped to (-pi, pi]
return [np.degrees(np.sqrt(np.mean(d[..., k - 1] ** 2))) for k in ks]def kstep_error(model, buffer, first=0, ks=(1, 5, 10, 25), T=200):
"""RMS angle error (degrees) of open-loop model rollouts along the
recorded actions, from every step of the stored T-step episodes (rows
first onward) that leaves max(ks) steps before the episode ends."""
n = max(ks)
ep = lambda x: x[first:buffer.size].reshape(-1, T, *x.shape[1:])
obs, act, nxt = ep(buffer.obs), ep(buffer.act), ep(buffer.next_obs)
windows = lambda x: np.stack([x[:, t:t + n]
for t in range(T - n + 1)], 1)
pred = rollout_model(model, obs[:, :T - n + 1], windows(act))[0]
d = np.radians(angle(pred) - angle(windows(nxt)))
d = np.arctan2(np.sin(d), np.cos(d)) # wrapped to (-pi, pi]
return [np.degrees(np.sqrt(np.mean(d[..., k - 1] ** 2))) for k in ks]对五个种子中的每一个,我们在一个随机回合上拟合模型,并在同一种子的第二个随机回合上测试:
models = []
print('seed k=1 k=5 k=10 k=25 (degrees, held-out random episode)')
for seed in range(num_seeds):
rng = np.random.default_rng(seed)
train, test = d2l.ReplayBufferC(200, 3, 1), d2l.ReplayBufferC(200, 3, 1)
run_episode(env, random_controller(rng), train, seed=seed)
run_episode(env, random_controller(rng), test)
m, o = make_model(seed)
fit_model(m, o, train, rng)
models.append((m, test))
errors = kstep_error(m, test)
print(f'{seed:4d} ' + ' '.join(f'{e:6.2f}' for e in errors))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
models = []
print('seed k=1 k=5 k=10 k=25 (degrees, held-out random episode)')
for seed in range(num_seeds):
rng = np.random.default_rng(seed)
train, test = d2l.ReplayBufferC(200, 3, 1), d2l.ReplayBufferC(200, 3, 1)
run_episode(env, random_controller(rng), train, seed=seed)
run_episode(env, random_controller(rng), test)
m, o = make_model(seed)
fit_model(m, o, train, rng)
models.append((m, test))
errors = kstep_error(m, test)
print(f'{seed:4d} ' + ' '.join(f'{e:6.2f}' for e in errors))seed k=1 k=5 k=10 k=25 (degrees, held-out random episode)
0 0.22 0.82 1.15 3.33
1 1.40 4.83 6.87 15.09
2 0.61 2.75 4.12 4.02
3 0.44 1.61 2.56 6.04
4 0.03 0.11 0.19 0.30
在每个种子上,十步后的误差都是单步误差的数倍,而单步误差在多数种子上不到一度。25 步后的误差因种子而异,但在这些留出随机回合上仍低于约 20 度:在随机力矩下,摆杆始终在底部附近晃荡,这正是训练回合覆盖的区域。等规划器把摆杆带到别处之后,我们还会回头审视这一前提。
规划深度就像 15.1 节 中 \(n\) 步回报的 \(n\) 一样是个权衡旋钮。更深的规划能看清力矩更长远的后果:起摆需要几十步蓄能,在摆杆升起前就截断的规划分不清好坏蓄能序列。但每多推演一步就会把模型误差叠加上去。这里取 \(n = 25\) 步(1.25 秒),1 将调节这一旋钮。
15.6.2 在模型中规划
15.6.2.1 随机打靶
在模型内部试跑一串力矩只需几次矩阵乘法,不耗费任何真实步数。最简单的搜索直接利用这一点。设摆杆静止悬垂在底部:我们随机抽取五条长度为 25 的力矩序列,在上文拟合的模型里逐一推演,并累加各自的预测奖励:
rng = np.random.default_rng(0)
s = np.array([[-1.0, 0.0, 0.0]], np.float32) # hanging down, at rest
A = rng.uniform(-c, c, (1, 5, horizon, 1)).astype(np.float32)
_, r_hat = rollout_model(model, np.repeat(s[:, None], 5, axis=1), A)
real = gym.make('Pendulum-v1').unwrapped # the same sequences, for real
for a, ret in zip(A[0], r_hat[0].sum(-1)):
real.reset()
real.state = np.array([np.pi, 0.0]) # angle, velocity
true = sum(real.step(a_t)[1] for a_t in a)
print(f'first actions {a[:3, 0].round(2)} predicted {ret:7.1f} '
f'true {true:7.1f}')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
rng = np.random.default_rng(0)
s = np.array([[-1.0, 0.0, 0.0]], np.float32) # hanging down, at rest
A = rng.uniform(-c, c, (1, 5, horizon, 1)).astype(np.float32)
_, r_hat = rollout_model(model, np.repeat(s[:, None], 5, axis=1), A)
real = gym.make('Pendulum-v1').unwrapped # the same sequences, for real
for a, ret in zip(A[0], r_hat[0].sum(-1)):
real.reset()
real.state = np.array([np.pi, 0.0]) # angle, velocity
true = sum(real.step(a_t)[1] for a_t in a)
print(f'first actions {a[:3, 0].round(2)} predicted {ret:7.1f} '
f'true {true:7.1f}')first actions [ 0.55 -0.92 -1.84] predicted -185.7 true -237.6
first actions [-0.47 1.99 1.92] predicted -184.5 true -232.7
first actions [ 1.15 -1.04 1.51] predicted -183.7 true -229.4
first actions [-0.3 0.48 1.98] predicted -182.1 true -223.2
first actions [-0.08 -1.07 1.21] predicted -185.5 true -242.4
在底部静止悬垂 25 步大约损失 \(25 \times 9.9 \approx 247\),而五条序列的预测值都远高于此,且彼此相距不过几分。最后一列在真实环境中从同一状态重放这五条序列:它们实际损失 223 到 242 分——把摆杆从底部微微晃开只比静止省下 5 到 24 分,远非模型预测的 60 到 80 分。模型对每条序列都乐观了 40 到 70 分,原因很可能在于数据覆盖:在随机回合中摆杆高速掠过底部,模型从未见过它静止悬在那里,因此对该状态给出了过高的奖励。即便如此,预测回报最高的序列在真实环境中也是五条里最好的,而在候选方案中做选择只需要排序正确,不必数值精准。在这五条里,我们选中最优序列并只执行它的第一个力矩。在这个最小的例子里,“模型能被信任多远”这一问题已经浮现:此处它的数值错了,但选择对了。
这便是随机打靶(random shooting):抽取大量候选序列 \((a_0^{(j)}, \ldots, a_{n-1}^{(j)})\),预测它们的回报
\[\hat G^{(j)} = \sum_{t=0}^{n-1} \hat r_t^{(j)},\]
其中 \(\hat r_t^{(j)}\) 是模型对候选 \(j\) 第 \(t\) 步的预测奖励,并保留最优者。求和不加折扣,因为在 25 步内取 \(\gamma = 0.99\) 最多只改变约五分之一的权重。我们只执行最优序列的第一个力矩;下一步观测真实状态,并从新状态重新规划。这正是 14.6 节 中的滚动时域模型预测控制(MPC),只不过当时使用已知运动方程规划,这里则是在所学模型 \(\hat f_\phi\) 中搜索。每步重规划避免了模型误差沿实际执行轨迹累积,因为下一真实观测在误差滚雪球之前就取代了预测值;不过规划后期步骤上的误差仍会影响哪一个首步力矩胜出。
plan 同时为一批 \(B\) 个状态执行该过程。它用高斯噪声把每个状态的给定方案扰动成 500 个候选(同时保留原方案本身作为候选之一),将力矩截断到 \([-c, c]\),用 rollout_model 推演所有候选,并返回每个状态的最优序列及其预测回报。由于原方案也在候选之中,返回方案的预测回报绝不低于起点方案。求一个动作的开销是 \(500 \times 25 = 12{,}500\) 次模型求值。
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]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]15.6.2.2 热启动
搜索应当从哪套方案出发?如果没有先验,每一步都会重抽全新随机序列——这等于扔掉上一步刚找到的(多半不错的)方案,迫使搜索每步都在 500 条随机序列里重新大海捞针寻找起摆方案,相邻两步的力矩也来自毫不相干的计划。热启动复用上一步的方案:其首步力矩刚刚执行完毕,因此把其余 24 个力矩前移一步、末尾补上一个零力矩,再围绕移位后的方案加噪扰动。如此一来,好方案只需找到一次,此后步步精炼。图 15.6.1 展示了这一搜索的单步过程。
mpc 基于模型构造出该控制器。各环境的当前方案保存在控制器闭包内,在首次调用时创建;扰动标准差取力矩上限 \(c = 2\)。在另外五个种子与另一组十个起始状态上的独立对比中,我们将它与每步重抽 500 条全新均匀随机序列的规划器比较:600 步真实交互后,热启动规划器在每次运行上都拿到约 \(-115\) 到 \(-155\) 分,而冷启动规划器落在约 \(-165\) 到 \(-555\) 分;即便到了 1,000 步真实交互,冷启动规划器在每个种子上仍落后 40 到 110 分。
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 controllerdef 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 controller15.6.2.3 寥寥几个回合实现起摆
规划器究竟需要多少真实步数?mpc_run 先跑一个随机回合;随后循环三次:在迄今全部数据上重新拟合模型,在十个测试起始状态上给规划器打分,再用规划器跑一个回合采集新数据;最后再做一次重拟合与打分。所得分数因此分别对应 200、400、600 与 800 步真实交互构建的规划器。
def mpc_run(seed, num_rounds=3):
"""One random episode, then rounds of: refit the model on all data,
score the planner on the ten test starts, collect one MPC episode."""
env = gym.make_vec('Pendulum-v1', num_envs=1, vectorization_mode='sync')
rng, (model, opt) = np.random.default_rng(seed), make_model(seed)
buffer = d2l.ReplayBufferC(200 * (num_rounds + 1), 3, 1)
run_episode(env, random_controller(rng), buffer, seed=seed)
scores = []
for r in range(num_rounds + 1):
fit_model(model, opt, buffer, rng)
scores.append(score(mpc(model, rng)))
if r < num_rounds:
run_episode(env, mpc(model, rng), buffer)
return scores, bufferdef mpc_run(seed, num_rounds=3):
"""One random episode, then rounds of: refit the model on all data,
score the planner on the ten test starts, collect one MPC episode."""
env = gym.make_vec('Pendulum-v1', num_envs=1, vectorization_mode='sync')
rng, (model, opt) = np.random.default_rng(seed), make_model(seed)
buffer = d2l.ReplayBufferC(200 * (num_rounds + 1), 3, 1)
run_episode(env, random_controller(rng), buffer, seed=seed)
scores = []
for r in range(num_rounds + 1):
fit_model(model, opt, buffer, rng)
scores.append(score(mpc(model, rng)))
if r < num_rounds:
run_episode(env, mpc(model, rng), buffer)
return scores, buffer下面打印五个种子所采集四个回合的回报与四次测试分:
runs = [mpc_run(seed) for seed in range(num_seeds)]
print('seed episode returns: random, MPC x 3 |'
' test score at 200/400/600/800 steps')
for seed, (scores, buf) in enumerate(runs):
rets = buf.rew[:buf.size].reshape(-1, 200).sum(1)
print(f'{seed:4d} ' + ''.join(f'{r:7.0f}' for r in rets) + ' | '
+ ''.join(f'{s:7.0f}' for s in scores))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
runs = [mpc_run(seed) for seed in range(num_seeds)]
print('seed episode returns: random, MPC x 3 |'
' test score at 200/400/600/800 steps')
for seed, (scores, buf) in enumerate(runs):
rets = buf.rew[:buf.size].reshape(-1, 200).sum(1)
print(f'{seed:4d} ' + ''.join(f'{r:7.0f}' for r in rets) + ' | '
+ ''.join(f'{s:7.0f}' for s in scores))seed episode returns: random, MPC x 3 | test score at 200/400/600/800 steps
0 -1072 -236 -119 -125 | -174 -169 -166 -170
1 -876 -267 -120 -123 | -215 -192 -214 -179
2 -966 -124 -125 -116 | -179 -182 -205 -169
3 -1501 -1541 -1273 -2 | -1550 -1393 -178 -170
4 -1703 -1471 -936 -125 | -1512 -649 -171 -175
多少分算好?在这十个测试起点上,能甩起并平衡的控制器从最靠近顶部的起点几乎不扣分,从靠近底部的五个起点各扣约 250 到 320 分,平均扣约 170 分。以同样方式在每回合末评估 15.5 节 的柔性演员–评论员贪心演员,它最终也稳在 \(-170\) 附近,并在每步更新 1 次时大约需 5,000 到 7,500 步才首次达到 \(-200\)。
仅 600 步真实交互(三个回合)后,规划器在每次运行上都达到约 \(-165\) 到 \(-215\) 分,已接近最优水平;800 步后达到约 \(-170\) 到 \(-195\) 分。它首次达到 \(-200\) 仅需 200 到 800 步真实交互,多数运行在 600 步内达标。五个种子中有三个仅凭首个随机回合拟合的模型就给出了约 \(-175\) 到 \(-340\) 分的规划器,远胜随机策略的 \(-1{,}000\) 以下。另两个种子(种子 3 和 4)的首个规划器失败(约 \(-1{,}500\) 分),其前一两个采集回合也未成功,但在 600 步真实交互后同样取得成功。
15.6.2.4 数据覆盖
较慢的两个种子恰好是随机回合损失最大的两个(约 \(1{,}500\) 与 \(1{,}700\) 分):随机力矩从未把摆杆抬过水平线。我们取前文误差表中仅由单个随机回合拟合的模型,改在规划器自身采集的回合(而非第二个随机回合)上测试:
print('seed k=1 k=5 k=10 k=25 (degrees, the planner\'s episodes)')
for seed, ((m, _), (_, buf)) in enumerate(zip(models, runs)):
errors = kstep_error(m, buf, first=200) # skip the random episode
print(f'{seed:4d} ' + ' '.join(f'{e:6.1f}' for e in errors))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
print('seed k=1 k=5 k=10 k=25 (degrees, the planner\'s episodes)')
for seed, ((m, _), (_, buf)) in enumerate(zip(models, runs)):
errors = kstep_error(m, buf, first=200) # skip the random episode
print(f'{seed:4d} ' + ' '.join(f'{e:6.1f}' for e in errors))seed k=1 k=5 k=10 k=25 (degrees, the planner's episodes)
0 0.2 1.0 3.2 56.4
1 0.3 0.9 1.8 27.7
2 0.2 0.9 1.8 29.3
3 7.9 48.5 81.8 120.3
4 10.8 56.4 78.5 87.5
在种子 0 到 2 上,模型沿规划器回合的误差起步与随机数据上一样小(单步不到一度),25 步后增至几十度——这些回合大部分时间停留在竖直向上附近,而倒立摆在顶部本就不稳定,角度预测的微小偏差就决定了它倒向哪一侧。而在种子 3 和 4 上,单步误差就有几度,五步后便达几十度。模型在数据去过的地方准确,在没去过的地方失准。在冰湖上,未尝试过的状态–动作对在计数模型看来毫无价值;这里神经网络则会外推到它从未见过的上半圆,且外推是错的。修复它的恰恰是规划器自己失败的尝试:哪怕失败的起摆尝试也会把摆杆推得比随机力矩更高,并记录下那里的真实物理过程。下一次重拟合时,模型就有了这些状态的数据,据此规划便水到渠成。规划器无需任何显式探索规则就能自发探索:它奔向模型许诺高回报的区域,而只要模型在那里猜错了,真实反馈就会纠正它。
15.6.2.5 真实交互步数的代价
规划器只需 200 到 800 步真实交互即可首次达到 \(-200\)。在同一测试分(十个测试起点的均值)上,采用自动学习温度的 15.5 节 柔性演员–评论员(每种配置五个种子,计入前 1,000 步随机预热)在每步更新 1 次时需约 5,000 到 7,500 步才首次达到 \(-200\),在每步更新 10 次时需约 1,600 到 4,000 步。按环境步数衡量,规划器比前者少约一个数量级,比后者也少几倍。
另一条坐标轴是计算量。规划器的每个动作都是一次搜索:12,500 次模型求值(对这个小网络在单核 CPU 上需几毫秒),且每个回合还要叠加一千步 Adam 重拟合。柔性演员–评论员每步真实交互只需对三个小网络做 1 次或 10 次梯度更新,而实际决策只需演员做一次前向传播。真实机器人还必须在控制周期(这里是 0.05 秒)内完成搜索。世界模型并没有让学习免费,它只是把成本从机器人稀缺的真实经验转移到了控制器稀缺的在线算力上。
15.6.3 以搜索作为策略改进
15.6.3.1 由演员引导的搜索
规划器本身没有策略。每个动作都要做一次完整搜索,除了模型与上一步移位后的方案外,它记不住自己找到的任何经验。策略网络只需一次前向传播就能决策且能跨状态泛化,但它需要训练,而 15.5 节 借助评论员训练策略耗费了数千步。搜索本身能否直接用来训练策略?
我们可以从策略自身的方案出发启动搜索。设演员是将状态映射为力矩的网络 \(\bar a_\theta(s)\)。在模型中,演员从状态 \(s\) 出发的方案就是沿自身预测轨迹选出的一串力矩:\(a_0 = \bar a_\theta(s)\),由 \(\hat f_\phi(s, a_0)\) 得 \(\hat s_1\),\(a_1 = \bar a_\theta(\hat s_1)\),如此延续 \(n\) 步。actor_plan 为一批状态计算该方案;improve 把它交给 plan 代替上一步的移位方案(同样 500 个候选与相同扰动),并返回最优候选的第一个力矩。
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]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]既然演员自身的方案就是候选之一,搜索返回动作所对应的方案预测回报绝不会低于演员方案。在模型内部、给定 \(n\) 步视野下,由策略作为起点的搜索永远不会比原策略更差。这正是 14.2.3.2 节 中策略迭代的贪心改进步——在每个状态选出按当前策略价值评判至少同样好的动作,只是这里的裁判换成了模型对未来 25 步的预测。该保证仅在模型内部且仅在视野范围内成立:失准的模型可能背书更差的动作,25 步截断的方案也看不见 25 步之后的后果。
15.6.3.2 向演员蒸馏
既然搜索能够改进演员,我们就可以训练演员模仿搜索。这正是以搜索为专家的 14.5 节 行为克隆:用 improve 标注状态,由于力矩连续,以平方误差将演员力矩回归到标签上。演员采用 15.5 节 的 d2l.SquashedGaussianPolicy——一个用 \(c \tanh\) 将高斯均值压缩到力矩区间的两层网络;我们只训练其压缩均值 \(\bar a_\theta(s) = c \tanh \mu_\theta(s)\)(\(\mu_\theta\) 同前为高斯均值,即 act_greedy 的返回值)。make_actor 构建演员及其 Adam 优化器,distill 执行 1,000 步 Adam 回归。
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())def make_actor(seed, lr=1e-3):
actor = d2l.SquashedGaussianPolicy(3, 1, scale=c, seed=seed)
return actor, nnx.Optimizer(actor, optax.adam(lr), wrt=nnx.Param)
@nnx.jit
def distill_step(actor, opt, obs, labels):
loss = lambda m: ((m.scale * jnp.tanh(m.policy(obs)[0]) - labels)
** 2).mean()
value, grads = nnx.value_and_grad(loss)(actor)
opt.update(actor, grads)
return value
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."""
step = nnx.cached_partial(distill_step, actor, opt)
for _ in range(num_steps):
i = rng.integers(len(obs), size=batch_size)
loss = step(obs[i], labels[i])
return float(loss)distill_step 是回归的单步编译 Adam 更新,与 model_step 绑定到模型一样,每次调用 distill 时由 nnx.cached_partial 将演员与优化器绑定到它上面。
search_and_distill 的每一轮(图 15.6.2)先重新拟合模型,再随机抽取 200 个已存状态用搜索打标签,将这些标签蒸馏进演员,最后用搜索决策采集一个真实回合。每轮只用当轮标签训练演员,不保留往轮标签。用搜索来决策让每个采集回合尽可能达到当前模型和演员的最高水准,从而将数据带到优秀控制器访问的状态。如果再配上一个同时预测状态价值的网络、离散走法上的树搜索,以及跨多局保存搜索目标的缓冲区,这套“搜索决策—打标—蒸馏”循环就是 AlphaZero 的核心循环。
循环每轮记录两项指标:用搜索采集的训练回合回报,以及演员完全不用搜索、独立行动时的测试分;全部结束后再在十个测试起点上评估带搜索的得分。两条曲线衡量的是不同对象:前者每轮只有一个训练回合,起点随机,随起点波动不亚于随智能体进步,碰上一个难起点就会出现低谷;后者则是全节统一的十个固定测试起点的均值。
def search_and_distill(seed, num_rounds=8, num_labels=200):
"""One random episode, then rounds of: refit the model, label stored
states with the search, regress the actor onto the labels, collect one
episode acting with search. Returns per round the collected return and
the actor's score alone, and the final score acting with search."""
env = gym.make_vec('Pendulum-v1', num_envs=1, vectorization_mode='sync')
rng, (model, opt) = np.random.default_rng(seed), make_model(seed)
actor, actor_opt = make_actor(seed)
buffer = d2l.ReplayBufferC(200 * (num_rounds + 1), 3, 1)
run_episode(env, random_controller(rng), buffer, seed=seed)
search = lambda obs: improve(model, actor, obs, rng)
rounds = []
for _ in range(num_rounds):
fit_model(model, opt, buffer, rng)
obs = buffer.obs[rng.choice(buffer.size, num_labels, replace=False)]
distill(actor, actor_opt, obs, search(obs), rng)
rounds.append([run_episode(env, search, buffer)[0],
score(actor.act_greedy)])
return np.array(rounds), score(search)def search_and_distill(seed, num_rounds=8, num_labels=200):
"""One random episode, then rounds of: refit the model, label stored
states with the search, regress the actor onto the labels, collect one
episode acting with search. Returns per round the collected return and
the actor's score alone, and the final score acting with search."""
env = gym.make_vec('Pendulum-v1', num_envs=1, vectorization_mode='sync')
rng, (model, opt) = np.random.default_rng(seed), make_model(seed)
actor, actor_opt = make_actor(seed)
buffer = d2l.ReplayBufferC(200 * (num_rounds + 1), 3, 1)
run_episode(env, random_controller(rng), buffer, seed=seed)
search = lambda obs: improve(model, actor, obs, rng)
rounds = []
for _ in range(num_rounds):
fit_model(model, opt, buffer, rng)
obs = buffer.obs[rng.choice(buffer.size, num_labels, replace=False)]
distill(actor, actor_opt, obs, search(obs), rng)
rounds.append([run_episode(env, search, buffer)[0],
score(actor.act_greedy)])
return np.array(rounds), score(search)八轮迭代从一个随机回合起步,因此第 \(r\) 轮的演员见过 \(200 r\) 步真实交互。我们运行三个种子,绘制跨种子中位数及区间带:
results = [search_and_distill(seed) for seed in range(3)]
rounds = np.array([r for r, _ in results])
d2l.plot_curves({'episode acting with search': rounds[:, :, 0],
'actor alone, ten starts': rounds[:, :, 1]},
'real environment steps', 'return',
x=200 * np.arange(1, 9), reference=-200)
print('final score on the ten starts, acting with search:',
' '.join(f'{s:.0f}' for _, s in results))final score on the ten starts, acting with search: -191 -202 -222
results = [search_and_distill(seed) for seed in range(3)]
rounds = np.array([r for r, _ in results])
d2l.plot_curves({'episode acting with search': rounds[:, :, 0],
'actor alone, ten starts': rounds[:, :, 1]},
'real environment steps', 'return',
x=200 * np.arange(1, 9), reference=-200)
print('final score on the ten starts, acting with search:',
' '.join(f'{s:.0f}' for _, s in results))final score on the ten starts, acting with search: -223 -188 -241
15.6.3.3 多轮搜索与蒸馏的表现
在展示的三次运行中,带搜索行动的智能体两三轮内就能甩起摆杆,八轮后在十个起点上得分约 \(-185\) 到 \(-245\),在多数运行上接近前文的热启动规划器。独立行动的演员在每次运行上也都有进步——从第一轮后的约 \(-900\) 到 \(-1{,}600\) 升至第八轮后的约 \(-190\) 到 \(-1{,}100\),但相邻轮次间得分可能骤降数百分。网络确实学到了搜索掌握的部分本领,但单独行动时仍力有未逮。
这些运行本身并未指出落后的确切原因,有三个候选因素。第一是 14.5 节 在冰湖上测过的分布偏移:标签采自存储状态,除首个随机回合外全都是搜索访问过的状态;模仿不完美的演员一旦单独行动,就会漂移到标签稀少的状态并在那里误差滚雪球。DAgger(14.5.4.1 节)在冰湖上通过标注学习器自身访问的状态修复了这一点。第二是训练集规模:每轮只在 200 条新标签上训练演员而丢弃旧标签,而 DAgger 会聚合各轮标签,AlphaZero 也在缓冲区中保留搜索目标。第三是标签本身的噪声:每条标签都是 500 个随机候选中最优者的首个力矩,本就带噪。5 将分离前两个原因。此外 AlphaZero 在测试期也会继续搜索,因此其网络只需为搜索提供优质起点即可:搜索与网络相互促进——更好的演员引导更好的搜索,更好的搜索再反过来教出演员。
15.6.3.4 将想象转移作为训练数据
模型也可以喂给没有规划器的学习器。Dyna (Sutton 1990年) 将真实交互步与在模型采样转移上的更新交替进行,而基于模型的策略优化(MBPO)(Janner 等 2019年) 将其引入柔性演员–评论员:每隔几百步重拟合模型,从经验回放池的真实状态出发在模型中推演当前演员几步,并用这些想象转移填充每个训练批次的绝大部分(图 15.6.3)。想象数据要多少有多少(只要算力允许),但模型误差会进入评论员目标,因此 MBPO 刻意采用短推演来遏制前文测到的累积误差。
这能减少 Pendulum 上的真实步数吗?我们运行了温度固定为 0.2、每步环境交互更新十次的柔性演员–评论员,每批由 5% 真实转移与 95% 三步推演的想象转移构成,每隔 250 步重拟合模型。在五个种子上,其贪心演员首次达到 \(-200\) 或更好用了 1,500 到 3,000 步;而去掉模型、保持同样每步十次更新时只用了 1,500 到 2,500 步。(这组运行采用了另一组十个固定起点,好控制器在上面扣分较少,因此比前文引用的运行更早达到 \(-200\)。)在相同更新比下,想象转移并未减少真实步数。MBPO 相比每步更新一次的柔性演员–评论员所获的很大一部分收益,其实来自每步真实交互对应的额外梯度更新——而经验回放本身无需模型就能提供这些更新;采用高更新比并用评论员集成抑制高更新比高估的无模型学习器,同样达到了 MBPO 的样本效率 (Chen 等 2021年)。6 将复现这一对比。模型最能发挥威力的地方正是本节的用法:在行动前向前看,并将搜索转化为策略。能够感知自身不确定性的模型集成、基于学习潜在状态的模型,以及末端接上学习价值函数的搜索,把这些思想推向更远;15.9 节 将作综述。
至此,我们已经能用几百步交互拟合动力学模型、在模型中规划,并把搜索的发现教给策略。但每一步都只在自身回合涉足的区域内信任模型 25 步,且总能通过继续交互和重拟合来检验这份信任。15.7 节 将拿走“继续行动”的权利:数据是一份固定日志,模型或价值函数在日志之外许下的任何承诺都无从检验。
15.6.4 小结
一条转移记录了环境的演化方式,用最小二乘在转移上拟合的网络 \(\hat f_\phi(s, a) \to (\hat s', \hat r)\) 将冰湖上的计数模型推广到了连续状态。它的单步误差很小,但沿推演轨迹会不断累积,且在数据未曾覆盖的区域误差很大。模型预测控制在模型中搜索力矩序列、执行第一个力矩并在下一步重新规划;借助热启动,仅凭一到三个回合构建的规划器在几百步真实交互内即可甩起倒立摆(柔性演员–评论员需要几千步),代价是每个动作需要数千次模型求值。由策略作为起点的搜索预测回报绝不低于原策略,因此它构成一次策略改进,而将演员回归到搜索动作可迁移其中一部分改进;不过演员单独行动时仍落后于搜索。其标签大多落在搜索访问的状态上、每轮数量较少且带噪,而本节运行尚未区分三者孰重孰轻。在每步更新次数相匹配时,将想象转移作为训练数据并未减少柔性演员–评论员所需的真实步数。
15.6.5 练习
- [code] 规划深度。规划器向前看 \(n = 25\) 步。
- 在运行代码前,根据本节的两张误差表预测在保持 500 个候选不变时,\(n = 10\) 与 \(n = 50\) 的测试分分别会怎样。
- 在两种深度下各用三个种子运行
mpc_run,将 600 步真实交互后的测试分与 \(n = 25\) 对比。 - 从底部起摆需要几十步蓄能。请从预测回报能区分与不能区分什么来解释 \(n = 10\) 的结果,并用误差表解释 \(n = 50\) 的结果。单次动作的计算开销如何随 \(n\) 变化?
- [code] 需要多少随机数据。种子 3 和 4 需要规划器自身失败的回合,模型才覆盖到上半圆。
- 对这两个种子,分别在一、二和五个随机回合上拟合模型。像覆盖度表那样,报告数据中摆杆达到的最高点(最大的 \(\cos\vartheta\))以及每个模型沿规划器回合的 25 步误差。
- 仅凭随机数据构建的规划器需要多少个随机回合,才能从大多数测试起点起摆?与规划器用自身采集回合所需的 600 步对比并解释差异。
- [code] 交叉熵方法。交叉熵方法 (Rubinstein 和 Kroese 2004年) 在每个动作处重复执行多轮随机打靶,并将采样分布重新拟合到最优候选上。
- 修改
plan使其运行五轮:每轮结束后,将方案每个力矩的均值和标准差设为 500 个候选中最优 50 个的均值和标准差,再从该高斯分布抽取下一批 500 个候选。 - 将 600 步真实交互后的测试分与每动作模型求值次数同本节的热启动随机打靶对比。
- 去掉热启动运行该方法,每步都从均值零力矩、标准差 \(c\) 出发。单步内的多轮精炼能否取代跨步精炼?
- 修改
- [code] 以分歧作为信任信号。● 模型集成能够指出它在哪里缺乏把握 (Chua 等 2018年)。
- 对种子 3 和 4,在首个随机回合上用不同种子拟合三个模型。沿规划器回合比较三个模型的分歧度(预测角度的标准差)与它们平均预测在 1、5、25 步后的误差。大分歧是否预示大误差?
- 在
plan中用三个模型的平均预测回报减去 \(\kappa\) 倍沿步累加的分歧度为每个候选打分,测试 \(\kappa \in \{0, 1, 10\}\)。种子 3 和 4 的首个 MPC 回合发生了什么变化? - 用 \(-\kappa\)(给分歧加奖励)重做 (b)。哪种符号适合还能继续采集数据的智能体,哪种适合不能再采数据的智能体?
- [code] 在演员自身状态上打标。● 本节循环用搜索采集回合,且每轮仅用当轮 200 条标签训练演员。
- 保持用搜索采集,但聚合标签:把每轮标注的状态和力矩追加到一个不断增长的集合中,并在整个集合上蒸馏演员。运行五个种子,将每轮演员得分与本节结果对比。
- 改为每轮仅用演员
actor.act_greedy采集回合,用improve标注演员回合中的状态,并如 (a) 那样聚合标签——这正是以搜索为专家的 14.5 节 DAgger。三个版本中哪一个给出更稳健的演员?该对比对正文列举的原因说明了什么? - 在某些种子上,DAgger 版本可能始终无法起摆。检查此类运行的数据,用本节的覆盖度表解释失败原因,并说明如何结合两种数据采集方式。
- [extended] 给柔性演员–评论员喂想象转移。●● 基于模型的策略优化 (Janner 等 2019年) 用模型想象的转移训练柔性演员–评论员。
- 将 15.5 节 的
train_sac复制到本笔记本。预热结束后,每隔 250 步环境交互在回放池上重拟合一个DynamicsModel,并从回放池随机抽取 2,000 个状态在模型中推演当前演员三步。将最近四次重拟合的想象转移存入第二个d2l.ReplayBufferC,并使每个训练批次有 95% 采自其中。 - 在每步更新 10 次下运行五个种子共 4,000 步,每隔 250 步在十个测试起点上评估贪心演员。用相同种子运行不带模型的对照组。报告每次运行首次达到 \(-200\) 或更好的步数。
- 为什么对照组必须采用相同的每步更新次数?在每步更新 1 次下重复两组实验并解释差异。
- 将推演长度分别改为 1 步和 10 步。本节误差表预测会出现什么结果,你的实测又如何?
- 将 15.5 节 的
- [code] 结合价值函数的前瞻。本节规划器只累加固定视野内的奖励,忽略之后发生的事;配合价值函数,视野可以短至一步。
- 在 CartPole 上,用 5,000 条随机动作转移拟合一个四维状态的
DynamicsModel,按 CartPole 已知规则由杆角度和小车位置判定终止。 - 将 15.4 节 的 DQN 训练 10,000 步,并以两种方式贪心决策:\(\operatorname{argmax}_a Q(s, a)\) 以及一步前瞻 \(\operatorname{argmax}_a \big[\hat r(s, a) + \gamma \max_{a'} Q(\hat s'(s, a), a')\big]\)。在五个种子上对比 20 个回合的平均回报。
- 在训练 40,000 步后重复对比。何时前瞻有帮助,何时模型误差会盖过它带来的收益?
- 在 CartPole 上,用 5,000 条随机动作转移拟合一个四维状态的