2019-01-29 21:06:09 -08:00
|
|
|
"""Example of a custom training workflow. Run this for a demo.
|
|
|
|
|
|
|
|
This example shows:
|
|
|
|
- using Tune trainable functions to implement custom training workflows
|
|
|
|
|
|
|
|
You can visualize experiment results in ~/ray_results using TensorBoard.
|
|
|
|
"""
|
2020-05-01 22:59:34 +02:00
|
|
|
import argparse
|
2020-10-02 23:07:44 +02:00
|
|
|
import os
|
2019-01-29 21:06:09 -08:00
|
|
|
|
|
|
|
import ray
|
2019-03-30 14:07:50 -07:00
|
|
|
from ray import tune
|
2019-04-07 00:36:18 -07:00
|
|
|
from ray.rllib.agents.ppo import PPOTrainer
|
2019-01-29 21:06:09 -08:00
|
|
|
|
2020-05-01 22:59:34 +02:00
|
|
|
parser = argparse.ArgumentParser()
|
2021-05-18 13:18:12 +02:00
|
|
|
parser.add_argument(
|
|
|
|
"--framework",
|
|
|
|
choices=["tf", "tf2", "tfe", "torch"],
|
|
|
|
default="tf",
|
2022-01-29 18:41:57 -08:00
|
|
|
help="The DL framework specifier.",
|
|
|
|
)
|
2020-05-01 22:59:34 +02:00
|
|
|
|
2019-01-29 21:06:09 -08:00
|
|
|
|
|
|
|
def my_train_fn(config, reporter):
|
2021-09-15 22:16:48 +02:00
|
|
|
iterations = config.pop("train-iterations", 10)
|
|
|
|
|
2021-05-10 16:09:05 +02:00
|
|
|
# Train for n iterations with high LR
|
2019-04-07 00:36:18 -07:00
|
|
|
agent1 = PPOTrainer(env="CartPole-v0", config=config)
|
2021-09-15 22:16:48 +02:00
|
|
|
for _ in range(iterations):
|
2019-01-29 21:06:09 -08:00
|
|
|
result = agent1.train()
|
|
|
|
result["phase"] = 1
|
|
|
|
reporter(**result)
|
|
|
|
phase1_time = result["timesteps_total"]
|
|
|
|
state = agent1.save()
|
|
|
|
agent1.stop()
|
|
|
|
|
2021-05-10 16:09:05 +02:00
|
|
|
# Train for n iterations with low LR
|
2019-01-29 21:06:09 -08:00
|
|
|
config["lr"] = 0.0001
|
2019-04-07 00:36:18 -07:00
|
|
|
agent2 = PPOTrainer(env="CartPole-v0", config=config)
|
2019-01-29 21:06:09 -08:00
|
|
|
agent2.restore(state)
|
2021-09-15 22:16:48 +02:00
|
|
|
for _ in range(iterations):
|
2019-01-29 21:06:09 -08:00
|
|
|
result = agent2.train()
|
|
|
|
result["phase"] = 2
|
|
|
|
result["timesteps_total"] += phase1_time # keep time moving forward
|
|
|
|
reporter(**result)
|
|
|
|
agent2.stop()
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
ray.init()
|
2020-05-01 22:59:34 +02:00
|
|
|
args = parser.parse_args()
|
2019-06-03 06:47:39 +08:00
|
|
|
config = {
|
2021-09-15 22:16:48 +02:00
|
|
|
# Special flag signalling `my_train_fn` how many iters to do.
|
|
|
|
"train-iterations": 2,
|
2019-06-03 06:47:39 +08:00
|
|
|
"lr": 0.01,
|
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-03 06:47:39 +08:00
|
|
|
"num_workers": 0,
|
2021-05-18 13:18:12 +02:00
|
|
|
"framework": args.framework,
|
2019-06-03 06:47:39 +08:00
|
|
|
}
|
2021-09-15 22:16:48 +02:00
|
|
|
resources = PPOTrainer.default_resource_request(config)
|
2019-06-03 06:47:39 +08:00
|
|
|
tune.run(my_train_fn, resources_per_trial=resources, config=config)
|