Recurrent Action Transformer with Memory

## Abstract

Abstract Recently, the use of transformers in offline reinforcement learning has become a rapidly developing area. This is due to their ability to treat the agent’s trajectory in the environment as a sequence, thereby reducing the policy learning problem to sequence modeling. In environments where the agent’s decisions depend on past events (POMDPs), it is essential to capture both the event itself and the decision point in the context of the model. However, the quadratic complexity of the attention mechanism limits the potential for context expansion. One solution to this problem is to extend transformers with memory mechanisms. This paper proposes a Recurrent Action Transformer with Memory (RATE), a novel model architecture that incorporates a recurrent memory mechanism designed to regulate information retention. To evaluate our model, we conducted extensive experiments on memory-intensive environments (ViZDoom-Two-Colors, T-Maze, Memory Maze, Minigrid-Memory), classic Atari games, and MuJoCo control environments. The results show that using memory can significantly improve performance in memory-intensive environments, while maintaining or improving results in classic environments. We believe that our results will stimulate research on memory mechanisms for transformers applicable to offline reinforcement learning.

## 1 Introduction

Figure: Figure 1: Recurrent Action Transformer with Memory (RATE). $R$ – returns-to-go, $o$ – observations, $a$ – actions, $M_{n}$ – segment’s $S_{n}$ memory embeddings.
Refer to caption: extracted/5925481/plots/RATE_scheme.png

Transformers (Vaswani et al., ), originally developed for Natural Language Processing (NLP), perform well in Reinforcement Learning (RL) (Agarwal et al., ; Li et al., ): online RL (Parisotto et al., ; Esslinger et al., ; Melo, ; Team et al., ), offline RL (Chen et al., ; Lee et al., ; Jiang et al., ), and model-based RL (Chen et al., ; Micheli et al., ; Robine et al., ), including solving the credit assignment problem and working in memory-intensive environments (Chen et al., ; Ni et al., ; Grigsby et al., ), provided that the entire trajectory fits within the model context. However, transformers struggle with long sequences due to quadratic attention complexity, limiting their use in long inference tasks. Several approaches attempt to increase the context size (Dai et al., ; Bulatov et al., ; Ding et al., ), but such models may become unstable when trained on long sequences (Zhang et al., ), or use a specific sparse attention mechanism that is unsuitable for non-NLP tasks (Beltagy et al., ; Zaheer et al., ; Ding et al., ).
Memory mechanisms offer a promising solution to account for past information without increasing context size. Our work explores memory in transformers for RL, inspired by NLP results (Dai et al., ; Bulatov et al., ).
The RL setting differs from NLP in the processing of input sequences, requiring specialized encoders for observations, rewards, and actions, and is also characterized by significant sparsity in some tasks.

In RL memory has two senses. One is using past information within an episode to make decisions (Lampinen et al., ; Ni et al., ). The other is transferring experience from one environment to another (Melo, ; Kang et al., ; Team et al., ), improving generalizability, sample efficiency, and solving Meta-RL (Duan et al., ; Wang et al., ) tasks. Our work focuses on the first case (Ni et al., ): using past information to make decisions within the same episode.

In this paper, we propose the Recurrent Action Transformer with Memory (RATE, Figure 1), a model that uses several memory mechanisms: memory embeddings, caching of previous hidden states, and Memory Retention Valve (MRV). We empirically show that memory mechanisms effectively preserve information from previous steps, allowing the model to use past information when making decisions in the present.
MRV is designed to control the process of updating memory embeddings and prevent the loss of important information when processing long sequences, thus enabling the processing of highly sparse tasks.
To evaluate the memory mechanisms, we perform extensive experiments in memory-intensive environments: ViZDoom-Two-Colors (Sorokin et al., ), Memory Maze (Pasukonis et al., ), Minigrid-Memory (Chevalier-Boisvert et al., ), and Passive T-Maze (Ni et al., ), as well as on standard RL benchmarks: Atari (Bellemare et al., ) and MuJoCo (Fu et al., ). We also study the impact of memory on the performance of the proposed model.

The proposed model interpolates and extrapolates well outside the transformer context, is able to retain important information for a long time when operating in highly sparse environments, and allows to compensate the effect of bias in the training data.

Our contribution can be summarized as follows:

- 1.
We propose the Recurrent Action Transformer with Memory (RATE), a transformer model for offline RL that makes use of memory mechanisms: memory embeddings, caching of hidden states, and the Memory Retention Valve (MRV). The proposed MRV is based on the cross-attention architecture and is designed to prevent information loss from memory embeddings and significantly improve the performance of RATE in memory-intensive environments with sparse structure (see section 3).
- 2.
We show that RATE significantly outperforms strong baselines with and without memory mechanisms in memory-intensive environments, including ViZDoom Two-Colors, Memory Maze, Minigrid-Memory, and T-Maze (see subsection 4.2).
- 3.
We demonstrate that RATE achieves better or comparable results in classic Atari games and MuJoCo control tasks, demonstrating that the proposed model is suitable for different types of tasks and emphasizing its universality (see subsection 4.2).

## 2 Background

### 2.1 Offline Reinforcement Learning

In RL (Sutton & Barto, ), we assume that the task can be described by a Markov Decision Process (MDP) as a tuple $\langle\mathcal{S},\mathcal{A},\mathcal{P},\mathcal{R}\rangle$. The process consists of states $s\in\mathcal{S}$, actions $a\in\mathcal{A}$, a state transition function $\mathcal{P}(s^{\prime}|s,a)$, and an immediate reward function $r=\mathcal{R}(s,a)$. The states are assumed to have the Markov Property, that is $\mathbb{P}(s_{t+1}|s_{t})=\mathbb{P}(s_{t+1}|s_{1},\dots,s_{t})$. Given a timestep $t$, we use $r_{t}=R(s_{t},a_{t})$ to denote the immediate reward that the agent receives at state $s_{t}$ performing action $a_{t}$ at that timestep. We describe trajectory $\tau$ of length $T$ as a sequence of states $s_{i}$, actions $a_{i}$, and immediate rewards $r_{i}$: $\tau=(s_{0},a_{0},r_{0},s_{1},a_{1},r_{1},\dots,s_{T-1},a_{T-1},r_{T-1})$. We denote return-to-go (Chen et al., ) $R_{t}$ of trajectory $\tau$ at the timestep $t$ as a sum of future rewards from the timestep $t$ to the end of trajectory: $R_{t}=\sum^{T-1}_{t^{\prime}=t}r_{t^{\prime}}$. The goal of a RL agent is to learn policy $\pi$ that maximizes the expected return. In online RL, the trajectories used to train an agent are obtained iteratively as the agent interacts with the environment. In offline RL, the agent does not interact with the environment during training. A fixed set of trajectories collected by an arbitrary policy is used for training. Although such a setting is more difficult because it does not allow additional exploration of the environment or generation of new trajectories, it is preferable for tasks where interaction with the environment is costly or risky, such as in robotics.

### 2.2 Partially Observable Markov Decision Process

In the real world, there are frequent situations where the full state of the environment is not available to the agent, so the Markov Property is violated, and the agent is said to receive observations instead of state as input. In this case, observations are no longer sufficient statistics of the past to make a decision in the current step. An example would be a robot navigating an environment based on a camera image or a situation in which a decision must be made based on information from the past that is not available in the current observation. A Partially Observable Markov Decision Process (POMDP) is used in such cases. POMDP is a generalization of the MDP and is written as $\langle\mathcal{S},\mathcal{A},\mathcal{O},\mathcal{P},\mathcal{R},\mathcal{Z}\rangle$, where $o\in\mathcal{O}$ – observations, $s\in\mathcal{S}$ – states, $a\in\mathcal{A}$ – actions, $r=\mathcal{R}(s,a)$ – immediate reward function, $\mathcal{P}(s^{\prime}|s,a)$ – state transition function and $\mathcal{Z}$ is an observation function $\mathcal{Z}^{a}_{s^{\prime}o}=P(O=o_{t+1}|S_{t+1}=s^{\prime},A_{t}=a)$.
To work successfully in such environments, mechanisms such as memory are needed to allow the use of information from the past (Parisotto et al., ; Lampinen et al., ; Esslinger et al., ). In our work, we propose an approach of adding memory to the agent in the form of memory embeddings, caching of hidden states, and MRV. In this paper we consider the setting of an offline model-free RL, where learning is formulated as a sequence modeling problem (Chen et al., ).

## 3 Recurrent Action Transformer with Memory

Figure: Algorithm 1 Recurrent Action Transformer with Memory

In this paper, we introduce a new architecture, Recurrent Action Transformer with Memory (RATE), in which we utilized recurrently trained memory embeddings (Bulatov et al., ) and caching of previous hidden states (Dai et al., ) to add memory, and Memory Retention Valve (MRV) to control information leakage from memory embeddings, allowing sparse sequences to be processed. The architecture of RATE is shown in Figure 1.

The RATE scheme is outlined in Algorithm 1. In the initial phase, we obtain embeddings $\tilde{R}$, $\tilde{o}$ and $\tilde{a}$ from the returns-to-go $R$, observations $o$, and actions $a$, respectively, using the corresponding encoders from Table 10. We then generate a trajectory $\tau_{0:T-1}$ consisting of triplets of these embeddingsx according to the technique described in the Decision Transformer (DT) (Chen et al., ) paper (Algorithm 3).

Next, the trajectory $\tau_{0:T-1}$ is divided into $N=T//K$ segments $S_{n}\in\mathbb{R}^{3K\times d},\ n\in[0,N-1]$, each consisting of $K$ triplets, where $K$ is the context length and $d$ is the model dimension.
To each segment $S_{n}$, memory embeddings $M_{n}\in\mathbb{R}^{m\times d}$ are concatenated at the beginning and at the end, forming a $\tilde{S}_{n}\in\mathbb{R}^{(3K+2m)\times d}$, where $m$ is the number of memory embeddings.
These segments $\tilde{S}_{n}$ are then fed into the transformer and the output is the predicted actions $\hat{a}_{n}=\hat{a}_{n\times K:(n+1)\times K}$, which are used to compute loss, and new memory embeddings $M_{n+1}$, which are then processed by the MRV block and transmitted to the next segment $S_{n+1}$.

The MRV scheme is presented in Algorithm 2 and is based on the cross-attention basis.
After the transformer processes the segment $S_{n}$, the previous memory embeddings $M_{n}$ and the new memory embeddings $M_{n+1}$ obtained at the output of the transformer are fed to the input of the MRV block.
Next, $M_{n}$ are multiplied by the query matrix $\mathbf{W}_{Q}^{h}$, and $M_{n+1}$ are multiplied by the key $\mathbf{W}_{K}^{h}$ and value $\mathbf{W}_{V}^{h}$ matrix for each of the attention heads $h$.
Then the attention scores are calculated using the $\texttt{softmax}()$ function, the results for each of all attention heads are concatenated and after linear transformation using the matrix $\mathbf{W}_{M}^{T}$ the final memory tokens $M_{n+1}$ are obtained at the output, which is passed to the next segment.

Unlike the DT learning process, where random fragments of length $K$ are cut from trajectories, we process segments of length $K$ sequentially, which allows us to capture all information in the processed trajectory. Thus, using memory mechanisms, we are able to process sequences of length $K_{eff}=K\times N$, where $K_{eff}$ is the effective context (Bulatov et al., ).

## 4 Experimental Evaluation

We designed experiments to accomplish two primary objectives: (a) to demonstrate the advantage of our RATE model in memory-intensive environments (T-Maze (Ni et al., ), ViZDoom-Two-Colors (Sorokin et al., ), Memory Maze (Pasukonis et al., ), Minigrid-Memory (Chevalier-Boisvert et al., )), and (b) to investigate the effectiveness of the proposed model in classical MDPs to demonstrate its versatility (Atari (Bellemare et al., ) and MuJoCo (Fu et al., )).

For comparison with RATE, we chose DT (Chen et al., ) as the main baseline, and adapted the memory-augmented architectures Recurrent Memory Transformer (RMT) (Bulatov et al., ) and Transformer-XL (TrXL) (Dai et al., ) developed for NLP tasks to the RL domain. Information about the environments used can be found in Table 7.

### 4.1 Memory-intensive environments

To test RATE memory mechanisms, we use memory-intensive environments Figure 2, i.e., environments where the agent requires memory to operate successfully. A brief description of these environments is presented below, and a full description and data collection methodology can be found in the Appendix B.

- 1.
ViZDoom-Two-Colors (Sorokin et al., ) – an agent in an acid-filled room observes a quickly disappearing green or red pillar. To stay alive, the agent must recall the pillar’s color and gather items of the same color.
- 2.
T-Maze (Ni et al., ) – an agent navigates a T-shaped corridor, receiving a clue at the start about which direction to turn at the end of the corridor. The task tests memory in a prolonged sparse reward environment (the agent receives a reward only at the end).
- 3.
Memory Maze (Pasukonis et al., ) – an agent navigates a maze, seeking objects matching the color of its view frame. The frame color changes after each successful find. The goal is to collect the most matching objects within a time limit.
- 4.
Minigrid-Memory (Chevalier-Boisvert et al., ) – a similar task to T-Maze, but with different observation spaces and reward functions (see Appendix B, Table 7). Another important difference is that the agent appears at a random point at the beginning of the episode, not at the beginning of the corridor. Thus, in the case of Minigrid-Memory, it is necessary to reach that clue first (in T-Maze it is a memory problem, in Minigrid-Memory it is a memory and credit assignment problem (Ni et al., )).

Figure: Figure 2: Memory-intensive environments with different observation spaces and reward functions used to test the performance of the memory mechanism in the RATE model.
Refer to caption: extracted/5925481/plots/memory_envs_2.png

In the experiments, the same hyperparameters presented in Table 8 were used for RATE, DT, RMT, and TrXL to simplify the comparison. The context length $K$ and the number of segments $N$ were chosen so that the effective context $K_{eff}=K\times N$ for RATE, RMT, and TrXL covers important events in memory-intensive environments during training. In turn, since DT has no memory mechanisms, for it $K=K_{eff}$. Thus, the context length $K$ for RATE, RMT and TrXL is less than the context length for DT by a factor of $N$, but all models process the same parts of trajectories. More information about the training procedure for each environment can be found in Appendix D.

### 4.2 Experimental Results

In this section, the main experimental results for each of the environments are presented in the corresponding paragraphs. Additional results can be found in the Appendix F. For each of the experiments, the same techniques were used for all models to obtain the results presented in the Appendix E. Unless otherwise indicated, all baselines were trained from scratch.

#### ViZDoom-Two-Colors.

The dataset for this environment was collected using a pre-trained Advantage Actor Critic (A2C) (Beeching et al., ), which has a slight bias in favor of selecting green items even if red items are required. However, the dataset is balanced by the pillars colors. Figure 3 (a) shows the inference results on all pillars, separately only on red pillars and separately only on green pillars.
As illustrated in the Figure 3 (a), for inference with the presence of a disappearing pillar at the beginning of the episode, all baselines have an average total reward for inference on green pillars greater than for inference on red pillars.

To prove that this is not due to the peculiarities of the algorithms, but to the presence of bias in the data, we performed an additional inference without a pillar at the beginning of the episode, demonstrating the ability of all baselines to collect exclusively green items. As can be seen from Figure 3 (b), DT learns the distribution of training data and is unable to remember the pillar color. In turn, baselines with memory mechanisms such as RATE, RMT and TrXL are successful in this task. The poor performance of baselines with memory on red pillars without the pillar at the episode beginning proves that it is the color of the pillar that they remember.

Figure: Figure 3: Results for the ViZDoom-Two-Colors: with (a) and without (b) pillar in the first $45$ steps of the episode; calculated at environment steps 0 0 – $89$ (c) and $90$ – $179$ (d); depending on the return-to-go (e, f, g). Pillar disappears after first $45$ steps, $K_{eff}=90$.
Refer to caption: extracted/5925481/plots/rate_vizdoom_main.png

This conclusion of DT’s inability to use information out of context as opposed to RATE is supported by the experimental results presented in Figure 3 (c, d), which illustrates the inference results for the first $90$ steps, where the pillar are entirely captured in the effective context, and the subsequent $90$ steps, where the pillar color information begins to disappear from the effective context (the context window moves as a sliding window). As a result, there is a drop in total reward for red-pillar environments by almost a factor of two, indicating DT’s inability to memorize information to use it out of context. In turn, for RATE, RMT, and TrXL, the values of total reward in the first and second cases are almost unchanged, indicating their ability to utilize information outside of the current context window.

Figure 3 (e, f, g) demonstrates the dependence of model performance on the return-to-go. In this paper, we used an empirical estimate of the target reward as the average of the top-$10$ total rewards in the training dataset. As can be seen, RATE not only significantly outperforms DT, but also outperforms the memory-augmented models RMT and TrXL.

Furthermore, Table 1 demonstrates that RATE outperforms not only transformer-based models (RMT, TrXL), but also recurrent baselines, which forget the pillars color fairly quickly and start to collecting green items like DT.

#### T-Maze.

The Figure 4 shows the inference results for the T-Maze.
To validate an agent’s long-term memory capabilities, we performed training on trajectories of length $90$ and inference on corridors of size $30$ – $900$, i.e. much larger than the effective context $K_{eff}=90$ of models. The Figure 4 demonstrates that DT’s ability to solve the task is limited by the length of the corridors in the training data. Specifically, DT-3, trained on trajectories of length $3\times 30=90$ with $K=K_{eff}=90$, exhibits a significant drop in performance (reaching a random turn guessing accuracy of $0.5$) when tasked with inference on corridors exceeding $90$ in length.

Figure: Figure 4: Results for the T-Maze environment with $K_{eff}=30\times 3=90$. The notations are represented as MODEL-N, where N is the number of segments into which the trajectories are divided.
Refer to caption: extracted/5925481/plots/rate_tmaze_main.png

In turn, RATE-3, RMT-3, and TrXL-3 (trained on $3\times 30=90$ steps) perform significantly better at inference corridor lengths longer than the model saw during training. Moreover, RATE-3 outperforms other memory-augmented baselines, indicating its ability to perform effectively in sparse environments. This confirms the ability of the RATE model to successfully memorize important information and retain it through a long time.

Additionally, Table 1 compares RATE with recurrent baselines. The results indicate that these baselines, unlike RATE, cannot handle sparse information, as shown by SR $=0.5$.

Table: Table 1: Comparison of Transformer (DT), RNN (Decision LSTM (DLSTM) (Siebenborn et al., ), Decision GRU (DGRU)) and SSM (Decision Mamba (DMamba) (Gu & Dao, )) models with RATE in memory-intensive environments. Results indicate the inability of RNN and SSM models to perform successfully in long-term memory sparse (T-Maze) and continuous (ViZDoom-Two-Colors) environments, in contrast to RATE. SR – Success Rate. DGRU is obtained by replacing the LSTM block with the GRU block (Chung et al., ) in DLSTM.

Figure: Figure 5: Results for the Minigrid-Memory environment, $K_{eff}=10\times 3=30$.
Refer to caption: extracted/5925481/plots/rate_minigrid_main.png

#### Minigrid-Memory.

The Figure 5 shows the results for the Minigrid-Memory. Training was conducted on grids of size $31$x$31$, inference was conducted on grids of size $11$x$11$ – $91$x$91$.
Unlike the previously discussed T-Maze, the credit assignment problem is also addressed here, since the agent first has to reach the oracle and find out which object to turn towards in the future.

The results show that TrXL performs better than the other baselines on grids of size smaller or equal to those used in training, and worse than the other baselines on larger grids, that is, it interpolates well and extrapolates poorly. In turn, for RMT we observe exactly the opposite situation: RMT interpolates poorly and extrapolates well. RATE performs slightly worse than TrXL but better than RMT on small grid sizes, and slightly worse than RMT but better than TrXL on large grid sizes, but on average has interpolation and extrapolation abilities better than RMT and TrXL individually, as well as greater stability.

#### Memory Maze.

Table 2 shows the results of comparing RATE with other basic baselines with and without memory. The results show that RATE is able to memorize the implicit information like maze structure more efficiently, which is reflected in a higher average reward per episode.

Table: Table 2: Results for the Memory Maze $9$x$9$ environment.

#### Atari and MuJoCo.

The results for Atari and MuJoCo are presented in Table 3 and Table 4.
Results for Decision Mamba (DMamba) (Ota, ) and Mamba as Decision Maker (MambaDM) (Cao et al., ) are from the corresponding papers. A more detailed description of the results obtained can be found in the Appendix D. The results demonstrate that RATE not only performs as well as the algorithms specifically designed for offline RL, but in many cases outperforms them in classical environments that do not require memory, which indicates the versatility of the model.

Table: Table 3: Raw scores for Atari games. Green – top-1 result, light green – top-2 result within the standard deviation.

Table: Table 4: Scores normalized according to the protocol in Fu et al. () for MuJoCo control tasks. ME – Medium-Expert dataset, M – Medium dataset, MR – Medium-Replay dataset. RATE outperforms DT in 9/9 of the cases. Green – top-1 result, light green – top-2 result within the standard deviation.

## 5 Ablation Study

In this section, we answer the following research questions (RQs) to evaluate the impact of memory on model performance:

- 1.
"How do the different components of RATE affect model performance in memory-intensive environments?"— RQ 1..
- 2.
"What is the upper-bound estimate of the performance of the RATE model?"— RQ 2..
- 3.
"Why do you need an MRV and what is its best configuration?"— RQ 3..

Figure: Figure 6: Results of replacing RATE memory tokens and cached hidden states with white noise during inference in ViZDoom-Two-Colors.
Refer to caption: extracted/5925481/plots/rate_vizdoom_noise_solo.png

#### RQ 1.

Investigating the impact of RATE components.
To study the influence of memory embeddings on RATE model performance, we conducted the following experiment: for the RATE model trained for T-Maze (with context $K=30$ on $N=3$ segments), we replaced pre-trained memory embeddings $M$ with random noise vectors during inference (see Figure 7).

Using random noise instead of memory embeddings, SR $=50\%$ in the T-Maze, indicating the agent reaches the junction but turns in only one direction regardless of the clue. Thus, we conclude that clue information is in memory embeddings, while the rest of the actions are shaped by transformer parameters.

During RATE inference in ViZDoom-Two-Colors environment with replacement of different components of memory RATE mechanisms (memory embeddings and cached hidden states) with noise (see Figure 6), it is found that for this environment the caching of hidden states has the largest contribution, because with its noise performance drop is the largest.
Thus, in sparse environments, memory embeddings contribute the most, while in continuous environments, hidden states caching is most impactful.

Figure: Figure 7: Results of replacing RATE memory tokens with white noise curing inference in T-Maze.
Refer to caption: extracted/5925481/plots/tmaze_noise.png

#### RQ 2.

Performance upper-bound estimate.
To evaluate the maximum possible performance of the RATE model, we conducted experiments with OracleDT – a DT model whose context is augmented as a pre- and post-fix with a vector $v$ of dimension $1\times\texttt{d_model}$ containing a priori 1-bit information about the environment. Thus, in the T-Maze environment, this information is represented by a clue at the beginning of the episode ($v_{i}=0$ if clue = 0 else $1$), and in the ViZDoom-Two-Colors environment, it is represented by a column color ($v_{i}=0$ if column color = red else $1$). A context $S^{{}^{\prime}}=\texttt{concat}(v,S,v)$ extended in this way can be interpreted as a context $\texttt{concat}(M,S,M)$ with $M$ memory embeddings added, trained perfectly and containing $100\%$ of the important information. Thus, in environments where the a priori information about the environment needed for decision making can be extracted into a given vector $v$, the condition $R[OracleDT]\geq R[RATE]\geq R[DT]$ must be satisfied (see Table 5). This a priori information cannot be extracted from the environment in general, which further emphasizes the advantage of RATE, which is able to automatically extract important information and record it in memory embeddings $M$.

**Table 5: Comparison of OracleDT with RATE. OracleDT determines the upper-bound estimate for the maximum reward that can be obtained using RATE in the environment. SR – Success Rate.**
| T-Maze |  |  |  |
| --- | --- | --- | --- |
|  | OracleDT<br>($K=90$) | DT (Chen et al., )<br>($K=90$) | RATE<br>($K_{eff}=3\times 30=90$) |
| SR ($T=90$) | 1.0 $\pm$ 0.0 | 1.0 $\pm$ 0.0 | 1.0 $\pm$ 0.0 |
| SR ($T=480$) | 1.0 $\pm$ 0.0 | 0.5 $\pm$ 0.0 | 0.90 $\pm$ 0.07 |
| SR ($T=900$) | 1.0 $\pm$ 0.0 | 0.5 $\pm$ 0.0 | 0.90 $\pm$ 0.07 |
| ViZDoom-Two-Colors |  |  |  |
| Reward[Total] | 56.5 $\pm$ 0.8 | 24.8 $\pm$ 1.4 | 41.5 $\pm$ 1.0 |
| Reward[Reds] | 55.3 $\pm$ 1.6 | 7.2 $\pm$ 0.4 | 38.2 $\pm$ 5.1 |
| Reward[Greens] | 57.2 $\pm$ 0.5 | 42.3 $\pm$ 3.3 | 44.7 $\pm$ 5.8 |

#### RQ 3.

Memory Retention Valve architecture ablation.
Without MRV in the T-Maze environment at corridor lengths of $L\gg K$, the performance of the RATE model decreased with each segment processed at inference, resulting in almost SR $=50$% on long trajectories (see Table 6). For example, in the T-Maze task, the important information to be remembered goes into memory embeddings when processing the first segment of the sequence, and then it must be retrieved when making decisions on the last segment. At the same time, due to the recurrent structure of the architecture, memory embeddings continue to be updated during the processing of intermediate segments when no new information needs to be memorized, causing important information from memory embeddings to leak out. To retain important information in memory embeddings, MRV mechanism was added to the architecture.
We considered the five different schemes detailed in subsection F.3 to implement MRV:

- 1.
MRV-CA-1: cross-attention-based MRV which uses an attention mechanism to control the updating of memory embeddings. The updated memory embeddings $M_{n+1}$ are fed to Query, and the incoming $M_{n}$ are fed to Key and Value.
- 2.
MRV-CA-2: uses the same mechanism as MRV-CA-1 but the incoming memory embeddings $M_{n}$ are fed to Query, and the updated $M_{n+1}$ are fed to Key and Value.
- 3.
MRV-G: gated MRV which uses a gating mechanism similar to the one used in GTrXL (Parisotto et al., ).
- 4.
MRV-GRU: uses a GRU (Chung et al., ) block to process updated $M_{n}$ with hidden states.
- 5.
MRV-LSTM: uses a LSTM (Hochreiter & Schmidhuber, ) block to process updated $M_{n}$ with cached states.

Table: Table 6: Results of ablation study of MRV configuration on T-Maze environment. $\dagger$ – baseline.

The best results in Table 6 were obtained using cross-attention scheme (MRV-CA-2), in which we fed $M_{n}$ memory tokens from the transformer input to the query and $M_{n+1}$ memory tokens from the transformer output to the key and value. This configuration is used throughout the work and is denoted simply as MRV. This configuration acts as an effective gating mechanism to prevent the loss of important information in prolonged sparse environments, which is reflected in significantly better results for RATE in the T-Maze environment.

## 6 Related Work

### 6.1 Transformers for Reinforcement Learning

Transformers have found application in various areas of RL (Agarwal et al., ; Li et al., ): online RL (Parisotto et al., ; Lampinen et al., ; Esslinger et al., ; Melo, ; Zheng et al., ; Pramanik et al., ; Team et al., ), offline RL (Chen et al., ; Janner et al., ; Lee et al., ; Reed et al., ; Jiang et al., ), and model-based RL (Chen et al., ; Micheli et al., ; Robine et al., ). The use of transformers as a general policy for many environments is also being explored (Lee et al., ; Melo, ; Reed et al., ). In our work, we consider the formulation of an offline model-free RL, where learning is formulated as a sequence modeling problem (Chen et al., ). Prominent representatives of such models are (Chen et al., ; Janner et al., ; Lee et al., ; Jiang et al., ), although planning in latent space (Jiang et al., ) is considered, which can be seen as modeling of the environment. Moreover,  (Janner et al., ; Jiang et al., ) are specialized for control tasks with vector observations and do not generalize to environments with observations in the form of images.
Therefore, we consider the Decision Transformer (Chen et al., ), which has no memory mechanism, as the main baseline for comparison.

### 6.2 Recurrent Neural Networks for Reinforcement Learning

For long input sequences, recurrent networks may have computational advantages over transformers. The RNNs recurrent unit maintains a hidden state, which is essentially a form of memory that is important for solving POMDPs. In Decision LSTM (DLSTM) (Siebenborn et al., ) in DT the transformer is replaced by an LSTM unit (Hochreiter & Schmidhuber, ).

### 6.3 State Space Models for Reinforcement Learning

Recently, State Space Models (SSMs) (Gu et al., ) have shown significant success in sequence modeling, particularly in offline RL (Bar-David et al., ; Cao et al., ; Gu & Dao, ; Ota, ). In Decision S4 (DS4) (Bar-David et al., ), sequence modeling is executed using S4 (Gu et al., ) layers within the framework of offline RL, whereas Decision Mamba (DMamba) (Ota, ) utilizes the most recent Mamba (Gu & Dao, ) sequence model instead of causal self-attention. Mamba Decision Maker (MambaDM) (Cao et al., ) integrates the unique features of SSMs to effectively combine local and global features with Global-local fusion Mamba (GLoMa) module.

### 6.4 Memory in Transformers

There are many ways to implement the memory mechanism for transformers (Bulatov et al., ; Dai et al., ; Ding et al., ; Lei et al., ; Rae et al., ; Wu et al., ; ). In Transformer-XL (TrXL) (Dai et al., ), it is proposed to split a long data sequence into segments and to access past segments at the expense of memory, but to ignore very distant segments. This increases the effective length of the context. The Compressive Transformer (Rae et al., ) uses compressed memory, allowing previous versions of memory to be compressed rather than discarded as in TrXL. ERNIE-Doc (Ding et al., ) suggests using the retrospective feed mechanism and the enhanced recurrence mechanism. Memformer (Wu et al., ) uses external dynamic memory to encode and retrieve past information. MART (Lei et al., ) extends this idea by adding a memory update mechanism similar to a recurrent neural network (Cho et al., ; Hochreiter & Schmidhuber, ). The Memorizing Transformer (Wu et al., ) proposes to store the internal representations of past inputs. The Recurrent Memory Transformer (RMT) (Bulatov et al., ) includes additional read and write memory tokens at each segment’s beginning and end. This method allows the effective context to be expanded to over 1 million tokens (Zhu et al., ).

An Adaptive Agent (AdA) (Bauer et al., ) uses memory architectures to store and employ information previously acquired by the agent. The default memory architecture is TrXL with normalization before each layer (Parisotto et al., ), and the use of gating on the feedforward layers (Shazeer, ) to stabilize training. We also use TrXL in our work but refrain from using additional modifications to stabilize training. Another distinctive feature of using a transformer in AdA, as opposed to DT, is that pixel observations, past actions, past rewards, and additional information are not tokenized separately but are combined into a single vector that feeds the transformer. The transformer itself predicts not only actions but also value function values.

## 7 Conclusion

In this paper, we propose Recurrent Action Transformer with Memory (RATE), a transformer model for offline RL that exploits memory mechanisms in the form of memory embeddings and caching of hidden states, and the Memory Retention Valve (MRV), which controls memory updating and prevents the loss of important information in sparse tasks.
In extensive experiments in memory-intensive environments such as ViZDoom-Two-Colors, Memory Maze, Minigrid-Memory, and T-Maze, we have shown that RATE outperforms recurrent and transformer baselines.
The proposed model interpolates and extrapolates well outside the transformer context, is able to retain important information for a long time when operating in highly sparse environments, and allows to compensate for the effect of bias in the training data.

We also show that the proposed model achieves better or comparable results to state-of-the-art Mamba-based models in Atari and MuJoCo environments, indicating that RATE is suitable for all tasks: both memory-intensive and not. We have thoroughly investigated the influence of memory mechanisms on the performance of the model and have clearly shown that the model uses them in decision making. This method shows great potential for tackling complex tasks with long sequences, especially in robotics, where training agents on pre-collected data sets is highly advantageous.

#### Limitations.

Limitations of the proposed model include its inability to design $K$ and $N$ in memory-intensive environments so that all important events fall into the efficient context of $K_{eff}=K\times N$. In addition, the approach based on dividing trajectories into segments during inference does not allow for memory updates effectively at each step using a sliding window. Also, there are currently no studies of the memory capacity of the proposed model, so the practical amount of information that can be stored remains unknown.

#### Reproducibility Statement.

The model description is presented in section 3 (Algorithm 1 and Algorithm 2), the training procedure is presented in Appendix D, the description of the used benchmarks is presented in Appendix B, the hyperparameters are presented in Table 8, and the configurations for displaying the experimental results are presented in Table 9.
The code is open-sourced and can be found in the [https://sites.google.com/view/rate-model/](https://sites.google.com/view/rate-model/).

## Appendix A Decision Transformer

Figure: Algorithm 3 Decision Transformer

Decision Transformer (DT) (Chen et al., ) is an algorithm for offline RL that reduces the RL task to a sequence modeling task. In DT, the scheme of which is presented in Algorithm 3, the trajectory $\tau$ is not divided into segments as in RATE. Instead, random fragments of length $K$ are sampled from the trajectory, since originally this architecture was designed to work only with MDP. The predicted actions $\hat{a}$ are sampled autoregressively.

## Appendix B Environments

### B.1 Memory-intensive environments

In this section, we provide an extended description of the environments used in this paper, as well as the methodology used to collect the trajectories. Table 7 summarizes the observations type, rewards type, and actions type for each of the environments considered in this paper.

#### ViZDoom-Two-Colors.

We used a modified ViZDoom-Two-Colors environment from (Sorokin et al., ) to assess the model’s memory abilities. The agent initially having $100$ hit points (HP) is placed in a room without inner walls filled with acid. At each step in the environment, the agent loses a fixed amount of health ($10/32$ HP per step). In the center of the environment, there is a pillar of either green or red color, which disappears after $45$ environment steps. Throughout the environment, objects of two colors (green and red) are generated. When the agent interacts with an object of the same color as the pillar, it gains an increase in health of $+25$ and a reward of $+1$. When the agent interacts with an object of the opposite color, it loses a similar amount of health. The agent receives an additional reward of $+0.02$ for each step it survives. The episode ends when the agent has zero health. Thus, the agent needs to remember the color of the pillar to select items of the correct color, even if the pillar is out of sight or has disappeared. The agent does not receive information about its current health or rewards, as these observations essentially convey the same information as the color of the pillar but persist beyond step $45$.

We collected a dataset of $5000$ trajectories of $90$ steps in length using a trained A2C (Beeching et al., ) agent (an agent trained with a non-disappearing pillar). The average reward for these $90$ steps is $4.46$. When collecting trajectories, to ensure that the agent saw the pillar before it disappeared, the agent always appeared facing the pillar in the same place – midway between the pillar and the nearest wall. In order to successfully complete this task, the agent needs to remember the color of the pillar. This environment tests the long-term memory mechanism, since the agent needs to retain information about the pillar for a time much longer than the pillar has been in the environment. Using only short-term memory and, for example, collecting the next item of the same color as the previous collected item, it will not be possible for the agent to survive for a long time, as this policy is extremely unstable. This is due to the fact that in the training dataset the agent occasionally makes a mistake and picks up an object of the opposite color. Thus, irrelevant information about the desired color may enter the transformer context and the agent will start collecting items of an opposite color, which will quickly lead to a failure.

#### T-Maze.

To investigate agent’s long-term memory on very long environments (the inference trajectory length is much longer than the effective context length $K_{eff}$) we used a modified version of the T-Maze environment (Ni et al., ). The agent’s objective in this environment is to navigate from the beginning of the T-shaped maze to the junction and choose the correct direction, based on a signal given at the beginning of the trajectory using four possible actions $a\in\{left,up,right,down\}$. This signal, represented as the $clue$ variable and equals to zero everywhere except the first observation, dictates whether the agent should turn up ($clue=1$) or down ($clue=-1$). Additionally, a constraint on the episode duration $T=L+2$, where the maximum duration is determined by the length of the corridor $L$ to the junction, adds complexity to the problem. To address this, a binary flag, represented as the $flag$ variable, which is equal to $1$ one step before the junction and 0 0 otherwise, indicating the arrival of the agent at the junction, is included in the observation vector. Additionally, a noise channel is added to the observation vector, with random integer values from the set $\{-1,0,+1\}$. The observation vector is thus defined as $o=[y,clue,flag,noise]$, where $y$ represents the vertical coordinate. The reward $r$ is given only at the end of the episode and depends on the correctness of the agent’s turn at the junction, being $1$ for a correct turn and 0 0 otherwise. This formulation deviates from the traditional Passive T-Maze environment (Ni et al., ) (different observations and reward functions) and presents a more intricate set of conditions for the agent to navigate and learn within the given time constraint.

The dataset consists of $2000$ of trajectories for each segment of length $30$ (i.e. $6000$ trajectories for the $K_{eff}=3\times 30=90$) and consists only of successful episodes. An artificial oracle with a priori information about the environment was used to generate the dataset.

**Table 7: Description of observations and reward functions for the considered environments.**
| Environment | Obs. type | Rewards | Actions | Obs. info |
| --- | --- | --- | --- | --- |
| ViZDoom-Two-Colors | Image | Continuous | Discrete | First-person view |
| T-Maze | Vector | Sparse<br>& Discrete | Discrete | Vector |
| Memory Maze | Image | Sparse<br>& Discrete | Discrete | First-person view |
| Minigrid-Memory | Image | Sparse | Discrete | Observes the $3\times 3$<br>part of the grid |
| Action Associative Retrieval | Vector | Sparse<br>& Discrete | Discrete | Vector |
| Atari | Image | Sparse<br>& Discrete | Discrete | Observes the<br>full game screen |
| MuJoCo | Vector | Continuous | Continuous | Vector |

#### Memory Maze.

In this first-person view 3D environment (Pasukonis et al., ), the agent appears in a randomly generated maze containing several objects of different colors at random locations. The agent’s task is to find an object of the same color in the maze as the outline around its observation image. After the agent finds an object of the desired color and steps on it, the color of the outline changes and the agent must find another object. The agent receives a $+1$ reward for stepping on the correct object. Otherwise, it receives no reward. The duration of an episode is a fixed number and is equal to $1000$. Thus, the agent’s task is to find as many objects of the desired color as possible in a limited time. The agent’s effectiveness in this environment depends on its ability to memorize the structure of the maze and the location of objects in it in order to find the desired objects faster.
Using the Dreamer model (Hafner et al., ) to collect dataset of $5000$ trajectories only achieved an average award of $4.7$ per episode, i.e., a rather sparse dataset.

#### Minigrid-Memory.

Minigrid-Memory (Chevalier-Boisvert et al., ) is a 2D grid environment designed to test an agent’s long-term memory and credit-assignment (Ni et al., ). The environment map is a T-shaped maze with a small room with an object inside it at the beginning of the corridor. The agent appears at a random coordinate in the corridor. The agent’s task is to reach the room with the object and memorize it, then reach the junction at the end of the maze and make a turn in the direction where the same object is located as in the room at the beginning of the maze. A reward $r=1-0.9\times\frac{t}{T}$ is given for success, and 0 0 for failure. The episode ends after any agent turns at a junction or after a limited amount of time (95 steps) has elapsed. The agent’s observations are limited to a $3\times 3$ size frame. $10000$ trajectories with grid size $31$x$31$ were collected using PPO (Schulman et al., ) with TransformerXL (Pleines et al., ) with a context length equal to the maximum episode duration.

### B.2 Standard benchmarks

#### Atari games.

For the Atari game environments (Bellemare et al., ), we used the same dataset as in DT, namely the DQN replay dataset with grayscale state images (Agarwal et al., ). This dataset contains $500$ thousand of the $50$ million steps of an online DQN (Mnih, ) agent for each game. We use the following set of games: SeaQuest, Breakout, Pong and Qbert.

#### MuJoCo.

Despite the fact that memory is not required in decision making in control environments like MuJoCo (Fu et al., ), we conducted additional experiments in this environment to compare with DT. For the continuous control tasks, we selected a standard MuJoCo locomotion environment and a set of trajectories from the D4RL benchmark (Fu et al., ). Since we chose DT and TAP as the main models for comparison on this data, we focused on the environments used in both works (HalfCheetah, Hopper, and Walker). We used three different dataset settings: 1) Medium – $1$ million timesteps generated by a “medium” policy that achieves about a third of the score of an expert policy; 2) Medium-Replay – the replay buffer of an agent trained with the performance of a medium policy (about $200$k–$400$k timesteps in our environments); 3) Medium-Expert – $1$ million timesteps generated by the medium policy concatenated with 1 million timesteps generated by an expert policy. The scores for the MuJoCo experiments are normalized such that 100 represents an expert policy, following the benchmark protocol outlined in (Fu et al., ). The performance metrics for Conservative Q-Learning (CQL) and Trajectory Autoencoding Planner (TAP) are reported from the TAP paper (Jiang et al., ), and for DT from the DT paper (Chen et al., ), as they use the same dataset and evaluation protocol.

Figure: Figure 8: Action Associative Retrieval.
Refer to caption: extracted/5925481/plots/aar.drawio.png

## Appendix C Action Associative Retrieval

As shown in subsection 4.2, DT has a SR $=50\%$ for inference at corridor lengths longer than the transformer context length. This is due to the fact that even a DT trained on balanced data has a slight bias in the predicted probability towards one of the two required actions, which leads to the fact that when $t>K$ the agent constantly produces only one action: up or down. In turn, the presence of memory in the agent allows us to combat this problem.

To check how the agent’s performance changes during training, we design an Action Associative Retrieval (AAR) Figure 8 environment.

There are two states in this environment: $S_{0}$ and $S_{1}$. The agent appears in state $S_{0}$ and by performing the action $a_{0}\in\{0,1\}$ moves to state $S_{1}$. Next, the agent must take $N-2$ steps to move from state $S_{1}$ to state $S_{1}$ by performing action $a=2$ (no op.).
At the end of the episode, the agent must perform the same action that moved it from state $S_{0}$ to state $S_{1}$ in order to move from state $S_{1}$ to state $S_{0}$.
Thus, the action $a\in\{0,1,2\}$.
Agent observations $o=[state,flag,noise]$, where $state\in\{0,1\}$ is the index of the current state, $flag\in\{0,1\}$ is a flag equal to $1$ in case the next step requires returning to the initial state and equal to 0 0 otherwise, $noise\in\{-1,0,+1\}$ is the noise channel. The agent receives a $+1$ reward if it returns to the initial state $S_{0}$ by performing the action that took it out from the $S_{0}$ to the $S_{1}$, and $-1$ in other cases. The training dataset consists of oracle-generated $6000$ trajectories with positive reward.

More formally, we can talk about the presence of memory in an agent when solving AAR (T-Maze-like) tasks under the condition that:

$$ $\forall t>K:\frac{1}{N_{0}}\sum_{i=1}^{N_{0}}p_{i}(a_{t}=a^{0}|a_{0}=a^{0})+ \frac{1}{N_{1}}\sum_{i=1}^{N_{1}}p_{i}(a_{t}=a^{1}|a_{0}=a^{1})>1$ (1) $$

This condition means that if the agent has memory, the sum of the average conditional probabilities over all experiments will be greater than one, i.e., these probabilities are independent of each other. Provided that the sum of these probabilities is less than or equal to one, the agent will choose at best the same target action in most experiments, even if another action is required.

where $a^{0},a^{1}\in\mathcal{A}$ – two mutually exclusive actions leading to a reward; $t$ is the step at which the final action is required; $N_{0},N_{1}$ are the number of experiments in environments where target action $a_{t}=a^{0}$ and $a_{t}=a^{1}$, respectively.

Figure: Figure 9: Experimental results with RATE and DT in the AAR environment. The graphs show the 10-runs average results of training on trajectories of length $T=90$ and validation on trajectories of length $T=180$, for RATE with $K_{eff}=3\times 30=90$ and for DT with $K=90$.
Refer to caption: extracted/5925481/plots/cross_plots.png

In the results Figure 9, the first $1\%$ of training steps was removed because it corresponds to the beginning of the training and is unrepresentative. Blue dots correspond to the beginning of training, red dots to the end of training.
As can be seen from Figure 9, during training, the probabilities $p_{i}(a_{t}=a^{0}|a_{0}=a^{0})$ and $p_{i}(a_{t}=a^{1}|a_{0}=a^{1})$ on the training trajectories have a strong positive correlation ($R_{train}^{DT}=1.00$ and $R_{train}^{RATE}=0.97$), where $R$ – correlation coefficient. This indicates that within-context (effective context) DT and RATE models are able to predict both $a^{0}$ and $a^{1}$ actions equally well.

At the same time, during validation, for the RATE model this pattern is preserved – the red points corresponding to the probabilities of choosing actions $a^{0}$ and $a^{1}$ are in the upper right part of the graph, positive correlation persists ($R_{val}^{RATE}=0.80$). On the other hand, in the DT case, the cluster of red dots is skewed toward choosing action $a^{1}$ and action $a^{0}$ with equal probabilities equal to $0.5$. Thus, in sum, these probabilities are less or equal to one, as evidenced by a strong negative correlation ($R_{val}^{DT}=-0.97$). The results confirm the inability of DT to generalize on trajectories whose lengths exceed the context length and the ability of RATE to handle such tasks.

## Appendix D Training

This section provides additional details on the training process of the baselines considered in the paper.
It is important to note that when training RATE in the transformer decoder the feed-forward network block was disabled, because without it on some environments the training results are slightly better. However, other transformer-based baselines were trained with the standard transformer decoder.

#### ViZDoom-Two-Colors.

Since the pillar disappears at time $t=45$, all trajectories start at time $t=0$ and end at time $t=90$ so that the information about the color of the pillar is guaranteed to be used in training. In this experiment, we compared DT with context length $K=90$ to RATE, RMT, and TrXL models with context length $K=30$ and partitioning the trajectory into $N=3$ segments. Thus, when trained, RATE also handles sequences of length $90$, since its effective context is $K_{eff}=N\times K=90$, but only processed subsequences of length $K=30$.

#### T-Maze.

The model names are written in the format MODEL-N, where $N$ is the number of segments of length $K=30$ into which the training trajectories can be partitioned. Thus, DT-3 was trained on trajectories of length $T\leq 3\times 30=90$ with context length. RATE-3 was trained on similar trajectories as DT-3, but with each trajectory divided into $3$ segments, during training, enabling the training of a model with a context length of $K=30$ on trajectories of length $T=90$. All the trajectories used in training start from $t=0$, i.e., from the moment of receiving a clue.

#### Memory Maze.

To train RATE, DT, RMT, and TrXL on Memory Maze, the same approach was used as for ViZDoom-Two-Colors environment, except that trajectories were sampled not from $t=0$ but from $t:\sum_{t^{\prime}=t}^{t+90}r_{t^{\prime}}\geq 2$.

As in the ViZDoom-Two-Colors case, training for DT was performed with a context length of $K=90$ and for RATE, RMT, and TrXL with a context length of $K=30$ and number of segments $N=3$, i.e., effective context length $K_{eff}=N\times K=3\times 30=90$.

#### Minigrid-Memory.

To train RATE, DT, RMT, and TrXL in this environment, trajectories were sampled in the same manner as for T-Maze. An environment configuration with a maze of size $31$x$31$ was used as a training configuration. Since the maximum episode duration is $95$, training proceeded in the following setting: for DT the context length $K=30$, for RATE, RMT, and TrXL the context length $K=10$ and the number of segments $N=3$. All trajectories, as in T-Maze, are sampled from time $t=0$.

#### Atari and MuJoCo.

When training RATE on Atari games and MuJoCo control tasks, sequences of length $T=90$ (Atari) and $T=60$ (MuJoCo) were sampled randomly from the original trajectories in the dataset. These trajectories were then divided into $N=3$ segments of length $K=30$ (Atari) and $K=20$ (MuJoCo), forming an effective context of length $K_{eff}=N\times K=90$ ($60$ for MuJoCo).

For Atari, we used the identical experimental design described in the DT paper (Chen et al., ). It is worth noting that we presented raw scores for Atari, rather than gamer-normalized scores as described in the DT paper. Table 3 shows the results for Atari environments.
RATE outperforms DT significantly in environments like Breakout and Qbert. We attribute this to the observation that, although these environments do not explicitly demand memory, intricate dynamics from the past exert a greater influence on agent behavior than in environments such as SeaQuest. Actions executed in the past notably alter the present state of the environment in Breakout and Qbert, whereas in SeaQuest, such actions hold little significance. For instance, the emergence of enemies and divers in SeaQuest is entirely independent of the agent’s prior actions.

For MuJoCo, our findings suggest that the conventional strategy of utilizing return is not suitable for our segment-based scheme. The issue arises during the trajectory, where the agent’s return persistently diminishes. However, the true value of the agent’s state at the onset and conclusion of the episode could remain unchanged, provided the agent’s policy performs consistently well. To rectify this discrepancy, we propose a novel evaluation strategy for MuJoCo tasks. In this approach, each segment commences with the maximum return, simulating the scenario where the agent initiates the trajectory anew. This method effectively mitigates the aforementioned issue, enhancing the accuracy of our evaluation process. Our MuJoCo experiments in Table 4 show that this benefits performance significantly for some environments. Thus, using RATE allowed us to obtain the best metrics for MuJoCo in 4/9 cases compared to the other baselines. RATE also outperforms DT in 9/9 tasks.

Table: Table 8: RATE hyperparameters for different experiments. $\ddagger$ – Leaky ReLU in the Atari.Pong case.

## Appendix E Results presentation

This section provides information on how the presented experimental results were obtained. $N_{runs}$ denotes the number of model runs; $N_{seeds}$ denotes the number of inference episodes with different seeds; sem denotes standard error of the mean, and std denotes standard deviation.

**Table 9: Experimental parameters used to present the final results.**
| Environment | $N_{runs}$ | $N_{seeds}$ | Metric | Notation |
| --- | --- | --- | --- | --- |
| ViZDoom-Two-Colors | 6 | 100 | Total reward | mean $\pm$ sem |
| T-Maze | 10 | 100 | Success Rate | mean $\pm$ sem |
| Memory Maze | 3 | 100 | Total reward | mean $\pm$ sem |
| Minigrid-Memory | 3 | 100 | Total reward | mean $\pm$ sem |
| Action Associative Retrieval | 10 | — | Success Rate | mean $\pm$ sem |
| Atari | 3 | 100 | Total reward | mean $\pm$ std |
| MuJoCo | 3 | 100 | Total reward | mean $\pm$ std |

## Appendix F Additional ablation studies

To determine the optimal hyperparameters associated with memory mechanisms, additional ablation studies were performed in ViZDoom-Two-Colors and T-Maze environments, and the results are presented in Figure 11 and Figure 10 (right). From the ablation studies results, it was found that for environments like ViZDoom-Two-Colors with continuous reward signal and image observations, the best results can be obtained using number of cached memory tokens $\texttt{mem_len}=(K\times 3+2\times\texttt{num_mem_tokens})\times N$, where $K$ – context length and $N$ – number of segments.

On the other hand, for environments with sparse events like T-Maze, it has been found that using caching of hidden states of previous tokens ($\texttt{mem_len}>0$) prevents remembering important information. In this case, gating with $\texttt{n_head_ca}=4$ and moderate number of memory tokens $\texttt{num_mem_tokens}=5$ gives the best results (see Figure 10 (right)).

Figure: Figure 10: (left) Investigating the RATE memory tokens noise effect in the ViZDoom-Two-Colors. (right) Results of RATE-3 (trained on corridor lengths $\leq 90$) ablation studies in the T-Maze environment. n_head_ca – number of MRV attention heads, num_mem_tokens – number of memory tokens.
Refer to caption: extracted/5925481/plots/rate_noise_rtg.png

Figure: Figure 11: Results of RATE ablation studies in the ViZDoom-Two-Colors environment.
Refer to caption: extracted/5925481/plots/rate_vizdoom_main_vizdoom_ablation.png

### F.1 Additional ViZDoom-Two-Colors ablation

The effect of combining of memory tokens with noise is shown in Figure 10 (left). The noise was applied as a convex combination: $\texttt{memory_tokens}=(1-\alpha)\times\texttt{memory_tokens}+\alpha\times
\texttt{noise}$. With unchanged hidden states caching at growth of the noise parameter $\alpha$, at first there is a decrease of performance at inference on green pillars (up to $\alpha=0.5$), and only then a decrease of performance at inference on red pillars. This phenomenon can be explained by the fact that memory embeddings is trained to record mostly information about red pillars, which helps to combat bias in the training data.

**Table 10: RATE encoders for each part of $(R,o,a)$ triplets. We use Embedding layer for encoding discrete actions and Linear for continuous ones. $\ddagger$ – channels / kernel sizes / padding.**
| Env. | R | O | Conv. configuration^‡ | A |
| --- | --- | --- | --- | --- |
| ViZDoom-Two-Colors | Linear | Conv2D $\times$ 3 | (32, 64, 64) / (8, 4, 3) / 0 | Embedding |
| T-Maze | Linear | Linear | – | Embedding |
| Memory Maze | Linear | Conv2D $\times$ 3 | (32, 64, 64) / (8, 4, 3) / 2 | Embedding |
| Minigrid-Memory | Linear | Conv2D $\times$ 3 | (32, 64, 64) / (8, 4, 3) / 0 | Embedding |
| Atari | Linear | Conv2D $\times$ 3 | (32, 64, 64) / (8, 4, 3) / 0 | Embedding |
| MuJoCo | Linear | Linear | – | Linear |

Figure: Figure 12: Memory Retention Valve configurations used in the ablation study. MRV-CA-2: cross-attention-based MRV which uses an attention mechanism to control the updating of memory embeddings and which is used in the work as the main mechanism. MRV-CA-1: uses the same mechanism as MRV-CA-2 but the updated memory embeddings $M_{n+1}$ are fed to Query, and the incoming memory embeddings $M_{n}$ are fed to Key and Value. MRV-G: gated MRV which uses a gating mechanism similar to the one used in Gated Transformer-XL (Parisotto et al., ). MRV-GRU: uses a GRU (Chung et al., ) block to process updated memory embeddings with hidden states. MRV-LSTM: uses a LSTM (Hochreiter & Schmidhuber, ) block to process updated memory embeddings with cached states.
Refer to caption: extracted/5925481/plots/gates_v3.png

### F.2 Curriculum Learning

Since in the T-Maze environment, the number of actions at the junction relates to the number of actions when moving straight along the corridor as $\frac{1}{L}$ and tends to 0 0 as $L$ increases, there is a significant imbalance in the agent’s action distribution, which can cause problems when performing rare class (turning actions) prediction.
Theoretically, this situation can be remedied through curriculum learning.

Curriculum learning (CL) is a technique in which a model is trained on examples of increasing difficulty.
In this approach, the model is first trained on the set of trajectories $Q_{1}=q_{1}$ of length $K\times 1$, then the trained model is re-trained on the set of trajectories $Q_{2}=q_{1}\cup q_{2}$, where the set $q_{2}$ is formed by trajectories of length $K\times 2$, and so on (in order of increasing complexity of the trajectories). Thus, for the $N$ segments considered during training, the set $Q_{N}=\bigcup_{i=1}^{N}q_{i}$ is used.

In the T-Maze environment, DT, RATE, RMT, and TrXL were trained with and without curriculum learning because this approach theoretically produces better results. However, it is important to note that the T-Maze task is successfully solved by the RATE model without using curriculum learning, and even vice versa – its use slightly degraded performance on long corridors. However, with respect to TrXL, the use of CL yielded slightly better results. The work showed that using CL does not achieve significantly better performance on the T-Maze task. The results of using the CL on the T-Maze environment are presented in Figure 13 (left), and the results of applying noise to memory embeddings to assess its importance are presented in Figure 13 (right).

Figure: Figure 13: (left). Results with and without the use of curriculum learning and (right) results of replacing RATE memory tokens with white noise at inference in T-Maze.
Refer to caption: extracted/5925481/plots/rate_tmaze_noise.png

### F.3 Supplemental MRV ablation

One of the options for implementing the memory tokenization gating mechanism was an approach similar to the one proposed in Gated Transforer-XL (GTrXL) (Parisotto et al., ) work. Thus, the MRV-G scheme was inspired by the gating mechanism from GTrXL and implemented as follows:

$$ $r=\sigma(M_{n}W_{r}+M_{n+1}U_{r})$ (2) $$

$$ $z=\sigma(M_{n}W_{z}+M_{n+1}U_{z}-\texttt{bias})$ (3) $$

$$ $h=\texttt{tanh}(M_{n}W_{g}+(M_{n+1}\times r)U_{r})$ (4) $$

$$ $\tilde{M}_{n+1}=\sigma(M_{n}(1-z)+z\times h)$ (5) $$

The results of the RATE (trained on corridor lengths of $\leq 150$) inference on the T-Maze environment with these MRV configurations are shown in Figure 14 and in Table 6. The results presented in Figure 14 confirm the high stability of RATE when using cross-attention-based MRV (MRV-CA-2), as well as the model’s ability to hold important information in memory embeddings when inference on long tasks.

Figure: Figure 14: Results of RATE inference with different MRV configurations on the T-Maze environment. Training was performed with the number of segments $N=5$ and context length $K=30$, i.e. on trajectories of length $\leq 150$. MRV-CA-2 is the final MRV configuration that is used throughout the work and is designated as MRV.
Refer to caption: extracted/5925481/plots/RATE_MEM_gates_ablation.png

## Appendix G Technical details

The Table 11 shows the technical parameters of the training models. Note that the difference between the number of DT and RATE parameters is small and equal to $\delta p$ = d_model $\times$ num_mem_tokens $\sim 10^{3}$. Training RATE with trajectory splitting into $N$ segments allows $\sim N$ smaller GPU memory size usage than for DT. The training was conducted using a single NVIDIA A100 80 Gb graphics card.

The code is available at [https://sites.google.com/view/rate-model/](https://sites.google.com/view/rate-model/).

**Table 11: Technical configurations of model training. The values in the table are for single run. The training was conducted on a single NVIDIA A100 GPU.**
| Env. | Model | GPU mem. | Train time | # params. |
| --- | --- | --- | --- | --- |
| ViZDoom-Two-Colors | RATE<br>DT | 24Gb<br>37Gb | 4h | 6.0M |
| T-Maze | RATE<br>DT | 10Gb<br>15Gb | 2h | 2.4M |
| Memory Maze | RATE<br>DT | 24Gb<br>37Gb | 12h | 6.0M |
| Minigrid-Memory | RATE<br>DT | 6Gb<br>15Gb | 10h | 6.0M |
| Atari | RATE<br>DT | 21Gb<br>32Gb | 9h | 4.7M |
| MuJoCo | RATE<br>DT | 15Gb<br>45Gb | 10h | 0.6M |

## Peer Reviews

confidence: 3
contribution: 1
initial_rating: 3
presentation: 2
questions: - Why are LSTM, GRU, Mamba unable to make *any* progress beyond on a random agent on such a simple task?
    - Where is the code for these baselines?
- Why did you create your own valve/gating mechanism instead of using one of the existing methods proposed by prior recurrent transformers?
soundness: 1
strengths: - The authors introduce a modification to decision transformers that improves performance
- The paper is fairly easy to follow
summary: The authors propose a memory-augmented transformer to use for long episodes in reinforcement learning. At a high level, their approach augments a decision transformer with a recurrent update to alleviate the memory pressure caused by $O(n^2)$ space complexity. The authors propose different gating mechanisms applied to the recurrent state that they call "valves". They compare their model to other types of decision transformers, and perform an ablation of valves.
weaknesses: I find some of the experimental results dubious, specifically the T-Maze experiments. In particular, the fact that only the author's proposed method and the decision transformer can solve a simple T-maze task. To succeed at the T-maze task, all a sequence model must do is memorize one bit of information (left or right) for 90 timesteps. Given that Mamba and its predecessors S4/S5 have been shown to memorize much more information over 16,000 timesteps gives me pause. 90 timesteps should be well-within the memory capabilities of even the LSTM or GRU. Furthermore, a score of 0.5 is what I would expect a memory-free agent to achieve, and this is precisely the score that the Mamba/LSTM/GRU models achieve.

I suspected the authors may have made a mistake during implementation, so I examined the "T-Maze_new" directory provided in the anonymous code link. However, there is no code or references to Mamba, GRU, or LSTM, and so I am not sure how the authors arrived at their conclusion. I do not want to sound overly harsh, but reproducibility is the biggest issue facing RL today.

Furthermore, most of the experiment tasks are what I would consider poor tests of memory. As far as I understand, both T-Maze and VizDoom require storing 1 bit of information presented at the initial timestep, for a duration of less than 100 timesteps. So I would not consider this a sufficient comparison between RATE and other related work.

Finally, I do not think this paper is very novel. Using a decision transformer to solve a reinforcement learning task is certainly not novel, and there have been numerous papers that extend the context length of transformers through the use of a recurrent state. I would consider this an incremental work, which would be fine if the experiments were convincing. But they are not.

---

confidence: 4
contribution: 3
initial_rating: 6
presentation: 3
questions: 1. what is "cached hidden states"? It is mentioned multiple times throughout the paper but lacks a clear definition.  
2. which Positional Encoding (PE) is used? Do you use any PE in MRV module?  
3. could you provide some experiments comparing RATE to ERNIE-Docs? The code change should be just minimal from TrXL  
4. in your Table 1, the performance of DMamba in T-Maze is quite lower to DT under the same context window (K = 90). Why is this?  What is the corridor length?   
5. I hope to see more of ablation studies. Especially about the capacity of memory chunk, the length of segment $S_n$ and the number of layers of transformer.  In appendix F, some of them seem to have been performed but  are correlated  with the "cached hidden states" and I don't quite understand what you're ablating on
6. could you show the  attention map  of causal and cross attention  during evaluation of the method ?
soundness: 3
strengths: ## originality:
The usage of memory chunk bears some similarity to existing works but the proposed MRV is  original and interesting, to my knowledge.

## quality:
The method is well supported by its experiments and ablation studies.

## clarity:
The paper is well written. I find most of it easy-to-read.

## significance:
Efficient Transformer for memory-intensive (RL) tasks is of great need and research interest. And this paper successfully designs a novel MRV method for it. Through the experiments conducted, the efficacy and advantage is demonstrated against some baseline methods.
summary: This paper studies how to design a new transformer architecture for RL tasks where history memory is needed. Due to the quadratic memory complexity of the vanilla transformer, naively expanding the context length would not result in an efficient solution to memory-intensive RL tasks. Therefore, authors propose to store memory information into a chunk that is updated after sequential processing of each segment. Through extensive experiments and detailed ablation study, the chosen memory chunk updating mechanism ---MRV--- is proven effective and superior towards other design choices.
weaknesses: I have several  concerns regarding this work:
1. lack of theoretical guidance. Since there is no theoretical guidance towards the design of RATE/MRV, I  think they are  likely empirically determined. This somehow shadows the contribution of this work. But I understand demanding this is beyond the scope.
2. ablation study. As Transformer itself is prone to many hyperparameters, I hope to see more ablation studies regarding various components of RATE (details in questions)

---

confidence: 3
contribution: 2
initial_rating: 5
presentation: 3
questions: 1.	Why could the Memory Retention Valve significantly improve the performance of RATE in memory-intensive environments? Could the authors give some examples or further explanations?
2.	As there are a lot of hyperparameters, is there some guidance to tune each of them?
soundness: 2
strengths: 1.	This paper is well-organized and a lot of details are included.
2.	RATE is validated on various memory-intensive environments. The results demonstrate RATE achieves good performance on different tasks and environments.
3.	The related works are well-studied and discussed.
summary: This paper presents the Recurrent Action Transformer with Memory (RATE), which extends a transformer model with a recurrent memory mechanism for offline reinforcement learning. RATE utilizes memory embeddings, caching of previous hidden states, and the Memory Retention Valve to help effective decision making which depends on the history information. Experimental results on memory-intensive environments, Atari games, and MuJoco control environments show that RATE is especially effective when the environment requires memory.
weaknesses: 1.	The idea of using the transformer for offline reinforcement learning tasks is not novel. At the same time, the motivation for Memory Retention Valve is not well explained.
2.	It seems that the hyperparameters of RATE are specifically tuned for each environment. At the same time, there are a lot of hyperparameters of RATE, which makes the tuning a really heavy workload.
3.	It is unclear that the hyperparameters of the compared baselines are tuned carefully.

---

confidence: 4
contribution: 2
initial_rating: 5
presentation: 4
questions: - From Appendix B.1, it looks like the data collection policies are optimal or near-optimal. Is that the case? It is unclear from the description if that is indeed the case. If that is the case, it would be interesting to know how the proposed method performs with suboptimal data.

- The memory update creates a recursive relationship throughout different trajectory segments. During learning, this should lead to some form of backpropagation through time. How does RATE deal with this? Does it truncate the gradient to flow through past forward passes?

- In Figure 4, why is the performance of TrXL-3 so different from other memory-augmented architectures? Most experiments present similar results among them.


**Summary of the Review**:

The work is clear, easy to follow, and provides a diverse set of environments to show the gains of the proposed method. Nonetheless, there are some design choices in the evaluation setup that are unclear and raise questions about its soundness. Most importantly, the work should bring some simple but crucial baselines to justify and contextualize its motivation of investigating memory in RL as sequence modeling. I believe these are the points that need to be addressed in order to recommend acceptance.

**References**:

[1] Ritter et. al. Rapid Task-Solving in Novel Environments, 2020.

[2] Chen et. al. Decision Transformer: Reinforcement Learning via Sequence Modeling, 2021.
soundness: 2
strengths: - The work is well-written and easy to follow.

- The methodology looks simple yet effective; while the use of multi-head attention modules for memory is already present in the literature [1], the use for decision transformers looks novel (to the best of my knowledge).

- While there are some concerns in the evaluation setup (see below), the number of experiments is extensive and covers diverse environments. The MRV ablation (RQ3) is particularly interesting.
summary: This work investigates the use of memory mechanisms for the Decision Transformer (DT) architecture, a formulation of the offline RL problem as sequence modeling that leverages a transformer network. The motivation is that the vanilla DT does not present an explicit memory mechanism, and the context length is limited due to the quadratic complexity of the attention operation. To address this limitation, the paper proposes RATE, an architecture that conditions the DT architecture with a learned memory embedding. This memory is updated via a Multi-Head Attention module (namely Memory Retention Valve). This module ensures that past sub trajectories can affect future ones, extending the effective context window of the model. The work provides empirical evaluation in several classic and memory-intensive environments, presenting results that are comparable or superior to DT and other memory-augmented architectures.
weaknesses: - The major concern regarding the work is that the presented empirical evidence does not justify the motivation of straightforwardly assuming the sequence modeling framework for decision-making. It is unclear how this performs in comparison with the standard offline RL or behavior cloning (with simple memory architectures) for memory-intensive environments. For instance, all presented baselines (DT, TrXL, RMT, DLSTM, DGRU, SSM) assume the sequence modeling framework, which is naturally memory demanding. It would be important to contextualize with other simpler architectures, to understand what the gains are of assuming such a modeling framework. It is unclear if sequence modeling is actually needed/helpful for the considered benchmarks. For instance, presenting results of simple LSTM with CQL and (filtered) behavior cloning (as in the DT paper [2], but for memory-intensive environments) would help clarify this.

- The evaluation setup from VizDoom-Two-Colors is questionable. The work leverages a pre-collected dataset that apparently is biased towards one of the colors. The bias does not look slight as it greatly affects the performance of DT, for instance. The choice of considering this dataset ended up considerably affecting the evaluation, as all experiments were required to control for the color. A much simpler solution would be to train a new policy in the environment and ensure this effect does not happen. Why not take this alternative path? The biased data puts in question if the proposed method is indeed performing better than the baselines or if this result is particular to this configuration.

- Appendix D describes that RATE is trained without the feed-forward network because this leads to better results, but it is unclear why that is the case. Also, it is unclear if this same design choice would lead the other baselines to better results. There is no ablation on that, and this choice makes comparisons against the other methods not completely fair.

- The data collection procedure for the Memory Maze (Appendix D) looks arbitrary. Why does the work change the initial sampling timestep following the described rule? 
    - Also, the sampling horizons for Atari and MuJoCo are much shorter than the standard for the benchmarks (which is often set to at least 200). This choice of short horizons raises the question if RATE can perform well in the classic setup of these benchmarks, which are commonly handled by non-transformer architectures.


Typo:

L148: embeddingsx -> embeddings

Meta-review: This paper introduces RATE, a recurrent transformer architecture with memory mechanisms designed for offline RL tasks. While the reviewers acknowledged the paper's thorough empirical evaluation and potential benefits in memory-intensive environments, several critical concerns remain unresolved. First, although the authors provided extensive ablation studies and implementation details in their response, the work lacks sufficient theoretical justification for the proposed memory retention mechanism. Second, the evaluation on non-standard variants of existing memory tasks (e.g., biased VizDoom dataset, arbitrary filtering in Memory Maze) raises questions about the broader applicability and robustness of the approach. Most importantly, the paper fails to convincingly demonstrate advantages over simpler memory architectures (e.g., LSTM with standard offline RL algorithms) in memory-intensive settings - the additional experiments comparing against CQL+LSTM show limited improvements that may not justify the increased architectural complexity. 

Given these fundamental limitations in theoretical foundation and experimental validation, I recommend rejection.

Decision: Reject