DreamerV3¶
DreamerV3 learns a model of the environment and trains its policy inside that model. A recurrent world model learns, from replayed sequences, to predict the next latent state, the reward and whether the episode continues; an actor and a critic then learn mostly from trajectories the model imagines.
Paper: Hafner, Pasukonis, Ba and Lillicrap, Mastering Diverse Domains
through World Models, arXiv:2301.04104v2, 2023; Nature, 2025
(arXiv:2301.04104v2). Official code:
danijar/dreamerv3. Ajax reproduces
the code that produced the paper's numbers (commit 2411f7d), plus one
later upstream bug fix (29eb964, the replay context). The
world-model design notes give the full
specification, and deviations.md lists
every version choice and every departure from the reference.
When to use it¶
A world model reuses every transition many times, so DreamerV3 tends to need fewer environment steps than a model-free agent, at a much higher compute cost per step. World models compares it with TD-MPC2, which plans with its model at every step.
| Feature | DreamerV3 |
|---|---|
| Discrete actions | yes |
| Continuous actions | yes, a Gaussian around a tanh-bounded mean, clipped and mapped onto the environment's bounds |
| Memory | built in: the world model is recurrent (memory= is not accepted) |
| Environments | gymnax, Brax, MuJoCo Playground |
| Observations | flat vectors only; the environment must not normalise observations or rewards |
| Several seeds in one call | yes, train(seed=[...]) |
| Extension phases | pretrain, post_update, eval_metrics, observe (the features join the observation the encoder reads and the decoder reconstructs; which extensions run) |
| Resume and checkpoints | yes; a resumed run continues the schedules and the replay, and equals the run left whole |
Example¶
# doc: skip (compiles and trains for about a minute on a CPU; tests/agents/DreamerV3/test_dreamerv3_agent.py covers this path)
from ajax import DreamerV3
from ajax.logging import LoggingConfig
# The smallest preset and a low train ratio, for a quick look on a CPU.
agent = DreamerV3("CartPole-v1", model_size="1m", n_envs=4, train_ratio=32,
batch_size=4, batch_length=16)
logging = LoggingConfig(log_frequency=1_000, backends=())
state, evaluations = agent.train(seed=0, n_timesteps=2_000, num_episode_test=2,
logging_config=logging)
print(evaluations["Train/episodic mean reward"]) # the score the paper reports
print(evaluations["Eval/episodic mean reward"])
The paper's DMC-proprio protocol (Table 2): the 12M model, 16 environments, a train ratio of 512, action repeat 2, and 500K environment frames, which is 250K rows at repeat 2:
# doc: skip (the paper's full budget; benchmarks/world_models/paper_protocol.py runs it)
from ajax import DreamerV3
agent = DreamerV3("CheetahRun", model_size="12m", n_envs=16, train_ratio=512,
action_repeat=2, episode_length=1000)
state, _ = agent.train(seed=0, n_timesteps=250_000) # 500K env frames
Key hyperparameters¶
Every default is the paper-era value. model_size and train_ratio are
those of the reference's dmc_proprio configuration, its one for vector
observations (its defaults block has the 200m widths and a ratio of 32).
| Argument | Default | What it does |
|---|---|---|
n_envs |
16 |
environments stepped in parallel |
model_size |
"12m" |
preset of "1m", "12m", "25m", "50m", "100m", "200m", "400m"; sets units, deter, hidden, classes |
train_ratio |
512 |
replayed steps trained per collected row |
batch_size, batch_length |
16, 64 |
sequences per batch, and their length |
imag_horizon |
15 |
imagined steps per start state |
return_horizon |
333 |
1 / (1 - gamma): sets the discount |
lam |
0.95 |
lambda of the imagined returns |
learning_rate |
4e-5 |
a float or a schedule of the update count; a 1,000-update linear warmup (warmup) multiplies it |
agc, eps |
0.3, 1e-20 |
adaptive gradient clipping, and LaProp's epsilon |
actent |
3e-4 |
actor entropy scale |
free_nats |
1.0 |
free bits of the KL losses |
dyn_scale, rep_scale |
1.0, 0.1 |
dynamics and representation loss scales |
replay_capacity |
5_000_000 |
rows kept, over all environments |
replay_on_host |
False |
keep the stored latents in pinned host memory instead of the accelerator's |
episode_length, action_repeat |
1000, 1 |
simulator steps per episode and per agent step, on Brax and Playground (Environments) |
The other arguments (network depths, bins, unimix, the other loss
scales, the slow critic, the return normaliser) are in the API
below.
Presets¶
DreamerV3.preset("DMC", env_id) builds the DMC-proprio configuration
above, the reference's dmc_proprio (configs.yaml:44, :84,
:232-236 at 29eb964; Presets):
model_size="12m", train_ratio=512, n_envs=16 and action_repeat=2.
The reference's other domains (Atari, Crafter, DMLab, Procgen) observe
images, which Ajax's DreamerV3 does not encode yet.
Differences from the reference¶
Each is in deviations.md, under its number.
- Synchronous, in float32 (D1, D3, D4). The reference acts and trains asynchronously, and computes in bfloat16.
- One decoder head for the flat observation vector (D5), where the reference has one per observation key; the loss is the same.
- Everything checkpointed and seeded (D2, D6).
- The two-hot expectation is computed in an exact form (D22). The reference's form adds noise to early predictions under JIT, which measurably changes the early actor entropy.
- The replay keeps one ring per environment, where the reference keeps one first-in first-out store over all its workers (D27).
- The DMC tasks run on MuJoCo Playground's MJX ports, whose physics differ from dm_control's (E18), so comparisons with the published curves are approximate.
Notes¶
- What
n_timestepscounts. One row per environment per vector step, reset rows included, as the reference'sstepdoes.env_frames = rows * action_repeatis logged next to it. - The score. The paper reports the returns of the stochastic policy's
training episodes, logged as
Train/episodic mean reward. The evaluation also samples its actions, since the reference has no deterministic mode. - Actions. Continuous actions are clipped to
[-1, 1]and mapped onto the environment's bounds, as the reference'sClipActionandNormalizeActionwrappers do. - Replay memory. Each row stores the observation, the action, the
reward, the flags and the posterior latent: about 8.3 KB at 12M on a
24-dimensional observation, so the DMC protocol's 250K rows take about
2.1 GB per seed (3.2 GB with the training step's working set).
agent.replay_bytes_per_seedgives the figure aftertrain. Each environment's ring keepsmin(ceil(replay_capacity / n_envs), rows per env of the run)rows, sized again by everytraincall, so that a run split into resumed calls keeps the replay of the run left whole. replay_on_host=True. The posterior latents are almost all of a row; with this option they stay in pinned host memory and the device holds little more than the working set. The results are the same, bit for bit, and each update is a little slower. XLA caps pinned host memory at 64 GB by default: setXLA_PJRT_GPU_HOST_MEMORY_LIMIT_GBhigher for more.- Recompilation. Widths, depths, counts,
bins,imag_horizon,batch_size,batch_length,train_ratioandreplay_capacityfix the compiled program; changing one recompiles.
Results¶
On a CPU, with the 1M preset and 20,000 rows, Pendulum swings up from 12,000 rows on (final evaluation -222, against about -1,200 at the start). On CartPole, Ajax was compared with the reference code itself on the same protocol, over three pre-registered rounds. Once both used the same two-hot expectation, the training statistics' seed ranges overlapped the reference's in at least 52 of 58 windows, and all five Ajax seeds passed the CartPole check that followed, as did all five of the reference's. PERFORMANCE_REPORT.md has the full account. The GPU validation against the published DMC curves is specified in VALIDATION.md and has not been run yet.
The probes (tests/probing) train DreamerV3 briefly on tiny environments
with known answers: discounting, a continuous advantage, and a risky or
safe choice it can only weigh in imagination.
API¶
ajax.agents.DreamerV3.DreamerV3.DreamerV3
dataclass
¶
DreamerV3(
env_id,
*,
n_envs=16,
env_params=None,
weight_decay=0.0,
episode_length=1000,
action_repeat=1,
extensions=(),
model_size="12m",
units=None,
deter=None,
hidden=None,
classes=None,
stoch=32,
blocks=8,
enc_layers=3,
dec_layers=3,
rew_layers=1,
con_layers=1,
bins=255,
free_nats=1.0,
unimix=0.01,
dyn_scale=1.0,
rep_scale=0.1,
rec_scale=1.0,
rew_scale=1.0,
con_scale=1.0,
actor_layers=3,
critic_layers=3,
actor_unimix=0.01,
actor_scale=1.0,
critic_scale=1.0,
repval_scale=0.3,
imag_horizon=15,
return_horizon=333,
lam=0.95,
repval_lam=0.95,
actent=0.0003,
slowreg=1.0,
slow_rate=0.02,
retnorm_rate=0.01,
retnorm_limit=1.0,
minstd=0.1,
maxstd=1.0,
learning_rate=4e-05,
agc=0.3,
agc_pmin=0.001,
beta1=0.9,
beta2=0.999,
eps=1e-20,
warmup=1000,
train_ratio=512,
batch_size=16,
batch_length=64,
replay_capacity=5000000,
replay_on_host=False,
)
Bases: OwnReplayAgent
DreamerV3, paper-era (2411f7d + 29eb964), for vector observations and either action space (the module's tick).
Every hyperparameter of the world model, the actor-critic and the optimiser (weight_decay included) is the DreamerV3Config field of the same name and default, documented there; setup builds model_config from them, the widths left None taking the model_size preset's. The env must not normalise observations or rewards.
model_size and train_ratio default to the reference's dmc_proprio block, its config for vector observations (29eb964 configs.yaml:232-235: size12m, train_ratio 512), not to its defaults block (:113 the 200m widths, :52 train_ratio 32); every other default is that block's.
replay_bytes_per_seed
property
¶
Bytes of the resolved replay rings of one seed (0 before).
prepare_replay ¶
The replay of a call ending at tick end_tick, one ring of C rows per env (count_ring_rows), and the state it resumes from (DESIGN.md sections 5.5, 5.6, 6.3). A fresh run sizes the ring from its own length and records it, but for a 0-tick one (a checkpoint skeleton), which takes the ring the latest run recorded (the minimal ring before any) so that its shapes are that run's. A resumed run grows the state's ring to the uninterrupted run's (size_ring) and records it.
set_compute_dtype ¶
The model's layers, recurrent state and stored latents compute in dtype (DreamerV3Config.compute_dtype).
collect ¶
Act and store one row per env (driver.py:55-81, replay.py:97-144).
tick is the absolute, unbatched tick index (the scan input, offset on resume): the row of every env written now is the tick-th of its stream. Returns the state and tick, which locates the replay's newest rows for the tick's updates (update, after the tick's rows: deviation D3).
update ¶
One training step on a fresh batch, then the write-back.
tick is the absolute, unbatched tick whose rows were added last: the replay holds tick + 1 rows per env. The batch pops the online queue and fills up uniformly (StreamReplay.sample); the learner's step (Algorithm J: replay context, joint gradient, LaProp, slow critic) uses fresh noise; its posterior latents of the trained rows are written back at once (synchronous, deviation D1). The loop folds the extensions' post_update phase after it.
evaluation_metrics ¶
Sampled evaluation episodes from a zero carry (is_first first).
The reference's policy samples in every mode (dreamerv3_spec 7.3); ajax.evaluate.evaluate_policy runs one episode in each of num_episode_test freshly reset envs with the training action repeat, from key: fresh at each evaluation (ajax.log.evaluation_keys), so each draws new initial states and action noise.
policy_parts ¶
As its evaluation acts: the row collector's sampling policy, from a zero carry.
report ¶
The logged training metrics: house keys, env_frames, losses.
Train/episodic mean reward is the rolling mean of the training
episodes' returns, the reference's score (dreamerv3_spec 7.3, 7.7);
env_frames = rows * action_repeat the reference's x-axis, its step
clock (rows, reset rows included) times the repeat (2411f7d
dreamerv3/main.py:124-132, embodied/core/logger.py:32;
DESIGN.md section 2): one row per episode above the simulator's
frames; Train/n_updates the training steps so far; Train/
restart_train_metrics ¶
The training metrics' means restart after each log (train.py:113-121).
make_policy ¶
observe_and_act with the agent's current parameters bound: the row collector's policy and the evaluation's.