Decision Transformer
Last updated
Last updated
The Decision Transformer model was proposed in by Lili Chen, Kevin Lu, Aravind Rajeswaran, Kimin Lee, Aditya Grover, Michael Laskin, Pieter Abbeel, Aravind Srinivas, Igor Mordatch.
The abstract from the paper is the following:
We introduce a framework that abstracts Reinforcement Learning (RL) as a sequence modeling problem. This allows us to draw upon the simplicity and scalability of the Transformer architecture, and associated advances in language modeling such as GPT-x and BERT. In particular, we present Decision Transformer, an architecture that casts the problem of RL as conditional sequence modeling. Unlike prior approaches to RL that fit value functions or compute policy gradients, Decision Transformer simply outputs the optimal actions by leveraging a causally masked Transformer. By conditioning an autoregressive model on the desired return (reward), past states, and actions, our Decision Transformer model can generate future actions that achieve the desired return. Despite its simplicity, Decision Transformer matches or exceeds the performance of state-of-the-art model-free offline RL baselines on Atari, OpenAI Gym, and Key-to-Door tasks.
Tips:
This version of the model is for tasks where the state is a vector, image-based states will come soon.
This model was contributed by . The original code can be found .
( state_dim = 17act_dim = 4hidden_size = 128max_ep_len = 4096action_tanh = Truevocab_size = 1n_positions = 1024n_layer = 3n_head = 1n_inner = Noneactivation_function = 'relu'resid_pdrop = 0.1embd_pdrop = 0.1attn_pdrop = 0.1layer_norm_epsilon = 1e-05initializer_range = 0.02scale_attn_weights = Trueuse_cache = Truebos_token_id = 50256eos_token_id = 50256scale_attn_by_inverse_layer_idx = Falsereorder_and_upcast_attn = False**kwargs )
Parameters
state_dim (int
, optional, defaults to 17) β The state size for the RL environment
act_dim (int
, optional, defaults to 4) β The size of the output action space
hidden_size (int
, optional, defaults to 128) β The size of the hidden layers
max_ep_len (int
, optional, defaults to 4096) β The maximum length of an episode in the environment
action_tanh (bool
, optional, defaults to True) β Whether to use a tanh activation on action prediction
vocab_size (int
, optional, defaults to 50257) β Vocabulary size of the GPT-2 model. Defines the number of different tokens that can be represented by the inputs_ids
passed when calling .
n_positions (int
, optional, defaults to 1024) β The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048).
n_layer (int
, optional, defaults to 3) β Number of hidden layers in the Transformer encoder.
n_head (int
, optional, defaults to 1) β Number of attention heads for each attention layer in the Transformer encoder.
n_inner (int
, optional) β Dimensionality of the inner feed-forward layers. If unset, will default to 4 times n_embd
.
activation_function (str
, optional, defaults to "gelu"
) β Activation function, to be selected in the list ["relu", "silu", "gelu", "tanh", "gelu_new"]
.
resid_pdrop (float
, optional, defaults to 0.1) β The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
embd_pdrop (int
, optional, defaults to 0.1) β The dropout ratio for the embeddings.
attn_pdrop (float
, optional, defaults to 0.1) β The dropout ratio for the attention.
layer_norm_epsilon (float
, optional, defaults to 1e-5) β The epsilon to use in the layer normalization layers.
initializer_range (float
, optional, defaults to 0.02) β The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
scale_attn_weights (bool
, optional, defaults to True
) β Scale attention weights by dividing by sqrt(hidden_size)..
use_cache (bool
, optional, defaults to True
) β Whether or not the model should return the last key/values attentions (not used by all models).
scale_attn_by_inverse_layer_idx (bool
, optional, defaults to False
) β Whether to additionally scale attention weights by 1 / layer_idx + 1
.
reorder_and_upcast_attn (bool
, optional, defaults to False
) β Whether to scale keys (K) prior to computing attention (dot-product) and upcast attention dot-product/softmax to float() when training with mixed precision.
Example:
Copied
( config )
forward
( input_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.Tensor]]] = Noneattention_mask: typing.Optional[torch.FloatTensor] = Nonetoken_type_ids: typing.Optional[torch.LongTensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonehead_mask: typing.Optional[torch.FloatTensor] = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Noneencoder_hidden_states: typing.Optional[torch.Tensor] = Noneencoder_attention_mask: typing.Optional[torch.FloatTensor] = Noneuse_cache: typing.Optional[bool] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None )
( config )
Parameters
forward
( states: typing.Optional[torch.FloatTensor] = Noneactions: typing.Optional[torch.FloatTensor] = Nonerewards: typing.Optional[torch.FloatTensor] = Nonereturns_to_go: typing.Optional[torch.FloatTensor] = Nonetimesteps: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.FloatTensor] = Noneoutput_hidden_states: typing.Optional[bool] = Noneoutput_attentions: typing.Optional[bool] = Nonereturn_dict: typing.Optional[bool] = None ) β transformers.models.decision_transformer.modeling_decision_transformer.DecisionTransformerOutput
or tuple(torch.FloatTensor)
Parameters
states (torch.FloatTensor
of shape (batch_size, episode_length, state_dim)
) β The states for each step in the trajectory
actions (torch.FloatTensor
of shape (batch_size, episode_length, act_dim)
) β The actions taken by the βexpertβ policy for the current state, these are masked for auto regressive prediction
rewards (torch.FloatTensor
of shape (batch_size, episode_length, 1)
) β The rewards for each state, action
returns_to_go (torch.FloatTensor
of shape (batch_size, episode_length, 1)
) β The returns for each state in the trajectory
timesteps (torch.LongTensor
of shape (batch_size, episode_length)
) β The timestep for each step in the trajectory
attention_mask (torch.FloatTensor
of shape (batch_size, episode_length)
) β Masking, used to mask the actions when performing autoregressive prediction
Returns
transformers.models.decision_transformer.modeling_decision_transformer.DecisionTransformerOutput
or tuple(torch.FloatTensor)
last_hidden_state (torch.FloatTensor
of shape (batch_size, sequence_length, hidden_size)
) β Sequence of hidden-states at the output of the last layer of the model.
state_preds (torch.FloatTensor
of shape (batch_size, sequence_length, state_dim)
) β Environment state predictions
action_preds (torch.FloatTensor
of shape (batch_size, sequence_length, action_dim)
) β Model action predictions
return_preds (torch.FloatTensor
of shape (batch_size, sequence_length, 1)
) β Predicted returns for each state
hidden_states (tuple(torch.FloatTensor)
, optional, returned when output_hidden_states=True
is passed or when config.output_hidden_states=True
) β Tuple of torch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size)
.
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (tuple(torch.FloatTensor)
, optional, returned when output_attentions=True
is passed or when config.output_attentions=True
) β Tuple of torch.FloatTensor
(one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length)
.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
Examples:
Copied
This is the configuration class to store the configuration of a . It is used to instantiate a Decision Transformer model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the standard DecisionTransformer architecture. Many of the config options are used to instatiate the GPT2 model that is used as part of the architecture.
Configuration objects inherit from and can be used to control the model outputs. Read the documentation from for more information.
config () β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the method to load the model weights.
The Decision Transformer Model This model is a PyTorch sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
The model builds upon the GPT2 architecture to perform autoregressive prediction of actions in an offline RL setting. Refer to the paper for more details:
A transformers.models.decision_transformer.modeling_decision_transformer.DecisionTransformerOutput
or a tuple of torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various elements depending on the configuration () and inputs.
The forward method, overrides the __call__
special method.