T RANSFORMER - BASED W ORLD M ODELS A RE H APPY W ITH 100 K I NTERACTIONS
A BSTRACT
Deep neural networks have been successful in many reinforcement learning settings. However, compared to human learners they are overly data hungry.
To build a sample-efficient world model, we apply a transformer to real-world episodes in an autoregressive manner: not only the compact latent states and the taken actions but also the experienced or predicted rewards are fed into the transformer, so that it can attend flexibly to all three modalities at different time steps. The transformer allows our world model to access previous states directly, instead of viewing them through a compressed recurrent state.
By utilizing the Transformer-XL architecture, it is able to learn long-term dependencies while staying computationally efficient.
Our transformer-based world model (TWM) generates meaningful, new experience, which is used to train a policy that outperforms previous model-free and model-based reinforcement learning algorithms on the Atari 100k benchmark.
I NTRODUCTION
Deep reinforcement learning methods have shown great success on many challenging decision making problems.
Notable methods include DQN (Mnih et al., 2015), PPO (Schulman et al., 2017), and MuZero (Schrittwieser et al., 2019).
However, most algorithms require hundreds of millions of interactions with the environment, whereas humans often can achieve similar results with less than 1% of these interactions, i.e., they are more sample-efficient.
The large amount of data that is necessary renders a lot of potential real world applications of reinforcement learning impossible.
Recent works have made a lot of progress in advancing the sample efficiency of RL algorithms: model-free methods have been improved with auxiliary objectives (Laskin et al., 2020b), data augmentation (Yarats et al., 2021, Laskin et al., 2020a), or both (Schwarzer et al., 2021).
Model-based methods have been successfully applied to complex image-based environments and have either been used for planning, such as EfficientZero (Ye et al., 2021), or for learning behaviors in imagination, such as SimPLe (Kaiser et al., 2020). o t − ℓ
[Equation]
Transformer
A promising model-based concept is learning in imagination (Ha & Schmidhuber, 2018; Kaiser et al., 2020; Hafner et al., 2020; Hafner et al., 2021): instead of learning behaviors from the collected experience directly, a generative model of the environment dynamics is learned in a (self-)supervised manner.
Such a so-called world model can create new trajectories by iteratively predicting the next state and reward.
This allows for potentially indefinite training data for the reinforcement learning algorithm without further interaction with the real environment.
Due to the nature of deep neural networks, a world model can generalize to new, unseen situations, which has the potential to drastically increase the sample efficiency.
This can be illustrated by a simple example: in the game of
Pong, the paddles and the ball move independently.
A successfully trained world model is able to imagine trajectories with paddle and ball configurations that have never been observed before, which enables learning of improved behaviors.
In this paper, we propose to model the world with transformers (Vaswani et al., 2017), which have significantly advanced the field of natural language processing and have been successfully applied to computer vision tasks (Dosovitskiy et al., 2021).
A transformer is a sequence model consisting of multiple self-attention layers with residual connections.
In each self-attention layer the inputs are mapped to keys, queries, and values.
The outputs are computed by weighting the values by the similarity of keys and queries.
Combined with causal masking, which prevents the self-attention layers from accessing future time steps in the training sequence, transformers can be used as autoregressive generative models.
The Transformer-XL architecture (Dai et al., 2019) is much more computationally efficient than vanilla transformers at inference time and introduces relative positional encodings, which remove the dependence on absolute time steps.
Our contributions: The contributions of this work can be summarized as follows: We present a new autoregressive world model based on the Transformer-XL (Dai et al., 2019) architecture and a model-free agent trained in latent imagination.
Running our policy is computationally efficient, as the transformer is not needed at inference time.
This is in contrast to related works (Hafner et al., 2020; 2021; Chen et al., 2022) that require the full world model during inference.
Our world model is provided with information on how much reward has already been emitted by feeding back predicted rewards into the world model.
As shown in our ablation study, this improves performance. We rewrite the balanced KL divergence loss of Hafner et al. (2021) to allow us to fine-tune the relative weight of the involved entropy and cross-entropy terms.
We introduce a new thresholded entropy loss that stabilizes the policy’s entropy during training and hereby simplifies the selection of hyperparameters that behave well across different games (see Figure 7). We propose a new effective sampling procedure for the growing dataset of experience, which balances the training distribution to shift the focus towards the latest experience. We demonstrate the efficacy of this procedure with an ablation study.
We compare our transformer-based world model (TWM) on the Atari 100k benchmark with recent sample-efficient methods and obtain excellent results.
Moreover, we report empirical confidence intervals of the aggregate metrics as suggested by Agarwal et al.
M ETHOD
We consider a partially observable Markov decision process (POMDP) with discrete time steps t ∈ N , scalar rewards r t ∈ R , high-dimensional image observations o t ∈ R h × w × c , and discrete actions a t ∈ { 1 , . . .
, m } , which are generated by some policy a t ∼ π ( a t | o 1: t , a 1: t − 1 ) , where o 1: t and a 1: t − 1 denote the sequences of observations and actions up to time steps t and t − 1 , respectively.
Episode ends are indicated by a boolean variable d t ∈ { 0 , 1 } .
Observations, rewards, and episode ends are jointly generated by the unknown environment dynamics o t , r t , d t ∼ p ( o t , r t , d t | o 1: t − 1 , a 1: t − 1 ) .
The goal is to find a policy π that maximizes the expected sum of discounted rewards E π (cid:2)(cid:80) ∞ t =1 γ t − 1 r t (cid:3) , where γ ∈ [0 , 1) is the discount factor.
Learning in imagination consists of three steps that are repeated iteratively: learning the dynamics, learning a policy, and interacting in the real environment.
In this section, we describe our world model and policy, concluding with the training procedure.
2. W ORLD M ODEL
Our world model consists of an observation model and a dynamics model, which do not share parameters.
Figure 1 illustrates our combined world model architecture.
Observation Model: The observation model is a variational autoencoder (Kingma & Welling, 2014), which encodes observations o t into compact, stochastic latent states z t and reconstructs the observations with a decoder, which in our case is only required to obtain a learning signal for z t : Observation encoder:
[Equation]
Observation [Equation] [Equation] We adopt the neural network architecture of DreamerV2 (Hafner et al., 2021) with slight modifications for our observation model.
Thus, a latent state z t is discrete and consists of a vector ofcategorical variables with 32 categories.
The observation decoder reconstructs the observation and predicts the means of independent standard normal distributions for all pixels.
In contrast to Hafner et al. (2021), the role of the observation model is to capture only non-temporal information about the current time step. However, we include short-time temporal information, since a single observation o t consists of four frames (aka frame stacking, see also Section 2.2).
Autoregressive Dynamics Model: The dynamics model predicts the next time step conditioned on the history of its past predictions.
The backbone is a deterministic aggregation model f ψ which computes a deterministic hidden state h t based on the history of the ℓ previously generated latent states, actions, and rewards.
Predictors for the reward, discount, and next latent state are conditioned on the hidden state.
The dynamics model consists of these components:
Aggregation model:
[Equation]
Reward
[Equation]
[Equation]
Discount predictor:
[Equation] Latent state predictor: [Equation] The aggregation model is implemented as a causally masked Transformer-XL (Dai et al., 2019), which enhances vanilla transformers (Vaswani et al., 2017) with a recurrence mechanism and relative positional encodings.
With these encodings, our world model learns the dynamics independent of absolute time steps.
Following Chen et al.
(2021), the latent states, actions, and rewards are sent into modality-specific linear embeddings before being passed to the transformer.
Due to the three modalities (latent states, actions, rewards), the number of input tokens is 3 ℓ − 1 , as the last reward is not part of the input.
We consider the outputs of the action modality as the hidden states and disregard the outputs of the other two modalities (see Figure 1; orange boxes vs. gray boxes in the top row).
The latent state, reward, and discount predictors are implemented as multilayer perceptrons (MLPs) and compute the parameters of a vector of independent categorical distributions, a normal distribution, and a Bernoulli distribution, respectively, conditioned on the deterministic hidden state.
The next state is determined by sampling from p ψ (ˆ z t +1 | h t ) .
The reward and discount are determined by the mean of p ψ (ˆ r t | h t ) and p ψ (ˆ γ t | h t ) , respectively.
Due to these design choices, our world model combines the benefits of transformers and recurrent neural networks, i.e.:
The dynamics model is autoregressive and has direct access to its previous outputs.
Training is more efficient compared with RNNs, since sequences are processed in parallel.
Inference is efficient due to the caching of previous outputs (Dai et al., 2019).
Long-term dependencies can be captured by the recurrence mechanism.
We want to provide an intuition on why a fully autoregressive dynamics model is beneficial: first, the direct access to previous latent states enables to model more complex dependencies between them, compared with RNNs, which only see them indirectly through a compressed recurrent state.
This also has the potential to make inference more robust, since degenerate predictions can be ignored more easily.
Second, because the model sees which rewards it has produced previously, it can react to its own predictions.
This is even more significant when the rewards are sampled from a probability distribution, since the introduced noise cannot be observed without autoregression.
Loss Functions: The observation model can be interpreted as a variational autoencoder with a temporal prior, which is provided by the latent state predictor.
The goal is to keep the distributions of the encoder and the latent state predictor close to each other, while slowly adapting to new observations and dynamics. Hafner et al. (2021) apply a balanced KL divergence loss, which lets them control which of the two distributions should be penalized more. To control the influences of its subterms more precisely, we disentangle this loss and obtain a balanced cross-entropy loss that computes the cross-entropy H ( p ϕ ( z t +1 | o t +1 ) , p ψ (ˆ z t +1 | h t )) and the entropy H ( p ϕ ( z t | o t )) explicitly.
Our derivation can be found in Appendix A.1. We call the cross-entropy term for the observation model the consistency loss , as its purpose is to prevent the encoder from diverging from the dynamics model.
The entropy regularizes the latent states and prevents them from collapsing to one-hot distributions. The observation decoder is optimized via negative log-likelihood, which provides a rich learning signal for the latent states. In summary, we optimize a self-supervised loss function for the observation model that is the expected sum over the decoder loss, the entropy regularizer and the consistency loss
[Equation]
where the hyperparameters α 1 , α 2 ≥ 0 control the relative weights of the terms.
For the balanced cross-entropy loss, we also minimize the cross-entropy in the loss of the dynamics model, which is how we train the latent state predictor.
The reward predictor and discount predictor are optimized via negative log-likelihood.
This leads to a self-supervised loss function for the dynamics model [Equation] [Equation]
[Equation]
with coefficients β 1 , β 2 ≥ 0 and where γ t = 0 for episode ends ( d t = 1 ) and γ t = γ otherwise.
P OLICY
Our policy π θ ( a t | ˆ z t ) is trained on imagined trajectories using a mainly standard advantage actorcritic (Mnih et al., 2016) approach.
We train two separate networks: an actor a t ∼ π θ ( a t | ˆ z t ) with parameters θ and a critic v ξ (ˆ z t ) with parameters ξ . We compute the advantages via Generalized
Advantage Estimation (Schulman et al., 2016) while using the discount factors predicted by the world model ˆ γ t instead of a fixed discount factor for all time steps.
As in DreamerV2 (Hafner et al., 2021), we weight the losses of the actor and the critic by the cumulative product of the discount factors, in order to softly account for episode ends.
Thresholded Entropy Loss: We penalize the objective of the actor with a slightly modified version of the usual entropy regularization term (Mnih et al., 2016).
Our penalty normalizes the entropy and only takes effect when the entropy falls below a certain threshold
[Equation]
where 0 ≤ Γ ≤ 1 is the threshold hyperparameter, H ( π θ ) is the entropy of the policy, m is the number of discrete actions, and ln( m ) is the maximum possible entropy of the categorical action distribution.
By doing this, we explicitly control the percentage of entropy that should be preserved across all games independent of the number of actions.
This ensures exploration in the real environment and in imagination without the need for ϵ -greedy action selection or changing the temperature of the action distribution. We also use the same stochastic policy when evaluating our agent in the experiments.
The idea of applying a hinge loss to the entropy was first introduced by Pereyra et al.
(2017) in the context of supervised learning. In Section 3.2 we show the effect of using a threshold on the entropy.
[Figure]
i n
[Figure]
Choice of Policy Input: The policy computes an action distribution π θ ( a t | x t ) given some view x t of the state. E.g., this view x t could be o t , z t or h t .
This view has to be chosen carefully, since it can have a significant impact on the performance of the policy and it affects the design choices for the world model.
Using x t = o t is relatively stable even with imperfect reconstructions ˆ o t , as the underlying distribution of observations p ( o ) does not change during training. However, it is also less computationally efficient, since it requires reconstructing the observations during imagination and additional convolutional layers for the policy.
Using x t = z t is slightly less stable, as the policy has to adopt to the changes of the distribution p ( z | o ) during training.
Nevertheless, the entropy regularizer and consistency loss in Equation (3) stabilize the distribution.
Using x t = [ z t , h t ] provides the agent with a summary of the history of experience, but it also adds the burden of running the transformer at inference time, i.e., when applied to the real environment.
Model-free agents already perform well on most Atari games when using a stack of the most recent frames (e.g., Mnih et al. 2015; Schulman et al. 2017).
Therefore, we choose x t = z t and apply frame stacking in order to incorporate short-time information directly into the latent states.
As a consequence, our policy is computationally efficient at training time (no reconstructions during imagination) and at inference time (no transformer when running in the real environment).
2. T RAINING
As is usual for learning with world models, we repeatedly (i) collect experience in the real environment with the current policy, (ii) improve the world model using the past experience, (iii) improve the policy using new experience generated by the world model.
During training we build a dataset D =
[( o 1 , a 1 , r 1 , d 1 ) , . .
, ( o T , a T , r T , d T )] of the collected experience.
To train the world model, N sequences of length ℓ are sampled from D and are used to estimate the loss functions in Equation (3) and Equation (4).
After each update of the world model, we generate M new trajectories of length H with the dynamics model and update the policy using standard model-free objectives, as explained in Section 2.2.
In Algorithm 1 we present pseudocode for training the world model and the actor-critic agent.
Balanced Dataset Sampling: Since the dataset grows slowly during training, uniform sampling of trajectories focuses too heavily on early experience, which can lead to overfitting especially in the low data regime.
Therefore, we keep visitation counts v 1 , . .
. , v T , which are incremented every time an entry is sampled as start of a sequence.
These counts are converted to probabilities using the softmax function
[Equation]
(6) where τ > 0 is a temperature hyperparameter.
With our sampling procedure, new entries in the dataset are oversampled and are selected more often than old ones.
Setting τ = ∞ restores uniform sampling as a special case, whereas reducing τ increases the amount of oversampling.
See Figurefor a comparison.
We empirically show the effectiveness in Section 3.2.
[Figure]
E XPERIMENTS
To compare data-efficient reinforcement learning algorithms, Kaiser et al.
(2020) proposed the Atari 100 k benchmark, which uses a subset of 26 Atari games from the Arcade Learning Environment (Bellemare et al., 2013) and limits the number of interactions per game to 100 k. This corresponds to 400 k frames (due to frame skipping) or roughly 2 hours of real-time gameplay, which istimes less than the commonly used 200 million frames (e.g., Mnih et al. 2015; Schulman et al. 2017;
Hafner et al. 2021). We compare our method with five strong competitors on the Atari 100k benchmark: (i) SimPLe (Kaiser et al., 2020) implements a world model as an action-conditional video prediction model and trains a policy with PPO (Schulman et al., 2017), (ii) DER (van Hasselt et al., 2019) is a variant of Rainbow (Hessel et al., 2018) fine-tuned for sample efficiency,
(iii) CURL (Laskin et al., 2020b) improves representations using contrastive learning as an auxiliary task and is combined with DER, (iv) DrQ (Yarats et al., 2021) improves DQN by averaging Q-value estimates over multiple data augmentations of observations, and (v) SPR (Schwarzer et al., 2021) forces representations to be consistent across multiple time steps and data augmentations by extending Rainbow with a selfsupervised consistency loss.
3. R ESULTS
We follow the advice of Agarwal et al.
(2021) who found significant discrepancies between reported point estimates of mean (and median) scores and a thorough statistical analysis that includes statistical uncertainty.
Thus, we report confidence interval estimates of the aggregate metrics median, interquartile mean (IQM), mean, and optimality gap in Figure 3 and performance profiles in Figure 4.
The metrics are computed on human normalized scores, which are calculated as (score agent - score random)/(score human - score random) .
We report the unnormalized scores per game in Table 1.
We compare with new scores for DER, CURL, DrQ, and SPR that were evaluated on 100 runs and provided by Agarwal et al.
They report scores for the improved DrQ( ε ), which is DrQ evaluated with standard ε -greedy parameters.
We performruns per game and compute the average score over 100 episodes at the end of training for each run.
TWM shows a significant improvement over previous approaches in all four aggregate metrics and brings the optimality gap closer to zero.
3. A BLATION S TUDY
Uniform Sampling:
To show the effectiveness of the sampling procedure described in Section 2.3, we evaluate three games with uniform dataset sampling, which is equivalent to setting τ = ∞ in Equation (6).
In Figure 5 we show that balanced dataset sampling significantly improves the performance in these games.
At the end of training, the dynamics loss from Equation (4) is lower when applying balanced sampling.
One reason might be that the world model overfits on early training data and performs bad in later stages of training.
[Figure]
[Table]
No Rewards: As described in Section 2.1, the predicted rewards are fed back into the transformer. In Figure 6 we show on three games that this can significantly increase the performance. In some games the performance is equivalent, probably because the world model can make correct predictions solely based on the latent states and actions
[Table] [Figure] [Figure]
u m a n N o r m a li z e d S c o r e [Figure]
Thresholded Entropy Loss: In Figure 7 we compare (i) our thresholded entropy loss for the policy (see Section 2.2) with (ii) the usual entropy penalty. For (i) we use the same hyperparameters as in our main experiments [Figure]
i [Figure] e., η = 0 . 01 and Γ =
[Figure] For (ii) we set η = 0 . 001 and Γ = 1 . 0 , effectively disabling the threshold. Without a threshold
[Figure] the entropy is more likely to either collapse or diverge. This cannot be solved by adjusting the penalty coefficient η alone, since it would increase or decrease the entropy in all games. [Figure]
R ELATED W ORK
The Dyna architecture (Sutton, 1991) introduced the idea of training a model of the environment and using it to further improve the value function or the policy.
Ha & Schmidhuber (2018) introduced the notion of a world model , which tries to completely imitate the environment and is used to generate experience to train a model-free agent.
They implement a world model as a VAE (Kingma & Welling, 2014) and an RNN and learn a policy in latent space with an evolution strategy. With
SimPLe, Kaiser et al. (2020) propose an iterative training procedure that alternates between training the world model and the policy.
Their policy operates on pixel-level and is trained using PPO (Schulman et al., 2017).
Hafner et al. (2020) present Dreamer and implement a world model as a stochastic RNN that splits the latent state in a stochastic part and a deterministic part; this idea was first introduced by Hafner et al., 2019.
This allows their world model to capture the stochasticity of the environment and simultaneously facilitates remembering information over multiple time steps.
Robine et al.
(2020) use a VQ-VAE to construct a world model with drastically lower number of parameters.
DreamerV2 (Hafner et al., 2021) achieves great performance on the Atari 50 M benchmark after making some changes to Dreamer, the most important ones being categorical latent variables and an improved objective.
Another direction of model-based reinforcement learning is planning, where the model is used at inference time to improve the action selection by looking ahead several time steps into the future.
The most prominent work is MuZero (Schrittwieser et al., 2019), where a learned sequence model of rewards and values is combined with Monte-Carlo Tree Search (Coulom, 2006) without learning explicit representations of the observations.
MuZero achieves impressive performance on the Atari 50 M benchmark, but it is also computationally expensive and requires significant engineering effort.
EfficientZero (Ye et al., 2021) improves MuZero and achieves great performance on the Atari 100k benchmark.
Transformers (Vaswani et al., 2017) advanced the effectiveness of sequence models in multiple domains, such as natural language processing and computer vision (Dosovitskiy et al., 2021).
Recently, they have also been applied to reinforcement learning tasks.
The Decision Transformer (Chen et al., 2021) and the Trajectory Transformer (Janner et al., 2021) are trained on an offline dataset of trajectories.
The Decision Transformer is conditioned on states, actions, and returns, and outputs optimal actions.
The Trajectory Transformer trains a sequence model of states, actions, and rewards, and is used for planning.
Chen et al.
(2022) replace the RNN of Dreamer with a transformer and outperform Dreamer on Hidden Order Discovery tasks.
However, their transformer has no access to previous rewards and they do not evaluate their method on the Atari 100k benchmark.
Moreover, their policy depends on the outputs of the transformer, leading to higher computational costs during inference time.
C ONCLUSION
In this work, we discuss a reinforcement learning approach using transformer-based world models. Our method (TWM) outperforms previous model-free and model-based methods in terms of human normalized score on the 26 games of the Atari 100k benchmark.
By using the transformer only during training, we were able to keep the computational costs low during inference, i.e., when running the learned policy in a real environment. We show how feeding back the predicted rewards into the transformer is beneficial for learning the world model.
Furthermore, we introduce the balanced cross-entropy loss for finer control over the trade-off between the entropy and cross-entropy terms in the loss functions of the world model. A new thresholded entropy loss effectively stabilizes the entropy of the policy. Finally, our novel balanced sampling procedure corrects issues of naive uniform sampling of past experience.
A A PPENDIX A. D ERIVATION OF B ALANCED C ROSS -E NTROPY L OSS
Hafner et al.
(2021) propose to use a balanced KL divergence loss to jointly optimize the observation encoder q θ and state predictor p θ with shared parameters θ , i.e., [Equation] ) where sg ( · ) denotes the stop-gradient operation and λ ∈ [0 , 1] controls how much the state predictor adapts to the observation encoder and vice versa. By using the identity D KL ( q ∥ p ) =
H ( q, p ) − H ( q ) , where H ( q, p ) is the cross-entropy of distribution p relative to distribution q , we show that our loss functions lead to the same gradients as the balanced KL objective, but with finer control over the individual components: [Equation] [Equation]
) since ∇ θ H ( sg ( q θ ))
= 0 and by defining λ 1 = λ and λ 2 = 1 − λ and λ 3 = 1 − λ .
In this form, we have control over the cross-entropy of the state predictor relative to the observation encoder and vice versa.
Moreover, we explicitly penalize the entropy of the observation encoder, instead of being entangled inside of the KL divergence.
As common in the literature, we define the loss function by omitting the gradient in Equation (10), so that automatic differentiation computes this gradient.
For our world model, we split the objective into two loss functions, as the observation encoder and state predictor have separate parameters, yielding Equations (3) and (4).
A. A DDITIONAL T RAINING D ETAILS
In Algorithm 1 we present pseudocode for training the world model and the actor-critic agent.
We use the SiLU activation function (Elfwing et al., 2018) for all models.
In Table 2 we summarize all hyperparameters that we used in our experiments.
In Table 3 we provide the number of parameters of our models.
Pretraining for Better Initialization: During training we need to correctly balance the amount of world model training and policy training, since the policy has to “keep up” with the distributional shift of the latent space.
However, we can spend some extra training time on the world model with pre-collected data (included in the 100k interactions) at the beginning of training in order to obtain a reasonable initialization for the latent states.
Algorithm 1 Training the world model and the actor-critic agent.
function train world model( ) // sample sequences of observations, // rewards, actions and discounts o,a,r,d = sample from dataset() z = encode(o) o hat = decode(z) h
= transformer(z,a,r) r hat,d hat,z hat =
predict(h) //
optimize world model via // self-supervised learning optim observation(o,z,o hat,z hat) optim dynamics(r,d,z,r hat,d hat,z hat) //
z will be used for imagination return z function train actor critic(z) //
imagine trajectories of states, // rewards, actions and discounts; // use z as starting point imag =
[z] for t = 0 until H do a = actor(z) imag.append(a)
h
=transformer(imag)r,d,z=predict(h) imag.extend([r,d,z]) //
optimize actor-critic via // reinforcement learning optim actor critic(imag)
[Table]
[Table]