test_compute_log_likelihoods.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. import numpy as np
  2. from scipy.stats import norm
  3. import unittest
  4. import ray
  5. import ray.rllib.agents.dqn as dqn
  6. import ray.rllib.agents.pg as pg
  7. import ray.rllib.agents.ppo as ppo
  8. import ray.rllib.agents.sac as sac
  9. from ray.rllib.utils.framework import try_import_tf
  10. from ray.rllib.utils.test_utils import check, framework_iterator
  11. from ray.rllib.utils.numpy import one_hot, fc, MIN_LOG_NN_OUTPUT, \
  12. MAX_LOG_NN_OUTPUT
  13. tf1, tf, tfv = try_import_tf()
  14. def do_test_log_likelihood(run,
  15. config,
  16. prev_a=None,
  17. continuous=False,
  18. layer_key=("fc", (0, 4), ("_hidden_layers.0.",
  19. "_logits.")),
  20. logp_func=None):
  21. config = config.copy()
  22. # Run locally.
  23. config["num_workers"] = 0
  24. # Env setup.
  25. if continuous:
  26. env = "Pendulum-v1"
  27. obs_batch = preprocessed_obs_batch = np.array([[0.0, 0.1, -0.1]])
  28. else:
  29. env = "FrozenLake-v1"
  30. config["env_config"] = {"is_slippery": False, "map_name": "4x4"}
  31. obs_batch = np.array([0])
  32. # PG does not preprocess anymore by default.
  33. preprocessed_obs_batch = one_hot(obs_batch, depth=16) \
  34. if run is not pg.PGTrainer else obs_batch
  35. prev_r = None if prev_a is None else np.array(0.0)
  36. # Test against all frameworks.
  37. for fw in framework_iterator(config):
  38. trainer = run(config=config, env=env)
  39. policy = trainer.get_policy()
  40. vars = policy.get_weights()
  41. # Sample n actions, then roughly check their logp against their
  42. # counts.
  43. num_actions = 1000 if not continuous else 50
  44. actions = []
  45. for _ in range(num_actions):
  46. # Single action from single obs.
  47. actions.append(
  48. trainer.compute_single_action(
  49. obs_batch[0],
  50. prev_action=prev_a,
  51. prev_reward=prev_r,
  52. explore=True,
  53. # Do not unsquash actions
  54. # (remain in normalized [-1.0; 1.0] space).
  55. unsquash_action=False,
  56. ))
  57. # Test all taken actions for their log-likelihoods vs expected values.
  58. if continuous:
  59. for idx in range(num_actions):
  60. a = actions[idx]
  61. if fw != "torch":
  62. if isinstance(vars, list):
  63. expected_mean_logstd = fc(
  64. fc(obs_batch, vars[layer_key[1][0]]),
  65. vars[layer_key[1][1]])
  66. else:
  67. expected_mean_logstd = fc(
  68. fc(
  69. obs_batch,
  70. vars["default_policy/{}_1/kernel".format(
  71. layer_key[0])]),
  72. vars["default_policy/{}_out/kernel".format(
  73. layer_key[0])])
  74. else:
  75. expected_mean_logstd = fc(
  76. fc(obs_batch,
  77. vars["{}_model.0.weight".format(layer_key[2][0])],
  78. framework=fw),
  79. vars["{}_model.0.weight".format(layer_key[2][1])],
  80. framework=fw)
  81. mean, log_std = np.split(expected_mean_logstd, 2, axis=-1)
  82. if logp_func is None:
  83. expected_logp = np.log(norm.pdf(a, mean, np.exp(log_std)))
  84. else:
  85. expected_logp = logp_func(mean, log_std, a)
  86. logp = policy.compute_log_likelihoods(
  87. np.array([a]),
  88. preprocessed_obs_batch,
  89. prev_action_batch=np.array([prev_a]) if prev_a else None,
  90. prev_reward_batch=np.array([prev_r]) if prev_r else None,
  91. actions_normalized=True,
  92. )
  93. check(logp, expected_logp[0], rtol=0.2)
  94. # Test all available actions for their logp values.
  95. else:
  96. for a in [0, 1, 2, 3]:
  97. count = actions.count(a)
  98. expected_prob = count / num_actions
  99. logp = policy.compute_log_likelihoods(
  100. np.array([a]),
  101. preprocessed_obs_batch,
  102. prev_action_batch=np.array([prev_a]) if prev_a else None,
  103. prev_reward_batch=np.array([prev_r]) if prev_r else None)
  104. check(np.exp(logp), expected_prob, atol=0.2)
  105. class TestComputeLogLikelihood(unittest.TestCase):
  106. @classmethod
  107. def setUpClass(cls) -> None:
  108. ray.init()
  109. @classmethod
  110. def tearDownClass(cls) -> None:
  111. ray.shutdown()
  112. def test_dqn(self):
  113. """Tests, whether DQN correctly computes logp in soft-q mode."""
  114. config = dqn.DEFAULT_CONFIG.copy()
  115. # Soft-Q for DQN.
  116. config["exploration_config"] = {"type": "SoftQ", "temperature": 0.5}
  117. config["seed"] = 42
  118. do_test_log_likelihood(dqn.DQNTrainer, config)
  119. def test_pg_cont(self):
  120. """Tests PG's (cont. actions) compute_log_likelihoods method."""
  121. config = pg.DEFAULT_CONFIG.copy()
  122. config["seed"] = 42
  123. config["model"]["fcnet_hiddens"] = [10]
  124. config["model"]["fcnet_activation"] = "linear"
  125. prev_a = np.array([0.0])
  126. do_test_log_likelihood(
  127. pg.PGTrainer,
  128. config,
  129. prev_a,
  130. continuous=True,
  131. layer_key=("fc", (0, 2), ("_hidden_layers.0.", "_logits.")))
  132. def test_pg_discr(self):
  133. """Tests PG's (cont. actions) compute_log_likelihoods method."""
  134. config = pg.DEFAULT_CONFIG.copy()
  135. config["seed"] = 42
  136. prev_a = np.array(0)
  137. do_test_log_likelihood(pg.PGTrainer, config, prev_a)
  138. def test_ppo_cont(self):
  139. """Tests PPO's (cont. actions) compute_log_likelihoods method."""
  140. config = ppo.DEFAULT_CONFIG.copy()
  141. config["seed"] = 42
  142. config["model"]["fcnet_hiddens"] = [10]
  143. config["model"]["fcnet_activation"] = "linear"
  144. prev_a = np.array([0.0])
  145. do_test_log_likelihood(ppo.PPOTrainer, config, prev_a, continuous=True)
  146. def test_ppo_discr(self):
  147. """Tests PPO's (discr. actions) compute_log_likelihoods method."""
  148. config = ppo.DEFAULT_CONFIG.copy()
  149. config["seed"] = 42
  150. prev_a = np.array(0)
  151. do_test_log_likelihood(ppo.PPOTrainer, config, prev_a)
  152. def test_sac_cont(self):
  153. """Tests SAC's (cont. actions) compute_log_likelihoods method."""
  154. config = sac.DEFAULT_CONFIG.copy()
  155. config["seed"] = 42
  156. config["policy_model"]["fcnet_hiddens"] = [10]
  157. config["policy_model"]["fcnet_activation"] = "linear"
  158. prev_a = np.array([0.0])
  159. # SAC cont uses a squashed normal distribution. Implement it's logp
  160. # logic here in numpy for comparing results.
  161. def logp_func(means, log_stds, values, low=-1.0, high=1.0):
  162. stds = np.exp(
  163. np.clip(log_stds, MIN_LOG_NN_OUTPUT, MAX_LOG_NN_OUTPUT))
  164. unsquashed_values = np.arctanh((values - low) /
  165. (high - low) * 2.0 - 1.0)
  166. log_prob_unsquashed = \
  167. np.sum(np.log(norm.pdf(unsquashed_values, means, stds)), -1)
  168. return log_prob_unsquashed - \
  169. np.sum(np.log(1 - np.tanh(unsquashed_values) ** 2),
  170. axis=-1)
  171. do_test_log_likelihood(
  172. sac.SACTrainer,
  173. config,
  174. prev_a,
  175. continuous=True,
  176. layer_key=("fc", (0, 2), ("action_model._hidden_layers.0.",
  177. "action_model._logits.")),
  178. logp_func=logp_func)
  179. def test_sac_discr(self):
  180. """Tests SAC's (discrete actions) compute_log_likelihoods method."""
  181. config = sac.DEFAULT_CONFIG.copy()
  182. config["seed"] = 42
  183. config["policy_model"]["fcnet_hiddens"] = [10]
  184. config["policy_model"]["fcnet_activation"] = "linear"
  185. prev_a = np.array(0)
  186. do_test_log_likelihood(sac.SACTrainer, config, prev_a)
  187. if __name__ == "__main__":
  188. import pytest
  189. import sys
  190. sys.exit(pytest.main(["-v", __file__]))