Skip to content
AI360Xpert
Beta

Decision Transformers and Trajectory Transformer

Decision Transformer treats control as next token prediction. You state the return you want and it generates the actions that earned that return in past data.

A Decision Transformer reads return to go, state and action tokens through causal attention and outputs the next action that fits the requested return
A Decision Transformer reads return to go, state and action tokens through causal attention and outputs the next action that fits the requested return

Why Does This Exist?

Offline reinforcement learning learns from a fixed dataset with no new environment interaction. The standard approach estimates values with Bellman backups, where each update bootstraps from the next estimate. On narrow datasets that bootstrapping compounds small approximation errors into large overestimates, and training diverges.

A second pain is stability. Temporal difference methods need target networks, careful discounting and extra regularizers to stay stable offline. Each addition helps one dataset and hurts the next.

Decision Transformer, introduced by Chen and colleagues in 2021, with the Trajectory Transformer from Janner and colleagues the same year, drops the backup entirely. It treats a trajectory as text to complete and trains with ordinary supervised loss. That trade buys stable optimization at the cost of giving up value based stitching.

This page covers the sequence framing, the return to go conditioning and the inference loop for both models. For the offline setting itself see offline batch reinforcement learning. For the attention mechanism they borrow see transformers in RL. For the value methods they replace see Q-learning.

The one idea you need first

A return is the sum of future rewards from a step onward. The return to go at step tt, written R^t\hat{R}_t, is that sum computed from tt to the end of the episode. If rewards are 22, 33 and 55, the return to go at step 11 is 1010, at step 22 is 88 and at step 33 is 55. Decision Transformer conditions on this number as its request.

Think of It Like This

Ordering by photo at a busy restaurant

You sit down and point at a photo of the finished dish you want. You do not list oven temperatures or stirring times. The cook has served that dish hundreds of times, so the photo is enough to reproduce the steps.

The photo is the return to go. The state of the counter is the state. Each cooking move is an action. The cook is the transformer, trained on past orders. You lower your expectation as courses arrive, just as the agent subtracts earned reward from its target.

Where it stops: a good cook improvises a new dish from spare parts. Decision Transformer does not. It only reproduces combinations it saw in full, so it struggles when the best plan mixes pieces from separate trips.

How It Actually Works

A trajectory τ\tau of length TT becomes an interleaved token list. Here sts_t is the state at step tt, ata_t is the action taken there, rtr_t is the reward received after it and R^t\hat{R}_t is the return to go from tt onward:

τ=(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 return to go is defined as:

R^t=∑k=tTrk\hat{R}_t = \sum_{k=t}^{T} r_k

In plain words: add up every reward from now until the episode ends. That sum is the request the model must satisfy.

Trajectory tokens and causal attention

Returns, states and actions live in different spaces, so each gets its own linear projection into a shared width dd. All three tokens from step tt share one learned timestep embedding ptp_t, which keeps the triplet aligned when the context window slides.

A causal mask restricts attention to the past. When the model predicts ata_t it may read R^1,s1,a1\hat{R}_1, s_1, a_1 through R^t−1,st−1,at−1\hat{R}_{t-1}, s_{t-1}, a_{t-1} plus the current R^t\hat{R}_t and sts_t. It never sees the true ata_t or anything later. The parameters θ\theta are all projection matrices, embeddings and attention weights.

Training loss and inference loop

Training is supervised on trajectories sampled from the offline set D\mathcal{D}. For continuous actions with predicted action a^t\hat{a}_t the loss is mean squared error:

L(θ)=Eτ∼D[1T∑t=1T∥at−a^t(R^t,st,τ<t)∥2]\mathcal{L}(\theta) = \mathbb{E}_{\tau \sim \mathcal{D}} \left[ \frac{1}{T} \sum_{t=1}^{T} \| a_t - \hat{a}_t(\hat{R}_t, s_t, \tau_{<t}) \|^2 \right]

Discrete actions use cross entropy over logits instead. There is no critic, no target network and no discount factor γ\gamma in this loss.

Inference runs as a loop. Pick a target R^1\hat{R}_1, observe s1s_1, predict a1a_1, execute it, receive r1r_1, then decay the request:

R^t+1=R^t−rt\hat{R}_{t+1} = \hat{R}_t - r_t

Append the new tokens and repeat inside a context window of recent steps, often K=20K = 20 timesteps.

Decision Transformer versus Trajectory Transformer

Both treat RL as sequence modeling but they predict different things:

  • Decision Transformer predicts actions directly from return, state and history. It acts as the policy. At test time you feed the desired return and read out actions.
  • Trajectory Transformer models the joint distribution over states, actions and rewards as discrete tokens. It acts as a world model. At test time you search over imagined futures with beam search and execute the first action of the best imagined path.

Use the first when you want a fast policy. Use the second when you want to plan through a learned model and can pay the search cost.

Worked example

Take a three step episode with rewards r1=2.0r_1 = 2.0, r2=3.0r_2 = 3.0 and r3=5.0r_3 = 5.0.

Returns to go, computed backward:

R^1=2.0+3.0+5.0=10.0\hat{R}_1 = 2.0 + 3.0 + 5.0 = 10.0 R^2=3.0+5.0=8.0\hat{R}_2 = 3.0 + 5.0 = 8.0 R^3=5.0\hat{R}_3 = 5.0

Equivalently R^2=R^1−r1=10.0−2.0=8.0\hat{R}_2 = \hat{R}_1 - r_1 = 10.0 - 2.0 = 8.0. The total return is 10.010.0.

At step t=2t = 2 the context holds five tokens: (R^1=10.0,s1,a1,R^2=8.0,s2)(\hat{R}_1 = 10.0, s_1, a_1, \hat{R}_2 = 8.0, s_2). The query at s2s_2 attends to those five and outputs a^2\hat{a}_2.

Suppose the dataset action is a2=[0.50,0.80]a_2 = [0.50, 0.80] and the head predicts a^2=[0.45,0.85]\hat{a}_2 = [0.45, 0.85]. With action width D=2D = 2:

L2=12[(0.45−0.50)2+(0.85−0.80)2]=12[0.0025+0.0025]=0.0025\mathcal{L}_2 = \frac{1}{2}[(0.45 - 0.50)^2 + (0.85 - 0.80)^2] = \frac{1}{2}[0.0025 + 0.0025] = 0.0025

During live rollout you prompt R^1=10.0\hat{R}_1 = 10.0, execute, receive r1=2.0r_1 = 2.0 and update to R^2=8.0\hat{R}_2 = 8.0. The agent now owes itself exactly 8.08.0 more to meet the request.

Code

This snippet computes returns to go, the action loss and the inference decay for the numbers above.

from typing import List

def compute_rtg(rewards: List[float]) -> List[float]:    """Return to go at each step: Rhat[t] = sum(rewards[t:])."""    rtg: List[float] = [0.0] * len(rewards)    running = 0.0    for i in range(len(rewards) - 1, -1, -1):        running += rewards[i]        rtg[i] = running    return rtg

def action_mse(pred: List[float], target: List[float]) -> float:    """Mean squared error over one action vector."""    return sum((p - t) ** 2 for p, t in zip(pred, target)) / len(pred)

rewards = [2.0, 3.0, 5.0]rtg = compute_rtg(rewards)print(rtg)  # -> [10.0, 8.0, 5.0]print(f"{action_mse([0.45, 0.85], [0.50, 0.80]):.6f}")  # -> 0.002500print(rtg[0] - rewards[0])  # -> 8.0

The printed return list, loss and decayed target match the hand computation. The loop runs backward so each entry reuses the sum of everything after it.

Watch Out For

Prompting a return the dataset never earned

Asking for R^1\hat{R}_1 far above the best trajectory in the data pushes the model out of distribution. The attention layers combine fragments they never saw together and the actions turn erratic. You see near expert scores on locomotion logs with smooth demos and near zero on maze logs that need new combinations.

Fix it by prompting near the best observed return, or near a high percentile such as the top tenth. If you truly need better than the data, pair the transformer with a learned value check or augment the data with model rollouts first.

Expecting the model to stitch two half trips

Suppose one log shows start AA to checkpoint BB and another shows BB to goal CC, but no log shows AA to CC. Value methods propagate reward backward across the shared state BB and find the full route. Decision Transformer matches whole sequences, so it never connects the halves.

Symptom: strong results on dense reward locomotion, weak results on sparse navigation that requires stitching. Use Trajectory Transformer with beam search, which can chain imagined segments through its learned dynamics, or add a Q guided sampling step.

The Quick Version

  • Decision Transformer replaces Bellman backups with conditional sequence prediction over (R^t,st,at)(\hat{R}_t, s_t, a_t) triplets.
  • Return to go R^t\hat{R}_t is the future reward sum from tt onward and acts as the prompt for how well to behave.
  • Training is plain supervised regression or classification with a causal mask, so optimization stays stable offline.
  • Inference prompts a target return and decays it by each earned reward with R^t+1=R^t−rt\hat{R}_{t+1} = \hat{R}_t - r_t.
  • Trajectory Transformer instead models full dynamics as discrete tokens and plans with beam search.
  • Sequence matching cannot stitch disjoint trips, so prompt inside the data range on stitching tasks.