Sam Babichenko

Reading notes / In-context learning

Retrieval-augmented Decision Transformer

Schmied et al., 2025

Trajectories and model
τ,\tau, τt−C:t\tau_{t-C:t}trajectory; its steps t−Ct-C to tt
st,s_t, at,a_t, rtr_tstate, action, reward at step tt
R^t\hat R_treturn-to-go ∑t′≥trt′\sum_{t'\ge t}r_{t'}
πθ\pi_\thetaDecision Transformer policy
Retrieval
ggtrajectory encoder for keys and queries
FH,\mathrm{FH}, E,E, PPFrozenHopfield map; language-model token embeddings; random projection
v,v, dLM,d_{\rm LM}, dind_{\rm in}vocabulary size; language-model width; input size
srel,s_{\rm rel}, su,s_{\rm u}, srets_{\rm ret}relevance (cosine similarity); utility; retrieval score
Constants
CCcontext length in steps (50, or 100 on the larger grids); values span 2C2C
l,l, kksub-trajectories retrieved, then kept after rescoring (k=1k=1, or 4 on robotics)
α\alphaweight of utility in srets_{\rm ret} (1 by default)
β\betaFrozenHopfield scale (10)
0.98; 0.2similarity cut-off for deduplication and retrieval; query-token dropout rate

Context. In-context reinforcement learning trains a transformer offline on many tasks so that, on a new task, it improves from episode to episode by reading its own earlier episodes, with no weight updates. The established methods, AD (Laskin et al., 2023): a transformer trained to predict the next action of a learning RL agent given its earlier episodes, so that it imitates the learning process itself (Laskin et al., 2023) and the DPT (Lee et al., 2023): a transformer trained to predict the optimal action for a query state given a context of interactions from the same task (Lee et al., 2023), keep whole episodes in context, so the input grows with episode length and attention cost with its square, and they have been shown mostly on bandits and small grid worlds. Schmied et al. (2025) keep past experience outside the model, in a vector index searched by nearest neighbors as in retrieval-augmented language models, and give a DT (Chen et al., 2021): a transformer that treats offline RL as sequence modeling, predicting the next action from recent states, actions, rewards and the reward still to come only the stored pieces of trajectory that resemble its current situation (Retrieval-Augmented Decision Transformer, RA-DT).

An agent does not need its whole history to act well, only the few past moments that resemble the present and what followed them, and a frozen encoder with nearest-neighbor search can find those, so a context of 50 to 100 steps can replace thousands. On grid worlds with sparse rewards this beats the whole-episode methods while training up to 7 times faster. On robot control and video games it raises scores on held-out tasks, but there neither it nor any baseline improves across episodes, so in-context learning beyond grid worlds is not shown.

Setting. A trajectory τ=(s0,a0,r0,R^0,… )\tau=(s_0,a_0,r_0,\hat R_0,\dots) lists states, actions, rewards and R^t=∑t′≥trt′\hat R_t=\sum_{t'\ge t}r_{t'}, the reward still to be collected from step tt to the end of the episode R^t\hat R_t. A Decision Transformer πθ\pi_\theta predicts ata_t from the last the context length in steps; 50 for RA-DT, 100 on the two larger grids steps of states, returns-to-go, actions and rewards, trained by cross-entropy or squared error on offline data, and at test time it is conditioned on a high target return. The training data come from proximal policy optimization, a standard on-policy RL method; here one PPO agent is trained per task and all its transitions are kept agents trained separately on each training task, with every transition kept, so they mix exploratory and good behavior. Evaluation follows earlier in-context RL work: on a held-out task the trained agent plays a fixed number of episodes, called trials, each finished episode becomes available as context, and success means reward rising across trials. AD and DPT see two whole episodes (200 to 2,000 steps), and so does the plain DT on the grid worlds (up to 6,400 tokens; 50 steps on the robotics and video-game benchmarks); RA-DT sees CC steps plus 2C2C retrieved steps.

Method. Every CC steps along every stored trajectory, the index receives a key, an embedding g(τt−C:t)g(\tau_{t-C:t}) of the last CC steps, and a value, the sub-trajectory τt−C:t+C\tau_{t-C:t+C}, the same CC steps followed by the next CC: at test time only the past is available to form a query, and the continuation shows how a similar situation played out. The embedding the trajectory encoder that maps a sub-trajectory to a vector for search; a DT pretrained on the same data, or a frozen language model applied after a fixed input map is either a DT pretrained on the same data or a domain-agnostic encoder: a fixed map (Paischer et al., 2022) that sends any input vector into the token-embedding space of a frozen language model by attention over its vocabulary maps each token into the token-embedding space of a frozen language model,FH(x)=E⊤softmax(βEPx),\mathrm{FH}(x)=E^\top\mathrm{softmax}(\beta EPx),with the language model's v×dLMv\times d_{\rm LM} token-embedding matrix, vv the vocabulary size the token-embedding matrix, a fixed random matrix with Gaussian entries mapping inputs of size dind_{\rm in} to dLMd_{\rm LM} a fixed random matrix and β\beta a scale, and frozen an encoder-only language model of 110M parameters (Devlin et al., 2019) runs on the result; the query averages the encoded state tokens. Retrieval takes the top the number of nearest keys first retrieved, before rescoring keys by q⊤u/(∥q∥ ∥u∥)q^\top u/(\|q\|\,\|u\|) between the query vector qq and a key vector uu srels_{\rm rel} to the query, rescores them bysret=srel⏟relevance+α su⏟utility,s_{\rm ret}=\underbrace{s_{\rm rel}}_{\text{relevance}}+\alpha\,\underbrace{s_{\rm u}}_{\text{utility}},with both scores normalized to [0,1][0,1] and the weight of utility against relevance in the retrieval score; 1 by default a weight, and keeps the top the number of retrieved sub-trajectories given to the model: one on the grid worlds and video games, four on the robotics tasks. The utility sus_{\rm u} is 1 for a sub-trajectory from the query's own task (0 otherwise) during training, when the index holds data from many tasks, and the return of the episode it came from at test time, when the index holds only the agent's own episodes on the new task. Retrieved sub-trajectories enter through cross-attention layers placed after each self-attention layer. During training the index is the training set itself, minus the query's own trajectory, and why: retrieving near-identical sub-trajectories teaches the model to copy its context, which leaves it unable to produce high-reward actions at test time: near-duplicate entries (cosine similarity above 0.98) are removed, retrievals above that similarity are skipped, and 20% of query tokens are dropped, so that the retrieved context is relevant without being a near copy of the input.

Main findings (all empirical). On three partially observed grid worlds with sparse rewards, RA-DT ends its trials with the highest reward at every grid size and is the only method that improves across trials on the procedurally generated mazes of 15×15 procedurally generated mazes with up to three goals to visit in order, distance-sensor and position observations and 400-step episodes (Steps 1 and 2). The domain-agnostic encoder comes close to the domain-specific one on the smallest grids, falls behind on the 20×\times20 grids and does better on the hardest Dark Key-Door: a grid world in which the agent must find an invisible key and then an invisible door, so a task is a pair of cells grid, so retrieval can work without an encoder trained for the domain. The gain comes from retrieving sub-trajectories that are both similar to the current one and from the same task (Step 3), and training is up to 7 times faster on the largest grid because the sequence no longer grows with the episode (Step 4). On a benchmark of simulated robot-arm manipulation tasks such as opening a door or inserting a peg, a suite of simulated locomotion and balance tasks such as walker-walk and cartpole-balance and procedurally generated video games with image observations; here 12 games for training and 4 held out it has the highest average scores on held-out tasks, but no method improves across trials there (Step 5).

Step 1

On Dark-Room, retrieving 50 steps beats keeping two whole episodes. In a grid world in which the agent sees only its own x-y position and must find an invisible goal cell, with reward 1 for each step spent on it grids of 10×\times10, 20×\times20 and 40×\times20 cells, episodes last 100, 200 and 800 steps, 80 goals are used for training and 20 held out, and each agent gets 40 trials, over three seeds. On 10×\times10, the two RA-DT variants reach about 80 and 75 by the last trials, near optimal, against about 55 for AD, 40 for DPT and under 10 for the plain DT, which does not improve across trials, so the improvement comes from the retrieved context. On 20×\times20 RA-DT reaches about 190, the domain-agnostic variant about 140, and AD and DPT about 70. On 40×\times20 all methods are noisy and far from optimal, RA-DT ending near 100, the domain-agnostic variant near 90 and the baselines between about 25 and 50 (values read from the plots). In attention maps on 10×\times10 the agent follows a retrieved trajectory that reached the goal and departs from one that did not, and state-visit counts show that once it finds the goal it stops exploring. Given 200 trials instead of 40 on 10×\times10, AD and DPT keep improving toward optimal, so part of RA-DT's lead is how fast it improves.

Step 2

With two key events and with procedurally generated mazes, RA-DT still leads. In Dark Key-Door, RA-DT leads on 10×\times10 (about 85 against 50 to 65) and on 20×\times20, where the domain-specific variant reaches about 80, the domain-agnostic one about 45 and the baselines 20 or less; on 40×\times20 the domain-agnostic variant reaches about 80 and the domain-specific one about 45, with the baselines near 10 or below. In MazeRunner RA-DT is the only method that improves over 30 trials, ending near 0.45 against about 0.15 for AD and DPT. It reaches 0.65 on training mazes against 0.4 on the 20 held-out mazes, which the authors attribute to pretraining on only 100 mazes. Among language models for the domain-agnostic encoder, BERT works best, and the distilled models, the decoder-only DistilGPT2 among them, are weaker.

Step 3

The gain comes from retrieving relevant sub-trajectories from the same task. All ablations are on Dark-Room 10×\times10. Training with sub-trajectories sampled uniformly from all tasks instead of retrieved ones gives poor in-context learning: context from another goal does not help predict the action, so the model learns to ignore its context. Sampling from the same task does better, and retrieval better still, since its sub-trajectories are also similar to the current situation. Retrieval also builds bursty contexts, inputs that hold experience related to the current one, which Chan et al. (2022) found drive in-context learning in transformers. Dropping the task-based reweighting (the same-task utility sus_{\rm u}) in training lowers performance considerably, though plain retrieval still beats uniform sampling, and α=0\alpha=0 hurts while a range of values works. Of the three regularizers, deduplication matters most, since RL datasets hold many nearly identical trajectories. A single cross-attention layer at the bottom of the network works about as well as one after every layer, so the gain does not come from the extra parameters, and averaging the state tokens is the best way to form the query.

Step 4

Training cost stops growing with episode length. RA-DT's input is CC steps plus 2C2C retrieved steps whatever the episode length, so on 40×\times20 the domain-specific variant trains almost 7 times faster than the baselines, which all use an exact implementation of attention that never stores the full attention matrix, which makes long sequences much faster. On 10×\times10 the domain-agnostic variant trains more slowly than the baselines because of the BERT encoding. At test time, retrieving at every step makes RA-DT slightly slower than the baselines, and retrieving every 25 steps makes it as fast at a small cost in reward. The index here is an exact search on the GPU; approximate nearest-neighbor indexes search large memories in time logarithmic in their size.

Step 5

On robot control and video games RA-DT scores higher on held-out tasks, but no method learns in context. Meta-World (training on 45 manipulation tasks, 90M transitions, evaluation on 5) and DMControl (11 tasks, 11M transitions, 5 held out) have continuous states and actions, and the paper treats them as fully observed (in Meta-World the goal position is masked out of the state). On the held-out tasks RA-DT's average (return−random)/(expert−random)(\text{return}-\text{random})/(\text{expert}-\text{random}): 0 for a random agent, 1 for the average return of the agent that collected the dataset. The paper does not restate it; the definition is in the paper that released the datasets (Schmied et al., 2023) is 0.17 on Meta-World against 0.09 for the DT, 0.08 for AD and 0.03 for DPT, and 0.53 on DMControl against 0.35, 0.09 and 0.30, but most of each gain comes from one task (door-unlock, 0.66 against at most 0.27; walker-walk, 1.14 against at most 0.40), and on training tasks RA-DT scores slightly below the plain DT. On Procgen, RA-DT again has the best averages, with wide intervals on the held-out games. Across 30 trials, no method improves on held-out tasks in any of the three benchmarks, and only the training tasks of Meta-World and DMControl show slight improvement. In Procgen, retrieval during training finds trajectories from the same or a similar level about 80% of the time, and at test time the index holds only the agent's own episodes on the level, so in my reading the search finds relevant experience and what fails is using it. The authors' reading is that fully observed tasks do not require memory; that next-action prediction on mixed-quality data cannot tell good actions from bad, which shows up even on Dark-Room as repeated loops of failing actions; and that 11 to 45 training tasks may be too few.

Caveats. Results are over three seeds, and most grid-world numbers are read from plots. The baselines are limited to two episodes of context and, on the Dark grids, 40 trials, and with more trials AD and DPT continue to improve (Step 1). RA-DT adds an index, an encoder, a reweighting that uses task labels during training, three retrieval regularizers and per-environment settings, such as blending the query with a random key on the robotics tasks and replacing retrieval with same-task samples in the first 10 steps of episodes on Dark-Room and Dark Key-Door. Its gains on held-out robotics tasks come mostly from single tasks, and in-context improvement is shown only in partially observed grid worlds and mazes, where memory of past episodes is required to solve the task at all.

Terms

In-context RL
improving across episodes on a new task by reading past episodes in the input, with no weight updates
Key and value
key g(τt−C:t)g(\tau_{t-C:t}), the past CC steps; value τt−C:t+C\tau_{t-C:t+C}, the same steps and their continuation
FrozenHopfield
E⊤softmax(βEPx)E^\top\mathrm{softmax}(\beta EPx): tokens mapped into a frozen language model's embedding space, then BERT
Retrieval score
srel+αsus_{\rm rel}+\alpha s_{\rm u}; utility = same task in training, episode return at test time
Retrieval regularization
deduplication (most important), similarity cut-off 0.98, 20% query dropout
Context length
C+2CC+2C steps for RA-DT against two whole episodes (up to 6,400 tokens) for AD, DPT, DT
Grid-world result
highest final reward on Dark-Room, Key-Door; only method improving on MazeRunner
Training speed
almost 7 times faster on 40×20, since input length no longer grows with the episode
Negative result
higher held-out scores on Meta-World, DMControl, Procgen, but no improvement across trials for any method
Likely causes (authors)
full observability needs no memory; next-action prediction cannot tell good from bad actions; few tasks

Quiz

  1. Why does RA-DT rescore retrieved sub-trajectories by task identity during training but by episode return at test time?
  2. Given 200 trials instead of 40 on Dark-Room 10×\times10, AD and DPT keep improving toward optimal. How should RA-DT's lead be read?

Sources