Search

Search papers and lessons

Dream to Control: Learning Behaviors by Latent Imagination (Dreamer)

Danijar Hafner, Timothy Lillicrap, Jimmy Ba et al. · 2019

Dreamer learns a world model from pixels, then trains an actor and a critic entirely on imagined latent rollouts, backpropagating value gradients through the learned dynamics.

On this page

  • Colour = topic mix
  • Probability
  • Calculus
  • Reinforcement learning
  • Linear algebra
  • Neural network basics
  • Discrete math
  • Sign in to see your progress

TL;DR

Dreamer is a reinforcement learning agent that learns from images. It first learns a compact latent world model from past experience, then trains its action model and its value model only on trajectories it imagines inside that latent space. The value estimates are differentiable, so the policy improves by pushing gradients back through the imagined dynamics.

On 20 visual control tasks it reached an average score of 823 after 5 million environment steps, above the 786 that the strong model-free D4PG agent reached after 100 million.

Where you'll see it: in model-based control from pixels, where real trials are slow or costly.

The problem

By 2019 there were two main ways for an agent to learn from images. Model-free actor-critic agents such as D4PG learned a policy directly from real experience. They were stable and strong, but they needed huge amounts of data: D4PG ran for about 10810^8 environment steps to reach its score. Model-based agents such as PlaNet learned a world model and then planned with it at decision time. PlaNet was far more data-efficient, but planning was expensive, and its plans were only as far-sighted as the fixed imagination horizon it searched over.

The paper asks for both properties at once: data efficiency from a learned model, and long-horizon behaviour without re-planning at every step. The authors observe that the model already makes predictions in a differentiable latent space, so the value of a trajectory can be differentiated with respect to the actions that produced it. Nothing in the model forces the agent to search for actions one at a time.

Key idea

Dreamer separates three jobs and runs them in a loop.

  1. Learn the world model. Encode each image into a compact latent state, predict the next latent from the previous one and the action, and predict the reward.
  2. Imagine. From states taken from real experience, roll the latent dynamics forward for a fixed horizon HH, sampling actions from the current policy. No images are generated and no environment is touched.
  3. Learn behaviour in imagination. Estimate the value of each imagined state with a learned critic that looks past the horizon, then update the actor to raise those values by differentiating through the imagined rollout.

The agent then acts in the real environment with its current policy, adds the new experience to the dataset, and repeats.

flowchart LR
  D[Dataset of real episodes] --> W[Learn latent world model]
  W --> I[Imagine H steps in latent space]
  I --> V[Critic estimates value beyond horizon]
  V --> A[Actor follows gradients through imagined rollout]
  A --> E[Act in real environment]
  E --> D

The central move is in the third box. Earlier model-based methods either planned at decision time or used the model only to create training data for a model-free learner. Dreamer does neither: the gradient of the value with respect to the policy flows through the learned dynamics. This is the same idea that a reparameterised actor-critic uses, but the "environment" that the gradient passes through is a network the agent learned itself. See Actor-Critic Methods and Model-Based Reinforcement Learning for the two pieces it combines.

The method

The environment and the latent model

The paper treats visual control as a partially observed decision problem. At each step tt the agent receives an image oto_t, chooses a continuous action ata_t, and receives a scalar reward rtr_t. The rewards are the only learning signal. The state is hidden, so the agent must infer it from the history of observations, which is the setting of a Partially Observable Markov Decision Process.

The latent model has three parts. Let sts_t be a latent state, a vector that summarises the history.

  • Representation model: pθ(st∣st−1,at−1,ot)p_\theta(s_t \mid s_{t-1}, a_{t-1}, o_t), which encodes the new image into the state.
  • Transition model: qθ(st∣st−1,at−1)q_\theta(s_t \mid s_{t-1}, a_{t-1}), which predicts the next state without seeing the image.
  • Reward model: qθ(rt∣st)q_\theta(r_t \mid s_t).

The transition model is what makes imagination possible: it moves the latent forward without any observation. The paper calls the representation and transition models together a recurrent state space model (RSSM), introduced in PlaNet (PlaNet). Its latent states are 30-dimensional diagonal Gaussians.

Training uses an evidence lower bound, the same bound behind the Variational Autoencoder. The terms are an image reconstruction log-likelihood, a reward log-likelihood, and a KL term that keeps the representation close to the transition prediction:

JREC≐Ep(∑t(ln⁡q(ot∣st)+ln⁡q(rt∣st)−β KL(p(st∣st−1,at−1,ot) ∥ q(st∣st−1,at−1))))+const\mathcal{J}_{\mathrm{REC}} \doteq \mathbb{E}_p\Big(\sum_t \big(\ln q(o_t \mid s_t) + \ln q(r_t \mid s_t) - \beta\,\mathrm{KL}(p(s_t \mid s_{t-1}, a_{t-1}, o_t) \,\|\, q(s_t \mid s_{t-1}, a_{t-1}))\big)\Big) + \text{const}

Here β=1\beta = 1 in the reported experiments, and the KL is clipped below 3 nats, following PlaNet. The KL term is the same divergence as in Kullback–Leibler Divergence, and the bound itself is a Variational Lower Bound (ELBO) on the data likelihood.

Pixel reconstruction is one of three representation objectives the paper compares. The others replace the observation term with a contrastive estimate or drop images entirely in favour of reward prediction. Section 6 covers the comparison.

Imagination and the value targets

Imagined trajectories start at latent states sts_t taken from sequences in the dataset. From there the agent rolls forward H=15H=15 steps using the transition model, the reward model and the action model. Reward is discounted by γ=0.99\gamma = 0.99.

The value of an imagined state is estimated by mixing several horizons. Let vψv_\psi be the learned value network. The kk-step estimate is

VNk(sτ)=E(∑n=τh−1γn−τrn+γh−τvψ(sh)),h=min⁡(τ+k,t+H).V_N^k(s_\tau) = \mathbb{E}\Big(\sum_{n=\tau}^{h-1} \gamma^{n-\tau} r_n + \gamma^{h-\tau} v_\psi(s_h)\Big), \qquad h = \min(\tau + k, t + H).

Short kk leans on rewards from the rollout and has low variance. Long kk leans on the critic and has higher bias when the critic is wrong. The paper's target is an exponentially weighted average of these, controlled by λ\lambda:

Vλ(sτ)=(1−λ)∑n=1H−1λn−1VNn(sτ)+λH−1VNH(sτ).V_\lambda(s_\tau) = (1-\lambda)\sum_{n=1}^{H-1} \lambda^{n-1} V_N^n(s_\tau) + \lambda^{H-1} V_N^H(s_\tau).

The paper uses λ=0.95\lambda = 0.95. This is the same bias-variance trade that Generalized Advantage Estimation (GAE) makes for advantages, applied here to values of imagined states. The underlying one-step bootstrapping is the Temporal-Difference Learning idea.

Worked example: the VλV_\lambda target

Take a toy case with H=3H = 3, γ=0.9\gamma = 0.9, λ=0.5\lambda = 0.5 (illustrative values, not the paper's). Imagined rewards are r0=1r_0 = 1, r1=0r_1 = 0, r2=2r_2 = 2, and the critic outputs v(s1)=10v(s_1) = 10, v(s2)=5v(s_2) = 5, v(s3)=4v(s_3) = 4.

  1. V1=r0+γ v(s1)=1+0.9⋅10=10V^1 = r_0 + \gamma\, v(s_1) = 1 + 0.9 \cdot 10 = 10.
  2. V2=r0+γ r1+γ2 v(s2)=1+0+0.81⋅5=5.05V^2 = r_0 + \gamma\, r_1 + \gamma^2\, v(s_2) = 1 + 0 + 0.81 \cdot 5 = 5.05.
  3. V3=r0+γ r1+γ2 r2+γ3 v(s3)=1+0+1.62+0.729⋅4=5.536V^3 = r_0 + \gamma\, r_1 + \gamma^2\, r_2 + \gamma^3\, v(s_3) = 1 + 0 + 1.62 + 0.729 \cdot 4 = 5.536.
  4. With H=3H = 3 the formula has two short terms and one long term: Vλ=(1−λ) [V1+λV2]+λ2V3V_\lambda = (1-\lambda)\,[V^1 + \lambda V^2] + \lambda^2 V^3.
  5. Substitute: 0.5⋅[10+0.5⋅5.05]+0.25⋅5.536=0.5⋅12.525+1.384=6.2625+1.384=7.64650.5 \cdot [10 + 0.5 \cdot 5.05] + 0.25 \cdot 5.536 = 0.5 \cdot 12.525 + 1.384 = 6.2625 + 1.384 = 7.6465.

The weights (1−λ)(1+λ)+λ2=1(1-\lambda)(1+\lambda) + \lambda^2 = 1 always sum to one, so VλV_\lambda is a proper average. Its value, 7.657.65, sits between the one-step target 1010 and the three-step target 5.545.54. Lowering λ\lambda would pull it toward V1V^1, and raising it toward the longer rollout.

Actor and critic

The critic vψv_\psi is trained to regress the target, with the target held fixed:

min⁡ψE(∑τ=tt+H12∥vψ(sτ)−sg(Vλ(sτ))∥2).\min_\psi \mathbb{E}\Big(\sum_{\tau=t}^{t+H} \tfrac{1}{2}\big\|v_\psi(s_\tau) - \mathrm{sg}(V_\lambda(s_\tau))\big\|^2\Big).

The actor qϕq_\phi is trained to maximise the same targets:

max⁡ϕE(∑τ=tt+HVλ(sτ)).\max_\phi \mathbb{E}\Big(\sum_{\tau=t}^{t+H} V_\lambda(s_\tau)\Big).

The actor's samples must be differentiable with respect to ϕ\phi. Dreamer uses the reparameterisation trick (Reparameterization Trick): the action is a deterministic function of a noise draw,

aτ=tanh⁡(μϕ(sτ)+σϕ(sτ) ϵ),ϵ∼N(0,I).a_\tau = \tanh\big(\mu_\phi(s_\tau) + \sigma_\phi(s_\tau)\,\epsilon\big), \qquad \epsilon \sim \mathcal{N}(0, I).

Because every step of the imagined rollout is a neural network, ∇ϕ\nabla_\phi of the value flows through the actions, the states, the rewards and the critic. The world model is frozen during this phase. The paper contrasts this with REINFORCE-style methods such as A3C and PPO, which use a value baseline but no gradients through the dynamics, and with DDPG and SAC, which differentiate a learned one-step action-value rather than a multi-step return through a model.

Hyperparameters that matter

Appendix A reports the same settings for every continuous-control task, which is part of the claim. The main ones:

  • Latent state: 30-dimensional diagonal Gaussians. Encoder and decoder are the convolutional networks from Ha and Schmidhuber's World Models; all other functions are three dense layers of 300 units with ELU activations.
  • Optimiser: Adam with learning rates 6×10−46 \times 10^{-4} for the world model and 8×10−58 \times 10^{-5} for the actor and the critic. Gradient norms above 100 are scaled down.
  • Batches: 50 sequences of length 50.
  • Exploration: after 5 random seed episodes, the agent alternates 100 training steps with one episode of collection, acting with the predicted mode plus N(0,0.3)\mathcal{N}(0, 0.3) noise.
  • Action repeat: fixed at 2 for every environment, so the agent chooses an action every second environment step.

Results

All continuous results use the DeepMind Control Suite with 64×64×364 \times 64 \times 3 image observations: 20 tasks, episodes of 1000 steps, rewards in [0,1][0, 1], and results averaged over 5 seeds.

AgentAverage scoreEnvironment stepsWall-clock per 10610^6 steps
Dreamer8235×1065 \times 10^6about 3 hours
PlaNet3325×1065 \times 10^6about 11 hours
D4PG (pixels, top model-free)78610810^8about 24 hours to similar performance

Three readings follow directly from these numbers.

  • Data efficiency. Dreamer scores 823 at 5×1065 \times 10^6 steps, which is about 2.5 times PlaNet's 332 with the same world model. It beats D4PG's 786 at 10810^8 steps, twenty times more data.
  • Compute. The paper's wall-clock figures give 11/3≈3.711 / 3 \approx 3.7 times faster than PlaNet and 24/3=824 / 3 = 8 times faster than D4PG per 10610^6 steps.
  • Horizon. The authors compare three ways to get behaviour from the same world model: a policy trained only on imagined rewards inside the horizon, online planning as in PlaNet, and Dreamer's value-based actor. Figure 4 shows that the value model makes Dreamer robust to the horizon length, including short horizons. Figure 7 reports that optimising only imagined rewards within the horizon, whether with an action model or online planning, gives shortsighted behaviour that succeeds only in reactive tasks such as the walker domain.

On the representation objective (Figure 8), pixel reconstruction performs best on most tasks, the contrastive objective solves about half of them, and reward prediction alone was not sufficient. The paper concludes that improvements in representation learning should carry over to Dreamer.

Dreamer also runs on discrete actions and early termination, on a subset of Atari games and DeepMind Lab levels. There the action model predicts categorical logits, uses straight-through gradients, uses imagination horizon H=10H = 10 and scales the KL by β=0.1\beta = 0.1.

Why it mattered

Dreamer showed that the learned-model approach could beat the strongest model-free agents on visual control, not just match them on data. Within this paper's comparison, the strongest pixel-based scores came from the model-free D4PG, and PlaNet, the model-based baseline, scored far lower. The paper also made the gradient path explicit: the model is a differentiable simulator, and the actor exploits that.

The authors' own conclusion points forward in one specific way: future research on representation learning can likely scale latent imagination to environments of higher visual complexity. The paper also reports its limits. On Atari and DeepMind Lab, agents that learn purely through world models were not yet competitive.

Reading guide

Read the paper in this order, with these prerequisites in hand.

  1. Section 1 (Introduction). Needs Model-Based Reinforcement Learning and Actor-Critic Methods. The contrast with planning and with replay-based actor-critics is the whole motivation.
  2. Section 2 (Control with World Models). Needs Markov Decision Process and Partially Observable Markov Decision Process for the POMDP setup, and World Model for the three latent components. For the transition model's role, Recurrent State Space Model is the design that PlaNet introduced.
  3. Section 3 (Learning Behaviors by Latent Imagination). Needs Value Function, Bellman Equation and Temporal-Difference Learning for the value targets. Reparameterization Trick explains the tanh-Gaussian actor. The VλV_\lambda mixture is the same bias-variance idea as Generalized Advantage Estimation (GAE). Policy Gradient is useful for the contrast with REINFORCE.
  4. Section 4 (Learning Latent Dynamics). Needs Variational Autoencoder, Variational Lower Bound (ELBO) and Latent Variable Model for the ELBO, and Kullback–Leibler Divergence for the KL term. The contrastive estimator in this section uses a noise-contrastive objective, so Generative Model helps with the framing.
  5. Section 5 (Related Work). Skim. It is a map of PlaNet, World Models, MuZero and DDPG-family methods; each is a link you can follow from the reading guide above.
  6. Section 6 (Experiments) and Appendix A. Read the results tables and Figures 4 and 8. Appendix A is the reference for hyperparameters.

Check yourself

QuestionWhat does Dreamer's actor get gradients through that a model-free actor-critic such as DDPG does not?Show answer

Dreamer's actor gradient flows through the whole imagined rollout: actions change the latent states, the states change the predicted rewards and the critic's estimates, and all of these are neural networks. So the gradient of the multi-step value is computed analytically through the learned dynamics. DDPG instead differentiates a learned one-step action-value obtained from real replay transitions, and it never differentiates through a model of how the state evolves.

QuestionUsing the toy numbers from the worked example, what is VλV_\lambda when λ=0\lambda = 0?Show answer

With λ=0\lambda = 0 every term except n=1n = 1 vanishes in the mixture, and the final term λH−1VH\lambda^{H-1} V^H is 00 for H>1H > 1. So Vλ=(1−0)⋅V1=10V_\lambda = (1-0)\cdot V^1 = 10. The target is the one-step bootstrap r0+γv(s1)r_0 + \gamma v(s_1), which has the lowest variance and the most bias if the critic is wrong.

QuestionWhy does the paper hold the critic target fixed with a stop-gradient rather than letting gradients flow into it?Show answer

The target VλV_\lambda is itself built from the critic vψv_\psi. If gradients flowed through the target, the critic would partly chase its own predictions and the update would be unstable. Treating the target as a constant makes the critic a regression problem, the standard practice in policy iteration with bootstrapped values, as the paper notes.

QuestionA researcher reduces Dreamer's imagination horizon from 15 to 3 on a task with a reward 20 steps in the future. Which component should keep the agent's behaviour sensible, and why?Show answer

The critic. Within a 3-step rollout the actor cannot see the reward at step 20 directly, but the VλV_\lambda target bootstraps from the critic's estimate of value at the end of the rollout. The critic has learned the discounted future reward, so it carries information beyond the horizon into the actor's objective. The paper's horizon experiment shows Dreamer stays robust to short horizons for this reason, while a policy trained only on rewards inside the horizon degrades.

Sources

  • Hafner, Lillicrap, Ba, Norouzi (2019). Dream to Control: Learning Behaviors by Latent Imagination. arXiv:1912.01603
  • Hafner et al. (2018). Learning Latent Dynamics for Planning from Pixels (PlaNet). arXiv:1811.04551
  • Ha and Schmidhuber (2018). World Models. arXiv:1803.10122
  • Sutton and Barto. Reinforcement Learning: An Introduction, 2nd edition. Online book

Read the full paper

Danijar Hafner, Timothy Lillicrap, Jimmy Ba et al., 2019. arXiv:1912.01603