{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Unity3D Game with Amazon SageMaker RL\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "\n", "This notebook's CI test result for us-west-2 is as follows. CI test results in other regions can be found at the end of the notebook. \n", "\n", "![This us-west-2 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/us-west-2/reinforcement_learning|rl_unity_ray|rl_unity_ray.ipynb)\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "---\n", "\n", "This notebook has been tested in a TensorFlow 1.15 Python 3.7 CPU Optimized kernel.\n", "\n", "## Introduction\n", "\n", "[Unity](https://unity.com/) is currently the most popular gaming engine used by game developers around the world. Unity engine can be used to create 3D, 2D, virtual reality, and augmented reality games, as well as simulations and other experiences. [ML-Agents](https://github.com/Unity-Technologies/ml-agents) is an open-sourced toolkit developed by Unity to enable games and simulations to serve as environments for training intelligent agents. It provides capabilities on how to interact with Unity executables as well as how to train a RL agent. For how to use ML-Agents to train a Unity game agent on SageMaker, please refer to this [notebook](https://github.com/awslabs/amazon-sagemaker-examples/blob/master/advanced_functionality/unity_ml_agents/unity_mlagents_learn.ipynb).\n", "\n", "In this notebook, we are using capabilities from ML-Agent to interact with Unity executables, but leveraging Amazon SageMaker RL to train the game agent. We will show how you can apply reinforcement learning to train an agent to play against a Unity game with Amazon SageMaker RL." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Pre-requisites \n", "\n", "### Imports\n", "\n", "To get started, we'll import the Python libraries we need, set up the environment with a few prerequisites for permissions and configurations." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "import sagemaker\n", "import boto3\n", "import sys\n", "import os\n", "import glob\n", "import re\n", "import subprocess\n", "import numpy as np\n", "from IPython.display import HTML\n", "import time\n", "from time import gmtime, strftime\n", "\n", "sys.path.append(\"common\")\n", "from misc import get_execution_role, wait_for_s3_object\n", "from docker_utils import build_and_push_docker_image\n", "from sagemaker.rl import RLEstimator, RLToolkit, RLFramework" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Setup S3 bucket\n", "\n", "Set up the linkage and authentication to the S3 bucket that you want to use for checkpoint and the metadata. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sage_session = sagemaker.session.Session()\n", "s3_bucket = sage_session.default_bucket()\n", "s3_output_path = \"s3://{}/\".format(s3_bucket)\n", "print(\"S3 bucket path: {}\".format(s3_output_path))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Define Variables \n", "\n", "We define variables such as the job prefix for the training jobs *and the image path for the container (only when this is BYOC).*" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# create a descriptive job name\n", "job_name_prefix = \"rl-unity-ray\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Configure where training happens\n", "\n", "You can train your RL training jobs using the SageMaker notebook instance or local notebook instance. In both of these scenarios, you can run the following in either local or SageMaker modes. The local mode uses the SageMaker Python SDK to run your code in a local container before deploying to SageMaker. This can speed up iterative testing and debugging while using the same familiar Python SDK interface. You just need to set `local_mode = True`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# run in local_mode on this machine, or as a SageMaker TrainingJob?\n", "local_mode = False\n", "\n", "if local_mode:\n", " instance_type = \"local\"\n", "else:\n", " # If on SageMaker, pick the instance type\n", " instance_type = \"ml.c5.2xlarge\"\n", "\n", "if \"ml.p\" in instance_type or \"ml.g\" in instance_type:\n", " cpu_or_gpu = \"gpu\"\n", "else:\n", " cpu_or_gpu = \"cpu\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Create an IAM role\n", "\n", "Either get the execution role when running from a SageMaker notebook instance `role = sagemaker.get_execution_role()` or, when running from local notebook instance, use utils method `role = get_execution_role()` to create an execution role." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "try:\n", " role = sagemaker.get_execution_role()\n", "except:\n", " role = get_execution_role()\n", "\n", "print(\"Using IAM role arn: {}\".format(role))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Install docker for `local` mode\n", "\n", "In order to work in `local` mode, you need to have docker installed. When running from you local machine, please make sure that you have docker and docker-compose (for local CPU machines) and nvidia-docker (for local GPU machines) installed. Alternatively, when running from a SageMaker notebook instance, you can simply run the following script to install dependenceis.\n", "\n", "Note, you can only run a single local notebook at one time." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# only run from SageMaker notebook instance\n", "if local_mode:\n", " !/bin/bash ./common/setup.sh" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Use Unity Example Environment" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The Unity ML-Agents Toolkit provides an expanding set of [example environments](https://github.com/Unity-Technologies/ml-agents/blob/742c2fbf01188fbf27e82d5a7d9b5fd42f0de67a/docs/Learning-Environment-Examples.md). You can specify one of the environments name in the config and SageMaker RL will start to train a RL agent against that environment.\n", "The training code loads an example environment (`Basic` by default) from the [default registry](https://github.com/Unity-Technologies/ml-agents/blob/742c2fbf01188fbf27e82d5a7d9b5fd42f0de67a/docs/Unity-Environment-Registry.md) and start the training. Currently SageMaker RL can only support example environment with a single agent." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Write the Training Code\n", "\n", "The training code is written in the file “train-unity.py” which is uploaded in the /src directory. \n", "First import the environment files and the preset files, and then define the main() function.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!pygmentize src/train-unity.py" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Train the RL model using the Python SDK Script mode\n", "\n", "If you are using local mode, the training will run on the notebook instance. When using SageMaker for training, you can select a GPU or CPU instance. The RLEstimator is used for training RL jobs. \n", "\n", "1. Specify the source directory where the environment, presets and training code is uploaded.\n", "2. Specify the entry point as the training code \n", "3. Specify the choice of RL toolkit and framework. This automatically resolves to the ECR path for the RL Container. \n", "4. Define the training parameters such as the instance count, job name, S3 path for output and job name. \n", "5. Specify the hyperparameters for the RL agent algorithm. \n", "6. Define the metrics definitions that you are interested in capturing in your logs. These can also be visualized in CloudWatch and SageMaker Notebooks. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "%%time\n", "\n", "ray_version = \"0.8.5\"\n", "suffix = \"py36\"\n", "\n", "image_name = \"462105765813.dkr.ecr.{region}.amazonaws.com/sagemaker-rl-ray-container:ray-{ray_version}-tf-{cpu_or_gpu}-{suffix}\".format(\n", " region=sage_session.boto_region_name,\n", " ray_version=ray_version,\n", " cpu_or_gpu=cpu_or_gpu,\n", " suffix=suffix,\n", ")\n", "metric_definitions = RLEstimator.default_metric_definitions(RLToolkit.RAY)\n", "\n", "estimator = RLEstimator(\n", " entry_point=\"train-unity.py\",\n", " source_dir=\"src\",\n", " dependencies=[\"common/sagemaker_rl\"],\n", " image_uri=image_name,\n", " role=role,\n", " instance_type=instance_type,\n", " instance_count=1,\n", " output_path=s3_output_path,\n", " base_job_name=job_name_prefix,\n", " metric_definitions=metric_definitions,\n", " debugger_hook_config=False,\n", " environment={\"PYTHONUNBUFFERED\": \"1\"},\n", " hyperparameters={\n", " # Attention scientists! You can override any Ray algorithm parameter here:\n", " # \"rl.training.config.env_config.env_name\": \"Basic\",\n", " # \"rl.training.stop.timesteps_total\": 10000,\n", " # \"rl.training.config.num_sgd_iter\": 10,\n", " },\n", ")\n", "\n", "estimator.fit(wait=True)\n", "job_name = estimator.latest_training_job.job_name\n", "print(\"Training job: %s\" % job_name)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Plot metrics for training job\n", "We can see the reward metric of the training as it's running, using algorithm metrics that are recorded in CloudWatch metrics. We can plot this to see the performance of the model over time.\n", "\n", "`TrainingJobAnalytics` could not parse the CloudWatch log immediately after running the training procedure, please wait for the training is done and stablized before running the following cell again!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%matplotlib inline\n", "from sagemaker.analytics import TrainingJobAnalytics\n", "import time\n", "\n", "sm_client = boto3.client(service_name=\"sagemaker\")\n", "\n", "state = sm_client.describe_training_job(TrainingJobName=job_name).get(\"SecondaryStatus\")\n", "\n", "if not local_mode:\n", " while state == \"Starting\":\n", " state = sm_client.describe_training_job(TrainingJobName=job_name).get(\"SecondaryStatus\")\n", " print(\"Training job starting...\")\n", " time.sleep(30)\n", " print(\"Training job started. Waiting for algorithm metric...\")\n", " df = TrainingJobAnalytics(job_name, [\"episode_reward_mean\"]).dataframe()\n", " num_metrics = len(df)\n", " if num_metrics == 0:\n", " print(\"No algorithm metrics found in CloudWatch, please check later.\")\n", " else:\n", " plt = df.plot(x=\"timestamp\", y=\"value\", figsize=(12, 5), legend=True, style=\"b-\")\n", " plt.set_ylabel(\"Mean reward per episode\")\n", " plt.set_xlabel(\"Training time (s)\")\n", "else:\n", " print(\"Can't plot metrics in local mode.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## (Optional) Bring customized Unity environment" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We have shown how to load a sample environment from the Unity Environment Registry and train a RL agent. However, you can use your custom Unity executable as the environment to start the training.\n", "1. [Create a Unity executable](https://github.com/Unity-Technologies/ml-agents/blob/742c2fbf01188fbf27e82d5a7d9b5fd42f0de67a/docs/Learning-Environment-Executable.md) of your Unity environment for Linux platform. Please make sure your environment only contains one single agent.\n", "2. Upload the executable file, dependency data files and library files to s3.\n", "3. Specify the s3 path as a train channel of the training job." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Train the RL model using the Python SDK Script mode with provided Unity executables" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "# %%time\n", "\n", "# metric_definitions = RLEstimator.default_metric_definitions(RLToolkit.RAY)\n", "\n", "# estimator = RLEstimator(entry_point=\"train-unity.py\",\n", "# source_dir='src',\n", "# dependencies=[\"common/sagemaker_rl\"],\n", "# image_uri=custom_image_name,\n", "# role=role,\n", "# instance_type=instance_type,\n", "# instance_count=1,\n", "# output_path=s3_output_path,\n", "# base_job_name=job_name_prefix,\n", "# metric_definitions=metric_definitions,\n", "# hyperparameters={\n", "# # Attention scientists! You can override any Ray algorithm parameter here:\n", "# # \"rl.training.config.env_config.env_name\": \" e.g. basic_env_linux.x86_64\",\n", "# # \"rl.training.stop.timesteps_total\": 1000,\n", "# # \"rl.training.config.num_sgd_iter\": 10,\n", "# }\n", "# )\n", "# s3_binary_path = ' e.g. s3://bucket/unity-data'\n", "# estimator.fit({'train': s3_binary_path}, wait=local_mode)\n", "# job_name = estimator.latest_training_job.job_name\n", "# print(\"Training job: %s\" % job_name)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Evaluation of RL models\n", "\n", "We use the last checkpointed model to run evaluation for the RL Agent. \n", "\n", "### Load checkpointed model\n", "\n", "Checkpointed data from the previously trained models will be passed on for evaluation / inference in the checkpoint channel. In local mode, we can simply use the local directory, whereas in the SageMaker mode, it needs to be moved to S3 first." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tmp_dir = \"/tmp/{}\".format(job_name)\n", "os.system(\"mkdir {}\".format(tmp_dir))\n", "print(\"Create local folder {}\".format(tmp_dir))\n", "\n", "if local_mode:\n", " model_tar_key = \"{}/model.tar.gz\".format(job_name)\n", "else:\n", " model_tar_key = \"{}/output/model.tar.gz\".format(job_name)\n", "\n", "local_checkpoint_dir = \"{}/model\".format(tmp_dir)\n", "\n", "wait_for_s3_object(s3_bucket, model_tar_key, tmp_dir, training_job_name=job_name)\n", "\n", "if not os.path.isfile(\"{}/model.tar.gz\".format(tmp_dir)):\n", " raise FileNotFoundError(\"File model.tar.gz not found\")\n", "\n", "os.system(\"mkdir -p {}\".format(local_checkpoint_dir))\n", "os.system(\"tar -xvzf {}/model.tar.gz -C {}\".format(tmp_dir, local_checkpoint_dir))\n", "\n", "print(\"Checkpoint directory {}\".format(local_checkpoint_dir))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "if local_mode:\n", " checkpoint_path = \"file://{}\".format(local_checkpoint_dir)\n", " print(\"Local checkpoint file path: {}\".format(local_checkpoint_dir))\n", "else:\n", " checkpoint_path = \"s3://{}/{}/checkpoint/\".format(s3_bucket, job_name)\n", " if not os.listdir(local_checkpoint_dir):\n", " raise FileNotFoundError(\"Checkpoint files not found under the path\")\n", " os.system(\"aws s3 cp --recursive {} {}\".format(local_checkpoint_dir, checkpoint_path))\n", " print(\"S3 checkpoint file path: {}\".format(checkpoint_path))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "%%time\n", "\n", "estimator_eval = RLEstimator(\n", " entry_point=\"evaluate-unity.py\",\n", " source_dir=\"src\",\n", " dependencies=[\"common/sagemaker_rl\"],\n", " image_uri=image_name,\n", " role=role,\n", " instance_type=instance_type,\n", " instance_count=1,\n", " base_job_name=job_name_prefix + \"-evaluation\",\n", " hyperparameters={\n", " \"evaluate_episodes\": 5,\n", " \"algorithm\": \"PPO\",\n", " # change the env name here acoording to the traine environment\n", " \"env\": \"Basic\",\n", " },\n", ")\n", "\n", "estimator_eval.fit(\n", " {\"model\": checkpoint_path}, wait=local_mode\n", ") # specify a train channel for the custom Unity executable option\n", "\n", "job_name = estimator_eval.latest_training_job.job_name" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Model deployment\n", "\n", "Now let us deploy the RL policy so that we can get the optimal action, given an environment observation." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from sagemaker.tensorflow.model import TensorFlowModel\n", "\n", "model = TensorFlowModel(model_data=estimator.model_data, framework_version=\"2.5.1\", role=role)\n", "\n", "predictor = model.deploy(initial_instance_count=1, instance_type=instance_type)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# ray 1.6.0 requires all the following inputs, ray 0.8.5 or below remove 'timestep'\n", "# 'prev_action', 'is_training', 'prev_reward', 'seq_lens' and 'timestep' are placeholders for this example\n", "# they won't affect prediction results\n", "\n", "# observation shape passed here must match with the environment specs\n", "input = {\n", " \"inputs\": {\n", " \"observations\": np.ones(shape=(1, 20)).tolist(),\n", " \"prev_action\": [0, 0],\n", " \"is_training\": False,\n", " \"prev_reward\": -1,\n", " \"seq_lens\": -1,\n", " \"timestep\": 1,\n", " }\n", "}" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "result = predictor.predict(input)\n", "\n", "result[\"outputs\"]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Clean up endpoint" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "predictor.delete_model()\n", "predictor.delete_endpoint()" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Notebook CI Test Results\n", "\n", "This notebook was tested in multiple regions. The test results are as follows, except for us-west-2 which is shown at the top of the notebook.\n", "\n", "![This us-east-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/us-east-1/reinforcement_learning|rl_unity_ray|rl_unity_ray.ipynb)\n", "\n", "![This us-east-2 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/us-east-2/reinforcement_learning|rl_unity_ray|rl_unity_ray.ipynb)\n", "\n", "![This us-west-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/us-west-1/reinforcement_learning|rl_unity_ray|rl_unity_ray.ipynb)\n", "\n", "![This ca-central-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/ca-central-1/reinforcement_learning|rl_unity_ray|rl_unity_ray.ipynb)\n", "\n", "![This sa-east-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/sa-east-1/reinforcement_learning|rl_unity_ray|rl_unity_ray.ipynb)\n", "\n", "![This eu-west-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/eu-west-1/reinforcement_learning|rl_unity_ray|rl_unity_ray.ipynb)\n", "\n", "![This eu-west-2 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/eu-west-2/reinforcement_learning|rl_unity_ray|rl_unity_ray.ipynb)\n", "\n", "![This eu-west-3 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/eu-west-3/reinforcement_learning|rl_unity_ray|rl_unity_ray.ipynb)\n", "\n", "![This eu-central-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/eu-central-1/reinforcement_learning|rl_unity_ray|rl_unity_ray.ipynb)\n", "\n", "![This eu-north-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/eu-north-1/reinforcement_learning|rl_unity_ray|rl_unity_ray.ipynb)\n", "\n", "![This ap-southeast-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/ap-southeast-1/reinforcement_learning|rl_unity_ray|rl_unity_ray.ipynb)\n", "\n", "![This ap-southeast-2 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/ap-southeast-2/reinforcement_learning|rl_unity_ray|rl_unity_ray.ipynb)\n", "\n", "![This ap-northeast-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/ap-northeast-1/reinforcement_learning|rl_unity_ray|rl_unity_ray.ipynb)\n", "\n", "![This ap-northeast-2 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/ap-northeast-2/reinforcement_learning|rl_unity_ray|rl_unity_ray.ipynb)\n", "\n", "![This ap-south-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/ap-south-1/reinforcement_learning|rl_unity_ray|rl_unity_ray.ipynb)\n" ] } ], "metadata": { "anaconda-cloud": {}, "kernelspec": { "display_name": "Python 3 (TensorFlow 2.6 Python 3.8 CPU Optimized)", "language": "python", "name": "python3__SAGEMAKER_INTERNAL__arn:aws:sagemaker:us-west-2:236514542706:image/tensorflow-2.6-cpu-py38-ubuntu20.04-v1" }, "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.8.2" }, "notice": "Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License." }, "nbformat": 4, "nbformat_minor": 4 }