test_nested_observation_spaces.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. from gym import spaces
  2. from gym.envs.registration import EnvSpec
  3. import gym
  4. import numpy as np
  5. import pickle
  6. import unittest
  7. import ray
  8. from ray.rllib.agents.a3c import A2CTrainer
  9. from ray.rllib.agents.pg import PGTrainer
  10. from ray.rllib.env import MultiAgentEnv
  11. from ray.rllib.env.base_env import convert_to_base_env
  12. from ray.rllib.env.vector_env import VectorEnv
  13. from ray.rllib.models import ModelCatalog
  14. from ray.rllib.models.tf.tf_modelv2 import TFModelV2
  15. from ray.rllib.models.torch.fcnet import FullyConnectedNetwork
  16. from ray.rllib.models.torch.torch_modelv2 import TorchModelV2
  17. from ray.rllib.evaluate import rollout
  18. from ray.rllib.tests.test_external_env import SimpleServing
  19. from ray.tune.registry import register_env
  20. from ray.rllib.utils.framework import try_import_tf, try_import_torch
  21. from ray.rllib.utils.numpy import one_hot
  22. from ray.rllib.utils.spaces.repeated import Repeated
  23. from ray.rllib.utils.test_utils import check
  24. tf1, tf, tfv = try_import_tf()
  25. _, nn = try_import_torch()
  26. DICT_SPACE = spaces.Dict({
  27. "sensors": spaces.Dict({
  28. "position": spaces.Box(low=-100, high=100, shape=(3, )),
  29. "velocity": spaces.Box(low=-1, high=1, shape=(3, )),
  30. "front_cam": spaces.Tuple(
  31. (spaces.Box(low=0, high=1, shape=(10, 10, 3)),
  32. spaces.Box(low=0, high=1, shape=(10, 10, 3)))),
  33. "rear_cam": spaces.Box(low=0, high=1, shape=(10, 10, 3)),
  34. }),
  35. "inner_state": spaces.Dict({
  36. "charge": spaces.Discrete(100),
  37. "job_status": spaces.Dict({
  38. "task": spaces.Discrete(5),
  39. "progress": spaces.Box(low=0, high=100, shape=()),
  40. })
  41. })
  42. })
  43. DICT_SAMPLES = [DICT_SPACE.sample() for _ in range(10)]
  44. TUPLE_SPACE = spaces.Tuple([
  45. spaces.Box(low=-100, high=100, shape=(3, )),
  46. spaces.Tuple((spaces.Box(low=0, high=1, shape=(10, 10, 3)),
  47. spaces.Box(low=0, high=1, shape=(10, 10, 3)))),
  48. spaces.Discrete(5),
  49. ])
  50. TUPLE_SAMPLES = [TUPLE_SPACE.sample() for _ in range(10)]
  51. # Constraints on the Repeated space.
  52. MAX_PLAYERS = 4
  53. MAX_ITEMS = 7
  54. MAX_EFFECTS = 2
  55. ITEM_SPACE = spaces.Box(-5, 5, shape=(1, ))
  56. EFFECT_SPACE = spaces.Box(9000, 9999, shape=(4, ))
  57. PLAYER_SPACE = spaces.Dict({
  58. "location": spaces.Box(-100, 100, shape=(2, )),
  59. "items": Repeated(ITEM_SPACE, max_len=MAX_ITEMS),
  60. "effects": Repeated(EFFECT_SPACE, max_len=MAX_EFFECTS),
  61. "status": spaces.Box(-1, 1, shape=(10, )),
  62. })
  63. REPEATED_SPACE = Repeated(PLAYER_SPACE, max_len=MAX_PLAYERS)
  64. REPEATED_SAMPLES = [REPEATED_SPACE.sample() for _ in range(10)]
  65. class NestedDictEnv(gym.Env):
  66. def __init__(self):
  67. self.action_space = spaces.Discrete(2)
  68. self.observation_space = DICT_SPACE
  69. self._spec = EnvSpec("NestedDictEnv-v0")
  70. self.steps = 0
  71. def reset(self):
  72. self.steps = 0
  73. return DICT_SAMPLES[0]
  74. def step(self, action):
  75. self.steps += 1
  76. return DICT_SAMPLES[self.steps], 1, self.steps >= 5, {}
  77. class NestedTupleEnv(gym.Env):
  78. def __init__(self):
  79. self.action_space = spaces.Discrete(2)
  80. self.observation_space = TUPLE_SPACE
  81. self._spec = EnvSpec("NestedTupleEnv-v0")
  82. self.steps = 0
  83. def reset(self):
  84. self.steps = 0
  85. return TUPLE_SAMPLES[0]
  86. def step(self, action):
  87. self.steps += 1
  88. return TUPLE_SAMPLES[self.steps], 1, self.steps >= 5, {}
  89. class RepeatedSpaceEnv(gym.Env):
  90. def __init__(self):
  91. self.action_space = spaces.Discrete(2)
  92. self.observation_space = REPEATED_SPACE
  93. self._spec = EnvSpec("RepeatedSpaceEnv-v0")
  94. self.steps = 0
  95. def reset(self):
  96. self.steps = 0
  97. return REPEATED_SAMPLES[0]
  98. def step(self, action):
  99. self.steps += 1
  100. return REPEATED_SAMPLES[self.steps], 1, self.steps >= 5, {}
  101. class NestedMultiAgentEnv(MultiAgentEnv):
  102. def __init__(self):
  103. super().__init__()
  104. self.observation_space = spaces.Dict({
  105. "dict_agent": DICT_SPACE,
  106. "tuple_agent": TUPLE_SPACE
  107. })
  108. self.action_space = spaces.Dict({
  109. "dict_agent": spaces.Discrete(1),
  110. "tuple_agent": spaces.Discrete(1)
  111. })
  112. self._agent_ids = {"dict_agent", "tuple_agent"}
  113. self.steps = 0
  114. def reset(self):
  115. return {
  116. "dict_agent": DICT_SAMPLES[0],
  117. "tuple_agent": TUPLE_SAMPLES[0],
  118. }
  119. def step(self, actions):
  120. self.steps += 1
  121. obs = {
  122. "dict_agent": DICT_SAMPLES[self.steps],
  123. "tuple_agent": TUPLE_SAMPLES[self.steps],
  124. }
  125. rew = {
  126. "dict_agent": 0,
  127. "tuple_agent": 0,
  128. }
  129. dones = {"__all__": self.steps >= 5}
  130. infos = {
  131. "dict_agent": {},
  132. "tuple_agent": {},
  133. }
  134. return obs, rew, dones, infos
  135. class InvalidModel(TorchModelV2):
  136. def forward(self, input_dict, state, seq_lens):
  137. return "not", "valid"
  138. class InvalidModel2(TFModelV2):
  139. def forward(self, input_dict, state, seq_lens):
  140. return tf.constant(0), tf.constant(0)
  141. class TorchSpyModel(TorchModelV2, nn.Module):
  142. capture_index = 0
  143. def __init__(self, obs_space, action_space, num_outputs, model_config,
  144. name):
  145. TorchModelV2.__init__(self, obs_space, action_space, num_outputs,
  146. model_config, name)
  147. nn.Module.__init__(self)
  148. self.fc = FullyConnectedNetwork(
  149. obs_space.original_space["sensors"].spaces["position"],
  150. action_space, num_outputs, model_config, name)
  151. def forward(self, input_dict, state, seq_lens):
  152. pos = input_dict["obs"]["sensors"]["position"].detach().cpu().numpy()
  153. front_cam = input_dict["obs"]["sensors"]["front_cam"][
  154. 0].detach().cpu().numpy()
  155. task = input_dict["obs"]["inner_state"]["job_status"][
  156. "task"].detach().cpu().numpy()
  157. ray.experimental.internal_kv._internal_kv_put(
  158. "torch_spy_in_{}".format(TorchSpyModel.capture_index),
  159. pickle.dumps((pos, front_cam, task)),
  160. overwrite=True)
  161. TorchSpyModel.capture_index += 1
  162. return self.fc({
  163. "obs": input_dict["obs"]["sensors"]["position"]
  164. }, state, seq_lens)
  165. def value_function(self):
  166. return self.fc.value_function()
  167. class TorchRepeatedSpyModel(TorchModelV2, nn.Module):
  168. capture_index = 0
  169. def __init__(self, obs_space, action_space, num_outputs, model_config,
  170. name):
  171. TorchModelV2.__init__(self, obs_space, action_space, num_outputs,
  172. model_config, name)
  173. nn.Module.__init__(self)
  174. self.fc = FullyConnectedNetwork(
  175. obs_space.original_space.child_space["location"], action_space,
  176. num_outputs, model_config, name)
  177. def forward(self, input_dict, state, seq_lens):
  178. ray.experimental.internal_kv._internal_kv_put(
  179. "torch_rspy_in_{}".format(TorchRepeatedSpyModel.capture_index),
  180. pickle.dumps(input_dict["obs"].unbatch_all()),
  181. overwrite=True)
  182. TorchRepeatedSpyModel.capture_index += 1
  183. return self.fc({
  184. "obs": input_dict["obs"].values["location"][:, 0]
  185. }, state, seq_lens)
  186. def value_function(self):
  187. return self.fc.value_function()
  188. def to_list(value):
  189. if isinstance(value, list):
  190. return [to_list(x) for x in value]
  191. elif isinstance(value, dict):
  192. return {k: to_list(v) for k, v in value.items()}
  193. elif isinstance(value, np.ndarray):
  194. return value.tolist()
  195. elif isinstance(value, int):
  196. return value
  197. else:
  198. return value.detach().cpu().numpy().tolist()
  199. class DictSpyModel(TFModelV2):
  200. capture_index = 0
  201. def __init__(self, obs_space, action_space, num_outputs, model_config,
  202. name):
  203. super().__init__(obs_space, action_space, None, model_config, name)
  204. # Will only feed in sensors->pos.
  205. input_ = tf.keras.layers.Input(
  206. shape=self.obs_space["sensors"]["position"].shape)
  207. self.num_outputs = num_outputs or 64
  208. out = tf.keras.layers.Dense(self.num_outputs)(input_)
  209. self._main_layer = tf.keras.models.Model([input_], [out])
  210. def forward(self, input_dict, state, seq_lens):
  211. def spy(pos, front_cam, task):
  212. # TF runs this function in an isolated context, so we have to use
  213. # redis to communicate back to our suite
  214. ray.experimental.internal_kv._internal_kv_put(
  215. "d_spy_in_{}".format(DictSpyModel.capture_index),
  216. pickle.dumps((pos, front_cam, task)),
  217. overwrite=True)
  218. DictSpyModel.capture_index += 1
  219. return np.array(0, dtype=np.int64)
  220. spy_fn = tf1.py_func(
  221. spy, [
  222. input_dict["obs"]["sensors"]["position"],
  223. input_dict["obs"]["sensors"]["front_cam"][0],
  224. input_dict["obs"]["inner_state"]["job_status"]["task"]
  225. ],
  226. tf.int64,
  227. stateful=True)
  228. with tf1.control_dependencies([spy_fn]):
  229. output = self._main_layer(
  230. [input_dict["obs"]["sensors"]["position"]])
  231. return output, []
  232. class TupleSpyModel(TFModelV2):
  233. capture_index = 0
  234. def __init__(self, obs_space, action_space, num_outputs, model_config,
  235. name):
  236. super().__init__(obs_space, action_space, None, model_config, name)
  237. # Will only feed in 0th index of observation Tuple space.
  238. input_ = tf.keras.layers.Input(shape=self.obs_space[0].shape)
  239. self.num_outputs = num_outputs or 64
  240. out = tf.keras.layers.Dense(self.num_outputs)(input_)
  241. self._main_layer = tf.keras.models.Model([input_], [out])
  242. def forward(self, input_dict, state, seq_lens):
  243. def spy(pos, cam, task):
  244. # TF runs this function in an isolated context, so we have to use
  245. # redis to communicate back to our suite
  246. ray.experimental.internal_kv._internal_kv_put(
  247. "t_spy_in_{}".format(TupleSpyModel.capture_index),
  248. pickle.dumps((pos, cam, task)),
  249. overwrite=True)
  250. TupleSpyModel.capture_index += 1
  251. return np.array(0, dtype=np.int64)
  252. spy_fn = tf1.py_func(
  253. spy, [
  254. input_dict["obs"][0],
  255. input_dict["obs"][1][0],
  256. input_dict["obs"][2],
  257. ],
  258. tf.int64,
  259. stateful=True)
  260. with tf1.control_dependencies([spy_fn]):
  261. output = tf1.layers.dense(input_dict["obs"][0], self.num_outputs)
  262. return output, []
  263. class NestedObservationSpacesTest(unittest.TestCase):
  264. @classmethod
  265. def setUpClass(cls):
  266. ray.init(num_cpus=5)
  267. @classmethod
  268. def tearDownClass(cls):
  269. ray.shutdown()
  270. def test_invalid_model(self):
  271. ModelCatalog.register_custom_model("invalid", InvalidModel)
  272. self.assertRaisesRegex(
  273. ValueError,
  274. "Subclasses of TorchModelV2 must also inherit from nn.Module",
  275. lambda: PGTrainer(
  276. env="CartPole-v0",
  277. config={
  278. "model": {
  279. "custom_model": "invalid",
  280. },
  281. "framework": "torch",
  282. }))
  283. def test_invalid_model2(self):
  284. ModelCatalog.register_custom_model("invalid2", InvalidModel2)
  285. self.assertRaisesRegex(
  286. ValueError, "State output is not a list",
  287. lambda: PGTrainer(
  288. env="CartPole-v0", config={
  289. "model": {
  290. "custom_model": "invalid2",
  291. },
  292. "framework": "tf",
  293. }))
  294. def do_test_nested_dict(self, make_env, test_lstm=False):
  295. ModelCatalog.register_custom_model("composite", DictSpyModel)
  296. register_env("nested", make_env)
  297. pg = PGTrainer(
  298. env="nested",
  299. config={
  300. "num_workers": 0,
  301. "rollout_fragment_length": 5,
  302. "train_batch_size": 5,
  303. "model": {
  304. "custom_model": "composite",
  305. "use_lstm": test_lstm,
  306. },
  307. "framework": "tf",
  308. })
  309. # Skip first passes as they came from the TorchPolicy loss
  310. # initialization.
  311. DictSpyModel.capture_index = 0
  312. pg.train()
  313. # Check that the model sees the correct reconstructed observations
  314. for i in range(4):
  315. seen = pickle.loads(
  316. ray.experimental.internal_kv._internal_kv_get(
  317. "d_spy_in_{}".format(i)))
  318. pos_i = DICT_SAMPLES[i]["sensors"]["position"].tolist()
  319. cam_i = DICT_SAMPLES[i]["sensors"]["front_cam"][0].tolist()
  320. task_i = DICT_SAMPLES[i]["inner_state"]["job_status"]["task"]
  321. self.assertEqual(seen[0][0].tolist(), pos_i)
  322. self.assertEqual(seen[1][0].tolist(), cam_i)
  323. check(seen[2][0], task_i)
  324. def do_test_nested_tuple(self, make_env):
  325. ModelCatalog.register_custom_model("composite2", TupleSpyModel)
  326. register_env("nested2", make_env)
  327. pg = PGTrainer(
  328. env="nested2",
  329. config={
  330. "num_workers": 0,
  331. "rollout_fragment_length": 5,
  332. "train_batch_size": 5,
  333. "model": {
  334. "custom_model": "composite2",
  335. },
  336. "framework": "tf",
  337. })
  338. # Skip first passes as they came from the TorchPolicy loss
  339. # initialization.
  340. TupleSpyModel.capture_index = 0
  341. pg.train()
  342. # Check that the model sees the correct reconstructed observations
  343. for i in range(4):
  344. seen = pickle.loads(
  345. ray.experimental.internal_kv._internal_kv_get(
  346. "t_spy_in_{}".format(i)))
  347. pos_i = TUPLE_SAMPLES[i][0].tolist()
  348. cam_i = TUPLE_SAMPLES[i][1][0].tolist()
  349. task_i = TUPLE_SAMPLES[i][2]
  350. self.assertEqual(seen[0][0].tolist(), pos_i)
  351. self.assertEqual(seen[1][0].tolist(), cam_i)
  352. check(seen[2][0], task_i)
  353. def test_nested_dict_gym(self):
  354. self.do_test_nested_dict(lambda _: NestedDictEnv())
  355. def test_nested_dict_gym_lstm(self):
  356. self.do_test_nested_dict(lambda _: NestedDictEnv(), test_lstm=True)
  357. def test_nested_dict_vector(self):
  358. self.do_test_nested_dict(
  359. lambda _: VectorEnv.vectorize_gym_envs(lambda i: NestedDictEnv()))
  360. def test_nested_dict_serving(self):
  361. self.do_test_nested_dict(lambda _: SimpleServing(NestedDictEnv()))
  362. def test_nested_dict_async(self):
  363. self.do_test_nested_dict(
  364. lambda _: convert_to_base_env(NestedDictEnv()))
  365. def test_nested_tuple_gym(self):
  366. self.do_test_nested_tuple(lambda _: NestedTupleEnv())
  367. def test_nested_tuple_vector(self):
  368. self.do_test_nested_tuple(
  369. lambda _: VectorEnv.vectorize_gym_envs(lambda i: NestedTupleEnv()))
  370. def test_nested_tuple_serving(self):
  371. self.do_test_nested_tuple(lambda _: SimpleServing(NestedTupleEnv()))
  372. def test_nested_tuple_async(self):
  373. self.do_test_nested_tuple(
  374. lambda _: convert_to_base_env(NestedTupleEnv()))
  375. def test_multi_agent_complex_spaces(self):
  376. ModelCatalog.register_custom_model("dict_spy", DictSpyModel)
  377. ModelCatalog.register_custom_model("tuple_spy", TupleSpyModel)
  378. register_env("nested_ma", lambda _: NestedMultiAgentEnv())
  379. act_space = spaces.Discrete(2)
  380. pg = PGTrainer(
  381. env="nested_ma",
  382. config={
  383. "num_workers": 0,
  384. "rollout_fragment_length": 5,
  385. "train_batch_size": 5,
  386. "multiagent": {
  387. "policies": {
  388. "tuple_policy": (
  389. None, TUPLE_SPACE, act_space,
  390. {"model": {"custom_model": "tuple_spy"}}),
  391. "dict_policy": (
  392. None, DICT_SPACE, act_space,
  393. {"model": {"custom_model": "dict_spy"}}),
  394. },
  395. "policy_mapping_fn": lambda aid, **kwargs: {
  396. "tuple_agent": "tuple_policy",
  397. "dict_agent": "dict_policy"}[aid],
  398. },
  399. "framework": "tf",
  400. })
  401. # Skip first passes as they came from the TorchPolicy loss
  402. # initialization.
  403. TupleSpyModel.capture_index = DictSpyModel.capture_index = 0
  404. pg.train()
  405. for i in range(4):
  406. seen = pickle.loads(
  407. ray.experimental.internal_kv._internal_kv_get(
  408. "d_spy_in_{}".format(i)))
  409. pos_i = DICT_SAMPLES[i]["sensors"]["position"].tolist()
  410. cam_i = DICT_SAMPLES[i]["sensors"]["front_cam"][0].tolist()
  411. task_i = DICT_SAMPLES[i]["inner_state"]["job_status"]["task"]
  412. self.assertEqual(seen[0][0].tolist(), pos_i)
  413. self.assertEqual(seen[1][0].tolist(), cam_i)
  414. check(seen[2][0], task_i)
  415. for i in range(4):
  416. seen = pickle.loads(
  417. ray.experimental.internal_kv._internal_kv_get(
  418. "t_spy_in_{}".format(i)))
  419. pos_i = TUPLE_SAMPLES[i][0].tolist()
  420. cam_i = TUPLE_SAMPLES[i][1][0].tolist()
  421. task_i = TUPLE_SAMPLES[i][2]
  422. self.assertEqual(seen[0][0].tolist(), pos_i)
  423. self.assertEqual(seen[1][0].tolist(), cam_i)
  424. check(seen[2][0], task_i)
  425. def test_rollout_dict_space(self):
  426. register_env("nested", lambda _: NestedDictEnv())
  427. agent = PGTrainer(env="nested", config={"framework": "tf"})
  428. agent.train()
  429. path = agent.save()
  430. agent.stop()
  431. # Test train works on restore
  432. agent2 = PGTrainer(env="nested", config={"framework": "tf"})
  433. agent2.restore(path)
  434. agent2.train()
  435. # Test rollout works on restore
  436. rollout(agent2, "nested", 100)
  437. def test_py_torch_model(self):
  438. ModelCatalog.register_custom_model("composite", TorchSpyModel)
  439. register_env("nested", lambda _: NestedDictEnv())
  440. a2c = A2CTrainer(
  441. env="nested",
  442. config={
  443. "num_workers": 0,
  444. "rollout_fragment_length": 5,
  445. "train_batch_size": 5,
  446. "model": {
  447. "custom_model": "composite",
  448. },
  449. "framework": "torch",
  450. })
  451. # Skip first passes as they came from the TorchPolicy loss
  452. # initialization.
  453. TorchSpyModel.capture_index = 0
  454. a2c.train()
  455. # Check that the model sees the correct reconstructed observations
  456. for i in range(4):
  457. seen = pickle.loads(
  458. ray.experimental.internal_kv._internal_kv_get(
  459. "torch_spy_in_{}".format(i)))
  460. pos_i = DICT_SAMPLES[i]["sensors"]["position"].tolist()
  461. cam_i = DICT_SAMPLES[i]["sensors"]["front_cam"][0].tolist()
  462. task_i = one_hot(
  463. DICT_SAMPLES[i]["inner_state"]["job_status"]["task"], 5)
  464. # Only look at the last entry (-1) in `seen` as we reset (re-use)
  465. # the ray-kv indices before training.
  466. self.assertEqual(seen[0][-1].tolist(), pos_i)
  467. self.assertEqual(seen[1][-1].tolist(), cam_i)
  468. check(seen[2][-1], task_i)
  469. # TODO(ekl) should probably also add a test for TF/eager
  470. def test_torch_repeated(self):
  471. ModelCatalog.register_custom_model("r1", TorchRepeatedSpyModel)
  472. register_env("repeat", lambda _: RepeatedSpaceEnv())
  473. a2c = A2CTrainer(
  474. env="repeat",
  475. config={
  476. "num_workers": 0,
  477. "rollout_fragment_length": 5,
  478. "train_batch_size": 5,
  479. "model": {
  480. "custom_model": "r1",
  481. },
  482. "framework": "torch",
  483. })
  484. # Skip first passes as they came from the TorchPolicy loss
  485. # initialization.
  486. TorchRepeatedSpyModel.capture_index = 0
  487. a2c.train()
  488. # Check that the model sees the correct reconstructed observations
  489. for i in range(4):
  490. seen = pickle.loads(
  491. ray.experimental.internal_kv._internal_kv_get(
  492. "torch_rspy_in_{}".format(i)))
  493. # Only look at the last entry (-1) in `seen` as we reset (re-use)
  494. # the ray-kv indices before training.
  495. self.assertEqual(
  496. to_list(seen[:][-1]), to_list(REPEATED_SAMPLES[i]))
  497. if __name__ == "__main__":
  498. import pytest
  499. import sys
  500. sys.exit(pytest.main(["-v", __file__]))