You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

147 lines
4.9 KiB

11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
  1. import gymnasium as gym
  2. import minigrid
  3. from ray.tune import register_env
  4. from ray.rllib.algorithms.ppo import PPOConfig
  5. from ray.rllib.algorithms.dqn.dqn import DQNConfig
  6. from ray.tune.logger import pretty_print
  7. from ray.rllib.models import ModelCatalog
  8. from torch_action_mask_model import TorchActionMaskModel
  9. from wrappers import OneHotShieldingWrapper, MiniGridShieldingWrapper
  10. from helpers import parse_arguments, create_log_dir, ShieldingConfig
  11. from shieldhandlers import MiniGridShieldHandler, create_shield_query
  12. from callbacks import MyCallbacks
  13. from ray.tune.logger import TBXLogger
  14. def shielding_env_creater(config):
  15. name = config.get("name", "MiniGrid-LavaCrossingS9N1-v0")
  16. framestack = config.get("framestack", 4)
  17. args = config.get("args", None)
  18. args.grid_path = F"{args.grid_path}_{config.worker_index}_{args.prism_config}.txt"
  19. args.prism_path = F"{args.prism_path}_{config.worker_index}_{args.prism_config}.prism"
  20. prob_forward = args.prob_forward
  21. prob_direct = args.prob_direct
  22. prob_next = args.prob_next
  23. shield_creator = MiniGridShieldHandler(args.grid_path,
  24. args.grid_to_prism_binary_path,
  25. args.prism_path,
  26. args.formula,
  27. args.shield_value,
  28. args.prism_config,
  29. shield_comparision=args.shield_comparision)
  30. env = gym.make(name, randomize_start=True,probability_forward=prob_forward, probability_direct_neighbour=prob_direct, probability_next_neighbour=prob_next)
  31. env = MiniGridShieldingWrapper(env, shield_creator=shield_creator,
  32. shield_query_creator=create_shield_query,
  33. mask_actions=args.shielding != ShieldingConfig.Disabled,
  34. create_shield_at_reset=args.shield_creation_at_reset)
  35. # env = minigrid.wrappers.ImgObsWrapper(env)
  36. # env = ImgObsWrapper(env)
  37. env = OneHotShieldingWrapper(env,
  38. config.vector_index if hasattr(config, "vector_index") else 0,
  39. framestack=framestack
  40. )
  41. return env
  42. def register_minigrid_shielding_env(args):
  43. env_name = "mini-grid-shielding"
  44. register_env(env_name, shielding_env_creater)
  45. ModelCatalog.register_custom_model(
  46. "shielding_model",
  47. TorchActionMaskModel
  48. )
  49. def ppo(args):
  50. register_minigrid_shielding_env(args)
  51. config = (PPOConfig()
  52. .rollouts(num_rollout_workers=args.workers)
  53. .resources(num_gpus=0)
  54. .environment(env="mini-grid-shielding", env_config={"name": args.env, "args": args, "shielding": args.shielding is ShieldingConfig.Full or args.shielding is ShieldingConfig.Training})
  55. .framework("torch")
  56. .callbacks(MyCallbacks)
  57. .rl_module(_enable_rl_module_api = False)
  58. .debugging(logger_config={
  59. "type": TBXLogger,
  60. "logdir": create_log_dir(args)
  61. })
  62. # .exploration(exploration_config={"exploration_fraction": 0.1})
  63. .training(_enable_learner_api=False ,model={
  64. "custom_model": "shielding_model"
  65. }))
  66. # config.entropy_coeff = 0.05
  67. algo =(
  68. config.build()
  69. )
  70. for i in range(args.evaluations):
  71. result = algo.train()
  72. print(pretty_print(result))
  73. if i % 5 == 0:
  74. checkpoint_dir = algo.save()
  75. print(f"Checkpoint saved in directory {checkpoint_dir}")
  76. algo.save()
  77. def dqn(args):
  78. register_minigrid_shielding_env(args)
  79. config = DQNConfig()
  80. config = config.resources(num_gpus=0)
  81. config = config.rollouts(num_rollout_workers=args.workers)
  82. config = config.environment(env="mini-grid-shielding", env_config={"name": args.env, "args": args })
  83. config = config.framework("torch")
  84. config = config.callbacks(MyCallbacks)
  85. config = config.rl_module(_enable_rl_module_api = False)
  86. config = config.debugging(logger_config={
  87. "type": TBXLogger,
  88. "logdir": create_log_dir(args)
  89. })
  90. config = config.training(hiddens=[], dueling=False, model={
  91. "custom_model": "shielding_model"
  92. })
  93. algo = (
  94. config.build()
  95. )
  96. for i in range(args.evaluations):
  97. result = algo.train()
  98. print(pretty_print(result))
  99. if i % 5 == 0:
  100. print("Saving checkpoint")
  101. checkpoint_dir = algo.save()
  102. print(f"Checkpoint saved in directory {checkpoint_dir}")
  103. def main():
  104. import argparse
  105. args = parse_arguments(argparse)
  106. if args.algorithm == "PPO":
  107. ppo(args)
  108. elif args.algorithm == "DQN":
  109. dqn(args)
  110. if __name__ == '__main__':
  111. main()