mirror of
https://github.com/wassname/ray.git
synced 2026-09-10 12:38:43 +08:00
[RLlib] Examples folder restructuring (Model examples; final part). (#8278)
- This PR completes any previously missing PyTorch Model counterparts to TFModels in examples/models. - It also makes sure, all example scripts in the rllib/examples folder are tested for both frameworks and learn the given task (this is often currently not checked) using a --as-test flag in connection with a --stop-reward.
This commit is contained in:
@@ -7,20 +7,32 @@ This example shows:
|
||||
|
||||
You can visualize experiment results in ~/ray_results using TensorBoard.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import numpy as np
|
||||
import gym
|
||||
from ray.rllib.models import ModelCatalog
|
||||
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
|
||||
from ray.rllib.models.tf.fcnet_v2 import FullyConnectedNetwork
|
||||
from gym.spaces import Discrete, Box
|
||||
|
||||
import ray
|
||||
from ray import tune
|
||||
from ray.rllib.utils import try_import_tf
|
||||
from ray.tune import grid_search
|
||||
from ray.rllib.models import ModelCatalog
|
||||
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
|
||||
from ray.rllib.models.tf.fcnet_v2 import FullyConnectedNetwork
|
||||
from ray.rllib.models.torch.torch_modelv2 import TorchModelV2
|
||||
from ray.rllib.models.torch.fcnet import FullyConnectedNetwork as TorchFC
|
||||
from ray.rllib.utils.framework import try_import_tf, try_import_torch
|
||||
from ray.rllib.utils.test_utils import check_learning_achieved
|
||||
|
||||
tf = try_import_tf()
|
||||
torch, nn = try_import_torch()
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--run", type=str, default="PPO")
|
||||
parser.add_argument("--torch", action="store_true")
|
||||
parser.add_argument("--as-test", action="store_true")
|
||||
parser.add_argument("--stop-iters", type=int, default=50)
|
||||
parser.add_argument("--stop-timesteps", type=int, default=100000)
|
||||
parser.add_argument("--stop-reward", type=float, default=0.1)
|
||||
|
||||
|
||||
class SimpleCorridor(gym.Env):
|
||||
@@ -46,11 +58,11 @@ class SimpleCorridor(gym.Env):
|
||||
elif action == 1:
|
||||
self.cur_pos += 1
|
||||
done = self.cur_pos >= self.end_pos
|
||||
return [self.cur_pos], 1 if done else 0, done, {}
|
||||
return [self.cur_pos], 1.0 if done else -0.1, done, {}
|
||||
|
||||
|
||||
class CustomModel(TFModelV2):
|
||||
"""Example of a custom model that just delegates to a fc-net."""
|
||||
"""Example of a keras custom model that just delegates to an fc-net."""
|
||||
|
||||
def __init__(self, obs_space, action_space, num_outputs, model_config,
|
||||
name):
|
||||
@@ -67,26 +79,58 @@ class CustomModel(TFModelV2):
|
||||
return self.model.value_function()
|
||||
|
||||
|
||||
class TorchCustomModel(TorchModelV2, nn.Module):
|
||||
"""Example of a PyTorch custom model that just delegates to a fc-net."""
|
||||
|
||||
def __init__(self, obs_space, action_space, num_outputs, model_config,
|
||||
name):
|
||||
TorchModelV2.__init__(self, obs_space, action_space, num_outputs,
|
||||
model_config, name)
|
||||
nn.Module.__init__(self)
|
||||
|
||||
self.torch_sub_model = TorchFC(obs_space, action_space, num_outputs,
|
||||
model_config, name)
|
||||
|
||||
def forward(self, input_dict, state, seq_lens):
|
||||
input_dict["obs"] = input_dict["obs"].float()
|
||||
fc_out, _ = self.torch_sub_model(input_dict, state, seq_lens)
|
||||
return fc_out, []
|
||||
|
||||
def value_function(self):
|
||||
return torch.reshape(self.torch_sub_model.value_function(), [-1])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
args = parser.parse_args()
|
||||
ray.init()
|
||||
|
||||
# Can also register the env creator function explicitly with:
|
||||
# register_env("corridor", lambda config: SimpleCorridor(config))
|
||||
ray.init()
|
||||
ModelCatalog.register_custom_model("my_model", CustomModel)
|
||||
tune.run(
|
||||
"PPO",
|
||||
stop={
|
||||
"timesteps_total": 10000,
|
||||
ModelCatalog.register_custom_model(
|
||||
"my_model", TorchCustomModel if args.torch else CustomModel)
|
||||
|
||||
config = {
|
||||
"env": SimpleCorridor, # or "corridor" if registered above
|
||||
"env_config": {
|
||||
"corridor_length": 5,
|
||||
},
|
||||
config={
|
||||
"env": SimpleCorridor, # or "corridor" if registered above
|
||||
"model": {
|
||||
"custom_model": "my_model",
|
||||
},
|
||||
"vf_share_layers": True,
|
||||
"lr": grid_search([1e-2, 1e-4, 1e-6]), # try different lrs
|
||||
"num_workers": 1, # parallelism
|
||||
"env_config": {
|
||||
"corridor_length": 5,
|
||||
},
|
||||
"model": {
|
||||
"custom_model": "my_model",
|
||||
},
|
||||
)
|
||||
"vf_share_layers": True,
|
||||
"lr": grid_search([1e-2, 1e-4, 1e-6]), # try different lrs
|
||||
"num_workers": 1, # parallelism
|
||||
"use_pytorch": args.torch
|
||||
}
|
||||
|
||||
stop = {
|
||||
"training_iteration": args.stop_iters,
|
||||
"timesteps_total": args.stop_timesteps,
|
||||
"episode_reward_mean": args.stop_reward,
|
||||
}
|
||||
|
||||
results = tune.run(args.run, config=config, stop=stop)
|
||||
|
||||
if args.as_test:
|
||||
check_learning_achieved(results, args.stop_reward)
|
||||
ray.shutdown()
|
||||
|
||||
Reference in New Issue
Block a user