2020-10-07 21:59:14 +02:00
|
|
|
from gym.spaces import Discrete, Box, MultiDiscrete, Space
|
2020-04-15 13:25:16 +02:00
|
|
|
import numpy as np
|
2021-04-16 09:16:24 +02:00
|
|
|
import tree # pip install dm_tree
|
2020-10-07 21:59:14 +02:00
|
|
|
from typing import Union, Optional
|
2020-02-19 21:18:45 +01:00
|
|
|
|
2022-05-24 22:14:25 -07:00
|
|
|
from ray.rllib.utils.annotations import PublicAPI
|
2020-04-01 09:43:21 +02:00
|
|
|
from ray.rllib.models.action_dist import ActionDistribution
|
2020-10-07 21:59:14 +02:00
|
|
|
from ray.rllib.models.modelv2 import ModelV2
|
2020-02-19 21:18:45 +01:00
|
|
|
from ray.rllib.utils.annotations import override
|
|
|
|
from ray.rllib.utils.exploration.exploration import Exploration
|
2020-04-28 14:59:16 +02:00
|
|
|
from ray.rllib.utils import force_tuple
|
2020-02-19 21:18:45 +01:00
|
|
|
from ray.rllib.utils.framework import try_import_tf, try_import_torch, TensorType
|
2020-11-11 18:45:28 +01:00
|
|
|
from ray.rllib.utils.spaces.simplex import Simplex
|
2020-05-27 10:21:30 +02:00
|
|
|
from ray.rllib.utils.spaces.space_utils import get_base_struct_from_space
|
2021-11-01 21:46:02 +01:00
|
|
|
from ray.rllib.utils.tf_utils import zero_logps_from_actions
|
2020-02-19 21:18:45 +01:00
|
|
|
|
2020-06-30 10:13:20 +02:00
|
|
|
tf1, tf, tfv = try_import_tf()
|
2020-02-19 21:18:45 +01:00
|
|
|
torch, _ = try_import_torch()
|
|
|
|
|
|
|
|
|
2022-05-24 22:14:25 -07:00
|
|
|
@PublicAPI
|
2020-02-19 21:18:45 +01:00
|
|
|
class Random(Exploration):
|
|
|
|
"""A random action selector (deterministic/greedy for explore=False).
|
|
|
|
|
|
|
|
If explore=True, returns actions randomly from `self.action_space` (via
|
|
|
|
Space.sample()).
|
|
|
|
If explore=False, returns the greedy/max-likelihood action.
|
|
|
|
"""
|
|
|
|
|
2020-10-07 21:59:14 +02:00
|
|
|
def __init__(
|
|
|
|
self, action_space: Space, *, model: ModelV2, framework: Optional[str], **kwargs
|
|
|
|
):
|
2020-02-19 21:18:45 +01:00
|
|
|
"""Initialize a Random Exploration object.
|
|
|
|
|
|
|
|
Args:
|
2021-12-15 22:32:52 +01:00
|
|
|
action_space: The gym action space used by the environment.
|
|
|
|
framework: One of None, "tf", "tfe", "torch".
|
2020-02-19 21:18:45 +01:00
|
|
|
"""
|
|
|
|
super().__init__(
|
2020-04-01 09:43:21 +02:00
|
|
|
action_space=action_space, model=model, framework=framework, **kwargs
|
|
|
|
)
|
2020-02-19 21:18:45 +01:00
|
|
|
|
2020-05-08 08:26:32 +02:00
|
|
|
self.action_space_struct = get_base_struct_from_space(self.action_space)
|
2020-03-01 20:53:35 +01:00
|
|
|
|
2020-02-19 21:18:45 +01:00
|
|
|
@override(Exploration)
|
|
|
|
def get_exploration_action(
|
|
|
|
self,
|
2020-04-01 09:43:21 +02:00
|
|
|
*,
|
|
|
|
action_distribution: ActionDistribution,
|
2020-03-04 13:00:37 -08:00
|
|
|
timestep: Union[int, TensorType],
|
|
|
|
explore: bool = True
|
|
|
|
):
|
2020-02-19 21:18:45 +01:00
|
|
|
# Instantiate the distribution object.
|
2020-10-02 23:07:44 +02:00
|
|
|
if self.framework in ["tf2", "tf", "tfe"]:
|
2020-04-01 09:43:21 +02:00
|
|
|
return self.get_tf_exploration_action_op(action_distribution, explore)
|
2020-02-19 21:18:45 +01:00
|
|
|
else:
|
2020-04-01 09:43:21 +02:00
|
|
|
return self.get_torch_exploration_action(action_distribution, explore)
|
2020-02-19 21:18:45 +01:00
|
|
|
|
2020-10-07 21:59:14 +02:00
|
|
|
def get_tf_exploration_action_op(
|
|
|
|
self,
|
|
|
|
action_dist: ActionDistribution,
|
|
|
|
explore: Optional[Union[bool, TensorType]],
|
|
|
|
):
|
2020-03-12 19:02:51 +01:00
|
|
|
def true_fn():
|
2020-05-08 08:26:32 +02:00
|
|
|
batch_size = 1
|
|
|
|
req = force_tuple(
|
|
|
|
action_dist.required_model_output_shape(
|
2021-04-27 10:44:54 +02:00
|
|
|
self.action_space, getattr(self.model, "model_config", None)
|
|
|
|
)
|
2022-01-29 18:41:57 -08:00
|
|
|
)
|
2020-05-08 08:26:32 +02:00
|
|
|
# Add a batch dimension?
|
|
|
|
if len(action_dist.inputs.shape) == len(req) + 1:
|
|
|
|
batch_size = tf.shape(action_dist.inputs)[0]
|
|
|
|
|
|
|
|
# Function to produce random samples from primitive space
|
|
|
|
# components: (Multi)Discrete or Box.
|
|
|
|
def random_component(component):
|
2021-09-06 12:14:00 +02:00
|
|
|
# Have at least an additional shape of (1,), even if the
|
|
|
|
# component is Box(-1.0, 1.0, shape=()).
|
|
|
|
shape = component.shape or (1,)
|
|
|
|
|
2020-05-08 08:26:32 +02:00
|
|
|
if isinstance(component, Discrete):
|
|
|
|
return tf.random.uniform(
|
|
|
|
shape=(batch_size,) + component.shape,
|
|
|
|
maxval=component.n,
|
|
|
|
dtype=component.dtype,
|
|
|
|
)
|
|
|
|
elif isinstance(component, MultiDiscrete):
|
2020-10-06 20:28:16 +02:00
|
|
|
return tf.concat(
|
|
|
|
[
|
|
|
|
tf.random.uniform(
|
|
|
|
shape=(batch_size, 1), maxval=n, dtype=component.dtype
|
|
|
|
)
|
|
|
|
for n in component.nvec
|
|
|
|
],
|
|
|
|
axis=1,
|
|
|
|
)
|
2020-05-08 08:26:32 +02:00
|
|
|
elif isinstance(component, Box):
|
|
|
|
if component.bounded_above.all() and component.bounded_below.all():
|
2021-04-11 13:16:01 +02:00
|
|
|
if component.dtype.name.startswith("int"):
|
|
|
|
return tf.random.uniform(
|
2021-09-06 12:14:00 +02:00
|
|
|
shape=(batch_size,) + shape,
|
2021-04-11 13:16:01 +02:00
|
|
|
minval=component.low.flat[0],
|
|
|
|
maxval=component.high.flat[0],
|
|
|
|
dtype=component.dtype,
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
return tf.random.uniform(
|
2021-09-06 12:14:00 +02:00
|
|
|
shape=(batch_size,) + shape,
|
2021-04-11 13:16:01 +02:00
|
|
|
minval=component.low,
|
|
|
|
maxval=component.high,
|
|
|
|
dtype=component.dtype,
|
|
|
|
)
|
2020-05-08 08:26:32 +02:00
|
|
|
else:
|
|
|
|
return tf.random.normal(
|
2021-09-06 12:14:00 +02:00
|
|
|
shape=(batch_size,) + shape, dtype=component.dtype
|
2020-05-08 08:26:32 +02:00
|
|
|
)
|
2020-11-11 18:45:28 +01:00
|
|
|
else:
|
|
|
|
assert isinstance(component, Simplex), (
|
|
|
|
"Unsupported distribution component '{}' for random "
|
|
|
|
"sampling!".format(component)
|
2022-01-29 18:41:57 -08:00
|
|
|
)
|
2020-11-11 18:45:28 +01:00
|
|
|
return tf.nn.softmax(
|
|
|
|
tf.random.uniform(
|
2021-09-06 12:14:00 +02:00
|
|
|
shape=(batch_size,) + shape,
|
2020-11-11 18:45:28 +01:00
|
|
|
minval=0.0,
|
|
|
|
maxval=1.0,
|
|
|
|
dtype=component.dtype,
|
|
|
|
)
|
2022-01-29 18:41:57 -08:00
|
|
|
)
|
2020-05-08 08:26:32 +02:00
|
|
|
|
|
|
|
actions = tree.map_structure(random_component, self.action_space_struct)
|
|
|
|
return actions
|
2020-03-12 19:02:51 +01:00
|
|
|
|
|
|
|
def false_fn():
|
2020-05-08 08:26:32 +02:00
|
|
|
return action_dist.deterministic_sample()
|
2020-03-01 20:53:35 +01:00
|
|
|
|
2020-03-12 19:02:51 +01:00
|
|
|
action = tf.cond(
|
|
|
|
pred=tf.constant(explore, dtype=tf.bool)
|
|
|
|
if isinstance(explore, bool)
|
|
|
|
else explore,
|
|
|
|
true_fn=true_fn,
|
|
|
|
false_fn=false_fn,
|
|
|
|
)
|
|
|
|
|
2021-09-06 12:14:00 +02:00
|
|
|
logp = zero_logps_from_actions(action)
|
2020-02-19 21:18:45 +01:00
|
|
|
return action, logp
|
|
|
|
|
2020-10-07 21:59:14 +02:00
|
|
|
def get_torch_exploration_action(
|
|
|
|
self, action_dist: ActionDistribution, explore: bool
|
|
|
|
):
|
2020-02-19 21:18:45 +01:00
|
|
|
if explore:
|
2020-04-15 13:25:16 +02:00
|
|
|
req = force_tuple(
|
|
|
|
action_dist.required_model_output_shape(
|
2021-04-27 10:44:54 +02:00
|
|
|
self.action_space, getattr(self.model, "model_config", None)
|
|
|
|
)
|
2022-01-29 18:41:57 -08:00
|
|
|
)
|
2020-05-08 08:26:32 +02:00
|
|
|
# Add a batch dimension?
|
2020-04-15 13:25:16 +02:00
|
|
|
if len(action_dist.inputs.shape) == len(req) + 1:
|
2020-05-08 08:26:32 +02:00
|
|
|
batch_size = action_dist.inputs.shape[0]
|
|
|
|
a = np.stack([self.action_space.sample() for _ in range(batch_size)])
|
|
|
|
else:
|
|
|
|
a = self.action_space.sample()
|
|
|
|
# Convert action to torch tensor.
|
2020-04-15 13:25:16 +02:00
|
|
|
action = torch.from_numpy(a).to(self.device)
|
2020-02-19 21:18:45 +01:00
|
|
|
else:
|
2020-04-15 13:25:16 +02:00
|
|
|
action = action_dist.deterministic_sample()
|
|
|
|
logp = torch.zeros((action.size()[0],), dtype=torch.float32, device=self.device)
|
2020-02-19 21:18:45 +01:00
|
|
|
return action, logp
|