Files
MachineLearningNotebooks/how-to-use-azureml/reinforcement-learning/cartpole-on-single-compute/cartpole_sc.ipynb

1010 lines
39 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Copyright (c) Microsoft Corporation. All rights reserved.\n",
"\n",
"Licensed under the MIT License."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/reinforcement-learning/cartpole_on_single_compute/cartpole_sc.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Reinforcement Learning in Azure Machine Learning - Cartpole Problem on Single Compute\n",
"\n",
"Reinforcement Learning in Azure Machine Learning is a managed service for running reinforcement learning training and simulation. With Reinforcement Learning in Azure Machine Learning, data scientists can start developing reinforcement learning systems on one machine, and scale to compute targets with 100s of nodes if needed.\n",
"\n",
"This example shows how to use Reinforcement Learning in Azure Machine Learning to train a Cartpole playing agent on a single compute. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Cartpole problem\n",
"\n",
"Cartpole, also known as [Inverted Pendulum](https://en.wikipedia.org/wiki/Inverted_pendulum), is a pendulum with a center of mass above its pivot point. This formation is essentially unstable and will easily fall over but can be kept balanced by applying appropriate horizontal forces to the pivot point.\n",
"\n",
"<table style=\"width:50%\">\n",
" <tr>\n",
" <th>\n",
" <img src=\"./images/cartpole.png\" alt=\"Cartpole image\" /> \n",
" </th>\n",
" </tr>\n",
" <tr>\n",
" <th><p>Fig 1. Cartpole problem schematic description (from <a href=\"https://towardsdatascience.com/cartpole-introduction-to-reinforcement-learning-ed0eb5b58288\">towardsdatascience.com</a>).</p></th>\n",
" </tr>\n",
"</table>\n",
"\n",
"The goal here is to train an agent to keep the cartpole balanced by applying appropriate forces to the pivot point.\n",
"\n",
"See [this video](https://www.youtube.com/watch?v=XiigTGKZfks) for a real-world demonstration of cartpole problem."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Prerequisite\n",
"The user should have completed the Azure Machine Learning Tutorial: [Get started creating your first ML experiment with the Python SDK](https://docs.microsoft.com/en-us/azure/machine-learning/tutorial-1st-experiment-sdk-setup). You will need to make sure that you have a valid subscription ID, a resource group, and an Azure Machine Learning workspace. All datastores and datasets you use should be associated with your workspace."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Set up Development Environment\n",
"The following subsections show typical steps to setup your development environment. Setup includes:\n",
"\n",
"* Connecting to a workspace to enable communication between your local machine and remote resources\n",
"* Creating an experiment to track all your runs\n",
"* Creating a remote compute target to use for training"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Azure Machine Learning SDK \n",
"Display the Azure Machine Learning SDK version."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import azureml.core\n",
"\n",
"print(\"Azure Machine Learning SDK Version:\", azureml.core.VERSION)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Get Azure Machine Learning workspace\n",
"Get a reference to an existing Azure Machine Learning workspace."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core import Workspace\n",
"\n",
"ws = Workspace.from_config()\n",
"print(ws.name, ws.location, ws.resource_group, sep = ' | ')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Create a new compute resource or attach an existing one\n",
"\n",
"A compute target is a designated compute resource where you run your training and simulation scripts. This location may be your local machine or a cloud-based compute resource. The code below shows how to create a cloud-based compute target. For more information see [What are compute targets in Azure Machine Learning?](https://docs.microsoft.com/en-us/azure/machine-learning/concept-compute-target)\n",
"\n",
"**Note: Creation of a compute resource can take several minutes**. Please make sure to change `STANDARD_D2_V2` to a [size available in your region](https://azure.microsoft.com/en-us/global-infrastructure/services/?products=virtual-machines)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core.compute import AmlCompute, ComputeTarget\n",
"import os\n",
"\n",
"# Choose a name and maximum size for your cluster\n",
"compute_name = \"cpu-cluster-d2\"\n",
"compute_min_nodes = 0\n",
"compute_max_nodes = 4\n",
"vm_size = \"STANDARD_D2_V2\"\n",
"\n",
"if compute_name in ws.compute_targets:\n",
" print(\"Found an existing compute target of name: \" + compute_name)\n",
" compute_target = ws.compute_targets[compute_name]\n",
" # Note: you may want to make sure compute_target is of type AmlCompute \n",
"else:\n",
" print(\"Creating new compute target...\")\n",
" provisioning_config = AmlCompute.provisioning_configuration(\n",
" vm_size=vm_size,\n",
" min_nodes=compute_min_nodes, \n",
" max_nodes=compute_max_nodes)\n",
" \n",
" # Create the cluster\n",
" compute_target = ComputeTarget.create(ws, compute_name, provisioning_config)\n",
" compute_target.wait_for_completion(show_output=True, min_node_count=None, timeout_in_minutes=20)\n",
"\n",
"print(compute_target.get_status().serialize())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Create Azure Machine Learning experiment\n",
"Create an experiment to track the runs in your workspace. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core.experiment import Experiment\n",
"\n",
"experiment_name = 'CartPole-v0-SC'\n",
"exp = Experiment(workspace=ws, name=experiment_name)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Train Cartpole Agent\n",
"To facilitate reinforcement learning, Azure Machine Learning Python SDK provides a high level abstraction, the _ReinforcementLearningEstimator_ class, which allows users to easily construct reinforcement learning run configurations for the underlying reinforcement learning framework. Reinforcement Learning in Azure Machine Learning supports the open source [Ray framework](https://ray.io/) and its highly customizable [RLlib](https://ray.readthedocs.io/en/latest/rllib.html#rllib-scalable-reinforcement-learning). In this section we show how to use _ReinforcementLearningEstimator_ and Ray/RLlib framework to train a cartpole playing agent. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Create reinforcement learning estimator\n",
"\n",
"The code below creates an instance of *ReinforcementLearningEstimator*, `training_estimator`, which then will be used to submit a job to Azure Machine Learning to start the Ray experiment run.\n",
"\n",
"Note that this example is purposely simplified to the minimum. Here is a short description of the parameters we are passing into the constructor:\n",
"\n",
"- `source_directory`, local directory containing your training script(s) and helper modules,\n",
"- `entry_script`, path to your entry script relative to the source directory,\n",
"- `script_params`, constant parameters to be passed to each run of training script,\n",
"- `compute_target`, reference to the compute target in which the trainer and worker(s) jobs will be executed,\n",
"- `rl_framework`, the reinforcement learning framework to be used (currently must be Ray).\n",
"\n",
"We use the `script_params` parameter to pass in general and algorithm-specific parameters to the training script.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.contrib.train.rl import ReinforcementLearningEstimator, Ray\n",
"from azureml.core.environment import Environment\n",
"\n",
"training_algorithm = \"PPO\"\n",
"rl_environment = \"CartPole-v0\"\n",
"video_capture = True\n",
"\n",
"if video_capture:\n",
" algorithm_config = '\\'{\"num_gpus\": 0, \"num_workers\": 1, \"monitor\": true}\\''\n",
"else:\n",
" algorithm_config = '\\'{\"num_gpus\": 0, \"num_workers\": 1, \"monitor\": false}\\''\n",
"\n",
"script_params = {\n",
"\n",
" # Training algorithm\n",
" \"--run\": training_algorithm,\n",
" \n",
" # Training environment\n",
" \"--env\": rl_environment,\n",
" \n",
" # Algorithm-specific parameters\n",
" \"--config\": algorithm_config,\n",
" \n",
" # Stop conditions\n",
" \"--stop\": '\\'{\"episode_reward_mean\": 200, \"time_total_s\": 300}\\'',\n",
" \n",
" # Frequency of taking checkpoints\n",
" \"--checkpoint-freq\": 2,\n",
" \n",
" # If a checkpoint should be taken at the end - optional argument with no value\n",
" \"--checkpoint-at-end\": \"\",\n",
" \n",
" # Log directory\n",
" \"--local-dir\": './logs'\n",
"}\n",
"\n",
"xvfb_env = None\n",
"if video_capture:\n",
" # Ray's video capture support requires to run everything under a headless display driver called (xvfb).\n",
" # There are two parts to this:\n",
" # 1. Use a custom docker file with proper instructions to install xvfb, ffmpeg, python-opengl\n",
" # and other dependencies.\n",
" \n",
" with open(\"files/docker/Dockerfile\", \"r\") as f:\n",
" dockerfile=f.read()\n",
"\n",
" xvfb_env = Environment(name='xvfb-vdisplay')\n",
" xvfb_env.docker.enabled = True\n",
" xvfb_env.docker.base_image = None\n",
" xvfb_env.docker.base_dockerfile = dockerfile\n",
" \n",
" # 2. Execute the Python process via the xvfb-run command to set up the headless display driver.\n",
" xvfb_env.python.user_managed_dependencies = True\n",
" xvfb_env.python.interpreter_path = \"xvfb-run -s '-screen 0 640x480x16 -ac +extension GLX +render' python\"\n",
"\n",
"\n",
"training_estimator = ReinforcementLearningEstimator(\n",
"\n",
" # Location of source files\n",
" source_directory='files',\n",
" \n",
" # Python script file\n",
" entry_script='cartpole_training.py',\n",
" \n",
" # A dictionary of arguments to pass to the training script specified in ``entry_script``\n",
" script_params=script_params,\n",
" \n",
" # The Azure Machine Learning compute target set up for Ray head nodes\n",
" compute_target=compute_target,\n",
" \n",
" # Reinforcement learning framework. Currently must be Ray.\n",
" rl_framework=Ray(),\n",
" \n",
" # Custom environmnet for Xvfb\n",
" environment=xvfb_env\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Training script\n",
"\n",
"As recommended in RLlib documentations, we use Ray Tune API to run the training algorithm. All the RLlib built-in trainers are compatible with the Tune API. Here we use `tune.run()` to execute a built-in training algorithm. For convenience, down below you can see part of the entry script where we make this call.\n",
"\n",
"This is the list of parameters we are passing into `tune.run()` via the `script_params` parameter:\n",
"\n",
"- `run_or_experiment`: name of the [built-in algorithm](https://ray.readthedocs.io/en/latest/rllib-algorithms.html#rllib-algorithms), 'PPO' in our example,\n",
"- `config`: Algorithm-specific configuration. This includes specifying the environment, `env`, which in our example is the gym **[CartPole-v0](https://gym.openai.com/envs/CartPole-v0/)** environment,\n",
"- `stop`: stopping conditions, which could be any of the metrics returned by the trainer. Here we use \"mean of episode reward\", and \"total training time in seconds\" as stop conditions, and\n",
"- `checkpoint_freq` and `checkpoint_at_end`: Frequency of taking checkpoints (number of training iterations between checkpoints), and if a checkpoint should be taken at the end.\n",
"\n",
"We also specify the `local_dir`, the directory in which the training logs, checkpoints and other training artificats will be recorded. \n",
"\n",
"See [RLlib Training APIs](https://ray.readthedocs.io/en/latest/rllib-training.html#rllib-training-apis) for more details, and also [Training (tune.run, tune.Experiment)](https://ray.readthedocs.io/en/latest/tune/api_docs/execution.html#training-tune-run-tune-experiment) for the complete list of parameters.\n",
"\n",
"```python\n",
"import ray\n",
"import ray.tune as tune\n",
"\n",
"if __name__ == \"__main__\":\n",
"\n",
" # parse arguments ...\n",
" \n",
" # Intitialize ray\n",
" ray.init(address=args.ray_address)\n",
"\n",
" # Run training task using tune.run\n",
" tune.run(\n",
" run_or_experiment=args.run,\n",
" config=dict(args.config, env=args.env),\n",
" stop=args.stop,\n",
" checkpoint_freq=args.checkpoint_freq,\n",
" checkpoint_at_end=args.checkpoint_at_end,\n",
" local_dir=args.local_dir\n",
" )\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Submit the estimator to start experiment\n",
"Now we use the *training_estimator* to submit a run."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"training_run = exp.submit(training_estimator)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Monitor experiment\n",
"\n",
"Azure Machine Learning provides a Jupyter widget to show the status of an experiment run. You could use this widget to monitor the status of the runs.\n",
"\n",
"Note that _ReinforcementLearningEstimator_ creates at least two runs: (a) A parent run, i.e. the run returned above, and (b) a collection of child runs. The number of the child runs depends on the configuration of the reinforcement learning estimator. In our simple scenario, configured above, only one child run will be created.\n",
"\n",
"The widget will show a list of the child runs as well. You can click on the link under **Status** to see the details of a child run. It will also show the metrics being logged."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.widgets import RunDetails\n",
"\n",
"RunDetails(training_run).show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Stop the run\n",
"To stop the run, call `training_run.cancel()`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Uncomment line below to cancel the run\n",
"#training_run.cancel()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Wait for completion\n",
"Wait for the run to complete before proceeding.\n",
"\n",
"**Note: The length of the run depends on the provisioning time of the compute target and it may take several minutes to complete.**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"training_run.wait_for_completion()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Get a handle to the child run\n",
"You can obtain a handle to the child run as follows. In our scenario, there is only one child run, we have it called `child_run_0`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import time\n",
"\n",
"child_run_0 = None\n",
"timeout = 30\n",
"while timeout > 0 and not child_run_0:\n",
" child_runs = list(training_run.get_children())\n",
" print('Number of child runs:', len(child_runs))\n",
" if len(child_runs) > 0:\n",
" child_run_0 = child_runs[0]\n",
" break\n",
" time.sleep(2) # Wait for 2 seconds\n",
" timeout -= 2\n",
"\n",
"print('Child run info:')\n",
"print(child_run_0)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Get access to training artifacts\n",
"We can simply use run id to get a handle to an in-progress or a previously concluded run."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core import Run\n",
"\n",
"run_id = child_run_0.id # Or set to run id of a completed run (e.g. 'rl-cartpole-v0_1587572312_06e04ace_head')\n",
"child_run_0 = Run(exp, run_id=run_id)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we can use the Run API to download policy training artifacts (saved model and checkpoints) to local compute."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from os import path\n",
"from distutils import dir_util\n",
"\n",
"path_prefix = path.join(\"logs\", training_algorithm)\n",
"print(\"Path prefix:\", path_prefix)\n",
"\n",
"if path.exists(path_prefix):\n",
" dir_util.remove_tree(path_prefix)\n",
"\n",
"# Uncomment line below to download run artifacts to local compute\n",
"#child_run_0.download_files(path_prefix)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Create a dataset of training artifacts\n",
"To evaluate a trained policy (a checkpoint) we need to make the checkpoint accessible to the rollout script. All the training artifacts are stored in workspace default datastore under **azureml/&lt;run_id&gt;** directory.\n",
"\n",
"Here we create a file dataset from the stored artifacts, and then use this dataset to feed these data to rollout estimator."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from azureml.core import Dataset\n",
"\n",
"run_id = child_run_0.id # Or set to run id of a completed run (e.g. 'rl-cartpole-v0_1587572312_06e04ace_head')\n",
"run_artifacts_path = os.path.join('azureml', run_id)\n",
"print(\"Run artifacts path:\", run_artifacts_path)\n",
"\n",
"# Create a file dataset object from the files stored on default datastore\n",
"datastore = ws.get_default_datastore()\n",
"training_artifacts_ds = Dataset.File.from_files(datastore.path(os.path.join(run_artifacts_path, '**')))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To verify, we can print out the number (and paths) of all the files in the dataset, as follows."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"artifacts_paths = training_artifacts_ds.to_path()\n",
"print(\"Number of files in dataset:\", len(artifacts_paths))\n",
"\n",
"# Uncomment line below to print all file paths\n",
"#print(\"Artifacts dataset file paths: \", artifacts_paths)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Display movies of selected training episodes\n",
"\n",
"Ray creates video output of selected training episodes in mp4 format. Here we will display two of these, i.e. the first and the last recorded videos, so you could see the improvement of the agent after training.\n",
"\n",
"First we introduce a few helper functions: a function to download the movies from our dataset, another one to find mp4 movies in a local directory, and one more to display a downloaded movie."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import shutil\n",
"\n",
"# A helper function to download movies from a dataset to local directory\n",
"def download_movies(artifacts_ds, movies, destination):\n",
" # Create the local destination directory \n",
" if path.exists(destination):\n",
" dir_util.remove_tree(destination)\n",
" dir_util.mkpath(destination)\n",
"\n",
" for i, artifact in enumerate(artifacts_ds.to_path()):\n",
" if artifact in movies:\n",
" print('Downloading {} ...'.format(artifact))\n",
" artifacts_ds.skip(i).take(1).download(target_path=destination, overwrite=True)\n",
"\n",
" print('Downloading movies completed!')\n",
"\n",
"\n",
"# A helper function to find movies in a directory\n",
"def find_movies(movie_path):\n",
" print(\"Looking in path:\", movie_path)\n",
" mp4_movies = []\n",
" for root, _, files in os.walk(movie_path):\n",
" for name in files:\n",
" if name.endswith('.mp4'):\n",
" mp4_movies.append(path.join(root, name))\n",
" print('Found {} movies'.format(len(mp4_movies)))\n",
"\n",
" return mp4_movies\n",
"\n",
"\n",
"# A helper function to display a movie\n",
"from IPython.core.display import display, HTML\n",
"def display_movie(movie_file):\n",
" display(\n",
" HTML('\\\n",
" <video alt=\"cannot display video\" autoplay loop> \\\n",
" <source src=\"{}\" type=\"video/mp4\"> \\\n",
" </video>'.format(movie_file)\n",
" )\n",
" )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's find the first and the last recorded videos in training artifacts dataset and download them to a local directory."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Find first and last movie\n",
"mp4_files = [file for file in training_artifacts_ds.to_path() if file.endswith('.mp4')]\n",
"mp4_files.sort()\n",
"\n",
"first_movie = mp4_files[0] if len(mp4_files) > 0 else None\n",
"last_movie = mp4_files[-1] if len(mp4_files) > 1 else None\n",
"\n",
"print(\"First movie:\", first_movie)\n",
"print(\"Last movie:\", last_movie)\n",
"\n",
"# Download movies\n",
"training_movies_path = path.join(\"training\", \"videos\")\n",
"download_movies(training_artifacts_ds, [first_movie, last_movie], training_movies_path)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Look for the downloaded movies in the local directory and sort them."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"mp4_files = find_movies(training_movies_path)\n",
"mp4_files.sort()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Display a movie of the first training episode. This is how the agent performs with no training."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"first_movie = mp4_files[0] if len(mp4_files) > 0 else None\n",
"print(\"First movie:\", first_movie)\n",
"\n",
"display_movie(first_movie)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Display a movie of the last training episode. This is how a fully-trained agent performs."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"last_movie = mp4_files[-1] if len(mp4_files) > 0 else None\n",
"print(\"Last movie:\", last_movie)\n",
"\n",
"display_movie(last_movie)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Evaluate Trained Agent and See Results\n",
"\n",
"We can evaluate a previously trained policy using the `rollout.py` helper script provided by RLlib (see [Evaluating Trained Policies](https://ray.readthedocs.io/en/latest/rllib-training.html#evaluating-trained-policies) for more details). Here we use an adaptation of this script to reconstruct a policy from a checkpoint taken and saved during training. We took these checkpoints by setting `checkpoint-freq` and `checkpoint-at-end` parameters above.\n",
"In this section we show how to use these checkpoints to evaluate the trained policy."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Evaluate a trained policy\n",
"We need to configure another reinforcement learning estimator, `rollout_estimator`, and then use it to submit another run. Note that the entry script for this estimator now points to `cartpole-rollout.py` script.\n",
"Also note how we pass the checkpoints dataset to this script using `inputs` parameter of the _ReinforcementLearningEstimator_.\n",
"\n",
"We are using script parameters to pass in the same algorithm and the same environment used during training. We also specify the checkpoint number of the checkpoint we wish to evaluate, `checkpoint-number`, and number of the steps we shall run the rollout, `steps`.\n",
"\n",
"The training artifacts dataset will be accessible to the rollout script as a mounted folder. The mounted folder and the checkpoint number, passed in via `checkpoint-number`, will be used to create a path to the checkpoint we are going to evaluate. The created checkpoint path then will be passed into RLlib rollout script for evaluation.\n",
"\n",
"Let's find the checkpoints and the last checkpoint number first."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Find checkpoints and last checkpoint number\n",
"checkpoint_files = [\n",
" os.path.basename(file) for file in training_artifacts_ds.to_path() \\\n",
" if os.path.basename(file).startswith('checkpoint-') and \\\n",
" not os.path.basename(file).endswith('tune_metadata')\n",
"]\n",
"\n",
"checkpoint_numbers = []\n",
"for file in checkpoint_files:\n",
" checkpoint_numbers.append(int(file.split('-')[1]))\n",
"\n",
"print(\"Checkpoints:\", checkpoint_numbers)\n",
"\n",
"last_checkpoint_number = max(checkpoint_numbers)\n",
"print(\"Last checkpoint number:\", last_checkpoint_number)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's configure rollout estimator. Note that we use the last checkpoint for evaluation. The assumption is that the last checkpoint points to our best trained agent. You may change this to any of the checkpoint numbers printed above and observe the effect."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"script_params = { \n",
" # Checkpoint number of the checkpoint from which to roll out\n",
" \"--checkpoint-number\": last_checkpoint_number,\n",
"\n",
" # Training algorithm\n",
" \"--run\": training_algorithm,\n",
" \n",
" # Training environment\n",
" \"--env\": rl_environment,\n",
" \n",
" # Algorithm-specific parameters\n",
" \"--config\": '{}',\n",
" \n",
" # Number of rollout steps \n",
" \"--steps\": 2000,\n",
" \n",
" # If should repress rendering of the environment\n",
" \"--no-render\": \"\",\n",
" \n",
" # The place where recorded videos will be stored\n",
" \"--video-dir\": \"./logs/video\"\n",
"}\n",
"\n",
"if video_capture:\n",
" script_params.pop(\"--no-render\")\n",
"else:\n",
" script_params.pop(\"--video-dir\")\n",
"\n",
"\n",
"# Ray's video capture support requires to run everything under a headless display driver called (xvfb).\n",
"# There are two parts to this:\n",
"\n",
"# 1. Use a custom docker file with proper instructions to install xvfb, ffmpeg, python-opengl\n",
"# and other dependencies.\n",
"# Note: Even when the rendering is off pyhton-opengl is needed.\n",
"\n",
"with open(\"files/docker/Dockerfile\", \"r\") as f:\n",
" dockerfile=f.read()\n",
"\n",
"xvfb_env = Environment(name='xvfb-vdisplay')\n",
"xvfb_env.docker.enabled = True\n",
"xvfb_env.docker.base_image = None\n",
"xvfb_env.docker.base_dockerfile = dockerfile\n",
" \n",
"# 2. Execute the Python process via the xvfb-run command to set up the headless display driver.\n",
"xvfb_env.python.user_managed_dependencies = True\n",
"if video_capture:\n",
" xvfb_env.python.interpreter_path = \"xvfb-run -s '-screen 0 640x480x16 -ac +extension GLX +render' python\"\n",
"\n",
"\n",
"rollout_estimator = ReinforcementLearningEstimator(\n",
" # Location of source files\n",
" source_directory='files',\n",
" \n",
" # Python script file\n",
" entry_script='cartpole_rollout.py',\n",
" \n",
" # A dictionary of arguments to pass to the rollout script specified in ``entry_script``\n",
" script_params = script_params,\n",
" \n",
" # Data inputs\n",
" inputs=[\n",
" training_artifacts_ds.as_named_input('artifacts_dataset'),\n",
" training_artifacts_ds.as_named_input('artifacts_path').as_mount()],\n",
" \n",
" # The Azure Machine Learning compute target set up for Ray head nodes\n",
" compute_target=compute_target,\n",
" \n",
" # Reinforcement learning framework. Currently must be Ray.\n",
" rl_framework=Ray(),\n",
" \n",
" # Custom environmnet for Xvfb\n",
" environment=xvfb_env)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Same as before, we use the *rollout_estimator* to submit a run."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"rollout_run = exp.submit(rollout_estimator)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And then, similar to the training section, we can monitor the real-time progress of the rollout run and its chid as follows. If you browse logs of the child run you can see the evaluation results recorded in driver_log.txt file. Note that you may need to wait several minutes before these results become available."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"RunDetails(rollout_run).show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Wait for completion of the rollout run before moving to the next section, or you may cancel the run."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Uncomment line below to cancel the run\n",
"#rollout_run.cancel()\n",
"rollout_run.wait_for_completion()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Display movies of selected rollout episodes\n",
"\n",
"To display recorded movies first we download recorded videos to local machine. Here again we create a dataset of rollout artifacts and use the helper functions introduced above to download and displays rollout videos."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Get a handle to child run\n",
"child_runs = list(rollout_run.get_children())\n",
"print('Number of child runs:', len(child_runs))\n",
"child_run_0 = child_runs[0]\n",
"\n",
"run_id = child_run_0.id # Or set to run id of a completed run (e.g. 'rl-cartpole-v0_1587572312_06e04ace_head')\n",
"run_artifacts_path = os.path.join('azureml', run_id)\n",
"print(\"Run artifacts path:\", run_artifacts_path)\n",
"\n",
"# Create a file dataset object from the files stored on default datastore\n",
"datastore = ws.get_default_datastore()\n",
"rollout_artifacts_ds = Dataset.File.from_files(datastore.path(os.path.join(run_artifacts_path, '**')))\n",
"\n",
"artifacts_paths = rollout_artifacts_ds.to_path()\n",
"print(\"Number of files in dataset:\", len(artifacts_paths))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, similar to the training section, we look for the last video."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Find last movie\n",
"mp4_files = [file for file in rollout_artifacts_ds.to_path() if file.endswith('.mp4')]\n",
"mp4_files.sort()\n",
"\n",
"last_movie = mp4_files[-1] if len(mp4_files) > 1 else None\n",
"print(\"Last movie:\", last_movie)\n",
"\n",
"# Download last movie\n",
"rollout_movies_path = path.join(\"rollout\", \"videos\")\n",
"download_movies(rollout_artifacts_ds, [last_movie], rollout_movies_path)\n",
"\n",
"# Look for the downloaded movie in local directory\n",
"mp4_files = find_movies(rollout_movies_path)\n",
"mp4_files.sort()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Display last video recorded during the rollout."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"last_movie = mp4_files[-1] if len(mp4_files) > 0 else None\n",
"print(\"Last movie:\", last_movie)\n",
"\n",
"display_movie(last_movie)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Cleaning up\n",
"For your convenience, below you can find code snippets to clean up any resources created as part of this tutorial that you don't wish to retain."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# To archive the created experiment:\n",
"#exp.archive()\n",
"\n",
"# To delete the compute target:\n",
"#compute_target.delete()\n",
"\n",
"# To delete downloaded training artifacts\n",
"#if os.path.exists(path_prefix):\n",
"# dir_util.remove_tree(path_prefix)\n",
"\n",
"# To delete downloaded training videos\n",
"#if path.exists(training_movies_path):\n",
"# dir_util.remove_tree(training_movies_path)\n",
"\n",
"# To delete downloaded rollout videos\n",
"#if path.exists(rollout_movies_path):\n",
"# dir_util.remove_tree(rollout_movies_path)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Next\n",
"This example was about running Reinforcement Learning in Azure Machine Learning (Ray/RLlib Framework) on a single compute. Please see [Pong Problem](../atari-on-distributed-compute/pong_rllib.ipynb)\n",
"example which uses Ray RLlib to train a Pong playing agent on a multi-node cluster."
]
}
],
"metadata": {
"authors": [
{
"name": "hoazari"
}
],
"kernelspec": {
"display_name": "Python 3.6",
"language": "python",
"name": "python36"
},
"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.6.9"
},
"notice": "Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License."
},
"nbformat": 4,
"nbformat_minor": 4
}