2021-05-18 11:10:46 +02:00
|
|
|
import numpy as np
|
2021-05-04 10:06:19 -07:00
|
|
|
from pathlib import Path
|
|
|
|
import os
|
2021-03-11 09:51:39 -08:00
|
|
|
import unittest
|
|
|
|
|
|
|
|
import ray
|
2022-05-22 18:58:47 +01:00
|
|
|
from ray.rllib.algorithms import cql
|
2021-05-18 11:10:46 +02:00
|
|
|
from ray.rllib.utils.framework import try_import_tf, try_import_torch
|
2021-03-11 09:51:39 -08:00
|
|
|
from ray.rllib.utils.test_utils import (
|
|
|
|
check_compute_single_action,
|
2021-09-30 16:39:05 +02:00
|
|
|
check_train_results,
|
|
|
|
framework_iterator,
|
2022-01-29 18:41:57 -08:00
|
|
|
)
|
2021-03-11 09:51:39 -08:00
|
|
|
|
2021-05-18 11:10:46 +02:00
|
|
|
tf1, tf, tfv = try_import_tf()
|
2021-05-13 09:17:23 +02:00
|
|
|
torch, _ = try_import_torch()
|
|
|
|
|
2021-03-11 09:51:39 -08:00
|
|
|
|
|
|
|
class TestCQL(unittest.TestCase):
|
|
|
|
@classmethod
|
|
|
|
def setUpClass(cls):
|
|
|
|
ray.init()
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def tearDownClass(cls):
|
|
|
|
ray.shutdown()
|
|
|
|
|
|
|
|
def test_cql_compilation(self):
|
2021-05-04 10:06:19 -07:00
|
|
|
"""Test whether a CQLTrainer can be built with all frameworks."""
|
|
|
|
|
|
|
|
# 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=SAC --env=Pendulum-v1 \
|
2021-05-04 10:06:19 -07:00
|
|
|
# --stop='{"timesteps_total": 50000}' \
|
|
|
|
# --config='{"output": "/tmp/out"}'
|
|
|
|
rllib_dir = Path(__file__).parent.parent.parent.parent
|
|
|
|
print("rllib dir={}".format(rllib_dir))
|
|
|
|
data_file = os.path.join(rllib_dir, "tests/data/pendulum/small.json")
|
|
|
|
print("data_file={} exists={}".format(data_file, os.path.isfile(data_file)))
|
|
|
|
|
2022-05-22 18:58:47 +01:00
|
|
|
config = (
|
|
|
|
cql.CQLConfig()
|
|
|
|
.environment(
|
|
|
|
env="Pendulum-v1",
|
|
|
|
)
|
|
|
|
.offline_data(
|
|
|
|
input_=[data_file],
|
|
|
|
# In the files, we use here for testing, actions have already
|
|
|
|
# been normalized.
|
|
|
|
# This is usually the case when the file was generated by another
|
|
|
|
# RLlib algorithm (e.g. PPO or SAC).
|
|
|
|
actions_in_input_normalized=False,
|
|
|
|
# Switch on off-policy evaluation.
|
|
|
|
input_evaluation=["is"],
|
|
|
|
)
|
|
|
|
.training(
|
|
|
|
clip_actions=False,
|
|
|
|
train_batch_size=2000,
|
|
|
|
twin_q=True,
|
|
|
|
replay_buffer_config={"learning_starts": 0},
|
|
|
|
bc_iters=2,
|
|
|
|
)
|
|
|
|
.evaluation(
|
|
|
|
always_attach_evaluation_results=True,
|
|
|
|
evaluation_interval=2,
|
|
|
|
evaluation_duration=10,
|
|
|
|
evaluation_config={"input": "sampler"},
|
|
|
|
evaluation_parallel_to_training=False,
|
|
|
|
evaluation_num_workers=2,
|
|
|
|
)
|
|
|
|
.rollouts(rollout_fragment_length=1)
|
|
|
|
)
|
2021-06-30 12:32:11 +02:00
|
|
|
num_iterations = 4
|
2021-03-11 09:51:39 -08:00
|
|
|
|
2021-05-18 11:10:46 +02:00
|
|
|
# Test for tf/torch frameworks.
|
2021-11-05 16:10:00 +01:00
|
|
|
for fw in framework_iterator(config, with_eager_tracing=True):
|
2022-05-22 18:58:47 +01:00
|
|
|
trainer = config.build()
|
2021-05-04 10:06:19 -07:00
|
|
|
for i in range(num_iterations):
|
2021-09-30 16:39:05 +02:00
|
|
|
results = trainer.train()
|
|
|
|
check_train_results(results)
|
|
|
|
print(results)
|
2022-04-26 14:28:39 +02:00
|
|
|
eval_results = results["evaluation"]
|
|
|
|
print(
|
|
|
|
f"iter={trainer.iteration} "
|
|
|
|
f"R={eval_results['episode_reward_mean']}"
|
|
|
|
)
|
2021-05-13 09:17:23 +02:00
|
|
|
|
2021-05-04 10:06:19 -07:00
|
|
|
check_compute_single_action(trainer)
|
2021-05-13 09:17:23 +02:00
|
|
|
|
2021-05-18 11:10:46 +02:00
|
|
|
# Get policy and model.
|
2021-05-13 09:17:23 +02:00
|
|
|
pol = trainer.get_policy()
|
|
|
|
cql_model = pol.model
|
2021-05-18 11:10:46 +02:00
|
|
|
if fw == "tf":
|
|
|
|
pol.get_session().__enter__()
|
2021-05-13 09:17:23 +02:00
|
|
|
|
|
|
|
# Example on how to do evaluation on the trained Trainer
|
2021-05-18 11:10:46 +02:00
|
|
|
# using the data from CQL's global replay buffer.
|
2021-05-13 09:17:23 +02:00
|
|
|
# Get a sample (MultiAgentBatch -> SampleBatch).
|
2021-10-26 11:56:02 -07:00
|
|
|
batch = trainer.local_replay_buffer.replay().policy_batches[
|
|
|
|
"default_policy"
|
|
|
|
]
|
2021-05-18 11:10:46 +02:00
|
|
|
|
|
|
|
if fw == "torch":
|
|
|
|
obs = torch.from_numpy(batch["obs"])
|
|
|
|
else:
|
|
|
|
obs = batch["obs"]
|
|
|
|
batch["actions"] = batch["actions"].astype(np.float32)
|
|
|
|
|
2021-05-13 09:17:23 +02:00
|
|
|
# Pass the observations through our model to get the
|
|
|
|
# features, which then to pass through the Q-head.
|
|
|
|
model_out, _ = cql_model({"obs": obs})
|
|
|
|
# The estimated Q-values from the (historic) actions in the batch.
|
2021-05-18 11:10:46 +02:00
|
|
|
if fw == "torch":
|
|
|
|
q_values_old = cql_model.get_q_values(
|
|
|
|
model_out, torch.from_numpy(batch["actions"])
|
2022-01-29 18:41:57 -08:00
|
|
|
)
|
2021-05-18 11:10:46 +02:00
|
|
|
else:
|
|
|
|
q_values_old = cql_model.get_q_values(
|
|
|
|
tf.convert_to_tensor(model_out), batch["actions"]
|
|
|
|
)
|
|
|
|
|
2021-05-13 09:17:23 +02:00
|
|
|
# The estimated Q-values for the new actions computed
|
|
|
|
# by our trainer policy.
|
|
|
|
actions_new = pol.compute_actions_from_input_dict({"obs": obs})[0]
|
2021-05-18 11:10:46 +02:00
|
|
|
if fw == "torch":
|
|
|
|
q_values_new = cql_model.get_q_values(
|
|
|
|
model_out, torch.from_numpy(actions_new)
|
2022-01-29 18:41:57 -08:00
|
|
|
)
|
2021-05-18 11:10:46 +02:00
|
|
|
else:
|
|
|
|
q_values_new = cql_model.get_q_values(model_out, actions_new)
|
|
|
|
|
|
|
|
if fw == "tf":
|
|
|
|
q_values_old, q_values_new = pol.get_session().run(
|
|
|
|
[q_values_old, q_values_new]
|
|
|
|
)
|
|
|
|
|
2021-05-13 09:17:23 +02:00
|
|
|
print(f"Q-val batch={q_values_old}")
|
|
|
|
print(f"Q-val policy={q_values_new}")
|
|
|
|
|
2021-05-18 11:10:46 +02:00
|
|
|
if fw == "tf":
|
|
|
|
pol.get_session().__exit__(None, None, None)
|
|
|
|
|
2021-05-04 10:06:19 -07:00
|
|
|
trainer.stop()
|
2021-03-11 09:51:39 -08:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
import pytest
|
|
|
|
import sys
|
2022-01-29 18:41:57 -08:00
|
|
|
|
2021-03-11 09:51:39 -08:00
|
|
|
sys.exit(pytest.main(["-v", __file__]))
|