Dreamer: Actor–Critic in Latent Imagination
Recurrent state-space models, imagined rollouts and DreamerV3’s robustness tricks.
Dreamer learns to act almost entirely inside its own model. That needs three things to go right at once: a latent model whose imagined states match what its filter infers from real data, an actor gradient that survives a 15-step trip through that model, and losses whose scales need no retuning for each new game. This lesson derives the recurrent state-space model's objective as an evidence lower bound, compares pathwise and REINFORCE actor gradients, proves what KL balancing and free bits do to the gradient, and dissects the transformations that let DreamerV3 run one configuration across more than 150 tasks.
What you’ll learn
- Write the RSSM and derive its training loss as an evidence lower bound on the action-conditioned likelihood of observation sequences.
- Derive the pathwise and score-function (REINFORCE) actor gradients, compute their variances in a Gaussian example, and explain why model-based actors use each.
- Prove the gradient decomposition behind KL balancing, and explain free bits and categorical latents with straight-through gradients.
- Analyze DreamerV3's symlog transform, two-hot regression and percentile return normalization, and state what its ablations and scaling results do and do not show.
The RSSM and its evidence lower bound
PlaNet (Hafner et al., 2019) introduced the recurrent state-space model (RSSM) that every Dreamer version builds on. Its state has two parts: a deterministic vector carried by a recurrent network (a GRU), which can remember reliably, and a stochastic vector , which can represent uncertainty about what comes next. PlaNet explains the split, and its ablations support it. A purely deterministic model cannot represent several possible futures and, in the paper's words, makes it easy for the planner to exploit inaccuracies; a purely stochastic one finds it hard to carry information over many steps.
Treat rewards and continuation flags as further observations and focus on . Given the actions, the model's likelihood integrates over latent paths; is a deterministic function of and :
Multiply and divide by the filtering distribution , which conditions only on the past and present, and apply Jensen's inequality to the concave logarithm:
Take the expectation over each conditional on the earlier latents. The last two terms become a KL divergence between filter and transition at every step:
The first sum is reconstruction, the second complexity (PlaNet's equation 3). The gap in the bound is the KL divergence from to the model's exact posterior over latent paths, which also conditions on future observations, so a filtering leaves a gap in general. It is used anyway because it is what the agent can compute online while acting.
For control, the complexity term matters more than its name suggests. It is the only loss that trains the prior, and the prior is all that imagination has. If the prior cannot predict what the filter will infer, imagined trajectories drift away from the states the actor will meet in reality, however good the reconstructions are. PlaNet also proposed latent overshooting, which trains multi-step prior predictions; its final RSSM agent did not need it, and Dreamer did not use it.
Two ways to push the actor
Behavior learning holds the world model fixed. From each filtered state the actor imagines steps, the critic is regressed onto λ-returns with stopped gradients, and the actor is updated to raise . Every term of depends on through the imagined actions and states, and there are two classical ways to differentiate such an expectation.
Take the simplest case: one Gaussian action , a return , and the objective . The score-function (REINFORCE) estimator differentiates the density; the pathwise (reparameterization) estimator writes with and differentiates . Both are unbiased:
Let , so . The pathwise estimate equals 1 for every sample. The score-function estimate is ; with and :
A baseline helps but cannot close the gap: with the ideal baseline the estimator still has variance 2. In an actor–critic the critic plays the baseline's role: the advantage multiplies .
Pathwise gradients need , and in imagination is the derivative of the learned model's rewards and transitions, chained through up to steps. A model can predict values well and still have wrong or exploding derivatives, and a pathwise actor follows them: low variance is bought with a bias toward the model's errors. REINFORCE uses only the values of returns, so it is unbiased with respect to the model's predictions, but noisy.
For with , and no baseline, what is the variance of a single-sample score-function estimate of ?
Show the answer
11
: the estimate's standard deviation is about 3.3 times the gradient it estimates, while the pathwise estimate is exact. Subtracting the baseline brings the variance down to 2.
The Dreamer versions chose differently. Dreamer backpropagated through reparameterized actions and latent states, with straight-through gradients for discrete actions. DreamerV2 mixed the two estimators with a weight and found REINFORCE substantially better on Atari (, entropy weight ) and backpropagation through the dynamics substantially better for continuous control (, ). DreamerV3's preprint kept that split; its published version uses REINFORCE for both discrete and continuous actions.
Categorical latents, KL balancing and free bits
DreamerV2 replaced the Gaussian with 32 categorical variables of 32 classes each, so a sample is a sparse binary vector of length 1,024 with 32 ones. Sampling a category is not differentiable, so gradients pass by the straight-through estimator: the one-hot sample is used in the forward pass and the gradient of the probabilities in the backward pass.
import torch
import torch.nn.functional as F
def sample_latent(logits, unimix=0.01):
"""logits: (..., 32, 32). One-hot samples with straight-through gradients."""
probs = F.softmax(logits, dim=-1)
probs = (1 - unimix) * probs + unimix / probs.shape[-1] # DreamerV3: 1% uniform mixture
idx = torch.distributions.Categorical(probs=probs).sample()
onehot = F.one_hot(idx, probs.shape[-1]).to(probs.dtype)
return onehot + probs - probs.detach() # value: the one-hot; gradient: that of probsDreamerV2's straight-through trick (its Algorithm 1) with DreamerV3's "unimix": mixing in 1% of a uniform distribution keeps every class's probability at least , so log-probabilities and KL divergences cannot blow up.
Categorical latents beat Gaussian ones on 42 of 55 Atari games in DreamerV2's ablation (worse on 8, tied on 5). The authors offered hypotheses rather than an explanation: a mixture of categoricals is again categorical, so the prior can match the aggregate posterior; sparsity may help generalization; straight-through gradients may be easier to optimize; and discrete latents may suit discrete events such as entering a new room. Which of these matters is still unsettled. The KL term changed too.
Write and evaluate at . By the multivariable chain rule the total derivative is the sum of the two partial derivatives:
A stop-gradient freezes one argument: has value and gradient , and has value and gradient . Mixing them with weights and gives value and gradient .
The two parts do different jobs. The prior part moves the prior toward the posterior: better predictions. The posterior part moves the posterior toward the prior, which can lower the KL by throwing information away. DreamerV2 used , so the prior learns four times faster than the posterior is regularized; KL balancing beat the plain KL on 44 of 55 games (worse on 6, tied on 5).
Above the free-bits threshold, DreamerV3's published weights and act like KL balancing with which , after rescaling the total?
Show the answer
0.909
: the prior is trained ten times harder than the posterior is regularized. The preprint's 0.5 and 0.1 give , close to DreamerV2's 0.8.
DreamerV3: transformations instead of tuning
Fixed hyperparameters fail across domains mostly through scales: rewards of 0.01 in one task and 10,000 in another, observation vectors with large entries, returns that are sparse here and dense there. DreamerV3 handles each scale problem with a transformation rather than a constant tuned per domain.
Symlog. Predict a transformed target and invert the transformation when reading the prediction out:
Near zero, , so and small targets are almost unchanged. For large it grows like , and its derivative shrinks the gradients of huge targets: a squared error on symlog targets turns a miss of into a loss of about instead of . DreamerV3 symlogs vector observations at the encoder's input and as the decoder's targets.
Two-hot regression. For rewards and values the network outputs a softmax over fixed bins , exponentially spaced ( of equally spaced points in ), and predicts . This is the published version; the preprint applied the same construction to the symlog of the target, with equally spaced bins, and read out . A target with is encoded as weights on its two neighboring bins:
So the two-hot vector's mean is exactly the target, and the loss is the cross-entropy . Its gradient with respect to the logits is , every entry between and whatever the size of : the scale of the gradient no longer depends on the scale of the target. The predicted distribution can also be bimodal, which suits sparse rewards whose returns are often either zero or large.
The floor is the point. With dense rewards the returns might span 100 to 900; dividing by brings advantages to order one, where is a gentle exploration bonus. With sparse rewards the returns might all lie between 0 and 0.05; dividing by would multiply the noise in those near-zero returns by twenty and drown the entropy term, making the policy deterministic before it has found any reward. With the floor they are left unscaled, and the entropy bonus keeps the policy exploring. Percentiles rather than the minimum and maximum keep a few unusually easy episodes from shrinking everyone else's advantages.
| DreamerV3 component | Problem it addresses |
|---|---|
| Symlog inputs and decoder targets | Large vector observations and reconstruction gradients |
| Two-hot reward and critic | Reward and return scales that vary by orders of magnitude; multimodal returns |
| KL balancing with free bits | Latents too informative to predict, or too predictable to inform |
| Unimix categoricals (1% uniform) | KL spikes from near-deterministic distributions |
| Return normalization floored at 1 | Exploring under sparse rewards without hurting dense ones |
| Critic regularized toward its own moving average; zero-initialized output weights | Unstable bootstrapped targets; spurious large predictions early in training |
What the evidence shows
With these changes DreamerV3 ran one configuration across 8 domains (Atari, ProcGen, DMLab, Atari 100k, continuous control from proprioception and from pixels, BSuite and Minecraft), and its authors report that it outperformed specialized, tuned methods across more than 150 tasks. Three further findings matter for the field.
- Scaling. Six model sizes from 12M to 400M parameters trained robustly with the same hyperparameters. Larger models reached higher scores and needed fewer environment interactions, and higher replay ratios predictably improved performance.
- The world model does most of the work. Stopping the task-specific reward and value gradients from shaping the representation mattered less than stopping the reconstruction gradients; in the authors' words, Dreamer "rests predominantly on the unsupervised objective of its world model". DreamerV2's ablation had pointed the same way: blocking image gradients hurt 51 of 55 Atari games.
- Minecraft. Diamonds from scratch with one GPU for 9 days, where VPT, which also used human demonstrations, trained on 720 GPUs for 9 days; with faster block breaking, as noted in the Bootstrapping lesson.
Key takeaways
- The RSSM splits the state into a deterministic memory and a stochastic . Its loss is a sequence ELBO, reconstruction minus a per-step KL between filter and prior, and that KL is the only signal that trains the prior used in imagination.
- Pathwise actor gradients have low variance but follow the learned model's derivatives; REINFORCE with a critic baseline is unbiased with respect to the model but noisy (variance against 0 in the Gaussian example). DreamerV2 chose per domain; published DreamerV3 uses REINFORCE throughout.
- KL balancing is the chain rule made explicit: the KL's gradient is a prior part plus a posterior part, which DreamerV2 weights 0.8 and 0.2; free bits switch both off below 1 nat.
- DreamerV3 removes scale sensitivity with transformations instead of tuned constants: symlog targets, two-hot classification whose gradient is bounded whatever the target, and return normalization by a percentile range floored at 1.
- The evidence: one configuration across more than 150 tasks, gains from larger models and higher replay ratios, a world-model objective that carries most of the learning, and diamonds in a modified Minecraft. Why categorical latents help, and any theory for the whole system, remain open.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
DreamerV2 uses KL balancing with . What does the larger weight do?
- It regularizes the posterior four times harder than it trains the prior
- It changes the value of the KL loss reported during training
- It trains the prior toward the posterior four times faster than it pulls the posterior toward the prior
- It increases the number of classes per latent variable
Show the answer
C. It trains the prior toward the posterior four times faster than it pulls the posterior toward the prior
The balanced loss has the value of the plain KL but the gradient . Training the prior harder favors better predictions over discarding information from the posterior, and it beat the plain KL on 44 of 55 Atari games.
What does clipping DreamerV3's KL losses below 1 nat (free bits) accomplish?
- Once the posterior is within 1 nat of the prior, the KL terms pass no gradient, so the model stops trading information about its input for predictability
- It guarantees that the prior matches the posterior exactly
- It caps the reconstruction loss
- It makes the KL divergence symmetric
Show the answer
A. Once the posterior is within 1 nat of the prior, the KL terms pass no gradient, so the model stops trading information about its input for predictability
is constant below 1 nat, so its gradient vanishes there and only the prediction loss shapes the latents. That prevents the degenerate solution in which latents are easy to predict because they say little about the observations.
In a sparse-reward task, every imagined λ-return in a batch lies between 0 and 0.05. What does DreamerV3's return normalization do to the advantages?
- Divides them by about 0.05, multiplying them by twenty
- Sets them to zero until a reward is found
- Divides them by their standard deviation
- Leaves them unscaled, because , so the fixed entropy bonus keeps the policy exploring
Show the answer
D. Leaves them unscaled, because , so the fixed entropy bonus keeps the policy exploring
The divisor is with the smoothed 5th-to-95th-percentile range. Small returns are never scaled up, which would amplify their noise and drown the entropy term; large ones are scaled down to order one.
A world model predicts returns accurately along the data, but its derivatives with respect to actions are badly wrong. Which actor update is directly affected?
- REINFORCE with a critic baseline
- The pathwise update that backpropagates the λ-return through the model
- Neither, since both use only predicted returns
- Both equally
Show the answer
B. The pathwise update that backpropagates the λ-return through the model
The pathwise gradient is built from the model's derivatives, chained through the imagined trajectory, so wrong derivatives give wrong updates even when the values are right. REINFORCE multiplies the score of the sampled action by a return, using values only.
Further reading
- D. Hafner, T. Lillicrap, I. Fischer, R. Villegas, D. Ha, H. Lee & J. Davidson, "Learning latent dynamics for planning from pixels," ICML (2019).
- D. Hafner, T. Lillicrap, J. Ba & M. Norouzi, "Dream to control: learning behaviors by latent imagination," ICLR (2020).
- D. Hafner, T. Lillicrap, M. Norouzi & J. Ba, "Mastering Atari with discrete world models," ICLR (2021).
- D. Hafner, J. Pasukonis, J. Ba & T. Lillicrap, "Mastering diverse control tasks through world models," Nature 640, 647–653 (2025); preprint "Mastering diverse domains through world models," arXiv:2301.04104 (2023).
- S. Mohamed, M. Rosca, M. Figurnov & A. Mnih, "Monte Carlo gradient estimation in machine learning," Journal of Machine Learning Research 21 (2020).