Decision Transformer is a model that solves reinforcement learning as a "sequence model that predicts the next token" problem. It was proposed in 2021 by Chen et al. at UC Berkeley in the paper "Decision Transformer: Reinforcement Learning via Sequence Modeling".
Reinforcement learning is the problem of learning a policy with which an agent chooses actions in an environment so as to maximize the total reward it receives (the return). Usually, a value function representing "how much reward is likely to come from now on" for each state is learned and used as a guide to improve the policy (TD learning). Because this approach updates estimates using other estimated values (bootstrapping), training tends to be unstable, and rewards in the distant future must also be discounted.
Decision Transformer uses neither a value function nor policy gradients. It treats past experience as a sequence in which three kinds of tokens alternate:
Return-to-go (the sum of rewards received from this timestep to the end)
State
Action
and predicts "the next action" with a causally masked Transformer, the same as GPT. At use time, entering a target value such as "I want to get this much return" first yields actions suited to that return. It is the same idea as giving a language model a prompt to make it generate text.
The paper evaluated it in offline reinforcement learning, which learns only from a fixed dataset. On Atari games and OpenAI Gym continuous control (D4RL), it matched or exceeded CQL, a representative method of the time, and was shown to be especially strong on tasks where rewards arrive late.
Building the sequence and the computation steps
Let the state at timestep t be st, the action at, and the reward rt. Instead of the reward itself, Decision Transformer takes as input the return-to-goR^t, the sum of rewards from that timestep to the last timestep T.
R^t=t′=t∑Trt′
A trajectory (the record of one episode) becomes a sequence with tokens arranged in groups of three, as follows.
τ=(R^1,s1,a1,R^2,s2,a2,…,R^T,sT,aT)
The reason for feeding "the return still to be obtained" rather than past rewards is to make the model choose actions according to a target future return.
The model computes as shown on the left of the figure at the top of the article.
Take the most recent K steps (3K tokens). K corresponds to the context length.
Apply a dedicated linear layer to each of return-to-go, state, and action to turn them into vectors of the same length, then pass them through layer normalization. When the state is an image (Atari), a convolutional encoder is used instead of the linear layer.
Learn an embedding per timestep and add the same one to the three tokens of the same timestep. Since one timestep corresponds to three tokens, it differs from an ordinary position embedding in that the embedding is held per timestep rather than per token position.
Pass the arranged tokens through GPT. Through masking, each token sees only itself and the tokens before it.
Apply a linear layer to the output of the state token st to predict the action at.
In training, segments of length K are taken from recorded trajectories, and the difference between the predicted and actual actions is used as the loss. Cross-entropy is used for discrete actions and mean squared error for continuous actions, and the losses at each timestep are averaged. The paper notes that having the model also predict states and returns-to-go can be tried, but it did not improve results.
At inference, the model runs as shown on the right of the figure at the top of the article.
Enter the target return R^1 (for example, an expert-level return) and the first state s1.
The model outputs an action at, which is executed in the environment.
When the environment returns the reward rt and the next state st+1, subtract the reward from the target: R^t+1=R^t−rt.
Append at, R^t+1, and st+1 to the end of the sequence and keep only the most recent K steps.
Repeat 2-4 until the episode ends.
The "return-to-go" is like the remaining points in a game, "how many more points do I want". You first say "I want 100 points", and every time you score 10 points you rewrite it as "90 more" while asking for the next move.
Why it works
The paper explains the advantages of solving the problem as a sequence model as follows.
No bootstrapping needed: TD learning is known to be prone to instability because it updates the next estimate with an estimated value, letting errors propagate. Decision Transformer only predicts actions conditioned on the actual returns in the records, so it does no such updating. There is also no need to discount future rewards.
Attention links "credit" directly: TD learning propagates how actions in the distant past affected later rewards (credit assignment) one step at a time, taking a long time. Self-attention can connect tokens at distant timesteps in one go. In a task where the reward comes when the agent picks up a key and then reaches a door, the trained model's attention concentrated on "the timestep the key was picked up" and "the timestep the door was reached".
The target return selects which behavior to imitate: the data mixes skilled and unskilled episodes. Because training is conditioned on the return, specifying a high return at inference draws out actions close to the skilled behavior in the data.
No optimization of a value function: in offline reinforcement learning, trying to maximize a learned value function exploits errors that overestimate the value of actions not in the data, so measures to make the policy conservative are usually needed. The paper suggests that Decision Transformer may not need such measures because it does not optimize against a learned function (this is the paper's conjecture).
The paper also compared it with "%BC", which does behavior cloning (learning that directly imitates the actions in the data) only on episodes in the top X% of returns. On D4RL, where data is plentiful, Decision Transformer was about the same as the best %BC. On Atari, where data is scarce, it was generally better than every %BC, and the paper attributes this to being able to use all trajectories for training, which helps generalization.
Experimental results
On average over D4RL continuous control (HalfCheetah, Hopper, Walker), Decision Transformer (DT) outperformed TD learning methods and behavior cloning (BC). Scores are normalized so that the expert policy is 100.
Method
Average (9 settings excluding Reacher)
DT
74.7
CQL
63.9
BEAR
48.2
BRAC-v
36.9
AWR
34.3
BC
46.4
Examples by dataset type (Hopper) are as follows.
Data
DT
CQL
BC
Medium-Expert
107.6
111.0
79.6
Medium
67.6
58.0
63.9
Medium-Replay
82.7
48.6
27.6
On Atari (1% of DQN replay data), with scores normalized so that a professional gamer is 100, it was about the same as CQL in 3 of the 4 games. On Qbert it lost to CQL by a wide margin.
Game
DT
CQL
BC
Breakout
267.5
211.1
138.9
Qbert
15.4
104.2
17.3
Pong
106.1
111.9
85.2
Seaquest
2.5
1.7
2.1
The difference was especially large on tasks where rewards arrive late.
Key-to-Door (pick up a key in the first room; a reward is given only on reaching the door in the last room): trained on 10K trajectories of random actions, the success rates were DT 94.6%, CQL 13.3%, and BC 1.6%.
D4RL with the reward delivered all at the end (intermediate rewards set to 0 and only the total given at the last timestep): on Hopper Medium-Replay, DT held 78.5 (82.7 in the original setting), while CQL dropped to 2.0 (originally 48.6).
Context length matters too. On Atari, setting K=1 (only the previous state) dropped the Pong score from 106.1 to 2.5 and Breakout from 267.5 to 73.9.
Practical notes
The target return R^1 must be chosen by the user. The paper uses 1× or 5× the maximum return in the data for Atari, and sets it based on expert performance for Gym (only for HalfCheetah was 50% of the expert better). Giving a target far beyond the range of the data does not guarantee that return will be achieved. Exceeding the data maximum was possible only on some tasks, such as Seaquest.
It depends on the quality and quantity of the offline data. What the model learns is the behavior in the data conditioned on return. It does not discover skilled behavior absent from the data through exploration. The paper evaluates only the offline setting and leaves online use as future work.
It is not stronger than TD learning on every task. There are settings where CQL is better, such as Qbert on Atari and HalfCheetah Medium-Replay on D4RL.
Choose the context length K to suit the task. The paper used 30 for Atari (50 for Pong), 20 for Gym (5 for Reacher, which has short episodes), and the whole episode for Key-to-Door. A longer K increases the attention cost with the square of K.
The paper's Gym setting uses 3 layers, 1 head, and 128-dimensional embeddings, and Atari uses 6 layers, 8 heads, and 128-dimensional embeddings, which are small models compared with language models. For Gym, it uses AdamW and a linear warmup over the first 105 steps.
Comparison with other methods
The following compares representative approaches to learning policies from offline data, from the same viewpoints.
Method
What it learns
How it uses returns
Tasks with late rewards
Limitations
TD learning (CQL, etc.)
A value function and a policy that maximizes it
Propagates value estimates one step at a time
Weak (values do not propagate far easily)
Needs measures to suppress value overestimation
Behavior cloning (BC)
A policy that directly imitates the actions in the data
Not used
Also imitates unskilled episodes
Ends up with the average behavior in the data
%BC (imitate only top episodes)
Actions of the top X% of episodes
Used to select episodes for training
Strong if only successful episodes are used
The best X% cannot be chosen without trying in the environment
Decision Transformer
Next-action prediction conditioned on return
Given as an input token
Strong (attention connects distant timesteps)
A target return must be chosen; no exploration
Around the same time, Trajectory Transformer (Janner et al.), which also predicts states and returns and handles values by discretizing them, was proposed. Decision Transformer differs in that it predicts only actions, without predicting states or returns and without discretizing values.
Rough guidelines for choosing:
Tasks with sparse rewards that arrive late: Decision Transformer is a good fit.
The data contains plenty of expert episodes: BC or %BC can give similar results and are simpler.
Fine-grained continuous control where CQL already works well: CQL can be better, so compare both and choose.
PyTorch example
▶Show code
python
import torch
import torch.nn as nn
"""
A small example of Decision Transformer (continuous actions) written to follow Section 3 and Algorithm 1 of the paper.
The sequence is (R^_1, s_1, a_1, R^_2, s_2, a_2, ...). The action is predicted from the output of the state token.
The paper's Gym implementation uses Hugging Face GPT-2. Here causally masked encoder layers stand in for GPT.
"""
class DecisionTransformer(nn.Module):
def __init__(self, state_dim, act_dim, d=128, n_layers=3, n_heads=1, max_timestep=1000, dropout=0.1):
super().__init__()
self.embed_t = nn.Embedding(max_timestep, d) # embedding per timestep (not per token)
self.embed_R = nn.Linear(1, d) # a linear layer per token type
self.embed_s = nn.Linear(state_dim, d)
self.embed_a = nn.Linear(act_dim, d)
self.ln = nn.LayerNorm(d)
layer = nn.TransformerEncoderLayer(d, n_heads, 4 * d, dropout, activation="relu", batch_first=True)
self.gpt = nn.TransformerEncoder(layer, n_layers)
self.pred_a = nn.Sequential(nn.Linear(d, act_dim), nn.Tanh()) # assumes an environment with actions in [-1, 1]
def forward(self, R, s, a, t):
# R: [B, K, 1], s: [B, K, state_dim], a: [B, K, act_dim], t: [B, K] (integer timesteps)
B, K, _ = s.shape
pos = self.embed_t(t) # add the same embedding to the 3 tokens of a timestep
tokens = torch.stack(
[self.embed_R(R) + pos, self.embed_s(s) + pos, self.embed_a(a) + pos], dim=2
).reshape(B, 3 * K, -1) # arrange as (R_1, s_1, a_1, R_2, ...)
tokens = self.ln(tokens)
causal = torch.triu(torch.ones(3 * K, 3 * K, dtype=torch.bool, device=s.device), diagonal=1)
h = self.gpt(tokens, mask=causal) # positions marked True (later than itself) are not seen
h = h.reshape(B, K, 3, -1)
return self.pred_a(h[:, :, 1]) # predict a_t from the output of the state token s_t
state_dim, act_dim, K = 11, 3, 20
model = DecisionTransformer(state_dim, act_dim)
opt = torch.optim.AdamW(model.parameters(), lr=1e-4, weight_decay=1e-4)
# Training: take segments of length K from recorded trajectories and apply squared error to actions only
model.train()
R = torch.randn(4, K, 1); s = torch.randn(4, K, state_dim)
a = torch.rand(4, K, act_dim) * 2 - 1; t = torch.arange(K).repeat(4, 1)
loss = ((model(R, s, a, t) - a) ** 2).mean()
opt.zero_grad(); loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 0.25)
opt.step()
# Inference: start from the target return and output actions one step at a time, subtracting the rewards obtained
@torch.no_grad()
def run_episode(env, model, target_return, max_steps=1000):
model.eval()
s0 = torch.as_tensor(env.reset(), dtype=torch.float32)
Rs, ss = [torch.tensor([float(target_return)])], [s0]
acts, ts = [], [0]
total = 0.0
for step in range(max_steps):
acts.append(torch.zeros(act_dim)) # slot for a_t not yet decided (masked, so not used for the prediction)
R_in = torch.stack(Rs[-K:]).unsqueeze(0)
s_in = torch.stack(ss[-K:]).unsqueeze(0)
a_in = torch.stack(acts[-K:]).unsqueeze(0)
t_in = torch.tensor(ts[-K:]).unsqueeze(0)
action = model(R_in, s_in, a_in, t_in)[0, -1]
acts[-1] = action
s_next, r, done, _ = env.step(action.numpy())
total += r
Rs.append(Rs[-1] - r) # reduce the return-to-go
ss.append(torch.as_tensor(s_next, dtype=torch.float32))
ts.append(step + 1)
if done:
break
return total
FAQ
Q. Is Decision Transformer reinforcement learning or supervised learning?
A.
The way it trains is supervised learning. Recorded trajectories are given as sequences, and it is trained with a loss for predicting the next action (cross-entropy or mean squared error). The problem it solves is reinforcement learning (especially offline reinforcement learning), which seeks a policy that maximizes return, and its distinguishing feature is solving it without value functions or policy gradients.
Q. If the target return is made very large, will it act arbitrarily well?
A.
No. The specified return and the return actually obtained agree well within the range of the data, but giving a target beyond the data maximum does not necessarily make it correspondingly better. In the paper, exceeding the data maximum was possible only on some tasks, such as Seaquest. The paper uses 1× or 5× the data maximum as the target.
Q. Why feed the "return-to-go" instead of the reward?
A.
To make the model choose actions according to the return it should obtain from now on, rather than the rewards received in the past. At inference, the rewards actually received are subtracted from the target return R^1, so "how much more needs to be obtained" can be conveyed at every step.