Train your first Deep Reinforcement Learning Agent 🤖

Ask a Question Open In Colab

Now that you’ve studied the bases of Reinforcement Learning, you’re ready to train your first agent and share it with the community through the Hub 🔥: A Lunar Lander agent that will learn to land correctly on the Moon 🌕

LunarLander

And finally, you’ll upload this trained agent to the Hugging Face Hub 🤗, a free, open platform where people can share ML models, datasets, and demos.

Thanks to our leaderboard, you’ll be able to compare your results with other classmates and exchange the best practices to improve your agent’s scores. Who will win the challenge for Unit 1 🏆?

To validate this hands-on for the certification process, you need to push your trained model to the Hub and get a result of >= 200.

To find your result, go to the leaderboard and find your model, the result = mean_reward - std of reward

For more information about the certification process, check this section 👉 https://huggingface.co/deep-rl-course/en/unit0/introduction#certification-process

So let’s get started! 🚀

To start the hands-on click on Open In Colab button 👇 :

Open In Colab

You can either do this hands-on by reading the notebook or following it with the video tutorial 📹 :

Unit 1: Train your first Deep Reinforcement Learning Agent 🤖

Unit 1 thumbnail

In this notebook, you’ll train your first Deep Reinforcement Learning agent a Lunar Lander agent that will learn to land correctly on the Moon 🌕. Using Stable-Baselines3 a Deep Reinforcement Learning library, share them with the community, and experiment with different configurations

⬇️ Here is an example of what you will achieve in just a couple of minutes. ⬇️

%%html
<video controls autoplay><source src="https://huggingface.co/ThomasSimonini/ppo-LunarLander-v2/resolve/main/replay.mp4" type="video/mp4"></video>

The environment 🎮

The library used 📚

We’re constantly trying to improve our tutorials, so if you find some issues in this notebook, please open an issue on the Github Repo.

Objectives of this notebook 🏆

At the end of the notebook, you will:

This hands-on is from Deep Reinforcement Learning Course

Deep RL Course illustration

In this free course, you will:

And more check 📚 the syllabus 👉 https://simoninithomas.github.io/deep-rl-course

Don’t forget to sign up to the course (we are collecting your email to be able to send you the links when each Unit is published and give you information about the challenges and updates).

The best way to keep in touch and ask questions is to join our discord server to exchange with the community and with us 👉🏻 https://discord.gg/ydHrjt3WP5

Prerequisites 🏗️

Before diving into the notebook, you need to:

🔲 📝 Read Unit 0 that gives you all the information about the course and help you to onboard 🤗

🔲 📚 Develop an understanding of the foundations of Reinforcement learning (MC, TD, Rewards hypothesis…) by doing Unit 1

A small recap of what is Deep Reinforcement Learning 📚

The RL process

Let’s do a small recap on what we learned in the first Unit:

There are two ways to find your optimal policy:

Let's train our first Deep Reinforcement Learning agent and upload it to the Hub 🚀

Set the GPU 💪

- To **accelerate the agent's training, we'll use a GPU**. To do that, go to `Runtime > Change Runtime type` GPU Step 1 GPU Step 2

Install dependencies and create a virtual screen 🔽

The first step is to install the dependencies, we’ll install multiple ones.

To make things easier, we created a script to install all these dependencies.

!apt install swig cmake
!pip install -r https://huggingface.co/spaces/ThomasSimonini/temp-space-requirements/raw/main/requirements/requirements-unit1.txt

During the notebook, we’ll need to generate a replay video. To do so, with colab, we need to have a virtual screen to be able to render the environment (and thus record the frames).

Hence the following cell will install virtual screen libraries and create and run a virtual screen 🖥

!sudo apt-get update
!apt install python-opengl
!apt install ffmpeg
!apt install xvfb
!pip3 install pyvirtualdisplay

To make sure the new installed libraries are used, sometimes it’s required to restart the notebook runtime. The next cell will force the runtime to crash, so you’ll need to connect again and run the code starting from here. Thanks for this trick, we will be able to run our virtual screen.

import os
os.kill(os.getpid(), 9)
# Virtual display
from pyvirtualdisplay import Display

virtual_display = Display(visible=0, size=(1400, 900))
virtual_display.start()

Import the packages 📦

One additional library we import is huggingface_hub to be able to upload and download trained models from the hub.

The Hugging Face Hub 🤗 works as a central place where anyone can share and explore models and datasets. It has versioning, metrics, visualizations and other features that will allow you to easily collaborate with others.

You can see here all the Deep reinforcement Learning models available 👉 https://huggingface.co/models?pipeline_tag=reinforcement-learning&sort=downloads

import gym

from huggingface_sb3 import load_from_hub, package_to_hub, push_to_hub
from huggingface_hub import (
    notebook_login,
)  # To log to our Hugging Face account to be able to upload models to the Hub.

from stable_baselines3 import PPO
from stable_baselines3.common.evaluation import evaluate_policy
from stable_baselines3.common.env_util import make_vec_env

Understand what is Gym and how it works 🤖

🏋 The library containing our environment is called Gym. You’ll use Gym a lot in Deep Reinforcement Learning.

The Gym library provides two things:

Let’s look at an example, but first let’s remember what’s the RL Loop.

The RL process

At each step:

With Gym:

1️⃣ We create our environment using gym.make()

2️⃣ We reset the environment to its initial state with observation = env.reset()

At each step:

3️⃣ Get an action using our model (in our example we take a random action)

4️⃣ Using env.step(action), we perform this action in the environment and get

If the episode is done:

Let’s look at an example! Make sure to read the code

import gym

# First, we create our environment called LunarLander-v2
env = gym.make("LunarLander-v2")

# Then we reset this environment
observation = env.reset()

for _ in range(20):
    # Take a random action
    action = env.action_space.sample()
    print("Action taken:", action)

    # Do this action in the environment and get
    # next_state, reward, done and info
    observation, reward, done, info = env.step(action)

    # If the game is done (in our case we land, crashed or timeout)
    if done:
        # Reset the environment
        print("Environment is reset")
        observation = env.reset()

Create the LunarLander environment 🌛 and understand how it works

The environment 🎮

In this first tutorial, we’re going to train our agent, a Lunar Lander, to land correctly on the moon. To do that, the agent needs to learn to adapt its speed and position(horizontal, vertical, and angular) to land correctly.


💡 A good habit when you start to use an environment is to check its documentation

👉 https://www.gymlibrary.dev/environments/box2d/lunar_lander/


Let’s see what the Environment looks like:

# We create our environment with gym.make("<name_of_the_environment>")
env = gym.make("LunarLander-v2")
env.reset()
print("_____OBSERVATION SPACE_____ \n")
print("Observation Space Shape", env.observation_space.shape)
print("Sample observation", env.observation_space.sample())  # Get a random observation

We see with Observation Space Shape (8,) that the observation is a vector of size 8, where each value contains different information about the lander:

print("\n _____ACTION SPACE_____ \n")
print("Action Space Shape", env.action_space.n)
print("Action Space Sample", env.action_space.sample())  # Take a random action

The action space (the set of possible actions the agent can take) is discrete with 4 actions available 🎮:

Reward function (the function that will gives a reward at each timestep) 💰:

Vectorized Environment

# Create the environment
env = make_vec_env("LunarLander-v2", n_envs=16)

Create the Model 🤖


💡 A good habit when using a new library is to dive first on the documentation: https://stable-baselines3.readthedocs.io/en/master/ and then try some tutorials.


image.png

To solve this problem, we’re going to use SB3 PPO. PPO (aka Proximal Policy Optimization) is one of the of the SOTA (state of the art) Deep Reinforcement Learning algorithms that you’ll study during this course.

PPO is a combination of:

Stable-Baselines3 is easy to set up:

1️⃣ You create your environment (in our case it was done above)

2️⃣ You define the model you want to use and instantiate this model model = PPO("MlpPolicy")

3️⃣ You train the agent with model.learn and define the number of training timesteps

# Create environment

env = gym.make('LunarLander-v2')

# Instantiate the agent
model = PPO('MlpPolicy', env, verbose=1)

# Train the agent
model.learn(total_timesteps=int(2e5))
# TODO: Define a PPO MlpPolicy architecture
# We use MultiLayerPerceptron (MLPPolicy) because the input is a vector,
# if we had frames as input we would use CnnPolicy
model =

Solution

# SOLUTION
# We added some parameters to accelerate the training
model = PPO(
    policy="MlpPolicy",
    env=env,
    n_steps=1024,
    batch_size=64,
    n_epochs=4,
    gamma=0.999,
    gae_lambda=0.98,
    ent_coef=0.01,
    verbose=1,
)

Train the PPO agent 🏃

# TODO: Train it for 1,000,000 timesteps

# TODO: Specify file name for model and save the model to file
model_name = ""

Solution

# SOLUTION
# Train it for 1,000,000 timesteps
model.learn(total_timesteps=1000000)
# Save the model
model_name = "ppo-LunarLander-v2"
model.save(model_name)

Evaluate the agent 📈

💡 When you evaluate your agent, you should not use your training environment but create an evaluation environment.

# TODO: Evaluate the agent
# Create a new environment for evaluation
eval_env =

# Evaluate the model with 10 evaluation episodes and deterministic=True
mean_reward, std_reward =

# Print the results

Solution

# @title
eval_env = gym.make("LunarLander-v2")
mean_reward, std_reward = evaluate_policy(model, eval_env, n_eval_episodes=10, deterministic=True)
print(f"mean_reward={mean_reward:.2f} +/- {std_reward}")

Publish our trained model on the Hub 🔥

Now that we saw we got good results after the training, we can publish our trained model on the Hub 🤗 with one line of code.

📚 The libraries documentation 👉 https://github.com/huggingface/huggingface_sb3/tree/main#hugging-face—x-stable-baselines3-v20

Here’s an example of a Model Card (with Space Invaders):

By using package_to_hub you evaluate, record a replay, generate a model card of your agent and push it to the hub.

This way:

To be able to share your model with the community there are three more steps to follow:

1️⃣ (If it’s not already done) create an account to HF ➡ https://huggingface.co/join

2️⃣ Sign in and then, you need to store your authentication token from the Hugging Face website.

Create HF Token
notebook_login()
!git config --global credential.helper store

If you don’t want to use a Google Colab or a Jupyter Notebook, you need to use this command instead: huggingface-cli login

3️⃣ We’re now ready to push our trained agent to the 🤗 Hub 🔥 using package_to_hub() function

Let’s fill the package_to_hub function:

💡 A good name is {username}/{model_architecture}-{env_id}

import gym
from stable_baselines3.common.vec_env import DummyVecEnv
from stable_baselines3.common.env_util import make_vec_env

from huggingface_sb3 import package_to_hub

## TODO: Define a repo_id
## repo_id is the id of the model repository from the Hugging Face Hub (repo_id = {organization}/{repo_name} for instance ThomasSimonini/ppo-LunarLander-v2
repo_id =

# TODO: Define the name of the environment
env_id =

# Create the evaluation env
eval_env = DummyVecEnv([lambda: gym.make(env_id)])


# TODO: Define the model architecture we used
model_architecture = ""

## TODO: Define the commit message
commit_message = ""

# method save, evaluate, generate a model card and record a replay video of your agent before pushing the repo to the hub
package_to_hub(model=model, # Our trained model
               model_name=model_name, # The name of our trained model
               model_architecture=model_architecture, # The model architecture we used: in our case PPO
               env_id=env_id, # Name of the environment
               eval_env=eval_env, # Evaluation Environment
               repo_id=repo_id, # id of the model repository from the Hugging Face Hub (repo_id = {organization}/{repo_name} for instance ThomasSimonini/ppo-LunarLander-v2
               commit_message=commit_message)

# Note: if after running the package_to_hub function and it gives an issue of rebasing, please run the following code
# cd <path_to_repo> && git add . && git commit -m "Add message" && git pull
# And don't forget to do a "git push" at the end to push the change to the hub.

Solution

import gym

from stable_baselines3 import PPO
from stable_baselines3.common.vec_env import DummyVecEnv
from stable_baselines3.common.env_util import make_vec_env

from huggingface_sb3 import package_to_hub

# PLACE the variables you've just defined two cells above
# Define the name of the environment
env_id = "LunarLander-v2"

# TODO: Define the model architecture we used
model_architecture = "PPO"

## Define a repo_id
## repo_id is the id of the model repository from the Hugging Face Hub (repo_id = {organization}/{repo_name} for instance ThomasSimonini/ppo-LunarLander-v2
## CHANGE WITH YOUR REPO ID
repo_id = "ThomasSimonini/ppo-LunarLander-v2"  # Change with your repo id, you can't push with mine 😄

## Define the commit message
commit_message = "Upload PPO LunarLander-v2 trained agent"

# Create the evaluation env
eval_env = DummyVecEnv([lambda: gym.make(env_id)])

# PLACE the package_to_hub function you've just filled here
package_to_hub(
    model=model,  # Our trained model
    model_name=model_name,  # The name of our trained model
    model_architecture=model_architecture,  # The model architecture we used: in our case PPO
    env_id=env_id,  # Name of the environment
    eval_env=eval_env,  # Evaluation Environment
    repo_id=repo_id,  # id of the model repository from the Hugging Face Hub (repo_id = {organization}/{repo_name} for instance ThomasSimonini/ppo-LunarLander-v2
    commit_message=commit_message,
)

Congrats 🥳 you’ve just trained and uploaded your first Deep Reinforcement Learning agent. The script above should have displayed a link to a model repository such as https://huggingface.co/osanseviero/test_sb3. When you go to this link, you can:

Under the hood, the Hub uses git-based repositories (don’t worry if you don’t know what git is), which means you can update the model with new versions as you experiment and improve your agent.

Compare the results of your LunarLander-v2 with your classmates using the leaderboard 🏆 👉 https://huggingface.co/spaces/huggingface-projects/Deep-Reinforcement-Learning-Leaderboard

Load a saved LunarLander model from the Hub 🤗

Thanks to [ironbar](https://github.com/ironbar) for the contribution.

Loading a saved model from the Hub is really easy.

You go https://huggingface.co/models?library=stable-baselines3 to see the list of all the Stable-baselines3 saved models.

  1. You select one and copy its repo_id
Copy-id
  1. Then we just need to use load_from_hub with:
from huggingface_sb3 import load_from_hub

repo_id = "Classroom-workshop/assignment2-omar"  # The repo_id
filename = "ppo-LunarLander-v2.zip"  # The model filename.zip

# When the model was trained on Python 3.8 the pickle protocol is 5
# But Python 3.6, 3.7 use protocol 4
# In order to get compatibility we need to:
# 1. Install pickle5 (we done it at the beginning of the colab)
# 2. Create a custom empty object we pass as parameter to PPO.load()
custom_objects = {
    "learning_rate": 0.0,
    "lr_schedule": lambda _: 0.0,
    "clip_range": lambda _: 0.0,
}

checkpoint = load_from_hub(repo_id, filename)
model = PPO.load(checkpoint, custom_objects=custom_objects, print_system_info=True)

Let’s evaluate this agent:

# @title
eval_env = gym.make("LunarLander-v2")
mean_reward, std_reward = evaluate_policy(model, eval_env, n_eval_episodes=10, deterministic=True)
print(f"mean_reward={mean_reward:.2f} +/- {std_reward}")

Some additional challenges 🏆

The best way to learn **is to try things by your own**! As you saw, the current agent is not doing great. As a first suggestion, you can train for more steps. With 1,000,000 steps, we saw some great results!

In the Leaderboard you will find your agents. Can you get to the top?

Here are some ideas to achieve so:

Compare the results of your LunarLander-v2 with your classmates using the leaderboard 🏆

Is moon landing too boring to you? Try to change the environment, why not using MountainCar-v0, CartPole-v1 or CarRacing-v0? Check how they works using the gym documentation and have fun 🎉.


Congrats on finishing this chapter! That was the biggest one, and there was a lot of information.

If you’re still feel confused with all these elements…it’s totally normal! This was the same for me and for all people who studied RL.

Take time to really grasp the material before continuing and try the additional challenges. It’s important to master these elements and having a solid foundations.

Naturally, during the course, we’re going to use and deeper explain again these terms but it’s better to have a good understanding of them now before diving into the next chapters.

Next time, in the bonus unit 1, you’ll train Huggy the Dog to fetch the stick.

Huggy

Keep learning, stay awesome 🤗