2020-01-02 19:08:03 -05:00
|
|
|
import numpy as np
|
|
|
|
import unittest
|
|
|
|
|
|
|
|
import ray
|
|
|
|
import ray.rllib.agents.pg as pg
|
|
|
|
from ray.rllib.evaluation.postprocessing import Postprocessing
|
|
|
|
from ray.rllib.models.tf.tf_action_dist import Categorical
|
|
|
|
from ray.rllib.models.torch.torch_action_dist import TorchCategorical
|
|
|
|
from ray.rllib.policy.sample_batch import SampleBatch
|
2021-09-30 16:39:05 +02:00
|
|
|
from ray.rllib.utils.numpy import fc
|
|
|
|
from ray.rllib.utils.test_utils import check, check_compute_single_action, \
|
|
|
|
check_train_results, framework_iterator
|
2020-01-02 19:08:03 -05:00
|
|
|
|
|
|
|
|
|
|
|
class TestPG(unittest.TestCase):
|
2021-09-03 13:29:57 +02:00
|
|
|
@classmethod
|
|
|
|
def setUpClass(cls) -> None:
|
2020-02-19 16:07:37 -08:00
|
|
|
ray.init()
|
2020-01-02 19:08:03 -05:00
|
|
|
|
2021-09-03 13:29:57 +02:00
|
|
|
@classmethod
|
|
|
|
def tearDownClass(cls) -> None:
|
2020-02-19 16:07:37 -08:00
|
|
|
ray.shutdown()
|
|
|
|
|
2020-01-02 19:08:03 -05:00
|
|
|
def test_pg_compilation(self):
|
2021-11-12 13:09:43 +00:00
|
|
|
"""Test whether a PGTrainer can be built with both frameworks."""
|
2020-01-02 19:08:03 -05:00
|
|
|
config = pg.DEFAULT_CONFIG.copy()
|
2021-08-16 22:01:01 +02:00
|
|
|
config["num_workers"] = 1
|
|
|
|
config["rollout_fragment_length"] = 500
|
|
|
|
num_iterations = 1
|
2020-01-02 19:08:03 -05:00
|
|
|
|
2021-11-05 14:39:28 +01:00
|
|
|
for _ in framework_iterator(config, with_eager_tracing=True):
|
[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
|
|
|
for env in ["FrozenLake-v1", "CartPole-v0"]:
|
2021-08-16 22:01:01 +02:00
|
|
|
trainer = pg.PGTrainer(config=config, env=env)
|
|
|
|
for i in range(num_iterations):
|
2021-09-30 16:39:05 +02:00
|
|
|
results = trainer.train()
|
|
|
|
check_train_results(results)
|
|
|
|
print(results)
|
|
|
|
|
2021-08-16 22:01:01 +02:00
|
|
|
check_compute_single_action(
|
|
|
|
trainer, include_prev_action_reward=True)
|
2020-01-02 19:08:03 -05:00
|
|
|
|
|
|
|
def test_pg_loss_functions(self):
|
|
|
|
"""Tests the PG loss function math."""
|
|
|
|
config = pg.DEFAULT_CONFIG.copy()
|
|
|
|
config["num_workers"] = 0 # Run locally.
|
|
|
|
config["gamma"] = 0.99
|
|
|
|
config["model"]["fcnet_hiddens"] = [10]
|
|
|
|
config["model"]["fcnet_activation"] = "linear"
|
|
|
|
|
2020-02-11 00:22:07 +01:00
|
|
|
# Fake CartPole episode of n time steps.
|
2021-04-27 10:44:54 +02:00
|
|
|
train_batch = SampleBatch({
|
2020-11-12 16:27:34 +01:00
|
|
|
SampleBatch.OBS: np.array([[0.1, 0.2, 0.3,
|
|
|
|
0.4], [0.5, 0.6, 0.7, 0.8],
|
|
|
|
[0.9, 1.0, 1.1, 1.2]]),
|
2020-01-02 19:08:03 -05:00
|
|
|
SampleBatch.ACTIONS: np.array([0, 1, 1]),
|
|
|
|
SampleBatch.REWARDS: np.array([1.0, 1.0, 1.0]),
|
2020-11-12 16:27:34 +01:00
|
|
|
SampleBatch.DONES: np.array([False, False, True]),
|
|
|
|
SampleBatch.EPS_ID: np.array([1234, 1234, 1234]),
|
|
|
|
SampleBatch.AGENT_INDEX: np.array([0, 0, 0]),
|
2021-04-27 10:44:54 +02:00
|
|
|
})
|
2020-01-02 19:08:03 -05:00
|
|
|
|
2020-04-07 21:40:34 +02:00
|
|
|
for fw, sess in framework_iterator(config, session=True):
|
|
|
|
dist_cls = (Categorical if fw != "torch" else TorchCategorical)
|
|
|
|
trainer = pg.PGTrainer(config=config, env="CartPole-v0")
|
|
|
|
policy = trainer.get_policy()
|
|
|
|
vars = policy.model.trainable_variables()
|
2020-07-11 22:06:35 +02:00
|
|
|
if sess:
|
2020-04-07 21:40:34 +02:00
|
|
|
vars = policy.get_session().run(vars)
|
|
|
|
|
|
|
|
# Post-process (calculate simple (non-GAE) advantages) and attach
|
|
|
|
# to train_batch dict.
|
|
|
|
# A = [0.99^2 * 1.0 + 0.99 * 1.0 + 1.0, 0.99 * 1.0 + 1.0, 1.0] =
|
|
|
|
# [2.9701, 1.99, 1.0]
|
2020-11-12 16:27:34 +01:00
|
|
|
train_batch_ = pg.post_process_advantages(policy,
|
|
|
|
train_batch.copy())
|
2020-04-07 21:40:34 +02:00
|
|
|
if fw == "torch":
|
2020-11-12 16:27:34 +01:00
|
|
|
train_batch_ = policy._lazy_tensor_dict(train_batch_)
|
2020-04-07 21:40:34 +02:00
|
|
|
|
|
|
|
# Check Advantage values.
|
2020-11-12 16:27:34 +01:00
|
|
|
check(train_batch_[Postprocessing.ADVANTAGES], [2.9701, 1.99, 1.0])
|
2020-04-07 21:40:34 +02:00
|
|
|
|
|
|
|
# Actual loss results.
|
2020-07-11 22:06:35 +02:00
|
|
|
if sess:
|
2020-04-07 21:40:34 +02:00
|
|
|
results = policy.get_session().run(
|
|
|
|
policy._loss,
|
|
|
|
feed_dict=policy._get_loss_inputs_dict(
|
2020-11-12 16:27:34 +01:00
|
|
|
train_batch_, shuffle=False))
|
2020-04-07 21:40:34 +02:00
|
|
|
else:
|
2020-08-07 16:49:49 -07:00
|
|
|
results = (pg.pg_tf_loss
|
|
|
|
if fw in ["tf2", "tfe"] else pg.pg_torch_loss)(
|
|
|
|
policy,
|
|
|
|
policy.model,
|
|
|
|
dist_class=dist_cls,
|
2020-11-12 16:27:34 +01:00
|
|
|
train_batch=train_batch_)
|
2020-04-07 21:40:34 +02:00
|
|
|
|
|
|
|
# Calculate expected results.
|
2020-04-15 13:25:16 +02:00
|
|
|
if fw != "torch":
|
|
|
|
expected_logits = fc(
|
2020-11-12 16:27:34 +01:00
|
|
|
fc(train_batch_[SampleBatch.OBS],
|
2020-04-15 13:25:16 +02:00
|
|
|
vars[0],
|
|
|
|
vars[1],
|
|
|
|
framework=fw),
|
|
|
|
vars[2],
|
|
|
|
vars[3],
|
|
|
|
framework=fw)
|
|
|
|
else:
|
|
|
|
expected_logits = fc(
|
2020-11-12 16:27:34 +01:00
|
|
|
fc(train_batch_[SampleBatch.OBS],
|
2020-04-15 13:25:16 +02:00
|
|
|
vars[2],
|
|
|
|
vars[3],
|
|
|
|
framework=fw),
|
|
|
|
vars[0],
|
|
|
|
vars[1],
|
|
|
|
framework=fw)
|
2020-04-07 21:40:34 +02:00
|
|
|
expected_logp = dist_cls(expected_logits, policy.model).logp(
|
2020-11-12 16:27:34 +01:00
|
|
|
train_batch_[SampleBatch.ACTIONS])
|
|
|
|
adv = train_batch_[Postprocessing.ADVANTAGES]
|
2020-04-07 21:40:34 +02:00
|
|
|
if sess:
|
|
|
|
expected_logp = sess.run(expected_logp)
|
2020-10-27 10:00:24 +01:00
|
|
|
elif fw == "torch":
|
|
|
|
expected_logp = expected_logp.detach().cpu().numpy()
|
|
|
|
adv = adv.detach().cpu().numpy()
|
2020-04-07 21:40:34 +02:00
|
|
|
else:
|
|
|
|
expected_logp = expected_logp.numpy()
|
2020-10-27 10:00:24 +01:00
|
|
|
expected_loss = -np.mean(expected_logp * adv)
|
2020-04-07 21:40:34 +02:00
|
|
|
check(results, expected_loss, decimals=4)
|
2020-02-19 21:18:45 +01:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2020-02-19 16:07:37 -08:00
|
|
|
import pytest
|
|
|
|
import sys
|
|
|
|
sys.exit(pytest.main(["-v", __file__]))
|