{'fraction_non_alphanumeric': 0.03391263270430869, 'fraction_numerical': 0.011163322642400737, 'mean_word_length': 4.921095245105255, 'pattern_counts': {'":': 0, '<': 0, '<?xml version=': 0, '>': 0, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
Transformers are Meta-Reinforcement Learners

The transformer architecture and variants presented 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 context-dependent weights from the attention mechanism. We argue that these capabilities suit the central role of a Meta-Reinforcement Learning algorithm. Indeed, a meta-RL 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 (Transformers for Meta-Reinforcement Learning), 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. We show that the self-attention computes a consensus representation that minimizes the Bayes Risk at each layer and provides meaningful features to compute the best actions. We conducted experiments in high-dimensional continuous control environments for locomotion and dexterous manipulation. Results show that TrMRL presents comparable or superior asymptotic performance, sample efficiency, and out-of-distribution generalization compared to the baselines in these environments.


Introduction
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., Proceedings of the 39 th International Conference on Machine Learning, Baltimore, Maryland, USA, PMLR 162, 2022. Copyright 2022 by the author(s). 2021b; Caron et al., 2021;Yuan et al., 2021). This intrinsically relates to its few-shot learning nature (Brown et al., 2020b): the attention weights work as context-dependent parameters, inducing better generalization. Furthermore, this architecture parallelizes token processing by design. This property avoids backpropagation through time, making it less prone to vanishing/exploding gradients, a very common problem for recurrent models. As a result, they can handle longer sequences more efficiently.
This work argues that these two capabilities are essential for a Meta-Reinforcement Learning (meta-RL) agent. We propose TrMRL (Transformers for Meta-Reinforcement Learning), a memory-based 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 refine 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 hypothesize that this challenge is because the instability of early stages of transformer optimization harms initial exploration, which is crucial for environments where the learned behaviors must guide exploration to prevent poor policies. 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).
We conducted a series of experiments to evaluate metatraining, fast adaptation, and out-of-distribution generalization in continuous control environments for locomotion and arXiv:2206.06614v1 [cs.LG] 14 Jun 2022  Figure 1. Illustration of the TrMRL agent. At each timestep, it associates the recent past of working memories to build an episodic memory through transformer layers recursively. We argue that the self-attention works as a fast adaptation strategy since it provides context-dependent parameters.
robotic manipulation. Results show that TrMRL presents comparable or superior performance and sample efficiency compared to the meta-RL baselines. We also conducted an experiment to validate the episode memory refinement process. Finally, we conducted an ablation study to show the effectiveness of the T-Fixup initialization, and the sensibility to network depth, sequence size, and the number of attention heads.
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 softattention (to pinpoint specific 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 predefined 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, specifically 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 offpolicy 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 transformer-based 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 efficiency. 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 offline 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. This formulation presents more challenges, since the agent needs to explore in the environment and apply RL gradients to maximize rewards, which is acknowledged to be much noisier (Norouzi et al., 2016).

Preliminaries
We define 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 : 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 re- is a policy parameterized by θ.

Problem Setup: Meta-Reinforcement Learning
In the meta-RL setting, we define 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 efficient 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.

Transformer Architecture
The transformer architecture (Vaswani et al., 2017) was first proposed as an encoder-decoder architecture for neural machine translation. Since then, many variants have emerged, proposing simplifications or architectural changes across many ML problems (Dosovitskiy et al., 2021a;Brown et al., 2020a;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 resid-ual connection (He et al., 2015) around them, followed by layer normalization (Ba et al., 2016). The multi-head self-attention (MHSA) block computes the self-attention operation across many different heads, whose outputs are concatenated to serve as input to a linear projection module, as in Equation 1: 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).

T-Fixup Initialization
The training of transformer models is notoriously difficult, 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 . It leads to problematic updates and significantly 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 finite 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 − 1 2 ), for input embeddings, where d is the embedding dimension; • Scale the linear projection matrices in each encoder attention block and position-wise feed-forward block by 0.67N − 1 4 .

Transformers are Meta-Reinforcement Learners
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 long-term dependencies, which is essential to the meta-RL agent to identify the MDP from a sequence of trajectories. Second, transformers present contextdependent weights from self-attention. This mechanism serves as a fast adaptation strategy and provides necessary adaptability to the meta-RL agent for new tasks.

Task Representation
We represent a working memory at the timestep t as a pa- is the reward, and η t is a boolean flag to identify whether this is a terminal state. Our first hypothesis is that we can define a task T as a distribution over working memories, as in 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 Φ.
Layer 1 Head 1 Figure 3. Illustration of causal self-attention as a fast adaptation strategy. In this simplified scenario (2 working memories), the attention weights αi,j drives the association between the current working memory and the past ones to compute a task representation µt. Selfattention computes this association by relative similarity.
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 one-dimensional representation.
We aim to find 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: 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 coefficient 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 coefficients, which we use to output an episodic memory from the transformer architecture.

Self-Attention as a Fast Adaptation Strategy
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 coefficients to implement Equation 3. We now derive how we compute these coefficients. Figure 3 illustrates this mechanism.
Let us define φ k t , φ q t , and φ v t 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: where a i , b j = d n=0 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, the self-attention output is: 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 (φ).

Transformers and Memory Reinstatement
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: where e l t 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 definition, and e 0 t (the base case) corresponds to the working memories φ t In this way, the transformer architecture recursively refines the episodic memory interacting memories retrieved from the past layer. We show the pseudocode for this process in Algorithm 1 (Appendix G). This refinement is guaranteed by a crucial property of the self-attention mechanism: it computes a consensus representation across the input memories associated to the sub-trajectory, as stated by Theorem 4.1 (Proof in Appendix F). Here, we define 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 4.1. Let S l = (e l 0 , . . . , e l N ) ∼ 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 self-attention mechanism. Then, the self-attention in the layer l + 1 computes a consensus representation 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" identifies the task and acts accordingly to maximize rewards.

Experiments and Discussion
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 B. For reproducibility (source code and hyperparameters), we refer to the released source code at https://github.com/ luckeciano/transformers-metarl.

Experimental Setup
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 first positions of the sequence until we fill 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").

Results and Analysis
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 confidence intervals.
Meta-Training Evaluation. Figure 4 shows the metatraining results for all the methods in the MetaWorld (success rates) and MuJoCo (average returns) environments. All subplots represent performance on test tasks over the training timesteps. TrMRL presented comparable or superior performance to the baseline methods. In scenarios where the task ambiguity is high, VariBAD presented stronger results, especially for Push-v2. In this context, ambiguity relates to the same working memories belonging to multiple different MDPs (as illustrated in Figure 2). These results support the effectiveness of the VariBAD objective that incorporates task uncertainty directly during action selection (Zintgraf et al., 2020). Reach-v2 and AntDir also presented some level of ambiguity, but TrMRL is on par with these scenarios. For scenarios with less ambiguity, such as HalfChee-taVel, TrMRL is way more sample efficient than VariBAD. It is worth mentioning that VariBAD's training objective can be leveraged by other encoding methods (such as TrMRL) (Zintgraf et al., 2020), and we let this as a future line of work.
PEARL failed to explore and learn these robotic manipulation tasks: prior work already pointed out the difficulty of training PEARL's task encoder for dexterous manipulation . On the other side, it presented better results on locomotion tasks, especially in sample efficiency. This is because of its off-policy nature inherited from the Soft Actor-Critic framework (Haarnoja et al., 2018). Compared with other on-policy methods (such as RL 2 and MAML), TrMRL significantly improved performance or sample efficiency.
Finally, for "MetaWorld-ML45-Train" (a simplified version of ML45 benchmark where we evaluate on the training 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. tasks), the more complex environment in this work, TrMRL achieved the best learning performance among the methods, supporting that the proposed method can generalize better across very different tasks in comparison with other methods. Additionally, VariBAD's performance suggests that its proposed objective does not scale well for this scenario, harming the final performance when compared with RL2. We hypothesize that the supervision from the dynamics and rewards in the training objective provides conflicting learning signals to the RNN.
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 six sequential episodes. Each agent runs its adaptation strategy to identify the task and maximize the reward across episodes. Figure 5 presents the results for the locomotion tasks. TrMRL again presents a comparable or superior performance in comparison to the baselines.
We highlight that TrMRL presented high performance since the first episode. 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 9 in Appendix D). Therefore, it presents a nice property for online adaptation. Other methods, such as PEARL and MAML, do not present such property, as they need a few episodes before executing adaptation efficiently.
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 veloci-  Figure 6 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 for locomotion tasks among the methods but performed poorly in this setting. VariBAD also presented unstable performance across the episodes. These results suggest that their task encoding mechanisms do not generate effective latent representations for OOD tasks.
Episodic Memory Refinement. We evaluated Theorem 4.1 empirically in Figure 7. In these two experiments, we interacted with one of the trained policies within the HalfChee-tahVel environment and collected the episodic memories computed from each layer throughout a few episodes and across different tasks. Firstly, we computed the dissimilarity between the memories from each layer and the final representation from the last layer. We refer to this metric as the representation error. Next, we computed linear regression models over the "expert" actions sampled from the trained policy. We used the episodic memories from each layer as features and reported the mean squared error on a test set. We aim to evaluate how meaningful the representations from each layer are by predicting the best action given a very lightweight model. Figure 7 shows that the representation error gradually decreases throughout the layers, suggesting the refinement of the episodic memory and the convergence to a consensus representation, as supported by Theorem 4.1. It also shows a correlated behavior in the regression error over the expert actions. This evidence suggests that the refinement of an episodic memory induces a consensus representation that is more meaningful to predict the best actions from the expert agent.

Conclusion and Future Work
In this work, we presented TrMRL, a memory-based meta-RL algorithm built upon a transformer, where the multihead 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 selfsupervised 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 efficiency in transformers for the meta-RL scenario.
Finn, C., Abbeel, P., and Levine, S. Model-agnostic meta-learning for fast adaptation of deep networks.

A. Reproducibility Statement
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 4.1 in Appendix F, 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.

B. Metal-RL Environments Description
In this Appendix, we detail the environments considered in this work.

B.1. MuJoCo -Locomotion Tasks
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. (2018). We considered 2 different environments.
• AntDir: This environment has an ant 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.

B.2. MetaWorld
The MetaWorld  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 ML1 mode used in this work. For more detailed description of the benchmark, we refer to .
• 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 meta-testing 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. Given the difficulty of such benchmark, in this work, we adopted a simplified version, "ML45-Train", where we also evaluate the performance of the methods in the 45 training tasks.
These robotic manipulation task families require adaptation across reward functions and dynamics.
Transformers are Meta-Reinforcement Learners C. Working Memories Latent Visualization Figure 8 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 efficiency behind TrMRL meta-training.

D. Online Adaptation
In this Appendix, we highlight that TrMRL presented high performance since the first episode. In fact, it only requires a few timesteps to achieve high performance in test tasks. Figure 9 shows that it only requires around 20 timesteps to achieve the best performance in the HalfCheetahVel environment. Therefore, it presents a nice 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 efficiently at each timestep. Other methods, such as PEARL and MAML, do not present such property, and they need a few episodes before executing adaptation efficiently.

E. Ablation Study
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 efficiency and asymptotic performance.

E.1. T-Fixup
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.

E.2. Working Memory Sequence Length
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 efficient. 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 efficiency.
We first analyze MetaWorld-ML1-Reach-v2. The environment defines 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 benefit from long sequences. Figure 11 (left) confirms this hypothesis, as the sample efficiency improves until sequences with several timesteps (N = 50).
The HalfCheetahVel environment defines 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 benefit from very long sequences. Figure 11 (right) confirms this hypothesis: there is an improvement in sample efficiency from N = 1 to N = 5, but it decreases for longer sequences as the training becomes harder (it is worth mentioning that all evaluated policies achieved the best asymptotic performance).

E.3. Number of Layers
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 efficiency 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.

E.4. Number of Attention Heads
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 significantly. Theorem 4.1. Let S l = (e l 0 , . . . , e l N ) ∼ 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 self-attention mechanism. Then, the self-attention in the layer l + 1 computes a consensus representation e l+1 N = N t=1 e l,V t ·exp e l,Q t ,e l,K i N t=1 exp e l,Q t ,e l,K i 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 define S l V as the set containing the projection of the elements in S l onto the V space: S l V = (e l,V 0 , . . . , e l,V N ), where e l,V = W V · e l (W V is the projection matrix). The Bayes risk of selectingê l,V as representation, BR(ê l,V ), under a loss function L, is defined by: BR(ê l,V ) = E p(e|S l V ,θ l ) [L(e,ê)] The MBR predictor selects the episodic memoryê l,V ∈ S l V that minimizes the Bayes Risk among the set of candidates: e l,V M BR = arg minê ∈S l V BR(ê). Employing negative cosine similarity as loss function, we can represent MBR prediction as: The memory representation outputted from a self-attention operation in layer l + 1 is given by: