T RANSFORMERS
ARE
M ETA -R EINFORCEMENT
L EARNERS
Anonymous authors
Paper under double-blind review
A BSTRACT
The transformer architecture and variants presented a remarkable success across many machine learning tasks in recent years.
This success is intrinsically related to the capability of handling long sequences and the presence of contextdependent weights from the attention mechanism.
We argue that these capabilities suit the central role of a Meta-Reinforcement Learning algorithm.
Indeed, a metaRL agent needs to infer the task from a sequence of trajectories.
Furthermore, it requires a fast adaptation strategy to adapt its policy for a new task - which can be achieved using the self-attention mechanism.
In this work, we present TrMRL ( Tr ansformers for M eta- R einforcement
L earning), a meta-RL agent that mimics the memory reinstatement mechanism using the transformer architecture.
It associates the recent past of working memories to build an episodic memory recursively through the transformer layers.
This memory works as a proxy to the current task, and we condition a policy head on it.
We conducted experiments in high-dimensional continuous control environments for locomotion and dexterous manipulation.
Results show that TrMRL achieves or surpasses state-of-the-art performance, sample efﬁciency, and out-of-distribution generalization in these environments.
I NTRODUCTION
In recent years, the Transformer architecture (Vaswani et al., 2017) achieved exceptional performance on many machine learning applications, especially for text (Devlin et al., 2019; Raffel et al., 2020) and image processing (Dosovitskiy et al., 2021b; Caron et al., 2021; Yuan et al., 2021).
This intrinsically relates to its few-shot learning nature Brown et al.
(2020a): the attention weights work as context-dependent parameters, inducing better generalization.
Furthermore, this architecture parallelizes token processing by design.
This capability avoids the vanishing gradients problem, very common for recurrent models.
As a result, they can handle longer sequences more efﬁciently.
This work argues that these two capabilities are essential for a Meta-Reinforcement Learning (metaRL) agent.
We propose TrMRL ( Tr ansformers for M eta- R einforcement
L earning), a memorybased meta-Reinforcement Learner which uses the transformer architecture to formulate the learning process.
It works as a memory reinstatement mechanism (Rovee-Collier, 2012) during learning, associating recent working memories to create an episodic memory which is used to contextualize the policy.
Figure 1 illustrates the process.
We formulated each task as a distribution over working memories.
TrMRL associates these memories using self-attention blocks to create a task representation in each head.
These task representations are combined in the position-wise MLP to create an episodic output (which we identify as episodic memory).
We recursively apply this procedure through layers to reﬁne the episodic memory.
In the end, we select the memory associated with the current timestep and feed it into the policy head.
Nonetheless, transformer optimization is often unstable, especially in the RL setting.
Past attempts either fail to stabilize (Mishra et al., 2018) or required architectural additions (Parisotto et al., 2019) or restrictions on the observations space (Loynd et al., 2020).
We argue that this challenge can be mitigated through a proper weight initialization scheme.
For this matter, we applied T-Fixup initialization (Huang et al., 2020).
[Figure]
We conducted a series of experiments to evaluate meta , fast adaptation and for and robotic manip ulation.
TrMRL consistently achieves or surpasses the current state-of-the-art meta
RL agents in and sample efﬁciency online adaptation to and performance on test tasks effectiveness
R ELATED W ORK
Meta-Learning is an established Machine Learning (ML) principle to learn inductive biases from the distribution of tasks to produce a data-efﬁcient learning system (Bengio et al., 1991; Schmidhuber et al., 1996; Thrun & Pratt, 1998).
This principle spanned in a variety of methods in recent years, learning different components of an ML system, such as the optimizer (Andrychowicz et al., 2016;
Li & Malik, 2016; Chen et al., 2017), neural architectures (Hutter et al., 2019; Zoph & Le, 2017), metric spaces (Vinyals et al., 2016), weight initializations (Finn et al., 2017; Nichol et al., 2018;
Finn et al., 2018) and conditional distributions (Zintgraf et al., 2019; Melo et al., 2019).
Another branch of methods learns the entire system using memory-based architectures (Ortega et al., 2019;
Wang et al., 2017; Duan et al., 2016; Ritter et al., 2018a) or generating update rules by discovery (Oh et al., 2020) or evolution (Co-Reyes et al., 2021).
Memory-Based Meta-Learning is the particular class of methods where we focus on in this work.
In this context, Wang et al.
(2017); Duan et al.
(2016) concurrently proposed the RL 2 framework, which formulates the learning process as a Recurrent Neural Network (RNN) where the hidden state works as the memory mechanism.
Given the recent rise of attention-based architectures, one natural idea is to use it as a replacement for RNNs.
Mishra et al.
(2018) proposed an architecture composed of causal convolutions (to aggregate information from past experience) and soft-attention (to pinpoint speciﬁc pieces of information).
In contrast, our work applies causal, multi-head self-attention by stabilizing the complete transformer architecture with an arbitrarily large context window.
Finally, Ritter et al.
(2021) also applied multi-head self-attention for rapid task solving for RL environments.
However, in a different dynamic: their work applied the attention mechanism iteratively in a pre-deﬁned episodic memory, while ours applies it recursively through transformer layers to build an episodic memory from the association of recent working memories.
Our work has intersections with Cognitive Neuroscience research on memory for learning systems (Hoskin et al., 2018; Rovee-Collier, 2012;
Wang et al., 2018).
In this context, Ritter et al.
(2018c) extended the RL 2 framework incorporating a differentiable neural dictionary as the inductive bias for episodic memory recall.
In the same line, Ritter et al.
(2018b) also extended RL 2 but integrating a different episodic memory system inspired by the reinstatement mechanism.
In our work, we also mimic reinstatement to retrieve episodic memories from working memories but using self-attention.
Lastly, Fortunato et al.
(2019) studied the association between working and episodic memories for
RL agents, speciﬁcally for memory tasks, proposing separated inductive biases for these memories based on LSTMs and auxiliary unsupervised losses.
In contrast, our work studies this association for the Meta-RL problem, using memory as a task proxy implemented by the transformer architecture.
Meta-Reinforcement Learning is a branch of Meta-Learning for RL agents.
Some of the algorithms described in past paragraphs extend to the Meta-RL setting by design (Finn et al., 2017;
Mishra et al., 2018; Wang et al., 2017; Duan et al., 2016).
Others were explicitly designed for RL and often aimed to create a task representation to condition the policy.
PEARL (Rakelly et al., 2019) is an off-policy method that learns a latent representation of the task and explores via posterior sampling.
MAESN (Gupta et al., 2018) also creates task variables but optimizes them with on-policy gradient descent and explores by sampling from the prior.
MQL (Fakoor et al., 2020) is also an off-policy method, but it uses a deterministic context that is not permutation invariant implemented by an RNN.
Lastly, VariBAD Zintgraf et al.
(2020) formulates the problem as a Bayes-Adaptive
MDP and extends the RL 2 framework by incorporating a stochastic latent representation of the task trained with a VAE objective.
Our work contrasts all the previous methods in this task representation: we condition the policy in the episodic memory generated by the transformer architecture from the association of past working memories.
We show that this episodic memory works as a proxy to the task representation.
Transformers for RL.
The application of the transformer architecture in the RL setting is still an open challenge.
Mishra et al.
(2018) tried to apply this architecture for simple bandit tasks and tabular MDPs and reported unstable train and random performance.
Parisotto et al.
(2019) then proposed some architectural changes in the vanilla transformer, reordering layer normalization modules and replacing residual connections with expressing gating mechanisms, improving state-of-the-art performance for a set of memory environments.
Loynd et al.
(2020) also studied how transformerbased models can improve the performance of sequential decision-making agents.
It stabilized the architecture using factored observations and an intense hyperparameter tuning procedure, resulting in improved sample efﬁciency.
In contrast to these methods, our work stabilizes the transformer model by improving optimization through a better weight initialization.
In this way, we could use the vanilla transformer without architectural additions or imposing restrictions on the observations.
Finally, recent work studied how to replace RL algorithms with transformer-based language models (Janner et al., 2021;
Chen et al., 2021).
Using a supervised prediction loss in the ofﬂine RL setting, they modeled the agent as a sequence problem.
Our work, on the other hand, considers the standard
RL formulation in the meta-RL setting.
P RELIMINARIES
We deﬁne a Markov decision process (MDP) by a tuple M = ( S , A , P , R , P 0 , γ, H ) , where S is a state space, A is an action space, P : S ×
A × S → [0 , ∞ ) is a transition dynamics, R :
S × A → [ − R max , R max ] is a bounded reward function, P 0 : S → [0 , ∞ ) is an initial state distribution, γ ∈ [0 , 1] is a discount factor, and H is the horizon.
The standard RL objective is to maximize the cumulative reward, i.e., max E [ (cid:80)
Tt =
γ t R ( s t , a t )] , with a t ∼ π θ ( a t | s t ) and s t ∼ P
( s t | s t − 1 , a t − 1 ) , where π θ : S ×
A → [0 , ∞ ) is a policy parameterized by θ .
3. P ROBLEM S ETUP : M ETA -R EINFORCEMENT L EARNING
In the meta-RL setting, we deﬁne p ( M ) :
M → [0 , ∞ ) a distribution over a set of MDPs
M .
During meta-training, we sample M i ∼ p ( M ) from this distribution, where M i =
( S , A , P i , R i , P 0 ,i , γ, H ) .
Therefore, the tasks 1 share a similar structure in this setting, but reward function and transition dynamics vary.
The goal is to learn a policy that, during meta-testing, can adapt to a new task sampled from the same distribution p ( M ) .
In this context, adaptation means maximizing the reward under the task in the most efﬁcient way.
To achieve this, the meta-RL agent should learn the prior knowledge shared across the distribution of tasks.
Simultaneously, it should learn how to differentiate and identify these tasks using only a few episodes.
3. T RANSFORMER A RCHITECTURE
The transformer architecture (Vaswani et al., 2017) was ﬁrst proposed as an encoder-decoder architecture for neural machine translation.
Since then, many variants have emerged, proposing simpliﬁcations or architectural changes across many ML problems (Dosovitskiy et al., 2021a; Brown et al., 2020b; Parisotto et al., 2019).
Here, we describe the encoder architecture as it composes our memory-based meta-learner.
The transformer encoder is a stack of multiple equivalent layers.
There are two main components in each layer: a multi-head self-attention block, followed by a position-wise feed-forward network.
Each component contains a residual connection (He et al., 2015) around them, followed by layer normalization (Ba et al., 2016).
The multi-head self-attention (MHSA) block computes the selfattention operation across many different heads, whose outputs are concatenated to serve as input to a linear projection module, as in Equation 1:
[Equation]
where K, Q, V are the keys, queries, and values for the sequence input, respectively.
Additionally, d represents the dimension size of keys and queries representation and ω the number of attention heads.
M represents the attention masking operation.
W o represents a linear projection operation.
The position-wise feed-forward block is a 2-layer dense network with a ReLU activation between these layers.
All positions in the sequence input share the parameters of this network, equivalently to a 1 × 1 temporal convolution over every step in the sequence.
Finally, we describe the positional encoding.
It injects the relative position information among the elements in the sequence input since the transformer architecture fully parallelizes the input processing.
The standard positional encoding is a sinusoidal function added to the sequence input (Vaswani et al., 2017).
3. T-F IXUP I NITIALIZATION
The training of transformer models is notoriously difﬁcult, especially in the RL setting (Parisotto et al., 2019).
Indeed, gradient optimization with attention layers often requires complex learning rate warmup schedules to prevent divergence (Huang et al., 2020).
Recent work suggests two main reasons for this requirement.
First, the Adam optimizer (Kingma & Ba, 2017) presents high variance in the inverse second moment for initial updates, proportional to a divergent integral (Liu et al., 2020).
It leads to problematic updates and signiﬁcantly affects optimization.
Second, the backpropagation through layer normalization can also destabilize optimization because the associated error depends on the magnitude of the input (Xiong et al., 2020).
Given these challenges, Huang et al.
(2020) proposed a weight initialization scheme (T-Fixup) to eliminate the need for learning rate warmup and layer normalization.
This is particularly important to the RL setting once current RL algorithms are very sensitive to the learning rate for learning and exploration.
T
Fixup appropriately bounds the original Adam update to make variance ﬁnite and reduce instability, regardless of model depth.
We refer to Huang et al.
(2020) for the mathematical derivation.
We apply the T-Fixup for the transformer encoder as follows:
• Apply Xavier initialization (Glorot & Bengio, 2010) for all parameters excluding input embeddings.
Use Gaussian initialization N (0 , d − 12 ) , for input embeddings, where d is the embedding dimension; • Scale the linear projection matrices in each encoder attention block and position-wise feedforward block by 0 .
67 N − 1 4 .
T RANSFORMERS ARE M ETA -R EINFORCEMENT L EARNERS
In this work, we argue that two critical capabilities of transformers compose the central role of a
Meta-Reinforcement Learner.
First, transformers can handle long sequences and reason over longterm dependencies, which is essential to the meta-RL agent to identify the MDP from a sequence of trajectories.
Second, transformers present context-dependent weights from self-attention.
This mechanism serves as a fast adaptation strategy and provides necessary adaptability to the meta-RL agent for new tasks.
4. T ASK R EPRESENTATION
We represent a working memory at the timestep t as a parameterized function φ t ( s t , a t , r t , η t ) , where s t is the MDP state, a t ∼ π ( a t | s t ) is an action, r t ∼ R ( s t , a t ) is the reward, and η t is a boolean ﬂag to identify whether this is a terminal state.
Our ﬁrst hypothesis is that we can deﬁne a task T as a distribution over working memories, as in Equation 2: [Equation] Φ → [ [Equation]
[Equation]
(2) where Φ is the working memory embedding space.
In this context, one goal of a meta-RL agent is to learn φ to make a distinction among the tasks in the embedding space Φ .
Furthermore, the learned embedding space should also approximate the distributions of similar tasks so that they can share knowledge.
Figure 2 illustrates this concept for a onedimensional representation.
We aim to ﬁnd a representation for the task given its distribution to contextualize our policy.
Intuitively, we can represent each task as a linear combination of working memories sampled by the policy interacting with it:
[Equation]
, η t )) , with N (cid:88)
[Equation]
(3) where N represents the length of a segment of sampled trajectories during the policy and task interaction.
W represents an arbitrary linear transformation.
Furthermore, α t is a coefﬁcient to compute how relevant a particular working memory t is to the task representation, given the set of sampled working memories.
Next, we show how the self-attention computes these coefﬁcients, which we use to output an episodic memory from the transformer architecture.
4. S ELF -A TTENTION AS A F AST A DAPTATION S TRATEGY
In this work, our central argument is that self-attention works as a fast adaptation strategy.
The context-dependent weights dynamically compute the working memories coefﬁcients to implement
Equation 3.
We now derive how we compute these coefﬁcients.
Figure 3 illustrates this mechanism.
Let us deﬁne φ kt , φ qt , and φ vt as a representation 2 of the working memory at timestep t in the keys, queries, and values spaces, respectively.
The dimension of the queries and keys spaces is d .
We aim to compute the attention operation in Equation 1 for a sequence of T timesteps, resulting in Equation 4:
[Figure]
[Equation]
where
[Equation]
where (cid:104) a i , b j (cid:105)
= (cid:80) dn =
a i,n · b j,n is the dot product between the working memories a i and b j .
Therefore, for a particular timestep t
[Equation]
the self-attention output is:
[Equation] [Equation]
Equation 5 shows that the self-attention mechanism implements the task representation in Equation 3 by associating past working memories given that the current one is φ t .
It computes this association with relative similarity through the dot product normalized by the softmax operation.
This inductive bias helps the working memory representation learning to approximate the density of the task distribution T ( φ ) .
4. T RANSFORMERS AND M EMORY R EINSTATEMENT
We now argue that the transformer model implements a memory reinstatement mechanism for episodic memory retrieval.
An episodic memory system is a long-lasting memory that allows an agent to recall and re-experience personal events (Tulving, 2002).
It complements the working memory system, which is active and relevant for short periods (Baddeley, 2010) and works as a buffer for episodic memory retrieval (Zilli & Hasselmo, 2008).
Adopting this memory interaction model, we model an episodic memory as a transformation over a collection of past memories. More concretely, we consider that a transformer layer implements this transformation:
[Equation]
where e lt represents the episodic memory retrieved from the last layer l for the timestamp t and f represents the transformer layer. Equation 6 provides a recursive deﬁnition, and e 0 t (the base case) corresponds to the working memories φ t
In this way, the transformer architecture recursively reﬁnes the episodic memory interacting memories retrieved from the past layer.
We show the pseudocode for this process in Algorithm 1. This reﬁnement is guaranteed by a crucial property of the selfattention mechanism: it computes a consensus representation across the input memories associated to the sub-trajectory, as stated by Theorem 1 (Proof in Appendix E).
Here, we deﬁne consensus representation as the memory representation that is closest on average to all likely representations (Kumar & Byrne, 2004), i.e., minimizes the Bayes risk considering the set of episodic memories. Theorem 1. Let S l =
( e l 0 , . . . , e lN ) ∼ p ( e |S l , θ l ) be a set of normalized episodic memory representations sampled from the posterior distribution p ( e |S l , θ l ) induced by the transformer layer l , parameterized by θ l .
Let K , Q , V be the Key, Query, and Value vector spaces in the selfattention mechanism.
Then, the self-attention in the layer l +1 computes a consensus representation e l +
[Equation]
N
[Equation]
whose associated Bayes risk (in terms of negative cosine similarity) lower bounds the Minimum Bayes Risk (MBR) predicted from the set of candidate samples S l projected onto the V space.
Lastly, we condition the policy head in the episodic memory from the current timestep to sample an action.
This complete process resembles a memory reinstatement operation: a reminder procedure that reintroduces past elements in advance of a long-term retention test (Rovee-Collier, 2012).
In our context, this “long-term retention test” identiﬁes the task and acts accordingly to maximize rewards.
E XPERIMENTS AND A NALYSIS
In this section, we present an empirical validation of our method, comparing it with the current state-of-the-art methods.
We considered high-dimensional, continuous control tasks for locomotion (MuJoCo 3 ) and dexterous manipulation (MetaWorld).
We describe them in Appendix A. For reproducibility (source code and hyperparameters), we refer to the released source code 4 .
5. E XPERIMENTAL S ETUP
Meta-Training.
During meta-training, we repeatedly sampled a batch of tasks to collect experience with the goal of learning to learn.
For each task, we ran a sequence of E episodes.
During the interaction, the agent conducted exploration with a gaussian policy.
During optimization, we concatenate these episodes to form a single trajectory and we maximize the discounted cumulative reward of this trajectory.
This is equivalent to the training setup for other on-policy meta-RL algorithms (Duan et al., 2016; Zintgraf et al., 2020).
For these experiments, we considered E = 2 .
We performed this training via Proximal Policy Optimization (PPO) (Schulman et al., 2017), and the data batches mixed different tasks.
Therefore, we present here an on-policy version of the TrMRL algorithm.
To stabilize transformer training, we used the T-Fixup as a weight initialization scheme.
Meta-Testing.
During meta-testing, we sampled new tasks.
These are different from the tasks in meta-training, but they come from the same distribution, except during Out-of-Distribution (OOD) evaluation.
For TrMRL, in this stage, we froze all network parameters.
For each task, we ran few episodes, performing the adaptation strategy.
The goal is to identify the current MDP and maximize the cumulative reward across the episodes.
Memory Write Logic.
At each timestep, we fed the network with the sequence of working memories.
This process works as follows: at the beginning of an episode (when the memory sequence is empty), we start writing the ﬁrst positions of the sequence until we ﬁll all the slots.
Then, for each new memory, we removed the oldest memory in the sequence (in the “back” of this “queue”) and added the most recent one (in the “front”).
Comparison Methods.
For comparison, we evaluated three different state-of-the-art meta-RL algorithms: RL 2 Duan et al.
(2016), optimized using PPO Schulman et al.
; PEARL (Rakelly et al., 2019); and MAML (Finn et al., 2017), whose outer-loop used TRPO (Schulman et al., 2015).
[Figure]
5. R ESULTS AND A NALYSIS
We compared TrMRL with baseline methods in terms of meta-training, episode adaptation, and
OOD performance.
We also present the latent visualization for TrMRL working memories and ablation studies.
All the curves presented are averaged across three random seeds, with 95% bootstrapped conﬁdence intervals.
Meta-Training Evaluation .
Figure 4 shows the meta-training results for all the methods in the
MetaWorld environments.
All subplots show the task success rate over the training timesteps.
The plots on top represent performance on training tasks, while the plots on the bottom represent on the test tasks.
TrMRL outperformed all baseline methods.
In the “Reach-v2”, TrMRL, RL 2 , and
MAML reached the perfect success rate, but TrMRL was more sample efﬁcient.
For more complex scenarios, such as “Push-v2” and ML45, TrMRL still performs consistently better.
Nevertheless, we also present that all the presented methods performed poorly on ML45 for test tasks, highlighting a big improvement room.
We hypothesize that this is due to the lack of a meta-exploration strategy and an inductive bias to improve knowledge share among different tasks.
For MuJoCo locomotion tasks, we refer to Appendix B.
Fast Adaptation Evaluation .
A critical skill for meta-RL agents is the capability of adapting to new tasks given a few episodes.
We evaluate this by running meta-testing on 20 test tasks over 6 sequential episodes.
Each agent runs its adaptation strategy to identify the task and maximize the reward across episodes.
Figure 6 presents the results for the locomotion tasks.
For AntDir and HalfCheetaVel,
TrMRL outperformed all methods.
For HalfCheetahDir, TrMRL started with better performance, but PEARL outperformed after running its adaptation.
We highlight that TrMRL presented high performance since the ﬁrst episode.
In fact, it only requires a few timesteps to achieve high performance in test tasks.
In the HalfCheetahVel, for example, it only requires around 20 timesteps to achieve the best performance (Figure 5).
Therefore, it presents a nice
[Figure]
property for online adaptation.
This is because the self-attention mechanism is lightweight and only requires a few working memories to achieve good performance.
Hence, we can run it efﬁciently at each timestep.
Other methods, such as PEARL and MAML, do not present such property
[Figure]
and they need a few episodes before executing adaptation efﬁciently
[Figure]
OOD Evaluation .
Another critical scenario is how the fast adaptation strategies perform for out-of-distribution tasks.
For this case, we change the HalfCheetahVel environment to sample OOD tasks during the meta-test.
In the standard setting, both training and testing target velocities are sampled from a uniform distribution in the interval [0 . 0 , 3 . 0] .
In the OOD setting, we sampled 20 tasks in the interval [3 . 0 , 4 . 0] and assessed adaptation throughout the episodes.
Figure 7 presents the results.
TrMRL surpasses all the baselines methods with a good margin, suggesting that the context-dependent weights learned a robust adaptation strategy, while other methods memorized some aspects of the standard distribution of tasks.
We especially highlight PEARL, which achieved the best performance among the methods but performed poorly in this setting, suggesting that it does not generate useful latent representations for OOD tasks.
C ONCLUSION AND F UTURE W ORK
In this work, we presented TrMRL, a memory-based meta-RL algorithm built upon a transformer, where the multi-head self-attention mechanism works as a fast adaptation strategy.
We designed this network to resemble a memory reinstatement mechanism, associating past working memories to dynamically represent a task and recursively build an episode memory through layers.
TrMRL demonstrated a valuable capability of learning from reward signals.
On the other side, recent Language Models presented substantial improvements by designing self-supervised tasks (Devlin et al., 2019; Raffel et al., 2020) or even automating their generation (Shin et al., 2020). As future work, we aim to investigate how to enable these forms of self-supervision to leverage off-policy data collected during the training and further improve sample efﬁciency in transformers for the meta-RL scenario.  R EPRODUCIBILITY S TATEMENT
Code Release . To ensure the reproducibility of our research, we released all the source code associated with our models and experimental pipeline. We refer to the supplementary material of this submission. It also includes the hyperparameters and the scripts to execute all the scenarios presented in this paper.
Baselines Reproducibility . We strictly reproduced the results from prior work implementations for baselines, and we provide their open-source repositories for reference. Proof of Theoretical Results and Pseudocode . We provide a detailed proof of Theorem 1 in
Appendix E, containing all assumptions considered.
We also provide pseudocode from TrMRL’s agent to improve clarity on the proposed method.
Availability of all simulation environments .
All environments used in this work are freely available and open-source.
A M ETAL -RL E NVIRONMENTS D ESCRIPTION
In this Appendix, we detail the environments considered in this work.
A. M U J O C O – L OCOMOTION T ASKS
This benchmark is a set of locomotion tasks on the MuJoCo (Todorov et al., 2012) environment.
It comprises different bodies, and each environment provides different tasks with different learning goals.
These locomotion tasks are previously introduced by Finn et al.
(2017) and Rothfuss et al.
We considered 3 different environments.
AntDir : This environment has an ant body, and the goal is to move forward or backward.
Hence, it presents these 2 tasks.
• HalfCheetahDir :
This environment has a half cheetah body, and the goal is to move forward or backward.
Hence, it presents these 2 tasks.
• HalfCheetalVel :
This environment also has a half cheetah body, and the goal is to achieve a target velocity running forward.
This target velocity comes from a continuous uniform distribution.
These locomotion task families require adaptation across reward functions
. A. M ETA W ORLD
The MetaWorld (Yu et al., 2021) benchmark contains a diverse set of manipulation tasks designed for multi-task RL and meta-RL settings.
MetaWorld presents a variety of evaluation modes.
Here, we describe the two modes used in this work.
For more detailed description of the benchmark, we refer to Yu et al.
• ML1 : This scenario considers a single robotic manipulation task but varies the goal.
The meta-training “tasks” corresponds to 50 random initial object and goal positions, and metatesting on 50 heldout positions.
• ML45 :
With the objective of testing generalization to new manipulation tasks, the benchmark provides 45 training tasks and holds out 5 meta-testing tasks.
These
robotic manipulation
task families require adaptation across reward functions and dynamics.
B M U J O C O : M ETA -T RAINING E VALUATION
In this Appendix
[Figure]
we supplement the meta-training evaluation with the results on MuJoCo locomotion tasks.
Figure 8 shows the average return over train tasks (on top) and test tasks (on bottom) for AntDir, HalfCheetahVel
[Figure]
and HalfCheetahDir, respectively.
While PEARL failed to explore and learn in robotic manipulation tasks, it presented better results on locomotion tasks, especially in sample efﬁciency.
This is because of its off-policy nature: it efﬁciently reuses trajectories sampled from previous policy versions, reducing the number of training steps needed.
TrMRL achieved the same test task performance in AntDir and HalfCheetahVel as PEARL, also keeping the metric stable over the training.
When comparing with other on-policy methods, TrMRL signiﬁcantly improved performance and sample efﬁciency
[Figure]
v e r a g e
R
[Figure]
t u r nT e s t T a s k
[Figure]
C W ORKING M EMORIES L ATENT V ISUALIZATION
Figure 9 presents a 3-D view of the working memories from the HalfCheetahVel environment.
We sampled some tasks (target velocities) and collected working memories during the meta-test setting.
We observe that this embedding space learns a representation of each MDP as a distribution over the working memories, as suggested in Section 4.
In this visualization, we can draw planes that approximately distinguish these tasks.
Working memories that cross this boundary represent the ambiguity between two tasks.
Furthermore, this representation also learns the similarity of tasks: for example, the cluster of working memories for target velocity v = 1 . 0 is between the clusters for v = 0 .
5 and v = 1 . 5 .
This property induces knowledge sharing among all the tasks, which suggests the sample efﬁciency behind TrMRL meta-training.
We plotted the 3 most relevant components from PCA.
TrMRL learns a representation of each MDP as a distribution over the working memories.
This representation distinguishes the tasks and approximates similar tasks, which helps knowledge sharing among them.
D A BLATION S TUDY
In this section, we present an ablation study regarding the main components of TrMRL to identify how they affect the performance of the learned agents.
For all the scenarios, we considered one environment for each benchmark to represent both locomotion (HalfCheetahVel) and dexterous manipulation (MetaWorld-ML1-Reach-v2).
We evaluated the meta-training phase so that we could analyze both sample efﬁciency and asymptotic performance.
D. T-F IXUP
In this work, we employed T-Fixup to address the instability from the early stages of transformer training, given the reasons described in Section 3.3.
In RL, the early stages of training are also the moment when the learning policies are more exploratory to cover the state and action spaces better and discover rewards, preventing the convergence to sub-optimal policies. Hence, it is crucial for RL that the transformer policy learns appropriately since the beginning to drive exploration. This section evaluated how T-Fixup becomes essential for environments where the learned behaviors must guide exploration to prevent poor policies.
For this, we present T-Fixup ablation (Figure 10) for two settings: MetaWorld-ML1-Reach-v2 and HalfCheetahVel.
For the reach environment, we compute the reward distribution using the distance between the gripper and the target location. Hence, it is always a dense and informative signal: even a random policy can easily explore the environment, and T-Fixup does not interfere with the learning curve.
On the other side, HalfCheetahVel requires a functional locomotion gate to drive exploration; otherwise, it can get stuck with low rewards (e.g., cheetah is exploring while fallen).
In this scenario, T-Fixup becomes crucial to prevent unstable learning updates that could collapse the learning policy to poor behaviors.
[Figure]
D. W ORKING M EMORY S EQUENCE L ENGTH
A meta-RL agent requires a sequence of interactions to identify the running task and act accordingly.
The length of this sequence N should be large enough to address the ambiguity associated with the set of tasks, but not too long to make the transformer optimization harder and less sample efﬁcient. In this ablation, we study two environments that present different levels of ambiguity and show that they also require different lengths to achieve optimal sample efﬁciency.
We ﬁrst analyze MetaWorld-ML1-Reach-v2. The environment deﬁnes each target location in the 3D space as a task.
The associated reward is the distance between the gripper and this target. Hence, at each timestep, the reward is ambiguous for all the tasks located on the sphere’s surface with the center in the gripper position. This suggests that the agent will beneﬁt from long sequences.
Figure 11 (left) conﬁrms this hypothesis, as the sample efﬁciency improves until sequences with several timesteps (N = 50).
The HalfCheetahVel environment deﬁnes each forward velocity as a different task.
The associated reward depends on the difference between the current cheetah velocity and this target. Hence, at each timestep, the emitted reward is ambiguous only for two possible tasks.
To identify the current task, the agent needs to estimate its velocity (which requires a few timesteps) and then disambiguate between these two tasks. This suggests that the agent will not beneﬁt from very long sequences. Figure 11 (right) conﬁrms this hypothesis: there is an improvement from N = 1 to N = 5, but the performance decreases for longer sequences as the training becomes harder. [Figure]
D. N UMBER OF L AYERS
Another important component is the network depth.
In Section 4, we hypothesized that more layers would help to recursively build a more meaningful version of the episodic memory since we interact with output memories from the past layer and mitigates the bias effect from the task representations.
Figure 12 shows how TrMRL behaves according to the number of layers.
We observe a similar pattern to the previous ablation case.
For Reach-v2, more layers improved the performance by reducing the effect of ambiguity and biased task representations.
For HalfCheetaVel, we can see an improvement from a single layer to 4 or 8 layers, but for 12 layers, sample efﬁciency starts to decrease.
On the other hand, we highlight that even for a deep network with 12 layers, we have a stable optimization procedure, showing the effectiveness of the T-Fixup initialization.
D. N UMBER OF A TTENTION H EADS
The last ablation case relates to the number of attention heads in each MHSA block.
We hypothesized that multiples heads would diversify working memory representation and improve network expressivity.
Nevertheless, Figure 13 shows that more heads slightly increased the performance in HalfCheetahVel and did not interfere in Reach-v2 signiﬁcantly. [Figure]
[Figure]
E P ROOF OF T HEOREM
Theorem 1.
Let S l
=
( e l 0 , . . .
, e lN )
∼ p
( e |S l , θ l ) be a set of normalized episodic memory representations sampled from the posterior distribution p ( e |S l , θ l ) induced by the transformer layer l , parameterized by θ l .
Let K , Q , V be the Key, Query, and Value vector spaces in the selfattention mechanism.
Then, the self-attention in the layer l +1 computes a consensus representation e l
[Equation]
1 N
[Equation]
whose associated Bayes risk (in terms of negative cosine similarity) lower bounds the Minimum Bayes Risk (MBR) predicted from the set of candidate samples S l projected onto the V space.
Proof.
Let us deﬁne S lV as the set containing the projection of the elements in S l onto the V space:
S lV =
( e l,V 0 , . . .
, e l,VN ) , where e l,V = W V · e l ( W V is the projection matrix).
The Bayes risk of selecting ˆ e l,V as representation, BR (ˆ e l,V ) , under a loss function L , is deﬁned by:
[Equation]
The MBR predictor selects the episodic memory ˆ e l,V ∈ S lV that minimizes the Bayes Risk among the set of candidates: e l,VMBR =
arg min ˆ e ∈S lV BR (ˆ e ) .
Employing negative cosine similarity as loss function, we can represent MBR prediction as:
[Equation]
The memory representation outputted from a self-attention operation in layer l + 1 is given by:
[Equation]
The attention weights α N,t deﬁne a probability distribution over the samples in S lV , which approximates the posterior distribution p ( e |S lV , θ l ) .
Hence, we can represent Equation 9 as an expectation: e l +
[Equation]
=
E p
[Equation]
e |S lV , θ l ) [ e ] .
Finally, we compute the Bayer risk for it:
[Equation]
F P SEUDOCODE
In this section, we present a pseudocode for TrMRL’s agent during its interaction with an arbitrary
MDP.
Forward Pass
Require:
MDP M ∼ p ( M )
Require: Working Memory Sequence Length N
Require:
Parameterized function φ ( s , a , r, η )
Require:
Transformer network with L layers { f 1 , . .
, f L }
Require: Policy Head π
Initialize Buffer with N − 1 PAD transitions: B = { ( s PAD , a PAD , r PAD , η PAD ) i } , i ∈ { 1 , . . .
, N − 1 } t ←s next ← swhile episode not done do
Retrieve the N − 1 most recent transitions ( s , a , r, η ) from B to create the ordered subset D
D ← D (cid:83) ( s next , a PAD , r PAD , η PAD )
Compute working memories: φ i =
φ ( s i , a i , r i , η i ) , ∀{ s i , a i , r i , η i } ∈ D
Set e 01 , . .
, e 0 N ← φ 1 , . .
. , φ N for each l ∈ 1 , . . .
, L do
Reﬁne episodic memories: e l 1 , . .
, e lN ← f l ( e l − 1 1 , . . .
, e l − 1 N ) end for
Sample a t ∼ π ( ·| e LN )
Collect ( s t +1 , r t , η t ) interacting with M applying action a t s next ← s t +1 B ← B (cid:83) ( s t , a t , r t , η t ) t ← t +end while