custom_input_api.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. """Example of creating a custom input api
  2. Custom input apis are useful when your data source is in a custom format or
  3. when it is necessary to use an external data loading mechanism.
  4. In this example, we train an rl agent on user specified input data.
  5. Instead of using the built in JsonReader, we will create our own custom input
  6. api, and show how to pass config arguments to it.
  7. To train CQL on the pendulum environment:
  8. $ python custom_input_api.py --input-files=../tests/data/pendulum/enormous.zip
  9. """
  10. import argparse
  11. import os
  12. import ray
  13. from ray import tune
  14. from ray.rllib.offline import JsonReader, ShuffledInput, IOContext, InputReader
  15. from ray.tune.registry import register_input
  16. parser = argparse.ArgumentParser()
  17. parser.add_argument(
  18. "--run",
  19. type=str,
  20. default="CQL",
  21. help="The RLlib-registered algorithm to use.")
  22. parser.add_argument(
  23. "--framework",
  24. choices=["tf", "tf2", "tfe", "torch"],
  25. default="tf",
  26. help="The DL framework specifier.")
  27. parser.add_argument("--stop-iters", type=int, default=100)
  28. parser.add_argument(
  29. "--input-files",
  30. type=str,
  31. default=os.path.join(
  32. os.path.dirname(os.path.abspath(__file__)),
  33. "../tests/data/pendulum/small.json"))
  34. class CustomJsonReader(JsonReader):
  35. """
  36. Example custom InputReader implementation (extended from JsonReader).
  37. This gets wrapped in ShuffledInput to comply with offline rl algorithms.
  38. """
  39. def __init__(self, ioctx: IOContext):
  40. """
  41. The constructor must take an IOContext to be used in the input config.
  42. Args:
  43. ioctx (IOContext): use this to access the `input_config` arguments.
  44. """
  45. super().__init__(ioctx.input_config["input_files"], ioctx)
  46. def input_creator(ioctx: IOContext) -> InputReader:
  47. """
  48. The input creator method can be used in the input registry or set as the
  49. config["input"] parameter.
  50. Args:
  51. ioctx (IOContext): use this to access the `input_config` arguments.
  52. Returns:
  53. instance of ShuffledInput to work with some offline rl algorithms
  54. """
  55. return ShuffledInput(CustomJsonReader(ioctx))
  56. if __name__ == "__main__":
  57. ray.init()
  58. args = parser.parse_args()
  59. # make absolute path because relative path looks in result directory
  60. args.input_files = os.path.abspath(args.input_files)
  61. # we register our custom input creator with this convenient function
  62. register_input("custom_input", input_creator)
  63. # config modified from rllib/tuned_examples/cql/pendulum-cql.yaml
  64. config = {
  65. "env": "Pendulum-v1",
  66. # we can either use the tune registry, class path, or direct function
  67. # to connect our input api.
  68. "input": "custom_input",
  69. # "input": "ray.rllib.examples.custom_input_api.CustomJsonReader",
  70. # "input": input_creator,
  71. # this gets passed to the IOContext
  72. "input_config": {
  73. "input_files": args.input_files,
  74. },
  75. "framework": args.framework,
  76. "actions_in_input_normalized": True,
  77. "clip_actions": True,
  78. "twin_q": True,
  79. "train_batch_size": 2000,
  80. "learning_starts": 0,
  81. "bc_iters": 100,
  82. "metrics_num_episodes_for_smoothing": 5,
  83. "evaluation_interval": 1,
  84. "evaluation_num_workers": 2,
  85. "evaluation_duration": 10,
  86. "evaluation_parallel_to_training": True,
  87. "evaluation_config": {
  88. "input": "sampler",
  89. "explore": False,
  90. }
  91. }
  92. stop = {
  93. "training_iteration": args.stop_iters,
  94. "evaluation/episode_reward_mean": -600,
  95. }
  96. analysis = tune.run(args.run, config=config, stop=stop, verbose=1)
  97. info = analysis.results[next(iter(analysis.results))]["info"]