2020-02-22 23:19:49 +01:00
|
|
|
import numpy as np
|
|
|
|
from scipy.stats import norm
|
|
|
|
import unittest
|
|
|
|
|
2020-12-07 13:08:17 +01:00
|
|
|
import ray
|
2020-02-22 23:19:49 +01:00
|
|
|
import ray.rllib.agents.dqn as dqn
|
2020-03-12 04:39:47 +01:00
|
|
|
import ray.rllib.agents.pg as pg
|
2020-02-22 23:19:49 +01:00
|
|
|
import ray.rllib.agents.ppo as ppo
|
|
|
|
import ray.rllib.agents.sac as sac
|
|
|
|
from ray.rllib.utils.framework import try_import_tf
|
2020-04-03 21:24:25 +02:00
|
|
|
from ray.rllib.utils.test_utils import check, framework_iterator
|
2020-02-22 23:19:49 +01:00
|
|
|
from ray.rllib.utils.numpy import one_hot, fc, MIN_LOG_NN_OUTPUT, \
|
|
|
|
MAX_LOG_NN_OUTPUT
|
|
|
|
|
2020-06-30 10:13:20 +02:00
|
|
|
tf1, tf, tfv = try_import_tf()
|
2020-02-22 23:19:49 +01:00
|
|
|
|
|
|
|
|
2020-03-12 04:39:47 +01:00
|
|
|
def do_test_log_likelihood(run,
|
|
|
|
config,
|
|
|
|
prev_a=None,
|
|
|
|
continuous=False,
|
2020-04-15 13:25:16 +02:00
|
|
|
layer_key=("fc", (0, 4), ("_hidden_layers.0.",
|
|
|
|
"_logits.")),
|
2020-03-12 04:39:47 +01:00
|
|
|
logp_func=None):
|
2020-02-22 23:19:49 +01:00
|
|
|
config = config.copy()
|
|
|
|
# Run locally.
|
|
|
|
config["num_workers"] = 0
|
|
|
|
# Env setup.
|
|
|
|
if continuous:
|
[RLlib] Upgrade gym version to 0.21 and deprecate pendulum-v0. (#19535)
* Fix QMix, SAC, and MADDPA too.
* Unpin gym and deprecate pendulum v0
Many tests in rllib depended on pendulum v0,
however in gym 0.21, pendulum v0 was deprecated
in favor of pendulum v1. This may change reward
thresholds, so will have to potentially rerun
all of the pendulum v1 benchmarks, or use another
environment in favor. The same applies to frozen
lake v0 and frozen lake v1
Lastly, all of the RLlib tests and have
been moved to python 3.7
* Add gym installation based on python version.
Pin python<= 3.6 to gym 0.19 due to install
issues with atari roms in gym 0.20
* Reformatting
* Fixing tests
* Move atari-py install conditional to req.txt
* migrate to new ale install method
* Fix QMix, SAC, and MADDPA too.
* Unpin gym and deprecate pendulum v0
Many tests in rllib depended on pendulum v0,
however in gym 0.21, pendulum v0 was deprecated
in favor of pendulum v1. This may change reward
thresholds, so will have to potentially rerun
all of the pendulum v1 benchmarks, or use another
environment in favor. The same applies to frozen
lake v0 and frozen lake v1
Lastly, all of the RLlib tests and have
been moved to python 3.7
* Add gym installation based on python version.
Pin python<= 3.6 to gym 0.19 due to install
issues with atari roms in gym 0.20
Move atari-py install conditional to req.txt
migrate to new ale install method
Make parametric_actions_cartpole return float32 actions/obs
Adding type conversions if obs/actions don't match space
Add utils to make elements match gym space dtypes
Co-authored-by: Jun Gong <jungong@anyscale.com>
Co-authored-by: sven1977 <svenmika1977@gmail.com>
2021-11-03 08:24:00 -07:00
|
|
|
env = "Pendulum-v1"
|
2020-02-22 23:19:49 +01:00
|
|
|
obs_batch = preprocessed_obs_batch = np.array([[0.0, 0.1, -0.1]])
|
|
|
|
else:
|
[RLlib] Upgrade gym version to 0.21 and deprecate pendulum-v0. (#19535)
* Fix QMix, SAC, and MADDPA too.
* Unpin gym and deprecate pendulum v0
Many tests in rllib depended on pendulum v0,
however in gym 0.21, pendulum v0 was deprecated
in favor of pendulum v1. This may change reward
thresholds, so will have to potentially rerun
all of the pendulum v1 benchmarks, or use another
environment in favor. The same applies to frozen
lake v0 and frozen lake v1
Lastly, all of the RLlib tests and have
been moved to python 3.7
* Add gym installation based on python version.
Pin python<= 3.6 to gym 0.19 due to install
issues with atari roms in gym 0.20
* Reformatting
* Fixing tests
* Move atari-py install conditional to req.txt
* migrate to new ale install method
* Fix QMix, SAC, and MADDPA too.
* Unpin gym and deprecate pendulum v0
Many tests in rllib depended on pendulum v0,
however in gym 0.21, pendulum v0 was deprecated
in favor of pendulum v1. This may change reward
thresholds, so will have to potentially rerun
all of the pendulum v1 benchmarks, or use another
environment in favor. The same applies to frozen
lake v0 and frozen lake v1
Lastly, all of the RLlib tests and have
been moved to python 3.7
* Add gym installation based on python version.
Pin python<= 3.6 to gym 0.19 due to install
issues with atari roms in gym 0.20
Move atari-py install conditional to req.txt
migrate to new ale install method
Make parametric_actions_cartpole return float32 actions/obs
Adding type conversions if obs/actions don't match space
Add utils to make elements match gym space dtypes
Co-authored-by: Jun Gong <jungong@anyscale.com>
Co-authored-by: sven1977 <svenmika1977@gmail.com>
2021-11-03 08:24:00 -07:00
|
|
|
env = "FrozenLake-v1"
|
2020-02-22 23:19:49 +01:00
|
|
|
config["env_config"] = {"is_slippery": False, "map_name": "4x4"}
|
|
|
|
obs_batch = np.array([0])
|
2021-12-13 12:04:23 +01:00
|
|
|
# PG does not preprocess anymore by default.
|
|
|
|
preprocessed_obs_batch = one_hot(obs_batch, depth=16) \
|
|
|
|
if run is not pg.PGTrainer else obs_batch
|
2020-02-22 23:19:49 +01:00
|
|
|
|
|
|
|
prev_r = None if prev_a is None else np.array(0.0)
|
|
|
|
|
|
|
|
# Test against all frameworks.
|
2020-04-03 21:24:25 +02:00
|
|
|
for fw in framework_iterator(config):
|
2020-02-22 23:19:49 +01:00
|
|
|
trainer = run(config=config, env=env)
|
2020-03-29 00:16:30 +01:00
|
|
|
|
2020-02-22 23:19:49 +01:00
|
|
|
policy = trainer.get_policy()
|
|
|
|
vars = policy.get_weights()
|
|
|
|
# Sample n actions, then roughly check their logp against their
|
|
|
|
# counts.
|
2020-03-12 04:39:47 +01:00
|
|
|
num_actions = 1000 if not continuous else 50
|
2020-02-22 23:19:49 +01:00
|
|
|
actions = []
|
|
|
|
for _ in range(num_actions):
|
|
|
|
# Single action from single obs.
|
|
|
|
actions.append(
|
2021-06-30 12:32:11 +02:00
|
|
|
trainer.compute_single_action(
|
2020-02-22 23:19:49 +01:00
|
|
|
obs_batch[0],
|
|
|
|
prev_action=prev_a,
|
|
|
|
prev_reward=prev_r,
|
2021-07-13 20:01:30 +02:00
|
|
|
explore=True,
|
|
|
|
# Do not unsquash actions
|
|
|
|
# (remain in normalized [-1.0; 1.0] space).
|
2021-09-30 16:39:38 +02:00
|
|
|
unsquash_action=False,
|
2021-07-13 20:01:30 +02:00
|
|
|
))
|
2020-02-22 23:19:49 +01:00
|
|
|
|
2020-03-12 04:39:47 +01:00
|
|
|
# Test all taken actions for their log-likelihoods vs expected values.
|
2020-02-22 23:19:49 +01:00
|
|
|
if continuous:
|
2020-03-12 04:39:47 +01:00
|
|
|
for idx in range(num_actions):
|
2020-02-22 23:19:49 +01:00
|
|
|
a = actions[idx]
|
2020-05-27 16:19:13 +02:00
|
|
|
if fw != "torch":
|
2020-02-22 23:19:49 +01:00
|
|
|
if isinstance(vars, list):
|
|
|
|
expected_mean_logstd = fc(
|
|
|
|
fc(obs_batch, vars[layer_key[1][0]]),
|
|
|
|
vars[layer_key[1][1]])
|
|
|
|
else:
|
|
|
|
expected_mean_logstd = fc(
|
|
|
|
fc(
|
|
|
|
obs_batch,
|
|
|
|
vars["default_policy/{}_1/kernel".format(
|
|
|
|
layer_key[0])]),
|
|
|
|
vars["default_policy/{}_out/kernel".format(
|
|
|
|
layer_key[0])])
|
|
|
|
else:
|
|
|
|
expected_mean_logstd = fc(
|
2020-04-15 13:25:16 +02:00
|
|
|
fc(obs_batch,
|
|
|
|
vars["{}_model.0.weight".format(layer_key[2][0])],
|
|
|
|
framework=fw),
|
|
|
|
vars["{}_model.0.weight".format(layer_key[2][1])],
|
|
|
|
framework=fw)
|
2020-02-22 23:19:49 +01:00
|
|
|
mean, log_std = np.split(expected_mean_logstd, 2, axis=-1)
|
|
|
|
if logp_func is None:
|
|
|
|
expected_logp = np.log(norm.pdf(a, mean, np.exp(log_std)))
|
|
|
|
else:
|
|
|
|
expected_logp = logp_func(mean, log_std, a)
|
|
|
|
logp = policy.compute_log_likelihoods(
|
|
|
|
np.array([a]),
|
|
|
|
preprocessed_obs_batch,
|
2020-12-07 13:08:17 +01:00
|
|
|
prev_action_batch=np.array([prev_a]) if prev_a else None,
|
2021-07-13 20:01:30 +02:00
|
|
|
prev_reward_batch=np.array([prev_r]) if prev_r else None,
|
|
|
|
actions_normalized=True,
|
|
|
|
)
|
2020-02-22 23:19:49 +01:00
|
|
|
check(logp, expected_logp[0], rtol=0.2)
|
|
|
|
# Test all available actions for their logp values.
|
|
|
|
else:
|
|
|
|
for a in [0, 1, 2, 3]:
|
|
|
|
count = actions.count(a)
|
2020-03-12 04:39:47 +01:00
|
|
|
expected_prob = count / num_actions
|
2020-02-22 23:19:49 +01:00
|
|
|
logp = policy.compute_log_likelihoods(
|
|
|
|
np.array([a]),
|
|
|
|
preprocessed_obs_batch,
|
2020-12-07 13:08:17 +01:00
|
|
|
prev_action_batch=np.array([prev_a]) if prev_a else None,
|
|
|
|
prev_reward_batch=np.array([prev_r]) if prev_r else None)
|
2020-03-12 04:39:47 +01:00
|
|
|
check(np.exp(logp), expected_prob, atol=0.2)
|
2020-02-22 23:19:49 +01:00
|
|
|
|
|
|
|
|
|
|
|
class TestComputeLogLikelihood(unittest.TestCase):
|
2020-12-07 13:08:17 +01:00
|
|
|
@classmethod
|
|
|
|
def setUpClass(cls) -> None:
|
|
|
|
ray.init()
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def tearDownClass(cls) -> None:
|
|
|
|
ray.shutdown()
|
|
|
|
|
2020-02-22 23:19:49 +01:00
|
|
|
def test_dqn(self):
|
|
|
|
"""Tests, whether DQN correctly computes logp in soft-q mode."""
|
2020-03-12 04:39:47 +01:00
|
|
|
config = dqn.DEFAULT_CONFIG.copy()
|
|
|
|
# Soft-Q for DQN.
|
|
|
|
config["exploration_config"] = {"type": "SoftQ", "temperature": 0.5}
|
2021-07-13 20:01:30 +02:00
|
|
|
config["seed"] = 42
|
2020-03-12 04:39:47 +01:00
|
|
|
do_test_log_likelihood(dqn.DQNTrainer, config)
|
|
|
|
|
|
|
|
def test_pg_cont(self):
|
|
|
|
"""Tests PG's (cont. actions) compute_log_likelihoods method."""
|
|
|
|
config = pg.DEFAULT_CONFIG.copy()
|
2021-07-13 20:01:30 +02:00
|
|
|
config["seed"] = 42
|
2020-03-12 04:39:47 +01:00
|
|
|
config["model"]["fcnet_hiddens"] = [10]
|
|
|
|
config["model"]["fcnet_activation"] = "linear"
|
|
|
|
prev_a = np.array([0.0])
|
|
|
|
do_test_log_likelihood(
|
|
|
|
pg.PGTrainer,
|
|
|
|
config,
|
|
|
|
prev_a,
|
|
|
|
continuous=True,
|
2020-04-15 13:25:16 +02:00
|
|
|
layer_key=("fc", (0, 2), ("_hidden_layers.0.", "_logits.")))
|
2020-03-12 04:39:47 +01:00
|
|
|
|
|
|
|
def test_pg_discr(self):
|
|
|
|
"""Tests PG's (cont. actions) compute_log_likelihoods method."""
|
|
|
|
config = pg.DEFAULT_CONFIG.copy()
|
2021-07-13 20:01:30 +02:00
|
|
|
config["seed"] = 42
|
2020-03-12 04:39:47 +01:00
|
|
|
prev_a = np.array(0)
|
|
|
|
do_test_log_likelihood(pg.PGTrainer, config, prev_a)
|
2020-02-22 23:19:49 +01:00
|
|
|
|
|
|
|
def test_ppo_cont(self):
|
|
|
|
"""Tests PPO's (cont. actions) compute_log_likelihoods method."""
|
|
|
|
config = ppo.DEFAULT_CONFIG.copy()
|
2021-07-13 20:01:30 +02:00
|
|
|
config["seed"] = 42
|
2020-02-22 23:19:49 +01:00
|
|
|
config["model"]["fcnet_hiddens"] = [10]
|
|
|
|
config["model"]["fcnet_activation"] = "linear"
|
|
|
|
prev_a = np.array([0.0])
|
2020-03-12 04:39:47 +01:00
|
|
|
do_test_log_likelihood(ppo.PPOTrainer, config, prev_a, continuous=True)
|
2020-02-22 23:19:49 +01:00
|
|
|
|
|
|
|
def test_ppo_discr(self):
|
|
|
|
"""Tests PPO's (discr. actions) compute_log_likelihoods method."""
|
2021-07-13 20:01:30 +02:00
|
|
|
config = ppo.DEFAULT_CONFIG.copy()
|
|
|
|
config["seed"] = 42
|
2020-02-22 23:19:49 +01:00
|
|
|
prev_a = np.array(0)
|
2021-07-13 20:01:30 +02:00
|
|
|
do_test_log_likelihood(ppo.PPOTrainer, config, prev_a)
|
2020-02-22 23:19:49 +01:00
|
|
|
|
2020-03-12 04:39:47 +01:00
|
|
|
def test_sac_cont(self):
|
|
|
|
"""Tests SAC's (cont. actions) compute_log_likelihoods method."""
|
2020-02-22 23:19:49 +01:00
|
|
|
config = sac.DEFAULT_CONFIG.copy()
|
2021-07-13 20:01:30 +02:00
|
|
|
config["seed"] = 42
|
2020-04-15 13:25:16 +02:00
|
|
|
config["policy_model"]["fcnet_hiddens"] = [10]
|
|
|
|
config["policy_model"]["fcnet_activation"] = "linear"
|
2020-02-22 23:19:49 +01:00
|
|
|
prev_a = np.array([0.0])
|
|
|
|
|
2020-03-12 04:39:47 +01:00
|
|
|
# SAC cont uses a squashed normal distribution. Implement it's logp
|
|
|
|
# logic here in numpy for comparing results.
|
2020-02-22 23:19:49 +01:00
|
|
|
def logp_func(means, log_stds, values, low=-1.0, high=1.0):
|
|
|
|
stds = np.exp(
|
|
|
|
np.clip(log_stds, MIN_LOG_NN_OUTPUT, MAX_LOG_NN_OUTPUT))
|
|
|
|
unsquashed_values = np.arctanh((values - low) /
|
|
|
|
(high - low) * 2.0 - 1.0)
|
|
|
|
log_prob_unsquashed = \
|
|
|
|
np.sum(np.log(norm.pdf(unsquashed_values, means, stds)), -1)
|
|
|
|
return log_prob_unsquashed - \
|
|
|
|
np.sum(np.log(1 - np.tanh(unsquashed_values) ** 2),
|
|
|
|
axis=-1)
|
|
|
|
|
2020-03-12 04:39:47 +01:00
|
|
|
do_test_log_likelihood(
|
2020-02-22 23:19:49 +01:00
|
|
|
sac.SACTrainer,
|
|
|
|
config,
|
|
|
|
prev_a,
|
|
|
|
continuous=True,
|
2021-02-02 13:05:58 +01:00
|
|
|
layer_key=("fc", (0, 2), ("action_model._hidden_layers.0.",
|
|
|
|
"action_model._logits.")),
|
2020-02-22 23:19:49 +01:00
|
|
|
logp_func=logp_func)
|
2020-03-12 04:39:47 +01:00
|
|
|
|
|
|
|
def test_sac_discr(self):
|
|
|
|
"""Tests SAC's (discrete actions) compute_log_likelihoods method."""
|
|
|
|
config = sac.DEFAULT_CONFIG.copy()
|
2021-07-13 20:01:30 +02:00
|
|
|
config["seed"] = 42
|
2020-04-15 13:25:16 +02:00
|
|
|
config["policy_model"]["fcnet_hiddens"] = [10]
|
|
|
|
config["policy_model"]["fcnet_activation"] = "linear"
|
2020-03-12 04:39:47 +01:00
|
|
|
prev_a = np.array(0)
|
|
|
|
|
2021-02-02 13:05:58 +01:00
|
|
|
do_test_log_likelihood(sac.SACTrainer, config, prev_a)
|
2020-03-12 04:39:47 +01:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
import pytest
|
|
|
|
import sys
|
|
|
|
sys.exit(pytest.main(["-v", __file__]))
|