{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Train a Multi agent system using RLLIB\n", "\n", "© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK\n", "\n", "This notebook will demonstrate how to use the `PrimaiteRayMARLEnv` to train a very basic system with two PPO agents." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### First, Import packages and read our config file." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from primaite.game.game import PrimaiteGame\n", "import yaml\n", "\n", "from primaite.session.ray_envs import PrimaiteRayEnv\n", "from primaite import PRIMAITE_PATHS\n", "\n", "import ray\n", "from ray import air, tune\n", "from ray.rllib.algorithms.ppo import PPOConfig\n", "from primaite.session.ray_envs import PrimaiteRayMARLEnv\n", "\n", "# If you get an error saying this config file doesn't exist, you may need to run `primaite setup` in your command line\n", "# to copy the files to your user data path.\n", "with open(PRIMAITE_PATHS.user_config_path / 'example_config/data_manipulation_marl.yaml', 'r') as f:\n", " cfg = yaml.safe_load(f)\n", "\n", "ray.init(local_mode=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Create a Ray algorithm config which accepts our two agents" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "config = (\n", " PPOConfig()\n", " .multi_agent(\n", " policies={'defender_1','defender_2'}, # These names are the same as the agents defined in the example config.\n", " policy_mapping_fn=lambda agent_id, episode, worker, **kw: agent_id,\n", " )\n", " .environment(env=PrimaiteRayMARLEnv, env_config=cfg)\n", " .env_runners(num_env_runners=0)\n", " .training(train_batch_size=128)\n", " )\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Set training parameters and start the training\n", "This example will save outputs to a default Ray directory and use mostly default settings." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tune.Tuner(\n", " \"PPO\",\n", " run_config=air.RunConfig(\n", " stop={\"timesteps_total\": 5 * 128},\n", " ),\n", " param_space=config\n", ").fit()" ] } ], "metadata": { "kernelspec": { "display_name": "venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.12" } }, "nbformat": 4, "nbformat_minor": 2 }