Exemple #1
0
 def __init__(
         self,
         optimizer=None,
         optimizer_args=None,
         step_size=0.01,
         use_maml=True,
      
         **kwargs):
     assert optimizer is not None  # only for use with MAML TRPO
     if optimizer is None:
         if optimizer_args is None:
             optimizer_args = dict()
         optimizer = PenaltyLbfgsOptimizer(**optimizer_args)
     if not use_maml:
         default_args = dict(
             batch_size=None,
             max_epochs=1,
         
         )
         optimizer = FirstOrderOptimizer(**default_args)
     self.optimizer = optimizer
     self.step_size = step_size
     self.use_maml = use_maml
     self.kl_constrain_step = -1  # needs to be 0 or -1 (original pol params, or new pol params)
    
     super(MAMLNPO, self).__init__(**kwargs)
 def __init__(self,
              optimizer=None,
              optimizer_args=None,
              step_size=0.01,
              **kwargs):
     if optimizer is None:
         if optimizer_args is None:
             optimizer_args = dict()
         optimizer = PenaltyLbfgsOptimizer(**optimizer_args)
     self.optimizer = optimizer
     self.step_size = step_size
     super(ModelNPO, self).__init__(**kwargs)
Exemple #3
0
 def __init__(self,
              optimizer=None,
              optimizer_args=None,
              step_size=0.01,
              entropy_weight=0.0,
              **kwargs):
     if optimizer is None:
         if optimizer_args is None:
             optimizer_args = dict()
         optimizer = PenaltyLbfgsOptimizer(**optimizer_args)
     self.optimizer = optimizer
     self.step_size = step_size
     self.pol_ent_wt = entropy_weight
     super(NPO, self).__init__(**kwargs)
Exemple #4
0
 def __init__(self,
              optimizer=None,
              optimizer_args=None,
              step_size=0.01,
              sample_backups=0,
              kl_sample_backups=0,
              **kwargs):
     if optimizer is None:
         if optimizer_args is None:
             optimizer_args = dict()
         optimizer = PenaltyLbfgsOptimizer(**optimizer_args)
     self.optimizer = optimizer
     self.step_size = step_size
     self.sample_backups = sample_backups
     self.kl_sample_backups = kl_sample_backups
     super(NPO, self).__init__(**kwargs)
Exemple #5
0
    def __init__(self,
                 env,
                 policy,
                 baseline,
                 optimizer=None,
                 optimizer_args=None,
                 step_size=0.01,
                 transfer=True,
                 record_rewards=True,
                 rewards=None,
                 **kwargs):
        if optimizer is None:
            if optimizer_args is None:
                optimizer_args = dict()
            optimizer = PenaltyLbfgsOptimizer(name='PenaltyLbfgsOptimizer')
        self.optimizer = optimizer
        self.step_size = step_size

        self.transfer = transfer
        self.record_rewards = record_rewards
        if self.record_rewards:
            if rewards is None:  #create empty dict
                self.rewards = {}
                self.rewards['average_discounted_return'] = []
                self.rewards['AverageReturn'] = []
                self.rewards['StdReturn'] = []
                self.rewards['MaxReturn'] = []
                self.rewards['MinReturn'] = []
            else:
                self.rewards = rewards
        super(NPO_t, self).__init__(env=env,
                                    policy=policy,
                                    baseline=baseline,
                                    sampler_cls=QMDPSampler,
                                    sampler_args=dict(),
                                    **kwargs)
    def __init__(
            self,
            name,
            input_shape,
            output_dim,
            # observation_space,
            mean_network=None,
            hidden_sizes=(32, 32),
            hidden_nonlinearity=tf.nn.tanh,
            optimizer=None,
            use_trust_region=True,
            step_size=0.01,
            learn_std=True,
            init_std=1.0,
            adaptive_std=False,
            std_share_network=False,
            std_hidden_sizes=(32, 32),
            std_nonlinearity=None,
            normalize_inputs=True,
            normalize_outputs=True,
            subsample_factor=1.0
    ):
        """
        :param input_shape: Shape of the input data.
        :param output_dim: Dimension of output.
        :param hidden_sizes: Number of hidden units of each layer of the mean network.
        :param hidden_nonlinearity: Non-linearity used for each layer of the mean network.
        :param optimizer: Optimizer for minimizing the negative log-likelihood.
        :param use_trust_region: Whether to use trust region constraint.
        :param step_size: KL divergence constraint for each iteration
        :param learn_std: Whether to learn the standard deviations. Only effective if adaptive_std is False. If
        adaptive_std is True, this parameter is ignored, and the weights for the std network are always learned.
        :param adaptive_std: Whether to make the std a function of the states.
        :param std_share_network: Whether to use the same network as the mean.
        :param std_hidden_sizes: Number of hidden units of each layer of the std network. Only used if
        `std_share_network` is False. It defaults to the same architecture as the mean.
        :param std_nonlinearity: Non-linearity used for each layer of the std network. Only used if `std_share_network`
        is False. It defaults to the same non-linearity as the mean.
        """
        Serializable.quick_init(self, locals())

        with tf.variable_scope(name):

            if optimizer is None:
                if use_trust_region:
                    optimizer = PenaltyLbfgsOptimizer("optimizer")
                else:
                    optimizer = LbfgsOptimizer("optimizer")

            self._optimizer = optimizer
            self._subsample_factor = subsample_factor

            if mean_network is None:
                mean_network = MLP(
                    name="mean_network",
                    input_shape=input_shape,
                    output_dim=output_dim,
                    hidden_sizes=hidden_sizes,
                    hidden_nonlinearity=hidden_nonlinearity,
                    output_nonlinearity=None,
                )

            l_mean = mean_network.output_layer

            if adaptive_std:
                l_log_std = MLP(
                    name="log_std_network",
                    input_shape=input_shape,
                    input_var=mean_network.input_layer.input_var,
                    output_dim=output_dim,
                    hidden_sizes=std_hidden_sizes,
                    hidden_nonlinearity=std_nonlinearity,
                    output_nonlinearity=None,
                ).output_layer
            else:
                l_log_std = L.ParamLayer(
                    mean_network.input_layer,
                    num_units=output_dim,
                    param=tf.constant_initializer(np.log(init_std)),
                    name="output_log_std",
                    trainable=learn_std,
                )

            LayersPowered.__init__(self, [l_mean, l_log_std])

            xs_var = mean_network.input_layer.input_var
            ys_var = tf.placeholder(dtype=tf.float32, name="ys", shape=(None, output_dim))
            old_means_var = tf.placeholder(dtype=tf.float32, name="ys", shape=(None, output_dim))
            old_log_stds_var = tf.placeholder(dtype=tf.float32, name="old_log_stds", shape=(None, output_dim))

            x_mean_var = tf.Variable(
                np.zeros((1,) + input_shape, dtype=np.float32),
                name="x_mean",
            )
            x_std_var = tf.Variable(
                np.ones((1,) + input_shape, dtype=np.float32),
                name="x_std",
            )
            y_mean_var = tf.Variable(
                np.zeros((1, output_dim), dtype=np.float32),
                name="y_mean",
            )
            y_std_var = tf.Variable(
                np.ones((1, output_dim), dtype=np.float32),
                name="y_std",
            )

            self.x_mean_var = x_mean_var
            self.x_std_var = x_std_var
            self.y_mean_var = y_mean_var
            self.y_std_var = y_std_var
            # self.observation_space = observation_space

            normalized_xs_var = (xs_var - x_mean_var) / x_std_var
            normalized_ys_var = (ys_var - y_mean_var) / y_std_var

            normalized_means_var = L.get_output(l_mean, {mean_network.input_layer: normalized_xs_var})
            normalized_log_stds_var = L.get_output(l_log_std, {mean_network.input_layer: normalized_xs_var})

            means_var = normalized_means_var * y_std_var + y_mean_var
            log_stds_var = normalized_log_stds_var + tf.log(y_std_var)

            normalized_old_means_var = (old_means_var - y_mean_var) / y_std_var
            normalized_old_log_stds_var = old_log_stds_var - tf.log(y_std_var)

            dist = self._dist = DiagonalGaussian(output_dim)

            normalized_dist_info_vars = dict(mean=normalized_means_var, log_std=normalized_log_stds_var)

            mean_kl = tf.reduce_mean(dist.kl_sym(
                dict(mean=normalized_old_means_var, log_std=normalized_old_log_stds_var),
                normalized_dist_info_vars,
            ))

            loss = - tf.reduce_mean(dist.log_likelihood_sym(normalized_ys_var, normalized_dist_info_vars))

            self._f_predict = tensor_utils.compile_function([xs_var], means_var)
            self._f_pdists = tensor_utils.compile_function([xs_var], [means_var, log_stds_var])
            self._l_mean = l_mean
            self._l_log_std = l_log_std

            optimizer_args = dict(
                loss=loss,
                target=self,
                network_outputs=[normalized_means_var, normalized_log_stds_var],
            )

            if use_trust_region:
                optimizer_args["leq_constraint"] = (mean_kl, step_size)
                optimizer_args["inputs"] = [xs_var, ys_var, old_means_var, old_log_stds_var]
            else:
                optimizer_args["inputs"] = [xs_var, ys_var]

            self._optimizer.update_opt(**optimizer_args)

            self._use_trust_region = use_trust_region
            self._name = name

            self._normalize_inputs = normalize_inputs
            self._normalize_outputs = normalize_outputs
            self._mean_network = mean_network
            self._x_mean_var = x_mean_var
            self._x_std_var = x_std_var
            self._y_mean_var = y_mean_var
            self._y_std_var = y_std_var

            self.input_dim = input_shape[0]
            self.output_dim = output_dim
Exemple #7
0
    def __init__(
            self,
            name,
            input_shape,
            output_dim,
            mean_network=None,
            hidden_sizes=(32, 32),
            hidden_nonlinearity=tf.nn.tanh,
            output_nonlinearity=lambda x: x * 0.0 + tf.Variable(
                initial_value=-1.0, dtype=tf.float32),
            # output_nonlinearity=tf.identity,
            optimizer=None,
            use_trust_region=True,
            step_size=0.01,
            learn_std=True,
            init_std=1.0,
            adaptive_std=False,
            std_share_network=False,
            std_hidden_sizes=(32, 32),
            std_nonlinearity=None,
            normalize_inputs=True,
            normalize_outputs=True,
            subsample_factor=1.0):
        """
        :param input_shape: Shape of the input data.
        :param output_dim: Dimension of output.
        :param hidden_sizes: Number of hidden units of each layer of the mean network.
        :param hidden_nonlinearity: Non-linearity used for each layer of the mean network.
        :param optimizer: Optimizer for minimizing the negative log-likelihood.
        :param use_trust_region: Whether to use trust region constraint.
        :param step_size: KL divergence constraint for each iteration
        :param learn_std: Whether to learn the standard deviations. Only effective if adaptive_std is False. If
        adaptive_std is True, this parameter is ignored, and the weights for the std network are always learned.
        :param adaptive_std: Whether to make the std a function of the states.
        :param std_share_network: Whether to use the same network as the mean.
        :param std_hidden_sizes: Number of hidden units of each layer of the std network. Only used if
        `std_share_network` is False. It defaults to the same architecture as the mean.
        :param std_nonlinearity: Non-linearity used for each layer of the std network. Only used if `std_share_network`
        is False. It defaults to the same non-linearity as the mean.
        """
        Serializable.quick_init(self, locals())

        with tf.variable_scope(name):

            if optimizer is None:
                if use_trust_region:
                    optimizer = PenaltyLbfgsOptimizer("optimizer")
                else:
                    optimizer = LbfgsOptimizer("optimizer")

            self._optimizer = optimizer
            self._subsample_factor = subsample_factor

            if mean_network is None:

                mean_network = create_MLP(
                    name="mean_network",
                    output_dim=1,
                    hidden_sizes=hidden_sizes,
                    hidden_nonlinearity=hidden_nonlinearity,
                    output_nonlinearity=output_nonlinearity,
                )
                forward_mean = lambda x, params, is_train: self.forward_MLP(
                    'mean_network',
                    all_params=params,
                    input_tensor=x,
                    is_training=is_train)[1]
            else:
                raise NotImplementedError('Not supported.')

            #     print("Debug2, mean network is defined here")
            #     mean_network = L.ParamLayer(
            #         incoming=L.InputLayer(
            #             shape=(None,) + input_shape,
            #             name="input_layer"),
            #         num_units=1,
            #         param=tf.constant_initializer(-200.0),
            #         name="mean_network",
            #         trainable=True,
            #     ),
            #     print(mean_network.input_layer)
            # print("debug4", isinstance(L.InputLayer(
            #             shape=(None,) + input_shape,
            #             name="input_layer"), tuple))
            #
            # l_mean = mean_network

            # mean_network = MLP(
            #         name="mean_network",
            #         input_shape=input_shape,
            #         output_dim=output_dim,
            #         hidden_sizes=hidden_sizes,
            #         hidden_nonlinearity=hidden_nonlinearity,
            #         output_nonlinearity=output_nonlinearity,
            #     )
            #
            # l_mean = mean_network.output_layer

            if adaptive_std:
                # l_log_std = MLP(
                #     name="log_std_network",
                #     input_shape=input_shape,
                #     input_var=mean_network.input_layer.input_var,
                #     output_dim=output_dim,
                #     hidden_sizes=std_hidden_sizes,
                #     hidden_nonlinearity=std_nonlinearity,
                #     output_nonlinearity=None,
                # ).output_layer
                raise NotImplementedError('Not supported.')
            else:
                # l_log_std = L.ParamLayer(
                #     mean_network.input_layer,
                #     num_units=output_dim,
                #     param=tf.constant_initializer(np.log(init_std)),
                #     name="output_log_std",
                #     trainable=learn_std,
                # )
                self.all_params['std_param'] = make_param_layer(
                    num_units=1,
                    param=tf.constant_initializer(init_std),
                    name="output_std_param",
                    trainable=learn_std,
                )
                forward_std = lambda x, params: forward_param_layer(
                    x, params['std_param'])
            self.all_param_vals = None

            LayersPowered.__init__(self, [l_mean, l_log_std])

            xs_var = mean_network.input_layer.input_var
            ys_var = tf.placeholder(dtype=tf.float32,
                                    name="ys",
                                    shape=(None, output_dim))
            old_means_var = tf.placeholder(dtype=tf.float32,
                                           name="ys",
                                           shape=(None, output_dim))
            old_log_stds_var = tf.placeholder(dtype=tf.float32,
                                              name="old_log_stds",
                                              shape=(None, output_dim))

            x_mean_var = tf.Variable(
                np.zeros((1, ) + input_shape, dtype=np.float32),
                name="x_mean",
            )
            x_std_var = tf.Variable(
                np.ones((1, ) + input_shape, dtype=np.float32),
                name="x_std",
            )
            y_mean_var = tf.Variable(
                np.zeros((1, output_dim), dtype=np.float32),
                name="y_mean",
            )
            y_std_var = tf.Variable(
                np.ones((1, output_dim), dtype=np.float32),
                name="y_std",
            )

            normalized_xs_var = (xs_var - x_mean_var) / x_std_var
            normalized_ys_var = (ys_var - y_mean_var) / y_std_var

            normalized_means_var = L.get_output(
                l_mean, {mean_network.input_layer: normalized_xs_var})
            normalized_log_stds_var = L.get_output(
                l_log_std, {mean_network.input_layer: normalized_xs_var})

            means_var = normalized_means_var * y_std_var + y_mean_var
            log_stds_var = normalized_log_stds_var + tf.log(y_std_var)

            normalized_old_means_var = (old_means_var - y_mean_var) / y_std_var
            normalized_old_log_stds_var = old_log_stds_var - tf.log(y_std_var)

            ## code added for symbolic prediction, used in constructing the meta-learning objective
            def normalized_means_var_sym(xs, params):
                inputs = OrderedDict({mean_network.input_layer: xs})
                inputs.update(params)
                return L.get_output(layer_or_layers=l_mean, inputs=inputs)

            # normalized_means_var_sym = lambda xs, params: L.get_output(layer_or_layers=l_mean, inputs=OrderedDict({mean_network.input_layer:xs}.)  #mean_network.input_layer: (xs-x_mean_var)/x_std_var,
            # normalized_log_stds_var_sym = L.get_output(l_log_std, {mean_network.input_layer: normalized_xs_var})
            means_var_sym = lambda xs, params: normalized_means_var_sym(
                xs=xs, params=params) * y_std_var + y_mean_var
            # log_stds_var = normalized_log_stds_var + tf.log(y_std_var)

            dist = self._dist = DiagonalGaussian(output_dim)

            normalized_dist_info_vars = dict(mean=normalized_means_var,
                                             log_std=normalized_log_stds_var)

            mean_kl = tf.reduce_mean(
                dist.kl_sym(
                    dict(mean=normalized_old_means_var,
                         log_std=normalized_old_log_stds_var),
                    normalized_dist_info_vars,
                ))

            # loss = - tf.reduce_mean(dist.log_likelihood_sym(normalized_ys_var, normalized_dist_info_vars))
            loss = tf.nn.l2_loss(normalized_ys_var - normalized_means_var
                                 ) + tf.nn.l2_loss(normalized_log_stds_var)
            self._f_predict = tensor_utils.compile_function([xs_var],
                                                            means_var)
            self._f_pdists = tensor_utils.compile_function(
                [xs_var], [means_var, log_stds_var])
            self._l_mean = l_mean
            self._l_log_std = l_log_std

            self._f_predict_sym = means_var_sym
            self.loss_sym = loss
            optimizer_args = dict(
                loss=loss,
                target=self,
                network_outputs=[
                    normalized_means_var, normalized_log_stds_var
                ],
            )

            if use_trust_region:
                optimizer_args["leq_constraint"] = (mean_kl, step_size)
                optimizer_args["inputs"] = [
                    xs_var, ys_var, old_means_var, old_log_stds_var
                ]
            else:
                optimizer_args["inputs"] = [xs_var, ys_var]

            self._optimizer.update_opt(**optimizer_args)

            self._use_trust_region = use_trust_region
            self._name = name

            self._normalize_inputs = normalize_inputs
            self._normalize_outputs = normalize_outputs
            self._mean_network = mean_network
            self._x_mean_var = x_mean_var
            self._x_std_var = x_std_var
            self._y_mean_var = y_mean_var
            self._y_std_var = y_std_var
Exemple #8
0
    def init_experts_opt(self):

        ###############################
        #
        # Variable Definitions
        #
        ###############################

        all_task_dist_info_vars = []
        all_obs_vars = []

        for i, policy in enumerate(self.local_policies):

            task_obs_var = self.env_partitions[
                i].observation_space.new_tensor_variable('obs%d' % i,
                                                         extra_dims=1)
            task_dist_info_vars = []

            for j, other_policy in enumerate(self.local_policies):

                state_info_vars = dict()  # Not handling recurrent policies
                dist_info_vars = other_policy.dist_info_sym(
                    task_obs_var, state_info_vars)
                task_dist_info_vars.append(dist_info_vars)

            all_obs_vars.append(task_obs_var)
            all_task_dist_info_vars.append(task_dist_info_vars)

        obs_var = self.env.observation_space.new_tensor_variable('obs',
                                                                 extra_dims=1)
        action_var = self.env.action_space.new_tensor_variable('action',
                                                               extra_dims=1)
        advantage_var = tensor_utils.new_tensor('advantage',
                                                ndim=1,
                                                dtype=tf.float32)

        old_dist_info_vars = {
            k: tf.placeholder(tf.float32,
                              shape=[None] + list(shape),
                              name='old_%s' % k)
            for k, shape in self.policy.distribution.dist_info_specs
        }

        old_dist_info_vars_list = [
            old_dist_info_vars[k]
            for k in self.policy.distribution.dist_info_keys
        ]

        central_obs_vars = [elem[1] for elem in self.central_policy_dist_infos]

        input_list = [
            obs_var, action_var, advantage_var
        ] + old_dist_info_vars_list + all_obs_vars + central_obs_vars

        ###############################
        #
        # Local Policy Optimization
        #
        ###############################

        self.optimizers = []
        self.metrics = []

        for n, policy in enumerate(self.local_policies):

            state_info_vars = dict()
            dist_info_vars = policy.dist_info_sym(obs_var, state_info_vars)
            dist = policy.distribution

            kl = dist.kl_sym(old_dist_info_vars, dist_info_vars)
            lr = dist.likelihood_ratio_sym(action_var, old_dist_info_vars,
                                           dist_info_vars)
            surr_loss = -tf.reduce_mean(lr * advantage_var)

            if self.constrain_together:
                additional_loss = Metrics.kl_on_others(
                    n, dist, all_task_dist_info_vars)

            elif self.constrain_against_central:
                additional_loss = Metrics.kl_on_central(
                    dist, dist_info_vars, self.central_policy_dist_infos[n][0])

            else:
                additional_loss = tf.constant(0.0)

            local_loss = surr_loss + self.penalty * additional_loss

            kl_metric = tensor_utils.compile_function(inputs=input_list,
                                                      outputs=additional_loss,
                                                      log_name="KLPenalty%d" %
                                                      n)
            self.metrics.append(kl_metric)

            mean_kl_constraint = tf.reduce_mean(kl)

            optimizer = PenaltyLbfgsOptimizer(name='expertOptimizer_' + str(n))
            optimizer.update_opt(
                loss=local_loss,
                target=policy,
                leq_constraint=(mean_kl_constraint, self.step_size),
                inputs=input_list,
                constraint_name="mean_kl_%d" % n,
            )
            self.optimizers.append(optimizer)

        return dict()