2019-05-20 16:46:05 -07:00
|
|
|
"""Note: Keep in sync with changes to VTraceTFPolicy."""
|
2022-05-28 09:54:47 +02:00
|
|
|
from typing import Dict, List, Optional, Type, Union
|
2018-08-01 20:53:53 -07:00
|
|
|
|
2018-06-25 22:33:57 -07:00
|
|
|
import ray
|
2021-10-29 12:03:56 +02:00
|
|
|
from ray.rllib.evaluation.episode import Episode
|
2021-01-19 14:22:36 +01:00
|
|
|
from ray.rllib.evaluation.postprocessing import (
|
|
|
|
compute_gae_for_sample_batch,
|
2019-03-29 12:44:23 -07:00
|
|
|
Postprocessing,
|
2022-01-29 18:41:57 -08:00
|
|
|
)
|
2021-10-29 12:03:56 +02:00
|
|
|
from ray.rllib.models.modelv2 import ModelV2
|
2022-05-28 09:54:47 +02:00
|
|
|
from ray.rllib.models.tf.tf_action_dist import TFActionDistribution
|
|
|
|
from ray.rllib.policy.dynamic_tf_policy_v2 import DynamicTFPolicyV2
|
|
|
|
from ray.rllib.policy.eager_tf_policy_v2 import EagerTFPolicyV2
|
|
|
|
from ray.rllib.policy.sample_batch import SampleBatch
|
2022-05-17 08:16:08 -07:00
|
|
|
from ray.rllib.policy.tf_mixins import (
|
2022-05-28 09:54:47 +02:00
|
|
|
compute_gradients,
|
2022-05-17 08:16:08 -07:00
|
|
|
EntropyCoeffSchedule,
|
|
|
|
LearningRateSchedule,
|
|
|
|
ValueNetworkMixin,
|
|
|
|
)
|
2022-05-28 09:54:47 +02:00
|
|
|
from ray.rllib.utils.annotations import override
|
2021-11-01 21:46:02 +01:00
|
|
|
from ray.rllib.utils.deprecation import Deprecated
|
2020-06-16 08:52:20 +02:00
|
|
|
from ray.rllib.utils.framework import try_import_tf
|
2021-11-01 21:46:02 +01:00
|
|
|
from ray.rllib.utils.tf_utils import explained_variance
|
2021-05-19 07:32:29 -07:00
|
|
|
from ray.rllib.utils.typing import (
|
2022-05-28 09:54:47 +02:00
|
|
|
AgentID,
|
2021-05-19 07:32:29 -07:00
|
|
|
LocalOptimizer,
|
|
|
|
ModelGradients,
|
2022-05-28 09:54:47 +02:00
|
|
|
TensorType,
|
|
|
|
TFPolicyV2Type,
|
2022-01-29 18:41:57 -08:00
|
|
|
)
|
2019-05-10 20:36:18 -07:00
|
|
|
|
2020-06-30 10:13:20 +02:00
|
|
|
tf1, tf, tfv = try_import_tf()
|
2018-06-09 00:21:35 -07:00
|
|
|
|
|
|
|
|
2022-05-28 09:54:47 +02:00
|
|
|
# We need this builder function because we want to share the same
|
|
|
|
# custom logics between TF1 dynamic and TF2 eager policies.
|
2022-07-13 09:55:20 -07:00
|
|
|
def get_a3c_tf_policy(name: str, base: TFPolicyV2Type) -> TFPolicyV2Type:
|
2022-05-28 09:54:47 +02:00
|
|
|
"""Construct a A3CTFPolicy inheriting either dynamic or eager base policies.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
base: Base class for this policy. DynamicTFPolicyV2 or EagerTFPolicyV2.
|
|
|
|
|
|
|
|
Returns:
|
2022-06-04 07:35:24 +02:00
|
|
|
A TF Policy to be used with MAML.
|
2022-05-28 09:54:47 +02:00
|
|
|
"""
|
|
|
|
|
|
|
|
class A3CTFPolicy(
|
|
|
|
ValueNetworkMixin, LearningRateSchedule, EntropyCoeffSchedule, base
|
|
|
|
):
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
obs_space,
|
|
|
|
action_space,
|
|
|
|
config,
|
|
|
|
existing_model=None,
|
|
|
|
existing_inputs=None,
|
|
|
|
):
|
|
|
|
# First thing first, enable eager execution if necessary.
|
|
|
|
base.enable_eager_execution_if_necessary()
|
|
|
|
|
2022-06-01 09:29:16 +02:00
|
|
|
config = dict(ray.rllib.algorithms.a3c.a3c.A3CConfig().to_dict(), **config)
|
2022-05-28 09:54:47 +02:00
|
|
|
|
|
|
|
# Initialize base class.
|
|
|
|
base.__init__(
|
|
|
|
self,
|
|
|
|
obs_space,
|
|
|
|
action_space,
|
|
|
|
config,
|
|
|
|
existing_inputs=existing_inputs,
|
|
|
|
existing_model=existing_model,
|
|
|
|
)
|
|
|
|
|
|
|
|
ValueNetworkMixin.__init__(self, self.config)
|
|
|
|
LearningRateSchedule.__init__(
|
|
|
|
self, self.config["lr"], self.config["lr_schedule"]
|
|
|
|
)
|
|
|
|
EntropyCoeffSchedule.__init__(
|
|
|
|
self, config["entropy_coeff"], config["entropy_coeff_schedule"]
|
|
|
|
)
|
|
|
|
|
|
|
|
# Note: this is a bit ugly, but loss and optimizer initialization must
|
|
|
|
# happen after all the MixIns are initialized.
|
|
|
|
self.maybe_initialize_optimizer_and_loss()
|
|
|
|
|
|
|
|
@override(base)
|
|
|
|
def loss(
|
|
|
|
self,
|
|
|
|
model: Union[ModelV2, "tf.keras.Model"],
|
|
|
|
dist_class: Type[TFActionDistribution],
|
|
|
|
train_batch: SampleBatch,
|
|
|
|
) -> Union[TensorType, List[TensorType]]:
|
|
|
|
|
|
|
|
model_out, _ = model(train_batch)
|
|
|
|
action_dist = dist_class(model_out, model)
|
|
|
|
if self.is_recurrent():
|
|
|
|
max_seq_len = tf.reduce_max(train_batch[SampleBatch.SEQ_LENS])
|
|
|
|
valid_mask = tf.sequence_mask(
|
|
|
|
train_batch[SampleBatch.SEQ_LENS], max_seq_len
|
|
|
|
)
|
|
|
|
valid_mask = tf.reshape(valid_mask, [-1])
|
|
|
|
else:
|
|
|
|
valid_mask = tf.ones_like(train_batch[SampleBatch.REWARDS])
|
|
|
|
|
|
|
|
log_prob = action_dist.logp(train_batch[SampleBatch.ACTIONS])
|
|
|
|
vf = model.value_function()
|
|
|
|
|
|
|
|
# The "policy gradients" loss
|
|
|
|
self.pi_loss = -tf.reduce_sum(
|
|
|
|
tf.boolean_mask(
|
|
|
|
log_prob * train_batch[Postprocessing.ADVANTAGES], valid_mask
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
delta = tf.boolean_mask(
|
|
|
|
vf - train_batch[Postprocessing.VALUE_TARGETS], valid_mask
|
|
|
|
)
|
|
|
|
|
|
|
|
# Compute a value function loss.
|
|
|
|
if self.config.get("use_critic", True):
|
|
|
|
self.vf_loss = 0.5 * tf.reduce_sum(tf.math.square(delta))
|
|
|
|
# Ignore the value function.
|
|
|
|
else:
|
|
|
|
self.vf_loss = tf.constant(0.0)
|
|
|
|
|
|
|
|
self.entropy_loss = tf.reduce_sum(
|
|
|
|
tf.boolean_mask(action_dist.entropy(), valid_mask)
|
|
|
|
)
|
|
|
|
|
|
|
|
self.total_loss = (
|
|
|
|
self.pi_loss
|
|
|
|
+ self.vf_loss * self.config["vf_loss_coeff"]
|
|
|
|
- self.entropy_loss * self.entropy_coeff
|
|
|
|
)
|
|
|
|
|
|
|
|
return self.total_loss
|
|
|
|
|
|
|
|
@override(base)
|
|
|
|
def stats_fn(self, train_batch: SampleBatch) -> Dict[str, TensorType]:
|
|
|
|
return {
|
|
|
|
"cur_lr": tf.cast(self.cur_lr, tf.float64),
|
|
|
|
"entropy_coeff": tf.cast(self.entropy_coeff, tf.float64),
|
|
|
|
"policy_loss": self.pi_loss,
|
|
|
|
"policy_entropy": self.entropy_loss,
|
|
|
|
"var_gnorm": tf.linalg.global_norm(
|
|
|
|
list(self.model.trainable_variables())
|
|
|
|
),
|
|
|
|
"vf_loss": self.vf_loss,
|
|
|
|
}
|
|
|
|
|
|
|
|
@override(base)
|
|
|
|
def grad_stats_fn(
|
|
|
|
self, train_batch: SampleBatch, grads: ModelGradients
|
|
|
|
) -> Dict[str, TensorType]:
|
|
|
|
return {
|
|
|
|
"grad_gnorm": tf.linalg.global_norm(grads),
|
|
|
|
"vf_explained_var": explained_variance(
|
|
|
|
train_batch[Postprocessing.VALUE_TARGETS],
|
|
|
|
self.model.value_function(),
|
|
|
|
),
|
|
|
|
}
|
|
|
|
|
|
|
|
@override(base)
|
|
|
|
def postprocess_trajectory(
|
|
|
|
self,
|
|
|
|
sample_batch: SampleBatch,
|
|
|
|
other_agent_batches: Optional[Dict[AgentID, SampleBatch]] = None,
|
|
|
|
episode: Optional[Episode] = None,
|
|
|
|
):
|
|
|
|
sample_batch = super().postprocess_trajectory(sample_batch)
|
|
|
|
return compute_gae_for_sample_batch(
|
|
|
|
self, sample_batch, other_agent_batches, episode
|
|
|
|
)
|
|
|
|
|
|
|
|
@override(base)
|
|
|
|
def compute_gradients_fn(
|
|
|
|
self, optimizer: LocalOptimizer, loss: TensorType
|
|
|
|
) -> ModelGradients:
|
|
|
|
return compute_gradients(self, optimizer, loss)
|
|
|
|
|
2022-07-13 09:55:20 -07:00
|
|
|
A3CTFPolicy.__name__ = name
|
|
|
|
A3CTFPolicy.__qualname__ = name
|
|
|
|
|
2022-05-28 09:54:47 +02:00
|
|
|
return A3CTFPolicy
|
|
|
|
|
|
|
|
|
2022-07-13 09:55:20 -07:00
|
|
|
A3CTF1Policy = get_a3c_tf_policy("A3CTF1Policy", DynamicTFPolicyV2)
|
|
|
|
A3CTF2Policy = get_a3c_tf_policy("A3CTF2Policy", EagerTFPolicyV2)
|
2022-05-28 09:54:47 +02:00
|
|
|
|
|
|
|
|
2021-08-03 18:30:02 -04:00
|
|
|
@Deprecated(
|
2022-06-01 09:29:16 +02:00
|
|
|
old="rllib.algorithms.a3c.a3c_tf_policy.postprocess_advantages",
|
2021-08-03 18:30:02 -04:00
|
|
|
new="rllib.evaluation.postprocessing.compute_gae_for_sample_batch",
|
2022-05-28 09:54:47 +02:00
|
|
|
error=True,
|
2021-10-25 10:39:35 +03:00
|
|
|
)
|
2022-05-28 09:54:47 +02:00
|
|
|
def postprocess_advantages(*args, **kwargs):
|
|
|
|
pass
|