2019-06-01 16:13:21 +08:00
|
|
|
import argparse
|
2020-10-02 23:07:44 +02:00
|
|
|
import os
|
2019-06-01 16:13:21 +08:00
|
|
|
|
|
|
|
import ray
|
2022-07-27 04:12:59 -07:00
|
|
|
from ray import air, tune
|
2022-06-11 15:10:39 +02:00
|
|
|
from ray.rllib.algorithms.algorithm import Algorithm
|
2020-12-26 20:14:18 -05:00
|
|
|
from ray.rllib.policy.policy_template import build_policy_class
|
2019-06-01 16:13:21 +08:00
|
|
|
from ray.rllib.policy.sample_batch import SampleBatch
|
|
|
|
|
|
|
|
parser = argparse.ArgumentParser()
|
2020-05-12 08:23:10 +02:00
|
|
|
parser.add_argument("--stop-iters", type=int, default=200)
|
2020-02-15 23:50:44 +01:00
|
|
|
parser.add_argument("--num-cpus", type=int, default=0)
|
2019-06-01 16:13:21 +08:00
|
|
|
|
|
|
|
|
2019-08-23 02:21:11 -04:00
|
|
|
def policy_gradient_loss(policy, model, dist_class, train_batch):
|
|
|
|
logits, _ = model({SampleBatch.CUR_OBS: train_batch[SampleBatch.CUR_OBS]})
|
|
|
|
action_dist = dist_class(logits, model)
|
|
|
|
log_probs = action_dist.logp(train_batch[SampleBatch.ACTIONS])
|
|
|
|
return -train_batch[SampleBatch.REWARDS].dot(log_probs)
|
2019-06-01 16:13:21 +08:00
|
|
|
|
|
|
|
|
|
|
|
# <class 'ray.rllib.policy.torch_policy_template.MyTorchPolicy'>
|
2020-12-26 20:14:18 -05:00
|
|
|
MyTorchPolicy = build_policy_class(
|
|
|
|
name="MyTorchPolicy", framework="torch", loss_fn=policy_gradient_loss
|
|
|
|
)
|
2019-06-01 16:13:21 +08:00
|
|
|
|
2022-03-25 18:25:51 +01:00
|
|
|
|
2022-06-11 15:10:39 +02:00
|
|
|
# Create a new Algorithm using the Policy defined above.
|
|
|
|
class MyAlgorithm(Algorithm):
|
2022-03-25 18:25:51 +01:00
|
|
|
def get_default_policy_class(self, config):
|
|
|
|
return MyTorchPolicy
|
|
|
|
|
2019-06-01 16:13:21 +08:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
args = parser.parse_args()
|
2020-02-15 23:50:44 +01:00
|
|
|
ray.init(num_cpus=args.num_cpus or None)
|
2022-07-27 04:12:59 -07:00
|
|
|
tuner = tune.Tuner(
|
2022-06-11 15:10:39 +02:00
|
|
|
MyAlgorithm,
|
2022-07-27 04:12:59 -07:00
|
|
|
run_config=air.RunConfig(
|
|
|
|
stop={"training_iteration": args.stop_iters},
|
|
|
|
),
|
|
|
|
param_space={
|
2019-06-01 16:13:21 +08:00
|
|
|
"env": "CartPole-v0",
|
2020-10-02 23:07:44 +02:00
|
|
|
# Use GPUs iff `RLLIB_NUM_GPUS` env var set to > 0.
|
|
|
|
"num_gpus": int(os.environ.get("RLLIB_NUM_GPUS", "0")),
|
2019-06-01 16:13:21 +08:00
|
|
|
"num_workers": 2,
|
2020-05-27 16:19:13 +02:00
|
|
|
"framework": "torch",
|
2019-06-01 16:13:21 +08:00
|
|
|
},
|
|
|
|
)
|
2022-07-27 04:12:59 -07:00
|
|
|
tuner.fit()
|