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.
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 , written , is that sum computed from to the end of the episode. If rewards are , and , the return to go at step is , at step is and at step is . 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 of length becomes an interleaved token list. Here is the state at step , is the action taken there, is the reward received after it and is the return to go from onward:
The return to go is defined as:
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 . All three tokens from step share one learned timestep embedding , which keeps the triplet aligned when the context window slides.
A causal mask restricts attention to the past. When the model predicts it may read through plus the current and . It never sees the true or anything later. The parameters are all projection matrices, embeddings and attention weights.
Training loss and inference loop
Training is supervised on trajectories sampled from the offline set . For continuous actions with predicted action the loss is mean squared error:
Discrete actions use cross entropy over logits instead. There is no critic, no target network and no discount factor in this loss.
Inference runs as a loop. Pick a target , observe , predict , execute it, receive , then decay the request:
Append the new tokens and repeat inside a context window of recent steps, often 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 , and .
Returns to go, computed backward:
Equivalently . The total return is .
At step the context holds five tokens: . The query at attends to those five and outputs .
Suppose the dataset action is and the head predicts . With action width :
During live rollout you prompt , execute, receive and update to . The agent now owes itself exactly 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.0The 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 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 to checkpoint and another shows to goal , but no log shows to . Value methods propagate reward backward across the shared state 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 triplets.
- Return to go is the future reward sum from 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 .
- 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.