test_supported_spaces.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. from gym.spaces import Box, Dict, Discrete, Tuple, MultiDiscrete
  2. import numpy as np
  3. import unittest
  4. import ray
  5. from ray.rllib.agents.registry import get_trainer_class
  6. from ray.rllib.examples.env.random_env import RandomEnv
  7. from ray.rllib.models.tf.fcnet import FullyConnectedNetwork as FCNetV2
  8. from ray.rllib.models.tf.visionnet import VisionNetwork as VisionNetV2
  9. from ray.rllib.models.torch.visionnet import VisionNetwork as TorchVisionNetV2
  10. from ray.rllib.models.torch.fcnet import FullyConnectedNetwork as TorchFCNetV2
  11. from ray.rllib.utils.error import UnsupportedSpaceException
  12. from ray.rllib.utils.test_utils import framework_iterator
  13. ACTION_SPACES_TO_TEST = {
  14. "discrete": Discrete(5),
  15. "vector": Box(-1.0, 1.0, (5, ), dtype=np.float32),
  16. "vector2": Box(-1.0, 1.0, (5, ), dtype=np.float32),
  17. "int_actions": Box(0, 3, (2, 3), dtype=np.int32),
  18. "multidiscrete": MultiDiscrete([1, 2, 3, 4]),
  19. "tuple": Tuple(
  20. [Discrete(2),
  21. Discrete(3),
  22. Box(-1.0, 1.0, (5, ), dtype=np.float32)]),
  23. "dict": Dict({
  24. "action_choice": Discrete(3),
  25. "parameters": Box(-1.0, 1.0, (1, ), dtype=np.float32),
  26. "yet_another_nested_dict": Dict({
  27. "a": Tuple([Discrete(2), Discrete(3)])
  28. })
  29. }),
  30. }
  31. OBSERVATION_SPACES_TO_TEST = {
  32. "discrete": Discrete(5),
  33. "vector": Box(-1.0, 1.0, (5, ), dtype=np.float32),
  34. "vector2": Box(-1.0, 1.0, (5, 5), dtype=np.float32),
  35. "image": Box(-1.0, 1.0, (84, 84, 1), dtype=np.float32),
  36. "atari": Box(-1.0, 1.0, (210, 160, 3), dtype=np.float32),
  37. "tuple": Tuple([Discrete(10),
  38. Box(-1.0, 1.0, (5, ), dtype=np.float32)]),
  39. "dict": Dict({
  40. "task": Discrete(10),
  41. "position": Box(-1.0, 1.0, (5, ), dtype=np.float32),
  42. }),
  43. }
  44. def check_support(alg, config, train=True, check_bounds=False, tfe=False):
  45. config["log_level"] = "ERROR"
  46. config["train_batch_size"] = 10
  47. config["rollout_fragment_length"] = 10
  48. def _do_check(alg, config, a_name, o_name):
  49. fw = config["framework"]
  50. action_space = ACTION_SPACES_TO_TEST[a_name]
  51. obs_space = OBSERVATION_SPACES_TO_TEST[o_name]
  52. print("=== Testing {} (fw={}) A={} S={} ===".format(
  53. alg, fw, action_space, obs_space))
  54. config.update(
  55. dict(
  56. env_config=dict(
  57. action_space=action_space,
  58. observation_space=obs_space,
  59. reward_space=Box(1.0, 1.0, shape=(), dtype=np.float32),
  60. p_done=1.0,
  61. check_action_bounds=check_bounds)))
  62. stat = "ok"
  63. try:
  64. a = get_trainer_class(alg)(config=config, env=RandomEnv)
  65. except ray.exceptions.RayActorError as e:
  66. if isinstance(e.args[2], UnsupportedSpaceException):
  67. stat = "unsupported"
  68. else:
  69. raise
  70. except UnsupportedSpaceException:
  71. stat = "unsupported"
  72. else:
  73. if alg not in ["DDPG", "ES", "ARS", "SAC"]:
  74. if o_name in ["atari", "image"]:
  75. if fw == "torch":
  76. assert isinstance(a.get_policy().model,
  77. TorchVisionNetV2)
  78. else:
  79. assert isinstance(a.get_policy().model, VisionNetV2)
  80. elif o_name in ["vector", "vector2"]:
  81. if fw == "torch":
  82. assert isinstance(a.get_policy().model, TorchFCNetV2)
  83. else:
  84. assert isinstance(a.get_policy().model, FCNetV2)
  85. if train:
  86. a.train()
  87. a.stop()
  88. print(stat)
  89. frameworks = ("tf", "torch")
  90. if tfe:
  91. frameworks += ("tf2", "tfe")
  92. for _ in framework_iterator(config, frameworks=frameworks):
  93. # Zip through action- and obs-spaces.
  94. for a_name, o_name in zip(ACTION_SPACES_TO_TEST.keys(),
  95. OBSERVATION_SPACES_TO_TEST.keys()):
  96. _do_check(alg, config, a_name, o_name)
  97. # Do the remaining obs spaces.
  98. assert len(OBSERVATION_SPACES_TO_TEST) >= len(ACTION_SPACES_TO_TEST)
  99. fixed_action_key = next(iter(ACTION_SPACES_TO_TEST.keys()))
  100. for i, o_name in enumerate(OBSERVATION_SPACES_TO_TEST.keys()):
  101. if i < len(ACTION_SPACES_TO_TEST):
  102. continue
  103. _do_check(alg, config, fixed_action_key, o_name)
  104. class TestSupportedSpacesPG(unittest.TestCase):
  105. @classmethod
  106. def setUpClass(cls) -> None:
  107. ray.init()
  108. @classmethod
  109. def tearDownClass(cls) -> None:
  110. ray.shutdown()
  111. def test_a3c(self):
  112. config = {"num_workers": 1, "optimizer": {"grads_per_step": 1}}
  113. check_support("A3C", config, check_bounds=True)
  114. def test_appo(self):
  115. check_support("APPO", {"num_gpus": 0, "vtrace": False}, train=False)
  116. check_support("APPO", {"num_gpus": 0, "vtrace": True})
  117. def test_impala(self):
  118. check_support("IMPALA", {"num_gpus": 0})
  119. def test_ppo(self):
  120. config = {
  121. "num_workers": 0,
  122. "train_batch_size": 100,
  123. "rollout_fragment_length": 10,
  124. "num_sgd_iter": 1,
  125. "sgd_minibatch_size": 10,
  126. }
  127. check_support("PPO", config, check_bounds=True, tfe=True)
  128. def test_pg(self):
  129. config = {"num_workers": 1, "optimizer": {}}
  130. check_support("PG", config, train=False, check_bounds=True, tfe=True)
  131. class TestSupportedSpacesOffPolicy(unittest.TestCase):
  132. @classmethod
  133. def setUpClass(cls) -> None:
  134. ray.init(num_cpus=4)
  135. @classmethod
  136. def tearDownClass(cls) -> None:
  137. ray.shutdown()
  138. def test_ddpg(self):
  139. check_support(
  140. "DDPG", {
  141. "exploration_config": {
  142. "ou_base_scale": 100.0
  143. },
  144. "timesteps_per_iteration": 1,
  145. "buffer_size": 1000,
  146. "use_state_preprocessor": True,
  147. },
  148. check_bounds=True)
  149. def test_dqn(self):
  150. config = {"timesteps_per_iteration": 1, "buffer_size": 1000}
  151. check_support("DQN", config, tfe=True)
  152. def test_sac(self):
  153. check_support("SAC", {"buffer_size": 1000}, check_bounds=True)
  154. class TestSupportedSpacesEvolutionAlgos(unittest.TestCase):
  155. @classmethod
  156. def setUpClass(cls) -> None:
  157. ray.init(num_cpus=4)
  158. @classmethod
  159. def tearDownClass(cls) -> None:
  160. ray.shutdown()
  161. def test_ars(self):
  162. check_support(
  163. "ARS", {
  164. "num_workers": 1,
  165. "noise_size": 1500000,
  166. "num_rollouts": 1,
  167. "rollouts_used": 1
  168. })
  169. def test_es(self):
  170. check_support(
  171. "ES", {
  172. "num_workers": 1,
  173. "noise_size": 1500000,
  174. "episodes_per_batch": 1,
  175. "train_batch_size": 1
  176. })
  177. if __name__ == "__main__":
  178. import pytest
  179. import sys
  180. # One can specify the specific TestCase class to run.
  181. # None for all unittest.TestCase classes in this file.
  182. class_ = sys.argv[1] if len(sys.argv) > 1 else None
  183. sys.exit(
  184. pytest.main(
  185. ["-v", __file__ + ("" if class_ is None else "::" + class_)]))