Search

Search papers and lessons

Decision Transformer: Reinforcement Learning via Sequence Modeling

Lili Chen, Kevin Lu, Aravind Rajeswaran et al. · 2021

Decision Transformer treats reinforcement learning as sequence prediction: a language-style model reads past states, actions and desired returns, then predicts the next action.

On this page

  • Colour = topic mix
  • Probability
  • Reinforcement learning
  • Discrete math
  • Calculus
  • Neural network basics
  • Linear algebra
  • ReadReady to readNot yet

TL;DR

Decision Transformer recasts reinforcement learning as a sequence prediction problem. It feeds a GPT-style transformer a sequence of desired future rewards, states and actions, and trains it to predict each action from what came before. At test time you ask for a high return and the model generates actions that try to earn it. On offline benchmarks it matched or beat strong value-based offline RL methods without any dynamic programming.

Builds on: Transformer, Offline Reinforcement Learning, Autoregressive Model · Leads to: later work that treats decision making as generative modeling of trajectories (no lesson in the graph yet)

Why it mattered

Most reinforcement learning systems learn a value function with temporal-difference updates, which pass reward information backward one step at a time. This is hard to stabilise and can be slow to credit a reward far in the future. Decision Transformer showed that a plain supervised objective, with no Bellman backups, can produce strong policies when the data is offline. The model is a standard transformer, so it can reuse the training recipes that language and vision models rely on. The paper has about 2,700 citations on Semantic Scholar, and it gave a concrete example that generative trajectory models can act as policies.

The problem

Offline reinforcement learning asks for a good policy from a fixed set of recorded trajectories, with no new interaction with the environment. The data may come from mixed, suboptimal policies. Value-based methods such as the ones in Offline Reinforcement Learning must estimate the value of actions the data never tried. Errors in those estimates propagate through bootstrapping, and the learned values tend to be overestimated.

Two things are missing from the standard recipe. One is a way to ask for a particular level of performance at test time. The other is a way to learn long-range credit assignment without the Bellman backup. Bootstrapping combined with function approximation and off-policy learning, the so-called deadly triad, is a known source of instability. Decision Transformer addresses both with a sequence model that conditions on the return it wants.

How it works

Here is the method for one trajectory, traced in order. Think of a short episode in a grid world where the agent gets reward 1 for reaching the goal and 0 otherwise.

  1. Record a trajectory. An episode is a list of states, actions and rewards: s1,a1,r1,s2,a2,r2,…s_1, a_1, r_1, s_2, a_2, r_2, \ldots. Suppose the episode has three steps and the agent reaches the goal on the last one, so the rewards are 0,0,10, 0, 1.
  2. Replace rewards with returns-to-go. Instead of the reward at each step, store the sum of rewards from that step to the end. These are the returns-to-go: R^1=0+0+1=1\hat{R}_1 = 0 + 0 + 1 = 1, R^2=0+1=1\hat{R}_2 = 0 + 1 = 1, R^3=1\hat{R}_3 = 1. The model then learns "from here, this much reward still arrives", which is the quantity you want to ask for at test time.
  3. Build the token sequence. Lay out the sequence as R^1,s1,a1,R^2,s2,a2,R^3,s3,a3\hat{R}_1, s_1, a_1, \hat{R}_2, s_2, a_2, \hat{R}_3, s_3, a_3. Each entry becomes one token after a linear embedding. Each timestep also gets a learned timestep embedding, added to its three tokens.
  4. Run a causal transformer. A GPT model reads the tokens with a causal mask, so each token can attend only to earlier tokens. The paper uses the last KK timesteps as context, which gives 3K3K tokens. Here KK is 20 to 50 in the experiments.
  5. Predict the action from the state token. The output at the position of sts_t goes to a prediction head that outputs ata_t. Training minimises the error between prediction and the recorded action.
  6. Generate at test time. Choose a target return, such as the maximum return seen in the data. Feed in the start state and the target return. The model predicts an action, the environment executes it, and the reward rr is subtracted from the target.
  7. Repeat. The new state, action and reduced target are appended to the sequence, and the loop continues until the episode ends.

Step 6 is what makes the method an RL method. The model has learned what actions tend to lead to a given amount of future reward, so asking for a higher return asks it for better actions.

flowchart LR
  A["Returns-to-go R"] --> E["Token embeddings + timestep"]
  B["States s"] --> E
  C["Actions a"] --> E
  E --> D["Causal GPT over last K steps"]
  D --> F["Predict action from state token"]
  F --> G["Act in environment"]
  G --> H["Subtract reward from target R"]
  H --> A
Example
Example 1: a three-step episode, by hand

An episode has rewards 0,0,10, 0, 1.

  1. Returns-to-go at step 1: the sum of rewards from step 1 on is 0+0+1=10 + 0 + 1 = 1.
  2. Returns-to-go at step 2: 0+1=10 + 1 = 1.
  3. Returns-to-go at step 3: 11.
  4. At test time, start with target return 11. The agent takes action a1a_1 and gets reward 00, so the new target is 1−0=11 - 0 = 1.
  5. The agent takes action a2a_2 and gets reward 00, so the target stays 11.
  6. The agent takes action a3a_3 and gets reward 11, so the target becomes 1−1=01 - 1 = 0, which means no more reward is needed.

The target counts down as reward arrives, so it always says how much is still left to earn.

Example
Example 2: the standard case, the context window

Take a context length of K=2K = 2 on a control task, with states and actions as numbers.

  1. The sequence has 2×3=62 \times 3 = 6 tokens: R^1,s1,a1,R^2,s2,a2\hat{R}_1, s_1, a_1, \hat{R}_2, s_2, a_2.
  2. Each token is embedded to the same width dd, and a timestep embedding is added. Here s1s_1 and a1a_1 share the embedding of timestep 1.
  3. A causal mask lets s2s_2 attend to R^1,s1,a1,R^2,s2\hat{R}_1, s_1, a_1, \hat{R}_2, s_2, but not to a2a_2, which is the token being predicted.
  4. The output at s2s_2 is passed to the action head, which predicts a^2\hat{a}_2.
  5. The loss is the mean squared error between a^2\hat{a}_2 and the recorded a2a_2, averaged over all timesteps in the window.

The window is short, so the model sees only the last two steps of history.

Example
Example 3: a sparse-reward task, the shape of the problem

Picture a long task where the only reward comes at the very end, such as opening a door after finding a key many rooms earlier. A value method has to carry that single reward back through every step in between, and each backup can add error.

  1. The episode has 100 steps, and the reward is 1 at step 100 and 0 before it.
  2. The returns-to-go are 11 at every step, because each step still sees the final reward ahead of it.
  3. The model sees the state at step 40 with the return token 11, and the context includes the earlier key pickup.
  4. Decision Transformer does not pass the reward backward through a chain of estimates. It reads the whole recent history, which contains the key pickup, and predicts the next action.
  5. Check: the final reward is the only signal, yet every step's return token already says it is still to come.

Try it: the same 100-step episode, but the reward is 10 at step 100. What is the returns-to-go at step 40? Answer: 1010, since the target is the sum of the rewards still to come, and only the last step pays out.

The math

An offline dataset holds trajectories τ=(s0,a0,r0,…,sT,aT,rT)\tau = (s_0, a_0, r_0, \ldots, s_T, a_T, r_T). The return at step tt is Rt=∑t′=tTrt′R_t = \sum_{t' = t}^{T} r_{t'}, and the paper's trajectory representation feeds returns-to-go R^t\hat{R}_t in place of rewards:

τ=(R^1,s1,a1,R^2,s2,a2,…,R^T,sT,aT).\tau = (\hat{R}_1, s_1, a_1, \hat{R}_2, s_2, a_2, \ldots, \hat{R}_T, s_T, a_T).

The model is an autoregressive network, so it factorises the probability of the trajectory into a product of next-token probabilities. The action is predicted from the state token, and the training objective is supervised. For discrete actions it uses Cross-Entropy Loss. For continuous actions it uses Mean Squared Error between predicted and recorded actions, averaged over the window.

Step 2 in symbols

The returns-to-go are suffix sums. For a trajectory with rewards r1,…,rTr_1, \ldots, r_T, the value R^t=rt+rt+1+⋯+rT\hat{R}_t = r_t + r_{t+1} + \cdots + r_T. Computing them takes one backward pass over the rewards. This is related to the Discounted Return idea, but without a discount factor, so the target is the total reward still to come.

Step 4 in symbols

The attention mask is a lower-triangular matrix MM with Mij=0M_{ij} = 0 when j≤ij \le i and −∞-\infty otherwise, added to the attention scores before the softmax. The token at position ii can use only positions up to ii. With KK timesteps, the sequence has 3K3K tokens, and the state token for step tt sees the returns, states and actions up to that step.

Step 5 in symbols

For continuous actions the training loss over a batch is

L=1K∑t=1K∥a^t−at∥2,\mathcal{L} = \frac{1}{K} \sum_{t=1}^{K} \lVert \hat{a}_t - a_t \rVert^2,

where a^t\hat{a}_t is the action predicted from the state token at step tt. For Example 2 with K=2K = 2, this averages two squared errors.

Step 6 in symbols

At test time, the target return is set to R^1=G\hat{R}_1 = G and decreased after each step by the reward received: R^t+1=R^t−rt\hat{R}_{t+1} = \hat{R}_t - r_t. Example 1 traces this update.

Results

The paper tests on three benchmarks: Atari, OpenAI Gym continuous control from the D4RL suite, and Key-to-Door.

On Atari, trained on a fraction of the DQN-replay data, Decision Transformer is competitive with the offline RL baseline CQL: it wins on some games and loses on others. Read the paper's Atari table for the per-game scores.

On the D4RL Gym locomotion tasks, Decision Transformer's averaged normalised score is higher than CQL's, but the margins are not uniform. Some individual tasks favour CQL. Read the Gym table for the exact per-task numbers before quoting any average.

Limits. The results are for benchmark datasets and a small set of hyperparameters per domain, not a broad search. The paper does not claim the method is better everywhere: it argues that a sequence model can match or exceed TD methods on these tasks while avoiding bootstrapping. The paper also compares against a percentile behaviour-cloning baseline, which imitates only the high-return part of the data, and that comparison is a useful check on what the model is really learning.

Common misreadings. It is tempting to think Decision Transformer is ordinary behavior cloning. In fact it conditions on a return, so the same model can produce different behaviour for different targets, which plain cloning cannot. It is tempting to think it learns values. In fact it never estimates a value function; it predicts actions. It is tempting to think a longer context always helps. In fact the context length is a hyperparameter, and a longer window costs more compute per step.

Tradeoffs. The approach needs a dataset that contains good enough returns to ask for, and it needs the target return to be chosen sensibly. A context window also limits how far back the model can attend. The paper studies the offline setting, so online learning, where the agent can gather new experience, is outside what it shows.

Reading guide

The chain of ideas is: an offline trajectory dataset, returns-to-go as the conditioning signal, a causal transformer over interleaved tokens, and action prediction at test time with a target return. Read the paper in this order.

Check yourself

QuestionWhat is a returns-to-go token, and why does the model use it instead of the reward at each step?Show answer

A returns-to-go token is the sum of rewards from the current step to the end of the episode. The model uses it because it can be set to a desired total at test time. Rewards are only known after they happen, so the model could not be asked for them in advance.

QuestionAn episode has rewards 0,1,0,20, 1, 0, 2. What are the returns-to-go at each of the four steps?Show answer

Add the rewards from each step to the end. At step 4 it is 22. At step 3 it is 0+2=20 + 2 = 2. At step 2 it is 1+0+2=31 + 0 + 2 = 3. At step 1 it is 0+1+0+2=30 + 1 + 0 + 2 = 3. The answer is (3,3,2,2)(3, 3, 2, 2).

QuestionWhy is the causal mask needed during training, and what would go wrong without it?Show answer

The model predicts each action from the state token, and it must not see the action it is predicting. Without the causal mask, the state token could attend to later tokens, including the action itself, so the training task would become trivial and the learned model would fail when it has no access to the true action at test time.

QuestionA paper reports that Decision Transformer has a higher average score than CQL on a set of Gym tasks. A colleague says this proves the method is better in every offline setting. What is the flaw?Show answer

An average over a fixed set of benchmark tasks says little about every setting. Individual tasks can favour the other method, and the hyperparameters were chosen per domain, not searched broadly. The honest claim is a stronger average on these benchmarks, checked task by task.

QuestionYou want a policy that gets the highest return possible in a new environment, and your dataset contains only poor trajectories. What should you expect from Decision Transformer?Show answer

The model learns to imitate behaviour that the data supports, conditioned on a return. If the dataset contains no good trajectories, asking for a high return asks the model to extrapolate beyond its data, and it may produce poor actions. The method depends on the data including good enough behaviour for the target return to mean something.

Sources

Read the full paper

Lili Chen, Kevin Lu, Aravind Rajeswaran et al., 2021. arXiv:2106.01345