Transformers documentation

Decision Transformer

You are viewing v4.40.2 version. A newer version v4.46.3 is available.
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Decision Transformer

Overview

Decision Transformer モデルは、Decision Transformer: Reinforcement Learning via Sequence Modeling で提案されました。 Lili Chen, Kevin Lu, Aravind Rajeswaran, Kimin Lee, Aditya Grover, Michael Laskin, Pieter Abbeel, Aravind Srinivas, Igor Mordatch.

論文の要約は次のとおりです。

強化学習(RL)をシーケンスモデリング問題として抽象化するフレームワークを紹介します。 これにより、Transformer アーキテクチャのシンプルさとスケーラビリティ、および関連する進歩を活用できるようになります。 GPT-x や BERT などの言語モデリングで。特に、Decision Transformer というアーキテクチャを紹介します。 RL の問題を条件付きシーケンス モデリングとして投げかけます。値関数に適合する以前の RL アプローチとは異なり、 ポリシー勾配を計算すると、Decision Transformer は因果的にマスクされたアルゴリズムを利用して最適なアクションを出力するだけです。 変成器。望ましいリターン (報酬)、過去の状態、アクションに基づいて自己回帰モデルを条件付けすることにより、 Decision Transformer モデルは、望ましいリターンを達成する将来のアクションを生成できます。そのシンプルさにも関わらず、 Decision Transformer は、最先端のモデルフリーのオフライン RL ベースラインのパフォーマンスと同等、またはそれを超えています。 Atari、OpenAI Gym、Key-to-Door タスク

このバージョンのモデルは、状態がベクトルであるタスク用です。

このモデルは、edbeeching によって提供されました。元のコードは ここ にあります。

DecisionTransformerConfig

class transformers.DecisionTransformerConfig

< >

( state_dim = 17 act_dim = 4 hidden_size = 128 max_ep_len = 4096 action_tanh = True vocab_size = 1 n_positions = 1024 n_layer = 3 n_head = 1 n_inner = None activation_function = 'relu' resid_pdrop = 0.1 embd_pdrop = 0.1 attn_pdrop = 0.1 layer_norm_epsilon = 1e-05 initializer_range = 0.02 scale_attn_weights = True use_cache = True bos_token_id = 50256 eos_token_id = 50256 scale_attn_by_inverse_layer_idx = False reorder_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 DecisionTransformerModel.
  • 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.

This is the configuration class to store the configuration of a DecisionTransformerModel. 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 PretrainedConfig and can be used to control the model outputs. Read the documentation from PretrainedConfig for more information.

Example:

>>> from transformers import DecisionTransformerConfig, DecisionTransformerModel

>>> # Initializing a DecisionTransformer configuration
>>> configuration = DecisionTransformerConfig()

>>> # Initializing a model (with random weights) from the configuration
>>> model = DecisionTransformerModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

DecisionTransformerGPT2Model

class transformers.DecisionTransformerGPT2Model

< >

( config )

forward

< >

( input_ids: Optional = None past_key_values: Optional = None attention_mask: Optional = None token_type_ids: Optional = None position_ids: Optional = None head_mask: Optional = None inputs_embeds: Optional = None encoder_hidden_states: Optional = None encoder_attention_mask: Optional = None use_cache: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None )

DecisionTransformerModel

class transformers.DecisionTransformerModel

< >

( config )

Parameters

  • config (~DecisionTransformerConfig) — 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 from_pretrained() method to load the model weights.

The Decision Transformer Model This model is a PyTorch torch.nn.Module 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: https://arxiv.org/abs/2106.01345

forward

< >

( states: Optional = None actions: Optional = None rewards: Optional = None returns_to_go: Optional = None timesteps: Optional = None attention_mask: Optional = None output_hidden_states: Optional = None output_attentions: Optional = None return_dict: Optional = 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)

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 (DecisionTransformerConfig) and inputs.

  • 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.

The DecisionTransformerModel forward method, overrides the __call__ special method.

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:

>>> from transformers import DecisionTransformerModel
>>> import torch

>>> model = DecisionTransformerModel.from_pretrained("edbeeching/decision-transformer-gym-hopper-medium")
>>> # evaluation
>>> model = model.to(device)
>>> model.eval()

>>> env = gym.make("Hopper-v3")
>>> state_dim = env.observation_space.shape[0]
>>> act_dim = env.action_space.shape[0]

>>> state = env.reset()
>>> states = torch.from_numpy(state).reshape(1, 1, state_dim).to(device=device, dtype=torch.float32)
>>> actions = torch.zeros((1, 1, act_dim), device=device, dtype=torch.float32)
>>> rewards = torch.zeros(1, 1, device=device, dtype=torch.float32)
>>> target_return = torch.tensor(TARGET_RETURN, dtype=torch.float32).reshape(1, 1)
>>> timesteps = torch.tensor(0, device=device, dtype=torch.long).reshape(1, 1)
>>> attention_mask = torch.zeros(1, 1, device=device, dtype=torch.float32)

>>> # forward pass
>>> with torch.no_grad():
...     state_preds, action_preds, return_preds = model(
...         states=states,
...         actions=actions,
...         rewards=rewards,
...         returns_to_go=target_return,
...         timesteps=timesteps,
...         attention_mask=attention_mask,
...         return_dict=False,
...     )
< > Update on GitHub