curriculum_learning.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. """
  2. Example of a curriculum learning setup using the `TaskSettableEnv` API
  3. and the env_task_fn config.
  4. This example shows:
  5. - Writing your own curriculum-capable environment using gym.Env.
  6. - Defining a env_task_fn that determines, whether and which new task
  7. the env(s) should be set to (using the TaskSettableEnv API).
  8. - Using Tune and RLlib to curriculum-learn this env.
  9. You can visualize experiment results in ~/ray_results using TensorBoard.
  10. """
  11. import argparse
  12. import numpy as np
  13. import os
  14. import ray
  15. from ray import tune
  16. from ray.rllib.env.apis.task_settable_env import TaskSettableEnv, TaskType
  17. from ray.rllib.env.env_context import EnvContext
  18. from ray.rllib.examples.env.curriculum_capable_env import CurriculumCapableEnv
  19. from ray.rllib.utils.framework import try_import_tf, try_import_torch
  20. from ray.rllib.utils.test_utils import check_learning_achieved
  21. tf1, tf, tfv = try_import_tf()
  22. torch, nn = try_import_torch()
  23. parser = argparse.ArgumentParser()
  24. parser.add_argument(
  25. "--run",
  26. type=str,
  27. default="PPO",
  28. help="The RLlib-registered algorithm to use.")
  29. parser.add_argument(
  30. "--framework",
  31. choices=["tf", "tf2", "tfe", "torch"],
  32. default="tf",
  33. help="The DL framework specifier.")
  34. parser.add_argument(
  35. "--as-test",
  36. action="store_true",
  37. help="Whether this script should be run as a test: --stop-reward must "
  38. "be achieved within --stop-timesteps AND --stop-iters.")
  39. parser.add_argument(
  40. "--stop-iters",
  41. type=int,
  42. default=50,
  43. help="Number of iterations to train.")
  44. parser.add_argument(
  45. "--stop-timesteps",
  46. type=int,
  47. default=200000,
  48. help="Number of timesteps to train.")
  49. parser.add_argument(
  50. "--stop-reward",
  51. type=float,
  52. default=10000.0,
  53. help="Reward at which we stop training.")
  54. def curriculum_fn(train_results: dict, task_settable_env: TaskSettableEnv,
  55. env_ctx: EnvContext) -> TaskType:
  56. """Function returning a possibly new task to set `task_settable_env` to.
  57. Args:
  58. train_results (dict): The train results returned by Trainer.train().
  59. task_settable_env (TaskSettableEnv): A single TaskSettableEnv object
  60. used inside any worker and at any vector position. Use `env_ctx`
  61. to get the worker_index, vector_index, and num_workers.
  62. env_ctx (EnvContext): The env context object (i.e. env's config dict
  63. plus properties worker_index, vector_index and num_workers) used
  64. to setup the `task_settable_env`.
  65. Returns:
  66. TaskType: The task to set the env to. This may be the same as the
  67. current one.
  68. """
  69. # Our env supports tasks 1 (default) to 5.
  70. # With each task, rewards get scaled up by a factor of 10, such that:
  71. # Level 1: Expect rewards between 0.0 and 1.0.
  72. # Level 2: Expect rewards between 1.0 and 10.0, etc..
  73. # We will thus raise the level/task each time we hit a new power of 10.0
  74. new_task = int(np.log10(train_results["episode_reward_mean"]) + 2.1)
  75. # Clamp between valid values, just in case:
  76. new_task = max(min(new_task, 5), 1)
  77. print(f"Worker #{env_ctx.worker_index} vec-idx={env_ctx.vector_index}"
  78. f"\nR={train_results['episode_reward_mean']}"
  79. f"\nSetting env to task={new_task}")
  80. return new_task
  81. if __name__ == "__main__":
  82. args = parser.parse_args()
  83. ray.init()
  84. # Can also register the env creator function explicitly with:
  85. # register_env(
  86. # "curriculum_env", lambda config: CurriculumCapableEnv(config))
  87. config = {
  88. "env": CurriculumCapableEnv, # or "curriculum_env" if registered above
  89. "env_config": {
  90. "start_level": 1,
  91. },
  92. "num_workers": 2, # parallelism
  93. "num_envs_per_worker": 5,
  94. "env_task_fn": curriculum_fn,
  95. # Use GPUs iff `RLLIB_NUM_GPUS` env var set to > 0.
  96. "num_gpus": int(os.environ.get("RLLIB_NUM_GPUS", "0")),
  97. "framework": args.framework,
  98. }
  99. stop = {
  100. "training_iteration": args.stop_iters,
  101. "timesteps_total": args.stop_timesteps,
  102. "episode_reward_mean": args.stop_reward,
  103. }
  104. results = tune.run(args.run, config=config, stop=stop, verbose=2)
  105. if args.as_test:
  106. check_learning_achieved(results, args.stop_reward)
  107. ray.shutdown()