世界模型:想象中的好策略,经得起真实检验吗?
World models
从只有位置的观察学习压缩表示与动力学,在模型里训练控制器,再分开检查预测和真实表现。
world-models位置一样,为什么要往相反方向刹车?
设想一辆需要停在原点的小车。传感器报告位置,却不报告速度。两辆车可以处在同一位置,一辆向左、一辆向右;若控制器把最新读数当成完整状态,就不知道该往哪边刹车。这是本篇原创教学问题,不是机器人基准。
世界模型根据已有经验,预测动作可能带来的后果。内部状态可以是物理量、循环记忆,也可以是学得的潜表示。值得追问的是:它究竟保留了什么信息?对于会产生不同奖励或未来的两段历史,它还能分清吗?一张看起来细节丰富的重构图,不能回答这个问题。
这个名称也指 Ha 与 Schmidhuber 的 2018 年工作。其视觉编码器、循环预测器与小控制器各司其职:CarRacing 实验仍在实际环境中训练控制器;VizDoom 实验才把控制器放进生成环境训练,再检验迁移。论文承认此前的模型式研究。这两项实验都没有规定世界模型必须重构图像或搜索一棵树。会议论文第 2—4 节
本程序从合成观察中学习压缩表示、转移预测器与奖励预测器,然后完全通过想象轨迹优化小控制器,最后回到真实教学模拟器评价。保留两个潜维度时,这个可精确表示的任务能很好地迁移;只留一个维度,就出现可测量的预测与迁移差距。
根据观察推断状态,与想象未来不是一回事
记观察为 、动作为 、模型状态为 。带观察的推断分布可以利用已经到达的证据修正状态;预测分布必须在没有那份未来证据时继续向前:
这是一组常见潜模型接口,不要求所有实现采用完全相同的奖励下标。本文用 表示推断、 表示预测;所引 Dreamer 论文的字母刚好相反。关键是每个函数接收了哪些信息。若每个想象步骤都喂入留出序列的真实未来观察,测到的是不断纠正后的重构,而非独立预测。Dreamer 第 2、4 节
采用重构目标的模型可以最小化下面的序列损失。期望针对带观察的潜状态序列, 控制正则强度:
在生成因子归一化且彼此相容、 时,它具有负 ELBO 的形式:观察与奖励的似然鼓励有用预测,KL 项则为“编码了转移先验没有预测到的信息”收取代价。任意修改 会改变目标,不能自动当成同一个似然下界。这个训练目标本身也没有证明潜状态保留了控制所需的全部区别。Dreamer 还考察了其他表示目标。Dreamer 第 4 节
若推断与预测都是对角高斯分布,KL 可以逐坐标计算;方差必须严格为正:
方向不能换。取 、,正向 KL 约为 ,反向约为 ;两分布相同时,两方向才都为零。固定作者实现中的 KL 方向也是推断相对于预测;其中 free_nats 对平均后的 KL 设下限,不是对每个坐标分别设置阈值。代码与核读范围
使用世界模型,并没有指定唯一的控制算法。 规划器可以在线比较想象动作序列;控制器可以把模型记忆当成特征;策略也可以先在想象经验上学习,随后不经过在线搜索就行动。Dreamer 从想象轨迹学习 actor 与价值函数。在 actor 学习时固定模型参数,仍然可以对经过模型的动作与状态求导。所选 TF2 代码还对传给 actor 的特征停止梯度,不能把这个细节混同于完全不截断的闭环求导。Dreamer 第 3 节 作者实现
下面用一种明确的有限时域记法写出价值自举。 表示收到 后是否继续,真正终止的转移有 :
这是本文声明的教学约定,奖励附在离开当前状态的转移上。人为截断位置的价值不一定为零。取两次奖励 1、2,下一状态价值 3、4,继续标志均为 1,、,反向计算得到 、。即使 ,有限边界仍然保留自举,得到 。固定代码的注释把这一设置称为 Monte Carlo,但实际递推仍含非零 bootstrap。回报实现
先学模型,再把真实环境移出策略训练
模拟器有位置 、速度 、有界动作 ,评价固定运行 20 步。奖励是新位置、新速度和动作成本的负值:
学习器每次只得到位置对应的四个仿射传感通道。把相邻两次读数拼接成八个观察值;由于这里 ,这些读数包含二维物理状态,单次当前读数却不包含。collect 独立抽取重置状态与单步动作,因此 256 条训练转移是生成式查询,不能说成一段已经执行的探索轨迹。另外独立生成 128 条留出转移。
PCA 只用训练观察拟合。给定保留维数 ,其正交基 决定编码与重构:
是八通道观察历史。这个确定性线性压缩器在实验中代替神经编码器,不是 VAE 或 RSSM。接着用最小二乘拟合潜空间中的仿射转移和二次奖励函数。定义 包含截距、 的每个坐标,以及所有不重复的二次乘积:
保留两个维度时,这个合成过程能够被精确表示,只剩浮点误差。这是教学问题特意具有的有利条件,不能据此推论视觉世界模型也会精确。只留一个维度时,解码器和转移模型无法找回全部被丢弃的信息。
控制器只有 个参数。我们从 16 个已编码的训练起点出发,优化平均想象回报:
本例的交叉熵搜索运行 12 轮,每轮抽取 48 组参数,保留最好的 8 组,用它们更新对角高斯分布,并把标准差下限设为 0.05。搜索前还评价一次零动作控制器,整个过程保留遇到的最佳候选。这是一个小型无导数优化器,不是 CMA-ES,也不是 Dreamer 的 actor–critic 更新。每个维数的训练执行 次模型转移。imagined_returns 与 optimize 内部不允许调用真实环境。
潜宽度为 时,奖励设计矩阵有 个特征。这里的最小二乘与八通道 SVD 都很小。策略搜索需要“轮数 × 种群 × 起点 × 时域”次模型计算,每步进行仿射转移与二次特征计算;向量化滚动只保存当前状态,不保存全部想象轨迹。这些计数没有测量相对神经智能体的实际耗时优势。
下面是完整的 Python、NumPy 程序。命令行展示摘要;experiment() 保留每个回合的真实与想象回报,可继续检查。
"""Original linear world model with learned compression and imagined policy search.
NumPy only. This is not VAE/RSSM/Dreamer or a reproduction of a paper benchmark.
"""
import json
import numpy as np
def positive_int(n):
if isinstance(n, bool) or not isinstance(n, (int, np.integer)) or n < 1:
raise ValueError('Expected a positive integer')
return int(n)
def observe(x):
return np.asarray(x)[..., None] * np.array([1., 2., -1., .5]) + np.array([.2, -.3, .1, .4])
def history(state):
"""state=[previous position,current position]; only observations reach learning."""
s = np.asarray(state, dtype=float)
return np.concatenate((observe(s[..., 0]), observe(s[..., 1])), axis=-1)
def real_step(state, action):
s = np.asarray(state, dtype=float); a = np.asarray(action, dtype=float)
if s.shape[-1] != 2 or not np.isfinite(s).all() or not np.isfinite(a).all() or np.any(abs(a) > 1):
raise ValueError('Finite two-position state and bounded action required')
velocity = .8 * (s[..., 1] - s[..., 0]) + .2 * a
x = s[..., 1] + velocity
return np.stack((s[..., 1], x), axis=-1), -(x*x + .1*velocity*velocity + .01*a*a)
def collect(seed, n=256):
rng = np.random.default_rng(seed); n = positive_int(n)
x = rng.uniform(-1, 1, n); v = rng.uniform(-.5, .5, n)
state = np.stack((x-v, x), axis=-1); action = rng.uniform(-1, 1, n)
nxt, reward = real_step(state, action)
return dict(observation=history(state), next_observation=history(nxt), action=action, reward=reward)
def design(z, action):
u = np.concatenate((z, np.asarray(action)[..., None]), axis=-1)
linear = [np.ones(u.shape[:-1])] + [u[..., i] for i in range(u.shape[-1])]
quadratic = [u[..., i]*u[..., j] for i in range(u.shape[-1]) for j in range(i, u.shape[-1])]
return np.stack(linear+quadratic, axis=-1)
def encode(model, observations):
return (np.asarray(observations)-model['mean']) @ model['basis']
def fit(data, dimension):
dimension = positive_int(dimension)
obs = np.asarray(data['observation'], dtype=float)
nxt = np.asarray(data['next_observation'], dtype=float)
a = np.asarray(data['action'], dtype=float); r = np.asarray(data['reward'], dtype=float)
if obs.ndim != 2 or obs.shape[1] != 8 or nxt.shape != obs.shape or a.shape != r.shape or a.shape != (len(obs),):
raise ValueError('Inconsistent training arrays')
if dimension > 2 or len(obs) < 16 or not all(np.isfinite(v).all() for v in (obs, nxt, a, r)):
raise ValueError('Need at least16 finite transitions and dimension1 or2')
mean = obs.mean(0); _, singular, vt = np.linalg.svd(obs-mean, full_matrices=False)
if singular[dimension-1] < 1e-10:
raise ValueError('Requested latent dimension is not identifiable')
basis = vt[:dimension].T.copy()
for j in range(dimension):
if basis[np.argmax(abs(basis[:, j])), j] < 0: basis[:, j] *= -1
model = dict(mean=mean, basis=basis)
z = encode(model, obs); target = encode(model, nxt)
inputs = np.column_stack((z, a, np.ones(len(z))))
model['transition'] = np.linalg.lstsq(inputs, target, rcond=None)[0]
model['reward'] = np.linalg.lstsq(design(z, a), r, rcond=None)[0]
return model
def predict(model, z, action):
inputs = np.concatenate((z, np.asarray(action)[..., None], np.ones(z.shape[:-1]+(1,))), axis=-1)
return inputs @ model['transition'], design(z, action) @ model['reward']
def diagnostics(model, data):
obs = data['observation']; z = encode(model, obs)
nxt, reward = predict(model, z, data['action'])
reconstructed = z @ model['basis'].T + model['mean']
decoded = nxt @ model['basis'].T + model['mean']
return dict(reconstruction_rmse=float(np.sqrt(np.mean((reconstructed-obs)**2))),
next_observation_rmse=float(np.sqrt(np.mean((decoded-data['next_observation'])**2))),
reward_rmse=float(np.sqrt(np.mean((reward-data['reward'])**2))))
def imagined_returns(model, weights, starts, horizon=20):
"""No access to real_step or new observations. Batch policies x initial states."""
horizon = positive_int(horizon); w = np.atleast_2d(np.asarray(weights, dtype=float))
starts = np.asarray(starts, dtype=float); d = model['basis'].shape[1]
if w.shape[1] != d+1 or starts.ndim != 2 or starts.shape[1] != d or len(starts) == 0:
raise ValueError('Invalid policy or latent start dimensions')
if not np.isfinite(w).all() or not np.isfinite(starts).all(): raise ValueError('Finite inputs required')
z = np.broadcast_to(starts, (len(w),)+starts.shape).copy(); total = np.zeros(z.shape[:2])
for _ in range(horizon):
action = np.tanh(np.einsum('pnd,pd->pn', z, w[:, :-1])+w[:, -1, None])
z, reward = predict(model, z, action); total += reward
return total
def optimize(model, starts, seed, rounds=12, population=48, elites=8, horizon=20):
rounds, population, elites, horizon = map(positive_int, (rounds, population, elites, horizon))
if elites > population: raise ValueError('Elites exceed population')
rng = np.random.default_rng(seed); mean = np.zeros(model['basis'].shape[1]+1); std = np.ones_like(mean)
best = mean.copy(); best_score = float(imagined_returns(model, best, starts, horizon).mean())
for _ in range(rounds):
candidates = rng.normal(mean, std, (population, len(mean)))
scores = imagined_returns(model, candidates, starts, horizon).mean(1)
selected = np.argsort(scores, kind='stable')[-elites:]
if scores[selected[-1]] > best_score:
best = candidates[selected[-1]].copy(); best_score = float(scores[selected[-1]])
mean = candidates[selected].mean(0); std = np.maximum(candidates[selected].std(0), .05)
return dict(weights=best, training_dream_return=best_score,
model_transitions=(1+rounds*population)*len(starts)*horizon)
def evaluate_real(model, weights, initial, horizon=20):
s = np.asarray(initial, dtype=float).copy(); total = np.zeros(len(s))
for _ in range(positive_int(horizon)):
z = encode(model, history(s)); action = np.tanh(z @ weights[:-1]+weights[-1])
s, reward = real_step(s, action); total += reward
return total
def experiment(seed=0):
# Independent generative queries, not one long exploration trajectory.
training = collect(seed, 256); heldout = collect(1000+seed, 128)
rng = np.random.default_rng(2000+seed)
x = rng.uniform(-1, 1, 32); v = rng.uniform(-.5, .5, 32)
initial = np.column_stack((x-v, x)); rows=[]
for dimension in (1, 2):
model = fit(training, dimension)
starts = encode(model, training['observation'][:16])
result = optimize(model, starts, 3000+seed)
w = result.pop('weights'); encoded_initial = encode(model, history(initial))
dreamed = imagined_returns(model, w, encoded_initial)[0]
actual = evaluate_real(model, w, initial)
baseline = evaluate_real(model, np.zeros_like(w), initial)
rows.append(dict(dimension=dimension, weights=w.tolist(), **result,
train=diagnostics(model, training), heldout=diagnostics(model, heldout),
evaluation_dream_mean=float(dreamed.mean()), evaluation_real_mean=float(actual.mean()),
zero_action_real_mean=float(baseline.mean()), transfer_mae=float(np.mean(abs(dreamed-actual))),
real_returns=actual.tolist(), dream_returns=dreamed.tolist()))
return dict(seed=seed, training_queries=256, heldout_queries=128,
evaluation_episodes=32, horizon=20, training_latent_starts=16, variants=rows)
if __name__ == '__main__':
result = experiment()
result['variants'] = [{k: v for k, v in row.items() if k not in ('real_returns', 'dream_returns')}
for row in result['variants']]
print(json.dumps(result, indent=2))
查看运行摘要
{
"seed": 0,
"training_queries": 256,
"heldout_queries": 128,
"evaluation_episodes": 32,
"horizon": 20,
"training_latent_starts": 16,
"variants": [
{
"dimension": 1,
"weights": [
-0.6832467507584297,
-0.055556214497803624
],
"training_dream_return": -5.686036022500115,
"model_transitions": 184640,
"train": {
"reconstruction_rmse": 0.17396791707394674,
"next_observation_rmse": 0.35445551756115073,
"reward_rmse": 0.4253483613474249
},
"heldout": {
"reconstruction_rmse": 0.16782452863097225,
"next_observation_rmse": 0.34678338141533105,
"reward_rmse": 0.3882464959250589
},
"evaluation_dream_mean": -5.481058678784623,
"evaluation_real_mean": -3.584740525251131,
"zero_action_real_mean": -21.493515891190064,
"transfer_mae": 2.152529451663676
},
{
"dimension": 2,
"weights": [
-0.8979232235443484,
-2.9093350675682936,
-0.3419744965065467
],
"training_dream_return": -0.6765545150942472,
"model_transitions": 184640,
"train": {
"reconstruction_rmse": 2.7262648183120436e-16,
"next_observation_rmse": 2.62381159472016e-16,
"reward_rmse": 4.842194318137974e-16
},
"heldout": {
"reconstruction_rmse": 2.651323253138859e-16,
"next_observation_rmse": 2.475362967304832e-16,
"reward_rmse": 4.821572390576542e-16
},
"evaluation_dream_mean": -0.3111218198167409,
"evaluation_real_mean": -0.3111218198167517,
"zero_action_real_mean": -21.493515891190064,
"transfer_mae": 1.071706742447609e-14
}
]
}下表每行都是一个完整独立种子。回报是不折扣的负成本之和,越接近零越好。同一种子中,两种表示和零动作基线使用相同的 32 个留出初始状态;数值保留五位小数。
| 种子 | 1D真实 | 2D真实 | 零动作真实 | 1D迁移MAE |
|---|---|---|---|---|
| 0 | −3.58474 | −0.31112 | −21.49352 | 2.15253 |
| 1 | −6.15890 | −0.49028 | −27.75658 | 1.55631 |
| 2 | −6.18937 | −0.44470 | −26.32942 | 1.43335 |
| 3 | −4.58186 | −0.59243 | −28.14857 | 1.69964 |
| 4 | −5.15951 | −0.32598 | −28.81196 | 1.37806 |
| 5 | −2.74048 | −0.31955 | −20.87005 | 2.14407 |
| 6 | −3.04130 | −0.32316 | −18.29014 | 2.35325 |
| 7 | −3.65189 | −0.32151 | −22.41338 | 1.49146 |
种子 0 的 1D 模型在留出数据上的下一观察 RMSE 约为 0.34678;它在评价起点上的平均想象回报为 −5.48106,真实为 −3.58474。到了种子 1,大小关系反过来。模型误差不一定乐观,也不一定悲观。全部八次运行的 2D 迁移 MAE 都低于 。这次比较与控制器搜索都没有证明策略全局最优。
评价成本要另记。每个维数的 32 个想象评价回合增加 640 次模型转移;学得控制器与零动作基线各消耗 640 次真实评价转移,代码针对每个维数都重跑了基线。这些评价不会更新模型或控制器。所有回合都在固定步数截断;本例没有学得的终止预测头,也没有终止状态训练。
一个太方便的模拟器,可能教错什么?
本实验没有随机动力学、图像、神经序列模型、后验采样或学得的继续概率。两帧观察按构造就是充分的,模型只训练一次,训练和测试服从同一确定性规律。若要考察分布变化,应另外声明对模拟器的改动,随后重新评价,而非悄悄用测试数据重拟合。
重构损失低、单步预测准、多步预测合理、策略有用,是不同的检查。表示可能保留了大幅视觉变化,却漏掉决定最优动作的微小线索;控制器也可能选择把自己带离模型训练分布的动作。2018 年论文记录了策略利用生成环境缺陷的现象;改变采样温度在该实验中有帮助,但没有证明不确定性已经校准,也不是通用补救办法。利用模型缺陷
因此,实际审查需要看留出序列、动作覆盖、误差如何随滚动时域增长、奖励与继续预测,以及策略真实表现。与简单的真实环境基线比较时,要列清交互和计算预算。随机预测器可以表达结果变化,却未必正确估计自身参数的不确定性;生成一个貌似合理的未来,也没有证明当前动作真会导致它。
你会保留什么信息?
-
两辆小车的位置都是零,速度分别为 与 ,动作都为零。下一位置各是什么?只看到相同当前观察的预测器,最小平均位置平方误差是多少?
答案: 下一位置是 与 。等权条件均值为零,最小 MSE 为 。问题在于缺少速度信息,不是优化不够充分;两段历史能够区分这两辆车。
-
在前面的两奖励例子中令 。为什么结果是 6.04 而非 2.8?若第二次转移确实终止,结果如何变化?
答案: 有限截断处的价值 4 贡献了 ,所以 。真正终止把第二个继续标志设为零,移除自举,得到 2.8。人为限制想象长度,不会自动把边界变成终止状态。
-
模型在训练集上重构图像很准,却把一个罕见动作的奖励预测错了。将潜维度翻倍,足以证明控制效果好吗?
答案: 不够。容量增加可能有帮助,却不会自动补齐动作覆盖、合适的训练目标或正确的外推。应补充有关该动作的证据,独立评价奖励与滚动误差,再把得到的策略放回实际环境检验。
-
有人拿本程序与另一控制器比较,只报告用了 256 个真实样本。他漏记了什么?怎样检验 1D 模型是否系统性乐观?
答案: 还有 128 条留出查询、每个维数 184,640 次训练模型转移,以及另外计数的模型与真实评价。应保留全部八个种子和新留出起点上逐回合的“想象减真实”差值,不能只选种子 1。现有种子间的差值已经变号,普遍乐观的结论没有支持。
沿着接口读,不靠“做梦”这个词分类
2018 年会议论文给出一种具体的生成模型与控制器设计;所选 Dreamer 的 2020 年论文把潜动力学接入可微行为学习。固定作者 TF2 仓库适合对照接口,其 README 另外链接了最初的 TF1 实现。这里 Dreamer 论文网址中的 v3 是该论文的第三次修订,不是后来名叫 DreamerV3 的算法。World Models Dreamer 论文 固定版本代码
继续读基于模型的强化学习,区分规划与模型误差;读PCA,检查重构压缩保留了什么;读MuZero,对照另一种在搜索中使用、围绕任务目标训练的潜模型。这些比较讨论目标与接口,本篇线性实验没有复现它们的论文基准成绩。
先判断,再看解释
模型重构训练观察很准确,就能保证其中训练出的控制器在真实环境表现好吗?
学习目标
- 区分带观察的状态推断、无未来观察的想象,以及使用模型的不同决策方式。
- 拟合压缩表示、动力学与奖励,分开评价模型预测、想象回报及策略真实迁移。
先修与延伸
查看知识关联图 →参考文献
- Recurrent World Models Facilitate Policy Evolution — scoped conference paper
David Ha; Jürgen Schmidhuber · 2018 - Dream to Control: Learning Behaviors by Latent Imagination — arXiv v3
Danijar Hafner; Timothy Lillicrap; Jimmy Ba; Mohammad Norouzi · 2020 - Dreamer author TensorFlow2 implementation — fixed scoped reading
Danijar Hafner · 2021
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-23 · Single AI author. Scoped reading: Official13-page NeurIPS31 PDF. Read2–6 and first850 characters of page1 for identity; viewed4. Distinguish real-environment car controller training from in-model VizDoom training; temperature/transfer results are not universal guarantees. No complete appendix audit or benchmark reproduction. First submitted2019-12-03; selected v3 dated2020-03-17, marked ICLR2020. This revision is not the DreamerV3 algorithm. Read pages2–6 of20 and first850 characters of page1 for identity; viewed6. Inference/imagination, ELBO and behavior training checked; not all appendices or benchmarks. Fixed2021-05-03 commit. All65 README and19 MIT license lines; dreamer.py132–211/238–288, models.py10–82, tools.py316–340. Author TF2 version, distinct from the linked original TF1 implementation. KL, imagination interfaces and lambda returns checked; no upstream copying, installation or execution. Eight paired equations and four explained exercises. Observation-conditioned inference and observation-free prediction separated; KL direction, beta1 ELBO conditions and finite lambda bootstrap checked independently. Actual PCA/least-squares world model and CEM controller evaluated on all8seeds, with13 control/program checks plus3 probabilistic derivations. Independent one-step control oracle and closed-form trajectories; no real environment in imagination.1D optimism changes sign;2D exactness is designed into the linear task. No VAE/RSSM/Dreamer benchmark reproduction.
- 区分带观察推断与无未来观察的预测;独立核KL方向、beta1的ELBO条件与有限lambda自举。真实PCA/最小二乘模型+CEM控制器保留全部8种子,13程序/控制加3概率推导检查。独立单步最优控制与闭式轨迹,真实环境不进想象;1D乐观性变号,2D精确性来自线性任务构造,不冒称VAE/RSSM/Dreamer基准复现。
- 每题四张计算SVG,8数值/几何与6个当前响应式组合通过;三张当前选定图均直接实看,初次两处英文间距修订保留,数值不变,资产与稿件SHA绑定,完整页面验收另记。
核对的来源位置:
- Recurrent World Models Facilitate Policy Evolution — scoped conference paper · Official13-page NeurIPS31 PDF. Read2–6 and first850 characters of page1 for identity; viewed4. Distinguish real-environment car controller training from in-model VizDoom training; temperature/transfer results are not universal guarantees. No complete appendix audit or benchmark reproduction.
- Dream to Control: Learning Behaviors by Latent Imagination — arXiv v3 · First submitted2019-12-03; selected v3 dated2020-03-17, marked ICLR2020. This revision is not the DreamerV3 algorithm. Read pages2–6 of20 and first850 characters of page1 for identity; viewed6. Inference/imagination, ELBO and behavior training checked; not all appendices or benchmarks.
- Dreamer author TensorFlow2 implementation — fixed scoped reading · Fixed2021-05-03 commit. All65 README and19 MIT license lines; dreamer.py132–211/238–288, models.py10–82, tools.py316–340. Author TF2 version, distinct from the linked original TF1 implementation. KL, imagination interfaces and lambda returns checked; no upstream copying, installation or execution.
相关主题