# Training Batch Reinforcement Learning Policies with Amazon SageMaker RL and Coach library

For many real-world problems, the reinforcement learning (RL) agent needs to learn from historical data that was generated by some deployed policy. For example, we may have historical data of experts playing games, users interacting with a website or sensor data from a control system. This notebook shows an example of how to use batch RL to train a new policy from offline dataset[1]. We use gym CartPole-v0 as a fake simulated system to generate offline dataset and the RL agents are trained using Amazon SageMaker RL.

We may want to evaluate the policy learned from historical data before deployment. Since simulators may not be available in all use cases, we need to evaluate how good the learned policy by using held out historical data. This is called as off-policy evaluation or counterfactual evaluation. In this notebook, we evaluate the policy during the training using several off-policy evaluation metrics.

We can deploy the policy using SageMaker Hosting endpoint. However, some use cases may not require a persistent serving endpoint with sub-second latency. Here we demonstrate how to deploy the policy with SageMaker Batch Transform, where large volumes of input state features can be inferenced with high throughput.

Figure below shows an overview of the entire notebook.

## Pre-requisites

### Roles and permissions

To get started, we’ll import the Python libraries we need, set up the environment with a few pre-requisites for permissions and configurations.

[ ]:

import sagemaker
import boto3
import sys
import os
import glob
import re
import subprocess
from IPython.display import HTML
import time
from time import gmtime, strftime

sys.path.append("common")
from misc import get_execution_role, wait_for_s3_object
from sagemaker.rl import RLEstimator, RLToolkit, RLFramework

# install gym environments if needed
!pip install gym
from env_utils import VectoredGymEnvironment


### Setup S3 buckets

Setup the linkage and authentication to the S3 bucket that you want to use for checkpoint and the metadata.

[ ]:

# S3 bucket
sage_session = sagemaker.session.Session()
s3_bucket = sage_session.default_bucket()
region_name = sage_session.boto_region_name
s3_output_path = "s3://{}/".format(s3_bucket)  # SDK appends the job name and output folder
print("S3 bucket path: {}".format(s3_output_path))


### Define Variables

We define variables such as the job prefix for the training jobs and the image path for the container (only when this is BYOC).

[ ]:

# create unique job name
job_name_prefix = "rl-batch-cartpole"


### Configure settings

You can run your RL training jobs on a SageMaker notebook instance or on your own machine. 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.

[ ]:

%%time

# run in local mode?
local_mode = False


### Create an IAM role

Either get the execution role when running from a SageMaker notebook role = sagemaker.get_execution_role() or, when running from local machine, use utils method role = get_execution_role() to create an execution role.

[ ]:

try:
role = sagemaker.get_execution_role()
except:
role = get_execution_role()

print("Using IAM role arn: {}".format(role))


### Install docker for local mode

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 or 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.

Note, you can only run a single local notebook at one time.

[ ]:

# only run from SageMaker notebook instance
if local_mode:
!/bin/bash ./common/setup.sh


## Collect offline data

In order to do Batch RL training, we need to first prepare the dataset that is generated by a deployed policy. In real world scenarios, customers can collect these offline data by interacting the live environment using the already deployed agent. In this notebook, we used OpenAI gym Cartpole-v0 as the environment to mimic a live environment and used a random policy with uniform action distribution to mimic a deployed agent. By interacting with multiple environments simultaneously, we can gather more trajectories from the environments.

Here is a short introduction of the cart-pole balancing problem, where a pole is attached by an un-actuated joint to a cart, moving along a frictionless track.

1. Objective: Prevent the pole from falling over

2. Environment: The environment used in this example is part of OpenAI Gym, corresponding to the version of the cart-pole problem described by Barto, Sutton, and Anderson [2]

3. State: Cart position, cart velocity, pole angle, pole velocity at tip

4. Action: Push cart to the left, push cart to the right

5. Reward: Reward is 1 for every step taken, including the termination step

[ ]:

# initiate 100 environment to collect rollout data
NUM_ENVS = 100
NUM_EPISODES = 5
vectored_envs = VectoredGymEnvironment("CartPole-v0", NUM_ENVS)


Now we have 100 environments of Cartpole-v0 ready. We’ll collect 5 episodes from each environment so we’ll have 500 episodes of data for training. We start from a random policy that generates the same uniform action probabilities regardless of the state features.

[ ]:

# initiate a random policy by setting action probabilities as uniform distribution
action_probs = [[1 / 2, 1 / 2] for _ in range(NUM_ENVS)]
df = vectored_envs.collect_rollouts_with_given_action_probs(
action_probs=action_probs, num_episodes=NUM_EPISODES
)

[ ]:

# the rollout dataframes contain attributes: action, action_probs, episode_id, reward, cumulative_rewards, state_features
# only show cumulative rewards at the last step of the episode


We can use the average cumulative reward of the random policy as a baseline for the Batch RL trained policy.

[ ]:

# average cumulative rewards for each episode
avg_rewards = df["cumulative_rewards"].sum() / (NUM_ENVS * NUM_EPISODES)
print(
"Average cumulative rewards over {} episodes rollouts was {}.".format(
(NUM_ENVS * NUM_EPISODES), avg_rewards
)
)


### Save Dataframe as CSV for Batch RL Training

Coach Batch RL support reading off policy data in CSV format. We will dump our collected rollout data in CSV format.

[ ]:

# dump dataframe as csv file
df.to_csv("src/cartpole_dataset.csv", index=False)


## Configure the presets for RL algorithm

The presets that configure the Batch RL training jobs are defined in the preset-cartpole-ddqnbcq.py file which is also uploaded on the /src directory. Using the preset file, you can define agent parameters to select the specific agent algorithm. You can also set the environment parameters, define the schedule and visualization parameters, and define the graph manager. The schedule presets will define the number of heat up steps, periodic evaluation steps, training steps between evaluations.

These can be overridden at runtime by specifying the RLCOACH_PRESET hyperparameter. Additionally, it can be used to define custom hyperparameters.

[ ]:

!pygmentize src/preset-cartpole-ddqnbcq.py


In this notebook, we use DDQN[6] to update the policy in an off-policy manner, and combine it with BCQ[5] to address the error induced by inaccurately estimated values for unseen state-action pairs. The training is completely off-line.

## Write the Training Code

The training code is written in the file “train-coach.py” which is uploaded in the /src directory. First import the environment files and the preset files, and then define the main() function.

[ ]:

!pygmentize src/train-coach.py


## Train the RL model using the Python SDK Script mode

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.

1. Specify the source directory where the environment, presets and training code is uploaded.

2. Specify the entry point as the training code

3. Define the training parameters such as the instance count, job name, S3 path for output and job name.

4. Specify the hyperparameters for the RL agent algorithm. The RLCOACH_PRESET can be used to specify the RL agent algorithm you want to use.

[ ]:

%%time

if local_mode:
instance_type = "local"
else:
instance_type = "ml.m4.xlarge"

estimator = RLEstimator(
entry_point="train-coach.py",
source_dir="src",
dependencies=["common/sagemaker_rl"],
toolkit=RLToolkit.COACH,
toolkit_version="1.0.0",
framework=RLFramework.TENSORFLOW,
role=role,
instance_type=instance_type,
instance_count=1,
output_path=s3_output_path,
base_job_name=job_name_prefix,
hyperparameters={"RLCOACH_PRESET": "preset-cartpole-ddqnbcq", "save_model": 1},
)
estimator.fit()


## Store intermediate training output and model checkpoints

The output from the training job above is stored on S3. The intermediate folder contains gifs and metadata of the training. We’ll need these metadata for metrics visualization and model evaluations.

[ ]:

job_name = estimator._current_job_name
print("Job name: {}".format(job_name))

s3_url = "s3://{}/{}".format(s3_bucket, job_name)

if local_mode:
output_tar_key = "{}/output.tar.gz".format(job_name)
else:
output_tar_key = "{}/output/output.tar.gz".format(job_name)

intermediate_folder_key = "{}/output/intermediate/".format(job_name)
output_url = "s3://{}/{}".format(s3_bucket, output_tar_key)
intermediate_url = "s3://{}/{}".format(s3_bucket, intermediate_folder_key)

print("S3 job path: {}".format(s3_url))
print("Output.tar.gz location: {}".format(output_url))
print("Intermediate folder path: {}".format(intermediate_url))

tmp_dir = "/tmp/{}".format(job_name)
os.system("mkdir {}".format(tmp_dir))
print("Create local folder {}".format(tmp_dir))


## Visualization

### Plot metrics for training job

We can pull the Off Policy Evaluation(OPE) metric of the training and plot it to see the performance of the model over time.

[ ]:

%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt

csv_file_name = "worker_0.batch_rl_graph.main_level.main_level.agent_0.csv"
key = os.path.join(intermediate_folder_key, csv_file_name)
wait_for_s3_object(s3_bucket, key, tmp_dir, training_job_name=job_name)

csv_file = "{}/{}".format(tmp_dir, csv_file_name)
df = df.dropna(subset=["Sequential Doubly Robust"])
df.dropna(subset=["Weighted Importance Sampling"])

plt.figure(figsize=(12, 5))
plt.xlabel("Number of epochs")

ax1 = df["Weighted Importance Sampling"].plot(color="blue", grid=True, label="WIS")
ax2 = df["Sequential Doubly Robust"].plot(color="red", grid=True, secondary_y=True, label="SDR")

h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()

plt.legend(h1 + h2, l1 + l2, loc=1)
plt.show()


There is a set of methods used to investigate the performance of the current trained policy without interacting with simulator / live environment. They can be used to estimate the goodness of the policy, based on the dataset collected from other policy. Here we showed two of these OPE metrics: WIS (Weighted Importance Sampling) [3] and SDR (Sequential Doubly Robust) [4]. As we can see in the plot, these metrics are improving as the learning agent is iterating over the given dataset.

## Evaluation of RL models

To evaluate the model trained with off policy data, we need to see the accumulative rewards of the agent by interacting with the environment. We use the last checkpointed model to run evaluation of the RL Agent. We use a different preset file here preset-cartpole-ddqnbcq-env.py to let the RL agent interact with the environment and collect rewards.

Checkpoint is 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.

[ ]:

wait_for_s3_object(s3_bucket, output_tar_key, tmp_dir, training_job_name=job_name)

if not os.path.isfile("{}/output.tar.gz".format(tmp_dir)):
os.system("tar -xvzf {}/output.tar.gz -C {}".format(tmp_dir, tmp_dir))

if local_mode:
checkpoint_dir = "{}/data/checkpoint".format(tmp_dir)
else:
checkpoint_dir = "{}/checkpoint".format(tmp_dir)

print("Checkpoint directory {}".format(checkpoint_dir))

[ ]:

if local_mode:
checkpoint_path = "file://{}".format(checkpoint_dir)
print("Local checkpoint file path: {}".format(checkpoint_path))
else:
checkpoint_path = "s3://{}/{}/checkpoint/".format(s3_bucket, job_name)
if not os.listdir(checkpoint_dir):
os.system("aws s3 cp --recursive {} {}".format(checkpoint_dir, checkpoint_path))
print("S3 checkpoint file path: {}".format(checkpoint_path))

[ ]:

estimator_eval = RLEstimator(
entry_point="evaluate-coach.py",
source_dir="src",
dependencies=["common/sagemaker_rl"],
toolkit=RLToolkit.COACH,
toolkit_version="1.0.0",
framework=RLFramework.TENSORFLOW,
role=role,
instance_type=instance_type,
instance_count=1,
output_path=s3_output_path,
base_job_name=job_name_prefix,
hyperparameters={"RLCOACH_PRESET": "preset-cartpole-ddqnbcq-env", "evaluate_steps": 1000},
)

estimator_eval.fit({"checkpoint": checkpoint_path})


### Batch Transform

As we can see from the above evaluation job, the trained agent gets a total reward of around 200 as compared to a total reward around 25 in our offline dataset. Therefore, we can confirm that the agent has learned a better policy from the off-policy data.

After we get the trained model, we can use it to do SageMaker Batch Transform, where customers can provide large volumes of input state features and get predictions with high throughput.

[ ]:

import time

from sagemaker.tensorflow.model import TensorFlowModel

if local_mode:
sage_session = sagemaker.local.LocalSession()

# Create SageMaker model entity by using model data generated by the estimator
model = TensorFlowModel(
model_data=estimator.model_data,
framework_version="1.15",
sagemaker_session=sage_session,
role=role,
)

prefix = "batch_test"

# setup input data prefix and output data prefix for batch transform
batch_input = "s3://{}/{}/{}/input/".format(
s3_bucket, job_name, prefix
)  # The location of the test dataset
batch_output = "s3://{}/{}/{}/output/".format(
s3_bucket, job_name, prefix
)  # The location to store the results of the batch transform job
print("Inputpath for batch transform: {}".format(batch_input))
print("Outputpath for batch transform: {}".format(batch_output))


In this notebook, we use the states of the environments as input for the Batch Transform.

[ ]:

import time

file_name = "env_states_{}.json".format(int(time.time()))
# resetting the environments
vectored_envs.reset_all_envs()
# dump environment states into jsonlines file
vectored_envs.dump_environment_states(tmp_dir, file_name)


In order to use SageMaker Batch Transform, we’ll need to first upload the input data from local to S3 bucket

[ ]:

%%time
from pathlib import Path

local_input_file_path = Path(tmp_dir) / file_name
s3_input_file_path = batch_input + file_name  # Path library will remove :// from s3 path
print(
"Copy file from local path '{}' to s3 path '{}'".format(
local_input_file_path, s3_input_file_path
)
)
assert os.system("aws s3 cp {} {}".format(local_input_file_path, s3_input_file_path)) == 0
print("S3 batch input file path: {}".format(s3_input_file_path))


Similar to how we launch a training job on SageMaker, we can initiate a batch transform job either in Local mode or SageMaker mode.

[ ]:

if local_mode:
instance_type = "local"
else:
instance_type = "ml.m4.xlarge"

transformer = model.transformer(
instance_count=1,
instance_type=instance_type,
output_path=batch_output,
assemble_with="Line",
accept="application/jsonlines",
strategy="SingleRecord",
)

transformer.transform(
data=batch_input,
data_type="S3Prefix",
content_type="application/jsonlines",
split_type="Line",
join_source="Input",
)

transformer.wait()


After we finished the batch transform job, we can download the prediction output from S3 bucket to local machine.

[ ]:

import subprocess

# get the latest generated output file
cmd = "aws s3 ls {} --recursive | sort | tail -n 1".format(batch_output)
result = subprocess.check_output(cmd, shell=True).decode("utf-8").split(" ")[-1].strip()
local_output_file_path = Path(tmp_dir) / f"{file_name}.out"
s3_output_file_path = "s3://{}/{}".format(s3_bucket, result)
print(
"Copy file from s3 path '{}' to local path '{}'".format(
s3_output_file_path, local_output_file_path
)
)
os.system("aws s3 cp {} {}".format(s3_output_file_path, local_output_file_path))
print("S3 batch output file local path: {}".format(local_output_file_path))

[ ]:

import subprocess

batcmd = "cat {}".format(local_output_file_path)
results = subprocess.check_output(batcmd, shell=True).decode("utf-8").split("\n")

[ ]:

results[:10]


In this notebook, we use simulated environments to collect rollout data of a random policy. Assuming the updated policy is now deployed, we can use Batch Transform to collect rollout data from this policy.

Here are the steps on how to collect rollout data with Batch Transform: 1. Use Batch Transform to get action predictions, provided observation features from the live environment at timestep t 2. Deployed agent takes suggested actions against the environment (simulator / real) at timestep t 3. Environment returns new observation features at timestep t+1 4. Return back to step 1. Use Batch Transform to get action predictions at timestep t+1

This iterative procedure enables us to collect a set of data that can cover the whole episode, similar to what we’ve shown at the beginning of the notebook. Once the data is sufficient, we can use these data to kick off a BatchRL training again.

Batch Transform works well when there are multiple episodes interacting with the environments concurrently. One of the typical use cases is email campaign, where each email user is an independent episode interacting with the deployed policy. Batch Transform can concurrently collect rollout data from millions of user context with efficiency. The collected rollout data can then be supplied to Batch RL Training to train a better policy to serve the email users.

### Reference

1. Batch Reinforcement Learning with Coach: https://github.com/NervanaSystems/coach/blob/master/tutorials/4.%20Batch%20Reinforcement%20Learning.ipynb

2. AG Barto, RS Sutton and CW Anderson, “Neuronlike Adaptive Elements That Can Solve Difficult Learning Control Problem”, IEEE Transactions on Systems, Man, and Cybernetics, 1983.

3. Thomas, Philip, Georgios Theocharous, and Mohammad Ghavamzadeh. “High confidence policy improvement.” International Conference on Machine Learning. 2015.

4. Jiang, Nan, and Lihong Li. “Doubly robust off-policy value evaluation for reinforcement learning.” arXiv preprint arXiv:1511.03722 (2015).

5. Fujimoto, Scott, David Meger, and Doina Precup. “Off-policy deep reinforcement learning without exploration.” arXiv preprint arXiv:1812.02900 (2018)

6. Van Hasselt, Hado, Arthur Guez, and David Silver. “Deep reinforcement learning with double q-learning.” Thirtieth AAAI conference on artificial intelligence. 2016.