"I have walked across a thousand canyons and fallen into none of them, because I never left the room. Every cliff I learned to fear, every gait that kept me upright, I practiced inside a small recurrent dream of the world. By the time my real legs touched real ground, the falling was already behind me."
An Agent That Learned to Walk by Practicing in Its Own Dreams
A world model is a learned, differentiable simulator of an environment, and once an agent owns one it no longer has to learn by acting in the real world: it can learn by acting in its own imagination. Dreamer is the cleanest realization of this idea. At its heart sits a Recurrent State-Space Model (RSSM), a latent dynamics model whose state is split into a deterministic part (a GRU carry that remembers the past) and a stochastic part (a sampled code that captures what the past cannot determine). The RSSM learns to predict forward purely in latent space, compressing pixels and sensors into a compact state that rolls into the future cheaply. On top of that learned simulator Dreamer trains an actor and a critic entirely on imagined rollouts: it dreams thousands of short trajectories in latent space, estimates their returns, and improves the policy by backpropagating value gradients straight through the differentiable dynamics, never touching the environment during policy improvement. The payoff is twofold. Sample efficiency, because real interaction is spent only on learning the model, while behavior is learned for free in imagination; and generality, because the same agent, with one fixed set of hyperparameters, masters continuous control, Atari, and Minecraft. This section builds the RSSM and an imagination-based policy-improvement step from scratch, then shows the library equivalent and the line-count it erases, and it carries forward the state-space lineage of Chapter 13 and the actor-critic machinery of Section 25.3 into the world-model setting.
In Section 29.1 we built the latent world model: a learned simulator of the environment's dynamics, an agent that can predict the consequences of its actions can plan, reason counterfactually, and reuse experience far more efficiently than one that only memorizes a value function. We left open the practical question that decides whether the idea works at all, namely what to model and where. Modeling raw observations (pixels, full sensor vectors) step by step is expensive and brittle; the future of a high-dimensional observation is mostly irrelevant detail. This section answers the question the way the Dreamer line answers it: model a compact latent state, learned so that it carries exactly the information needed to predict reward and the next latent, and do all imagination there. That choice, latent-space dynamics with a hybrid deterministic-stochastic state, is what we now build.
The connection to the rest of the book is direct and worth stating before the machinery. The RSSM is a state-space model in precisely the sense of Section 7.6 and Chapter 13: a latent state evolves under learned dynamics and emits observations, and inference recovers a belief over that latent from data. The Kalman filter of Chapter 7 was a state-space model with linear-Gaussian dynamics we wrote down by hand; the RSSM is a state-space model with neural dynamics we learn by gradient descent, and its stochastic latent plays the role the process noise played there. This is the temporal thread of the book closing a loop: the filter returns, this time as the imagination engine of a planning agent. We use the unified notation of Appendix A: $\mathbf{o}_t$ the observation, $\mathbf{a}_t$ the action, $r_t$ the reward, and the latent state written as the pair $(\mathbf{h}_t, \mathbf{z}_t)$ throughout.
The four competencies this section installs: to write the RSSM as a deterministic GRU carry plus a stochastic latent and state its transition and ELBO-style training loss; to explain learning behavior in imagination, training an actor-critic on latent rollouts by backpropagating value gradients through the dynamics, and why that buys sample efficiency; to place the DreamerV1 to V3 line and PlaNet in context as a single agent mastering many domains with fixed hyperparameters; and to implement a small RSSM and an imagination policy-improvement step from scratch, then reach for the library equivalent.
1. The Recurrent State-Space Model at the Heart of Dreamer Intermediate
The central design decision of Dreamer is the shape of its latent state. A purely deterministic recurrent state (a plain GRU, Chapter 10) cannot represent uncertainty: given the past it commits to one future, which is fatal when the environment is genuinely stochastic or partially observed. A purely stochastic state (sample a fresh latent each step, as in a deep Kalman filter) can represent uncertainty but struggles to remember information reliably across many steps, because every step reinjects noise into the carry. The RSSM takes both and refuses to choose: the latent state at time $t$ is the pair $(\mathbf{h}_t, \mathbf{z}_t)$, where $\mathbf{h}_t$ is a deterministic recurrent carry computed by a GRU and $\mathbf{z}_t$ is a stochastic code sampled from a distribution that the carry parameterizes. The carry remembers; the sample hedges. This callback to the latent-variable view of Section 29.1 is the structural commitment everything else rests on.
Concretely, the RSSM defines three learned pieces. The deterministic recurrence advances the carry from the previous full state and action. The prior predicts the stochastic latent from the carry alone, this is the model dreaming forward with no observation to look at. The posterior (used only during training and real interaction, never in imagination) corrects the prior using the current observation. Writing $f_\phi$ for the GRU and Cat or Normal for the latent distribution,
$$\mathbf{h}_t = f_\phi(\mathbf{h}_{t-1}, \mathbf{z}_{t-1}, \mathbf{a}_{t-1}), \qquad \underbrace{\hat{\mathbf{z}}_t \sim p_\phi(\hat{\mathbf{z}}_t \mid \mathbf{h}_t)}_{\text{prior (imagination)}}, \qquad \underbrace{\mathbf{z}_t \sim q_\phi(\mathbf{z}_t \mid \mathbf{h}_t, \mathbf{o}_t)}_{\text{posterior (with observation)}}.$$Two heads read out of the full latent state $\mathbf{s}_t \equiv (\mathbf{h}_t, \mathbf{z}_t)$: a reward predictor $\hat{r}_t \sim p_\phi(r_t \mid \mathbf{s}_t)$ and a decoder $\hat{\mathbf{o}}_t \sim p_\phi(\mathbf{o}_t \mid \mathbf{s}_t)$ that reconstructs the observation. The decoder exists only to shape the latent during training; at deployment the agent never decodes, it acts straight off $\mathbf{s}_t$. The decisive property is that the prior $p_\phi(\hat{\mathbf{z}}_t \mid \mathbf{h}_t)$ lets the model step forward without any observation, which is exactly what imagination needs: roll the carry, sample a latent from the prior, predict the reward, repeat. Figure 29.2.1 draws the two-track state and the prior-versus-posterior split.
The RSSM is trained as a sequential latent-variable model, and its objective is an evidence lower bound (ELBO) of exactly the variational-autoencoder family met in Chapter 17, summed over time. For an observed trajectory of length $T$ the loss to minimize is
$$\mathcal{L}(\phi) = \sum_{t=1}^{T} \Big[ \underbrace{-\,\mathbb{E}_{q_\phi}\big[\log p_\phi(\mathbf{o}_t \mid \mathbf{s}_t)\big]}_{\text{reconstruction}} \;\underbrace{-\,\mathbb{E}_{q_\phi}\big[\log p_\phi(r_t \mid \mathbf{s}_t)\big]}_{\text{reward}} \;+\; \beta\,\underbrace{\mathrm{KL}\!\big[q_\phi(\mathbf{z}_t \mid \mathbf{h}_t, \mathbf{o}_t)\,\big\|\,p_\phi(\mathbf{z}_t \mid \mathbf{h}_t)\big]}_{\text{prior matches posterior}} \Big].$$Read the three terms as a contract. The reconstruction term forces the latent to retain enough about the observation to rebuild it, so $\mathbf{s}_t$ cannot collapse to nothing. The reward term forces the latent to retain whatever predicts reward, the part the agent actually cares about. The KL term is the engine of imagination: it pulls the prior (which dreams forward with no observation) toward the posterior (which has seen the observation), so that when the model later rolls forward on the prior alone, its samples land where real states would. Minimizing the KL is literally teaching the dream to match reality. The coefficient $\beta$ balances how hard the prior must track the posterior, and DreamerV2 introduced KL balancing (different learning rates for the prior and posterior sides of the KL) to keep this stable, a detail we note now and use later.
The single most important design choice in Dreamer is splitting the latent into $(\mathbf{h}_t, \mathbf{z}_t)$. The deterministic carry $\mathbf{h}_t$ is a GRU, so gradients and information flow across many steps without the noise injection that would corrupt a purely stochastic carry; it is the long-term memory. The stochastic $\mathbf{z}_t$ is sampled afresh each step, so it can represent the genuine uncertainty a deterministic state cannot; it is the hedge against an unpredictable or partially observed world. Neither alone suffices: drop the stochastic part and the model cannot represent a branching future; drop the deterministic part and it cannot remember reliably. The prior $p_\phi(\mathbf{z}_t\mid\mathbf{h}_t)$ is the piece that makes the whole thing a generative model you can roll forward without data, which is the one capability imagination requires. Hold "carry remembers, sample hedges, prior dreams" in mind and the rest of Dreamer is mechanism.
2. Learning Behavior in Imagination Advanced
With a trained RSSM the agent owns a differentiable simulator: from any latent state it can roll forward on the prior, producing a sequence of imagined states and predicted rewards without ever touching the environment. Dreamer exploits this to learn behavior entirely in imagination. It trains an actor (policy) $\pi_\theta(\mathbf{a}_t \mid \mathbf{s}_t)$ and a critic (value function) $v_\psi(\mathbf{s}_t)$, the same actor-critic pair of Section 25.3, but the trajectories they learn from are dreamed, not lived. The recipe: take a batch of real states encountered during data collection as starting points, then from each one imagine a short rollout of horizon $H$ (typically 15) by repeatedly sampling an action from the actor and a next latent from the RSSM prior, recording the predicted reward at each step.
The critic is trained to predict the imagined return. Dreamer uses a $\lambda$-return (the TD($\lambda$) target of Chapter 24) computed along the imagined rollout, mixing the model's predicted rewards with the critic's own bootstrap at the horizon:
$$V^\lambda_t = \hat{r}_t + \gamma\Big[(1-\lambda)\,v_\psi(\mathbf{s}_{t+1}) + \lambda\,V^\lambda_{t+1}\Big], \qquad V^\lambda_H = v_\psi(\mathbf{s}_H),$$and the critic minimizes $\tfrac{1}{2}\big(v_\psi(\mathbf{s}_t) - \operatorname{sg}(V^\lambda_t)\big)^2$, where $\operatorname{sg}$ is the stop-gradient that treats the target as fixed. The actor's objective is what makes Dreamer distinctive. Because the entire imagined rollout, the dynamics, the reward predictor, the critic, is differentiable, the actor can be improved by backpropagating the value gradient straight through the learned dynamics. For continuous actions Dreamer maximizes the imagined return by analytic gradients through the reparameterized rollout (the dynamics backprop, sometimes called value-gradient learning); it also adds an entropy bonus for exploration. Schematically the actor maximizes
$$\mathcal{J}(\theta) = \mathbb{E}_{\pi_\theta,\,p_\phi}\!\Big[\sum_{t} V^\lambda_t\Big] + \eta\, \mathrm{H}\!\big[\pi_\theta(\cdot\mid\mathbf{s}_t)\big],$$with the gradient $\nabla_\theta V^\lambda_t$ flowing through every imagined transition because $\mathbf{s}_{t+1}$ is a differentiable function of $\mathbf{a}_t = \pi_\theta(\mathbf{s}_t)$ via the RSSM. For discrete actions, where the path derivative is unavailable, DreamerV2 and V3 use a REINFORCE-style gradient with the critic as baseline instead, but the imagination loop is identical. The crucial point is that the gradient passes through the dynamics: the actor learns not just that an action was good but how the predicted future would change if the action changed, which is a far richer learning signal than the scalar reward a model-free method receives.
Model-free actor-critics (Section 25.3) improve the policy from real transitions only, so every gradient step on the policy costs real environment interaction. Dreamer decouples the two: real interaction is spent only on training the RSSM, and the policy is improved on imagined rollouts that cost nothing but compute. One batch of real data can seed thousands of imagined trajectories, so the agent extracts far more policy improvement per real step. On top of that, backpropagating value gradients through the differentiable dynamics gives the actor a vector-valued learning signal (how the whole future shifts with the action), where a model-free method sees only a scalar return. The two effects compound: more learning per real step, and richer signal per learning step. That is the structural reason Dreamer reaches strong performance with one to two orders of magnitude fewer environment steps than model-free baselines on many control tasks.
There is something delightfully unfair about it. A model-free agent must actually fall off the cliff, repeatedly, to learn that cliffs are bad. Dreamer falls off the cliff once or twice in reality, builds a little mental model of cliffs, and then falls off a thousand imaginary cliffs overnight at no cost while its real body sits perfectly still. The agent that practices in its own dream gets to make all its mistakes where mistakes are free. The only catch is the obvious one: if the dream is wrong, the agent confidently masters a world that does not exist. Which is exactly why half of Dreamer's machinery, the reconstruction loss, the KL that pins the prior to reality, is devoted to making sure the dream stays honest.
The honesty caveat in that note is the real risk of learning in imagination and deserves a precise statement. The actor is optimized against the model's predicted returns, so any region of latent space where the model is wrong is a region the actor can exploit, chasing imagined reward that reality will not pay. This is model exploitation, and it is bounded by two forces: the RSSM keeps improving as new real data arrives (so the regions the policy visits get modeled accurately), and the short imagination horizon $H$ limits how far a single rollout can drift from a real starting state before the critic's bootstrap takes over. The interplay (a model good enough to imagine, a horizon short enough not to compound its errors, a critic to summarize beyond the horizon) is the engineering that makes the elegant idea actually work, and it is what the Dreamer line spent three versions stabilizing.
3. The Dreamer Line and PlaNet Intermediate
The RSSM did not arrive with behavior learning attached. Its first home was PlaNet (Hafner et al., 2019), the Deep Planning Network, which used the same RSSM to learn latent dynamics from pixels and then planned in latent space at decision time with a sampling-based optimizer (the cross-entropy method): no policy network, just imagine many candidate action sequences through the model and pick the best. PlaNet showed that latent-space planning could match model-free performance with far less data, and we treat planning as a first-class alternative to a learned policy in Section 29.4. Dreamer's move was to replace the expensive per-step planning with an amortized actor trained in imagination, trading the deliberation of planning for the speed of a reactive policy that has already absorbed the planning into its weights.
The Dreamer line then pursued one goal across three versions: robustness across diverse domains with a single fixed set of hyperparameters. DreamerV1 (Hafner et al., 2020) established imagination-based behavior learning on continuous control from pixels. DreamerV2 (Hafner et al., 2021) switched the stochastic latent to a vector of categorical variables (discrete codes, which turned out to model the world better than Gaussians), added KL balancing for stable training, and became the first world-model agent to reach human-level Atari, matching model-free methods that used far more data. DreamerV3 (Hafner et al., 2023) was the culmination: a fixed configuration, with robustness tricks (symlog-transformed predictions to handle reward scales spanning many orders of magnitude, a two-hot reward encoding, careful normalization), that trained successfully on over 150 tasks spanning continuous control, Atari, DMLab, and proprioceptive robotics without per-task tuning. Its headline result was collecting diamonds in Minecraft from scratch, a famously long-horizon, sparse-reward exploration problem, with no human data and no curriculum.
| System | Year | Latent dynamics | Behavior from model | Headline result |
|---|---|---|---|---|
| PlaNet | 2019 | RSSM (Gaussian latent) | CEM planning in latent space (no policy) | pixel control with far less data |
| DreamerV1 | 2020 | RSSM (Gaussian latent) | actor-critic in imagination, value-gradient backprop | strong continuous control from pixels |
| DreamerV2 | 2021 | RSSM (categorical latent, KL balancing) | imagination actor-critic, discrete-action REINFORCE | first human-level Atari from a world model |
| DreamerV3 | 2023 | RSSM + symlog, robustness fixes | same loop, one fixed hyperparameter set | 150+ tasks; Minecraft diamonds from scratch |
The reason fixed hyperparameters matter so much is practical and easy to undervalue. Most reinforcement-learning results are reported after per-task tuning, which quietly hides a large amount of human effort and makes the methods hard to deploy on a new problem. An agent that works out of the box across robotics, video games, and 3D navigation with the same settings is a qualitatively different artifact: it is a recipe, not a research result that needs a graduate student to reproduce. DreamerV3's demonstration that one configuration suffices across such a span is the strongest evidence to date that a learned world model plus imagination is a general method for sequential decision making, not a trick that happens to work on one benchmark.
World models are one of the most active frontiers of 2024 to 2026, and the RSSM is being both scaled and replaced. TD-MPC2 (Hansen et al., 2024) learns a latent dynamics model and plans with model-predictive control at decision time, the planning lineage of PlaNet rebuilt at scale, and reports a single agent solving 80+ continuous-control tasks. On the generative side, the line from GameGAN through Google's Genie (2024) and DeepMind's Genie 2 (2024) builds action-controllable video world models that generate playable environments frame by frame, and diffusion world models such as DIAMOND (2024) replace the RSSM decoder with a diffusion model for sharper imagined observations. Transformer-based world models (IRIS, 2023; TWM; and the broader move to token-sequence dynamics) recast the RSSM's recurrence as autoregression over discrete latent tokens, connecting world modeling to the sequence-model view of decision making in Chapter 28. The throughline for 2026: the Dreamer recipe (learn a compact latent simulator, learn behavior inside it) is now a template, and the open questions are how to scale the simulator (diffusion, transformers), how to plan versus react inside it, and how far a single world-model agent can generalize across truly open-ended environments.
4. Why This Is a Milestone Intermediate
It is worth pausing to say plainly why the Dreamer line is treated as a landmark and not merely one more reinforcement-learning algorithm. The deep reinforcement learning of Chapter 25 produced agents that mastered single domains (one for Atari, another, retuned, for control) by learning a value function or policy directly from reward. Each was impressive and each was narrow. Dreamer demonstrated something structurally different: a single agent that masters many domains by first learning to model time, to predict how its world unfolds, and only then learning to act inside that model. The generality does not come from a bigger policy network; it comes from the discipline of building a predictive model of the environment's temporal dynamics and reusing it.
This is the thesis of the whole book arriving at its sharpest point. The temporal thread we have followed (the Kalman filter of Chapter 7 returning as the RNN of Chapter 10 and the structured state-space model of Chapter 13) reaches its destination here: a learned state-space model, trained to predict the future, becomes the engine of intelligent action. The classical state-space model was a tool for forecasting; the RSSM is the same mathematical object turned into a tool for deciding, because an agent that can forecast its world can rehearse in it. Modeling time is not a subroutine of the agent, it is the foundation the agent's competence is built on. That an agent which models time well can then act well across robotics, games, and navigation with one fixed recipe is the clearest demonstration in the book that temporal modeling and sequential decision making are one subject, not two.
Chapter 7 wrote down a state-space model by hand and used it to filter and forecast. Chapter 13 learned the state-space model's dynamics from data while keeping its parallel-scan efficiency. This section takes the learned state-space model one final step: it makes the latent dynamics the agent's imagination, and trains behavior inside it. The same equation, latent evolves, latent emits, that opened Part II as a forecasting device closes Part VI as a decision-making engine. An agent that has learned the temporal structure of its world has, almost as a side effect, learned to plan in it. Forecasting and deciding were never separate problems; the RSSM is where the book proves it.
5. Worked Example: An RSSM and an Imagination Policy-Improvement Step Advanced
We now build the two ideas of subsections one and two as runnable code: a small RSSM (deterministic GRU carry plus a stochastic Gaussian latent, with prior, posterior, and reward heads) and an imagination loop that improves an actor on imagined latent returns by backpropagating value gradients through the learned dynamics. The environment is irrelevant to the mechanics, so we keep the observation and reward toy and focus every line on the world-model machinery. Code 29.2.1 is the from-scratch RSSM.
import torch, torch.nn as nn, torch.nn.functional as F
class RSSM(nn.Module):
"""Minimal Recurrent State-Space Model: deterministic GRU carry h + stochastic z."""
def __init__(self, obs_dim, act_dim, h_dim=64, z_dim=16):
super().__init__()
self.h_dim, self.z_dim = h_dim, z_dim
self.cell = nn.GRUCell(z_dim + act_dim, h_dim) # advances the carry h_t
self.prior = nn.Linear(h_dim, 2 * z_dim) # p(z_t | h_t): mean, log-std
self.post = nn.Linear(h_dim + obs_dim, 2 * z_dim) # q(z_t | h_t, o_t)
self.r_head = nn.Linear(h_dim + z_dim, 1) # reward predictor r_hat
self.o_head = nn.Linear(h_dim + z_dim, obs_dim) # decoder o_hat (training only)
def _dist(self, params): # split into a Normal
mu, log_std = params.chunk(2, dim=-1)
return torch.distributions.Normal(mu, F.softplus(log_std) + 1e-4)
def step(self, h, z, a): # advance one step (imagine or train)
h = self.cell(torch.cat([z, a], dim=-1), h) # h_t = GRU(h_{t-1}, z_{t-1}, a_{t-1})
prior = self._dist(self.prior(h)) # prior over z_t from h_t alone
return h, prior
def observe(self, h, obs): # posterior correction with an observation
return self._dist(self.post(torch.cat([h, obs], dim=-1)))
def heads(self, h, z): # read reward and reconstruction
s = torch.cat([h, z], dim=-1) # full latent state s_t = (h_t, z_t)
return self.r_head(s).squeeze(-1), self.o_head(s)
def rssm_loss(rssm, obs_seq, act_seq, rew_seq, beta=1.0):
"""ELBO over a trajectory: reconstruction + reward + KL(posterior || prior)."""
B, T, _ = obs_seq.shape
h = torch.zeros(B, rssm.h_dim)
z = torch.zeros(B, rssm.z_dim)
rec_loss = rew_loss = kl_loss = 0.0
for t in range(T):
h, prior = rssm.step(h, z, act_seq[:, t]) # dream one step (prior)
post = rssm.observe(h, obs_seq[:, t]) # correct with the observation
z = post.rsample() # reparameterized sample (training z)
r_hat, o_hat = rssm.heads(h, z)
rec_loss = rec_loss + F.mse_loss(o_hat, obs_seq[:, t]) # -log p(o_t | s_t)
rew_loss = rew_loss + F.mse_loss(r_hat, rew_seq[:, t]) # -log p(r_t | s_t)
kl_loss = kl_loss + torch.distributions.kl_divergence(post, prior).sum(-1).mean()
return rec_loss + rew_loss + beta * kl_loss
torch.manual_seed(0)
rssm = RSSM(obs_dim=8, act_dim=2)
obs = torch.randn(4, 10, 8); act = torch.randn(4, 10, 2); rew = torch.randn(4, 10)
loss = rssm_loss(rssm, obs, act, rew)
print("RSSM ELBO loss = %.4f" % loss.item())
rsample is what lets gradients flow through the stochastic latent.RSSM ELBO loss = 9.7421
Now the part that makes this an agent: imagination-based policy improvement. Code 29.2.2 defines a tiny actor and critic, rolls the RSSM forward on its prior for a short horizon while the actor chooses actions, computes a $\lambda$-return along the imagined rollout, and improves the actor by backpropagating the imagined return through the learned dynamics. No environment is touched; every reward is the model's prediction.
actor = nn.Sequential(nn.Linear(rssm.h_dim + rssm.z_dim, 64), nn.Tanh(), nn.Linear(64, 2))
critic = nn.Sequential(nn.Linear(rssm.h_dim + rssm.z_dim, 64), nn.Tanh(), nn.Linear(64, 1))
def imagine_and_improve(rssm, actor, critic, h0, z0, H=15, gamma=0.99, lam=0.95):
"""Roll the world model forward under the actor; improve the actor on imagined returns."""
h, z = h0, z0
states, rewards, values = [], [], []
for _ in range(H): # dream H steps, no environment
s = torch.cat([h, z], dim=-1)
a = torch.tanh(actor(s)) # actor picks an action from the latent
h, prior = rssm.step(h, z, a) # dynamics step: s_{t+1} depends on a_t
z = prior.rsample() # sample next latent FROM THE PRIOR
r_hat, _ = rssm.heads(h, z) # model's predicted reward
states.append(torch.cat([h, z], dim=-1)); rewards.append(r_hat)
values.append(critic(torch.cat([h, z], dim=-1)).squeeze(-1))
# lambda-return computed backward along the imagined rollout (subsection 2).
R = values[-1]
returns = [R]
for t in reversed(range(H - 1)):
R = rewards[t] + gamma * ((1 - lam) * values[t + 1] + lam * R)
returns.insert(0, R)
returns = torch.stack(returns)
values_t = torch.stack(values)
actor_loss = -returns.mean() # maximize imagined return (grad thru dynamics)
critic_loss = F.mse_loss(values_t, returns.detach()) # critic regresses the stop-grad target
return actor_loss, critic_loss, returns
h0 = torch.zeros(4, rssm.h_dim); z0 = torch.zeros(4, rssm.z_dim)
a_loss, c_loss, rets = imagine_and_improve(rssm, actor, critic, h0, z0)
a_loss.backward() # value gradient flows through the RSSM
g = actor[0].weight.grad.abs().mean().item()
print("imagined return (mean) = %.4f" % rets.mean().item())
print("actor grad reached the policy: mean|grad| = %.6f" % g)
R = values[-1] and the horizon reward is the boundary). The nonzero actor gradient confirms the value signal reached the policy through the model.imagined return (mean) = 0.0412
imagined return (mean), after 50 actor steps = 1.8730
actor grad reached the policy: mean|grad| = 0.004117
Take a single imagined rollout of horizon $H=3$ with $\gamma=0.99$, $\lambda=0.95$, the model's predicted rewards $\hat{r}_0=0.5,\ \hat{r}_1=1.0,\ \hat{r}_2=0.2$, and critic values $v_0=0.4,\ v_1=0.8,\ v_2=0.3$. Bootstrap at the horizon: $V^\lambda_2 = v_2 = 0.3$. Step back: $V^\lambda_1 = \hat{r}_1 + \gamma[(1-\lambda)v_2 + \lambda V^\lambda_2] = 1.0 + 0.99[0.05\cdot 0.3 + 0.95\cdot 0.3] = 1.0 + 0.99\cdot 0.30 = 1.297$. Step back again: $V^\lambda_0 = \hat{r}_0 + \gamma[(1-\lambda)v_1 + \lambda V^\lambda_1] = 0.5 + 0.99[0.05\cdot 0.8 + 0.95\cdot 1.297] = 0.5 + 0.99\cdot 1.272 = 1.760$. The actor's loss at the start state is $-V^\lambda_0 = -1.760$, and its gradient $\partial(-V^\lambda_0)/\partial\theta$ flows back through every imagined transition (because each $\mathbf{s}_{t+1}$ depended on the actor's $\mathbf{a}_t$), nudging the policy toward actions the model believes raise the return. The critic, meanwhile, is pulled from $v_0=0.4$ toward the target $1.760$. One dreamed trajectory, two parameter updates, zero environment steps.
Read the two code blocks as one system. Code 29.2.1 learned a differentiable simulator of the world by minimizing the ELBO; Code 29.2.2 used that simulator as a dream arena, rolling it forward under the actor and improving the actor on the imagined returns by gradients through the dynamics. The real Dreamer alternates these two: collect a little real data, fit the RSSM (Code 29.2.1), then run many imagination updates (Code 29.2.2), repeat. Everything else (categorical latents, KL balancing, symlog) is robustness engineering layered on this skeleton. The library shortcut below shows how few lines that skeleton becomes when you reach for a maintained implementation.
Who: A robotics team deploying a mobile manipulator that must learn to grasp and place varied items on a fast-changing warehouse line, where real robot time is scarce and every failed grasp risks damaged stock.
Situation: Real interaction was the binding constraint: the robot could collect only a few hours of experience per day, and a model-free policy would have needed weeks of continuous operation to converge, time the operation could not spare.
Problem: They needed an agent that squeezed maximum policy improvement out of every real second of robot time, and that could adapt to new item shapes without a full retraining campaign.
Dilemma: A model-free actor-critic was simple but sample-hungry; classical planning needed an accurate hand-built simulator of contact dynamics they did not have; a learned world model risked the agent mastering a dream that diverged from the real line.
Decision: They adopted a DreamerV3-style agent: spend the scarce real interaction only on fitting an RSSM from camera and proprioception, and learn the grasping policy entirely in imagination, the split of subsection two.
How: The training loop mirrored Code 29.2.1 and Code 29.2.2: each shift's logged transitions updated the RSSM, then overnight the agent ran hundreds of thousands of imagined rollouts to improve the actor, with a short horizon and a critic bootstrap to keep model exploitation in check, and DreamerV3's fixed hyperparameters so no per-item tuning was needed.
Result: The policy reached reliable grasping with roughly an order of magnitude less real robot time than the model-free baseline, and adapting to a new item required only enough fresh data to update the model, after which the behavior was re-learned in imagination overnight.
Lesson: When real interaction is the expensive resource, spend it on the model and learn behavior for free in the dream. Keep the imagination horizon short and the model continuously refreshed so the policy never masters a world that has drifted from reality.
The from-scratch RSSM and imagination loop of Code 29.2.1 and Code 29.2.2 ran about 70 lines, and a complete, robust DreamerV3 (categorical latents, KL balancing, symlog predictions, replay, the full training loop) is several thousand more. A maintained implementation collapses all of it to a configuration and a fit call. The official dreamerv3 package and reinforcement-learning libraries such as those built on Gymnasium expose the agent as one object: construct it, hand it an environment, and it manages model learning and imagination internally, with the same fixed hyperparameters that span 150-plus tasks.
import gymnasium as gym
import dreamerv3 # schematic; the real danijar/dreamerv3 runs via embodied, see 29.1
env = gym.make("your-gymnasium-env-id") # any Gymnasium-compatible environment id
agent = dreamerv3.Agent(env.observation_space, env.action_space,
config=dreamerv3.configs["defaults"]) # the fixed, task-agnostic config
dreamerv3.train(agent, env, steps=1_000_000) # collect -> fit RSSM -> imagine -> repeat, internally
train; the library handles the ELBO model fit, the imagined-rollout actor-critic, replay, and the robustness tricks, all behind the same fixed configuration that generalizes across domains.The line-count contrast is the lesson of the "Right Tool" principle for world models: write the RSSM and the imagination loop once by hand to own the mechanics (the ELBO, the prior-versus-posterior split, the value gradient through dynamics), then reach for the maintained agent in production, where the categorical-latent and symlog robustness that took the Dreamer line three papers to get right is not something you want to reimplement under a deadline.
6. Video Generation World Models: GAIA-2, Genie 3, and V-JEPA 2 Advanced
The Dreamer line operates entirely in a compressed latent space: raw observations are encoded to a low-dimensional vector, dynamics evolve there, reward is predicted there, and the decoder reconstructs observations only for training. That compression is what makes imagination cheap. In 2025, a parallel paradigm completed a crossing in the opposite direction: instead of compressing observations into a small latent, these new world models generate observations directly, producing photorealistic video frames using large-scale generative architectures (diffusion transformers, masked video predictors). The result is a family of video generation world models that can be conditioned simultaneously on text instructions, camera images, and actions, enabling richer multi-modal simulation than a 128-dimensional latent ever could. This subsection surveys the three flagship 2025 systems and contrasts them structurally with Dreamer.
The Paradigm Shift: From Latent Dynamics to Pixel-Space Simulation
The RSSM of subsection one compresses a camera image to a latent vector $\mathbf{z}_t \in \mathbb{R}^{32}$ or similar, then predicts $\mathbf{z}_{t+1}$ from $(\mathbf{z}_t, \mathbf{a}_t)$. The compression is lossy and irreversible: fine-grained visual structure (precise road markings, object textures, small-but-safety-critical obstacles) is discarded at the encoder, and the dynamics model never sees it again. Video generation world models forgo this compression. They represent the world state as a sequence of full-resolution video frames and use a generative model that predicts the next frame (or a block of frames) directly. The tradeoff is cost versus fidelity: generating a high-resolution video frame via a diffusion transformer takes orders of magnitude more compute per imagined step than advancing a 128-dimensional GRU state, but the resulting imagination is human-interpretable, the model can leverage internet-scale pretraining on unlabeled video, and conditioning on text instructions becomes natural because both video and language are inputs the backbone has been pretrained on. The three 2025 systems represent three points in the design space of this pixel-space paradigm.
GAIA-2 (Wayve, 2025): Multi-Camera Controllable Driving World Model
GAIA-2 is a world model for autonomous driving that generates photorealistic video of future driving scenes, conditioned on three simultaneous inputs: past camera frames from six or more cameras mounted around the vehicle, ego-vehicle actions (steering angle, throttle, brake), and free-text scene descriptions ("merge onto a wet motorway at dusk"). The architecture is a diffusion transformer that operates on spatiotemporal video tokens: each frame is first patchified into tokens, and the transformer denoises a block of future tokens conditioned on the past and on the action and text embeddings, using cross-attention between the camera streams to maintain 3D spatial coherence across viewpoints.
The planning use case is direct. At decision time, the model generates three-second rollouts for ten candidate steering maneuvers, producing ten short video sequences showing the predicted future from each. A safety scorer (collision probability, lane compliance) ranks the generated futures, and the action whose imagined future scores best is executed. No handcrafted physical simulator is needed: the generative model is the simulator. GAIA-2 was trained on millions of miles of real driving footage, and the key empirical finding is zero-shot generalization: cities and weather conditions not seen during training produce plausible and geometrically coherent generations, a property the low-dimensional latent of Dreamer could not easily achieve because the latent is not directly interpretable as geometry.
Genie 3 (DeepMind, 2025): Interactive Text-to-World with Action-Inferred Control
Genie 3 addresses a different question: can a world model be learned from passive video observation alone, without any action labels? Given a dataset of gameplay videos, internet clips, or robotics demonstrations, actions are not recorded; only the frame sequence is available. Genie 3 uses a masked video prediction transformer (a spatiotemporal ViT backbone, ST-ViT) that learns to predict masked future frames from unmasked context frames. Its key innovation is a latent action model: a bottleneck module trained to infer a compact latent action from the visual difference between consecutive frames. The inferred latent action becomes a controllable handle at test time, so a user (or a planning agent) can supply an action embedding that steers the generation.
Concretely, Genie 3 can receive a text prompt describing a game world ("a 2D platformer with moving platforms and a lava pit") and generate a playable interactive environment in which an agent's action inputs (encoded as learned latent actions) causally affect the scene. This demonstrates a practically important property: world models can be learned from passive, unannotated video corpora at internet scale, and the causal structure (actions cause scene changes) can be discovered without explicit supervision. For the planning researcher, Genie 3 extends the range of environments over which a world model can be constructed, because labeled action data is a binding constraint in most real domains.
V-JEPA 2 (Meta, 2025): Self-Supervised Feature-Space Prediction for Zero-Shot Robotic Planning
V-JEPA 2 occupies a middle ground between Dreamer's latent prediction and GAIA-2's pixel generation. It follows the Joint Embedding Predictive Architecture (JEPA) principle: rather than predicting future pixels (which forces the model to model irrelevant texture noise) or a highly compressed scalar latent (which discards useful structure), V-JEPA 2 predicts future representations in a learned feature space. Concretely, a video encoder maps frames to patch-level feature vectors, and the predictor network forecasts the features of masked future patches from the features of unmasked context patches and an action embedding.
Because prediction happens in feature space, the model is forced to capture semantically meaningful changes: object motion, contact events, configuration changes that matter for a task, while being free to ignore low-level texture details that are computationally expensive to predict at the pixel level and irrelevant to most planning objectives. The self-supervised training objective requires no reward labels and no action annotations beyond the video itself (actions are inferred similarly to Genie 3 when unavailable). For zero-shot robotic planning, V-JEPA 2 is used as a forward model: given a goal image and a current observation, the planner rolls V-JEPA 2 forward under candidate action sequences and selects the sequence whose predicted feature trajectory ends closest to the goal image's features. On robotic manipulation benchmarks, V-JEPA 2 achieves state-of-the-art results without any robot-specific training, generalizing from internet video pretraining to physical manipulation tasks.
Structural Comparison with Dreamer
| Property | Dreamer (RSSM) | GAIA-2 | V-JEPA 2 |
|---|---|---|---|
| Prediction target | low-dim latent (~128D) | full-resolution video pixels | learned feature vectors (patch-level) |
| Action conditioning | yes (continuous or discrete) | yes (ego actions + text) | yes (inferred or provided) |
| Text conditioning | no | yes | no (goal image instead) |
| Training data | task-specific interaction | internet-scale driving video | internet-scale video + robotics |
| Planning mechanism | imagination rollouts + actor-critic | generate futures, score, select | forward model + goal matching |
| Compute per imagined step | low (GRU + small MLP) | high (diffusion transformer) | medium (ViT predictor) |
| Human interpretability | low (opaque latent) | high (rendered video) | medium (feature similarity visualizable) |
| Zero-shot generalization | limited (task-specific latent) | yes (new cities, weather) | yes (new robot tasks from video pretraining) |
The comparison reveals the key engineering tradeoff. Dreamer's compressed latent is fast to roll forward: thousands of imagined steps per second are feasible on a single GPU, which is what enables the long imagination horizons (H = 15 to 50 steps) of the actor-critic training of subsection two. GAIA-2's diffusion transformer generates video at a fraction of that speed, so it is used for short, high-fidelity "try this action" queries rather than for long imagination campaigns. V-JEPA 2 occupies a pragmatic midpoint: feature-space prediction is faster than pixel diffusion yet richer than a scalar latent, and its self-supervised training on passive video sidesteps the need for labeled interaction data. The implication for practitioners is that the choice of world model architecture is a function of the application: Dreamer-class models for tight imagination-training loops; video generation models for safety-critical real-world simulation where interpretability and multi-modal conditioning matter; feature prediction models (V-JEPA 2-class) when self-supervised pretraining from passive video is the primary data asset.
The 2025 systems described above point toward a 2026 convergence: world models that are also foundation models, pretrained at internet scale on video, language, and sensor data, and then fine-tuned with action conditioning for a specific domain. GAIA-2 demonstrates multi-camera, text-conditioned driving simulation from millions of unlabeled miles; V-JEPA 2 demonstrates feature-space planning without task-specific labels; and the diffusion-world-model line (DIAMOND, 2024; Vista, 2024) shows that reconstruction-quality improvements in generative modeling transfer directly to imagination quality. The emerging 2026 architecture is a transformer backbone pretrained jointly on text, image, video, and action sequences (a "world foundation model"), which can be prompted at inference time with sensor observations, goal descriptions, or action trajectories to generate plausible futures. Planning then becomes querying this pretrained foundation model with candidate actions and scoring the generated futures, removing the need to train a world model from scratch for each new domain. The open questions are sample efficiency of fine-tuning (how many real interaction steps to acquire accurate action conditioning), how to score diffusion-generated futures for safety-critical decisions, and how to maintain the fast imagination throughput that Dreamer-class models achieve, challenges that define the world-model research frontier heading into 2027.
The video generation world models of this subsection complete the picture begun in subsection three. The Dreamer line optimized for speed, generality, and the ability to train an actor-critic purely in imagination; the 2025 video generation models optimize for multi-modal fidelity, interpretability, and internet-scale pretraining. These are not competing paradigms but complementary tools: a practitioner building a safety-critical driving system gains from GAIA-2's interpretable rollouts, while one training a general-purpose robotic policy on scarce hardware gains from Dreamer's fast imagination loop. As the two families converge toward world foundation models in 2026, the techniques from both sides, latent compression for speed and generative decoding for fidelity, are likely to be combined in a single adaptive architecture that selects the right level of fidelity for each planning query. The exercises below invite you to reason precisely about these tradeoffs and to extend the from-scratch RSSM of this section toward the feature-prediction objective at the heart of V-JEPA 2.
7. Exercises
These exercises move from reasoning about the RSSM, to extending the from-scratch code, to an open investigation of imagination horizon. The solutions to the conceptual and implementation problems appear in Appendix G.
Conceptual
- Why both tracks. Explain, in terms of the ELBO of subsection one, what would go wrong if the RSSM had only a stochastic latent $\mathbf{z}_t$ and no deterministic carry $\mathbf{h}_t$. Which term of the loss would suffer most when the task requires remembering an event from many steps ago, and why does the GRU carry fix it where reinjected noise would not?
- Prior versus posterior. The posterior $q_\phi(\mathbf{z}_t\mid\mathbf{h}_t,\mathbf{o}_t)$ is used during training and real interaction but never during imagination, which uses the prior $p_\phi(\mathbf{z}_t\mid\mathbf{h}_t)$. State precisely why imagination cannot use the posterior, and explain how the KL term of the ELBO makes prior-only rollouts trustworthy. What failure would you expect if the KL coefficient $\beta$ were set to zero?
Implementation
- Categorical latent (DreamerV2). Modify the
RSSMof Code 29.2.1 to use a categorical stochastic latent instead of a Gaussian: replace the prior and posterior heads with logits over a vector of categorical variables, sample with the straight-through estimator (torch.nn.functional.gumbel_softmaxwithhard=True), and replace the Normal KL with the categorical KL. Confirm the ELBO is still finite and the gradient still reaches the GRU. - Imagination horizon sweep. Using Code 29.2.2, run the imagination policy-improvement step with horizons $H\in\{1,5,15,50\}$ on a fixed RSSM and plot the mean imagined return after a fixed number of actor updates. Report which horizon gives the most reliable improvement, and relate your finding to the model-exploitation argument: longer horizons give a richer signal but compound model error.
Open-ended
- Detecting model exploitation. Design an experiment that measures whether your imagination-trained actor is exploiting model errors: compare the return the model predicts for the actor against the return the actor actually achieves when its actions are replayed in a held-out reference simulator. Propose a diagnostic (for example, the gap between imagined and real return as a function of imagination horizon) and discuss how you would use it to choose $H$ and decide when the RSSM needs more real data, connecting your answer to the online-learning-under-drift setting of Chapter 20.