2021-01-19 09:51:05 +01:00
|
|
|
import numpy as np
|
2020-07-14 05:07:16 +02:00
|
|
|
import os
|
|
|
|
from pathlib import Path
|
2020-04-07 01:38:50 +02:00
|
|
|
import unittest
|
|
|
|
|
|
|
|
import ray
|
2022-05-16 00:45:32 -07:00
|
|
|
import ray.rllib.algorithms.marwil as marwil
|
2022-05-20 05:10:59 -07:00
|
|
|
from ray.rllib.algorithms.marwil.marwil_tf_policy import MARWILEagerTFPolicy
|
|
|
|
from ray.rllib.algorithms.marwil.marwil_torch_policy import MARWILTorchPolicy
|
2021-01-19 09:51:05 +01:00
|
|
|
from ray.rllib.evaluation.postprocessing import compute_advantages
|
|
|
|
from ray.rllib.offline import JsonReader
|
|
|
|
from ray.rllib.utils.framework import try_import_tf, try_import_torch
|
2022-01-29 18:41:57 -08:00
|
|
|
from ray.rllib.utils.test_utils import (
|
|
|
|
check,
|
|
|
|
check_compute_single_action,
|
|
|
|
check_train_results,
|
|
|
|
framework_iterator,
|
|
|
|
)
|
2020-04-07 01:38:50 +02:00
|
|
|
|
2020-06-30 10:13:20 +02:00
|
|
|
tf1, tf, tfv = try_import_tf()
|
2021-01-19 09:51:05 +01:00
|
|
|
torch, _ = try_import_torch()
|
2020-04-07 01:38:50 +02:00
|
|
|
|
|
|
|
|
|
|
|
class TestMARWIL(unittest.TestCase):
|
|
|
|
@classmethod
|
|
|
|
def setUpClass(cls):
|
2021-03-24 16:07:40 +01:00
|
|
|
ray.init(num_cpus=4)
|
2020-04-07 01:38:50 +02:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def tearDownClass(cls):
|
|
|
|
ray.shutdown()
|
|
|
|
|
2020-07-14 05:07:16 +02:00
|
|
|
def test_marwil_compilation_and_learning_from_offline_file(self):
|
|
|
|
"""Test whether a MARWILTrainer can be built with all frameworks.
|
|
|
|
|
2021-05-04 10:06:19 -07:00
|
|
|
Learns from a historic-data file.
|
2020-10-06 20:28:16 +02:00
|
|
|
To generate this data, first run:
|
|
|
|
$ ./train.py --run=PPO --env=CartPole-v0 \
|
|
|
|
--stop='{"timesteps_total": 50000}' \
|
|
|
|
--config='{"output": "/tmp/out", "batch_mode": "complete_episodes"}'
|
2020-07-14 05:07:16 +02:00
|
|
|
"""
|
|
|
|
rllib_dir = Path(__file__).parent.parent.parent.parent
|
|
|
|
print("rllib dir={}".format(rllib_dir))
|
|
|
|
data_file = os.path.join(rllib_dir, "tests/data/cartpole/large.json")
|
2022-01-29 18:41:57 -08:00
|
|
|
print("data_file={} exists={}".format(data_file, os.path.isfile(data_file)))
|
2020-07-14 05:07:16 +02:00
|
|
|
|
2022-05-21 03:50:20 -07:00
|
|
|
config = (
|
|
|
|
marwil.MARWILConfig()
|
|
|
|
.rollouts(num_rollout_workers=2)
|
|
|
|
.environment(env="CartPole-v0")
|
|
|
|
.evaluation(
|
|
|
|
evaluation_interval=3,
|
|
|
|
evaluation_num_workers=1,
|
|
|
|
evaluation_duration=5,
|
|
|
|
evaluation_parallel_to_training=True,
|
|
|
|
evaluation_config={"input": "sampler"},
|
|
|
|
)
|
|
|
|
.offline_data(input_=[data_file])
|
|
|
|
)
|
|
|
|
|
2020-10-31 08:16:09 +01:00
|
|
|
num_iterations = 350
|
|
|
|
min_reward = 70.0
|
2020-04-07 01:38:50 +02:00
|
|
|
|
|
|
|
# Test for all frameworks.
|
2021-02-08 15:02:19 +01:00
|
|
|
for _ in framework_iterator(config, frameworks=("tf", "torch")):
|
2022-05-16 13:13:49 +02:00
|
|
|
trainer = marwil.MARWILTrainer(config=config)
|
2020-10-31 08:16:09 +01:00
|
|
|
learnt = False
|
2020-04-07 01:38:50 +02:00
|
|
|
for i in range(num_iterations):
|
2021-09-30 16:39:05 +02:00
|
|
|
results = trainer.train()
|
|
|
|
check_train_results(results)
|
|
|
|
print(results)
|
|
|
|
|
|
|
|
eval_results = results.get("evaluation")
|
2021-03-24 16:07:40 +01:00
|
|
|
if eval_results:
|
2022-01-29 18:41:57 -08:00
|
|
|
print(
|
|
|
|
"iter={} R={} ".format(i, eval_results["episode_reward_mean"])
|
|
|
|
)
|
2021-03-24 16:07:40 +01:00
|
|
|
# Learn until some reward is reached on an actual live env.
|
|
|
|
if eval_results["episode_reward_mean"] > min_reward:
|
|
|
|
print("learnt!")
|
|
|
|
learnt = True
|
|
|
|
break
|
2020-07-14 05:07:16 +02:00
|
|
|
|
2020-10-31 08:16:09 +01:00
|
|
|
if not learnt:
|
|
|
|
raise ValueError(
|
|
|
|
"MARWILTrainer did not reach {} reward from expert "
|
2022-01-29 18:41:57 -08:00
|
|
|
"offline data!".format(min_reward)
|
|
|
|
)
|
2020-10-31 08:16:09 +01:00
|
|
|
|
2022-01-29 18:41:57 -08:00
|
|
|
check_compute_single_action(trainer, include_prev_action_reward=True)
|
2020-07-14 05:07:16 +02:00
|
|
|
|
2020-05-21 10:16:18 -07:00
|
|
|
trainer.stop()
|
2020-04-07 01:38:50 +02:00
|
|
|
|
2021-06-03 22:29:00 +02:00
|
|
|
def test_marwil_cont_actions_from_offline_file(self):
|
|
|
|
"""Test whether MARWILTrainer runs with cont. actions.
|
|
|
|
|
|
|
|
Learns from a historic-data file.
|
|
|
|
To generate this data, first run:
|
[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
|
|
|
$ ./train.py --run=PPO --env=Pendulum-v1 \
|
2021-06-03 22:29:00 +02:00
|
|
|
--stop='{"timesteps_total": 50000}' \
|
|
|
|
--config='{"output": "/tmp/out", "batch_mode": "complete_episodes"}'
|
|
|
|
"""
|
|
|
|
rllib_dir = Path(__file__).parent.parent.parent.parent
|
|
|
|
print("rllib dir={}".format(rllib_dir))
|
|
|
|
data_file = os.path.join(rllib_dir, "tests/data/pendulum/large.json")
|
2022-01-29 18:41:57 -08:00
|
|
|
print("data_file={} exists={}".format(data_file, os.path.isfile(data_file)))
|
2021-06-03 22:29:00 +02:00
|
|
|
|
|
|
|
config = marwil.DEFAULT_CONFIG.copy()
|
|
|
|
config["num_workers"] = 1
|
|
|
|
config["evaluation_num_workers"] = 1
|
|
|
|
config["evaluation_interval"] = 3
|
2021-12-04 13:26:33 +01:00
|
|
|
config["evaluation_duration"] = 5
|
2021-06-03 22:29:00 +02:00
|
|
|
config["evaluation_parallel_to_training"] = True
|
|
|
|
# Evaluate on actual environment.
|
|
|
|
config["evaluation_config"] = {"input": "sampler"}
|
|
|
|
# Learn from offline data.
|
|
|
|
config["input"] = [data_file]
|
2022-05-27 04:14:54 -07:00
|
|
|
config[
|
|
|
|
"off_policy_estimation_methods"
|
|
|
|
] = [] # disable (data has no action-probs)
|
2021-06-03 22:29:00 +02:00
|
|
|
num_iterations = 3
|
|
|
|
|
|
|
|
# Test for all frameworks.
|
|
|
|
for _ in framework_iterator(config, frameworks=("tf", "torch")):
|
[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
|
|
|
trainer = marwil.MARWILTrainer(config=config, env="Pendulum-v1")
|
2021-06-03 22:29:00 +02:00
|
|
|
for i in range(num_iterations):
|
|
|
|
print(trainer.train())
|
|
|
|
trainer.stop()
|
|
|
|
|
2021-01-19 09:51:05 +01:00
|
|
|
def test_marwil_loss_function(self):
|
|
|
|
"""
|
|
|
|
To generate the historic data used in this test case, first run:
|
|
|
|
$ ./train.py --run=PPO --env=CartPole-v0 \
|
|
|
|
--stop='{"timesteps_total": 50000}' \
|
|
|
|
--config='{"output": "/tmp/out", "batch_mode": "complete_episodes"}'
|
|
|
|
"""
|
|
|
|
rllib_dir = Path(__file__).parent.parent.parent.parent
|
|
|
|
print("rllib dir={}".format(rllib_dir))
|
|
|
|
data_file = os.path.join(rllib_dir, "tests/data/cartpole/small.json")
|
2022-01-29 18:41:57 -08:00
|
|
|
print("data_file={} exists={}".format(data_file, os.path.isfile(data_file)))
|
2021-01-19 09:51:05 +01:00
|
|
|
config = marwil.DEFAULT_CONFIG.copy()
|
|
|
|
config["num_workers"] = 0 # Run locally.
|
|
|
|
# Learn from offline data.
|
|
|
|
config["input"] = [data_file]
|
|
|
|
|
2021-05-20 00:44:11 +02:00
|
|
|
for fw, sess in framework_iterator(config, session=True):
|
2021-01-19 09:51:05 +01:00
|
|
|
reader = JsonReader(inputs=[data_file])
|
|
|
|
batch = reader.next()
|
|
|
|
|
|
|
|
trainer = marwil.MARWILTrainer(config=config, env="CartPole-v0")
|
|
|
|
policy = trainer.get_policy()
|
|
|
|
model = policy.model
|
|
|
|
|
|
|
|
# Calculate our own expected values (to then compare against the
|
|
|
|
# agent's loss output).
|
|
|
|
cummulative_rewards = compute_advantages(
|
2022-01-29 18:41:57 -08:00
|
|
|
batch, 0.0, config["gamma"], 1.0, False, False
|
|
|
|
)["advantages"]
|
2021-01-19 09:51:05 +01:00
|
|
|
if fw == "torch":
|
|
|
|
cummulative_rewards = torch.tensor(cummulative_rewards)
|
2021-05-20 00:44:11 +02:00
|
|
|
if fw != "tf":
|
|
|
|
batch = policy._lazy_tensor_dict(batch)
|
2021-10-25 15:00:00 +02:00
|
|
|
model_out, _ = model(batch)
|
2021-01-19 09:51:05 +01:00
|
|
|
vf_estimates = model.value_function()
|
2021-05-20 00:44:11 +02:00
|
|
|
if fw == "tf":
|
2022-01-29 18:41:57 -08:00
|
|
|
model_out, vf_estimates = policy.get_session().run(
|
|
|
|
[model_out, vf_estimates]
|
|
|
|
)
|
2021-01-19 09:51:05 +01:00
|
|
|
adv = cummulative_rewards - vf_estimates
|
|
|
|
if fw == "torch":
|
|
|
|
adv = adv.detach().cpu().numpy()
|
|
|
|
adv_squared = np.mean(np.square(adv))
|
|
|
|
c_2 = 100.0 + 1e-8 * (adv_squared - 100.0)
|
|
|
|
c = np.sqrt(c_2)
|
|
|
|
exp_advs = np.exp(config["beta"] * (adv / c))
|
2021-05-20 00:44:11 +02:00
|
|
|
dist = policy.dist_class(model_out, model)
|
|
|
|
logp = dist.logp(batch["actions"])
|
2021-01-19 09:51:05 +01:00
|
|
|
if fw == "torch":
|
|
|
|
logp = logp.detach().cpu().numpy()
|
2021-05-20 00:44:11 +02:00
|
|
|
elif fw == "tf":
|
|
|
|
logp = sess.run(logp)
|
2021-01-19 09:51:05 +01:00
|
|
|
# Calculate all expected loss components.
|
|
|
|
expected_vf_loss = 0.5 * adv_squared
|
|
|
|
expected_pol_loss = -1.0 * np.mean(exp_advs * logp)
|
2022-01-29 18:41:57 -08:00
|
|
|
expected_loss = expected_pol_loss + config["vf_coeff"] * expected_vf_loss
|
2021-01-19 09:51:05 +01:00
|
|
|
|
|
|
|
# Calculate the algorithm's loss (to check against our own
|
|
|
|
# calculation above).
|
2021-03-17 08:18:15 +01:00
|
|
|
batch.set_get_interceptor(None)
|
2021-01-19 09:51:05 +01:00
|
|
|
postprocessed_batch = policy.postprocess_trajectory(batch)
|
2022-01-29 18:41:57 -08:00
|
|
|
loss_func = (
|
2022-05-20 05:10:59 -07:00
|
|
|
MARWILEagerTFPolicy.loss if fw != "torch" else MARWILTorchPolicy.loss
|
2022-01-29 18:41:57 -08:00
|
|
|
)
|
2021-05-20 00:44:11 +02:00
|
|
|
if fw != "tf":
|
|
|
|
policy._lazy_tensor_dict(postprocessed_batch)
|
2022-01-29 18:41:57 -08:00
|
|
|
loss_out = loss_func(
|
|
|
|
policy, model, policy.dist_class, postprocessed_batch
|
|
|
|
)
|
2021-05-20 00:44:11 +02:00
|
|
|
else:
|
|
|
|
loss_out, v_loss, p_loss = policy.get_session().run(
|
|
|
|
[policy._loss, policy.loss.v_loss, policy.loss.p_loss],
|
|
|
|
feed_dict=policy._get_loss_inputs_dict(
|
2022-01-29 18:41:57 -08:00
|
|
|
postprocessed_batch, shuffle=False
|
|
|
|
),
|
|
|
|
)
|
2021-01-19 09:51:05 +01:00
|
|
|
|
|
|
|
# Check all components.
|
|
|
|
if fw == "torch":
|
|
|
|
check(policy.v_loss, expected_vf_loss, decimals=4)
|
|
|
|
check(policy.p_loss, expected_pol_loss, decimals=4)
|
2021-05-20 00:44:11 +02:00
|
|
|
elif fw == "tf":
|
|
|
|
check(v_loss, expected_vf_loss, decimals=4)
|
|
|
|
check(p_loss, expected_pol_loss, decimals=4)
|
2021-01-19 09:51:05 +01:00
|
|
|
else:
|
|
|
|
check(policy.loss.v_loss, expected_vf_loss, decimals=4)
|
|
|
|
check(policy.loss.p_loss, expected_pol_loss, decimals=4)
|
|
|
|
check(loss_out, expected_loss, decimals=3)
|
|
|
|
|
2020-04-07 01:38:50 +02:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
import pytest
|
|
|
|
import sys
|
2022-01-29 18:41:57 -08:00
|
|
|
|
2020-04-07 01:38:50 +02:00
|
|
|
sys.exit(pytest.main(["-v", __file__]))
|