2019-07-24 13:09:41 -07:00
|
|
|
"""Example of using a custom ModelV2 Keras-style model."""
|
2019-07-03 15:59:47 -07:00
|
|
|
|
|
|
|
import argparse
|
2020-10-02 23:07:44 +02:00
|
|
|
import os
|
2019-07-03 15:59:47 -07:00
|
|
|
|
|
|
|
import ray
|
|
|
|
from ray import tune
|
2020-06-16 08:52:20 +02:00
|
|
|
from ray.rllib.agents.dqn.distributional_q_tf_model import \
|
|
|
|
DistributionalQTFModel
|
2019-07-03 15:59:47 -07:00
|
|
|
from ray.rllib.models import ModelCatalog
|
2019-07-27 02:08:16 -07:00
|
|
|
from ray.rllib.models.tf.misc import normc_initializer
|
2019-07-03 15:59:47 -07:00
|
|
|
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
|
2020-05-18 17:26:40 +02:00
|
|
|
from ray.rllib.models.tf.visionnet import VisionNetwork as MyVisionNetwork
|
2021-03-08 15:41:27 +01:00
|
|
|
from ray.rllib.policy.policy import LEARNER_STATS_KEY
|
2020-12-27 09:46:03 -05:00
|
|
|
from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID
|
2020-06-16 08:52:20 +02:00
|
|
|
from ray.rllib.utils.framework import try_import_tf
|
2019-07-03 15:59:47 -07:00
|
|
|
|
2020-06-30 10:13:20 +02:00
|
|
|
tf1, tf, tfv = try_import_tf()
|
2019-07-03 15:59:47 -07:00
|
|
|
|
|
|
|
parser = argparse.ArgumentParser()
|
2021-05-18 13:18:12 +02:00
|
|
|
parser.add_argument(
|
|
|
|
"--run",
|
|
|
|
type=str,
|
|
|
|
default="DQN",
|
|
|
|
help="The RLlib-registered algorithm to use.")
|
2019-07-03 15:59:47 -07:00
|
|
|
parser.add_argument("--stop", type=int, default=200)
|
2020-05-12 08:23:10 +02:00
|
|
|
parser.add_argument("--use-vision-network", action="store_true")
|
2020-02-15 23:50:44 +01:00
|
|
|
parser.add_argument("--num-cpus", type=int, default=0)
|
2019-07-03 15:59:47 -07:00
|
|
|
|
|
|
|
|
|
|
|
class MyKerasModel(TFModelV2):
|
|
|
|
"""Custom model for policy gradient algorithms."""
|
|
|
|
|
|
|
|
def __init__(self, obs_space, action_space, num_outputs, model_config,
|
|
|
|
name):
|
|
|
|
super(MyKerasModel, self).__init__(obs_space, action_space,
|
|
|
|
num_outputs, model_config, name)
|
|
|
|
self.inputs = tf.keras.layers.Input(
|
|
|
|
shape=obs_space.shape, name="observations")
|
|
|
|
layer_1 = tf.keras.layers.Dense(
|
|
|
|
128,
|
|
|
|
name="my_layer1",
|
|
|
|
activation=tf.nn.relu,
|
|
|
|
kernel_initializer=normc_initializer(1.0))(self.inputs)
|
|
|
|
layer_out = tf.keras.layers.Dense(
|
|
|
|
num_outputs,
|
|
|
|
name="my_out",
|
|
|
|
activation=None,
|
|
|
|
kernel_initializer=normc_initializer(0.01))(layer_1)
|
|
|
|
value_out = tf.keras.layers.Dense(
|
|
|
|
1,
|
|
|
|
name="value_out",
|
|
|
|
activation=None,
|
|
|
|
kernel_initializer=normc_initializer(0.01))(layer_1)
|
|
|
|
self.base_model = tf.keras.Model(self.inputs, [layer_out, value_out])
|
|
|
|
|
|
|
|
def forward(self, input_dict, state, seq_lens):
|
|
|
|
model_out, self._value_out = self.base_model(input_dict["obs"])
|
|
|
|
return model_out, state
|
|
|
|
|
|
|
|
def value_function(self):
|
|
|
|
return tf.reshape(self._value_out, [-1])
|
|
|
|
|
2020-03-23 12:40:22 -07:00
|
|
|
def metrics(self):
|
|
|
|
return {"foo": tf.constant(42.0)}
|
|
|
|
|
2019-07-03 15:59:47 -07:00
|
|
|
|
2020-04-06 20:56:16 +02:00
|
|
|
class MyKerasQModel(DistributionalQTFModel):
|
2019-07-03 15:59:47 -07:00
|
|
|
"""Custom model for DQN."""
|
|
|
|
|
|
|
|
def __init__(self, obs_space, action_space, num_outputs, model_config,
|
|
|
|
name, **kw):
|
|
|
|
super(MyKerasQModel, self).__init__(
|
|
|
|
obs_space, action_space, num_outputs, model_config, name, **kw)
|
|
|
|
|
|
|
|
# Define the core model layers which will be used by the other
|
|
|
|
# output heads of DistributionalQModel
|
|
|
|
self.inputs = tf.keras.layers.Input(
|
|
|
|
shape=obs_space.shape, name="observations")
|
|
|
|
layer_1 = tf.keras.layers.Dense(
|
|
|
|
128,
|
|
|
|
name="my_layer1",
|
|
|
|
activation=tf.nn.relu,
|
|
|
|
kernel_initializer=normc_initializer(1.0))(self.inputs)
|
|
|
|
layer_out = tf.keras.layers.Dense(
|
|
|
|
num_outputs,
|
|
|
|
name="my_out",
|
|
|
|
activation=tf.nn.relu,
|
|
|
|
kernel_initializer=normc_initializer(1.0))(layer_1)
|
|
|
|
self.base_model = tf.keras.Model(self.inputs, layer_out)
|
|
|
|
|
2021-03-08 15:41:27 +01:00
|
|
|
# Implement the core forward method.
|
2019-07-03 15:59:47 -07:00
|
|
|
def forward(self, input_dict, state, seq_lens):
|
|
|
|
model_out = self.base_model(input_dict["obs"])
|
|
|
|
return model_out, state
|
|
|
|
|
2020-03-23 12:40:22 -07:00
|
|
|
def metrics(self):
|
|
|
|
return {"foo": tf.constant(42.0)}
|
|
|
|
|
2019-07-03 15:59:47 -07:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
args = parser.parse_args()
|
2021-03-29 20:07:44 +02:00
|
|
|
ray.init(num_cpus=args.num_cpus or None)
|
2019-11-25 00:11:24 -08:00
|
|
|
ModelCatalog.register_custom_model(
|
|
|
|
"keras_model", MyVisionNetwork
|
|
|
|
if args.use_vision_network else MyKerasModel)
|
|
|
|
ModelCatalog.register_custom_model(
|
|
|
|
"keras_q_model", MyVisionNetwork
|
|
|
|
if args.use_vision_network else MyKerasQModel)
|
2020-03-23 12:40:22 -07:00
|
|
|
|
|
|
|
# Tests https://github.com/ray-project/ray/issues/7293
|
|
|
|
def check_has_custom_metric(result):
|
|
|
|
r = result["result"]["info"]["learner"]
|
2020-12-27 09:46:03 -05:00
|
|
|
if DEFAULT_POLICY_ID in r:
|
2021-03-08 15:41:27 +01:00
|
|
|
r = r[DEFAULT_POLICY_ID].get(LEARNER_STATS_KEY,
|
|
|
|
r[DEFAULT_POLICY_ID])
|
2020-03-23 12:40:22 -07:00
|
|
|
assert r["model"]["foo"] == 42, result
|
|
|
|
|
|
|
|
if args.run == "DQN":
|
|
|
|
extra_config = {"learning_starts": 0}
|
|
|
|
else:
|
|
|
|
extra_config = {}
|
|
|
|
|
2019-07-03 15:59:47 -07:00
|
|
|
tune.run(
|
|
|
|
args.run,
|
|
|
|
stop={"episode_reward_mean": args.stop},
|
2020-03-23 12:40:22 -07:00
|
|
|
config=dict(
|
2020-10-02 23:07:44 +02:00
|
|
|
extra_config,
|
|
|
|
**{
|
2020-03-23 12:40:22 -07:00
|
|
|
"env": "BreakoutNoFrameskip-v4"
|
|
|
|
if args.use_vision_network else "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")),
|
2020-03-23 12:40:22 -07:00
|
|
|
"callbacks": {
|
|
|
|
"on_train_result": check_has_custom_metric,
|
|
|
|
},
|
|
|
|
"model": {
|
|
|
|
"custom_model": "keras_q_model"
|
|
|
|
if args.run == "DQN" else "keras_model"
|
|
|
|
},
|
2020-05-27 16:19:13 +02:00
|
|
|
"framework": "tf",
|
2020-03-23 12:40:22 -07:00
|
|
|
}))
|