Paper notes

DreamerV3: One Set of Hyperparameters for 150+ Tasks with a World-Model Agent

DreamerV3 (Hafner et al., 2023) learns a world model and trains an actor and critic on imagined latent trajectories. With symlog, twohot regression, free bits and percentile return normalization, one hyperparameter set beats or matches specialists on 150+ tasks and finds a Minecraft diamond.

Published Updated 38 min read

On this page
  1. Why this paper matters
  2. Background: why general RL is hard
  3. Method
  4. World model: a recurrent state-space model
  5. Critic: classification over exponentially spaced bins
  6. Actor: return normalization makes one entropy scale work everywhere
  7. Robust predictions: symlog and the twohot loss
  8. Other implementation notes
  9. Experiments and results
  10. 8 domains, one set of algorithm hyperparameters
  11. Minecraft: diamonds from scratch
  12. Ablations and scaling
  13. Checking it with code
  14. Experiment 1: does the gradient size decouple from the target size?
  15. Experiment 2: one network, four regression heads
  16. Experiment 3: percentile return normalization
  17. What these experiments show, and what they do not
  18. Limitations and caveats
  19. What to take away from this paper
  20. Further reading
  21. FAQ

DreamerV3 is a general reinforcement learning algorithm from Hafner, Pasukonis, Ba and Lillicrap (January 2023), in the model-based family. It trains three networks: a world model that predicts the consequences of actions, a critic that estimates the value of each state, and an actor that picks actions. The actor and critic learn only from trajectories imagined inside the world model’s latent space; the real environment only supplies data. The paper’s claim is that adding a set of robustness techniques to this skeleton (symlog transform, twohot regression, free bits, 1% uniform mixing, percentile return normalization) lets one set of hyperparameters beat or match specialist algorithms on more than 150 tasks across 8 domains. The paper also says it is the first algorithm to collect diamonds in Minecraft from scratch, without human data or curricula.

This page reads arXiv v2 (17 April 2024); v1 appeared on 10 January 2023. Every number attributed to the paper comes from v2.

Why this paper matters

  • The goal is less tuning, not a record on one benchmark. The paper opens by pointing out that applying RL to a new domain takes substantial expertise and experimentation. DreamerV3 treats “no retuning when the domain changes” as the property to demonstrate, and tests it on more than 150 tasks.
  • Long-horizon exploration from sparse rewards. A Minecraft diamond requires discovering a chain of 12 items in a randomly generated 3D world, with sparse rewards and a long horizon; earlier approaches relied on human demonstrations (VPT) or adaptive curricula.
  • Reproducible on one GPU. Every Dreamer agent is trained on a single A100, and the paper provides six model sizes from 12M to 400M parameters, showing that performance rises with model size while the required environment interaction falls.
  • The learning signal comes from reconstruction. The ablations show Dreamer rests mainly on the world model’s unsupervised reconstruction objective rather than on reward and value gradients, and the paper suggests future variants could pretrain on unsupervised data.
  • Connections on this site. The idea of a world model is covered in the World Models explainer; the paper uses PPO as its general-purpose baseline; the Atari opponents Rainbow and IQN belong to the DQN line.

Background: why general RL is hard

RL tasks differ along many axes: discrete or continuous actions, images or vectors, dense or sparse rewards, reward scales that differ by orders of magnitude, 2D or 3D worlds, fixed or procedurally generated levels. In its related work the paper sizes up the usual candidates: PPO is fairly robust but needs a lot of experience and often scores below specialists; SAC is popular for continuous control but needs entropy-scale tuning and struggles with high-dimensional inputs; MuZero succeeded on board games and Atari but has no released implementation and many complex components; Gato needs expert data.

The first two Dreamer generations each targeted one domain: DreamerV1 handled only continuous control, DreamerV2 surpassed human performance on Atari, and DreamerV3 aims to work out of the box across many. Its core idea comes from World Models: learn a model that predicts the future and let the policy practice inside it. The difference is that the world model and the policy are trained together, and the world model comes with a full set of tricks that keep training stable.

Method

DreamerV3 consists of three networks trained concurrently on the same replay buffer, while the agent interacts with the environment by sampling from the actor (no lookahead planning).

The DreamerV3 training loop: world model and actor-critic in imagination The upper half is the world model: an observation x passes through the encoder to a discrete stochastic representation z, the recurrent state h is updated from the previous h, z and action a, h and z form the model state s, which predicts the observation, reward and continue flag; a dynamics predictor predicts z from h and is tied to the encoder's z by a KL term. The lower half is behavior learning: starting from replayed states the actor picks actions, the sequence model predicts the next state, the loop rolls 15 steps in latent space, the critic estimates values, and lambda-returns with return normalization update the actor. (a) World model: trained on replayed real sequences Observation x_t image or vector Encoder q(z_t | h_t, x_t) Latent z_t discrete, stochastic Model state s_t (h_t, z_t) Decoder: rebuild x_t Reward r_t (twohot) Continue c_t (logistic) L_pred Recurrent state h_t = f(h_(t−1), z_(t−1), a_(t−1)) Dynamics predictor p(z_t | h_t) KL: L_dyn, L_rep (b) Behavior learning in imagination: roll H=15 steps in latent space, no environment Start s_t from replay Actor π(a_t | s_t) samples action a_t Sequence model + heads s_(t+1), r, c s_(t+1) next step Critic v(s_t) binned distribution, twohot λ-return R_t ÷ max(1, S), S = percentile range Actor update REINFORCE + entropy η=3e-4
The DreamerV3 training loop (after the paper's Figure 3 and Equations 1 to 7): the top half trains the world model on replayed real sequences; the bottom half rolls out imagined trajectories in latent space to train the critic and the actor.

World model: a recurrent state-space model

The world model is a Recurrent State-Space Model (RSSM) with the following components (the paper’s Equation 1):

ComponentFormula
Sequence modelht=fϕ(ht−1,zt−1,at−1)h_t = f_\phi(h_{t-1}, z_{t-1}, a_{t-1})
Encoderzt∼qϕ(zt∣ht,xt)z_t \sim q_\phi(z_t \mid h_t, x_t)
Dynamics predictorz^t∼pϕ(z^t∣ht)\hat z_t \sim p_\phi(\hat z_t \mid h_t)
Reward predictorr^t∼pϕ(r^t∣ht,zt)\hat r_t \sim p_\phi(\hat r_t \mid h_t, z_t)
Continue predictorc^t∼pϕ(c^t∣ht,zt)\hat c_t \sim p_\phi(\hat c_t \mid h_t, z_t)
Decoderx^t∼pϕ(x^t∣ht,zt)\hat x_t \sim p_\phi(\hat x_t \mid h_t, z_t)

hth_t is a deterministic recurrent state (a GRU with block-diagonal recurrent weights) and ztz_t is a discrete stochastic representation sampled from a vector of softmax distributions, with straight-through gradients through the sampling. Images use convolutional networks and vectors use MLPs. hth_t and ztz_t together form the model state sts_t, from which the reward, the continue flag (ct∈{0,1}c_t\in\{0,1\}, whether the episode goes on) and the reconstruction are predicted. The loss has three terms (Equations 2 and 3):

L(ϕ)=Eqϕ ⁣[∑t=1T(βpredLpred+βdynLdyn+βrepLrep)],βpred=1, βdyn=1, βrep=0.1\mathcal L(\phi)=\mathbb E_{q_\phi}\!\left[\sum_{t=1}^{T}\bigl(\beta_{\mathrm{pred}}\mathcal L_{\mathrm{pred}}+\beta_{\mathrm{dyn}}\mathcal L_{\mathrm{dyn}}+\beta_{\mathrm{rep}}\mathcal L_{\mathrm{rep}}\bigr)\right],\qquad \beta_{\mathrm{pred}}=1,\ \beta_{\mathrm{dyn}}=1,\ \beta_{\mathrm{rep}}=0.1 Ldyn=max⁡(1, KL[ sg(qϕ(zt∣ht,xt)) ∥ pϕ(zt∣ht) ]),Lrep=max⁡(1, KL[ qϕ(zt∣ht,xt) ∥ sg(pϕ(zt∣ht)) ])\begin{aligned} \mathcal L_{\mathrm{dyn}}&=\max\bigl(1,\ \mathrm{KL}[\,\mathrm{sg}(q_\phi(z_t\mid h_t,x_t))\ \|\ p_\phi(z_t\mid h_t)\,]\bigr), \\ \mathcal L_{\mathrm{rep}}&=\max\bigl(1,\ \mathrm{KL}[\,q_\phi(z_t\mid h_t,x_t)\ \|\ \mathrm{sg}(p_\phi(z_t\mid h_t))\,]\bigr) \end{aligned}

Lpred\mathcal L_{\mathrm{pred}} is the sum of the negative log-likelihoods of the decoder, reward predictor and continue predictor. The dynamics loss trains the sequence model to predict the next representation; the representation loss makes representations easier to predict. They differ only in where the stop-gradient sg\mathrm{sg} sits and in their weights (1 versus 0.1); the ablation legend calls this “KL balance”. Free bits clip both KL terms below 1 nat (about 1.44 bits): once a KL is small enough it produces no gradient, so learning focuses on the prediction loss, which avoids the degenerate solution where the dynamics are trivial to predict but the representation carries too little about the observation. In addition, the categorical distributions of the encoder, the dynamics predictor (and the actor) are mixed with 1% uniform noise, which makes them impossible to become deterministic and keeps the KL losses free of spikes. The paper’s ablation (Figure 6a) finds the world model’s KL objective is the single most important of the robustness techniques.

Critic: classification over exponentially spaced bins

The actor maximizes the discounted return Rt=∑τ≥0γτrt+τR_t=\sum_{\tau\ge0}\gamma^\tau r_{t+\tau} with γ=0.997\gamma=0.997. Returns beyond the imagination horizon are bootstrapped with the critic vψv_\psi, which is trained toward the λ\lambda-return (Equation 5):

Rtλ=rt+γct((1−λ)vt+λRt+1λ),RTλ=vTR^\lambda_t=r_t+\gamma c_t\bigl((1-\lambda)v_t+\lambda R^\lambda_{t+1}\bigr),\qquad R^\lambda_T=v_T

Instead of regressing a scalar, the critic outputs a probability distribution over a set of exponentially spaced bins, trained by maximum likelihood and read out as the expectation. The motivation (detailed in the next subsection) is that the return distribution can be multimodal and span orders of magnitude. The paper’s other stabilizers: the critic loss is also applied to replayed sequences (weight βrepval=0.3\beta_{\mathrm{repval}}=0.3); the critic is regularized toward the output of an exponential moving average of its own parameters (decay 0.98), which acts like a target network but lets returns be computed with the current critic; and the output layers of the reward predictor and critic are zero-initialized, so that large random initial predictions do not delay the start of learning.

Actor: return normalization makes one entropy scale work everywhere

The actor is trained with the REINFORCE estimator for both discrete and continuous actions, plus an entropy bonus for exploration. The trouble is that the right entropy scale depends on the scale and frequency of rewards: explore more when rewards are sparse, exploit more when they are dense or within reach, yet the amount of exploration should not depend on an arbitrary rescaling of rewards. DreamerV3 rescales returns to roughly the interval [0,1][0,1] so that a fixed entropy coefficient η=3×10−4\eta=3\times10^{-4} works in every domain:

max⁡θ ∑t=1Tsg ⁣(Rtλ−vψ(st)max⁡(1,S))log⁡πθ(at∣st)+η H[πθ(at∣st)],S=EMA(Per(Rtλ,95)−Per(Rtλ,5), 0.99)\begin{aligned} &\max_\theta\ \sum_{t=1}^{T}\mathrm{sg}\!\left(\frac{R^\lambda_t-v_\psi(s_t)}{\max(1,S)}\right)\log\pi_\theta(a_t\mid s_t)+\eta\,\mathrm H\bigl[\pi_\theta(a_t\mid s_t)\bigr], \\ &S=\mathrm{EMA}\bigl(\mathrm{Per}(R^\lambda_t,95)-\mathrm{Per}(R^\lambda_t,5),\ 0.99\bigr) \end{aligned}

Two details matter. First, SS is the gap between the 95th and 5th percentiles of the return batch, smoothed by an exponential moving average, so it is insensitive to outlier returns; normalizing by the minimum and maximum would let one extreme return shrink all the others too much. Second, the divisor is max⁡(1,S)\max(1,S): only large returns are scaled down and returns below 1 are left untouched, so function-approximation noise is not amplified under sparse rewards. The paper contrasts the usual alternatives: normalizing advantages puts a fixed emphasis on maximizing returns over entropy whether or not rewards are within reach; normalizing by the standard deviation can fail under sparse rewards, where the standard deviation is near zero and rewards are amplified regardless of their size; constrained optimization that holds the entropy at a target explores slowly under sparse rewards and converges lower under dense ones. The paper says it found no hyperparameters that were stable across domains for these approaches.

Robust predictions: symlog and the twohot loss

Reconstructing inputs and predicting rewards and returns are hard because the scale of these quantities is unknown. The paper notes that predicting large targets with a squared loss can diverge, absolute and Huber losses stagnate learning, and normalizing targets by running statistics introduces non-stationarity. DreamerV3 proposes the symlog squared error: the network predicts a transformed target and the inverse transform is applied when reading out (Equations 8 and 9):

L(θ)=12(f(x,θ)−symlog(y))2,y^=symexp(f(x,θ)),symlog(x)=sign(x)ln⁡(∣x∣+1),symexp(x)=sign(x)(e∣x∣−1)\begin{aligned} \mathcal L(\theta)&=\tfrac12\bigl(f(x,\theta)-\mathrm{symlog}(y)\bigr)^2,\qquad \hat y=\mathrm{symexp}\bigl(f(x,\theta)\bigr), \\ \mathrm{symlog}(x)&=\mathrm{sign}(x)\ln(|x|+1),\qquad \mathrm{symexp}(x)=\mathrm{sign}(x)\bigl(e^{|x|}-1\bigr) \end{aligned}

symlog is close to the identity near zero, so it does not disturb targets that are already small; it compresses large magnitudes logarithmically while keeping the sign. DreamerV3 uses it to transform vector observations (encoder inputs and decoder targets). For potentially stochastic targets such as rewards and returns it uses the symexp twohot loss (Equations 10 and 11): the network outputs a softmax distribution over bins located at B=symexp(−20…+20)B=\mathrm{symexp}(-20\ldots+20) (the paper’s main text does not give the number of bins; the experiments below use 255), the prediction is y^=softmax(f(x))⊤B\hat y=\mathrm{softmax}(f(x))^{\top}B, and the target is the twohot encoding of the true value (only the two nearest bins are non-zero, with weights linear in distance that sum to 1), trained with cross-entropy:

L(θ)=− twohot(y)⊤log⁡softmax(f(x,θ))\mathcal L(\theta)=-\,\mathrm{twohot}(y)^{\top}\log\mathrm{softmax}\bigl(f(x,\theta)\bigr)

The loss depends only on the probabilities assigned to the bins, not on the values at the bin locations, so “the size of the gradients is decoupled from the size of the targets”. The paper adds an implementation detail: because the bins span many orders of magnitude, the summation order matters when taking the expectation, and positive and negative bins should be summed separately from small to large and then added; this page does not test that.

Other implementation notes

The main hyperparameters (the paper’s Table 4), identical on every benchmark:

HyperparameterValue
Batch size and length16 and 64
Learning rate4×10−54\times10^{-5}
OptimizerLaProp (ϵ=10−20\epsilon=10^{-20}), adaptive gradient clipping AGC (0.3)
Imagination horizon HH15
Discount γ\gamma, λ\lambda0.997 (horizon 333), 0.95
World-model loss scalesprediction 1, dynamics 1, representation 0.1, free bits 1 nat
Criticreplay loss 0.3, EMA decay 0.98
Actorentropy 3×10−43\times10^{-4}, return-normalization decay 0.99, limit 1

The main text writes the imagination length as “prediction horizon T=16T=16”, Table 4 gives the imagination horizon as H=15H=15, and TT in the table is the batch length 64; the paper does not explain how these symbols relate, so 15 is taken from Table 4. The networks use RMSNorm and SiLU. LaProp normalizes gradients with RMSProp and then applies momentum, which the paper says allows a smaller epsilon and avoids occasional instabilities they saw with Adam. The paper also states that it uses no hyperparameter annealing, prioritized replay, weight decay or dropout.

Experiments and results

8 domains, one set of algorithm hyperparameters

The paper’s Table 2 lists the setup of each benchmark (every agent is trained on a single A100):

BenchmarkTasksEnv stepsReplay ratioGPU daysModel
Minecraft1100M328.9200M
DMLab30100M322.9200M
ProcGen1650M6416.1200M
Atari57200M327.7200M
Atari100K26400K1280.1200M
BSuite23-10240.5200M
Proprio control18500K5120.312M
Visual control201M5120.112M

The table has two more columns: environment instances (1 for Atari100K and BSuite, 64 for Minecraft, 16 elsewhere) and action repeat (1 to 4). The task counts add up to 191, but the 26 Atari100K games are taken from the 57 Atari games and the two control benchmarks share tasks, and the paper does not say how its “over 150 tasks” is deduplicated.

The paper’s main claims per benchmark, all against published results it cites:

  • Atari (200M frames): beats MuZero while using a fraction of its compute, and also beats Rainbow and IQN.
  • ProcGen (50M frames): matches the tuned PPG and beats Rainbow; the paper’s own fixed-hyperparameter PPO matches the published score of the highly tuned official PPO.
  • DMLab (100M frames): exceeds IMPALA and R2D2+ at 1B steps, which the paper describes as a data-efficiency gain of over 1000%, noting that those baselines were not designed for data efficiency.
  • Atari100K: beats IRIS, TWM, SPR and SimPLe. EfficientZero combines online tree search, prioritized replay and hyperparameter scheduling, and also resets levels early to increase data diversity, which the paper says makes a comparison difficult.
  • The two control benchmarks: proprioceptive control beats D4PG, DMPO and MPO, and visual control beats DrQ-v2 and CURL; the paper calls both new state of the art.
  • BSuite (23 environments, 468 configurations): beats Boot DQN and others, with the largest gain in the “robustness to reward scale” category.

The paper also uses a fixed-hyperparameter PPO as a baseline and says DreamerV3 substantially outperforms it in every domain.

Minecraft: diamonds from scratch

The task is to obtain 12 milestone items in a randomly generated world: log, plank, stick, crafting table, wooden pickaxe, cobblestone, stone pickaxe, iron ore, furnace, iron ingot, iron pickaxe, diamond. Each item is rewarded once per episode with +1, plus −0.01 and +0.01 for each heart lost or restored. An episode lasts at most 36,000 steps, which is 30 minutes at 20 Hz, and experienced humans need about 20 minutes to get a diamond. The paper builds its environment on MineRL v0.4.4 with a flat categorical action space, and removes the original early termination on breaking diamond ore (otherwise many successful episodes ended before the item was picked up). DreamerV3 runs with default hyperparameters, 64 parallel environments and about 8.9 days on one GPU; the episode returns after 100M environment steps (about 100 days of game time) are in the paper’s Table 5:

MethodEpisode return at 100M steps
DreamerV39.1
IMPALA7.1
Rainbow6.3
PPO5.1

Figure 5 shows that all 10 DreamerV3 seeds collect at least one diamond during training, while none of the three baselines ever does; they get as far as the iron pickaxe. The paper notes that it uses the block-breaking action setting from prior work, because the original action space makes it hard for stochastic policies to hold a key for a long time. It also compares with VPT, which behavior-cloned contractor keyboard-and-mouse data and then fine-tuned with RL using 720 GPUs for 9 days; DreamerV3 used 1 GPU for 9 days and no human data. The environment settings of the two are not identical.

The world model can also be inspected: given 5 context frames and the full action sequence, without the intermediate images, it predicts 45 steps ahead (the paper’s Figure 4 for a DMLab maze and a quadruped robot, Figure 7 for Minecraft).

Ablations and scaling

The paper ablates on 14 tasks (Figure 6). Figure 6a replaces each technique with its usual alternative: no observation symlog, advantage normalization instead of return normalization, a Huber loss instead of symexp twohot, no KL balance and free bits, and finally all of them removed. All techniques contribute on average, most notably the world model’s KL objective, followed by return normalization and symexp twohot regression, though each is critical only on a subset of tasks. Figure 6b cuts either the reward-and-value gradients or the reconstruction gradients: Dreamer rests predominantly on the world model’s unsupervised reconstruction objective, unlike most RL algorithms that rely on reward and value gradients. Figures 6c and 6d vary the model size (6 sizes from 12M to 400M) and the replay ratio on Crafter and a DMLab task: larger models perform better and need less environment interaction, and higher replay ratios also perform better.

Checking it with code

The paper’s ablation (Figure 6a) shows that symlog, twohot regression and return normalization each help, but that is an average over 14 tasks; it does not show why each technique helps or when it breaks. The three small experiments below isolate them using only a CPU and synthetic data. They are not a reproduction of DreamerV3 as a whole:

  • grad: feed one target to a network whose output is zero and see how large the gradient is for each of four regression heads;
  • fit: train the same small MLP with each of the four heads on four kinds of synthetic target at four scales and compare the fitting error;
  • norm: see how different “divisors” behave when returns contain outliers or when only rare successes are returned.

Environment: Apple M2 Max, Python 3.14.3, PyTorch 2.10.0 (CPU only, 2 threads), NumPy 2.4.2; no dataset and no pretrained model. The output of each mode is pasted in its subsection, and the numbers come from one complete run of this script; individual decimals may differ slightly on other environments.

"""Two robustness tricks from DreamerV3: symlog / symexp-twohot regression
heads, and percentile return normalization. CPU only, no external data.

Usage: python dreamer_en.py grad | fit | norm
"""
import sys

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F

torch.set_num_threads(2)


def symlog(x):
    return torch.sign(x) * torch.log1p(x.abs())


def symexp(x):
    return torch.sign(x) * torch.expm1(x.abs())


# Paper Eq. (10): 255 bins spaced by symexp, covering [-4.85e8, 4.85e8]
BINS = symexp(torch.linspace(-20, 20, 255))
KINDS = ["mse", "huber", "symlog", "twohot"]


def twohot(y):
    """scalar -> 255-vector: two adjacent bins non-zero, weights sum to 1."""
    y = y.clamp(BINS[0], BINS[-1])
    k = (torch.bucketize(y, BINS, right=True) - 1).clamp(0, len(BINS) - 2)
    lo, hi = BINS[k], BINS[k + 1]
    w_hi = (y - lo) / (hi - lo)
    out = torch.zeros(len(y), len(BINS))
    out.scatter_(1, k[:, None], (1 - w_hi)[:, None])
    out.scatter_(1, (k + 1)[:, None], w_hi[:, None])
    return out


def out_dim(kind):
    return len(BINS) if kind == "twohot" else 1


def head_loss(kind, f, y):
    """f: network output (n, out_dim); y: targets on the raw scale (n,)."""
    if kind == "mse":
        return 0.5 * ((f[:, 0] - y) ** 2).mean()
    if kind == "huber":
        return F.smooth_l1_loss(f[:, 0], y)  # delta = 1
    if kind == "symlog":
        return 0.5 * ((f[:, 0] - symlog(y)) ** 2).mean()
    logp = F.log_softmax(f, dim=1)
    return -(twohot(y) * logp).sum(dim=1).mean()


def head_read(kind, f):
    """Read the network output as a prediction on the raw scale."""
    if kind in ("mse", "huber"):
        return f[:, 0]
    if kind == "symlog":
        return symexp(f[:, 0])
    return F.softmax(f, dim=1) @ BINS


def run_grad():
    mid = int(BINS.abs().argmin())
    print("bins: n=%d  first=%.3e  middle(index %d)=%.1e  last=%.3e" %
          (len(BINS), BINS[0], mid, BINS[mid], BINS[-1]))
    print("relative spacing of adjacent bins at |y|>>1: %.4f" %
          (float(np.exp(40 / 254) - 1)))
    g = torch.Generator().manual_seed(0)
    for scale in (1e-2, 1.0, 1e2, 1e4, 1e8):
        y = torch.randn(2000, generator=g) * scale
        err = (head_read("twohot", torch.log(twohot(y) + 1e-30)) - y).abs()
        print("twohot roundtrip scale=%.0e  max rel err=%.2e" %
              (scale, float(err.max() / y.abs().max())))
    print()
    print("grad norm wrt head output at init (output layer = 0), one sample")
    print("%-8s" % "y" + "".join("%12s" % k for k in KINDS))
    for y in (1.0, 1e2, 1e4, 1e8):
        row = []
        for kind in KINDS:
            f = torch.zeros(1, out_dim(kind), requires_grad=True)
            head_loss(kind, f, torch.tensor([y])).backward()
            row.append(float(f.grad.norm()))
        print("%-8.0e" % y + "".join("%12.3g" % v for v in row))


def make_task(name, seed):
    """Return h(x): the expected target (before multiplying by scale c)."""
    g = torch.Generator().manual_seed(seed)
    u = torch.randn(8, generator=g)
    v = torch.randn(8, generator=g)
    z = lambda x: x @ u / u.norm()  # standard normal
    s = lambda x: torch.sin(2 * x @ v / v.norm())
    if name == "signed":  # bounded, changes sign
        return lambda x: torch.tanh(z(x)) + 0.5 * s(x)
    if name == "positive":  # value-function-like: positive, smooth
        return lambda x: 1 + 0.5 * torch.tanh(z(x)) + 0.25 * s(x)
    if name == "heavy":  # positive, spans three orders of magnitude
        return lambda x: torch.exp(1.5 * z(x))
    # sparse: reward is 1 with probability h(x), else 0; h(x) in [0.05, 0.5]
    return lambda x: 0.05 + 0.45 * torch.sigmoid(2 * z(x))


TASKS = ["signed", "positive", "heavy", "sparse"]


def fit_one(task, kind, c, seed, steps=3000, bs=256, lr=1e-3):
    h = make_task(task, 100 + seed)  # own seed, apart from init and batches
    torch.manual_seed(seed)
    net = nn.Sequential(nn.Linear(8, 128), nn.SiLU(), nn.Linear(128, 128),
                        nn.SiLU(), nn.Linear(128, out_dim(kind)))
    nn.init.zeros_(net[-1].weight)  # paper: zero-init reward/critic head
    nn.init.zeros_(net[-1].bias)
    opt = torch.optim.Adam(net.parameters(), lr=lr)
    gx = torch.Generator().manual_seed(1000 + seed)  # samples the inputs
    gy = torch.Generator().manual_seed(2000 + seed)  # samples random rewards
    for _ in range(steps):
        x = torch.randn(bs, 8, generator=gx)
        if task == "sparse":
            y = c * (torch.rand(bs, generator=gy) < h(x)).float()
        else:
            y = c * h(x)
        loss = head_loss(kind, net(x), y)
        opt.zero_grad()
        loss.backward()
        opt.step()
    xt = torch.randn(4096, 8, generator=torch.Generator().manual_seed(7))
    with torch.no_grad():
        yt = c * h(xt)  # compare with the expectation, not with one sample
        pred = head_read(kind, net(xt))
    return float((pred - yt).abs().mean() / yt.abs().mean())


def run_fit():
    scales = (1e-2, 1.0, 1e2, 1e4)
    seeds = (0, 1, 2)
    print("metric = mean|pred - E[y]| / mean|E[y]|, mean over %d seeds"
          % len(seeds))
    print("%-9s %-7s" % ("task", "c") + "".join("%14s" % k for k in KINDS))
    for task in TASKS:
        for c in scales:
            row = []
            for kind in KINDS:
                r = [fit_one(task, kind, c, s) for s in seeds]
                row.append("%.3f+-%.3f" % (np.mean(r), np.std(r)))
            print("%-9s %-7.0e" % (task, c) +
                  "".join("%14s" % v for v in row), flush=True)


def run_norm():
    n = 1024
    rng = np.random.default_rng(0)
    base = rng.standard_normal(n)
    print("batch of %d returns ~ N(0,1); a fraction p is replaced by 100" % n)
    print("%-7s %9s %9s %9s   %s" %
          ("p", "std", "max-min", "P95-P5", "(ratio to p=0)"))
    ref = None
    for p in (0, 0.005, 0.01, 0.02, 0.04, 0.05, 0.055, 0.06, 0.08, 0.10):
        r = base.copy()
        k = round(p * n)
        r[:k] = 100.0
        vals = (r.std(), r.max() - r.min(),
                np.percentile(r, 95) - np.percentile(r, 5))
        ref = ref or vals
        print("%-7.3f %9.3f %9.3f %9.3f   %5.1fx %5.1fx %5.1fx" %
              ((p,) + vals + tuple(v / b for v, b in zip(vals, ref))))
    print()
    print("sparse returns: 1 with success rate p, else 0; batch of %d" % n)
    print("%-7s %9s %16s %20s" % ("p", "std", "scale by 1/std",
                                  "scale by 1/max(1,S)"))
    for p in (0.001, 0.005, 0.02, 0.1, 0.5):
        r = np.zeros(n)
        r[:round(p * n)] = 1.0
        S = np.percentile(r, 95) - np.percentile(r, 5)
        print("%-7.3f %9.4f %16.1f %20.2f" %
              (p, r.std(), 1 / r.std(), 1 / max(1.0, S)))


if __name__ == "__main__":
    {"grad": run_grad, "fit": run_fit, "norm": run_norm}[sys.argv[1]]()

Experiment 1: does the gradient size decouple from the target size?

The four heads are squared loss, Huber loss (δ=1\delta=1), symlog squared loss and twohot cross-entropy. The output layer starts at zero (the paper’s recipe for the reward head and the critic), so the network outputs all zeros; we take the gradient of the loss with respect to that output and look at its norm as the target yy varies. Twohot uses 255 bins located at symexp(−20…+20)\mathrm{symexp}(-20\ldots+20) as in Equation 10.

bins: n=255  first=-4.852e+08  middle(index 127)=7.5e-08  last=4.852e+08
relative spacing of adjacent bins at |y|>>1: 0.1706
twohot roundtrip scale=1e-02  max rel err=3.41e-07
twohot roundtrip scale=1e+00  max rel err=5.82e-08
twohot roundtrip scale=1e+02  max rel err=8.16e-08
twohot roundtrip scale=1e+04  max rel err=5.34e-08
twohot roundtrip scale=1e+08  max rel err=7.37e-08

grad norm wrt head output at init (output layer = 0), one sample
y                mse       huber      symlog      twohot
1e+00              1           1       0.693       0.724
1e+02            100           1        4.62       0.765
1e+04          1e+04           1        9.21       0.706
1e+08          1e+08           1        18.4       0.968
Target yySquaredHubersymlogTwohot
1110.6930.724
10210^{2}10014.620.765
10410^{4}10410^{4}19.210.706
10810^{8}10810^{8}118.40.968

How to read it:

  • The squared-loss gradient is just yy: a target of 10810^8 gives a gradient of 10810^8. This is why the paper worries that a squared loss can diverge on large targets.
  • Huber’s gradient is clipped at 1: however large the target, each step can only move a fixed small amount. This is the source of the “stagnation” the paper mentions, and Experiment 2 shows its consequence.
  • The symlog gradient grows like ln⁡(1+y)\ln(1+y), from 0.693 to 18.4: much slower than the squared loss, but it still grows with the scale.
  • The twohot gradient stays between 0.7 and 1. It is the difference between the softmax output and the twohot target, both probability vectors, so its norm is at most 2\sqrt2 whatever the scale of yy.
  • The twohot encoding itself is lossless: encoding random targets at every scale and reading them back as an expectation gives a maximum relative error of at most 3.41e-07, which is float32 rounding. The price is resolution: the bins are equally spaced in symexp space, so the first non-zero bin sits at e40/254−1≈0.1706e^{40/254}-1\approx0.1706, which is also the bin spacing near zero (and the relative spacing of adjacent bins at large values is the same 0.1706). A target much smaller than that is read out with limited precision, as Experiment 2 shows.

Experiment 2: one network, four regression heads

The input x∈R8x\in\mathbb R^8 is standard normal and the target is c⋅h(x)c\cdot h(x), with hh one of four kinds (the functions are in the script):

  • signed: bounded and changes sign, a sum of tanh⁡\tanh and a sine;
  • positive: like a value function, positive and smooth;
  • heavy-tailed: exp⁡(1.5z)\exp(1.5z) where zz is a standard-normal projection of xx; positive and spanning about three orders of magnitude;
  • sparse reward: the reward is cc with probability h(x)∈[0.05,0.5]h(x)\in[0.05,0.5] and 0 otherwise, so it is random and its expectation is c h(x)c\,h(x).

The scale cc is 10−210^{-2}, 1, 10210^2 or 10410^4. The network is an 8-128-128-output SiLU MLP with a zero-initialized output layer, trained for 3000 steps with Adam (learning rate 10−310^{-3}), batch size 256, 3 random seeds. The metric is the mean absolute error between the prediction and the expectation E[y∣x]\mathbb E[y\mid x], divided by the mean absolute value of the expectation (lower is better; the best entry in each row is in bold). The sparse task is scored against the expectation, not against one particular sample.

metric = mean|pred - E[y]| / mean|E[y]|, mean over 3 seeds
task      c                 mse         huber        symlog        twohot
signed    1e-02    0.039+-0.004  0.039+-0.004  0.039+-0.004  0.138+-0.016
signed    1e+00    0.014+-0.002  0.014+-0.001  0.026+-0.003  0.025+-0.003
signed    1e+02    0.025+-0.007  0.010+-0.001  0.146+-0.017  0.020+-0.001
signed    1e+04    0.222+-0.125  0.117+-0.058  0.528+-0.123  0.021+-0.001
positive  1e-02    0.022+-0.001  0.022+-0.001  0.022+-0.001  0.056+-0.001
positive  1e+00    0.007+-0.001  0.007+-0.001  0.009+-0.001  0.016+-0.000
positive  1e+02    0.014+-0.001  0.008+-0.001  0.031+-0.001  0.010+-0.001
positive  1e+04    0.047+-0.003  0.035+-0.005  0.053+-0.003  0.009+-0.000
heavy     1e-02    0.192+-0.054  0.160+-0.049  0.053+-0.015  0.039+-0.002
heavy     1e+00    0.068+-0.010  0.022+-0.003  0.007+-0.001  0.039+-0.011
heavy     1e+02    0.311+-0.045  0.090+-0.025  0.017+-0.000  0.049+-0.016
heavy     1e+04    0.524+-0.011  0.352+-0.030  0.034+-0.001  0.029+-0.007
sparse    1e-02    0.157+-0.050  0.157+-0.050  0.158+-0.051  0.092+-0.002
sparse    1e+00    0.047+-0.005  0.047+-0.005  0.221+-0.025  0.039+-0.007
sparse    1e+02    0.038+-0.005  0.984+-0.001  0.880+-0.004  0.039+-0.007
sparse    1e+04    0.090+-0.003  1.000+-0.000  0.991+-0.001  0.040+-0.008
TaskccSquaredHubersymlogTwohot
signed10−210^{-2}0.039 ± 0.0040.039 ± 0.0040.039 ± 0.0040.138 ± 0.016
signed10.014 ± 0.0020.014 ± 0.0010.026 ± 0.0030.025 ± 0.003
signed10210^{2}0.025 ± 0.0070.010 ± 0.0010.146 ± 0.0170.020 ± 0.001
signed10410^{4}0.222 ± 0.1250.117 ± 0.0580.528 ± 0.1230.021 ± 0.001
positive10−210^{-2}0.022 ± 0.0010.022 ± 0.0010.022 ± 0.0010.056 ± 0.001
positive10.007 ± 0.0010.007 ± 0.0010.009 ± 0.0010.016 ± 0.000
positive10210^{2}0.014 ± 0.0010.008 ± 0.0010.031 ± 0.0010.010 ± 0.001
positive10410^{4}0.047 ± 0.0030.035 ± 0.0050.053 ± 0.0030.009 ± 0.000
heavy-tailed10−210^{-2}0.192 ± 0.0540.160 ± 0.0490.053 ± 0.0150.039 ± 0.002
heavy-tailed10.068 ± 0.0100.022 ± 0.0030.007 ± 0.0010.039 ± 0.011
heavy-tailed10210^{2}0.311 ± 0.0450.090 ± 0.0250.017 ± 0.0000.049 ± 0.016
heavy-tailed10410^{4}0.524 ± 0.0110.352 ± 0.0300.034 ± 0.0010.029 ± 0.007
sparse reward10−210^{-2}0.157 ± 0.0500.157 ± 0.0500.158 ± 0.0510.092 ± 0.002
sparse reward10.047 ± 0.0050.047 ± 0.0050.221 ± 0.0250.039 ± 0.007
sparse reward10210^{2}0.038 ± 0.0050.984 ± 0.0010.880 ± 0.0040.039 ± 0.007
sparse reward10410^{4}0.090 ± 0.0031.000 ± 0.0000.991 ± 0.0010.040 ± 0.008

The number after ± is the standard deviation over the 3 seeds. How to read it:

  1. At small scale (c=10−2c=10^{-2}) the first three heads are nearly identical. In the signed and positive groups, the squared, Huber and symlog errors are exactly the same, a direct consequence of symlog being close to the identity near zero. Twohot is actually the worst (0.138 for signed, 0.056 for positive), because the target is smaller than the position of the first non-zero bin, 0.1706, so the readout lacks resolution.
  2. At large scale (c=104c=10^4) the squared loss and symlog each fail somewhere. The squared loss has an error of 0.524 on heavy-tailed targets and 0.222 on signed ones (standard deviation 0.125 across the 3 seeds); symlog is worst on signed targets (0.528). My explanation for the latter is that when the target changes sign near zero, symlog turns a smooth target into a near-step function that a small network fits badly; this page did not test that explanation separately.
  3. Sparse random rewards are the weak spot of Huber and symlog. For c≥100c\ge100 Huber’s relative error is 0.984 and 1.000, almost exactly “predict 0”. This follows directly: when the target is cc (with probability p<0.5p<0.5) or 0, and c≫1c\gg1, the stationary point of the Huber loss satisfies (1−p)min⁡(f,1)=p(1-p)\min(f,1)=p, that is f∗=p/(1−p)f^*=p/(1-p), independent of cc, while the expectation is cpcp. The optimum of symlog is the mean of ln⁡(1+y)\ln(1+y) mapped back (error 0.880 at c=102c=10^2 and 0.991 at c=104c=10^4), which badly underestimates rare large rewards. The squared loss (0.038, 0.090) and twohot (0.039, 0.040) both predict the expectation and have much smaller errors.
  4. On heavy-tailed targets symlog is the steadiest. At c=1c=1 and c=102c=10^2 symlog is best (0.007, 0.017), while the squared-loss error grows with scale (0.068, 0.311, 0.524); at c=104c=10^4 twohot (0.029) and symlog (0.034) are comparable.
  5. No head wins every row, but twohot has the best worst case. Over the 16 rows the largest error of each head is: squared 0.524, Huber 1.000, symlog 0.991, twohot 0.138. This matches the division of labor in DreamerV3: rewards and returns are random and of unknown magnitude, so they use twohot; deterministic vector observations use symlog.

Experiment 3: percentile return normalization

DreamerV3’s divisor is max⁡(1,S)\max(1,S), where SS is the gap between the 95th and 5th percentiles of the return batch. The script looks at the statistic of a single batch and does not apply the paper’s exponential moving average. Group 1: 1024 returns drawn from N(0,1)\mathcal N(0,1), with a fraction pp replaced by 100; compare the standard deviation, the range and P95−P5P_{95}-P_5 (the multiple relative to p=0p=0 is in parentheses). Group 2: returns are 0 or 1 with success rate pp; compare how much “divide by the standard deviation” and “divide by max⁡(1,S)\max(1,S)” scale the returns up.

batch of 1024 returns ~ N(0,1); a fraction p is replaced by 100
p             std   max-min    P95-P5   (ratio to p=0)
0.000       0.972     6.965     3.035     1.0x   1.0x   1.0x
0.005       7.041   103.899     3.111     7.2x  14.9x   1.0x
0.010       9.886   103.899     3.175    10.2x  14.9x   1.0x
0.020      13.878   103.899     3.290    14.3x  14.9x   1.1x
0.040      19.638   103.899     3.750    20.2x  14.9x   1.2x
0.050      21.788   103.899     4.546    22.4x  14.9x   1.5x
0.055      22.770   103.899   101.527    23.4x  14.9x  33.5x
0.060      23.701   103.899   101.527    24.4x  14.9x  33.5x
0.080      27.175   103.899   101.523    28.0x  14.9x  33.5x
0.100      29.982   103.899   101.523    30.8x  14.9x  33.5x

sparse returns: 1 with success rate p, else 0; batch of 1024
p             std   scale by 1/std  scale by 1/max(1,S)
0.001      0.0312             32.0                 1.00
0.005      0.0697             14.3                 1.00
0.020      0.1384              7.2                 1.00
0.100      0.2995              3.3                 1.00
0.500      0.5000              2.0                 1.00

Group 1:

Outlier share ppStdMax−minP95−P5P_{95}-P_5
0 (baseline)0.9726.9653.035
0.5%7.041 (×7.2)103.899 (×14.9)3.111 (×1.0)
1%9.886 (×10.2)103.899 (×14.9)3.175 (×1.0)
2%13.878 (×14.3)103.899 (×14.9)3.290 (×1.1)
4%19.638 (×20.2)103.899 (×14.9)3.750 (×1.2)
5%21.788 (×22.4)103.899 (×14.9)4.546 (×1.5)
5.5%22.770 (×23.4)103.899 (×14.9)101.527 (×33.5)
6%23.701 (×24.4)103.899 (×14.9)101.527 (×33.5)
8%27.175 (×28.0)103.899 (×14.9)101.523 (×33.5)
10%29.982 (×30.8)103.899 (×14.9)101.523 (×33.5)
  • With only 0.5% of the returns replaced by 100, the standard deviation grows 7.2 times and the range 14.9 times, while P95−P5P_{95}-P_5 changes by a factor of 1.0.
  • P95−P5P_{95}-P_5 barely moves while the outlier share is at most 5% (1.5 times at 5%), and jumps to 33.5 times as soon as it exceeds 5% (5.5%): the 95th percentile then lands inside the pile of outliers. So its breakdown point is exactly 5%, set by the percentile that is used. The paper’s exponential moving average (decay 0.99) smooths such a jump over about 100 updates but does not make it disappear.

Group 2:

Success rate ppStdScale by 1/σ1/\sigmaScale by 1/max⁡(1,S)1/\max(1,S)
0.1%0.0312×32.0×1.00
0.5%0.0697×14.3×1.00
2%0.1384×7.2×1.00
10%0.2995×3.3×1.00
50%0.5000×2.0×1.00
  • At a success rate of only 0.1%, dividing by the standard deviation scales the return of the rare success up by 32.0 times, and the lower the success rate the larger the amplification; this is the paper’s point that normalizing by the standard deviation “can fail under sparse rewards” by amplifying rewards regardless of their size.
  • With max⁡(1,S)\max(1,S) as the divisor, SS is at most 1 in all of these batches, so the scale factor is always 1.00 and the returns are left untouched; that is the role of the floor of 1.

What these experiments show, and what they do not

  • The three experiments support the three design motives of the paper: gradient size decoupled from target size (Experiment 1), predicting random rewards by their expectation regardless of scale (Experiment 2), and a return-normalization divisor that is robust to both outliers and sparsity (Experiment 3).
  • They do not show how much each technique contributes in the complete algorithm; for that, see the paper’s ablation.
  • The data are synthetic, with only 3 seeds, 3000 steps and a fixed learning rate; errors on large targets that have not finished converging might shrink with longer training.
  • Adam is insensitive to the overall scale of the gradient, so no divergence of the squared loss appears here, only larger errors on large targets; in real RL the targets also change during training (non-stationarity), which is harder and was not simulated.
  • The two groups in norm are hand-built, and the 5% breakdown point is set by the 95th and 5th percentiles themselves, not an empirical constant.

Limitations and caveats

  • “One set of hyperparameters” means the algorithm’s hyperparameters. Table 2 lets the replay ratio (32 to 1024), the number of environment instances (1 to 64), the model size (12M or 200M) and the action repeat vary by benchmark; the paper treats these as compute settings, not algorithm hyperparameters.
  • The paper describes the reward predictor’s loss in two ways. The world-model section says the prediction loss trains the decoder and the reward predictor with the symlog squared loss; later text and the appendix say the reward predictor and critic use the symexp twohot loss, and the ablation is “no symexp twohot”. This page follows the latter.
  • Baseline budgets are not equal. On DMLab, IMPALA and R2D2+ use published results at 1B steps, 10 times DreamerV3’s 100M, which favors the baselines; Atari100K has no EfficientZero comparison; the Minecraft IMPALA and Rainbow are the authors’ own tuned versions (Acme implementations with learning rate and entropy scale tuned).
  • Few seeds. DreamerV3 and PPO use 5 seeds per benchmark, ProcGen only 1, BSuite and Minecraft 10 each; the curves show the mean with one standard deviation.
  • Minecraft diamonds are rare. Figure 9 shows that at 100M steps only 0.4% of individual episodes end with a diamond; “every seed found one” means at least once during training. “First” is also limited to the paper’s environment setting (MineRL’s block-breaking action space, modified episode termination). The paper’s related work adds that Voyager reaches a similar depth in the tech tree by calling a language model through an API, but on top of a MineFlayer scripting layer engineered for the game, so the setting differs.
  • The ablation covers 14 tasks, and the paper does not spell out how they were chosen; per-task curves are in the supplementary material.
  • The small experiments here only test the principles. The regression and normalization experiments in the previous section use synthetic data and a small MLP; they are not a reproduction of the full algorithm.

What to take away from this paper

  1. Generality comes from a batch of “scale-free” small designs, not a new network architecture. symlog, twohot, percentile return normalization and free bits each answer the question “what if the magnitude changes?”.
  2. Predicting a random reward means predicting its expectation, not its median or a geometric mean. In the experiments here, the Huber loss slides toward the median and symlog regression toward a geometric-mean-like value; twohot regression, which reads out the expectation, is both unbiased and insensitive to scale.
  3. The key to return normalization is the floor of 1. It leaves small sparse rewards untouched, so a fixed entropy coefficient dominates under sparse rewards and the agent explores more.
  4. The value of the world model is first of all its representation. In the ablation the reconstruction signal matters more than the reward gradients, in line with the idea behind self-supervised pretraining.
  5. Read the results with two distinctions in mind: algorithm hyperparameters versus compute settings, and “a diamond appeared at some point in training” versus “every episode gets a diamond”.

Further reading

FAQ

How is DreamerV3 different from PPO?
PPO is model-free: it updates the policy directly from the data it collects. DreamerV3 first learns a world model from replayed experience, then trains the actor and critic on trajectories that the world model imagines in latent space; the real environment only supplies data. The paper uses a high-quality PPO implementation as a baseline and reports that DreamerV3 with fixed hyperparameters is substantially better in all 8 domains.
What are the symlog transform and twohot regression for?
They make the network indifferent to the scale of what it predicts. symlog(x)=sign(x)·ln(|x|+1) is close to the identity near zero and compresses large values logarithmically; DreamerV3 uses it for vector observations. Twohot regression has the network output a distribution over exponentially spaced bins, trained with cross-entropy and read out as the expectation, so gradient size does not depend on target size; it is used for rewards and the critic. In the small experiment on this page, only twohot kept its relative error below 0.14 in all 16 settings.
Does DreamerV3 really use a single set of hyperparameters?
The algorithm's hyperparameters (the paper's Table 4) are identical on every benchmark, with no annealing, prioritized replay, weight decay or dropout. The compute settings differ by benchmark (Table 2): the replay ratio ranges from 32 to 1024, the number of environment instances from 1 to 64, and the two control benchmarks use a 12M model while the rest use 200M. So the accurate claim is that the algorithm does not need retuning per domain, not that every setting is the same.
How reliable is DreamerV3 at mining diamonds in Minecraft?
With 10 seeds, every run collected at least one diamond within 100M environment steps, while the IMPALA, Rainbow and PPO baselines never did. But at the end of the budget only 0.4% of individual episodes end with a diamond, which the paper itself calls a challenge left for future work.
What does DreamerV3 have to do with large language models?
It is a reinforcement learning algorithm for control and games, with models of 12M to 400M parameters that consume pixels and vectors, not text. The paper's introduction notes that reinforcement learning is also a key ingredient for improving language models beyond their pretraining data. What DreamerV3 contributes is a recipe that makes RL insensitive to reward scale, reward sparsity and input type, and its return normalization and target transforms can be reused in other RL systems.