Paper notes

Decision Transformer: Reinforcement Learning as Conditional Sequence Modeling

Decision Transformer (Chen et al., 2021) recasts offline RL as conditional sequence modeling: a causal GPT trained on return, state and action tokens, prompted with a target return. We recompute its tables, rerun its shortest-path toy, and show where return conditioning fails.

Published Updated 48 min read

On this page
  1. Why This Paper Is Worth Reading
  2. Background: The Two Old Routes in Offline RL
  3. Method
  4. Trajectory representation: feed returns-to-go, not rewards
  5. Model: a GPT with three small changes
  6. Training and inference
  7. What the return condition does
  8. Experiments and Conclusions
  9. Atari
  10. D4RL Gym tasks
  11. Comparison with percentile behavior cloning
  12. Controllability of the return and context length
  13. Long-horizon credit assignment and delayed rewards
  14. Hands-On Check: Model Size, the Paper’s Tables, Shortest Paths and a Stochastic Counterexample
  15. Model size: the Gym-sized Transformer body has only 595 thousand parameters
  16. Recomputing the tables: a few mismatches, none changes the conclusions
  17. Shortest paths: what the return condition does, and what the Transformer does
  18. A stochastic environment: conditioning on “win” is not choosing the best arm
  19. Limitations and What Came Next
  20. What to Take Away From This Paper
  21. Further Reading
  22. FAQ

Decision Transformer (DT) is an offline reinforcement learning method proposed by Chen et al. in June 2021. It learns no value function and computes no policy gradient. Instead it writes each trajectory as a sequence of interleaved return, state, and action tokens, trains a causally masked GPT to predict the action at each state token, and uses nothing more than a supervised mean-squared-error or cross-entropy loss. At test time the total return you want is given as a prompt, and the model “generates” actions that should achieve it. On Atari, the Gym continuous-control tasks of D4RL, and Key-to-Door, the paper reports that this matches or beats the strongest model-free offline RL algorithms of the time, chiefly CQL.

This post follows the text of arXiv v2 (June 24, 2021); the first submission was on June 2, 2021, and the paper appeared at NeurIPS 2021. I recompute the paper’s tables row by row, reproduce its shortest-path example with two controls, and use a bandit to demonstrate a known weakness of return conditioning; the places where the paper does not agree with itself are collected in “Hands-On Check” and “Limitations and What Came Next”. I looked up the abstracts of the later papers cited here in November 2026.

Why This Paper Is Worth Reading

  • It puts reinforcement learning into the language-modeling framework. The network is a GPT, the loss is supervised, and the condition is a prompt: the paper wants to reuse the networks, training practice, and scaling experience that language modeling has already matured, instead of designing yet another RL-specific algorithm.
  • It sidesteps temporal-difference (TD) learning. The paper argues that without bootstrapping it avoids one corner of RL’s “deadly triad”, needs no discount factor, and leaves credit assignment to self-attention. In the offline setting, error propagation and value overestimation are what methods such as CQL suppress with conservatism; DT does not touch them.
  • It started a whole line of follow-ups. The idea of return-conditioned supervised learning (RCSL) predates it, and Trajectory Transformer appeared at the same time; DT made it the simplest GPT version, and then came online fine-tuning, multi-task extensions, theoretical criticism, and simple baselines. Together they draw the boundary of where DT applies.
  • It rewards a critical second reading. Most of its conclusions come from “filter by return and condition on it” rather than from the Transformer; a few of its tables do not add up; and it is known to fail in stochastic environments and where stitching is needed. After this post you should be able to say when DT is reliable.

Background: The Two Old Routes in Offline RL

Offline RL gives you a fixed set of trajectories collected by arbitrary policies and forbids interacting with the environment. The difficulty is distribution shift: once the policy leaves the data, the value estimates have nothing to stand on; the paper names error propagation and value overestimation. Existing methods fall into two broad groups:

RouteExamplesApproachWeakness
Value plus conservatismCQL, BEAR, BRACLearn a value function with TD, then use pessimism or constraints to suppress out-of-distribution actionsNeeds Bellman backups; credit propagates poorly when rewards are sparse and horizons long
ImitationBehavior cloning (BC)Supervised learning on the actions in the dataGood and bad behavior are mixed, so the result is the average

DT takes a third route: label every sample with hindsight, namely how much return the trajectory eventually collected, train the conditional distribution of “what to do in this state when this much return is wanted”, and at test time ask for a high return. This family is called return-conditioned supervised learning (RCSL). The paper puts it in the same class as upside-down RL and reward-conditioned policies; the differences it points to are context length and architecture, and DT’s motivation shifts to sequence modeling, which it says can model behavior even without rewards and scales well. In the paper’s own ablation, a context length of K=1K=1 (close to Kumar et al.’s method) is clearly worse.

Method

Trajectory representation: feed returns-to-go, not rewards

A trajectory has rewards r1,…,rTr_1,\dots,r_T. DT does not feed rewards directly; it feeds returns-to-go, the sum of rewards from the current step to the end:

R^t=∑t′=tTrt′,τ=(R^1,s1,a1, R^2,s2,a2, …, R^T,sT,aT).\hat R_t=\sum_{t'=t}^{T} r_{t'} ,\qquad \tau=\big(\hat R_1,s_1,a_1,\ \hat R_2,s_2,a_2,\ \dots,\ \hat R_T,s_T,a_T\big).

For example, rewards of 0, 1, 2 give returns-to-go of 3, 3, 2. The paper’s reason is that an action should depend on how much return is still wanted, not on how much has been collected. At test time you only need a target return for the first step (expert level, say, or 1 for success and 0 for failure) and the initial state to start generating.

Model: a GPT with three small changes

Decision Transformer: training and inference Top, training: a trajectory with rewards 0, 1, 2 has returns-to-go 3, 3, 2; it is written as an interleaved sequence of return, state and action tokens, fed to a causally masked GPT, and the action of each step is predicted at the position of its state token. Bottom, inference: set a target return, the GPT reads the last K steps and outputs an action, the environment returns a reward and the next state, the target return drops by the reward just received, and the loop repeats until the episode ends. Training: write the trajectory as interleaved (return, state, action) tokens Rewards r = 0, 1, 2; return R = sum of rewards from this step on = 3, 3, 2 Step 1 R₁=3 s₁ a₁ predict a₁ Step 2 R₂=3 s₂ a₂ predict a₂ Step 3 R₃=2 s₃ a₃ predict a₃ Causal GPT: tokens see only their left context, plus timestep embeddings Actions are predicted at the state tokens: MSE for continuous, cross-entropy for discrete Inference: the target return is the prompt, and each reward is subtracted Set a target return R = the total you want (e.g. expert level) GPT reads last K steps return, state, action outputs action a Environment runs a returns reward r and the next state s Update the target new R = old R - r go to the next step Repeat until the episode ends; the context keeps only the last K steps
Decision Transformer in training and inference (redrawn from the paper's Figure 1 and Algorithm 1): the top half writes a trajectory with rewards 0, 1, 2 as an interleaved sequence of returns-to-go (3, 3, 2), states, and actions, and a causal GPT predicts each step's action at its state token; the bottom half is inference, where the target return is reduced by each reward just received.

The model reads the last KK steps, 3K3K tokens in all (one return-to-go, one state, and one action per step). Compared with a plain GPT there are three differences:

  • One linear layer per modality. Returns, states, and actions each get a linear layer into the embedding dimension, followed by layer normalization. For image states (Atari) a convolutional encoder replaces the linear layer; the appendix says it is the DQN convolutional encoder plus one linear layer, and that Atari uses Tanh in place of layer normalization, which made little difference.
  • A timestep embedding, not a token-position embedding. A step is three tokens, so position information is a learned embedding per step, added to the three tokens of that step.
  • Actions are predicted only at state tokens. The loss is mean squared error for continuous actions and cross-entropy for discrete ones, averaged over steps. The paper says that also predicting states or returns-to-go gave no improvement.

Training and inference

Training is supervised learning: sample KK-step trajectory segments from the dataset and compute the action-prediction loss. At inference you set a target return R^1\hat R_1; the model outputs an action; the environment executes it and returns a reward rr and a new state; the target is updated to R^t+1=R^t−r\hat R_{t+1}=\hat R_t-r; only the last KK steps are kept; and this repeats until the episode ends. The main settings of the paper’s Gym and Atari experiments:

ItemGym (D4RL)Atari
Layers, heads, width3, 1, 1286, 8, 128
Context length KK20 (Reacher: 5)30 (Pong: 50)
State encoderLinear layerDQN convolutional encoder plus linear layer
Optimization10510^5 steps of AdamW, learning rate 10−410^{-4}, batch 645 epochs, learning rate 6×10−46\times10^{-4}, batch 128 (Pong: 512)
Target returnNear expert level (HalfCheetah about 50%): HalfCheetah 6000, Hopper 3600, Walker 5000, Reacher 501 or 5 times the dataset maximum: Breakout 90, Qbert 2500, Pong 20, Seaquest 1450

The official code has a few implementation details that the paper’s text omits. Gym returns are divided by 1000 (Reacher by 10) before they are fed in; in the delayed-reward setting the evaluation code does not decrement the target return; and layer normalization is applied after the timestep embedding is added and the three token types are interleaved, whereas the paper’s text puts it after the linear embedding and before the timestep embedding.

What the return condition does

In the data, trajectories with high returns look more like the behavior of a “good policy” than those with low returns. The conditional distribution p(at∣st,R^t,… )p(a_t\mid s_t,\hat R_t,\dots) separates the two kinds of behavior, and asking for a high return at inference samples from the “expert” part of that conditional. So DT is essentially behavior cloning conditioned on return, inside the data distribution: how good it can be depends on whether the data contain enough high-return behavior. That is why the paper compares against percentile behavior cloning (%BC), covered below. One thing to keep in mind is that the condition is the final return of the whole trajectory, not the causal effect of this step’s action. In stochastic environments the two come apart, as the bandit example in this post demonstrates.

Experiments and Conclusions

Atari

The Atari experiments use 1% of the DQN replay dataset (500 thousand of the 50 million transitions) and four games (Breakout, Qbert, Pong, Seaquest), and report the mean and standard deviation over 3 seeds. Scores are normalized to a professional gamer (100 is the professional gamer, 0 is a random policy). The CQL, REM, and QR-DQN numbers are taken directly from their papers; BC uses the same network and hyperparameters as DT but without the return condition. Bold marks the best mean in each row:

GameDTCQLQR-DQNREMBC
Breakout267.5 ± 97.5211.117.18.9138.9 ± 61.7
Qbert15.4 ± 11.4104.20.00.017.3 ± 14.7
Pong106.1 ± 8.1111.918.00.585.2 ± 20.0
Seaquest2.5 ± 0.41.70.40.72.1 ± 0.3

The paper reads this as “competitive with CQL in 3 of 4 games”. A closer look: DT leads on Breakout and Seaquest, is slightly lower on Pong, and is far lower on Qbert (15.4 against 104.2). The Breakout lead over CQL is 56.4 points, while DT’s own seed-to-seed standard deviation is 97.5; with only 3 seeds, that lead is within noise. BC, which has the return condition removed, is lower on Breakout and Pong (138.9 and 85.2) and slightly higher on Qbert (17.3 against 15.4). All of these gaps are of the same order as the 3-seed standard deviations (Breakout differs by 128.6 with standard deviations of 97.5 and 61.7; Pong differs by 20.9 with 8.1 and 20.0), so from this table alone it is hard to say how much the return condition contributes on Atari.

D4RL Gym tasks

The benchmark has the three D4RL locomotion environments (HalfCheetah, Hopper, Walker2d) plus the paper’s own 2D Reacher (goal-conditioned, sparse reward), each with three datasets: Medium (1 million steps from a “medium” policy that scores about a third of an expert), Medium-Replay (the replay buffer of an agent trained up to medium level, roughly 25 thousand to 400 thousand steps), and Medium-Expert (1 million medium steps and 1 million expert steps, combined). CQL numbers come from the CQL paper, BEAR, BRAC, and AWR from the D4RL paper, and BC was run by the authors (the paper says previously reported BC was weak, so they switched to an MLP and reran it). Scores are normalized so that an expert is 100; the ± on DT is the spread over 3 seeds. The table lists only DT, CQL, and BC, with the best value among these three in bold (ME, M, and MR are Medium-Expert, Medium, and Medium-Replay):

TaskDTCQLBC
ME · HalfCheetah86.8 ± 1.362.459.9
ME · Hopper107.6 ± 1.8111.079.6
ME · Walker108.1 ± 0.298.736.6
ME · Reacher89.1 ± 1.330.673.3
M · HalfCheetah42.6 ± 0.144.443.1
M · Hopper67.6 ± 1.058.063.9
M · Walker74.0 ± 1.479.277.3
M · Reacher51.2 ± 3.426.048.9
MR · HalfCheetah36.6 ± 0.846.24.3
MR · Hopper82.7 ± 7.048.627.6
MR · Walker66.6 ± 3.026.736.9
MR · Reacher18.0 ± 2.419.05.4

The paper concludes that DT “achieves the highest scores in a majority of the tasks and is competitive with the state of the art in the remaining tasks”. By my recomputation, DT has the best mean of all six methods in 7 of the 12 rows, and beats CQL in 7 and loses in 5. Excluding Reacher, the average is 74.7 for DT, 63.9 for CQL, and 47.7 for BC (the paper prints BC’s two averages in swapped places). BEAR, BRAC-v, and AWR are not in the table; BRAC-v is best on three rows. The advantage is concentrated in datasets of mixed quality, detailed in the Hands-On Check below.

Comparison with percentile behavior cloning

The paper proposes a control called percentile behavior cloning (%BC): behavior-clone only the top X% of timesteps, ranked by the return of the whole trajectory, with X running from 100% (ordinary BC) down toward 0 (clone only the best trajectory). It is not a realistic method, because X can only be chosen by trying it in the environment, but it answers the question “is DT just imitating a high-return subset of the data?”

  • On D4RL (Table 3, average over the 8 Medium and Medium-Replay rows): 10%BC is 56.7, DT is printed as 56.1 (the rows recompute to 54.9), 25%BC is 52.7, 40%BC is 49.4, CQL is 43.5, and 100%BC (plain BC) is 39.5. With plenty of data, the best %BC matches DT and does not lose to CQL.
  • On Atari (Table 4): with little data (1%), %BC is weak. On Breakout, 10%, 25%, 40%, and 100% give 28.5, 73.5, 108.2, and 138.9 against DT’s 267.5; on Pong, 2.5, 13.3, 72.7, and 85.2 against 106.1. The paper’s explanation is that with little data, DT can use every trajectory to generalize, even those that look nothing like the target return.

Controllability of the return and context length

  • Does the return actually steer the behavior (Figure 4)? The paper varies the target return and plots the return actually obtained: on every task the two are highly correlated, and on Pong, HalfCheetah, and Walker they almost lie on the ideal diagonal. The paper also says that on Seaquest a target above the dataset’s maximum return still yields higher returns, so it calls DT “sometimes capable of extrapolation”. That is a reading of a figure; the paper gives no numbers.
  • Context length (Table 5). Removing the history (K=1K=1) lowers the score on all four games: Breakout drops from 267.5 to 73.9, Pong from 106.1 to 2.5, and Qbert and Seaquest go from 15.1 to 13.6 and from 2.5 to 0.6. The paper’s guess is that the context lets the model identify which policy produced the actions.

Long-horizon credit assignment and delayed rewards

In the Key-to-Door environment the agent first visits a room with a key, then an empty room, and finally a room with a door. The door pays a reward only if the key was picked up in the first phase, so credit has to travel from the start of the episode to the end. The training data are all trajectories of random actions, and a random policy succeeds 3.1% of the time. Success rates (Table 6, in %):

Training dataDT%BCCQLBC
1,000 random trajectories71.869.913.11.4
10,000 random trajectories94.695.113.31.6

The paper’s reading is that methods using hindsight returns (DT, and %BC trained only on successful trajectories) learn effective policies, while TD learning (CQL) cannot propagate value over the long horizon. It is worth noting that %BC does as well as DT, so what this experiment shows is that filtering or conditioning on success works; it does not on its own show that attention performs long-range credit assignment. The paper also modifies DT to output return tokens as well, and finds that its return predictions update with events and its attention concentrates on the moments of picking up the key and reaching the door (Figure 5); this is a qualitative observation.

The delayed-reward experiment postpones all of Hopper’s reward to a single payment at the end of the trajectory (Table 7; scores are D4RL-normalized):

Hopper dataDT (delayed)DT (dense)CQL (delayed)CQL (dense)
Medium-Expert107.3107.69.0111.0
Medium60.767.65.258.0
Medium-Replay78.582.72.048.6

DT’s scores barely change while CQL falls to single digits; the paper concludes that DT and imitation learning are insensitive to reward sparsity. This experiment covers only Hopper.

Hands-On Check: Model Size, the Paper’s Tables, Shortest Paths and a Stochastic Counterexample

The Decision Transformer paper has a dozen tables and, in the appendix, a shortest-path toy you can reproduce. The script below does four things: (1) it counts the parameters of the Gym-sized DT using the official implementation’s configuration and compares it with GPT-2 small; (2) it recomputes the game-normalized Atari scores from the raw scores, recomputes the averages of Tables 2 and 3 from their rows, and compares the BC column of Table 7 with Table 2; (3) it reproduces the appendix A.3 shortest-path example (20 nodes, 1,000 random walks) and adds two controls: a GPT without the prior, and a lookup-table policy that only counts how often each (state, steps-left) pair occurs, with no neural network; (4) it runs a two-armed bandit to show that, in a stochastic environment, conditioning on “win” does not pick the best arm.

Environment: Apple M2 Max (CPU only, 4 threads), Python 3.14.3, torch 2.10.0, numpy 2.4.2, transformers 5.3.0; no model or dataset is downloaded, and the whole script takes about 3 minutes. Parameters are counted from a Hugging Face GPT2Model configuration (the official implementation uses a copy of it with the positional embeddings removed). I transcribed the table numbers from the paper’s PDF text. The averages of Tables 2 and 3 can mostly be recomputed from the transcribed rows; for the few that cannot, I checked my transcription against the PDF layout and confirmed that the printed numbers themselves are off. All randomness uses fixed seeds, with separate seeds for sampling, training, and evaluation. Parts 1, 2, and 4 are deterministic arithmetic or numpy random numbers and should reproduce exactly in another environment; part 3 trains a small Transformer, so a different torch version or hardware may move individual percentages slightly. Part 3 is a small experiment of my own: 5 random graphs, one training run per graph, and no measurement of seed-to-seed variation, so I do not interpret differences of a few points.

"""Decision Transformer: model size, tables, shortest path, a bandit."""
import numpy as np
import torch
import torch.nn as nn
from transformers import GPT2Config, GPT2Model

torch.set_num_threads(4)

# ============ 1. Model size (Gym: 3 layers, d=128, 1 head) ============
print("== 1. model size ==")


def gpt2_body(h, layers, heads=1):
    # the official code builds on HF GPT2Model; count without embeddings
    cfg = GPT2Config(vocab_size=1, n_embd=h, n_layer=layers, n_head=heads,
                     n_inner=4 * h, n_positions=1024)
    m = GPT2Model(cfg)
    n = sum(p.numel() for p in m.parameters())
    return n - m.wte.weight.numel() - m.wpe.weight.numel()


def dt_total(state_dim, act_dim, h=128, layers=3, max_ep_len=1000):
    body = gpt2_body(h, layers)
    unused_wte = h                      # official code keeps a vocab_size=1 wte
    time_emb = max_ep_len * h           # one vector per timestep
    inputs = (1 * h + h) + (state_dim * h + h) + (act_dim * h + h) + 2 * h
    heads = (h * state_dim + state_dim) + (h * act_dim + act_dim) + (h + 1)
    return body + unused_wte + time_emb + inputs + heads


body = gpt2_body(128, 3)
formula = 3 * (12 * 128 ** 2 + 13 * 128) + 2 * 128   # 12Ld^2 + 13Ld + ln_f
print(f"transformer body {body:,} (formula {formula:,})")
for name, sd, ad in (("hopper", 11, 3), ("halfcheetah", 17, 6),
                     ("walker2d", 17, 6)):
    print(f"{name} (state {sd}, action {ad}): {dt_total(sd, ad):,}")
gpt2_small = gpt2_body(768, 12, heads=12)
print(f"gpt2-small body {gpt2_small:,} = {gpt2_small / body:.0f}x DT body")

# ============ 2. Recompute the paper's tables ============
print("\n== 2. paper tables ==")
GAMES = ("Breakout", "Qbert", "Pong", "Seaquest")
RANGE = {"Breakout": (2, 30), "Qbert": (164, 13455),     # table 11
         "Pong": (-21, 15), "Seaquest": (68, 42055)}     # (random, gamer)


def norm(game, raw):
    lo, hi = RANGE[game]
    return 100 * (raw - lo) / (hi - lo)


def check_norm(title, cols, raw_rows, printed_rows):
    """Raw scores have few decimals: allow rounding, flag the rest."""
    bad = []
    for game in GAMES:
        for col, raw, shown in zip(cols, raw_rows[game], printed_rows[game]):
            dec = len(raw.split(".")[1]) if "." in raw else 0
            tol = 0.5 * 10 ** -dec
            a, b = norm(game, float(raw) - tol), norm(game, float(raw) + tol)
            if not min(a, b) - 0.05 <= shown <= max(a, b) + 0.05:
                bad.append(f"{game} {col}: printed {shown}, "
                           f"recomputed {norm(game, float(raw)):.1f}")
    print(f"{title}: {len(bad)} of {4 * len(cols)} cells off by > rounding")
    for line in bad:
        print("  " + line)


check_norm("table 1 vs table 12", ("DT", "CQL", "QR-DQN", "REM", "BC"),
           {"Breakout": ("76.9", "61.1", "6.8", "4.5", "40.9"),
            "Qbert": ("2215.8", "14012.0", "156.0", "160.1", "2464.1"),
            "Pong": ("17.1", "19.3", "-14.5", "-20.8", "9.7"),
            "Seaquest": ("1129.3", "779.4", "250.1", "370.5", "968.6")},
           {"Breakout": (267.5, 211.1, 17.1, 8.9, 138.9),
            "Qbert": (15.4, 104.2, 0.0, 0.0, 17.3),
            "Pong": (106.1, 111.9, 18.0, 0.5, 85.2),
            "Seaquest": (2.5, 1.7, 0.4, 0.7, 2.1)})
check_norm("table 4 vs table 13", ("DT", "10%BC", "25%BC", "40%BC", "100%BC"),
           {"Breakout": ("76.9", "10.0", "22.6", "32.3", "40.9"),
            "Qbert": ("2215.8", "1045", "2302.5", "1674.1", "2464.1"),
            "Pong": ("17.1", "-20.3", "-16.2", "5.2", "9.7"),
            "Seaquest": ("1129.3", "521.3", "549.3", "758", "968.6")},
           {"Breakout": (267.5, 28.5, 73.5, 108.2, 138.9),
            "Qbert": (15.4, 6.6, 16.0, 11.8, 17.3),
            "Pong": (106.1, 2.5, 13.3, 72.7, 85.2),
            "Seaquest": (2.5, 1.1, 1.1, 1.6, 2.1)})

# Table 2: per row DT, CQL, BEAR, BRAC-v, AWR, BC; None means "-"
T2 = {("ME", "HalfCheetah"): (86.8, 62.4, 53.4, 41.9, 52.7, 59.9),
      ("ME", "Hopper"): (107.6, 111.0, 96.3, 0.8, 27.1, 79.6),
      ("ME", "Walker"): (108.1, 98.7, 40.1, 81.6, 53.8, 36.6),
      ("ME", "Reacher"): (89.1, 30.6, None, None, None, 73.3),
      ("M", "HalfCheetah"): (42.6, 44.4, 41.7, 46.3, 37.4, 43.1),
      ("M", "Hopper"): (67.6, 58.0, 52.1, 31.1, 35.9, 63.9),
      ("M", "Walker"): (74.0, 79.2, 59.1, 81.1, 17.4, 77.3),
      ("M", "Reacher"): (51.2, 26.0, None, None, None, 48.9),
      ("MR", "HalfCheetah"): (36.6, 46.2, 38.6, 47.7, 40.3, 4.3),
      ("MR", "Hopper"): (82.7, 48.6, 33.7, 0.6, 28.4, 27.6),
      ("MR", "Walker"): (66.6, 26.7, 19.2, 0.9, 15.5, 36.9),
      ("MR", "Reacher"): (18.0, 19.0, None, None, None, 5.4)}
M2 = ("DT", "CQL", "BEAR", "BRAC-v", "AWR", "BC")
PRINTED = {"DT": (74.7, 69.2), "CQL": (63.9, 54.2), "BEAR": (48.2, None),
           "BRAC-v": (36.9, None), "AWR": (34.3, None), "BC": (46.4, 47.7)}


def near(x, y):
    return abs(x - y) < 0.1       # treated as rounding


print("table 2 averages (without Reacher / all), printed vs recomputed")
for j, m in enumerate(M2):
    rows = [(k, v[j]) for k, v in T2.items() if v[j] is not None]
    no_r = np.mean([x for k, x in rows if k[1] != "Reacher"])
    allm = np.mean([x for _, x in rows])
    p0, p1 = PRINTED[m]
    swapped = p1 and near(p0, allm) and near(p1, no_r) and not near(p0, no_r)
    note = "   <- the two printed values are swapped" if swapped else ""
    shown = f"{p0} / {p1}" if p1 else f"{p0} / -"
    got = f"{no_r:.1f} / {allm:.1f}" if p1 else f"{no_r:.1f} / -"
    print(f"  {m:7s} printed {shown:11s} recomputed {got}{note}")
wins = sum(v[0] == max(x for x in v if x is not None) for v in T2.values())
print(f"DT has the best mean in {wins} of {len(T2)} rows of table 2")
for other, j in (("CQL", 1), ("BC", 5)):
    w = sum(v[0] > v[j] for v in T2.values())
    print(f"DT vs {other}: {w} wins, {len(T2) - w} losses over the 12 rows")
# per-dataset means without Reacher
for ds in ("ME", "M", "MR"):
    vals = [v for k, v in T2.items() if k[0] == ds and k[1] != "Reacher"]
    m = [np.mean([v[j] for v in vals]) for j in (0, 1, 5)]
    print(f"{ds:2s} mean without Reacher: DT {m[0]:.1f}, CQL {m[1]:.1f}, "
          f"BC {m[2]:.1f}")

# Table 3: DT, x%BC, CQL; the eight Medium and Medium-Replay rows
T3 = [(42.6, 42.9, 43.0, 43.1, 43.1, 44.4),
      (67.6, 65.9, 65.2, 65.3, 63.9, 58.0),
      (74.0, 78.8, 80.9, 78.8, 77.3, 79.2),
      (51.2, 51.0, 48.9, 58.2, 58.4, 26.0),
      (36.6, 40.8, 40.9, 41.1, 4.3, 46.2),
      (82.7, 70.6, 58.6, 31.0, 27.6, 48.6),
      (66.6, 70.4, 67.8, 67.2, 36.9, 26.7),
      (18.0, 33.1, 16.2, 10.7, 5.4, 19.0)]
P3 = (56.1, 56.7, 52.7, 49.4, 39.5, 43.5)
M3 = ("DT", "10%BC", "25%BC", "40%BC", "100%BC", "CQL")
print("table 3 average row, printed vs recomputed")
for j, m in enumerate(M3):
    r = np.mean([row[j] for row in T3])
    flag = "" if near(r, P3[j]) else "   <- differs"
    print(f"  {m:7s} printed {P3[j]:.1f}  recomputed {r:.1f}{flag}")
# Table 7 (delayed reward) BC column vs the Hopper rows of table 2
print("table 7 BC vs table 2 BC (Hopper): ", end="")
t7 = {"ME": 59.9, "M": 63.9, "MR": 27.6}
print(", ".join(f"{k} {t7[k]} vs {T2[(k, 'Hopper')][5]}" for k in t7))

# ============ 3. Shortest path, trained on random walks ============
print("\n== 3. shortest path from random walks ==")
N, T, NR = 20, 10, 11          # nodes, trajectory length, returns k=0..10


def make_graph(seed):
    rng = np.random.RandomState(seed)
    while True:
        adj = rng.rand(N, N) < 0.1          # paper: 20 nodes, edge density 0.1
        np.fill_diagonal(adj, False)
        best = None
        for goal in range(N):               # reverse BFS: distance to the goal
            dist = np.full(N, np.inf)
            dist[goal] = 0
            frontier = [goal]
            while frontier:
                nxt = []
                for v in frontier:
                    for u in np.flatnonzero(adj[:, v]):
                        if dist[u] == np.inf:
                            dist[u] = dist[v] + 1
                            nxt.append(u)
                frontier = nxt
            starts = [s for s in range(N) if 1 <= dist[s] <= T - 1]
            if best is None or len(starts) > len(best[2]):
                best = (goal, dist, starts)
        if len(best[2]) >= 6:               # goal needs many start nodes
            return adj, best[0], best[1], best[2]


def walk(adj, goal, start, rng):
    s, path = start, [start]
    for _ in range(T):
        nb = np.flatnonzero(adj[s])
        if s != goal and len(nb):               # stay once the goal is reached
            s = rng.choice(nb)
        path.append(s)
    return path


def first_hit(path, goal):
    return path.index(goal) if goal in path else T


def make_data(adj, goal, n, rng):
    others = [s for s in range(N) if s != goal]
    data = []
    for _ in range(n):
        path = walk(adj, goal, rng.choice(others), rng)
        g = first_hit(path, goal)
        # 3 tokens per step: state s_t, return k_t (steps left), action a_t
        data.append((path, [(path[t], max(g - t, 0), path[t + 1])
                            for t in range(T)]))
    return data


class TinyGPT(nn.Module):
    def __init__(self, d=64, layers=2, heads=4):
        super().__init__()
        self.emb = nn.Embedding(N + NR + N, d)
        self.pos = nn.Embedding(3 * T, d)
        block = nn.TransformerEncoderLayer(d, heads, 4 * d, 0.0,
                                           batch_first=True, norm_first=True)
        self.enc = nn.TransformerEncoder(block, layers,
                                         enable_nested_tensor=False)
        self.ln, self.head = nn.LayerNorm(d), nn.Linear(d, N + NR + N)

    def forward(self, x):
        L = x.shape[1]
        h = self.emb(x) + self.pos(torch.arange(L))
        mask = nn.Transformer.generate_square_subsequent_mask(L)
        return self.head(self.ln(self.enc(h, mask=mask, is_causal=True)))


def train(data, seed, steps=400):
    torch.manual_seed(seed)
    x = torch.tensor([[v for s, k, a in toks for v in (s, N + k, N + NR + a)]
                      for _, toks in data])
    model = TinyGPT()
    opt = torch.optim.AdamW(model.parameters(), lr=3e-3, weight_decay=0.01)
    ce = nn.CrossEntropyLoss()
    for _ in range(steps):
        out = model(x[:, :-1])
        k_logits = out[:, 0::3, N:N + NR]            # return, after a state
        a_logits = out[:, 1::3, N + NR:]             # action, after a return
        loss = (ce(k_logits.reshape(-1, NR), (x[:, 1::3] - N).reshape(-1))
                + ce(a_logits.reshape(-1, N),
                     (x[:, 2::3] - N - NR).reshape(-1)))
        opt.zero_grad()
        loss.backward()
        opt.step()
    return model


PRIOR = torch.tensor([T + 1 - k for k in range(NR)], dtype=torch.float32)


@torch.no_grad()
def rollout_gpt(model, adj, starts, reps, gen, power):
    s = torch.tensor([x for x in starts for _ in range(reps)])
    seq, path = s[:, None], [s]
    valid = torch.tensor(adj)
    for t in range(T):
        p = torch.softmax(model(seq)[:, -1, N:N + NR], -1) * PRIOR ** power
        k = torch.multinomial(p / p.sum(-1, keepdim=True), 1, generator=gen)
        seq = torch.cat([seq, N + k], 1)
        pa = torch.softmax(model(seq)[:, -1, N + NR:], -1)
        a = torch.multinomial(pa, 1, generator=gen)[:, 0]
        seq = torch.cat([seq, (N + NR + a)[:, None]], 1)
        s = torch.where(valid[s, a], a, s)       # stay if a is not a neighbor
        path.append(s)
        if t < T - 1:
            seq = torch.cat([seq, s[:, None]], 1)
    return torch.stack(path, 1).tolist()


def rollout_table(adj, data, starts, reps, rng, power, plan):
    cr, ca = np.zeros((N, NR)), np.zeros((N, NR, N))
    cr0 = np.zeros((N, NR))                   # returns at step 0 only
    for _, toks in data:
        for t, (s, k, a) in enumerate(toks):
            cr[s, k] += 1
            ca[s, k, a] += 1
            cr0[s, k] += t == 0
    prior = PRIOR.numpy().astype(float)
    paths = []
    for st in starts:
        for _ in range(reps):
            s, path, k = st, [st], None
            for t in range(T):
                if k is None or not plan:     # plan: draw the return once
                    c = cr0[s] if plan else cr[s]
                    p = c / max(c.sum(), 1) * prior ** power
                    k = rng.choice(NR, p=p / p.sum() if p.sum() else None)
                else:
                    k = max(k - 1, 1)         # then subtract 1 per step
                w = ca[s, k]
                nb = np.flatnonzero(adj[s])
                if w.sum():
                    a = rng.choice(N, p=w / w.sum())
                else:
                    a = rng.choice(nb) if len(nb) else s
                s = a if adj[s, a] else s
                path.append(s)
            paths.append(path)
    return paths


def metrics(paths, goal, dist, starts, reps, seen):
    d = np.repeat(dist[starts], reps)
    hit = np.array([goal in p for p in paths])
    steps = np.array([first_hit(p, goal) for p in paths])
    new = [tuple(p[:steps[i] + 1]) not in seen
           for i, p in enumerate(paths) if hit[i]]
    return (hit.mean(), (steps[hit] == d[hit]).mean(),
            (steps[hit] - d[hit]).mean(), np.mean(new))


NAMES = ["random walk", "GPT, no prior", "GPT, prior^1", "GPT, prior^10",
         "table, each step", "table, plan once"]
rows = []
for g in range(5):
    adj, goal, dist, starts = make_graph(g)
    data = make_data(adj, goal, 1000, np.random.RandomState(100 + g))
    seen = {tuple(p[i:j]) for p, _ in data
            for i in range(len(p)) for j in range(i + 2, len(p) + 1)}
    model = train(data, 200 + g)
    reps = 200
    gen = torch.Generator().manual_seed(300 + g)
    rng_t = np.random.RandomState(400 + g)
    rng_w = np.random.RandomState(500 + g)
    args = (goal, dist, starts, reps, seen)
    res = [metrics([walk(adj, goal, st, rng_w) for st in starts
                    for _ in range(reps)], *args)]
    for power in (0, 1, 10):
        res.append(metrics(rollout_gpt(model, adj, starts, reps, gen, power),
                           *args))
    res.append(metrics(rollout_table(adj, data, starts, reps, rng_t, 10,
                                     False), *args))
    res.append(metrics(rollout_table(adj, data, starts, reps, rng_t, 10,
                                     True), *args))
    rows.append(res)
    print(f"graph {g}: goal {goal}, {len(starts)} starts, shortest "
          f"{int(dist[starts].min())}-{int(dist[starts].max())} steps | "
          f"success {res[0][0]:.0%} -> {res[3][0]:.0%}, "
          f"optimal {res[0][1]:.0%} -> {res[3][1]:.0%}")
print("mean over 5 graphs        success optimal excess  unseen")
for i, name in enumerate(NAMES):
    s, o, e, u = np.mean([r[i] for r in rows], axis=0)
    print(f"  {name:18s} {s:8.1%} {o:7.1%} {e:6.2f} {u:7.1%}")

# ====== 4. A stochastic bandit: conditioning on return is not optimal ======
print("\n== 4. a stochastic bandit ==")
P_WIN = np.array([0.5, 0.1])          # arm 0 is safe, arm 1 is a lottery
print("P(lottery) in data | P(lottery | win) data, exact | "
      "success of DT(target=win), best arm")
for pb in (0.5, 0.9, 0.99):
    rng = np.random.RandomState(600 + int(pb * 100))
    n = 200_000
    arm = (rng.rand(n) < pb).astype(int)
    win = rng.rand(n) < P_WIN[arm]
    q = np.bincount(arm[win], minlength=2) / win.sum()        # P(arm|win)
    exact = pb * P_WIN[1] / (pb * P_WIN[1] + (1 - pb) * P_WIN[0])
    rng2 = np.random.RandomState(700 + int(pb * 100))        # fresh episodes
    arm2 = (rng2.rand(n) < q[1]).astype(int)
    dt_rate = (rng2.rand(n) < P_WIN[arm2]).mean()
    best = np.argmax([win[arm == a].mean() for a in (0, 1)])
    best_rate = (rng2.rand(n) < P_WIN[best]).mean()
    print(f"  {pb:.2f} | {q[1]:.3f}, {exact:.3f} | "
          f"{dt_rate:.3f}, {best_rate:.3f}")

The output:

== 1. model size ==
transformer body 595,072 (formula 595,072)
hopper (state 11, action 3): 727,695
halfcheetah (state 17, action 6): 730,008
walker2d (state 17, action 6): 730,008
gpt2-small body 85,056,000 = 143x DT body

== 2. paper tables ==
table 1 vs table 12: 2 of 20 cells off by > rounding
  Qbert QR-DQN: printed 0.0, recomputed -0.1
  Pong DT: printed 106.1, recomputed 105.8
table 4 vs table 13: 4 of 20 cells off by > rounding
  Qbert 25%BC: printed 16.0, recomputed 16.1
  Qbert 40%BC: printed 11.8, recomputed 11.4
  Pong DT: printed 106.1, recomputed 105.8
  Pong 10%BC: printed 2.5, recomputed 1.9
table 2 averages (without Reacher / all), printed vs recomputed
  DT      printed 74.7 / 69.2 recomputed 74.7 / 69.2
  CQL     printed 63.9 / 54.2 recomputed 63.9 / 54.2
  BEAR    printed 48.2 / -    recomputed 48.2 / -
  BRAC-v  printed 36.9 / -    recomputed 36.9 / -
  AWR     printed 34.3 / -    recomputed 34.3 / -
  BC      printed 46.4 / 47.7 recomputed 47.7 / 46.4   <- the two printed values are swapped
DT has the best mean in 7 of 12 rows of table 2
DT vs CQL: 7 wins, 5 losses over the 12 rows
DT vs BC: 10 wins, 2 losses over the 12 rows
ME mean without Reacher: DT 100.8, CQL 90.7, BC 58.7
M  mean without Reacher: DT 61.4, CQL 60.5, BC 61.4
MR mean without Reacher: DT 62.0, CQL 40.5, BC 22.9
table 3 average row, printed vs recomputed
  DT      printed 56.1  recomputed 54.9   <- differs
  10%BC   printed 56.7  recomputed 56.7
  25%BC   printed 52.7  recomputed 52.7
  40%BC   printed 49.4  recomputed 49.4
  100%BC  printed 39.5  recomputed 39.6   <- differs
  CQL     printed 43.5  recomputed 43.5
table 7 BC vs table 2 BC (Hopper): ME 59.9 vs 79.6, M 63.9 vs 63.9, MR 27.6 vs 27.6

== 3. shortest path from random walks ==
graph 0: goal 18, 17 starts, shortest 1-4 steps | success 61% -> 92%, optimal 38% -> 76%
graph 1: goal 15, 18 starts, shortest 1-4 steps | success 83% -> 96%, optimal 43% -> 82%
graph 2: goal 5, 19 starts, shortest 1-6 steps | success 23% -> 80%, optimal 48% -> 77%
graph 3: goal 7, 14 starts, shortest 1-4 steps | success 63% -> 92%, optimal 48% -> 80%
graph 4: goal 2, 17 starts, shortest 1-7 steps | success 33% -> 63%, optimal 71% -> 90%
mean over 5 graphs        success optimal excess  unseen
  random walk           52.7%   49.4%   1.76   14.4%
  GPT, no prior         51.7%   48.4%   1.74    1.0%
  GPT, prior^1          77.2%   55.5%   1.17    1.0%
  GPT, prior^10         84.8%   81.2%   0.32    6.1%
  table, each step      80.6%   68.0%   0.84    7.4%
  table, plan once      86.7%   75.3%   0.58    4.5%

== 4. a stochastic bandit ==
P(lottery) in data | P(lottery | win) data, exact | success of DT(target=win), best arm
  0.50 | 0.167, 0.167 | 0.434, 0.500
  0.90 | 0.641, 0.643 | 0.243, 0.501
  0.99 | 0.953, 0.952 | 0.120, 0.500

Model size: the Gym-sized Transformer body has only 595 thousand parameters

  • The body has 595,072 parameters, matching the formula L(12d2+13d)+2dL(12d^2+13d)+2d with L=3L=3 layers and d=128d=128 (the final layer norm accounts for the 2d2d). Adding the timestep embedding (1000×128=128,0001000\times128=128{,}000), the linear layers for the three input types, and the prediction heads gives 727,695 (Hopper: 11-dimensional state, 3-dimensional action) or 730,008 (HalfCheetah and Walker2d: 17-dimensional state, 6-dimensional action). Outside the body, the timestep embedding is the largest piece, more than 17.5% of the total. The total also includes the state and return prediction heads that the official code builds but that take no part in the training objective, plus a word embedding with a vocabulary of one; together these are only a thousand or two parameters.
  • On the same accounting, the GPT-2 small body has 85,056,000 parameters, 143 times as many. In the Gym experiments, the “Transformer” in the title is a very small network; the paper itself says only that it is large compared with standard RL models that learn a single policy. Scalability is the paper’s motivation, not something it evaluates.

Recomputing the tables: a few mismatches, none changes the conclusions

  • Game-normalized scores. Recomputing from the raw scores in Tables 12 and 13 with the random and professional-gamer scores of Table 11, 2 of the 20 cells in Table 1 fall outside rounding error (Qbert QR-DQN: printed 0.0, recomputed -0.1; Pong DT: printed 106.1, recomputed 105.8), and so do 4 of the 20 cells in Table 4; the largest is Pong 10%BC (printed 2.5, recomputed 1.9). All gaps are at most 0.6 points. For comparison, the standard deviation is 8.1 for Pong DT and 13.8 for Qbert 25%BC; only Pong 10%BC has a standard deviation (0.2) smaller than its gap, but it is the worst column in that table (2.5 against 106.1 for DT), so no comparison changes.
  • The averages in Table 2 reproduce, except that the two BC averages are swapped. DT is 74.7 (without Reacher) and 69.2 (all settings), CQL is 63.9 and 54.2, and BEAR, BRAC-v, and AWR also match. BC is printed as 46.4 and 47.7, but recomputes to 47.7 (without Reacher) and 46.4 (all): the two numbers are in each other’s place.
  • “Highest on most tasks” holds. Across the 12 rows of Table 2, DT has the best mean in 7, beats CQL in 7 and loses in 5, and beats BC in 10 and loses in 2. BRAC-v is best on three rows: HalfCheetah in Medium and in Medium-Replay, and Walker in Medium.
  • The advantage is concentrated in mixed-quality data. Excluding Reacher and averaging by dataset: on Medium-Expert, DT is 100.8, CQL 90.7, BC 58.7; on Medium-Replay, 62.0, 40.5, 22.9; but on Medium, collected by a single “medium” policy, the three are 61.4, 60.5, 61.4, with DT and BC practically equal. This fits the explanation that return conditioning helps only when the data mixes behavior of different quality: when the data come from one policy, there is nothing to separate by return.
  • The DT average in Table 3 is printed too high. It is printed as 56.1, but the rows recompute to 54.9, a gap of 1.2 that rounding cannot explain. With the recomputed value, 10%BC (56.7) is 1.8 points above DT; the printed numbers show a gap of only 0.6. 100%BC is printed as 39.5 and recomputes to 39.6, a rounding-level difference. Either way, “the best percentile BC matches DT” holds: on these datasets, cloning only the top 10% by return is enough to catch up with DT.
  • One BC cell in Table 7 differs from Table 2. In the Hopper Medium-Expert row, BC is 59.9 in Table 7 and 79.6 in Table 2; 59.9 happens to be the BC value of the HalfCheetah row in Table 2, which looks like a copied row. The Medium and Medium-Replay rows agree.

Shortest paths: what the return condition does, and what the Transformer does

I reproduced the example from appendix A.3: a random directed graph on 20 nodes where each edge exists with probability 0.1; a training set of 1,000 random walks of 10 steps, with three tokens per step (state, steps left, action); at inference the model generates its own return token, with its predicted probability multiplied by the prior Pprior(k)∝T+1−kP_{prior}(k)\propto T+1-k raised to the 10th power (kk is the number of steps still needed to reach the goal, so the prior favors smaller kk). What the paper leaves open and I chose: the walk stays at the goal once it arrives; the goal is the node reachable within 9 steps from the largest number of other nodes; the model is a small GPT with 2 layers, 64 dimensions, and 4 heads, trained full-batch on the 1,000 sequences for 400 steps; return tokens take the values k=0,…,10k=0,\dots,10. Two things changed during debugging: in the first version a random walk could leave the goal after reaching it, which put a contradiction in the return tokens (the goal has been reached, yet the return gets worse), so I made the goal absorbing; and I first used prior exponent 1, which helped only a little, before switching to the paper’s 10, so the table lists both. Each number in the table is the mean over 5 graphs, with 200 rollouts from every start node. “Reaches goal” is the share that arrive within 10 steps, “Shortest” is the share of those that take exactly the shortest path, and “New path” is the share of those whose path from start to goal is not a contiguous subsequence of any training walk.

PolicyReaches goalShortestExtra stepsNew path
Random walk (the data source)52.7%49.4%1.7614.4%
GPT, no prior51.7%48.4%1.741.0%
GPT, prior exponent 177.2%55.5%1.171.0%
GPT, prior exponent 1084.8%81.2%0.326.1%
Table, resample return each step80.6%68.0%0.847.4%
Table, draw once then subtract 1 per step86.7%75.3%0.584.5%
  • A GPT without the prior is a random walk (51.7% against 52.7%): the model faithfully learns the distribution of the data, including the distribution of return tokens, so sampling the returns it predicts yields average behavior. The improvement comes from the step that favors high returns, not from the Transformer itself.
  • The strength of the prior matters. With exponent 1, the success rate rises to 77.2%, but only 55.5% of the successes take a shortest path; exponent 10 (the paper’s choice) lifts that to 81.2% with 0.32 extra steps on average. The paper does not say why it picked 10 and I simply followed it. It shows that the “high” in a return condition has to be high enough: with a gentle condition, the model still takes detours.
  • A lookup table gets close without a neural network. Counting how often each action follows each (state, steps-left) pair and multiplying by the same prior gives 80.6% (resampling the return every step) or 86.7% (drawing once at the start and subtracting 1 each step, closer to how DT runs), in the same range as the GPT’s 84.8%. The GPT has a higher share of shortest paths (81.2% against 75.3%) and fewer extra steps (0.32 against 0.58); I did not measure how much of that gap is noise, so I only claim the direction. What I can say is that in this toy the gain comes mainly from conditioning on steps left, not from network capacity.
  • “New path” is not evidence of stitching. The paper says 15.8% of generated paths are not subsequences of training trajectories and were stitched from suboptimal segments. In my reproduction the exponent-10 GPT gets 6.1%, while random walks themselves already have 14.4% of their paths outside these 1,000 training walks: with limited data, a freshly sampled walk is often “new”. The GPT without the prior has only 1.0%, even lower than random walks, so it mostly replays segments that appeared in training. The counting rule also differs: I look only at the segment before the goal is reached, and the paper does not say how it counts. So this share neither proves nor disproves stitching.
  • The five graphs differ a lot. The random-walk success rate ranges from 23% to 83%, and the exponent-10 GPT improves it on every graph: 61%→92%, 83%→96%, 23%→80%, 63%→92%, 33%→63%. The last graph has the longest shortest paths (1 to 7 steps) and the lowest success rate within the 10-step budget.

A stochastic environment: conditioning on “win” is not choosing the best arm

The bandit has two arms: the safe arm wins with probability 0.5, the lottery arm with probability 0.1. The data-collecting policy picks the lottery arm with probability pp. DT conditions on “win” and acts from the conditional distribution; for this one-step problem that distribution is just Bayes’ rule:

P(lottery∣win)=0.1 p0.1 p+0.5 (1−p).P(\text{lottery}\mid\text{win})=\frac{0.1\,p}{0.1\,p+0.5\,(1-p)} .
Lottery share in the dataP(lottery arm) given “win”DT win rateAlways the safe arm
0.500.1670.4340.500
0.900.6410.2430.501
0.990.9530.1200.500

The estimated conditional probabilities agree with the exact values (0.167, 0.643, 0.952). The more lottery pulls the data contain, the more of the “winners” got there by luck, and the more the model leans toward the lottery arm; when 90% of the data come from the lottery arm, DT wins only 24.3% of the time, less than half of what always pulling the safe arm gets. The root cause is that DT conditions on an outcome (the return of the whole trajectory), not on a choice you control; in a stochastic environment the outcome mixes in luck, and the model cannot separate the two. This is exactly the failure mode that Paster et al. point out. The paper does not test stochastic environments; its conclusion mentions that in stochastic settings one should condition on a distribution of returns rather than a single deterministic return, but there is no experiment.

Limitations and What Came Next

Points the paper does not develop, but that later research has answered:

  • The evaluation is narrow and the opponents are limited. Atari has only 4 games, 1% of the data, and 3 seeds; D4RL has only 3 locomotion environments plus the self-built Reacher; most baseline scores are taken from other papers, and BC was rerun by the authors; Key-to-Door and delayed rewards each use a single environment.
  • The Transformer is not the key. Emmons et al. (2021, RvS) found that in every environment suite they considered, maximizing likelihood with a two-layer feedforward MLP is competitive with much more complex methods based on TD learning or Transformer sequence modeling; choosing the model capacity and what to condition on is what matters. In this post’s shortest-path example, a lookup table with no neural network reaches a similar success rate.
  • Stochastic environments. Paster et al. (2022) point out that conditioning on a target return and taking the predicted action can fail dramatically in stochastic environments, because a trajectory may have achieved its return only by luck; their ESPER method instead clusters trajectories and conditions on each cluster’s average return. The bandit example here reproduces the failure.
  • Stitching and theory. Yamagata et al. (2022) point out that DT lacks stitching ability, that is, it cannot assemble an optimal policy from pieces of suboptimal trajectories, an important capability in offline RL; they relabel returns-to-go with Q-learning results (QDT). Brandfonbrener et al. (2022) prove that RCSL returns the optimal policy only under assumptions stronger than those of dynamic programming, and give counterexamples for when they fail. The paper’s own shortest-path example claims stitching; in my reproduction the share of new paths is lower, and it does not demonstrate stitching either.
  • The target return is chosen by hand. In Gym it is set near expert level, yet HalfCheetah has to drop to about 50% to work better; in Atari it is 1 or 5 times the dataset maximum. The paper admits that more principled return conditioning is possible and gives no method.
  • Inconsistencies between tables and text. Six cells of Tables 1 and 4 fall outside rounding error against the raw-score Tables 12 and 13, by up to 0.6 points; the two BC averages in Table 2 are swapped; the DT average in Table 3 is printed as 56.1 but recomputes to 54.9; the BC cell of Hopper Medium-Expert in Table 7 differs from Table 2; Qbert for DT is 15.1 in Table 5 and 15.4 in Table 1; the text says it reports “mean and standard deviation” while the captions of Tables 1 to 4 say “mean and variance”; and Tables 9 and 10 say “linear warmup for the first 10510^5 steps”, yet DT trains for only 10510^5 steps in total, BC for only 2.5×1042.5\times10^4, and the official code defaults to 10410^4 warmup steps. Each is harmless alone, but together they suggest checking the numbers against the data and code instead of quoting the paper.

Later work (abstracts consulted in November 2026):

WorkContribution
Trajectory Transformer (Janner et al., 2021, concurrent with DT)Models the distribution of whole trajectories with a Transformer and repurposes beam search as a planner
RvS (Emmons et al., 2021)A two-layer MLP with maximum likelihood is competitive with more complex methods; capacity and what to condition on are what matter
Online Decision Transformer (Zheng et al., 2022)Blends offline pretraining and online fine-tuning in one framework, with sequence-level entropy regularization for exploration
Gato (Reed et al., 2022)One network plays Atari, captions images, chats, and stacks blocks with a real robot arm: a multi-task, multi-embodiment generalist policy
ESPER (Paster et al., 2022)Shows that return conditioning fails in stochastic environments and conditions on clustered average returns instead
Brandfonbrener et al. (2022)Proves that RCSL needs stronger assumptions than dynamic programming to be optimal
QDT (Yamagata et al., 2022)Relabels returns-to-go with dynamic-programming results to add stitching
Bhargava et al. (2023)A systematic comparison of CQL, BC, and DT on D4RL and Robomimic

Bhargava et al. summarize their findings in four points: DT needs more data than CQL but is more robust; in sparse-reward and low-quality-data settings DT is substantially better than CQL and BC; DT and BC are preferable as the task horizon grows or when the data come from human demonstrators; and CQL excels when high stochasticity combines with low data quality. They also find that scaling the amount of data for DT by 5x gives a 2.5x average score improvement on Atari.

What to Take Away From This Paper

  1. The paradigm: reinforcement learning rewritten as conditional sequence modeling. There are three tokens per step (return-to-go, state, action), actions are predicted only at state tokens, and at inference the target return acts as a prompt that is reduced by each reward.
  2. The key variable is the return condition, not the Transformer: percentile behavior cloning, the MLP of RvS, and this post’s lookup-table control all match DT to some degree. On Medium data DT ties BC, which says that conditioning helps only when the data mix behavior of different quality.
  3. The boundary of applicability: near-deterministic environments, adequate coverage, and high-return behavior that is already in the data. Stochastic environments and tasks that need stitching fail, and later work such as ESPER and QDT patches those two holes.
  4. The strength of the evidence: small scale, few seeds, baseline numbers mostly taken from elsewhere, and several tables that do not add up. The direction is credible and the magnitude deserves a discount; its value lies in proposing a clean framework, not in proving that it is better in every setting.

Further Reading

FAQ

What is Decision Transformer, and how does it differ from conventional reinforcement learning?
Decision Transformer (DT; Chen et al., NeurIPS 2021) recasts offline reinforcement learning as conditional sequence modeling. Each trajectory is written as an interleaved sequence of (return, state, action) tokens, and a causally masked GPT is trained to predict the action at each state token with an ordinary supervised loss: mean squared error for continuous actions, cross-entropy for discrete ones. There is no value function, no Bellman backup, and no policy gradient. At test time you supply a desired target return; the model outputs an action, the environment returns a reward, the target return is reduced by that reward, and the loop continues.
What are returns-to-go in Decision Transformer, and how is the target return chosen?
Returns-to-go are the sum of rewards from the current step to the end of the trajectory. The paper feeds them to the model instead of the rewards themselves because an action should depend on how much return is still wanted, not on how much has already been collected. At inference the target return is a hyperparameter set by hand: in Gym the paper uses values near expert level (about 50% for HalfCheetah, which worked better: HalfCheetah 6000, Hopper 3600, Walker 5000, Reacher 50), and in Atari it uses 1 or 5 times the largest return in the dataset (Breakout 90, Qbert 2500, Pong 20, Seaquest 1450). The paper reports that on Seaquest a target above the dataset maximum still produced higher returns, which suggests some extrapolation, but nothing guarantees it.
Is Decision Transformer really better than CQL, and can the results be trusted?
In the paper's D4RL table, DT has the best mean in 7 of 12 rows, beating CQL in 7 and losing in 5. Excluding Reacher, it leads CQL by 10.1 and 21.5 points on average on Medium-Expert and Medium-Replay data, but on Medium data it is nearly tied with CQL and behavior cloning (61.4, 60.5, 61.4). Atari covers only 4 games and 3 seeds, and on Qbert CQL scores 104.2 against DT's 15.4. Percentile behavior cloning on the top 10% of the data by return matches DT on average. Several numbers in the paper also do not add up; for example, the DT average in Table 3 is printed as 56.1 but recomputes to 54.9. The direction is credible and the magnitude deserves a discount; Bhargava et al. (2023) offer a systematic comparison.
Can Decision Transformer stitch suboptimal trajectories together, and is it reliable in stochastic environments?
Both are known weaknesses. Stitching: Yamagata et al. (2022) point out that DT lacks stitching ability and propose relabeling returns with Q-learning results (QDT). Stochastic environments: Paster et al. (2022) show that conditioning on a target return and taking the predicted action can fail because a trajectory may have reached its return by luck. In this post's bandit example the safe arm wins with probability 0.5 and the lottery arm with 0.1; when 90% of the data come from the lottery arm, DT conditioned on 'win' picks the lottery arm 64.1% of the time and wins only 24.3%, against about 50% for always taking the safe arm. Brandfonbrener et al. (2022) further show that return-conditioned supervised learning needs stronger assumptions than dynamic programming to return the optimal policy.
How does Decision Transformer relate to today's large language models, and is it still worth learning?
DT's network is a GPT, its training objective is next-token prediction at the action positions, and the target return acts as a prompt, so it is an early example of putting reinforcement learning into the language-modeling framework. Its original experiments are small, though: the Gym-sized Transformer body has 595,072 parameters, about 1/143 of the GPT-2 small body. Later work also found that the return condition, not the Transformer, does the heavy lifting: Emmons et al. (2021) get competitive results with a two-layer MLP. Writing actions as tokens reappears in Gato (2022), and the RT-2 and OpenVLA explainers on this site also write actions as tokens, but they train by behavior cloning without return conditioning. For the origin and the limits of 'RL as sequence modeling', DT is worth reading.