Lesson 6.6 — World Models
Previous lesson · 6.5 Vision-Language-Action Models · Course overview · Course roadmap
Policies and World Models
A policy selects actions from observations. A world model predicts how actions change the environment. Predictions can be over measured states, images, or learned latent variables. Given a model and an objective, a planner can compare candidate actions by rolling the model forward.
Model predictive control (MPC) repeatedly optimizes for the current history, executes part of a plan, and reads a new observation. A model can also produce imagined trajectories used to train a policy offline. The comparison below uses a proportional feedback baseline and online CEM planning for a small system with two hidden timescales.
Compare reactive control and model-based planning on the same system
Model-free vs. Model-based Control
Partial Observability and Belief State
In an MDP, the agent observes a state sufficient to determine the conditional law of the next state and reward given the action. A POMDP exposes observations that can leave important state hidden. A belief state is a conditional probability distribution over the hidden state given the observations and executed actions.
Imagine two internal contributions to one sensor. In the first system a positive contribution cancels a negative one. In the second, both contributions are zero. The sensor reads zero in both systems. Now leave both systems alone. The cancellation in the first system breaks as its two components fade at different rates. The second stays at rest.
With just that first reading and the common input, a deterministic predictor must issue the same forecast for both. A history of readings and executed inputs can help distinguish them. When uncertainty persists, a belief can retain several possibilities. In the figure, switch to identical internal states to see the two futures coincide.
A learned latent vector can summarize history for prediction. It need not recover a unique physical state or encode a calibrated belief. In the teaching system, different pairs satisfying give the same zero output when the preceding input is zero. Apply the same action to both and the next observations can separate.
One reading, two possible futures
Apply a common input and inspect the initial state components
| System | Hidden a | Hidden b | Observed y |
|---|---|---|---|
| System 1 | 0.3 | -0.9194 | 0 |
| System 2 | 0 | 0 | 0 |
Encoder, Transition, and Decoder
Initialize a width-four latent from four observed outputs and three previously executed inputs. Then evolve it under the proposed input sequence and decode one output per transition. The training data does not include the true hidden state.
The encoder uses 32 parameters, the transition 24, and the decoder five. With the identity activation this gives an affine model. With tanh, it gives a nonlinear model of the same parameter count. Once a rollout begins, it uses only the predicted latent and its candidate inputs. At the next MPC call, encode the newest observed history.
Encoder–Transition–Decoder Dataflow
Deterministic Memory and Stochastic State
A recurrent state space model (RSSM) combines deterministic memory with a stochastic latent. After a real observation, a representation model forms a posterior. During imagination, sample the prior predicted from the state because no future observation is available. Decoders can predict observations, rewards, or episode continuation.
PlaNet and Dreamer use learned recurrent dynamics. DreamerV3 uses categorical stochastic latents. The lab demonstrates the prior–posterior mechanism with an exact scalar Gaussian filter. Its dynamics are , with an observation and independent centered process and observation noise of variances and .
The Kalman gain balances prior precision and measurement precision. Larger reduces the influence of the observation. Larger spreads the prediction and can increase the gain. This calibrated linear Gaussian example illustrates an update whose neural counterpart must learn its conditional distributions from data.
Deterministic & Stochastic State Update
| Belief | Mean | Standard deviation |
|---|---|---|
| Prior | 0 | 0.922 |
| Posterior | -0.9142 | 0.367 |
Prediction and Prior–Posterior Alignment
A stochastic model can train a sequence objective that scores predicted observations and rewards while aligning the representation posterior with the predictive prior. Here the schematic expectation is taken under each posterior and every term is summed over time.
Here and . DreamerV3 also predicts continuation and separates the dynamics and representation KL objectives. The stop-gradient operator keeps the value while preventing differentiation through that argument. A floor on each KL changes the gradient in the region below the floor.
The two terms can have the same value while updating different model paths. The lab illustrates the KL with a one-dimensional Gaussian posterior and a standard-normal prior. The trainable 61-parameter world model uses deterministic output-prediction MSE.
Reconstruction & KL Objective
Multi-step Rollout and Compounding Error
A one-step objective trains a prediction initialized from a real history. To plan, the model must continue from its own predicted latent after that first transition. A multi-step objective differentiates through this recursion at each step in its training horizon.
A first-order expression separates error entering at transition from its propagation through later transition Jacobians. The rightmost Jacobian acts first, and the empty product is the identity. This expression uses zero initial latent error.
The Jacobian can change along a nonlinear trajectory. Process variability and uncertainty about the fitted model are separate effects. This lab measures prediction discrepancy directly on synthetic trajectories and displays how it changes with the rollout horizon.
Prediction Error Accumulation
| Model | Absolute error | Prefix MSE |
|---|---|---|
| Linear latent · H=8 | — | — |
| Nonlinear latent · H=1 | — | — |
| Nonlinear latent · H=8 | — | — |
Imagination, CEM, and Model Predictive Control
PlaNet uses latent dynamics for online action search. Dreamer uses imagined latent trajectories to train an actor and critic. In the teaching MPC, the objective averages a quadratic tracking cost and action penalty for a bounded candidate sequence.
At a planning call the past has already happened. Infer a starting state from that observed history, then start each candidate rollout from the same inferred state. Only the proposed future inputs change. Costs assigned to the branches are predictions. After a command is applied, the next real sensor reading supplies evidence for the next call.
| During a candidate rollout | After acting in the environment |
|---|---|
| A proposed input advances a predicted latent. | An executed input changes the physical system. |
| The decoder supplies an imagined output for scoring. | A sensor supplies a new observation for state inference. |
| Other branches remain available for comparison. | Only the executed branch contributes a new real observation. |
The cross-entropy method (CEM) initializes a diagonal Gaussian with mean zero and standard deviation 0.6. Each iteration draws and clips 48 action sequences to , evaluates them with the world model, and selects the lowest-cost eight. Fit the next Gaussian to those elite samples, with a standard-deviation floor of 0.08. After three rounds, use the best sequence from the last round. Typically execute one action and plan again.
The actor–critic alternative estimates returns from imagined rewards and continuation signals and learns a policy. One simplified bootstrapped return is
Here is the continuation factor, is discount, and determines how much later returns enter. The teaching experiment implements CEM action search, so the measured controls come from candidate costs and replanning.
MPC / CEM / Replanning Explorer
| Plan step | Selected action | Predicted y |
|---|---|---|
| 1 | 1 | 0.3338 |
| 2 | 0.9541 | 0.673 |
| 3 | 0.5556 | 0.7368 |
| 4 | 0.5471 | 0.8427 |
| 5 | 0.0269 | 0.702 |
| 6 | 0.6927 | 0.9336 |
| 7 | 0.0813 | 0.8044 |
| 8 | -0.076 | 0.6625 |
| 9 | 0.409 | 0.8021 |
| 10 | 0.3935 | 0.8623 |
Engineering Experiment · Prediction and Closed-loop Planning
The plant from Lesson 4.1 has two hidden coordinates with separate time constants. The input changes every three steps and lies in . The learner sees only the executed inputs and scalar outputs.
The nominal split has 48 training and 16 validation episodes of 48 steps, giving 1824 and 608 eight-step windows respectively. The 20-step test uses 24 independent episodes. The out-of-distribution evaluation retains their inputs and changes the coefficients of the first transition to and the coefficients of the second to . All three models use the same 61-parameter initialization, seed 3, 360 Adam updates at 0.008, and batch size 32. The affine model and one nonlinear model train at horizon eight. The remaining nonlinear model trains at horizon one.
The closed-loop evaluation uses eight additional initial histories for each plant, alternating targets of magnitude 0.7, and 30 control steps. All MPC variants use horizon ten, 48 candidates, three CEM rounds, and one executed action per plan. Oracle MPC uses the true plant and hidden state. The proportional controller applies . Measured cost uses the actual simulated outputs and applied inputs of the teaching system.
Live Latent Dynamics Training
Prediction benchmark · Seed 3
| Model | Validation 1-step MSE | Validation mean 8-step MSE | Test step 20 MSE | OOD step 20 MSE |
|---|---|---|---|---|
| Linear latent · H=8 | 0.001312 | 0.001482 | 0.002292 | 0.039040 |
| Nonlinear latent · H=1 | 0.001858 | 0.570084 | 0.606819 | 0.644808 |
| Nonlinear latent · H=8 | 0.001478 | 0.002869 | 0.008681 | 0.052487 |
The eight-step validation column averages errors over the entire eight-step rollout. The 20-step columns evaluate the final predicted step.
Closed-loop tracking benchmark
| Model | Nominal cost | Nominal final error | OOD cost | OOD final error |
|---|---|---|---|---|
| P controller | 0.038709 | 0.152439 | 0.031503 | 0.120170 |
| Oracle MPC | 0.025454 | 0.053524 | 0.020900 | 0.059882 |
| Linear latent · H=8 | 0.027306 | 0.111919 | 0.029035 | 0.104477 |
| Nonlinear latent · H=1 | 0.149054 | 0.400653 | 0.115719 | 0.329140 |
| Nonlinear latent · H=8 | 0.027236 | 0.066329 | 0.024150 | 0.058578 |
The one-step nonlinear model's error grows substantially over free rollouts, and its MPC tracks poorly on this split. Multi-step training improves both results for the nonlinear model. The affine latent model has the lowest validation prediction MSE here, while the multi-step nonlinear model has slightly lower nominal MPC cost. The Oracle uses the same finite CEM budget, so its measured cost still depends on search.
Reproducible PyTorch implementation
The script uses PyTorch CPU float64 and NumPy. It trains the three predictors, evaluates the 20-step tests, executes CEM with the measured plant, and writes the results to result0606.json.
import math,json,torch,numpy as np
torch.set_default_dtype(torch.float64);torch.set_num_threads(1)
class RNG:
def __init__(self,s):self.s=s
def __call__(self):self.s=(1664525*self.s+1013904223)%2**32;return self.s/2**32
def normal(self):return math.sqrt(-2*math.log(max(self(),1e-12)))*math.cos(2*math.pi*self())
def plant(s,u,shift=False):
a,b=s;a=(.93 if shift else .88)*a+(.24 if shift else .3)*u;b=(.5 if shift else .4)*b+(.18 if shift else .2)*u
return [a,b],a+.4*b+.1*u+.12*math.sin(2*a)
def episodes(seed,n,shift=False,T=48):
r=RNG(seed);out=[]
for _ in range(n):
s=[0.,0.];ys=[0.];us=[];ss=[s];u=0
for k in range(T):
if k%3==0:u=2*r()-1
us.append(u);s,y=plant(s,u,shift);ys.append(y);ss.append(s)
out.append((ys,us,ss))
return out
def windows(eps,H=8):return [(y[k-3:k+1]+u[k-3:k],u[k:k+H],y[k+1:k+H+1]) for y,u,s in eps for k in range(3,len(u)-H+1)]
def pack(ds):return tuple(torch.tensor(z) for z in zip(*ds))
D=4;SHAPES=[(D,7),(D,),(D,D+1),(D,),(1,D),(1,)]
def init(seed):
r=RNG(seed);return [torch.nn.Parameter(torch.tensor([.4*(2*r()-1) for _ in range(math.prod(s))]).reshape(s)) for s in SHAPES]
def forward(p,x,u,mode):
z=x@p[0].T+p[1];z=z if mode=='linear' else z.tanh();o=[]
for j in range(u.shape[1]):
z=torch.cat([z,u[:,j,None]],-1)@p[2].T+p[3];z=z if mode=='linear' else z.tanh();o.append((z@p[4].T+p[5])[:,0])
return torch.stack(o,1)
def train(mode,seed=3,steps=360,lr=.008):
p=init(seed);r=RNG(seed+200);ds=pack(windows(episodes(101,48)));vs=pack(windows(episodes(202,16)));opt=torch.optim.Adam(p,lr=lr);H=1 if mode=='one' else 8;hist=[]
for i in range(steps+1):
if i%60==0 or i==steps:
with torch.no_grad():
err=(forward(p,vs[0],vs[1],mode)-vs[2])**2;hist.append([i,err[:,0].mean().item(),err.mean().item(),err[:,-1].mean().item()])
if i==steps:break
ix=[int(r()*len(ds[0])) for _ in range(32)];x,u,y=(a[ix] for a in ds);opt.zero_grad();loss=(forward(p,x,u[:,:H],mode)-y[:,:H]).square().mean();loss.backward();opt.step()
return p,hist
def cem(p,mode,x,s,target,r,shift=False,H=10,N=48,iters=3):
mu=np.zeros(H);sig=np.ones(H)*.6
for _ in range(iters):
cand=np.array([[max(-1,min(1,mu[j]+sig[j]*r.normal())) for j in range(H)] for _ in range(N)])
if mode=='oracle':
a=np.full(N,s[0]);b=np.full(N,s[1]);out=[]
for u in cand.T:
a=(.93 if shift else .88)*a+(.24 if shift else .3)*u;b=(.5 if shift else .4)*b+(.18 if shift else .2)*u;out.append(a+.4*b+.1*u+.12*np.sin(2*a))
pred=np.stack(out,1)
else:
with torch.no_grad():pred=forward(p,torch.tensor(x).repeat(N,1),torch.tensor(cand),mode).numpy()
cost=((pred-target)**2+.03*cand**2).mean(1);idx=np.argsort(cost,kind='stable')[:8];elite=cand[idx];mu=elite.mean(0);sig=np.maximum(.08,elite.std(0))
return cand[idx[0]],pred[idx[0]],float(cost[idx[0]])
def roll(p,mode,ep,target,seed,shift=False):
y,u,ss=ep;ys=y[:4];us=u[:3];s=ss[3];r=RNG(seed);plans=[]
for k in range(30):
if mode=='p':act=max(-1,min(1,1.1*(target-ys[-1])))
else:
seq,pred,cost=cem(p,mode,ys[-4:]+us[-3:],s,target,r,shift);act=float(seq[0]);plans.append([seq.tolist(),pred.tolist(),cost])
s,obs=plant(s,act,shift);ys.append(obs);us.append(act)
return ys[3:],us[3:],plans
def main():
result={};models={}
for mode in ['linear','one','multi']:
p,hist=train(mode);models[mode]=p;result[mode]={'p':[a.detach().tolist() for a in p],'hist':hist};print(mode,hist[0],hist[-1],flush=True)
for name,shift in [('test',False),('ood',True)]:
x,u,y=pack(windows(episodes(303,24,shift),H=20));
with torch.no_grad():err=(forward(p,x,u,mode)-y).square();result[mode][name]=err.mean(0).tolist()
for shift in [False,True]:
eps=episodes(404 if not shift else 405,8,shift,T=3);key='control_ood' if shift else 'control';result[key]={}
for mode in ['p','oracle','linear','one','multi']:
ys=[];us=[];tra=[]
for i,ep in enumerate(eps):
target=.7 if i%2==0 else -.7;y,u,plans=roll(models.get(mode),mode,ep,target,900+i,shift);ys.append(np.mean((np.array(y[1:])-target)**2+.03*np.array(u)**2));us.append(abs(y[-1]-target));tra.append({'y':y,'u':u,'target':target,'plans':plans})
result[key][mode]={'cost':float(np.mean(ys)),'final':float(np.mean(us)),'example':tra[0]};print(key,mode,result[key][mode]['cost'],result[key][mode]['final'],flush=True)
open('result0606.json','w').write(json.dumps(result))
if __name__=='__main__':main()
References and Chapter Synthesis
- Ha and Schmidhuber combine a visual latent, predictive model, and controller. World Models
- Hafner et al. plan online in latent dynamics. PlaNet · Project site
- Dreamer learns control from imagined trajectories. Dream to Control · DreamerV3 preprint · Nature article · Implementation
- Further coverage of model-based planning and policy learning. Berkeley Deep RL
| Resource | Reading focus |
|---|---|
| DreamerV3 official repository | RSSM, world model loss, imagination, actor/critic; record commit before reproducing. |
| PlaNet project | Latent dynamics and online planning |
| Berkeley Deep RL | Model-based RL, planning, policy learning |
Chapter 6 links model adaptation and multimodal representation to imitation, action generation, and predictive control. The roadmap outlines the next chapter on physics-aware model research.
Previous lesson · 6.5 Vision-Language-Action Models · Course overview · Course roadmap