Notes / Robot Learning

Dreamer V3

Updated

Imagine learning to catch a ball. Every attempt gives you experience, but you also have a mental model of where the ball is going which allows you to anticipate which actions are more likely to lead you to catching it. An agent with a world model does something related, learning to predict the consequences of actions and using those predictions to improve its behaviour. It learns to predict the consequences of actions, then uses those predictions to improve its behavior.

Dreamer learns a compact world model and trains an actor and a critic inside it. The world model supplies imagined experience, the critic estimates how rewarding a state is, and the actor learns to choose actions that lead to better outcomes.

Introduction

Training embodied intelligence is, in part, difficult because of the data required. Collecting real interactions between a robot and its environment can be expensive - a robot needs time to move, an environment may need to reset, and a failed attempt might teach only a little. If an agent can learn to anticipate the results of its actions, it can improve training efficiency by reducing the number of real samples needed to achieve the desired performance on a task.

But predicting the next camera frame is not the whole task. A useful world model needs to preserve the information that matters for what happens next, what reward arrives, and whether the episode continues. And even a good model does not tell the agent which actions to choose. That is the actor’s job.

Dreamer alternates between collecting real experience, fitting its model to replayed sequences, and improving its actor and critic on imagined sequences. All three networks develop during training. During a particular actor–critic update, the world model stays fixed.

Training the World Model

Similar to classical state estimation, one observation does not uniquely determine our entire current state. Knowing the current state requires fusing in an entire history of actions and observations in order to produce a belief of the current state of the system.

Dreamer V3 uses a recurrent state-space model, or RSSM. Its state has two parts:

st=(ht,zt).s_t=(h_t,z_t).

The recurrent state hth_t carries information from the past, including action and observation history. Its update is deterministic given the previous state and action. The stochastic latent ztz_t is sampled from a learned distribution, allowing multiple possible latent outcomes for the same history, similar to how we maintain a belief of our state in classical state estimation, but instead we do so in latent space. Together they form the state used by the actor, critic, and prediction heads.

We will use the following timing convention throughout the note: the agent observes xtx_t, receives the reward rtr_t from the previous action, and chooses ata_t. That action leads to xt+1x_{t+1} and rt+1r_{t+1}. The continuation label ct+1c_{t+1} is zero if that transition terminates the task, and one otherwise.

RSSM Observation Step
RSSM Observation StepPast state and action update memory. Memory predicts a prior; memory and a real observation infer a posterior. A posterior sample joins memory to predict observation, reward, and continuation. KL losses compare the two distributions.samplecarry hₜKL: compare q and pPrevious state + actionhₜ₋₁, zₜ₋₁, aₜ₋₁Memoryhₜ = f(hₜ₋₁, zₜ₋₁, aₜ₋₁)Prior pPredict zₜ from hₜReal observationxₜ → encoderPosterior qInfer zₜ from hₜ and xₜModel statesₜ = (hₜ, zₜ), zₜ ∼ qPrediction headsxₜ · rₜ · cₜ

Scroll sideways to follow the full diagram.

Updating Recurrent Memory

Replay supplies the previous action. The recurrent network combines it with the previous state to update memory. At this point, the model has not seen the new observation.

ht=fϕ(ht−1,zt−1,at−1)h_t=f_\phi(h_{t-1},z_{t-1},a_{t-1})

Prior and Posterior Distributions

When training the world model, we use recorded observations and actions to learn a compact representation of the environment and its dynamics. We then use this model to generate imagined trajectories for training the actor and critic. During these rollouts, future observations are unavailable, so the model must predict how its state evolves using only its current state and the chosen actions.

The posterior and prior networks support these two settings. The posterior infers the current latent state from the current observation and the model’s memory of previous observations and actions. The prior predicts a distribution over that same latent state from memory alone, without seeing the current observation. Training encourages the prior to match the observation-informed posterior, allowing it to take over during imagined rollouts.

The memory update consumes the previous latent and the action that was taken:

ht=fϕ(ht−1,zt−1,at−1).h_t=f_\phi(h_{t-1},z_{t-1},a_{t-1}).

From this memory, the model produces a prior pϕ(zt∣ht)p_\phi(z_t\mid h_t). Think of it as a prediction made of the current state before seeing the current observation. It is a distribution over latent codes which we intend to be a maximally true representation of the agent’s true current state.

The posterior also receives the encoded observation:

qϕ(zt∣ht,eϕ(xt)).q_\phi(z_t\mid h_t,e_\phi(x_t)).

If a new obstacle has just entered the camera view, the posterior can reflect it even when the prior did not expect it. While fitting the world model, we sample ztz_t from this observation-informed posterior and combine it with hth_t.

This distinction is the hinge of the whole algorithm. When a real observation is available, use the posterior. When imagining a future observation that does not exist yet, use the prior.

Prediction Losses

Three prediction heads read the same state sts_t. One reconstructs the observation, one predicts the arriving reward, and one predicts continuation. They are trained against the recorded values from real trajectories:

Lpred,t=−log⁡pϕ(xt∣st)−log⁡pϕ(rt∣st)−log⁡pϕ(ct∣st).\begin{aligned} \mathcal L_{\mathrm{pred},t}={}&-\log p_\phi(x_t\mid s_t)\\ &-\log p_\phi(r_t\mid s_t) -\log p_\phi(c_t\mid s_t). \end{aligned}

Here pϕp_\phi denotes each output head, not just the latent prior. Reconstructing observations encourages the state to retain information; reward and continuation prediction make it useful for evaluating future behavior. The observation decoder helps train the model, but it does not need to render images while the actor practices in latent space.

Dynamics and Representation Losses

The prior will eventually have to carry a rollout without fresh observations. We therefore train it to match the posterior’s distribution. Meanwhile, we gently encourage the posterior to produce representations that the prior can predict so that it doesn’t end up learning representations that can’t feasibly be matched by the prior during imagination.

Let qtq_t and ptp_t denote the posterior and prior. Dreamer splits this pressure into two losses:

Ldyn,t=max⁡(1,KL⁡[sg⁡(qt)∥pt]),Lrep,t=max⁡(1,KL⁡[qt∥sg⁡(pt)]).\begin{aligned} \mathcal L_{\mathrm{dyn},t} &=\max(1,\operatorname{KL}[\operatorname{sg}(q_t)\Vert p_t]),\\ \mathcal L_{\mathrm{rep},t} &=\max(1,\operatorname{KL}[q_t\Vert\operatorname{sg}(p_t)]). \end{aligned}

The stop-gradient operator sg⁡\operatorname{sg} preserves a value but blocks its gradient through that occurrence. In the dynamics loss, the posterior is the fixed target. In the representation loss, the prior is the fixed target.

Why the max⁡(1,⋅)\max(1,\cdot)? Below one nat of KL divergence, this penalty has no gradient. This gives the posterior room to incorporate useful information from the current observation that the prior cannot predict from history alone. As we’ll see, the posterior is not just a training target for the prior: its sampled latent helps reconstruct observations, predict rewards, and form the state the actor uses during real-world inference. Pushing the two distributions to agree too strongly could make the posterior discard new information simply because the prior cannot anticipate it. So this threshold relaxes that pressure once they are sufficiently close.

The world-model objective averages the following over replay sequences:

Lworld=Lpred+Ldyn+0.1Lrep.\mathcal L_{\mathrm{world}} =\mathcal L_{\mathrm{pred}} +\mathcal L_{\mathrm{dyn}} +0.1\mathcal L_{\mathrm{rep}}.

This loss formulation also why we separate the KL between the prior and posterior into two different terms rather than comparing them to each other just in one - the unequal weights put stronger pressure on prediction to catch up with evidence than on evidence to become predictable. We then repeatedly step the observation step along a replay sequence, using the recorded actions, and update the world-model parameters ϕ\phi.

Generating Imagined Trajectories

Now that we have learned a way to predict the evolution of the system from actions and initial state, we can put it to use for learning behaviours. This process is called imagination.

Let’s start from a state inferred from replay, detach it from the model-training graph, and call it s^0\hat s_0 (the hat marks imagined quantities). The different indices may be confusing, but what we’re saying is to take the state at real trajectory time tt, and use it as the starting state of imagination.

Latent Imagination Rollout
Latent Imagination RolloutA replay posterior state starts an imagined rollout. The actor samples an action, the recurrent model and prior produce the next state, reward and continuation are predicted, and the process repeats.memory + priorReplay startŝ₀ = stop-gradient(sₜ)Actor πSample action â₀Imagined stateŝ₁ = (ĥ₁, ẑ₁), ẑ₁ ∼ pPredicted outcomeReward r̂₁ · continue ĉ₁Same actor πSample action â₁Next imagined stateŝ₂, then ŝ₃, …, ŝHCritic vValue beyond the horizon

Scroll sideways to follow the full diagram.

Initializing from Replay

Infer a state from a replayed observation, then detach it from the model-training graph.

s^0=sg(st)\hat s_0=\mathrm{sg}(s_t)

At each step, the actor samples an action:

a^k∼πθ(⋅∣s^k).\hat a_k\sim\pi_\theta(\cdot\mid\hat s_k).

The recurrent model advances memory, and the prior supplies the next latent:

h^k+1=fϕ(h^k,z^k,a^k),z^k+1∼pϕ(⋅∣h^k+1).\begin{aligned} \hat h_{k+1}&=f_\phi(\hat h_k,\hat z_k,\hat a_k),\\ \hat z_{k+1}&\sim p_\phi(\cdot\mid\hat h_{k+1}). \end{aligned}

The reward and continuation heads evaluate the resulting state s^k+1\hat s_{k+1}. Feeding that state back into the actor produces another action, then another state, and so on until the imagination horizon HH.

Notice that there is now no future real observation xt+kx_{t+k} to encode as there was during training of the world model. The posterior has handed off to the prior, and we now rely on it to accurately estimate the agent state during the imagined trajectory. An imagined trajectory is hence a sequence of compact states, actions, predicted rewards, and continuation probabilities.

Training the Actor and Critic

The actor and critic are two networks, with the actor choosing the action from a given state and the critic scoring the value of states under the current actor.

Our rollout is finite, so we cannot simply wait for every future reward. At its end, we bootstrap from the critic, using its estimated value of being at the terminal state in the rollout:

GH=vψ(s^H).G_H=v_\psi(\hat s_H).

Then work backward through the imagined rewards. Here is a small numerical example before we write the general equation where we see a trajectory starting from state s0s_0 and taking two actions.

Return and Advantage Computation
Return and Advantage ComputationHere we have a toy trajectory has rewards 1 and 2, discount 0.9, continuation 1, lambda 1, and final value 4. Working backward gives returns 5.6 and 6.04. The initial critic baseline 3 gives advantage 3.04.â₀â₁State ŝ₀Baseline v₀ = 3State ŝ₁Arriving reward r̂₁ = 1State ŝ₂Arriving reward r̂₂ = 2Bootstrap G₂Final critic value = 4Return G₁2 + 0.9 × 4 = 5.60Return G₀1 + 0.9 × 5.60 = 6.04Critic targetFit a distribution to G₀Actor advantageG₀ − v₀ = 6.04 − 3 = +3.04

Scroll sideways to follow the full diagram.

Example Trajectory

Take two predicted rewards, 1 and 2. We use discount γ = 0.9 and continuation ĉ = 1 (the trajectory continues). Lets say the initial critic predicts a return of 3 at the starting state.

r^1=1,r^2=2,γ=0.9\hat r_1=1,\quad\hat r_2=2,\quad\gamma=0.9

Computing Return Targets

In the example, we computed the return target using all the imagined rewards and the critic’s estimate at the end of the rollout. More generally, we can combine two estimates of future return: the critic’s prediction at the next state, and a longer estimate built from rewards predicted by the world model. This lets imagined experience improve the critic while the critic accounts for rewards beyond the rollout horizon. Dreamer balances these estimates using a λ\lambda-return:

Gk=r^k+1+γc^k+1[(1−λ)vk+1+λGk+1].G_k=\hat r_{k+1}+\gamma\hat c_{k+1} \left[(1-\lambda)v_{k+1}+\lambda G_{k+1}\right].

The first term is the predicted arriving reward. The rest is a discounted estimate of what comes after it. Continuation c^k+1\hat c_{k+1} gates that future contribution, since a terminal transition has no future return to account for.

The term vk+1v_{k+1} asks the critic directly. The term Gk+1G_{k+1} uses more of the rollout. With λ=0\lambda=0, we use one reward and the next critic value; with λ=1\lambda=1, we use the remaining imagined rewards and the final bootstrap. V3’s default λ=0.95\lambda=0.95 puts most of the mixture on the longer estimate.

Training the Critic

The critic’s job is to predict GkG_k from s^k\hat s_k. V3 represents returns with probabilities over fixed, exponentially spaced bins. Its scalar value is the probability-weighted mean of those bin positions. I’ll explain this design choice after a brief example:

A target between two neighboring bins is encoded with two nonzero weights. For example, a target of 33 between bins 22 and 66 assigns them weights 0.750.75 and 0.250.25. Cross-entropy trains the critic toward that soft target.

When I first read the paper, I wondered: why predict a distribution over bins rather than regress the reward directly? The authors designed Dreamer to work across domains where reward magnitudes can differ dramatically. Using cross-entropy over bins makes training less sensitive to those magnitudes, although the fixed bin range limits the values the model can represent.

My next thought was: why not simply apply a logarithmic transformation to the reward before regressing it? Compressing the target would also change the scale of the regression error and its gradients.

The return target is stopped during this update. Later states are weighted by their discounted probability of being reached:

w0=1,wk=∏j=1kγc^j.w_0=1,\qquad w_k=\prod_{j=1}^{k}\gamma\hat c_j.

V3 also regularizes the critic toward a slowly averaged version of itself and uses an auxiliary value loss on replay trajectories.

Training the Actor

In order to refine its policy, the actor considers whether the sampled action lead to a better imagined outcome than the critic expected:

Ak=Gk−vψ(s^k).A_k=G_k-v_\psi(\hat s_k).

A positive advantage pushes the sampled action’s log probability up while a negative advantage pushes it down. Try changing either side of that comparison:

Return and Advantage Sensitivity

The same toy example as earlier with γ = 0.9, λ = 1, and continuation = 1. Adjust the reward or the initial critic’s baseline.

G₀ = 1 + 0.9 × (2 + 0.9 × 4) = 6.04

Advantage +3.04. The policy-gradient term increases the sampled action’s log probability.

V3 scales advantages by max⁡(1,S)\max(1,S), where SS is a smoothed 95th-minus-5th percentile range of returns. This reduces large update magnitudes without amplifying small signals. Including entropy and trajectory weights, the actor loss is

Lπ=−E∑ksg⁡(wk)[sg⁡ ⁣(Gk−vkmax⁡(1,S))log⁡πθ(a^k∣s^k)+η H[πθ(⋅∣s^k)]].\begin{aligned} \mathcal L_\pi=-\mathbb E\sum_k\operatorname{sg}(w_k)\Bigg[& \operatorname{sg}\!\left(\frac{G_k-v_k}{\max(1,S)}\right) \log\pi_\theta(\hat a_k\mid\hat s_k)\\ &+\eta\,\mathcal H[\pi_\theta(\cdot\mid\hat s_k)]\Bigg]. \end{aligned}

Entropy H\mathcal H encourages exploration, the advantage term rewards actions with better sampled outcomes. In this V3 update, and each timestep kk is weighted by the probability of it being reached wkw_k that we defined earlier.

Inference

After all that imagination and behaviour training, inference is pleasantly short. We update memory from the previous state and executed action, encode the new observation, sample the observation-informed latent, and pass the state to the actor and execute its action.

xt⟶qϕ(zt∣ht,eϕ(xt))⟶(ht,zt)⟶πθ⟶at.x_t\longrightarrow q_\phi(z_t\mid h_t,e_\phi(x_t)) \longrightarrow (h_t,z_t) \longrightarrow \pi_\theta \longrightarrow a_t.

Here, we use the observation encoder and posterior learned during world model training since real observations keep arriving during interaction with the environment. The observation decoder, reward head, and critic aren’t used in inference.

Gradients Through Categorical Sampling

There is one small puzzle hidden in the diagrams that we glossed over - if ztz_t is sampled from categorical distributions, how can reconstruction gradients train the encoder?

V3 uses a straight-through estimator. For a toy three-category factor, let the probabilities be p=[0.1,0.7,0.2]p=[0.1,0.7,0.2] and suppose the sampled one-hot code is zsample=[0,1,0]z_{\mathrm{sample}}=[0,1,0]. Construct

z=p+sg⁡(zsample−p).z=p+\operatorname{sg}(z_{\mathrm{sample}}-p).

In the forward pass, the probabilities cancel and the decoder receives the hard sample [0,1,0][0,1,0]. In the backward pass, the stopped term contributes no derivative, so the gradient follows the probabilities pp and then the softmax logits.

This is a biased, surrogate gradient - certainly not an exact derivative. But the prior-posterior KL comparison doesn’t need this trick since it operates on the distributions directly.

References