Skip to main content
© 2026 ePowerAI — instrumented learning, no login required.
CoursesContact
ePOWERAI
CoursesContact
Week 12: World Models and Reinforcement Learning
Generative Models
01Week 1: Probabilistic Foundations
02Week 2: Variational Autoencoders
03Week 3: Generative Adversarial Networks
04Week 4: Energy-Based Models and Score Matching
05Week 5: Normalizing Flows
06Week 6: Denoising Diffusion Probabilistic Models
07Week 7: Flow Matching and Consistency Models
08Week 8: Conditioning and Control
09Week 9: Latent Diffusion and Multimodal Generation
10Week 10: Evaluating Generative Models
11Week 11: Representation Learning with Generative Models
12Week 12: World Models and Reinforcement Learning
13Week 13: Safety, Misuse, and Alignment
14Week 14: Generative AI Capstone
Week 12· Generative Models12 min read

Week 12: World Models and Reinforcement Learning

Learning Outcomes
  • Explain the world-model architecture and its role in model-based RLReinforcement Learning
  • Derive the RSSM ELBO (reconstruction + KL prior/posterior) and relate it to the VAE bound from Week 2
  • Explain Dreamer-style latent imagination: actor, critic, and short-horizon rollout for policy improvement
  • Analyze sample-efficiency tradeoffs and compounding model error in open-loop vs. closed-loop planning
Prerequisites
  • Week 2: VAEs - Latent variable representations
  • Week 11: Representation Learning - Feature extraction

Reinforcement Learning background is highly recommended for understanding the RLReinforcement Learning components.

  • Also see: Reinforcement Learning Week 10: Model-Based Reinforcement Learning and Planning — the planning side of world models.

Purpose of this lecture#

The generative models studied so far produce outputs in response to noise and conditioning signals. This lecture applies the same neural machinery to a fundamentally different goal: building a world model — a learned simulator that predicts how the environment transitions in response to agent actions, enabling an agent to plan by imagining future states rather than by acting in the real world. World models represent the deepest integration of generative modeling with decision-making, and they provide the conceptual foundation for understanding how foundation models will be used in physical AI.


World models: architecture and role#

World models (Ha & Schmidhuber, 2018) are a class of generative models that learn to simulate the environment in which an agent operates. The key insight is that the same neural machinery used to generate images, audio, or text can be applied to predict the next state of the environment given the current state and action: p(st+1∣st,at)p(s_{t+1} \mid s_t, a_t)p(st+1​∣st​,at​). This predictive capability enables model-based reinforcement learning, where the agent can plan by simulating many possible actions in its internal world model rather than interacting with the real environment.

The world model architecture typically consists of three components:

  1. Encoder: maps observations oto_tot​ to latent states ztz_tzt​
  2. Dynamics model: learns the transition function p(zt+1∣zt,at)p(z_{t+1} \mid z_t, a_t)p(zt+1​∣zt​,at​)
  3. Decoder: maps latent states back to observations o^t=p(ot∣zt)\hat{o}_t = p(o_t \mid z_t)o^t​=p(ot​∣zt​)

This structure enables imagination: the agent can generate sequences of imagined states by sampling from the dynamics model, then decode them to produce simulated observations. This imagination capability is crucial for planning, as the agent can evaluate many possible action sequences without actually executing them in the real environment.


The RSSM architecture#

The recurrent state space model (RSSM; Hafner et al., 2019) is the workhorse world-model backbone behind PlaNet and Dreamer. It factors the latent state into a deterministic recurrent path hth_tht​ and a stochastic path ztz_tzt​:

ht=fϕ(ht−1,zt−1,at−1),zt∼qϕ(zt∣ht,ot),o^t∼pθ(ot∣ht,zt)h_t = f_\phi(h_{t-1}, z_{t-1}, a_{t-1}), \qquad z_t \sim q_\phi(z_t \mid h_t, o_t), \qquad \hat{o}_t \sim p_\theta(o_t \mid h_t, z_t)ht​=fϕ​(ht−1​,zt−1​,at−1​),zt​∼qϕ​(zt​∣ht​,ot​),o^t​∼pθ​(ot​∣ht​,zt​)

At training time the posterior qϕ(zt∣ht,ot)q_\phi(z_t \mid h_t, o_t)qϕ​(zt​∣ht​,ot​) sees the current observation (filter). At imagination time only the prior pθ(zt∣ht)p_\theta(z_t \mid h_t)pθ​(zt​∣ht​) is available — the model must predict the next latent without oto_tot​:

pθ(zt∣ht)=N ⁣(μθ(ht), σθ2(ht))p_\theta(z_t \mid h_t) = \mathcal{N}\!\big(\mu_\theta(h_t),\, \sigma_\theta^2(h_t)\big)pθ​(zt​∣ht​)=N(μθ​(ht​),σθ2​(ht​))

This prior/posterior split is exactly the VAE structure from Week 2 applied to sequential data: hth_tht​ plays the role of context, ztz_tzt​ is the latent code, and the decoder reconstructs oto_tot​ (and usually reward rtr_trt​).

RSSM ELBO#

For a trajectory (o1:T,a1:T)(o_{1:T}, a_{1:T})(o1:T​,a1:T​), the world-model objective is an ELBO on log⁡p(o1:T∣a1:T)\log p(o_{1:T} \mid a_{1:T})logp(o1:T​∣a1:T​):

LRSSM=∑t=1T(Eqϕ ⁣[log⁡pθ(ot∣ht,zt)]⏟reconstruction+Eqϕ ⁣[log⁡pθ(rt∣ht,zt)]⏟reward (optional)−DKL(qϕ(zt∣ht,ot) ∥ pθ(zt∣ht))⏟prior matching)\begin{aligned} \mathcal{L}_\text{RSSM} &= \sum_{t=1}^{T} \Big( \underbrace{\mathbb{E}_{q_\phi}\!\big[\log p_\theta(o_t \mid h_t, z_t)\big]}_{\text{reconstruction}} + \underbrace{\mathbb{E}_{q_\phi}\!\big[\log p_\theta(r_t \mid h_t, z_t)\big]}_{\text{reward (optional)}} - \underbrace{D_\text{KL}\big(q_\phi(z_t \mid h_t, o_t)\,\|\, p_\theta(z_t \mid h_t)\big)}_{\text{prior matching}} \Big) \end{aligned}LRSSM​​=t=1∑T​(reconstructionEqϕ​​[logpθ​(ot​∣ht​,zt​)]​​+reward (optional)Eqϕ​​[logpθ​(rt​∣ht​,zt​)]​​−prior matchingDKL​(qϕ​(zt​∣ht​,ot​)∥pθ​(zt​∣ht​))​​)​

Intuition: reconstruction forces ztz_tzt​ to carry information needed to explain oto_tot​; the KL keeps the posterior close to the prior so that open-loop rollouts (no observations) stay on-distribution. If the KL is too weak, imagination diverges from filtered states; if too strong, ztz_tzt​ collapses and the model becomes a deterministic RNN with limited multi-modality.

What breaks here

Compounding imagination error. One-step prediction MSE can look excellent while multi-step open-loop rollouts drift badly — the browser lab demonstrates this with a linear latent dynamics model. MBRL therefore uses short imagination horizons, periodic re-encoding from real observations, ensembles, or stochastic latents that express uncertainty rather than a single overconfident mean.


Dreamer: latent imagination for policy learning#

Dreamer (Hafner et al., 2020; DreamerV2/V3) freezes the RSSM as a differentiable simulator and trains policy components inside it:

  1. World model — RSSM + reward head, trained on real environment data with the ELBO above
  2. Actor πψ(at∣ht,zt)\pi_\psi(a_t \mid h_t, z_t)πψ​(at​∣ht​,zt​) — proposes actions in latent space
  3. Critic Vξ(ht,zt)V_\xi(h_t, z_t)Vξ​(ht​,zt​) — estimates expected return from a latent state

Latent imagination#

Starting from a real latent (ht,zt)(h_t, z_t)(ht​,zt​) obtained by filtering observations, Dreamer rolls out HHH imagined steps without new environment interaction:

aτ∼πψ( ⋅∣hτ,zτ),hτ+1=fϕ(hτ,zτ,aτ),zτ+1∼pθ(zτ+1∣hτ+1),r^τ∼pθ(r∣hτ,zτ)a_\tau \sim \pi_\psi(\,\cdot\mid h_\tau, z_\tau), \quad h_{\tau+1}=f_\phi(h_\tau, z_\tau, a_\tau), \quad z_{\tau+1}\sim p_\theta(z_{\tau+1}\mid h_{\tau+1}), \quad \hat{r}_\tau \sim p_\theta(r\mid h_\tau, z_\tau)aτ​∼πψ​(⋅∣hτ​,zτ​),hτ+1​=fϕ​(hτ​,zτ​,aτ​),zτ+1​∼pθ​(zτ+1​∣hτ+1​),r^τ​∼pθ​(r∣hτ​,zτ​)

for τ=t,…,t+H−1\tau = t, \ldots, t+H-1τ=t,…,t+H−1. Returns are bootstrapped with the critic (e.g. λ\lambdaλ-returns / GAE-style targets). The critic fits these targets; the actor maximizes expected return by backpropagating through the differentiable dynamics (analytic gradients through h,zh,zh,z when continuous, or reinforce-style estimators when discrete).

Why this is sample-efficient: each real transition can seed many imagined trajectories. Policy gradients use model-generated experience, so the agent needs far fewer environment steps than model-free methods — provided the world model is accurate on action-relevant directions.

DreamerV3 adds practical stabilizers (symlog observations/rewards, free-bits KL floors, percentile return normalization) that make the same recipe work across discrete and continuous control without per-domain retuning.


Model predictive control and latent-space planning#

Model predictive control (MPC) uses the world model at decision time rather than amortizing a policy:

  1. Predict short-horizon trajectories under candidate action sequences
  2. Optimize expected return or cost over the horizon
  3. Execute only the first action, then replan (receding horizon)

In latent space this is cheaper than pixel-space planning: optimize over zzz-trajectories (dimension dz≪H×W×Cd_z \ll H\times W\times Cdz​≪H×W×C), optionally decode only for visualization. Cross-entropy method (CEM), MPPI, or gradient-based planners all apply to pθ(zt+1∣ht+1)p_\theta(z_{t+1}\mid h_{t+1})pθ​(zt+1​∣ht+1​).

ApproachWhen actions are chosenStrengthFailure mode
Dreamer (actor-critic)Amortized policy πψ\pi_\psiπψ​ trained offline in imaginationFast at act time; scales with dataPolicy inherits model bias
Latent MPCOnline optimization each stepReplans with latest latent; flexible costPlanning compute; model error on long HHH

Closed-loop vs. open-loop: re-encoding observations (or resetting zzz to the filtered posterior) every kkk steps bounds error growth. Pure open-loop dreams of length 40 with a slightly wrong A,BA,BA,B already diverge — the lab quantifies this.


Sample efficiency and model-based vs. model-free RL#

Sample efficiency measures real environment interactions needed to reach a performance level. Model-based methods reuse a learned simulator for many gradient steps; model-free methods require a real transition (or replay of one) for each update.

Model-based (world model)Model-free
DataFewer real steps if model is goodMany real steps
ComputeTrain model + imagination / planningTrain policy / value only
RiskModel exploitation, compounding errorHigh sample cost, less planning structure

Model exploitation: the actor may discover adversarial action sequences that the world model scores highly but the real environment does not. Mitigations include short HHH, ensembles, uncertainty penalties, and continual fine-tuning of the model on on-policy data.


World models in physical AI#

In robotics and autonomous systems, world models support:

  1. Lookahead — predict contact, occlusion, and object motion before acting
  2. Uncertainty — stochastic ztz_tzt​ expresses multi-modal futures (e.g. which way a door swings)
  3. Sim-to-real — train policies in imagination; transfer with residual adaptation

Challenges remain: visual domain gap, long-horizon credit, and ensuring the latent is controllable (action-relevant) rather than merely reconstructive.


Cross-course context: world models across the curriculum#

CourseWhat is being simulated
Reinforcement LearningEnvironment dynamics p(s′∣s,a)p(s'\mid s,a)p(s′∣s,a) for planning and MBRL
Robot LearningBody + scene dynamics for control and sim-to-real
Generative Models (this course)Data distribution p(x)p(x)p(x); RSSM as a sequential generative model
Physical AI (VLMs)Joint vision–language structure; video/world prediction with multimodal conditioning

The same ELBO and latent-dynamics machinery appears under different names: a VAE for images, an RSSM for pixels+actions, a diffusion policy for action chunks. Generative modeling supplies the likelihood and representation tools; RL supplies the decision objective.


Browser lab: latent dynamics rollout (RSSM / Dreamer-style)#

Linear latent world model zt+1=Azt+Bat+ξz_{t+1} = A z_t + B a_t + \xizt+1​=Azt​+Bat​+ξ. One-step fit looks fine; multi-step open-loop imagination compounds error — why MBRL needs short horizons or closed-loop replan.

python · runs in browser
import numpy as np

rng = np.random.default_rng(0)
d_z, d_a = 4, 2
# True dynamics (stable spiral-ish)
A_true = np.array([
    [0.90, -0.10, 0.00, 0.00],
    [0.10,  0.90, 0.00, 0.00],
    [0.00,  0.00, 0.85, 0.05],
    [0.00,  0.00, -0.05, 0.85],
])
B_true = rng.normal(0, 0.3, size=(d_z, d_a))
noise = 0.05

def rollout(A, B, z0, actions, noise_std=0.0):
    z = z0.copy()
    traj = [z.copy()]
    for a in actions:
        z = A @ z + B @ a + rng.normal(0, noise_std, size=d_z)
        traj.append(z.copy())
    return np.array(traj)

# Collect data and fit least-squares ẑ' ≈ A z + B a
T_data = 800
z = rng.normal(size=d_z)
Zs, Zs_next, As = [], [], []
for _ in range(T_data):
    a = rng.normal(size=d_a)
    z_next = A_true @ z + B_true @ a + rng.normal(0, noise, size=d_z)
    Zs.append(z); Zs_next.append(z_next); As.append(a)
    z = z_next
Z, Zp, Act = map(np.array, (Zs, Zs_next, As))
# z' = A z + B a  ⇒  Zp = Z @ A.T + Act @ B.T
Phi = np.hstack([Z, Act])
Theta, *_ = np.linalg.lstsq(Phi, Zp, rcond=None)  # (d_z+d_a, d_z)
A_hat = Theta[:d_z, :].T
B_hat = Theta[d_z:, :].T

print(f"One-step train MSE: {np.mean((Zp - (Z @ A_hat.T + Act @ B_hat.T))**2):.4f}")
print(f"||A_hat - A_true||_F: {np.linalg.norm(A_hat - A_true):.3f}")

# Multi-step open-loop imagination error
z0 = rng.normal(size=d_z)
actions = rng.normal(size=(40, d_a))
true_tr = rollout(A_true, B_true, z0, actions, noise_std=0.0)
pred_tr = rollout(A_hat, B_hat, z0, actions, noise_std=0.0)
print(f"\n{'H':>4}  {'MSE@H':>10}  {'||z|| drift':>12}")
for H in [1, 5, 10, 20, 40]:
    mse = np.mean((true_tr[H] - pred_tr[H]) ** 2)
    drift = np.linalg.norm(pred_tr[H] - true_tr[H])
    print(f"{H:4d}  {mse:10.4f}  {drift:12.3f}")

# Closed-loop: replan every k steps (reset latent to true — like re-encoding obs)
def closed_loop_mse(k, H=40):
    z_t, z_p = z0.copy(), z0.copy()
    errs = []
    for t in range(H):
        a = actions[t]
        z_t = A_true @ z_t + B_true @ a
        z_p = A_hat @ z_p + B_hat @ a
        if (t + 1) % k == 0:
            z_p = z_t.copy()  # re-encode from observation
        errs.append(np.mean((z_t - z_p) ** 2))
    return np.mean(errs)

print("\nMean MSE over 40 steps with re-encode every k:")
for k in [40, 10, 5, 1]:
    print(f"  k={k:2d}  MSE={closed_loop_mse(k):.4f}")
print("Notice: one-step fit ≠ long dream accuracy; short imagination + frequent re-encoding stabilizes MBRL.")

What to try: raise process noise = 0.2 or shrink T_data — multi-step error blows up faster.


Key takeaways#

World models are action-conditioned generative models of environment dynamics. The RSSM splits latent state into a recurrent deterministic path hth_tht​ and a stochastic code ztz_tzt​, trained with an ELBO that balances reconstruction against prior–posterior KL so open-loop imagination stays on-distribution. Dreamer freezes that model and improves an actor–critic inside short latent rollouts, trading model bias for sample efficiency. Latent MPC plans online in the same space. One-step fit quality does not guarantee multi-step dream accuracy — short horizons, re-encoding, and uncertainty-aware latents are essential.


Conceptual questions#

  1. A world model predicts the next observation given the current state and action. What are the advantages of this approach over direct policy learning? What are the potential disadvantages?

  2. Write the RSSM ELBO terms for one timestep and explain the role of the KL between qϕ(zt∣ht,ot)q_\phi(z_t \mid h_t, o_t)qϕ​(zt​∣ht​,ot​) and pθ(zt∣ht)p_\theta(z_t \mid h_t)pθ​(zt​∣ht​). What goes wrong if this KL is driven to zero? What goes wrong if it is ignored?

  3. Dreamer uses latent imagination to improve an actor–critic. What are the key components of this process, and how does it differ from model-free learning and from online latent MPC?

  4. Model-based methods can be more sample-efficient than model-free methods, but they also suffer from model error. How does Dreamer (and the browser lab) address compounding imagination error?

  5. How do world models in generative modeling relate to world models in reinforcement learning? What are the key similarities and differences?

Solutions
  1. Advantages of a predictive world model over direct policy learning: sample efficiency (plan in imagination instead of acting), reuse of one model across tasks/rewards, support for planning/MPC, and interpretability of predicted rollouts. Disadvantages: compounding model error (the planner trusts inaccurate predictions), extra compute to learn and roll out the model, model exploitation by the optimizer, and an objective mismatch — predictive accuracy is not the same as task reward.
  2. Per-step terms: reconstruction Eq[log⁡p(ot∣ht,zt)]\mathbb{E}_{q}[\log p(o_t\mid h_t,z_t)]Eq​[logp(ot​∣ht​,zt​)] (and usually reward), minus DKL(qϕ(zt∣ht,ot) ∥ pθ(zt∣ht))D_\text{KL}(q_\phi(z_t\mid h_t,o_t)\,\|\,p_\theta(z_t\mid h_t))DKL​(qϕ​(zt​∣ht​,ot​)∥pθ​(zt​∣ht​)). The KL keeps the filter close to the prior so open-loop imagination (no oto_tot​) stays on-distribution. KL→0\to 0→0 collapses ztz_tzt​ toward a deterministic RNN (weak multi-modality). Ignoring the KL lets the posterior use information unavailable at imagination time, so dreams diverge from filtered states.
  3. Dreamer's imagination uses the RSSM world model (rolls out h,zh,zh,z), an actor πψ\pi_\psiπψ​, and a critic VξV_\xiVξ​, training on short model-generated trajectories with few real interactions. Unlike model-free learning, gradients use imagined transitions; unlike online latent MPC, Dreamer amortizes actions into πψ\pi_\psiπψ​ so act-time does not run a planner.
  4. Short imagination horizons cap compounding error; stochastic latents + KL balancing express uncertainty; the model is refreshed with real data; the critic bootstraps beyond HHH. The lab shows one-step MSE can look fine while multi-step open-loop MSE blows up — re-encoding every kkk steps (closed loop) restores accuracy.
  5. Similarity: both learn a generative simulator p(next∣current,⋅)p(\text{next}\mid \text{current}, \cdot)p(next∣current,⋅) with the same latent-variable/ELBO machinery. Differences: in pure generative modeling there is no agent, action, or reward — the "world" is the data distribution; in RL the model is action-conditioned and exists to support reward-maximizing planning, so it must be accurate in action-relevant directions and is judged by downstream control performance rather than sample fidelity.

Knowledge Check#

Check world models and generative RL.

Exercise · Fill in the blank

Dreamer-style agents train policies by rolling out imagined trajectories inside a learned latent ___ model (e.g. RSSM).

Exercise · Multiple choice

An RSSM typically maintains:

A recurrent latent state updated with actions and observations for dynamics prediction
Only a single static ImageNet label
No temporal structure
Exact pixels without compression always
Question 1 of 3

Latent-space MPC uses the world model to:

Plan short-horizon actions by optimizing imagined trajectories then executing the first action
Avoid any planning forever
Only label images offline
Delete the policy network always

Looking ahead#

With world models linking generation to decision-making, the course turns to the risks that accompany powerful generative systems.

Week 13: Safety, Misuse, and Alignment. We examine misuse vectors (deepfakes, memorization, adversarial inputs), detection and differential-privacy defenses, and the RLHF/DPO alignment techniques that steer model behavior toward human preferences.


Further reading#

  • Ha, D., & Schmidhuber, J. (2018). World Models. NeurIPS.
  • Hafner, D., et al. (2019). Learning Latent Dynamics for Planning from Pixels (PlaNet, RSSM). ICML.
  • Hafner, D., et al. (2020). Dream to Control: Learning Behaviors by Latent Imagination (Dreamer). ICML.
  • Hafner, D., et al. (2023). Mastering Diverse Domains through World Models (DreamerV3). arXiv.
  • Sutton, R. S. (1991). Dyna: An Integrated Architecture for Learning, Planning, and Reacting. ACM SIGART.
← Previous
Week 11: Representation Learning with Generative Models
Next →
Week 13: Safety, Misuse, and Alignment
On this page
  • Purpose of this lecture
  • World models: architecture and role
  • The RSSM architecture
  • RSSM ELBO
  • Dreamer: latent imagination for policy learning
  • Latent imagination
  • Model predictive control and latent-space planning
  • Sample efficiency and model-based vs. model-free RL
  • World models in physical AI
  • Cross-course context: world models across the curriculum
  • Browser lab: latent dynamics rollout (RSSM / Dreamer-style)
  • Key takeaways
  • Conceptual questions
  • Knowledge Check
  • Looking ahead
  • Further reading