2019-07-27 02:08:16 -07:00
|
|
|
import numpy as np
|
2019-12-28 09:51:09 -08:00
|
|
|
import functools
|
2019-07-27 02:08:16 -07:00
|
|
|
|
|
|
|
from ray.rllib.models.action_dist import ActionDistribution
|
|
|
|
from ray.rllib.utils.annotations import override, DeveloperAPI
|
2020-02-22 23:19:49 +01:00
|
|
|
from ray.rllib.utils import try_import_tf, try_import_tfp, SMALL_NUMBER, \
|
|
|
|
MIN_LOG_NN_OUTPUT, MAX_LOG_NN_OUTPUT
|
2020-02-19 21:18:45 +01:00
|
|
|
from ray.rllib.utils.tuple_actions import TupleActions
|
2019-07-27 02:08:16 -07:00
|
|
|
|
|
|
|
tf = try_import_tf()
|
2020-02-22 23:19:49 +01:00
|
|
|
tfp = try_import_tfp()
|
2019-07-27 02:08:16 -07:00
|
|
|
|
|
|
|
|
|
|
|
@DeveloperAPI
|
|
|
|
class TFActionDistribution(ActionDistribution):
|
|
|
|
"""TF-specific extensions for building action distributions."""
|
|
|
|
|
|
|
|
@DeveloperAPI
|
2019-08-10 14:05:12 -07:00
|
|
|
def __init__(self, inputs, model):
|
2020-02-11 00:22:07 +01:00
|
|
|
super().__init__(inputs, model)
|
2019-07-27 02:08:16 -07:00
|
|
|
self.sample_op = self._build_sample_op()
|
2020-04-15 13:25:16 +02:00
|
|
|
self.sampled_action_logp_op = self.logp(self.sample_op)
|
2019-07-27 02:08:16 -07:00
|
|
|
|
|
|
|
@DeveloperAPI
|
|
|
|
def _build_sample_op(self):
|
|
|
|
"""Implement this instead of sample(), to enable op reuse.
|
|
|
|
|
|
|
|
This is needed since the sample op is non-deterministic and is shared
|
2019-08-10 14:05:12 -07:00
|
|
|
between sample() and sampled_action_logp().
|
2019-07-27 02:08:16 -07:00
|
|
|
"""
|
|
|
|
raise NotImplementedError
|
|
|
|
|
2019-08-10 14:05:12 -07:00
|
|
|
@override(ActionDistribution)
|
2019-07-27 02:08:16 -07:00
|
|
|
def sample(self):
|
|
|
|
"""Draw a sample from the action distribution."""
|
|
|
|
return self.sample_op
|
|
|
|
|
2019-08-10 14:05:12 -07:00
|
|
|
@override(ActionDistribution)
|
|
|
|
def sampled_action_logp(self):
|
2019-07-27 02:08:16 -07:00
|
|
|
"""Returns the log probability of the sampled action."""
|
2020-04-15 13:25:16 +02:00
|
|
|
return self.sampled_action_logp_op
|
2019-07-27 02:08:16 -07:00
|
|
|
|
|
|
|
|
|
|
|
class Categorical(TFActionDistribution):
|
|
|
|
"""Categorical distribution for discrete action spaces."""
|
|
|
|
|
2019-08-10 14:05:12 -07:00
|
|
|
@DeveloperAPI
|
2020-02-19 21:18:45 +01:00
|
|
|
def __init__(self, inputs, model=None, temperature=1.0):
|
2020-03-06 19:37:12 +01:00
|
|
|
assert temperature > 0.0, "Categorical `temperature` must be > 0.0!"
|
2020-02-19 21:18:45 +01:00
|
|
|
# Allow softmax formula w/ temperature != 1.0:
|
|
|
|
# Divide inputs by temperature.
|
|
|
|
super().__init__(inputs / temperature, model)
|
|
|
|
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def deterministic_sample(self):
|
|
|
|
return tf.math.argmax(self.inputs, axis=1)
|
2019-08-10 14:05:12 -07:00
|
|
|
|
2019-07-27 02:08:16 -07:00
|
|
|
@override(ActionDistribution)
|
|
|
|
def logp(self, x):
|
|
|
|
return -tf.nn.sparse_softmax_cross_entropy_with_logits(
|
|
|
|
logits=self.inputs, labels=tf.cast(x, tf.int32))
|
|
|
|
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def entropy(self):
|
2020-02-19 21:18:45 +01:00
|
|
|
a0 = self.inputs - tf.reduce_max(self.inputs, axis=1, keep_dims=True)
|
2019-07-27 02:08:16 -07:00
|
|
|
ea0 = tf.exp(a0)
|
2020-02-19 21:18:45 +01:00
|
|
|
z0 = tf.reduce_sum(ea0, axis=1, keep_dims=True)
|
2019-07-27 02:08:16 -07:00
|
|
|
p0 = ea0 / z0
|
2020-02-19 21:18:45 +01:00
|
|
|
return tf.reduce_sum(p0 * (tf.log(z0) - a0), axis=1)
|
2019-07-27 02:08:16 -07:00
|
|
|
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def kl(self, other):
|
2020-02-12 21:46:15 +01:00
|
|
|
a0 = self.inputs - tf.reduce_max(self.inputs, axis=1, keep_dims=True)
|
|
|
|
a1 = other.inputs - tf.reduce_max(other.inputs, axis=1, keep_dims=True)
|
2019-07-27 02:08:16 -07:00
|
|
|
ea0 = tf.exp(a0)
|
|
|
|
ea1 = tf.exp(a1)
|
2020-02-12 21:46:15 +01:00
|
|
|
z0 = tf.reduce_sum(ea0, axis=1, keep_dims=True)
|
|
|
|
z1 = tf.reduce_sum(ea1, axis=1, keep_dims=True)
|
2019-07-27 02:08:16 -07:00
|
|
|
p0 = ea0 / z0
|
2020-02-12 21:46:15 +01:00
|
|
|
return tf.reduce_sum(p0 * (a0 - tf.log(z0) - a1 + tf.log(z1)), axis=1)
|
2019-07-27 02:08:16 -07:00
|
|
|
|
|
|
|
@override(TFActionDistribution)
|
|
|
|
def _build_sample_op(self):
|
|
|
|
return tf.squeeze(tf.multinomial(self.inputs, 1), axis=1)
|
|
|
|
|
2019-08-06 18:13:16 +00:00
|
|
|
@staticmethod
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def required_model_output_shape(action_space, model_config):
|
|
|
|
return action_space.n
|
|
|
|
|
2019-07-27 02:08:16 -07:00
|
|
|
|
|
|
|
class MultiCategorical(TFActionDistribution):
|
2019-08-06 18:13:16 +00:00
|
|
|
"""MultiCategorical distribution for MultiDiscrete action spaces."""
|
2019-07-27 02:08:16 -07:00
|
|
|
|
2019-08-10 14:05:12 -07:00
|
|
|
def __init__(self, inputs, model, input_lens):
|
|
|
|
# skip TFActionDistribution init
|
|
|
|
ActionDistribution.__init__(self, inputs, model)
|
2019-07-27 02:08:16 -07:00
|
|
|
self.cats = [
|
2019-08-10 14:05:12 -07:00
|
|
|
Categorical(input_, model)
|
2019-07-27 02:08:16 -07:00
|
|
|
for input_ in tf.split(inputs, input_lens, axis=1)
|
|
|
|
]
|
|
|
|
self.sample_op = self._build_sample_op()
|
2020-04-15 13:25:16 +02:00
|
|
|
self.sampled_action_logp_op = self.logp(self.sample_op)
|
2019-07-27 02:08:16 -07:00
|
|
|
|
2020-02-19 21:18:45 +01:00
|
|
|
@override(ActionDistribution)
|
|
|
|
def deterministic_sample(self):
|
2020-03-04 09:41:40 +01:00
|
|
|
return tf.stack(
|
2020-03-23 20:19:30 +01:00
|
|
|
[cat.deterministic_sample() for cat in self.cats], axis=1)
|
2020-02-19 21:18:45 +01:00
|
|
|
|
2019-07-27 02:08:16 -07:00
|
|
|
@override(ActionDistribution)
|
|
|
|
def logp(self, actions):
|
2020-03-04 09:41:40 +01:00
|
|
|
# If tensor is provided, unstack it into list.
|
2019-07-27 02:08:16 -07:00
|
|
|
if isinstance(actions, tf.Tensor):
|
|
|
|
actions = tf.unstack(tf.cast(actions, tf.int32), axis=1)
|
|
|
|
logps = tf.stack(
|
|
|
|
[cat.logp(act) for cat, act in zip(self.cats, actions)])
|
|
|
|
return tf.reduce_sum(logps, axis=0)
|
|
|
|
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def multi_entropy(self):
|
|
|
|
return tf.stack([cat.entropy() for cat in self.cats], axis=1)
|
|
|
|
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def entropy(self):
|
|
|
|
return tf.reduce_sum(self.multi_entropy(), axis=1)
|
|
|
|
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def multi_kl(self, other):
|
2020-02-12 21:46:15 +01:00
|
|
|
return tf.stack(
|
|
|
|
[cat.kl(oth_cat) for cat, oth_cat in zip(self.cats, other.cats)],
|
|
|
|
axis=1)
|
2019-07-27 02:08:16 -07:00
|
|
|
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def kl(self, other):
|
|
|
|
return tf.reduce_sum(self.multi_kl(other), axis=1)
|
|
|
|
|
|
|
|
@override(TFActionDistribution)
|
|
|
|
def _build_sample_op(self):
|
|
|
|
return tf.stack([cat.sample() for cat in self.cats], axis=1)
|
|
|
|
|
2019-08-06 18:13:16 +00:00
|
|
|
@staticmethod
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def required_model_output_shape(action_space, model_config):
|
|
|
|
return np.sum(action_space.nvec)
|
|
|
|
|
2019-07-27 02:08:16 -07:00
|
|
|
|
2020-03-06 19:37:12 +01:00
|
|
|
class GumbelSoftmax(TFActionDistribution):
|
|
|
|
"""GumbelSoftmax distr. (for differentiable sampling in discr. actions
|
|
|
|
|
|
|
|
The Gumbel Softmax distribution [1] (also known as the Concrete [2]
|
|
|
|
distribution) is a close cousin of the relaxed one-hot categorical
|
|
|
|
distribution, whose tfp implementation we will use here plus
|
|
|
|
adjusted `sample_...` and `log_prob` methods. See discussion at [0].
|
|
|
|
|
|
|
|
[0] https://stackoverflow.com/questions/56226133/
|
|
|
|
soft-actor-critic-with-discrete-action-space
|
|
|
|
|
|
|
|
[1] Categorical Reparametrization with Gumbel-Softmax (Jang et al, 2017):
|
|
|
|
https://arxiv.org/abs/1611.01144
|
|
|
|
[2] The Concrete Distribution: A Continuous Relaxation of Discrete Random
|
|
|
|
Variables (Maddison et al, 2017) https://arxiv.org/abs/1611.00712
|
|
|
|
"""
|
|
|
|
|
|
|
|
@DeveloperAPI
|
|
|
|
def __init__(self, inputs, model=None, temperature=1.0):
|
|
|
|
"""Initializes a GumbelSoftmax distribution.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
temperature (float): Temperature parameter. For low temperatures,
|
|
|
|
the expected value approaches a categorical random variable.
|
|
|
|
For high temperatures, the expected value approaches a uniform
|
|
|
|
distribution.
|
|
|
|
"""
|
|
|
|
assert temperature >= 0.0
|
|
|
|
self.dist = tfp.distributions.RelaxedOneHotCategorical(
|
|
|
|
temperature=temperature, logits=inputs)
|
|
|
|
super().__init__(inputs, model)
|
|
|
|
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def deterministic_sample(self):
|
|
|
|
# Return the dist object's prob values.
|
|
|
|
return self.dist._distribution.probs
|
|
|
|
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def logp(self, x):
|
|
|
|
# Override since the implementation of tfp.RelaxedOneHotCategorical
|
|
|
|
# yields positive values.
|
|
|
|
if x.shape != self.dist.logits.shape:
|
|
|
|
values = tf.one_hot(
|
|
|
|
x, self.dist.logits.shape.as_list()[-1], dtype=tf.float32)
|
|
|
|
assert values.shape == self.dist.logits.shape, (
|
|
|
|
values.shape, self.dist.logits.shape)
|
|
|
|
|
|
|
|
# [0]'s implementation (see line below) seems to be an approximation
|
|
|
|
# to the actual Gumbel Softmax density.
|
|
|
|
return -tf.reduce_sum(
|
|
|
|
-x * tf.nn.log_softmax(self.dist.logits, axis=-1), axis=-1)
|
|
|
|
|
|
|
|
@override(TFActionDistribution)
|
|
|
|
def _build_sample_op(self):
|
|
|
|
return self.dist.sample()
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def required_model_output_shape(action_space, model_config):
|
|
|
|
return action_space.n
|
|
|
|
|
|
|
|
|
2019-07-27 02:08:16 -07:00
|
|
|
class DiagGaussian(TFActionDistribution):
|
|
|
|
"""Action distribution where each vector element is a gaussian.
|
|
|
|
|
|
|
|
The first half of the input vector defines the gaussian means, and the
|
|
|
|
second half the gaussian standard deviations.
|
|
|
|
"""
|
|
|
|
|
2019-08-10 14:05:12 -07:00
|
|
|
def __init__(self, inputs, model):
|
2019-07-27 02:08:16 -07:00
|
|
|
mean, log_std = tf.split(inputs, 2, axis=1)
|
|
|
|
self.mean = mean
|
|
|
|
self.log_std = log_std
|
|
|
|
self.std = tf.exp(log_std)
|
2020-02-11 00:22:07 +01:00
|
|
|
super().__init__(inputs, model)
|
2019-07-27 02:08:16 -07:00
|
|
|
|
2020-02-19 21:18:45 +01:00
|
|
|
@override(ActionDistribution)
|
|
|
|
def deterministic_sample(self):
|
|
|
|
return self.mean
|
|
|
|
|
2019-07-27 02:08:16 -07:00
|
|
|
@override(ActionDistribution)
|
|
|
|
def logp(self, x):
|
2020-02-19 21:18:45 +01:00
|
|
|
return -0.5 * tf.reduce_sum(
|
|
|
|
tf.square((x - self.mean) / self.std), axis=1) - \
|
|
|
|
0.5 * np.log(2.0 * np.pi) * tf.to_float(tf.shape(x)[1]) - \
|
|
|
|
tf.reduce_sum(self.log_std, axis=1)
|
2019-07-27 02:08:16 -07:00
|
|
|
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def kl(self, other):
|
|
|
|
assert isinstance(other, DiagGaussian)
|
|
|
|
return tf.reduce_sum(
|
|
|
|
other.log_std - self.log_std +
|
|
|
|
(tf.square(self.std) + tf.square(self.mean - other.mean)) /
|
|
|
|
(2.0 * tf.square(other.std)) - 0.5,
|
2020-02-19 21:18:45 +01:00
|
|
|
axis=1)
|
2019-07-27 02:08:16 -07:00
|
|
|
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def entropy(self):
|
|
|
|
return tf.reduce_sum(
|
2020-02-19 21:18:45 +01:00
|
|
|
self.log_std + .5 * np.log(2.0 * np.pi * np.e), axis=1)
|
2019-07-27 02:08:16 -07:00
|
|
|
|
|
|
|
@override(TFActionDistribution)
|
|
|
|
def _build_sample_op(self):
|
|
|
|
return self.mean + self.std * tf.random_normal(tf.shape(self.mean))
|
|
|
|
|
2019-08-06 18:13:16 +00:00
|
|
|
@staticmethod
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def required_model_output_shape(action_space, model_config):
|
|
|
|
return np.prod(action_space.shape) * 2
|
|
|
|
|
2019-07-27 02:08:16 -07:00
|
|
|
|
2020-02-22 23:19:49 +01:00
|
|
|
class SquashedGaussian(TFActionDistribution):
|
|
|
|
"""A tanh-squashed Gaussian distribution defined by: mean, std, low, high.
|
|
|
|
|
|
|
|
The distribution will never return low or high exactly, but
|
|
|
|
`low`+SMALL_NUMBER or `high`-SMALL_NUMBER respectively.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, inputs, model, low=-1.0, high=1.0):
|
|
|
|
"""Parameterizes the distribution via `inputs`.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
low (float): The lowest possible sampling value
|
|
|
|
(excluding this value).
|
|
|
|
high (float): The highest possible sampling value
|
|
|
|
(excluding this value).
|
|
|
|
"""
|
|
|
|
assert tfp is not None
|
2020-04-15 13:25:16 +02:00
|
|
|
mean, log_std = tf.split(inputs, 2, axis=-1)
|
2020-02-22 23:19:49 +01:00
|
|
|
# Clip `scale` values (coming from NN) to reasonable values.
|
2020-04-15 13:25:16 +02:00
|
|
|
log_std = tf.clip_by_value(log_std, MIN_LOG_NN_OUTPUT,
|
|
|
|
MAX_LOG_NN_OUTPUT)
|
|
|
|
std = tf.exp(log_std)
|
|
|
|
self.distr = tfp.distributions.Normal(loc=mean, scale=std)
|
2020-02-22 23:19:49 +01:00
|
|
|
assert np.all(np.less(low, high))
|
|
|
|
self.low = low
|
|
|
|
self.high = high
|
|
|
|
super().__init__(inputs, model)
|
|
|
|
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def deterministic_sample(self):
|
|
|
|
mean = self.distr.mean()
|
|
|
|
return self._squash(mean)
|
|
|
|
|
|
|
|
@override(TFActionDistribution)
|
|
|
|
def _build_sample_op(self):
|
|
|
|
return self._squash(self.distr.sample())
|
|
|
|
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def logp(self, x):
|
|
|
|
unsquashed_values = self._unsquash(x)
|
|
|
|
log_prob = tf.reduce_sum(
|
|
|
|
self.distr.log_prob(value=unsquashed_values), axis=-1)
|
|
|
|
unsquashed_values_tanhd = tf.math.tanh(unsquashed_values)
|
|
|
|
log_prob -= tf.math.reduce_sum(
|
|
|
|
tf.math.log(1 - unsquashed_values_tanhd**2 + SMALL_NUMBER),
|
|
|
|
axis=-1)
|
|
|
|
return log_prob
|
|
|
|
|
|
|
|
def _squash(self, raw_values):
|
|
|
|
# Make sure raw_values are not too high/low (such that tanh would
|
|
|
|
# return exactly 1.0/-1.0, which would lead to +/-inf log-probs).
|
|
|
|
return (tf.clip_by_value(
|
|
|
|
tf.math.tanh(raw_values),
|
|
|
|
-1.0 + SMALL_NUMBER,
|
|
|
|
1.0 - SMALL_NUMBER) + 1.0) / 2.0 * (self.high - self.low) + \
|
|
|
|
self.low
|
|
|
|
|
|
|
|
def _unsquash(self, values):
|
|
|
|
return tf.math.atanh((values - self.low) /
|
|
|
|
(self.high - self.low) * 2.0 - 1.0)
|
|
|
|
|
|
|
|
|
2019-07-27 02:08:16 -07:00
|
|
|
class Deterministic(TFActionDistribution):
|
|
|
|
"""Action distribution that returns the input values directly.
|
|
|
|
|
2020-03-01 20:53:35 +01:00
|
|
|
This is similar to DiagGaussian with standard deviation zero (thus only
|
|
|
|
requiring the "mean" values as NN output).
|
2019-07-27 02:08:16 -07:00
|
|
|
"""
|
|
|
|
|
2020-02-19 21:18:45 +01:00
|
|
|
@override(ActionDistribution)
|
|
|
|
def deterministic_sample(self):
|
|
|
|
return self.inputs
|
|
|
|
|
2019-07-27 02:08:16 -07:00
|
|
|
@override(TFActionDistribution)
|
2020-04-01 09:43:21 +02:00
|
|
|
def logp(self, x):
|
|
|
|
return tf.zeros_like(self.inputs)
|
2019-07-27 02:08:16 -07:00
|
|
|
|
|
|
|
@override(TFActionDistribution)
|
|
|
|
def _build_sample_op(self):
|
|
|
|
return self.inputs
|
|
|
|
|
2019-08-06 18:13:16 +00:00
|
|
|
@staticmethod
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def required_model_output_shape(action_space, model_config):
|
|
|
|
return np.prod(action_space.shape)
|
|
|
|
|
2019-07-27 02:08:16 -07:00
|
|
|
|
|
|
|
class MultiActionDistribution(TFActionDistribution):
|
|
|
|
"""Action distribution that operates for list of actions.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
inputs (Tensor list): A list of tensors from which to compute samples.
|
|
|
|
"""
|
|
|
|
|
2019-08-10 14:05:12 -07:00
|
|
|
def __init__(self, inputs, model, action_space, child_distributions,
|
|
|
|
input_lens):
|
|
|
|
# skip TFActionDistribution init
|
|
|
|
ActionDistribution.__init__(self, inputs, model)
|
2019-07-27 02:08:16 -07:00
|
|
|
self.input_lens = input_lens
|
|
|
|
split_inputs = tf.split(inputs, self.input_lens, axis=1)
|
|
|
|
child_list = []
|
|
|
|
for i, distribution in enumerate(child_distributions):
|
2019-08-10 14:05:12 -07:00
|
|
|
child_list.append(distribution(split_inputs[i], model))
|
2019-07-27 02:08:16 -07:00
|
|
|
self.child_distributions = child_list
|
|
|
|
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def logp(self, x):
|
|
|
|
split_indices = []
|
|
|
|
for dist in self.child_distributions:
|
|
|
|
if isinstance(dist, Categorical):
|
|
|
|
split_indices.append(1)
|
|
|
|
else:
|
|
|
|
split_indices.append(tf.shape(dist.sample())[1])
|
|
|
|
split_list = tf.split(x, split_indices, axis=1)
|
|
|
|
for i, distribution in enumerate(self.child_distributions):
|
|
|
|
# Remove extra categorical dimension
|
|
|
|
if isinstance(distribution, Categorical):
|
|
|
|
split_list[i] = tf.cast(
|
|
|
|
tf.squeeze(split_list[i], axis=-1), tf.int32)
|
2019-12-28 09:51:09 -08:00
|
|
|
log_list = [
|
2019-07-27 02:08:16 -07:00
|
|
|
distribution.logp(split_x) for distribution, split_x in zip(
|
|
|
|
self.child_distributions, split_list)
|
2019-12-28 09:51:09 -08:00
|
|
|
]
|
|
|
|
return functools.reduce(lambda a, b: a + b, log_list)
|
2019-07-27 02:08:16 -07:00
|
|
|
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def kl(self, other):
|
2019-12-28 09:51:09 -08:00
|
|
|
kl_list = [
|
2019-07-27 02:08:16 -07:00
|
|
|
distribution.kl(other_distribution)
|
|
|
|
for distribution, other_distribution in zip(
|
|
|
|
self.child_distributions, other.child_distributions)
|
2019-12-28 09:51:09 -08:00
|
|
|
]
|
|
|
|
return functools.reduce(lambda a, b: a + b, kl_list)
|
2019-07-27 02:08:16 -07:00
|
|
|
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def entropy(self):
|
2019-12-28 09:51:09 -08:00
|
|
|
entropy_list = [s.entropy() for s in self.child_distributions]
|
|
|
|
return functools.reduce(lambda a, b: a + b, entropy_list)
|
2019-07-27 02:08:16 -07:00
|
|
|
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def sample(self):
|
|
|
|
return TupleActions([s.sample() for s in self.child_distributions])
|
|
|
|
|
2020-02-19 21:18:45 +01:00
|
|
|
@override(ActionDistribution)
|
|
|
|
def deterministic_sample(self):
|
|
|
|
return TupleActions(
|
|
|
|
[s.deterministic_sample() for s in self.child_distributions])
|
|
|
|
|
2019-07-27 02:08:16 -07:00
|
|
|
@override(TFActionDistribution)
|
2019-08-10 14:05:12 -07:00
|
|
|
def sampled_action_logp(self):
|
|
|
|
p = self.child_distributions[0].sampled_action_logp()
|
2019-07-27 02:08:16 -07:00
|
|
|
for c in self.child_distributions[1:]:
|
2019-08-10 14:05:12 -07:00
|
|
|
p += c.sampled_action_logp()
|
2019-07-27 02:08:16 -07:00
|
|
|
return p
|
|
|
|
|
|
|
|
|
|
|
|
class Dirichlet(TFActionDistribution):
|
|
|
|
"""Dirichlet distribution for continuous actions that are between
|
|
|
|
[0,1] and sum to 1.
|
|
|
|
|
|
|
|
e.g. actions that represent resource allocation."""
|
|
|
|
|
2019-08-10 14:05:12 -07:00
|
|
|
def __init__(self, inputs, model):
|
2019-07-27 02:08:16 -07:00
|
|
|
"""Input is a tensor of logits. The exponential of logits is used to
|
|
|
|
parametrize the Dirichlet distribution as all parameters need to be
|
|
|
|
positive. An arbitrary small epsilon is added to the concentration
|
|
|
|
parameters to be zero due to numerical error.
|
|
|
|
|
|
|
|
See issue #4440 for more details.
|
|
|
|
"""
|
|
|
|
self.epsilon = 1e-7
|
|
|
|
concentration = tf.exp(inputs) + self.epsilon
|
|
|
|
self.dist = tf.distributions.Dirichlet(
|
|
|
|
concentration=concentration,
|
|
|
|
validate_args=True,
|
|
|
|
allow_nan_stats=False,
|
|
|
|
)
|
2020-02-11 00:22:07 +01:00
|
|
|
super().__init__(concentration, model)
|
2019-07-27 02:08:16 -07:00
|
|
|
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def logp(self, x):
|
2020-02-11 00:22:07 +01:00
|
|
|
# Support of Dirichlet are positive real numbers. x is already
|
|
|
|
# an array of positive numbers, but we clip to avoid zeros due to
|
2019-07-27 02:08:16 -07:00
|
|
|
# numerical errors.
|
|
|
|
x = tf.maximum(x, self.epsilon)
|
|
|
|
x = x / tf.reduce_sum(x, axis=-1, keepdims=True)
|
|
|
|
return self.dist.log_prob(x)
|
|
|
|
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def entropy(self):
|
|
|
|
return self.dist.entropy()
|
|
|
|
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def kl(self, other):
|
|
|
|
return self.dist.kl_divergence(other.dist)
|
|
|
|
|
|
|
|
@override(TFActionDistribution)
|
|
|
|
def _build_sample_op(self):
|
|
|
|
return self.dist.sample()
|
2019-08-06 18:13:16 +00:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def required_model_output_shape(action_space, model_config):
|
|
|
|
return np.prod(action_space.shape)
|