2019-02-22 11:18:51 -08:00
|
|
|
import logging
|
2018-06-28 09:49:08 -07:00
|
|
|
|
2018-07-22 05:09:25 -07:00
|
|
|
import ray
|
2019-03-29 12:44:23 -07:00
|
|
|
from ray.rllib.evaluation.postprocessing import compute_advantages, \
|
|
|
|
Postprocessing
|
2019-05-20 16:46:05 -07:00
|
|
|
from ray.rllib.policy.sample_batch import SampleBatch
|
2019-07-09 03:30:32 +02:00
|
|
|
from ray.rllib.policy.tf_policy import LearningRateSchedule, \
|
2020-01-21 08:06:50 +01:00
|
|
|
EntropyCoeffSchedule
|
2019-05-20 16:46:05 -07:00
|
|
|
from ray.rllib.policy.tf_policy_template import build_tf_policy
|
2020-06-16 08:52:20 +02:00
|
|
|
from ray.rllib.utils.framework import try_import_tf
|
|
|
|
from ray.rllib.utils.tf_ops import explained_variance, make_tf_callable
|
2019-05-10 20:36:18 -07:00
|
|
|
|
2020-06-30 10:13:20 +02:00
|
|
|
tf1, tf, tfv = try_import_tf()
|
2018-06-28 09:49:08 -07:00
|
|
|
|
2019-02-22 11:18:51 -08:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2018-06-28 09:49:08 -07:00
|
|
|
|
2020-01-02 17:42:13 -08:00
|
|
|
class PPOLoss:
|
2018-07-19 15:30:36 -07:00
|
|
|
def __init__(self,
|
2019-08-10 14:05:12 -07:00
|
|
|
dist_class,
|
|
|
|
model,
|
2018-07-19 15:30:36 -07:00
|
|
|
value_targets,
|
|
|
|
advantages,
|
|
|
|
actions,
|
2019-08-10 14:05:12 -07:00
|
|
|
prev_logits,
|
|
|
|
prev_actions_logp,
|
2018-07-19 15:30:36 -07:00
|
|
|
vf_preds,
|
|
|
|
curr_action_dist,
|
|
|
|
value_fn,
|
|
|
|
cur_kl_coeff,
|
2018-10-15 11:02:50 -07:00
|
|
|
valid_mask,
|
2018-07-19 15:30:36 -07:00
|
|
|
entropy_coeff=0,
|
|
|
|
clip_param=0.1,
|
2018-09-23 13:11:17 -07:00
|
|
|
vf_clip_param=0.1,
|
2018-07-19 15:30:36 -07:00
|
|
|
vf_loss_coeff=1.0,
|
2020-01-21 08:06:50 +01:00
|
|
|
use_gae=True):
|
2018-06-28 09:49:08 -07:00
|
|
|
"""Constructs the loss for Proximal Policy Objective.
|
|
|
|
|
|
|
|
Arguments:
|
2019-08-10 14:05:12 -07:00
|
|
|
dist_class: action distribution class for logits.
|
2018-06-28 09:49:08 -07:00
|
|
|
value_targets (Placeholder): Placeholder for target values; used
|
|
|
|
for GAE.
|
|
|
|
actions (Placeholder): Placeholder for actions taken
|
|
|
|
from previous model evaluation.
|
|
|
|
advantages (Placeholder): Placeholder for calculated advantages
|
|
|
|
from previous model evaluation.
|
2019-08-10 14:05:12 -07:00
|
|
|
prev_logits (Placeholder): Placeholder for logits output from
|
|
|
|
previous model evaluation.
|
2020-01-21 08:06:50 +01:00
|
|
|
prev_actions_logp (Placeholder): Placeholder for action prob output
|
|
|
|
from the previous (before update) Model evaluation.
|
2018-06-28 09:49:08 -07:00
|
|
|
vf_preds (Placeholder): Placeholder for value function output
|
2020-01-21 08:06:50 +01:00
|
|
|
from the previous (before update) Model evaluation.
|
2018-06-28 09:49:08 -07:00
|
|
|
curr_action_dist (ActionDistribution): ActionDistribution
|
|
|
|
of the current model.
|
|
|
|
value_fn (Tensor): Current value function output Tensor.
|
|
|
|
cur_kl_coeff (Variable): Variable holding the current PPO KL
|
|
|
|
coefficient.
|
2020-01-21 08:06:50 +01:00
|
|
|
valid_mask (Optional[tf.Tensor]): An optional bool mask of valid
|
|
|
|
input elements (for max-len padded sequences (RNNs)).
|
2018-06-28 09:49:08 -07:00
|
|
|
entropy_coeff (float): Coefficient of the entropy regularizer.
|
|
|
|
clip_param (float): Clip parameter
|
2018-09-23 13:11:17 -07:00
|
|
|
vf_clip_param (float): Clip parameter for the value function
|
2018-06-28 09:49:08 -07:00
|
|
|
vf_loss_coeff (float): Coefficient of the value function loss
|
|
|
|
use_gae (bool): If true, use the Generalized Advantage Estimator.
|
|
|
|
"""
|
2020-01-21 08:06:50 +01:00
|
|
|
if valid_mask is not None:
|
|
|
|
|
|
|
|
def reduce_mean_valid(t):
|
|
|
|
return tf.reduce_mean(tf.boolean_mask(t, valid_mask))
|
|
|
|
|
|
|
|
else:
|
2018-10-15 11:02:50 -07:00
|
|
|
|
2020-01-21 08:06:50 +01:00
|
|
|
def reduce_mean_valid(t):
|
|
|
|
return tf.reduce_mean(t)
|
2018-10-15 11:02:50 -07:00
|
|
|
|
2019-08-10 14:05:12 -07:00
|
|
|
prev_dist = dist_class(prev_logits, model)
|
2018-06-28 09:49:08 -07:00
|
|
|
# Make loss functions.
|
2019-08-10 14:05:12 -07:00
|
|
|
logp_ratio = tf.exp(curr_action_dist.logp(actions) - prev_actions_logp)
|
2018-06-28 09:49:08 -07:00
|
|
|
action_kl = prev_dist.kl(curr_action_dist)
|
2018-10-15 11:02:50 -07:00
|
|
|
self.mean_kl = reduce_mean_valid(action_kl)
|
2018-06-28 09:49:08 -07:00
|
|
|
|
|
|
|
curr_entropy = curr_action_dist.entropy()
|
2018-10-15 11:02:50 -07:00
|
|
|
self.mean_entropy = reduce_mean_valid(curr_entropy)
|
2018-06-28 09:49:08 -07:00
|
|
|
|
|
|
|
surrogate_loss = tf.minimum(
|
|
|
|
advantages * logp_ratio,
|
2018-07-19 15:30:36 -07:00
|
|
|
advantages * tf.clip_by_value(logp_ratio, 1 - clip_param,
|
|
|
|
1 + clip_param))
|
2018-10-15 11:02:50 -07:00
|
|
|
self.mean_policy_loss = reduce_mean_valid(-surrogate_loss)
|
2018-06-28 09:49:08 -07:00
|
|
|
|
|
|
|
if use_gae:
|
2020-06-25 19:01:32 +02:00
|
|
|
vf_loss1 = tf.math.square(value_fn - value_targets)
|
2018-09-23 13:11:17 -07:00
|
|
|
vf_clipped = vf_preds + tf.clip_by_value(
|
|
|
|
value_fn - vf_preds, -vf_clip_param, vf_clip_param)
|
2020-06-25 19:01:32 +02:00
|
|
|
vf_loss2 = tf.math.square(vf_clipped - value_targets)
|
2018-07-12 19:22:46 +02:00
|
|
|
vf_loss = tf.maximum(vf_loss1, vf_loss2)
|
2018-10-15 11:02:50 -07:00
|
|
|
self.mean_vf_loss = reduce_mean_valid(vf_loss)
|
|
|
|
loss = reduce_mean_valid(
|
|
|
|
-surrogate_loss + cur_kl_coeff * action_kl +
|
|
|
|
vf_loss_coeff * vf_loss - entropy_coeff * curr_entropy)
|
2018-06-28 09:49:08 -07:00
|
|
|
else:
|
|
|
|
self.mean_vf_loss = tf.constant(0.0)
|
2018-10-15 11:02:50 -07:00
|
|
|
loss = reduce_mean_valid(-surrogate_loss +
|
|
|
|
cur_kl_coeff * action_kl -
|
|
|
|
entropy_coeff * curr_entropy)
|
2018-06-28 09:49:08 -07:00
|
|
|
self.loss = loss
|
|
|
|
|
|
|
|
|
2019-08-23 02:21:11 -04:00
|
|
|
def ppo_surrogate_loss(policy, model, dist_class, train_batch):
|
|
|
|
logits, state = model.from_batch(train_batch)
|
|
|
|
action_dist = dist_class(logits, model)
|
|
|
|
|
2020-01-21 08:06:50 +01:00
|
|
|
mask = None
|
2019-08-23 02:21:11 -04:00
|
|
|
if state:
|
|
|
|
max_seq_len = tf.reduce_max(train_batch["seq_lens"])
|
|
|
|
mask = tf.sequence_mask(train_batch["seq_lens"], max_seq_len)
|
2019-05-18 00:23:11 -07:00
|
|
|
mask = tf.reshape(mask, [-1])
|
|
|
|
|
|
|
|
policy.loss_obj = PPOLoss(
|
2019-08-23 02:21:11 -04:00
|
|
|
dist_class,
|
|
|
|
model,
|
|
|
|
train_batch[Postprocessing.VALUE_TARGETS],
|
|
|
|
train_batch[Postprocessing.ADVANTAGES],
|
|
|
|
train_batch[SampleBatch.ACTIONS],
|
2020-04-01 09:43:21 +02:00
|
|
|
train_batch[SampleBatch.ACTION_DIST_INPUTS],
|
|
|
|
train_batch[SampleBatch.ACTION_LOGP],
|
2019-08-23 02:21:11 -04:00
|
|
|
train_batch[SampleBatch.VF_PREDS],
|
|
|
|
action_dist,
|
|
|
|
model.value_function(),
|
2019-07-21 12:27:17 -07:00
|
|
|
policy.kl_coeff,
|
2019-05-18 00:23:11 -07:00
|
|
|
mask,
|
2019-07-21 12:27:17 -07:00
|
|
|
entropy_coeff=policy.entropy_coeff,
|
2019-05-18 00:23:11 -07:00
|
|
|
clip_param=policy.config["clip_param"],
|
|
|
|
vf_clip_param=policy.config["vf_clip_param"],
|
|
|
|
vf_loss_coeff=policy.config["vf_loss_coeff"],
|
2019-08-06 18:13:16 +00:00
|
|
|
use_gae=policy.config["use_gae"],
|
2020-01-21 08:06:50 +01:00
|
|
|
)
|
2019-05-18 00:23:11 -07:00
|
|
|
|
|
|
|
return policy.loss_obj.loss
|
|
|
|
|
|
|
|
|
2019-08-23 02:21:11 -04:00
|
|
|
def kl_and_loss_stats(policy, train_batch):
|
2019-07-03 15:59:47 -07:00
|
|
|
return {
|
2019-07-21 12:27:17 -07:00
|
|
|
"cur_kl_coeff": tf.cast(policy.kl_coeff, tf.float64),
|
|
|
|
"cur_lr": tf.cast(policy.cur_lr, tf.float64),
|
2019-05-18 00:23:11 -07:00
|
|
|
"total_loss": policy.loss_obj.loss,
|
|
|
|
"policy_loss": policy.loss_obj.mean_policy_loss,
|
|
|
|
"vf_loss": policy.loss_obj.mean_vf_loss,
|
2019-07-03 15:59:47 -07:00
|
|
|
"vf_explained_var": explained_variance(
|
2019-08-23 02:21:11 -04:00
|
|
|
train_batch[Postprocessing.VALUE_TARGETS],
|
|
|
|
policy.model.value_function()),
|
2019-05-18 00:23:11 -07:00
|
|
|
"kl": policy.loss_obj.mean_kl,
|
|
|
|
"entropy": policy.loss_obj.mean_entropy,
|
2019-07-21 12:27:17 -07:00
|
|
|
"entropy_coeff": tf.cast(policy.entropy_coeff, tf.float64),
|
2019-05-18 00:23:11 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
2020-04-01 09:43:21 +02:00
|
|
|
def vf_preds_fetches(policy):
|
|
|
|
"""Adds value function outputs to experience train_batches."""
|
2019-05-18 00:23:11 -07:00
|
|
|
return {
|
2019-08-23 02:21:11 -04:00
|
|
|
SampleBatch.VF_PREDS: policy.model.value_function(),
|
2019-05-18 00:23:11 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
def postprocess_ppo_gae(policy,
|
|
|
|
sample_batch,
|
|
|
|
other_agent_batches=None,
|
|
|
|
episode=None):
|
2019-03-29 12:44:23 -07:00
|
|
|
"""Adds the policy logits, VF preds, and advantages to the trajectory."""
|
|
|
|
|
2019-05-18 00:23:11 -07:00
|
|
|
completed = sample_batch["dones"][-1]
|
|
|
|
if completed:
|
|
|
|
last_r = 0.0
|
|
|
|
else:
|
|
|
|
next_state = []
|
2019-08-23 02:21:11 -04:00
|
|
|
for i in range(policy.num_state_tensors()):
|
2020-06-30 10:13:20 +02:00
|
|
|
next_state.append(sample_batch["state_out_{}".format(i)][-1])
|
2019-05-18 00:23:11 -07:00
|
|
|
last_r = policy._value(sample_batch[SampleBatch.NEXT_OBS][-1],
|
|
|
|
sample_batch[SampleBatch.ACTIONS][-1],
|
|
|
|
sample_batch[SampleBatch.REWARDS][-1],
|
|
|
|
*next_state)
|
|
|
|
batch = compute_advantages(
|
|
|
|
sample_batch,
|
|
|
|
last_r,
|
|
|
|
policy.config["gamma"],
|
|
|
|
policy.config["lambda"],
|
|
|
|
use_gae=policy.config["use_gae"])
|
|
|
|
return batch
|
|
|
|
|
|
|
|
|
|
|
|
def clip_gradients(policy, optimizer, loss):
|
2019-08-23 02:21:11 -04:00
|
|
|
variables = policy.model.trainable_variables()
|
2019-05-18 00:23:11 -07:00
|
|
|
if policy.config["grad_clip"] is not None:
|
2019-08-23 02:21:11 -04:00
|
|
|
grads_and_vars = optimizer.compute_gradients(loss, variables)
|
|
|
|
grads = [g for (g, v) in grads_and_vars]
|
2019-05-18 00:23:11 -07:00
|
|
|
policy.grads, _ = tf.clip_by_global_norm(grads,
|
|
|
|
policy.config["grad_clip"])
|
2019-08-23 02:21:11 -04:00
|
|
|
clipped_grads = list(zip(policy.grads, variables))
|
2019-05-18 00:23:11 -07:00
|
|
|
return clipped_grads
|
|
|
|
else:
|
2019-08-23 02:21:11 -04:00
|
|
|
return optimizer.compute_gradients(loss, variables)
|
2019-05-18 00:23:11 -07:00
|
|
|
|
|
|
|
|
2020-01-02 17:42:13 -08:00
|
|
|
class KLCoeffMixin:
|
2019-05-18 00:23:11 -07:00
|
|
|
def __init__(self, config):
|
2018-06-28 09:49:08 -07:00
|
|
|
# KL Coefficient
|
2019-05-18 00:23:11 -07:00
|
|
|
self.kl_coeff_val = config["kl_coeff"]
|
|
|
|
self.kl_target = config["kl_target"]
|
2020-06-30 10:13:20 +02:00
|
|
|
self.kl_coeff = tf1.get_variable(
|
2018-06-28 09:49:08 -07:00
|
|
|
initializer=tf.constant_initializer(self.kl_coeff_val),
|
2018-07-19 15:30:36 -07:00
|
|
|
name="kl_coeff",
|
|
|
|
shape=(),
|
|
|
|
trainable=False,
|
|
|
|
dtype=tf.float32)
|
2018-06-28 09:49:08 -07:00
|
|
|
|
2019-05-18 00:23:11 -07:00
|
|
|
def update_kl(self, sampled_kl):
|
|
|
|
if sampled_kl > 2.0 * self.kl_target:
|
|
|
|
self.kl_coeff_val *= 1.5
|
|
|
|
elif sampled_kl < 0.5 * self.kl_target:
|
|
|
|
self.kl_coeff_val *= 0.5
|
2019-06-02 14:14:31 +08:00
|
|
|
self.kl_coeff.load(self.kl_coeff_val, session=self.get_session())
|
2019-05-18 00:23:11 -07:00
|
|
|
return self.kl_coeff_val
|
|
|
|
|
|
|
|
|
2020-01-02 17:42:13 -08:00
|
|
|
class ValueNetworkMixin:
|
2019-05-18 00:23:11 -07:00
|
|
|
def __init__(self, obs_space, action_space, config):
|
|
|
|
if config["use_gae"]:
|
2019-08-23 02:21:11 -04:00
|
|
|
|
|
|
|
@make_tf_callable(self.get_session())
|
|
|
|
def value(ob, prev_action, prev_reward, *state):
|
|
|
|
model_out, _ = self.model({
|
|
|
|
SampleBatch.CUR_OBS: tf.convert_to_tensor([ob]),
|
|
|
|
SampleBatch.PREV_ACTIONS: tf.convert_to_tensor(
|
|
|
|
[prev_action]),
|
|
|
|
SampleBatch.PREV_REWARDS: tf.convert_to_tensor(
|
|
|
|
[prev_reward]),
|
2020-04-29 12:12:59 +02:00
|
|
|
"is_training": tf.convert_to_tensor([False]),
|
2019-08-23 02:21:11 -04:00
|
|
|
}, [tf.convert_to_tensor([s]) for s in state],
|
|
|
|
tf.convert_to_tensor([1]))
|
|
|
|
return self.model.value_function()[0]
|
|
|
|
|
2018-06-28 09:49:08 -07:00
|
|
|
else:
|
2019-08-23 02:21:11 -04:00
|
|
|
|
|
|
|
@make_tf_callable(self.get_session())
|
|
|
|
def value(ob, prev_action, prev_reward, *state):
|
|
|
|
return tf.constant(0.0)
|
|
|
|
|
|
|
|
self._value = value
|
2019-05-18 00:23:11 -07:00
|
|
|
|
|
|
|
|
2019-07-07 15:06:41 -07:00
|
|
|
def setup_config(policy, obs_space, action_space, config):
|
|
|
|
# auto set the model option for layer sharing
|
|
|
|
config["model"]["vf_share_layers"] = config["vf_share_layers"]
|
|
|
|
|
|
|
|
|
2019-05-18 00:23:11 -07:00
|
|
|
def setup_mixins(policy, obs_space, action_space, config):
|
|
|
|
ValueNetworkMixin.__init__(policy, obs_space, action_space, config)
|
|
|
|
KLCoeffMixin.__init__(policy, config)
|
2019-07-09 03:30:32 +02:00
|
|
|
EntropyCoeffSchedule.__init__(policy, config["entropy_coeff"],
|
|
|
|
config["entropy_coeff_schedule"])
|
2019-05-18 00:23:11 -07:00
|
|
|
LearningRateSchedule.__init__(policy, config["lr"], config["lr_schedule"])
|
|
|
|
|
|
|
|
|
|
|
|
PPOTFPolicy = build_tf_policy(
|
|
|
|
name="PPOTFPolicy",
|
|
|
|
get_default_config=lambda: ray.rllib.agents.ppo.ppo.DEFAULT_CONFIG,
|
|
|
|
loss_fn=ppo_surrogate_loss,
|
|
|
|
stats_fn=kl_and_loss_stats,
|
2020-04-01 09:43:21 +02:00
|
|
|
extra_action_fetches_fn=vf_preds_fetches,
|
2019-05-18 00:23:11 -07:00
|
|
|
postprocess_fn=postprocess_ppo_gae,
|
|
|
|
gradients_fn=clip_gradients,
|
2019-07-07 15:06:41 -07:00
|
|
|
before_init=setup_config,
|
2019-05-18 00:23:11 -07:00
|
|
|
before_loss_init=setup_mixins,
|
2019-07-09 03:30:32 +02:00
|
|
|
mixins=[
|
|
|
|
LearningRateSchedule, EntropyCoeffSchedule, KLCoeffMixin,
|
|
|
|
ValueNetworkMixin
|
|
|
|
])
|