ray icon indicating copy to clipboard operation
ray copied to clipboard

[rllib] Example of LSTM model with variable length action space

Open josjo80 opened this issue 7 years ago • 4 comments

I'm playing with SMAC and would like to add an LSTM to the PPO policy network. However, this is a case where the environment has variable length action space, so I'm looking for an example or any advise on how to construct the network. It appears to me that the network has to be custom since the RLlib model default parameters do not include variable action space. Below is the initial custom model that I need to change. Thanks! SMAC: https://github.com/oxwhirl/smac

from __future__ import division
from __future__ import print_function

import tensorflow as tf
import tensorflow.contrib.slim as slim

from ray.rllib.models import Model
from ray.rllib.models.misc import normc_initializer


class MaskedActionsModel(Model):
    """Custom RLlib model that emits -inf logits for invalid actions.
    
    This is used to handle the variable-length StarCraft action space.
    """

    def _build_layers_v2(self, input_dict, num_outputs, options):
        action_mask = input_dict["obs"]["action_mask"]
        if num_outputs != action_mask.shape[1].value:
            raise ValueError(
                "This model assumes num outputs is equal to max avail actions",
                num_outputs, action_mask)

        # Standard fully connected network
        last_layer = input_dict["obs"]["obs"]
        hiddens = options.get("fcnet_hiddens")
        for i, size in enumerate(hiddens):
            label = "fc{}".format(i)
            last_layer = slim.fully_connected(
                last_layer,
                size,
                weights_initializer=normc_initializer(1.0),
                activation_fn=tf.nn.tanh,
                scope=label)
        action_logits = slim.fully_connected(
            last_layer,
            num_outputs,
            weights_initializer=normc_initializer(0.01),
            activation_fn=None,
            scope="fc_out")

        # Mask out invalid actions (use tf.float32.min for stability)
        inf_mask = tf.maximum(tf.log(action_mask), tf.float32.min)
        masked_logits = inf_mask + action_logits

        return masked_logits, last_layer

josjo80 avatar Jul 09 '19 15:07 josjo80

The below policy model works, if anyone is interested. This starts to look more like the OpenAI Dota Five architecture. https://s3-us-west-2.amazonaws.com/openai-assets/dota_benchmark_results/network_diagram_08_06_2018.pdf

from __future__ import division
from __future__ import print_function

import numpy as np

import tensorflow as tf
import tensorflow.contrib.slim as slim

from ray.rllib.models import Model
from ray.rllib.models.misc import normc_initializer, linear
from ray.rllib.utils.annotations import override, DeveloperAPI, PublicAPI


class MaskedActionsLSTM(Model):
    """Custom RLlib model that emits -inf logits for invalid actions.

    This is used to handle the variable-length StarCraft action space.
    """
    @override(Model)
    def _build_layers_v2(self, input_dict, num_outputs, options):
        action_mask = input_dict["obs"]["action_mask"]
        if num_outputs != action_mask.shape[1].value:
            raise ValueError(
                "This model assumes num outputs is equal to max avail actions",
                num_outputs, action_mask)

        # Standard fully connected network
        last_layer = input_dict["obs"]["obs"]
        hiddens = options.get("fcnet_hiddens")
        for i, size in enumerate(hiddens):
            label = "fc{}".format(i)
            last_layer = slim.fully_connected(
                last_layer,
                size,
                weights_initializer=normc_initializer(1.0),
                activation_fn=tf.nn.tanh,
                scope=label)

        # Add LSTM output
        cell_size = options.get("lstm_cell_size")
        last_layer = self.add_time_dimension(last_layer, self.seq_lens)
        # Setup the LSTM cell
        lstm = tf.nn.rnn_cell.LSTMCell(cell_size, state_is_tuple=True)
        self.state_init = [
            np.zeros(lstm.state_size.c, np.float32),
            np.zeros(lstm.state_size.h, np.float32)
        ]

        # Setup LSTM inputs
        if self.state_in:
            c_in, h_in = self.state_in
        else:
            c_in = tf.placeholder(
                tf.float32, [None, lstm.state_size.c], name="c")
            h_in = tf.placeholder(
                tf.float32, [None, lstm.state_size.h], name="h")
            self.state_in = [c_in, h_in]

        # Setup LSTM outputs
        state_in = tf.nn.rnn_cell.LSTMStateTuple(c_in, h_in)
        lstm_out, lstm_state = tf.nn.dynamic_rnn(
            lstm,
            last_layer,
            initial_state=state_in,
            sequence_length=self.seq_lens,
            time_major=False,
            dtype=tf.float32)

        self.state_out = list(lstm_state)

        # Compute outputs
        last_layer = tf.reshape(lstm_out, [-1, cell_size])
        action_logits = linear(last_layer, num_outputs, "action",
                        normc_initializer(0.01))

        # Mask out invalid actions (use tf.float32.min for stability)
        inf_mask = tf.maximum(tf.log(action_mask), tf.float32.min)
        masked_logits = inf_mask + action_logits
        return masked_logits, last_layer



    def add_time_dimension(self, padded_inputs, seq_lens):
        """Adds a time dimension to padded inputs.
        Arguments:
            padded_inputs (Tensor): a padded batch of sequences. That is,
            for seq_lens=[1, 2, 2], then inputs=[A, *, B, B, C, C], where
            A, B, C are sequence elements and * denotes padding.
            seq_lens (Tensor): the sequence lengths within the input batch,
            suitable for passing to tf.nn.dynamic_rnn().
        Returns:
            Reshaped tensor of shape [NUM_SEQUENCES, MAX_SEQ_LEN, ...].
        """

        # Sequence lengths have to be specified for LSTM batch inputs. The
        # input batch must be padded to the max seq length given here. That is,
        # batch_size == len(seq_lens) * max(seq_lens)
        padded_batch_size = tf.shape(padded_inputs)[0]
        max_seq_len = padded_batch_size // tf.shape(seq_lens)[0]

        # Dynamically reshape the padded batch to introduce a time dimension.
        new_batch_size = padded_batch_size // max_seq_len
        new_shape = ([new_batch_size, max_seq_len] +
                     padded_inputs.get_shape().as_list()[1:])
        return tf.reshape(padded_inputs, new_shape)


    @DeveloperAPI
    def chop_into_sequences(episode_ids,
                    unroll_ids,
                    agent_indices,
                    feature_columns,
                    state_columns,
                    max_seq_len,
                    dynamic_max=True,
                    shuffle=False,
                    _extra_padding=0):
        """Truncate and pad experiences into fixed-length sequences.
        Arguments:
            episode_ids (list): List of episode ids for each step.
            unroll_ids (list): List of identifiers for the sample batch. This is
                used to make sure sequences are cut between sample batches.
            agent_indices (list): List of agent ids for each step. Note that this
                has to be combined with episode_ids for uniqueness.
            feature_columns (list): List of arrays containing features.
            state_columns (list): List of arrays containing LSTM state values.
            max_seq_len (int): Max length of sequences before truncation.
            dynamic_max (bool): Whether to dynamically shrink the max seq len.
                For example, if max len is 20 and the actual max seq len in the
                data is 7, it will be shrunk to 7.
            shuffle (bool): Whether to shuffle the sequence outputs.
            _extra_padding (int): Add extra padding to the end of sequences.
        Returns:
            f_pad (list): Padded feature columns. These will be of shape
                [NUM_SEQUENCES * MAX_SEQ_LEN, ...].
            s_init (list): Initial states for each sequence, of shape
                [NUM_SEQUENCES, ...].
            seq_lens (list): List of sequence lengths, of shape [NUM_SEQUENCES].
        Examples:
            >>> f_pad, s_init, seq_lens = chop_into_sequences(
                episode_ids=[1, 1, 5, 5, 5, 5],
                unroll_ids=[4, 4, 4, 4, 4, 4],
                agent_indices=[0, 0, 0, 0, 0, 0],
                feature_columns=[[4, 4, 8, 8, 8, 8],
                                 [1, 1, 0, 1, 1, 0]],
                state_columns=[[4, 5, 4, 5, 5, 5]],
                max_seq_len=3)
            >>> print(f_pad)
            [[4, 4, 0, 8, 8, 8, 8, 0, 0],
             [1, 1, 0, 0, 1, 1, 0, 0, 0]]
            >>> print(s_init)
            [[4, 4, 5]]
            >>> print(seq_lens)
            [2, 3, 1]
        """

        prev_id = None
        seq_lens = []
        seq_len = 0
        unique_ids = np.add(
            np.add(episode_ids, agent_indices),
            np.array(unroll_ids) << 32)
        for uid in unique_ids:
            if (prev_id is not None and uid != prev_id) or \
                    seq_len >= max_seq_len:
                seq_lens.append(seq_len)
                seq_len = 0
            seq_len += 1
            prev_id = uid
        if seq_len:
            seq_lens.append(seq_len)
        assert sum(seq_lens) == len(unique_ids)
        seq_lens = np.array(seq_lens)

        # Dynamically shrink max len as needed to optimize memory usage
        if dynamic_max:
            max_seq_len = max(seq_lens) + _extra_padding

        feature_sequences = []
        for f in feature_columns:
            f = np.array(f)
            f_pad = np.zeros((len(seq_lens) * max_seq_len, ) + np.shape(f)[1:])
            seq_base = 0
            i = 0
            for l in seq_lens:
                for seq_offset in range(l):
                    f_pad[seq_base + seq_offset] = f[i]
                    i += 1
                seq_base += max_seq_len
            assert i == len(unique_ids), f
            feature_sequences.append(f_pad)

        initial_states = []
        for s in state_columns:
            s = np.array(s)
            s_init = []
            i = 0
            for l in seq_lens:
                s_init.append(s[i])
                i += l
            initial_states.append(np.array(s_init))

        if shuffle:
            permutation = np.random.permutation(len(seq_lens))
            for i, f in enumerate(feature_sequences):
                orig_shape = f.shape
                f = np.reshape(f, (len(seq_lens), -1) + f.shape[2:])
                f = f[permutation]
                f = np.reshape(f, orig_shape)
                feature_sequences[i] = f
            for i, s in enumerate(initial_states):
                s = s[permutation]
                initial_states[i] = s
            seq_lens = seq_lens[permutation]

        return feature_sequences, initial_states, seq_lens

josjo80 avatar Jul 09 '19 22:07 josjo80

This is really cool work, thank you for your contributions! :)

nMack429 avatar Mar 16 '20 11:03 nMack429

Hi, I'm a bot from the Ray team :)

To help human contributors to focus on more relevant issues, I will automatically add the stale label to issues that have had no activity for more than 4 months.

If there is no further activity in the 14 days, the issue will be closed!

  • If you'd like to keep the issue open, just leave any comment, and the stale label will be removed!
  • If you'd like to get more attention to the issue, please tag one of Ray's contributors.

You can always ask for help on our discussion forum or Ray's public slack channel.

stale[bot] avatar Nov 13 '20 09:11 stale[bot]

Hi again! The issue will be closed because there has been no more activity in the 14 days since the last message.

Please feel free to reopen or open a new issue if you'd still like it to be addressed.

Again, you can always ask for help on our discussion forum or Ray's public slack channel.

Thanks again for opening the issue!

stale[bot] avatar Nov 27 '20 10:11 stale[bot]