2021-01-28 19:28:48 +01:00
|
|
|
from functools import partial
|
2017-12-28 13:19:04 -08:00
|
|
|
import gym
|
2021-01-28 19:28:48 +01:00
|
|
|
from gym.spaces import Box, Dict, Discrete
|
2017-12-28 13:19:04 -08:00
|
|
|
import numpy as np
|
|
|
|
import unittest
|
|
|
|
|
|
|
|
import ray
|
2021-01-28 19:28:48 +01:00
|
|
|
from ray.rllib.models import ActionDistribution, ModelCatalog, MODEL_DEFAULTS
|
2020-12-26 20:14:36 -05:00
|
|
|
from ray.rllib.models.preprocessors import NoPreprocessor, Preprocessor
|
2022-01-29 18:41:57 -08:00
|
|
|
from ray.rllib.models.tf.tf_action_dist import (
|
|
|
|
MultiActionDistribution,
|
|
|
|
TFActionDistribution,
|
|
|
|
)
|
2021-01-28 19:28:48 +01:00
|
|
|
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
|
2020-04-15 13:25:16 +02:00
|
|
|
from ray.rllib.utils.annotations import override
|
2020-12-03 15:51:30 +01:00
|
|
|
from ray.rllib.utils.framework import try_import_tf, try_import_torch
|
|
|
|
from ray.rllib.utils.test_utils import framework_iterator
|
2019-05-16 22:12:07 -07:00
|
|
|
|
2020-06-30 10:13:20 +02:00
|
|
|
tf1, tf, tfv = try_import_tf()
|
2020-12-03 15:51:30 +01:00
|
|
|
torch, _ = try_import_torch()
|
2017-12-28 13:19:04 -08:00
|
|
|
|
|
|
|
|
|
|
|
class CustomPreprocessor(Preprocessor):
|
2018-10-20 15:21:22 -07:00
|
|
|
def _init_shape(self, obs_space, options):
|
2019-03-25 19:00:33 -04:00
|
|
|
return [1]
|
2017-12-28 13:19:04 -08:00
|
|
|
|
|
|
|
|
|
|
|
class CustomPreprocessor2(Preprocessor):
|
2018-10-20 15:21:22 -07:00
|
|
|
def _init_shape(self, obs_space, options):
|
2019-03-25 19:00:33 -04:00
|
|
|
return [1]
|
2017-12-28 13:19:04 -08:00
|
|
|
|
|
|
|
|
2020-04-29 12:12:59 +02:00
|
|
|
class CustomModel(TFModelV2):
|
2018-06-27 22:51:04 -07:00
|
|
|
def _build_layers(self, *args):
|
2018-10-20 15:21:22 -07:00
|
|
|
return tf.constant([[0] * 5]), None
|
2017-12-28 13:19:04 -08:00
|
|
|
|
|
|
|
|
2019-08-06 18:13:16 +00:00
|
|
|
class CustomActionDistribution(TFActionDistribution):
|
2020-04-15 13:25:16 +02:00
|
|
|
def __init__(self, inputs, model):
|
|
|
|
# Store our output shape.
|
2020-05-27 10:19:47 +02:00
|
|
|
custom_model_config = model.model_config["custom_model_config"]
|
|
|
|
if "output_dim" in custom_model_config:
|
2020-04-15 13:25:16 +02:00
|
|
|
self.output_shape = tf.concat(
|
2022-01-29 18:41:57 -08:00
|
|
|
[tf.shape(inputs)[:1], custom_model_config["output_dim"]], axis=0
|
|
|
|
)
|
2020-04-15 13:25:16 +02:00
|
|
|
else:
|
|
|
|
self.output_shape = tf.shape(inputs)
|
|
|
|
super().__init__(inputs, model)
|
|
|
|
|
2019-08-06 18:13:16 +00:00
|
|
|
@staticmethod
|
|
|
|
def required_model_output_shape(action_space, model_config=None):
|
2020-05-27 10:19:47 +02:00
|
|
|
custom_model_config = model_config["custom_model_config"] or {}
|
2022-01-29 18:41:57 -08:00
|
|
|
if custom_model_config is not None and custom_model_config.get("output_dim"):
|
2020-05-27 10:19:47 +02:00
|
|
|
return custom_model_config.get("output_dim")
|
2019-08-06 18:13:16 +00:00
|
|
|
return action_space.shape
|
|
|
|
|
2020-04-15 13:25:16 +02:00
|
|
|
@override(TFActionDistribution)
|
2019-08-06 18:13:16 +00:00
|
|
|
def _build_sample_op(self):
|
2020-06-30 10:13:20 +02:00
|
|
|
return tf.random.uniform(self.output_shape)
|
2020-04-15 13:25:16 +02:00
|
|
|
|
|
|
|
@override(ActionDistribution)
|
|
|
|
def logp(self, x):
|
|
|
|
return tf.zeros(self.output_shape)
|
2019-08-06 18:13:16 +00:00
|
|
|
|
|
|
|
|
2021-01-28 19:28:48 +01:00
|
|
|
class CustomMultiActionDistribution(MultiActionDistribution):
|
|
|
|
@override(MultiActionDistribution)
|
|
|
|
def entropy(self):
|
|
|
|
raise NotImplementedError
|
|
|
|
|
|
|
|
|
2020-10-12 22:50:43 +02:00
|
|
|
class TestModelCatalog(unittest.TestCase):
|
2017-12-28 13:19:04 -08:00
|
|
|
def tearDown(self):
|
2018-07-12 14:00:00 -05:00
|
|
|
ray.shutdown()
|
2017-12-28 13:19:04 -08:00
|
|
|
|
2020-03-12 04:39:47 +01:00
|
|
|
def test_custom_preprocessor(self):
|
2019-08-26 01:37:28 -07:00
|
|
|
ray.init(object_store_memory=1000 * 1024 * 1024)
|
2017-12-28 13:19:04 -08:00
|
|
|
ModelCatalog.register_custom_preprocessor("foo", CustomPreprocessor)
|
|
|
|
ModelCatalog.register_custom_preprocessor("bar", CustomPreprocessor2)
|
|
|
|
env = gym.make("CartPole-v0")
|
2018-06-19 22:47:00 -07:00
|
|
|
p1 = ModelCatalog.get_preprocessor(env, {"custom_preprocessor": "foo"})
|
2018-01-05 21:32:41 -08:00
|
|
|
self.assertEqual(str(type(p1)), str(CustomPreprocessor))
|
2018-06-19 22:47:00 -07:00
|
|
|
p2 = ModelCatalog.get_preprocessor(env, {"custom_preprocessor": "bar"})
|
2018-01-05 21:32:41 -08:00
|
|
|
self.assertEqual(str(type(p2)), str(CustomPreprocessor2))
|
2018-06-19 22:47:00 -07:00
|
|
|
p3 = ModelCatalog.get_preprocessor(env)
|
2018-01-05 21:32:41 -08:00
|
|
|
self.assertEqual(type(p3), NoPreprocessor)
|
2017-09-16 15:53:19 -07:00
|
|
|
|
2020-03-12 04:39:47 +01:00
|
|
|
def test_default_models(self):
|
2019-08-26 01:37:28 -07:00
|
|
|
ray.init(object_store_memory=1000 * 1024 * 1024)
|
2017-09-16 15:53:19 -07:00
|
|
|
|
2020-12-03 15:51:30 +01:00
|
|
|
for fw in framework_iterator(frameworks=("jax", "tf", "tf2", "torch")):
|
2022-01-29 18:41:57 -08:00
|
|
|
obs_space = Box(0, 1, shape=(3,), dtype=np.float32)
|
2020-12-03 15:51:30 +01:00
|
|
|
p1 = ModelCatalog.get_model_v2(
|
|
|
|
obs_space=obs_space,
|
|
|
|
action_space=Discrete(5),
|
|
|
|
num_outputs=5,
|
|
|
|
model_config={},
|
|
|
|
framework=fw,
|
|
|
|
)
|
|
|
|
self.assertTrue("FullyConnectedNetwork" in type(p1).__name__)
|
|
|
|
# Do a test forward pass.
|
|
|
|
obs = np.array([obs_space.sample()])
|
|
|
|
if fw == "torch":
|
|
|
|
obs = torch.from_numpy(obs)
|
|
|
|
out, state_outs = p1({"obs": obs})
|
|
|
|
self.assertTrue(out.shape == (1, 5))
|
|
|
|
self.assertTrue(state_outs == [])
|
|
|
|
|
|
|
|
# No Conv2Ds for JAX yet.
|
|
|
|
if fw != "jax":
|
|
|
|
p2 = ModelCatalog.get_model_v2(
|
|
|
|
obs_space=Box(0, 1, shape=(84, 84, 3), dtype=np.float32),
|
|
|
|
action_space=Discrete(5),
|
|
|
|
num_outputs=5,
|
|
|
|
model_config={},
|
|
|
|
framework=fw,
|
|
|
|
)
|
|
|
|
self.assertTrue("VisionNetwork" in type(p2).__name__)
|
2017-09-16 15:53:19 -07:00
|
|
|
|
2020-03-12 04:39:47 +01:00
|
|
|
def test_custom_model(self):
|
2019-08-26 01:37:28 -07:00
|
|
|
ray.init(object_store_memory=1000 * 1024 * 1024)
|
2017-12-28 13:19:04 -08:00
|
|
|
ModelCatalog.register_custom_model("foo", CustomModel)
|
2020-04-29 12:12:59 +02:00
|
|
|
p1 = ModelCatalog.get_model_v2(
|
2022-01-29 18:41:57 -08:00
|
|
|
obs_space=Box(0, 1, shape=(3,), dtype=np.float32),
|
2020-04-29 12:12:59 +02:00
|
|
|
action_space=Discrete(5),
|
|
|
|
num_outputs=5,
|
2022-01-29 18:41:57 -08:00
|
|
|
model_config={"custom_model": "foo"},
|
|
|
|
)
|
2018-01-05 21:32:41 -08:00
|
|
|
self.assertEqual(str(type(p1)), str(CustomModel))
|
2017-10-23 23:16:52 -07:00
|
|
|
|
2020-03-12 04:39:47 +01:00
|
|
|
def test_custom_action_distribution(self):
|
2022-01-29 18:41:57 -08:00
|
|
|
class Model:
|
2019-08-10 17:59:54 -07:00
|
|
|
pass
|
|
|
|
|
2020-02-11 00:22:07 +01:00
|
|
|
ray.init(
|
2022-01-29 18:41:57 -08:00
|
|
|
object_store_memory=1000 * 1024 * 1024, ignore_reinit_error=True
|
|
|
|
) # otherwise fails sometimes locally
|
2019-08-06 18:13:16 +00:00
|
|
|
# registration
|
2022-01-29 18:41:57 -08:00
|
|
|
ModelCatalog.register_custom_action_dist("test", CustomActionDistribution)
|
2019-08-06 18:13:16 +00:00
|
|
|
action_space = Box(0, 1, shape=(5, 3), dtype=np.float32)
|
|
|
|
|
|
|
|
# test retrieving it
|
|
|
|
model_config = MODEL_DEFAULTS.copy()
|
|
|
|
model_config["custom_action_dist"] = "test"
|
2022-01-29 18:41:57 -08:00
|
|
|
dist_cls, param_shape = ModelCatalog.get_action_dist(action_space, model_config)
|
2019-08-06 18:13:16 +00:00
|
|
|
self.assertEqual(str(dist_cls), str(CustomActionDistribution))
|
|
|
|
self.assertEqual(param_shape, action_space.shape)
|
|
|
|
|
|
|
|
# test the class works as a distribution
|
2022-01-29 18:41:57 -08:00
|
|
|
dist_input = tf1.placeholder(tf.float32, (None,) + param_shape)
|
2019-08-10 17:59:54 -07:00
|
|
|
model = Model()
|
|
|
|
model.model_config = model_config
|
|
|
|
dist = dist_cls(dist_input, model=model)
|
2019-08-06 18:13:16 +00:00
|
|
|
self.assertEqual(dist.sample().shape[1:], dist_input.shape[1:])
|
|
|
|
self.assertIsInstance(dist.sample(), tf.Tensor)
|
|
|
|
with self.assertRaises(NotImplementedError):
|
|
|
|
dist.entropy()
|
|
|
|
|
|
|
|
# test passing the options to it
|
2022-01-29 18:41:57 -08:00
|
|
|
model_config["custom_model_config"].update({"output_dim": (3,)})
|
|
|
|
dist_cls, param_shape = ModelCatalog.get_action_dist(action_space, model_config)
|
|
|
|
self.assertEqual(param_shape, (3,))
|
|
|
|
dist_input = tf1.placeholder(tf.float32, (None,) + param_shape)
|
2019-08-10 17:59:54 -07:00
|
|
|
model.model_config = model_config
|
|
|
|
dist = dist_cls(dist_input, model=model)
|
2019-08-06 18:13:16 +00:00
|
|
|
self.assertEqual(dist.sample().shape[1:], dist_input.shape[1:])
|
|
|
|
self.assertIsInstance(dist.sample(), tf.Tensor)
|
|
|
|
with self.assertRaises(NotImplementedError):
|
|
|
|
dist.entropy()
|
|
|
|
|
2021-01-28 19:28:48 +01:00
|
|
|
def test_custom_multi_action_distribution(self):
|
2022-01-29 18:41:57 -08:00
|
|
|
class Model:
|
2021-01-28 19:28:48 +01:00
|
|
|
pass
|
|
|
|
|
|
|
|
ray.init(
|
2022-01-29 18:41:57 -08:00
|
|
|
object_store_memory=1000 * 1024 * 1024, ignore_reinit_error=True
|
|
|
|
) # otherwise fails sometimes locally
|
2021-01-28 19:28:48 +01:00
|
|
|
# registration
|
2022-01-29 18:41:57 -08:00
|
|
|
ModelCatalog.register_custom_action_dist("test", CustomMultiActionDistribution)
|
2021-01-28 19:28:48 +01:00
|
|
|
s1 = Discrete(5)
|
2022-01-29 18:41:57 -08:00
|
|
|
s2 = Box(0, 1, shape=(3,), dtype=np.float32)
|
2021-01-28 19:28:48 +01:00
|
|
|
spaces = dict(action_1=s1, action_2=s2)
|
|
|
|
action_space = Dict(spaces)
|
|
|
|
# test retrieving it
|
|
|
|
model_config = MODEL_DEFAULTS.copy()
|
|
|
|
model_config["custom_action_dist"] = "test"
|
2022-01-29 18:41:57 -08:00
|
|
|
dist_cls, param_shape = ModelCatalog.get_action_dist(action_space, model_config)
|
2021-01-28 19:28:48 +01:00
|
|
|
self.assertIsInstance(dist_cls, partial)
|
|
|
|
self.assertEqual(param_shape, s1.n + 2 * s2.shape[0])
|
|
|
|
|
|
|
|
# test the class works as a distribution
|
|
|
|
dist_input = tf1.placeholder(tf.float32, (None, param_shape))
|
|
|
|
model = Model()
|
|
|
|
model.model_config = model_config
|
|
|
|
dist = dist_cls(dist_input, model=model)
|
|
|
|
self.assertIsInstance(dist.sample(), dict)
|
|
|
|
self.assertIn("action_1", dist.sample())
|
|
|
|
self.assertIn("action_2", dist.sample())
|
|
|
|
self.assertEqual(dist.sample()["action_1"].dtype, tf.int64)
|
|
|
|
self.assertEqual(dist.sample()["action_2"].shape[1:], s2.shape)
|
|
|
|
|
|
|
|
with self.assertRaises(NotImplementedError):
|
|
|
|
dist.entropy()
|
|
|
|
|
2017-10-23 23:16:52 -07:00
|
|
|
|
2017-12-28 13:19:04 -08:00
|
|
|
if __name__ == "__main__":
|
2020-03-12 04:39:47 +01:00
|
|
|
import pytest
|
|
|
|
import sys
|
2022-01-29 18:41:57 -08:00
|
|
|
|
2020-03-12 04:39:47 +01:00
|
|
|
sys.exit(pytest.main(["-v", __file__]))
|