World models: does a good imagined policy survive reality?
世界模型
Learn compressed representations and dynamics from position observations, train a controller in imagination, and test prediction and real behavior separately.
world-modelsThe same position can require opposite actions
Imagine a cart that should stop at the origin. A sensor reports its position, but not its velocity. Two carts can occupy the same place while moving in opposite directions. A controller that treats the latest reading as the complete state cannot tell which way to brake. This is our original teaching problem, not a robotics benchmark.
A world model predicts consequences of actions from available experience. Its internal state might be a physical vector, a recurrent memory, or a learned latent representation. The useful question is what information survives inside it: can it distinguish histories that imply different rewards or futures? A detailed-looking reconstructed image does not answer that question.
The name also refers to Ha and Schmidhuber’s 2018 work. Their visual encoder, recurrent predictor and small controller had distinct roles. The CarRacing experiment trained the controller using the actual environment; the VizDoom experiment trained it inside a generated environment before transfer. The paper acknowledges earlier model-based work. Neither experiment establishes that all world models must reconstruct images or search a tree. Conference paper, Sections 2–4
Our program learns a compressed representation, a transition predictor and a reward predictor from synthetic observations. It then optimizes a small controller entirely through imagined rollouts and evaluates that controller in the real teaching simulator. Keeping two latent dimensions succeeds on this exactly representable task; retaining one introduces a measurable prediction and transfer gap.
Inferring a state is different from imagining its future
Let be an observation, an action and a model state. An observation-conditioned inference distribution can correct its state using evidence that has actually arrived. A predictive distribution must advance without that future evidence:
These are common latent-model interfaces, not a requirement that every implementation use this exact reward indexing. We use for inference and for prediction; the selected Dreamer paper uses the opposite letters. What matters is which arguments each function receives. Feeding held-out future observations into every imagined step would test reconstruction under correction, not autonomous prediction. Dreamer, Sections 2 and 4
A reconstruction-based model can minimize the following sequence objective. The expectations use the observation-conditioned latent sequence; controls regularization:
With compatible normalized generative factors and , this has the negative-ELBO form: observation and reward likelihoods reward useful predictions, while the KL term charges for encoding information that the transition prior did not predict. An arbitrary changes the objective; it is not automatically the same likelihood bound. This training objective alone does not prove that latent states preserve every distinction needed for control. Dreamer also examines other representation objectives. Dreamer, Section 4
For diagonal Gaussian inference and prediction, the KL can be evaluated coordinate by coordinate. Variances must be strictly positive:
The direction matters. For and , the forward KL is about and the reverse about . Matching the two distributions would make either direction zero. In the fixed author implementation, the KL direction agrees with inference relative to prediction; its free_nats operation floors the averaged KL, not each coordinate separately. Read code and scope
Using a model does not specify one control algorithm. A planner can compare imagined action sequences online; a controller can use the model’s memory as features; or a learned policy can be optimized using imagined experience and later act without online search. Dreamer learns an actor and value function from imagined trajectories. Fixing model parameters during actor learning still allows derivatives through the model with respect to actions and states. The selected TF2 code also stops gradients through the features passed into the actor, a detail that should not be confused with unrestricted closed-loop differentiation. Dreamer, Section 3 Author implementation
One finite-horizon return convention makes the value bootstrap explicit. Let be continuation after receiving , so a true terminal transition has :
This is a stated teaching convention, with rewards attached to outgoing transitions. A value at an externally imposed cutoff need not vanish. With rewards 1 and 2, next values 3 and 4, continuation 1, and , backward calculation gives and . At , the finite boundary still bootstraps: . The fixed code’s comment calls this setting Monte Carlo, but its nonzero bootstrap remains in the actual recurrence. Return implementation
Learn a model, then keep reality out of policy training
The simulator uses position , velocity , bounded action and a fixed 20-step evaluation horizon. Reward is the negative cost of the new position, new velocity and action:
The learner receives four affine sensor channels per position. Concatenating two successive readings gives eight observed numbers; because here, those readings contain the two-dimensional physical state. One current reading alone does not. collect draws independent reset states and one-step actions: its 256 training transitions are generative queries, not a claimed exploration trajectory. Another 128 independent transitions are held out.
PCA is fit using training observations only. For a chosen dimension , its orthonormal basis yields the encoding and reconstruction:
Here is the eight-channel observation history. This deterministic linear compressor replaces a neural encoder for the experiment; it is not a VAE or an RSSM. Next, least squares fits an affine transition in latent space and a quadratic reward function. Define to contain an intercept, every coordinate of , and each distinct quadratic product:
Two retained dimensions make this synthetic process exactly representable up to floating-point error. That favorable property is designed into the teaching problem; it is not evidence that a learned visual model will be exact. With one dimension, the decoder and transition cannot recover all the discarded information.
The controller has only parameters. We optimize its mean imagined return from 16 encoded training starts:
Our cross-entropy search samples 48 parameter vectors in each of 12 rounds, retains the best eight, and updates a diagonal Gaussian from them with a standard-deviation floor of 0.05. It also evaluates a zero-action controller before search and retains the best candidate encountered. This is a small derivative-free optimizer, not CMA-ES and not Dreamer’s actor–critic update. Training executes model transitions per dimension. No call to the real environment is permitted inside imagined_returns or optimize.
For latent width , the reward design has features. Least-squares fitting and the eight-channel SVD are small here. Policy search costs rounds × population × starts × horizon model steps, each using an affine transition and quadratic features; the vectorized rollout stores current states rather than every imagined trajectory. These counts do not measure wall-clock speed against a neural agent.
Run the following complete program with Python and NumPy. The CLI shows summary output; experiment() retains all per-episode real and imagined returns for inspection.
"""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))
Inspect the recorded summary
{
"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
}
]
}Each row below is a complete independent seed. Returns are undiscounted sums of negative costs; a less negative number is better. The same 32 held-out initial states are used for both representations and the zero-action baseline within a seed. Values are rounded to five decimal places.
| Seed | 1D real | 2D real | Zero-action real | 1D transfer 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 |
For seed 0, the 1D held-out next-observation RMSE is about 0.34678. Its mean imagined evaluation return is −5.48106 versus −3.58474 in reality; for seed 1, the ordering reverses. Model error is not necessarily optimistic or pessimistic. The 2D transfer MAE is below in all eight runs. Neither controller search nor this comparison proves global policy optimality.
Keep evaluation separate from training cost. Per dimension, the 32 imagined evaluation episodes add 640 model transitions; the learned controller and zero-action baseline each consume 640 real evaluation transitions. The code repeats the baseline for each dimension. These evaluations never update the model or controller. All episodes end at a fixed cutoff; this example has no learned termination head or terminal-state training.
A convenient simulator can teach the wrong lesson
The experiment has no stochastic dynamics, images, neural sequence model, posterior sampling or learned continuation. Two observations are sufficient by construction, all models are trained once, and the same deterministic law governs training and testing. To test distribution shift, add a separately declared change to the simulator and rerun evaluation without silently refitting on the test data.
Low reconstruction loss, accurate one-step prediction, sensible multi-step forecasts and useful policies are distinct tests. A representation might preserve large visual variations while dropping a small cue that changes the optimal action. A controller may also select actions that lead away from the model’s training distribution. The 2018 paper documents policies exploiting its generated environment; changing sampling temperature helped in that experiment, but did not establish calibrated uncertainty or a universal remedy. World-model exploitation
A practical review therefore checks held-out sequences, action coverage, rollout-horizon error, reward and continuation predictions, and real policy performance. Compare against a simple real-world baseline using explicit interaction and computation budgets. A stochastic predictor can express variability without correctly estimating uncertainty about its own parameters; a plausible generated future is not proof that the chosen action will cause it.
What information would you keep?
-
Two carts have position zero, velocities and , and action zero. What is their next position? What is the smallest average squared position error of a predictor that sees only the identical current observation?
Answer: The next positions are and . Their equal-weight conditional mean is zero, giving minimum MSE . The failure comes from missing velocity information, not insufficient optimization. Two histories distinguish the carts.
-
Use the two-reward example with . Why is the result 6.04 rather than 2.8? What changes if the second transition really terminates?
Answer: The finite-cutoff value 4 contributes , so . True termination sets the second continuation to zero, removing that bootstrap and giving 2.8. An arbitrary imagination cutoff is not automatically a terminal state.
-
A model has accurate image reconstruction on its training set but predicts the wrong rewards for a rare action. Is doubling the latent dimension enough to certify good control?
Answer: No. More capacity may help but does not supply missing action coverage, a suitable training objective, or correct extrapolation. Collect evidence about that action, evaluate reward and rollout errors independently, and test the resulting policy in the actual environment.
-
Someone reports only 256 real samples while comparing this program with another controller. Which costs are missing, and what additional experiment would test whether the 1D model’s optimism is systematic?
Answer: There are also 128 held-out queries, 184,640 training model transitions per dimension, and separately counted model and real evaluation rollouts. Keep episode-level imagined-minus-real gaps over all eight seeds and new held-out starts, instead of selecting seed 1. The observed sign already changes across seeds; a universal optimism claim is unsupported.
Follow the interfaces, not the word “dream”
The 2018 conference paper provides one concrete generative-model/controller design; Dreamer’s selected 2020 paper connects latent dynamics to differentiable behavior learning. The fixed author TF2 repository is a useful interface comparison, while its README separately links the original TF1 implementation. v3 in our Dreamer paper URL means the third revision of that paper, not the later algorithm named DreamerV3. World Models Dreamer paper Versioned code
Read model-based reinforcement learning for planning and model-error distinctions, PCA for what reconstruction compression preserves, and MuZero for a different task-oriented latent model used inside search. The comparisons concern objectives and interfaces; our linear experiment reproduces none of those papers’ benchmark scores.
Make a prediction, then check
Does accurate reconstruction of training observations guarantee that a controller trained inside the model performs well in the real environment?
Learning objectives
- Separate observation-conditioned inference, imagination without future observations, and distinct ways to use a model for decisions.
- Fit compressed representations, dynamics and rewards, and evaluate predictions, imagined returns and real policy transfer separately.
Prerequisites & connections
- Model-based reinforcement learning
- Principal component analysis
- Variational autoencoders
- Recurrent neural networks
References
- 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
Version1 · Editorial status: Recorded technical checks completed
View technical check record (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.
- 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.
- Four computed SVG variants per topic;8 numeric/geometry tests and6 current responsive cases passed. All three selected current captures directly viewed. Two initial English spacing edits preserved; numeric results unchanged. Actual assets and manuscripts are SHA bound. Full article acceptance recorded separately.
Source locations checked:
- 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.
Related topics