diff --git a/notebooks/unit4/requirements-unit4.txt b/notebooks/unit4/requirements-unit4.txt new file mode 100644 index 0000000..1d18b22 --- /dev/null +++ b/notebooks/unit4/requirements-unit4.txt @@ -0,0 +1,6 @@ +gym +git+https://github.com/ntasfi/PyGame-Learning-Environment.git +git+https://github.com/qlan3/gym-games.git +huggingface_hub +imageio-ffmpeg +pyyaml==6.0 diff --git a/notebooks/unit4/unit4.ipynb b/notebooks/unit4/unit4.ipynb new file mode 100644 index 0000000..45d1c0c --- /dev/null +++ b/notebooks/unit4/unit4.ipynb @@ -0,0 +1,1614 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "id": "view-in-github", + "colab_type": "text" + }, + "source": [ + "\"Open" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "CjRWziAVU2lZ" + }, + "source": [ + "# Unit 4: Code your first Deep Reinforcement Learning Algorithm with PyTorch: Reinforce. And test its robustness ๐Ÿ’ช\n", + "\n", + "\"thumbnail\"/\n", + "\n", + "\n", + "In this notebook, you'll code your first Deep Reinforcement Learning algorithm from scratch: Reinforce (also called Monte Carlo Policy Gradient).\n", + "\n", + "Reinforce is a *Policy-based method*: a Deep Reinforcement Learning algorithm that tries **to optimize the policy directly without using an action-value function**.\n", + "\n", + "More precisely, Reinforce is a *Policy-gradient method*, a subclass of *Policy-based methods* that aims **to optimize the policy directly by estimating the weights of the optimal policy using gradient ascent**.\n", + "\n", + "To test its robustness, we're going to train it in 2 different simple environments:\n", + "- Cartpole-v1\n", + "- PixelcopterEnv\n", + "\n", + "โฌ‡๏ธ Here is an example of what **you will achieve at the end of this notebook.** โฌ‡๏ธ" + ] + }, + { + "cell_type": "markdown", + "source": [ + " \"Environments\"/\n" + ], + "metadata": { + "id": "s4rBom2sbo7S" + } + }, + { + "cell_type": "markdown", + "source": [ + "### ๐ŸŽฎ Environments: \n", + "\n", + "- [CartPole-v1](https://www.gymlibrary.dev/environments/classic_control/cart_pole/)\n", + "- [PixelCopter](https://pygame-learning-environment.readthedocs.io/en/latest/user/games/pixelcopter.html)\n", + "\n", + "### ๐Ÿ“š RL-Library: \n", + "\n", + "- Python\n", + "- PyTorch\n", + "\n", + "\n", + "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](https://github.com/huggingface/deep-rl-class/issues)." + ], + "metadata": { + "id": "BPLwsPajb1f8" + } + }, + { + "cell_type": "markdown", + "metadata": { + "id": "L_WSo0VUV99t" + }, + "source": [ + "## Objectives of this notebook ๐Ÿ†\n", + "At the end of the notebook, you will:\n", + "- Be able to **code from scratch a Reinforce algorithm using PyTorch.**\n", + "- Be able to **test the robustness of your agent using simple environments.**\n", + "- Be able to **push your trained agent to the Hub** with a nice video replay and an evaluation score ๐Ÿ”ฅ." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "lEPrZg2eWa4R" + }, + "source": [ + "## This notebook is from the Deep Reinforcement Learning Course\n", + "\"Deep" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "6p5HnEefISCB" + }, + "source": [ + "In this free course, you will:\n", + "\n", + "- ๐Ÿ“– Study Deep Reinforcement Learning in **theory and practice**.\n", + "- ๐Ÿง‘โ€๐Ÿ’ป Learn to **use famous Deep RL libraries** such as Stable Baselines3, RL Baselines3 Zoo, CleanRL and Sample Factory 2.0.\n", + "- ๐Ÿค– Train **agents in unique environments** \n", + "\n", + "And more check ๐Ÿ“š the syllabus ๐Ÿ‘‰ https://simoninithomas.github.io/deep-rl-course\n", + "\n", + "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).**\n", + "\n", + "\n", + "The best way to keep in touch is to join our discord server to exchange with the community and with us ๐Ÿ‘‰๐Ÿป https://discord.gg/ydHrjt3WP5" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "mjY-eq3eWh9O" + }, + "source": [ + "## Prerequisites ๐Ÿ—๏ธ\n", + "Before diving into the notebook, you need to:\n", + "\n", + "๐Ÿ”ฒ ๐Ÿ“š [Study Policy Gradients by reading Unit 4](https://huggingface.co/deep-rl-course/unit4/introduction)" + ] + }, + { + "cell_type": "markdown", + "source": [ + "# Let's code Reinforce algorithm from scratch ๐Ÿ”ฅ\n", + "\n", + "\n", + "To validate this hands-on for the certification process, you need to push your trained models to the Hub.\n", + "\n", + "- Get a result of >= 350 for `Cartpole-v1`.\n", + "- Get a result of >= 5 for `PixelCopter`.\n", + "\n", + "To find your result, go to the leaderboard and find your model, **the result = mean_reward - std of reward**. **If you don't see your model on the leaderboard, go at the bottom of the leaderboard page and click on the refresh button**.\n", + "\n", + "For more information about the certification process, check this section ๐Ÿ‘‰ https://huggingface.co/deep-rl-course/en/unit0/introduction#certification-process\n" + ], + "metadata": { + "id": "Bsh4ZAamchSl" + } + }, + { + "cell_type": "markdown", + "source": [ + "## An advice ๐Ÿ’ก\n", + "It's better to run this colab in a copy on your Google Drive, so that **if it timeouts** you still have the saved notebook on your Google Drive and do not need to fill everything from scratch.\n", + "\n", + "To do that you can either do `Ctrl + S` or `File > Save a copy in Google Drive.`" + ], + "metadata": { + "id": "JoTC9o2SczNn" + } + }, + { + "cell_type": "markdown", + "source": [ + "## Set the GPU ๐Ÿ’ช\n", + "- To **accelerate the agent's training, we'll use a GPU**. To do that, go to `Runtime > Change Runtime type`\n", + "\n", + "\"GPU" + ], + "metadata": { + "id": "PU4FVzaoM6fC" + } + }, + { + "cell_type": "markdown", + "source": [ + "- `Hardware Accelerator > GPU`\n", + "\n", + "\"GPU" + ], + "metadata": { + "id": "KV0NyFdQM9ZG" + } + }, + { + "cell_type": "markdown", + "source": [ + "## Create a virtual display ๐Ÿ–ฅ\n", + "\n", + "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). \n", + "\n", + "Hence the following cell will install the librairies and create and run a virtual screen ๐Ÿ–ฅ" + ], + "metadata": { + "id": "bTpYcVZVMzUI" + } + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "jV6wjQ7Be7p5" + }, + "outputs": [], + "source": [ + "%%capture\n", + "!apt install python-opengl\n", + "!apt install ffmpeg\n", + "!apt install xvfb\n", + "!pip install pyvirtualdisplay\n", + "!pip install pyglet==1.5.1" + ] + }, + { + "cell_type": "code", + "source": [ + "# Virtual display\n", + "from pyvirtualdisplay import Display\n", + "\n", + "virtual_display = Display(visible=0, size=(1400, 900))\n", + "virtual_display.start()" + ], + "metadata": { + "id": "Sr-Nuyb1dBm0" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "tjrLfPFIW8XK" + }, + "source": [ + "## Install the dependencies ๐Ÿ”ฝ\n", + "The first step is to install the dependencies. Weโ€™ll install multiple ones:\n", + "\n", + "- `gym`\n", + "- `gym-games`: Extra gym environments made with PyGame.\n", + "- `huggingface_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.\n", + "\n", + "You can see here all the Reinforce models available ๐Ÿ‘‰ https://huggingface.co/models?other=reinforce\n", + "\n", + "And you can find all the Deep Reinforcement Learning models here ๐Ÿ‘‰ https://huggingface.co/models?pipeline_tag=reinforcement-learning\n" + ] + }, + { + "cell_type": "code", + "source": [ + "!pip install -r https://raw.githubusercontent.com/huggingface/deep-rl-class/main/notebooks/unit4/requirements-unit4.txt" + ], + "metadata": { + "id": "e8ZVi-uydpgL" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "AAHAq6RZW3rn" + }, + "source": [ + "## Import the packages ๐Ÿ“ฆ\n", + "In addition to import the installed libraries, we also import:\n", + "\n", + "- `imageio`: A library that will help us to generate a replay video\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "V8oadoJSWp7C" + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "\n", + "from collections import deque\n", + "\n", + "import matplotlib.pyplot as plt\n", + "%matplotlib inline\n", + "\n", + "# PyTorch\n", + "import torch\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "import torch.optim as optim\n", + "from torch.distributions import Categorical\n", + "\n", + "# Gym\n", + "import gym\n", + "import gym_pygame\n", + "\n", + "# Hugging Face Hub\n", + "from huggingface_hub import notebook_login # To log to our Hugging Face account to be able to upload models to the Hub.\n", + "import imageio" + ] + }, + { + "cell_type": "markdown", + "source": [ + "## Check if we have a GPU\n", + "\n", + "- Let's check if we have a GPU\n", + "- If it's the case you should see `device:cuda0`" + ], + "metadata": { + "id": "RfxJYdMeeVgv" + } + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "kaJu5FeZxXGY" + }, + "outputs": [], + "source": [ + "device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "U5TNYa14aRav" + }, + "outputs": [], + "source": [ + "print(device)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "PBPecCtBL_pZ" + }, + "source": [ + "We're now ready to implement our Reinforce algorithm ๐Ÿ”ฅ" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "8KEyKYo2ZSC-" + }, + "source": [ + "# First agent: Playing CartPole-v1 ๐Ÿค–" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "haLArKURMyuF" + }, + "source": [ + "## Create the CartPole environment and understand how it works\n", + "### [The environment ๐ŸŽฎ](https://www.gymlibrary.dev/environments/classic_control/cart_pole/)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "AH_TaLKFXo_8" + }, + "source": [ + "### Why do we use a simple environment like CartPole-v1?\n", + "As explained in [Reinforcement Learning Tips and Tricks](https://stable-baselines3.readthedocs.io/en/master/guide/rl_tips.html), when you implement your agent from scratch you need **to be sure that it works correctly and find bugs with easy environments before going deeper**. Since finding bugs will be much easier in simple environments.\n", + "\n", + "\n", + "> Try to have some โ€œsign of lifeโ€ on toy problems\n", + "\n", + "\n", + "> Validate the implementation by making it run on harder and harder envs (you can compare results against the RL zoo). You usually need to run hyperparameter optimization for that step.\n", + "___\n", + "### The CartPole-v1 environment\n", + "\n", + "> A pole is attached by an un-actuated joint to a cart, which moves along a frictionless track. The pendulum is placed upright on the cart and the goal is to balance the pole by applying forces in the left and right direction on the cart.\n", + "\n", + "\n", + "\n", + "So, we start with CartPole-v1. The goal is to push the cart left or right **so that the pole stays in the equilibrium.**\n", + "\n", + "The episode ends if:\n", + "- The pole Angle is greater than ยฑ12ยฐ\n", + "- Cart Position is greater than ยฑ2.4\n", + "- Episode length is greater than 500\n", + "\n", + "We get a reward ๐Ÿ’ฐ of +1 every timestep the Pole stays in the equilibrium." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "POOOk15_K6KA" + }, + "outputs": [], + "source": [ + "env_id = \"CartPole-v1\"\n", + "# Create the env\n", + "env = gym.make(env_id)\n", + "\n", + "# Create the evaluation env\n", + "eval_env = gym.make(env_id)\n", + "\n", + "# Get the state space and action space\n", + "s_size = env.observation_space.shape[0]\n", + "a_size = env.action_space.n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "FMLFrjiBNLYJ" + }, + "outputs": [], + "source": [ + "print(\"_____OBSERVATION SPACE_____ \\n\")\n", + "print(\"The State Space is: \", s_size)\n", + "print(\"Sample observation\", env.observation_space.sample()) # Get a random observation" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "Lu6t4sRNNWkN" + }, + "outputs": [], + "source": [ + "print(\"\\n _____ACTION SPACE_____ \\n\")\n", + "print(\"The Action Space is: \", a_size)\n", + "print(\"Action Space Sample\", env.action_space.sample()) # Take a random action" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "7SJMJj3WaFOz" + }, + "source": [ + "## Let's build the Reinforce Architecture\n", + "This implementation is based on two implementations:\n", + "- [PyTorch official Reinforcement Learning example](https://github.com/pytorch/examples/blob/main/reinforcement_learning/reinforce.py)\n", + "- [Udacity Reinforce](https://github.com/udacity/deep-reinforcement-learning/blob/master/reinforce/REINFORCE.ipynb)\n", + "- [Improvement of the integration by Chris1nexus](https://github.com/huggingface/deep-rl-class/pull/95)\n", + "\n", + "\"Reinforce\"/" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "49kogtxBODX8" + }, + "source": [ + "So we want:\n", + "- Two fully connected layers (fc1 and fc2).\n", + "- Using ReLU as activation function of fc1\n", + "- Using Softmax to output a probability distribution over actions" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "w2LHcHhVZvPZ" + }, + "outputs": [], + "source": [ + "class Policy(nn.Module):\n", + " def __init__(self, s_size, a_size, h_size):\n", + " super(Policy, self).__init__()\n", + " # Create two fully connected layers\n", + "\n", + "\n", + "\n", + " def forward(self, x):\n", + " # Define the forward pass\n", + " # state goes to fc1 then we apply ReLU activation function\n", + "\n", + " # fc1 outputs goes to fc2\n", + "\n", + " # We output the softmax\n", + " \n", + " def act(self, state):\n", + " \"\"\"\n", + " Given a state, take action\n", + " \"\"\"\n", + " state = torch.from_numpy(state).float().unsqueeze(0).to(device)\n", + " probs = self.forward(state).cpu()\n", + " m = Categorical(probs)\n", + " action = np.argmax(m)\n", + " return action.item(), m.log_prob(action)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "rOMrdwSYOWSC" + }, + "source": [ + "### Solution" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "jGdhRSVrOV4K" + }, + "outputs": [], + "source": [ + "class Policy(nn.Module):\n", + " def __init__(self, s_size, a_size, h_size):\n", + " super(Policy, self).__init__()\n", + " self.fc1 = nn.Linear(s_size, h_size)\n", + " self.fc2 = nn.Linear(h_size, a_size)\n", + "\n", + " def forward(self, x):\n", + " x = F.relu(self.fc1(x))\n", + " x = self.fc2(x)\n", + " return F.softmax(x, dim=1)\n", + " \n", + " def act(self, state):\n", + " state = torch.from_numpy(state).float().unsqueeze(0).to(device)\n", + " probs = self.forward(state).cpu()\n", + " m = Categorical(probs)\n", + " action = np.argmax(m)\n", + " return action.item(), m.log_prob(action)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "ZTGWL4g2eM5B" + }, + "source": [ + "I make a mistake, can you guess where?\n", + "\n", + "- To find out let's make a forward pass:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "lwnqGBCNePor" + }, + "outputs": [], + "source": [ + "debug_policy = Policy(s_size, a_size, 64).to(device)\n", + "debug_policy.act(env.reset())" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "14UYkoxCPaor" + }, + "source": [ + "- Here we see that the error says `ValueError: The value argument to log_prob must be a Tensor`\n", + "\n", + "- It means that `action` in `m.log_prob(action)` must be a Tensor **but it's not.**\n", + "\n", + "- Do you know why? Check the act function and try to see why it does not work. \n", + "\n", + "Advice ๐Ÿ’ก: Something is wrong in this implementation. Remember that we act function **we want to sample an action from the probability distribution over actions**.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "gfGJNZBUP7Vn" + }, + "source": [ + "### (Real) Solution" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "Ho_UHf49N9i4" + }, + "outputs": [], + "source": [ + "class Policy(nn.Module):\n", + " def __init__(self, s_size, a_size, h_size):\n", + " super(Policy, self).__init__()\n", + " self.fc1 = nn.Linear(s_size, h_size)\n", + " self.fc2 = nn.Linear(h_size, a_size)\n", + "\n", + " def forward(self, x):\n", + " x = F.relu(self.fc1(x))\n", + " x = self.fc2(x)\n", + " return F.softmax(x, dim=1)\n", + " \n", + " def act(self, state):\n", + " state = torch.from_numpy(state).float().unsqueeze(0).to(device)\n", + " probs = self.forward(state).cpu()\n", + " m = Categorical(probs)\n", + " action = m.sample()\n", + " return action.item(), m.log_prob(action)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "rgJWQFU_eUYw" + }, + "source": [ + "By using CartPole, it was easier to debug since **we know that the bug comes from our integration and not from our simple environment**." + ] + }, + { + "cell_type": "markdown", + "source": [ + "- Since **we want to sample an action from the probability distribution over actions**, we can't use `action = np.argmax(m)` since it will always output the action that have the highest probability.\n", + "\n", + "- We need to replace with `action = m.sample()` that will sample an action from the probability distribution P(.|s)" + ], + "metadata": { + "id": "c-20i7Pk0l1T" + } + }, + { + "cell_type": "markdown", + "metadata": { + "id": "4MXoqetzfIoW" + }, + "source": [ + "### Let's build the Reinforce Training Algorithm\n", + "This is the Reinforce algorithm pseudocode:\n", + "\n", + "\"Policy\n", + " " + ] + }, + { + "cell_type": "markdown", + "source": [ + "- When we calculate the return Gt (line 6) we see that we calculate the sum of discounted rewards **starting at timestep t**.\n", + "\n", + "- Why? Because our policy should only **reinforce actions on the basis of the consequences**: so rewards obtained before taking an action are useless (since they were not because of the action), **only the ones that come after the action matters**.\n", + "\n", + "- Before coding this you should read this section [don't let the past distract you](https://spinningup.openai.com/en/latest/spinningup/rl_intro3.html#don-t-let-the-past-distract-you) that explains why we use reward-to-go policy gradient.\n", + "\n", + "We use an interesting technique coded by [Chris1nexus](https://github.com/Chris1nexus) to **compute the return at each timestep efficiently**. The comments explained the procedure. Don't hesitate also [to check the PR explanation](https://github.com/huggingface/deep-rl-class/pull/95)\n", + "But overall the idea is to **compute the return at each timestep efficiently**." + ], + "metadata": { + "id": "QmcXG-9i2Qu2" + } + }, + { + "cell_type": "markdown", + "metadata": { + "id": "O554nUGPpcoq" + }, + "source": [ + "The second question you may ask is **why do we minimize the loss**? You talked about Gradient Ascent not Gradient Descent?\n", + "\n", + "- We want to maximize our utility function $J(\\theta)$ but in PyTorch like in Tensorflow it's better to **minimize an objective function.**\n", + " - So let's say we want to reinforce action 3 at a certain timestep. Before training this action P is 0.25.\n", + " - So we want to modify $\\theta$ such that $\\pi_\\theta(a_3|s; \\theta) > 0.25$\n", + " - Because all P must sum to 1, max $\\pi_\\theta(a_3|s; \\theta)$ will **minimize other action probability.**\n", + " - So we should tell PyTorch **to min $1 - \\pi_\\theta(a_3|s; \\theta)$.**\n", + " - This loss function approaches 0 as $\\pi_\\theta(a_3|s; \\theta)$ nears 1.\n", + " - So we are encouraging the gradient to max $\\pi_\\theta(a_3|s; \\theta)$\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "iOdv8Q9NfLK7" + }, + "outputs": [], + "source": [ + "def reinforce(policy, optimizer, n_training_episodes, max_t, gamma, print_every):\n", + " # Help us to calculate the score during the training\n", + " scores_deque = deque(maxlen=100)\n", + " scores = []\n", + " # Line 3 of pseudocode\n", + " for i_episode in range(1, n_training_episodes+1):\n", + " saved_log_probs = []\n", + " rewards = []\n", + " state = # TODO: reset the environment\n", + " # Line 4 of pseudocode\n", + " for t in range(max_t):\n", + " action, log_prob = # TODO get the action\n", + " saved_log_probs.append(log_prob)\n", + " state, reward, done, _ = # TODO: take an env step\n", + " rewards.append(reward)\n", + " if done:\n", + " break \n", + " scores_deque.append(sum(rewards))\n", + " scores.append(sum(rewards))\n", + " \n", + " # Line 6 of pseudocode: calculate the return\n", + " returns = deque(maxlen=max_t) \n", + " n_steps = len(rewards) \n", + " # Compute the discounted returns at each timestep,\n", + " # as the sum of the gamma-discounted return at time t (G_t) + the reward at time t\n", + " \n", + " # In O(N) time, where N is the number of time steps\n", + " # (this definition of the discounted return G_t follows the definition of this quantity \n", + " # shown at page 44 of Sutton&Barto 2017 2nd draft)\n", + " # G_t = r_(t+1) + r_(t+2) + ...\n", + " \n", + " # Given this formulation, the returns at each timestep t can be computed \n", + " # by re-using the computed future returns G_(t+1) to compute the current return G_t\n", + " # G_t = r_(t+1) + gamma*G_(t+1)\n", + " # G_(t-1) = r_t + gamma* G_t\n", + " # (this follows a dynamic programming approach, with which we memorize solutions in order \n", + " # to avoid computing them multiple times)\n", + " \n", + " # This is correct since the above is equivalent to (see also page 46 of Sutton&Barto 2017 2nd draft)\n", + " # G_(t-1) = r_t + gamma*r_(t+1) + gamma*gamma*r_(t+2) + ...\n", + " \n", + " \n", + " ## Given the above, we calculate the returns at timestep t as: \n", + " # gamma[t] * return[t] + reward[t]\n", + " #\n", + " ## We compute this starting from the last timestep to the first, in order\n", + " ## to employ the formula presented above and avoid redundant computations that would be needed \n", + " ## if we were to do it from first to last.\n", + " \n", + " ## Hence, the queue \"returns\" will hold the returns in chronological order, from t=0 to t=n_steps\n", + " ## thanks to the appendleft() function which allows to append to the position 0 in constant time O(1)\n", + " ## a normal python list would instead require O(N) to do this.\n", + " for t in range(n_steps)[::-1]:\n", + " disc_return_t = (returns[0] if len(returns)>0 else 0)\n", + " returns.appendleft( ) # TODO: complete here \n", + " \n", + " ## standardization of the returns is employed to make training more stable\n", + " eps = np.finfo(np.float32).eps.item()\n", + " \n", + " ## eps is the smallest representable float, which is \n", + " # added to the standard deviation of the returns to avoid numerical instabilities\n", + " returns = torch.tensor(returns)\n", + " returns = (returns - returns.mean()) / (returns.std() + eps)\n", + " \n", + " # Line 7:\n", + " policy_loss = []\n", + " for log_prob, disc_return in zip(saved_log_probs, returns):\n", + " policy_loss.append(-log_prob * disc_return)\n", + " policy_loss = torch.cat(policy_loss).sum()\n", + " \n", + " # Line 8: PyTorch prefers gradient descent \n", + " optimizer.zero_grad()\n", + " policy_loss.backward()\n", + " optimizer.step()\n", + " \n", + " if i_episode % print_every == 0:\n", + " print('Episode {}\\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_deque)))\n", + " \n", + " return scores" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "YB0Cxrw1StrP" + }, + "source": [ + "#### Solution" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "NCNvyElRStWG" + }, + "outputs": [], + "source": [ + "def reinforce(policy, optimizer, n_training_episodes, max_t, gamma, print_every):\n", + " # Help us to calculate the score during the training\n", + " scores_deque = deque(maxlen=100)\n", + " scores = []\n", + " # Line 3 of pseudocode\n", + " for i_episode in range(1, n_training_episodes+1):\n", + " saved_log_probs = []\n", + " rewards = []\n", + " state = env.reset()\n", + " # Line 4 of pseudocode\n", + " for t in range(max_t):\n", + " action, log_prob = policy.act(state)\n", + " saved_log_probs.append(log_prob)\n", + " state, reward, done, _ = env.step(action)\n", + " rewards.append(reward)\n", + " if done:\n", + " break \n", + " scores_deque.append(sum(rewards))\n", + " scores.append(sum(rewards))\n", + " \n", + " # Line 6 of pseudocode: calculate the return\n", + " returns = deque(maxlen=max_t) \n", + " n_steps = len(rewards) \n", + " # Compute the discounted returns at each timestep,\n", + " # as \n", + " # the sum of the gamma-discounted return at time t (G_t) + the reward at time t\n", + " #\n", + " # In O(N) time, where N is the number of time steps\n", + " # (this definition of the discounted return G_t follows the definition of this quantity \n", + " # shown at page 44 of Sutton&Barto 2017 2nd draft)\n", + " # G_t = r_(t+1) + r_(t+2) + ...\n", + " \n", + " # Given this formulation, the returns at each timestep t can be computed \n", + " # by re-using the computed future returns G_(t+1) to compute the current return G_t\n", + " # G_t = r_(t+1) + gamma*G_(t+1)\n", + " # G_(t-1) = r_t + gamma* G_t\n", + " # (this follows a dynamic programming approach, with which we memorize solutions in order \n", + " # to avoid computing them multiple times)\n", + " \n", + " # This is correct since the above is equivalent to (see also page 46 of Sutton&Barto 2017 2nd draft)\n", + " # G_(t-1) = r_t + gamma*r_(t+1) + gamma*gamma*r_(t+2) + ...\n", + " \n", + " \n", + " ## Given the above, we calculate the returns at timestep t as: \n", + " # gamma[t] * return[t] + reward[t]\n", + " #\n", + " ## We compute this starting from the last timestep to the first, in order\n", + " ## to employ the formula presented above and avoid redundant computations that would be needed \n", + " ## if we were to do it from first to last.\n", + " \n", + " ## Hence, the queue \"returns\" will hold the returns in chronological order, from t=0 to t=n_steps\n", + " ## thanks to the appendleft() function which allows to append to the position 0 in constant time O(1)\n", + " ## a normal python list would instead require O(N) to do this.\n", + " for t in range(n_steps)[::-1]:\n", + " disc_return_t = (returns[0] if len(returns)>0 else 0)\n", + " returns.appendleft( gamma*disc_return_t + rewards[t] ) \n", + " \n", + " ## standardization of the returns is employed to make training more stable\n", + " eps = np.finfo(np.float32).eps.item()\n", + " ## eps is the smallest representable float, which is \n", + " # added to the standard deviation of the returns to avoid numerical instabilities \n", + " returns = torch.tensor(returns)\n", + " returns = (returns - returns.mean()) / (returns.std() + eps)\n", + " \n", + " # Line 7:\n", + " policy_loss = []\n", + " for log_prob, disc_return in zip(saved_log_probs, returns):\n", + " policy_loss.append(-log_prob * disc_return)\n", + " policy_loss = torch.cat(policy_loss).sum()\n", + " \n", + " # Line 8: PyTorch prefers gradient descent \n", + " optimizer.zero_grad()\n", + " policy_loss.backward()\n", + " optimizer.step()\n", + " \n", + " if i_episode % print_every == 0:\n", + " print('Episode {}\\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_deque)))\n", + " \n", + " return scores" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "RIWhQyJjfpEt" + }, + "source": [ + "## Train it\n", + "- We're now ready to train our agent.\n", + "- But first, we define a variable containing all the training hyperparameters.\n", + "- You can change the training parameters (and should ๐Ÿ˜‰)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "utRe1NgtVBYF" + }, + "outputs": [], + "source": [ + "cartpole_hyperparameters = {\n", + " \"h_size\": 16,\n", + " \"n_training_episodes\": 1000,\n", + " \"n_evaluation_episodes\": 10,\n", + " \"max_t\": 1000,\n", + " \"gamma\": 1.0,\n", + " \"lr\": 1e-2,\n", + " \"env_id\": env_id,\n", + " \"state_space\": s_size,\n", + " \"action_space\": a_size,\n", + "}" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "D3lWyVXBVfl6" + }, + "outputs": [], + "source": [ + "# Create policy and place it to the device\n", + "cartpole_policy = Policy(cartpole_hyperparameters[\"state_space\"], cartpole_hyperparameters[\"action_space\"], cartpole_hyperparameters[\"h_size\"]).to(device)\n", + "cartpole_optimizer = optim.Adam(cartpole_policy.parameters(), lr=cartpole_hyperparameters[\"lr\"])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "uGf-hQCnfouB" + }, + "outputs": [], + "source": [ + "scores = reinforce(cartpole_policy,\n", + " cartpole_optimizer,\n", + " cartpole_hyperparameters[\"n_training_episodes\"], \n", + " cartpole_hyperparameters[\"max_t\"],\n", + " cartpole_hyperparameters[\"gamma\"], \n", + " 100)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "Qajj2kXqhB3g" + }, + "source": [ + "## Define evaluation method ๐Ÿ“\n", + "- Here we define the evaluation method that we're going to use to test our Reinforce agent." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "3FamHmxyhBEU" + }, + "outputs": [], + "source": [ + "def evaluate_agent(env, max_steps, n_eval_episodes, policy):\n", + " \"\"\"\n", + " Evaluate the agent for ``n_eval_episodes`` episodes and returns average reward and std of reward.\n", + " :param env: The evaluation environment\n", + " :param n_eval_episodes: Number of episode to evaluate the agent\n", + " :param policy: The Reinforce agent\n", + " \"\"\"\n", + " episode_rewards = []\n", + " for episode in range(n_eval_episodes):\n", + " state = env.reset()\n", + " step = 0\n", + " done = False\n", + " total_rewards_ep = 0\n", + " \n", + " for step in range(max_steps):\n", + " action, _ = policy.act(state)\n", + " new_state, reward, done, info = env.step(action)\n", + " total_rewards_ep += reward\n", + " \n", + " if done:\n", + " break\n", + " state = new_state\n", + " episode_rewards.append(total_rewards_ep)\n", + " mean_reward = np.mean(episode_rewards)\n", + " std_reward = np.std(episode_rewards)\n", + "\n", + " return mean_reward, std_reward" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "xdH2QCrLTrlT" + }, + "source": [ + "## Evaluate our agent ๐Ÿ“ˆ" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "ohGSXDyHh0xx" + }, + "outputs": [], + "source": [ + "evaluate_agent(eval_env, \n", + " cartpole_hyperparameters[\"max_t\"], \n", + " cartpole_hyperparameters[\"n_evaluation_episodes\"],\n", + " cartpole_policy)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "7CoeLkQ7TpO8" + }, + "source": [ + "### Publish our trained model on the Hub ๐Ÿ”ฅ\n", + "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.\n", + "\n", + "Here's an example of a Model Card:\n", + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "Jmhs1k-cftIq" + }, + "source": [ + "### Push to the Hub\n", + "#### Do not modify this code" + ] + }, + { + "cell_type": "code", + "source": [ + "from huggingface_hub import HfApi, snapshot_download\n", + "from huggingface_hub.repocard import metadata_eval_result, metadata_save\n", + "\n", + "from pathlib import Path\n", + "import datetime\n", + "import json\n", + "import imageio\n", + "\n", + "import tempfile\n", + "\n", + "import os" + ], + "metadata": { + "id": "LIVsvlW_8tcw" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "Lo4JH45if81z" + }, + "outputs": [], + "source": [ + "def record_video(env, policy, out_directory, fps=30):\n", + " \"\"\"\n", + " Generate a replay video of the agent\n", + " :param env\n", + " :param Qtable: Qtable of our agent\n", + " :param out_directory\n", + " :param fps: how many frame per seconds (with taxi-v3 and frozenlake-v1 we use 1)\n", + " \"\"\"\n", + " images = [] \n", + " done = False\n", + " state = env.reset()\n", + " img = env.render(mode='rgb_array')\n", + " images.append(img)\n", + " while not done:\n", + " # Take the action (index) that have the maximum expected future reward given that state\n", + " action, _ = policy.act(state)\n", + " state, reward, done, info = env.step(action) # We directly put next_state = state for recording logic\n", + " img = env.render(mode='rgb_array')\n", + " images.append(img)\n", + " imageio.mimsave(out_directory, [np.array(img) for i, img in enumerate(images)], fps=fps)" + ] + }, + { + "cell_type": "code", + "source": [ + "def push_to_hub(repo_id, \n", + " model,\n", + " hyperparameters,\n", + " eval_env,\n", + " video_fps=30\n", + " ):\n", + " \"\"\"\n", + " Evaluate, Generate a video and Upload a model to Hugging Face Hub.\n", + " This method does the complete pipeline:\n", + " - It evaluates the model\n", + " - It generates the model card\n", + " - It generates a replay video of the agent\n", + " - It pushes everything to the Hub\n", + "\n", + " :param repo_id: repo_id: id of the model repository from the Hugging Face Hub\n", + " :param model: the pytorch model we want to save\n", + " :param hyperparameters: training hyperparameters\n", + " :param eval_env: evaluation environment\n", + " :param video_fps: how many frame per seconds to record our video replay \n", + " \"\"\"\n", + "\n", + " _, repo_name = repo_id.split(\"/\")\n", + " api = HfApi()\n", + " \n", + " # Step 1: Create the repo\n", + " repo_url = api.create_repo(\n", + " repo_id=repo_id,\n", + " exist_ok=True,\n", + " )\n", + "\n", + " with tempfile.TemporaryDirectory() as tmpdirname:\n", + " local_directory = Path(tmpdirname)\n", + " \n", + " # Step 2: Save the model\n", + " torch.save(model, local_directory / \"model.pt\")\n", + "\n", + " # Step 3: Save the hyperparameters to JSON\n", + " with open(local_directory / \"hyperparameters.json\", \"w\") as outfile:\n", + " json.dump(hyperparameters, outfile)\n", + " \n", + " # Step 4: Evaluate the model and build JSON\n", + " mean_reward, std_reward = evaluate_agent(eval_env, \n", + " hyperparameters[\"max_t\"],\n", + " hyperparameters[\"n_evaluation_episodes\"], \n", + " model)\n", + " # Get datetime\n", + " eval_datetime = datetime.datetime.now()\n", + " eval_form_datetime = eval_datetime.isoformat()\n", + "\n", + " evaluate_data = {\n", + " \"env_id\": hyperparameters[\"env_id\"], \n", + " \"mean_reward\": mean_reward,\n", + " \"n_evaluation_episodes\": hyperparameters[\"n_evaluation_episodes\"],\n", + " \"eval_datetime\": eval_form_datetime,\n", + " }\n", + "\n", + " # Write a JSON file\n", + " with open(local_directory / \"results.json\", \"w\") as outfile:\n", + " json.dump(evaluate_data, outfile)\n", + "\n", + " # Step 5: Create the model card\n", + " env_name = hyperparameters[\"env_id\"]\n", + " \n", + " metadata = {}\n", + " metadata[\"tags\"] = [\n", + " env_name,\n", + " \"reinforce\",\n", + " \"reinforcement-learning\",\n", + " \"custom-implementation\",\n", + " \"deep-rl-class\"\n", + " ]\n", + "\n", + " # Add metrics\n", + " eval = metadata_eval_result(\n", + " model_pretty_name=repo_name,\n", + " task_pretty_name=\"reinforcement-learning\",\n", + " task_id=\"reinforcement-learning\",\n", + " metrics_pretty_name=\"mean_reward\",\n", + " metrics_id=\"mean_reward\",\n", + " metrics_value=f\"{mean_reward:.2f} +/- {std_reward:.2f}\",\n", + " dataset_pretty_name=env_name,\n", + " dataset_id=env_name,\n", + " )\n", + "\n", + " # Merges both dictionaries\n", + " metadata = {**metadata, **eval}\n", + "\n", + " model_card = f\"\"\"\n", + " # **Reinforce** Agent playing **{env_id}**\n", + " This is a trained model of a **Reinforce** agent playing **{env_id}** .\n", + " To learn to use this model and train yours check Unit 4 of the Deep Reinforcement Learning Course: https://huggingface.co/deep-rl-course/unit4/introduction\n", + " \"\"\"\n", + "\n", + " readme_path = local_directory / \"README.md\"\n", + " readme = \"\"\n", + " if readme_path.exists():\n", + " with readme_path.open(\"r\", encoding=\"utf8\") as f:\n", + " readme = f.read()\n", + " else:\n", + " readme = model_card\n", + "\n", + " with readme_path.open(\"w\", encoding=\"utf-8\") as f:\n", + " f.write(readme)\n", + "\n", + " # Save our metrics to Readme metadata\n", + " metadata_save(readme_path, metadata)\n", + "\n", + " # Step 6: Record a video\n", + " video_path = local_directory / \"replay.mp4\"\n", + " record_video(env, model, video_path, video_fps)\n", + "\n", + " # Step 7. Push everything to the Hub\n", + " api.upload_folder(\n", + " repo_id=repo_id,\n", + " folder_path=local_directory,\n", + " path_in_repo=\".\",\n", + " )\n", + "\n", + " print(f\"Your model is pushed to the Hub. You can view your model here: {repo_url}\")" + ], + "metadata": { + "id": "_TPdq47D7_f_" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "w17w8CxzoURM" + }, + "source": [ + "### .\n", + "\n", + "By using `push_to_hub` **you evaluate, record a replay, generate a model card of your agent and push it to the Hub**.\n", + "\n", + "This way:\n", + "- You can **showcase our work** ๐Ÿ”ฅ\n", + "- You can **visualize your agent playing** ๐Ÿ‘€\n", + "- You can **share with the community an agent that others can use** ๐Ÿ’พ\n", + "- You can **access a leaderboard ๐Ÿ† to see how well your agent is performing compared to your classmates** ๐Ÿ‘‰ https://huggingface.co/spaces/huggingface-projects/Deep-Reinforcement-Learning-Leaderboard\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "cWnFC0iZooTw" + }, + "source": [ + "To be able to share your model with the community there are three more steps to follow:\n", + "\n", + "1๏ธโƒฃ (If it's not already done) create an account to HF โžก https://huggingface.co/join\n", + "\n", + "2๏ธโƒฃ Sign in and then, you need to store your authentication token from the Hugging Face website.\n", + "- Create a new token (https://huggingface.co/settings/tokens) **with write role**\n", + "\n", + "\n", + "\"Create\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "QB5nIcxR8paT" + }, + "outputs": [], + "source": [ + "notebook_login()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "GyWc1x3-o3xG" + }, + "source": [ + "If you don't want to use a Google Colab or a Jupyter Notebook, you need to use this command instead: `huggingface-cli login` (or `login`)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "F-D-zhbRoeOm" + }, + "source": [ + "3๏ธโƒฃ We're now ready to push our trained agent to the ๐Ÿค— Hub ๐Ÿ”ฅ using `package_to_hub()` function" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "UNwkTS65Uq3Q" + }, + "outputs": [], + "source": [ + "repo_id = \"\" #TODO Define your repo id {username/Reinforce-{model-id}}\n", + "push_to_hub(repo_id,\n", + " cartpole_policy, # The model we want to save\n", + " cartpole_hyperparameters, # Hyperparameters\n", + " eval_env, # Evaluation environment\n", + " video_fps=30\n", + " )" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "jrnuKH1gYZSz" + }, + "source": [ + "Now that we try the robustness of our implementation, let's try a more complex environment: PixelCopter ๐Ÿš\n", + "\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "source": [ + "## Second agent: PixelCopter ๐Ÿš\n", + "\n", + "### Study the PixelCopter environment ๐Ÿ‘€\n", + "- [The Environment documentation](https://pygame-learning-environment.readthedocs.io/en/latest/user/games/pixelcopter.html)\n" + ], + "metadata": { + "id": "JNLVmKKVKA6j" + } + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "JBSc8mlfyin3" + }, + "outputs": [], + "source": [ + "env_id = \"Pixelcopter-PLE-v0\"\n", + "env = gym.make(env_id)\n", + "eval_env = gym.make(env_id)\n", + "s_size = env.observation_space.shape[0]\n", + "a_size = env.action_space.n" + ] + }, + { + "cell_type": "code", + "source": [ + "print(\"_____OBSERVATION SPACE_____ \\n\")\n", + "print(\"The State Space is: \", s_size)\n", + "print(\"Sample observation\", env.observation_space.sample()) # Get a random observation" + ], + "metadata": { + "id": "L5u_zAHsKBy7" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "source": [ + "print(\"\\n _____ACTION SPACE_____ \\n\")\n", + "print(\"The Action Space is: \", a_size)\n", + "print(\"Action Space Sample\", env.action_space.sample()) # Take a random action" + ], + "metadata": { + "id": "D7yJM9YXKNbq" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "NNWvlyvzalXr" + }, + "source": [ + "The observation space (7) ๐Ÿ‘€:\n", + "- player y position\n", + "- player velocity\n", + "- player distance to floor\n", + "- player distance to ceiling\n", + "- next block x distance to player\n", + "- next blocks top y location\n", + "- next blocks bottom y location\n", + "\n", + "The action space(2) ๐ŸŽฎ:\n", + "- Up\n", + "- Down\n", + "\n", + "The reward function ๐Ÿ’ฐ: \n", + "- For each vertical block it passes through it gains a positive reward of +1. Each time a terminal state reached it receives a negative reward of -1." + ] + }, + { + "cell_type": "markdown", + "source": [ + "### Define the new Policy ๐Ÿง \n", + "- We need to have a deeper neural network since the environment is more complex" + ], + "metadata": { + "id": "aV1466QP8crz" + } + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "I1eBkCiX2X_S" + }, + "outputs": [], + "source": [ + "class Policy(nn.Module):\n", + " def __init__(self, s_size, a_size, h_size):\n", + " super(Policy, self).__init__()\n", + " # Define the three layers here\n", + "\n", + " def forward(self, x):\n", + " # Define the forward process here\n", + " return F.softmax(x, dim=1)\n", + " \n", + " def act(self, state):\n", + " state = torch.from_numpy(state).float().unsqueeze(0).to(device)\n", + " probs = self.forward(state).cpu()\n", + " m = Categorical(probs)\n", + " action = m.sample()\n", + " return action.item(), m.log_prob(action)" + ] + }, + { + "cell_type": "markdown", + "source": [ + "#### Solution" + ], + "metadata": { + "id": "47iuAFqV8Ws-" + } + }, + { + "cell_type": "code", + "source": [ + "class Policy(nn.Module):\n", + " def __init__(self, s_size, a_size, h_size):\n", + " super(Policy, self).__init__()\n", + " self.fc1 = nn.Linear(s_size, h_size)\n", + " self.fc2 = nn.Linear(h_size, h_size*2)\n", + " self.fc3 = nn.Linear(h_size*2, a_size)\n", + "\n", + " def forward(self, x):\n", + " x = F.relu(self.fc1(x))\n", + " x = F.relu(self.fc2(x))\n", + " x = self.fc3(x)\n", + " return F.softmax(x, dim=1)\n", + " \n", + " def act(self, state):\n", + " state = torch.from_numpy(state).float().unsqueeze(0).to(device)\n", + " probs = self.forward(state).cpu()\n", + " m = Categorical(probs)\n", + " action = m.sample()\n", + " return action.item(), m.log_prob(action)" + ], + "metadata": { + "id": "wrNuVcHC8Xu7" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "SM1QiGCSbBkM" + }, + "source": [ + "### Define the hyperparameters โš™๏ธ\n", + "- Because this environment is more complex.\n", + "- Especially for the hidden size, we need more neurons." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "y0uujOR_ypB6" + }, + "outputs": [], + "source": [ + "pixelcopter_hyperparameters = {\n", + " \"h_size\": 64,\n", + " \"n_training_episodes\": 50000,\n", + " \"n_evaluation_episodes\": 10,\n", + " \"max_t\": 10000,\n", + " \"gamma\": 0.99,\n", + " \"lr\": 1e-4,\n", + " \"env_id\": env_id,\n", + " \"state_space\": s_size,\n", + " \"action_space\": a_size,\n", + "}" + ] + }, + { + "cell_type": "markdown", + "source": [ + "### Train it\n", + "- We're now ready to train our agent ๐Ÿ”ฅ." + ], + "metadata": { + "id": "wyvXTJWm9GJG" + } + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "7mM2P_ckysFE" + }, + "outputs": [], + "source": [ + "# Create policy and place it to the device\n", + "# torch.manual_seed(50)\n", + "pixelcopter_policy = Policy(pixelcopter_hyperparameters[\"state_space\"], pixelcopter_hyperparameters[\"action_space\"], pixelcopter_hyperparameters[\"h_size\"]).to(device)\n", + "pixelcopter_optimizer = optim.Adam(pixelcopter_policy.parameters(), lr=pixelcopter_hyperparameters[\"lr\"])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "v1HEqP-fy-Rf" + }, + "outputs": [], + "source": [ + "scores = reinforce(pixelcopter_policy,\n", + " pixelcopter_optimizer,\n", + " pixelcopter_hyperparameters[\"n_training_episodes\"], \n", + " pixelcopter_hyperparameters[\"max_t\"],\n", + " pixelcopter_hyperparameters[\"gamma\"], \n", + " 1000)" + ] + }, + { + "cell_type": "markdown", + "source": [ + "### Publish our trained model on the Hub ๐Ÿ”ฅ" + ], + "metadata": { + "id": "8kwFQ-Ip85BE" + } + }, + { + "cell_type": "code", + "source": [ + "repo_id = \"\" #TODO Define your repo id {username/Reinforce-{model-id}}\n", + "push_to_hub(repo_id,\n", + " pixelcopter_policy, # The model we want to save\n", + " pixelcopter_hyperparameters, # Hyperparameters\n", + " eval_env, # Evaluation environment\n", + " video_fps=30\n", + " )" + ], + "metadata": { + "id": "6PtB7LRbTKWK" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "7VDcJ29FcOyb" + }, + "source": [ + "## Some additional challenges ๐Ÿ†\n", + "The best way to learn **is to try things on your own**! As you saw, the current agent is not doing great. As a first suggestion, you can train for more steps. But also trying to find better parameters.\n", + "\n", + "In the [Leaderboard](https://huggingface.co/spaces/huggingface-projects/Deep-Reinforcement-Learning-Leaderboard) you will find your agents. Can you get to the top?\n", + "\n", + "Here are some ideas to achieve so:\n", + "* Train more steps\n", + "* Try different hyperparameters by looking at what your classmates have done ๐Ÿ‘‰ https://huggingface.co/models?other=reinforce\n", + "* **Push your new trained model** on the Hub ๐Ÿ”ฅ\n", + "* **Improving the implementation for more complex environments** (for instance, what about changing the network to a Convolutional Neural Network to handle\n", + "frames as observation)?" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "x62pP0PHdA-y" + }, + "source": [ + "________________________________________________________________________\n", + "\n", + "**Congrats on finishing this unit**!ย There was a lot of information.\n", + "And congrats on finishing the tutorial. You've just coded your first Deep Reinforcement Learning agent from scratch using PyTorch and shared it on the Hub ๐Ÿฅณ.\n", + "\n", + "Don't hesitate to iterate on this unit **by improving the implementation for more complex environments** (for instance, what about changing the network to a Convolutional Neural Network to handle\n", + "frames as observation)?\n", + "\n", + "In the next unit, **we're going to learn more about Unity MLAgents**, by training agents in Unity environments. This way, you will be ready to participate in the **AI vs AI challenges where you'll train your agents\n", + "to compete against other agents in a snowball fight and a soccer game.**\n", + "\n", + "Sounds fun? See you next time!\n", + "\n", + "Finally, we would love **to hear what you think of the course and how we can improve it**. If you have some feedback then, please ๐Ÿ‘‰ [fill this form](https://forms.gle/BzKXWzLAGZESGNaE9)\n", + "\n", + "See you in Unit 5! ๐Ÿ”ฅ\n", + "\n", + "### Keep Learning, stay awesome ๐Ÿค—\n", + "\n" + ] + } + ], + "metadata": { + "accelerator": "GPU", + "colab": { + "private_outputs": true, + "provenance": [], + "collapsed_sections": [ + "BPLwsPajb1f8", + "L_WSo0VUV99t", + "mjY-eq3eWh9O", + "JoTC9o2SczNn", + "gfGJNZBUP7Vn", + "YB0Cxrw1StrP", + "47iuAFqV8Ws-", + "x62pP0PHdA-y" + ], + "include_colab_link": true + }, + "gpuClass": "standard", + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.10" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/units/en/_toctree.yml b/units/en/_toctree.yml index 21d4d59..70c2213 100644 --- a/units/en/_toctree.yml +++ b/units/en/_toctree.yml @@ -110,8 +110,27 @@ title: Optuna - local: unitbonus2/hands-on title: Hands-on +- title: Unit 4. Policy Gradient with PyTorch + sections: + - local: unit4/introduction + title: Introduction + - local: unit4/what-are-policy-based-methods + title: What are the policy-based methods? + - local: unit4/advantages-disadvantages + title: The advantages and disadvantages of policy-gradient methods + - local: unit4/policy-gradient + title: Diving deeper into policy-gradient + - local: unit4/pg-theorem + title: (Optional) the Policy Gradient Theorem + - local: unit4/hands-on + title: Hands-on + - local: unit4/quiz + title: Quiz + - local: unit4/conclusion + title: Conclusion + - local: unit4/additional-readings + title: Additional Readings - title: What's next? New Units Publishing Schedule sections: - local: communication/publishing-schedule title: Publishing Schedule - diff --git a/units/en/unit4/additional-readings.mdx b/units/en/unit4/additional-readings.mdx new file mode 100644 index 0000000..6d246ae --- /dev/null +++ b/units/en/unit4/additional-readings.mdx @@ -0,0 +1,20 @@ +# Additional Readings + +These are **optional readings** if you want to go deeper. + + +## Introduction to Policy Optimization + +- [Part 3: Intro to Policy Optimization - Spinning Up documentation](https://spinningup.openai.com/en/latest/spinningup/rl_intro3.html) + + +## Policy Gradient + +- [https://johnwlambert.github.io/policy-gradients/](https://johnwlambert.github.io/policy-gradients/) +- [RL - Policy Gradient Explained](https://jonathan-hui.medium.com/rl-policy-gradients-explained-9b13b688b146) +- [Chapter 13, Policy Gradient Methods; Reinforcement Learning, an introduction by Richard Sutton and Andrew G. Barto](http://incompleteideas.net/book/RLbook2020.pdf) + +## Implementation + +- [PyTorch Reinforce implementation](https://github.com/pytorch/examples/blob/main/reinforcement_learning/reinforce.py) +- [Implementations from DDPG to PPO](https://github.com/MrSyee/pg-is-all-you-need) diff --git a/units/en/unit4/advantages-disadvantages.mdx b/units/en/unit4/advantages-disadvantages.mdx new file mode 100644 index 0000000..3b483a9 --- /dev/null +++ b/units/en/unit4/advantages-disadvantages.mdx @@ -0,0 +1,74 @@ +# The advantages and disadvantages of policy-gradient methods + +At this point, you might ask, "but Deep Q-Learning is excellent! Why use policy-gradient methods?". To answer this question, let's study the **advantages and disadvantages of policy-gradient methods**. + +## Advantages + +There are multiple advantages over value-based methods. Let's see some of them: + +### The simplicity of integration + +We can estimate the policy directly without storing additional data (action values). + +### Policy-gradient methods can learn a stochastic policy + +Policy-gradient methods canย **learn a stochastic policy while value functions can't**. + +This has two consequences: + +1. We **don't need to implement an exploration/exploitation trade-off by hand**. Since we output a probability distribution over actions, the agent exploresย **the state space without always taking the same trajectory.** + +2. We also get rid of the problem of **perceptual aliasing**. Perceptual aliasing is when two states seem (or are) the same but need different actions. + +Let's take an example: we have an intelligent vacuum cleaner whose goal is to suck the dust and avoid killing the hamsters. + +
+ Hamster 1 +
+ +Our vacuum cleaner can only perceive where the walls are. + +The problem is that the **two rose cases are aliased states because the agent perceives an upper and lower wall for each**. + +
+ Hamster 1 +
+ +Under a deterministic policy, the policy either will move right when in a red state or move left. **Either case will cause our agent to get stuck and never suck the dust**. + +Under a value-based Reinforcement learning algorithm, we learn a **quasi-deterministic policy** ("greedy epsilon strategy"). Consequently, our agent can **spend a lot of time before finding the dust**. + +On the other hand, an optimal stochastic policy **will randomly move left or right in rose states**. Consequently, **it will not be stuck and will reach the goal state with a high probability**. + +
+ Hamster 1 +
+ +### Policy-gradient methods are more effective in high-dimensional action spaces and continuous actions spaces + +The problem with Deep Q-learning is that their **predictions assign a score (maximum expected future reward) for each possible action**, at each time step, given the current state. + +But what if we have an infinite possibility of actions? + +For instance, with a self-driving car, at each state, you can have a (near) infinite choice of actions (turning the wheel at 15ยฐ, 17.2ยฐ, 19,4ยฐ, honking, etc.). **We'll need to output a Q-value for each possible action**! And **taking the max action of a continuous output is an optimization problem itself**! + +Instead, with policy-gradient methods, we output aย **probability distribution over actions.** + +### Policy-gradient methods have better convergence properties + +In value-based methods, we use an aggressive operator to **change the value function: we take the maximum over Q-estimates**. +Consequently, the action probabilities may change dramatically for an arbitrarily small change in the estimated action values if that change results in a different action having the maximal value. + +For instance, if during the training, the best action was left (with a Q-value of 0.22) and the training step after it's right (since the right Q-value becomes 0.23), we dramatically changed the policy since now the policy will take most of the time right instead of left. + +On the other hand, in policy-gradient methods, stochastic policy action preferences (probability of taking action) **change smoothly over time**. + +## Disadvantages + +Naturally, policy-gradient methods also have some disadvantages: + +- **Frequently, policy-gradient converges on a local maximum instead of a global optimum.** +- Policy-gradient goes slower,ย **step by step: it can take longer to train (inefficient).** +- Policy-gradient can have high variance. We'll see in actor-critic unit why and how we can solve this problem. + +๐Ÿ‘‰ If you want to go deeper into the advantages and disadvantages of policy-gradient methods, [you can check this video](https://youtu.be/y3oqOjHilio). diff --git a/units/en/unit4/conclusion.mdx b/units/en/unit4/conclusion.mdx new file mode 100644 index 0000000..a49ed5d --- /dev/null +++ b/units/en/unit4/conclusion.mdx @@ -0,0 +1,17 @@ +# Conclusion + + +**Congrats on finishing this unit**!ย There was a lot of information. +And congrats on finishing the tutorial. You've just coded your first Deep Reinforcement Learning agent from scratch using PyTorch and shared it on the Hub ๐Ÿฅณ. + +Don't hesitate to iterate on this unit **by improving the implementation for more complex environments** (for instance, what about changing the network to a Convolutional Neural Network to handle +frames as observation)? + +In the next unit, **we're going to learn more about Unity MLAgents**, by training agents in Unity environments. This way, you will be ready to participate in the **AI vs AI challenges where you'll train your agents +to compete against other agents in a snowball fight and a soccer game.** + +Sounds fun? See you next time! + +Finally, we would love **to hear what you think of the course and how we can improve it**. If you have some feedback then, please ๐Ÿ‘‰ [fill this form](https://forms.gle/BzKXWzLAGZESGNaE9) + +### Keep Learning, stay awesome ๐Ÿค— diff --git a/units/en/unit4/hands-on.mdx b/units/en/unit4/hands-on.mdx new file mode 100644 index 0000000..b0c8956 --- /dev/null +++ b/units/en/unit4/hands-on.mdx @@ -0,0 +1,1012 @@ +# Hands on + + + + + + + +Now that we studied the theory behind Reinforce, **youโ€™re ready to code your Reinforce agent with PyTorch**. And you'll test its robustness using CartPole-v1 and PixelCopter,. + +You'll then be able to iterate and improve this implementation for more advanced environments. + +
+ Environments +
+ + +To validate this hands-on for the certification process, you need to push your trained models to the Hub. + +- Get a result of >= 350 for `Cartpole-v1`. +- Get a result of >= 5 for `PixelCopter`. + +To find your result, go to the leaderboard and find your model, **the result = mean_reward - std of reward**. **If you don't see your model on the leaderboard, go at the bottom of the leaderboard page and click on the refresh button**. + +For more information about the certification process, check this section ๐Ÿ‘‰ https://huggingface.co/deep-rl-course/en/unit0/introduction#certification-process + +**To start the hands-on click on Open In Colab button** ๐Ÿ‘‡ : + +[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/deep-rl-class/blob/master/notebooks/unit4/unit4.ipynb) + + +# Unit 4: Code your first Deep Reinforcement Learning Algorithm with PyTorch: Reinforce. And test its robustness ๐Ÿ’ช + +thumbnail + + +In this notebook, you'll code your first Deep Reinforcement Learning algorithm from scratch: Reinforce (also called Monte Carlo Policy Gradient). + +Reinforce is a *Policy-based method*: a Deep Reinforcement Learning algorithm that tries **to optimize the policy directly without using an action-value function**. + +More precisely, Reinforce is a *Policy-gradient method*, a subclass of *Policy-based methods* that aims **to optimize the policy directly by estimating the weights of the optimal policy using gradient ascent**. + +To test its robustness, we're going to train it in 2 different simple environments: +- Cartpole-v1 +- PixelcopterEnv + +โฌ‡๏ธ Here is an example of what **you will achieve at the end of this notebook.** โฌ‡๏ธ + + Environments + + +### ๐ŸŽฎ Environments: + +- [CartPole-v1](https://www.gymlibrary.dev/environments/classic_control/cart_pole/) +- [PixelCopter](https://pygame-learning-environment.readthedocs.io/en/latest/user/games/pixelcopter.html) + +### ๐Ÿ“š RL-Library: + +- Python +- PyTorch + + +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](https://github.com/huggingface/deep-rl-class/issues). + +## Objectives of this notebook ๐Ÿ† + +At the end of the notebook, you will: + +- Be able to **code from scratch a Reinforce algorithm using PyTorch.** +- Be able to **test the robustness of your agent using simple environments.** +- Be able to **push your trained agent to the Hub** with a nice video replay and an evaluation score ๐Ÿ”ฅ. + +## Prerequisites ๐Ÿ—๏ธ + +Before diving into the notebook, you need to: + +๐Ÿ”ฒ ๐Ÿ“š [Study Policy Gradients by reading Unit 4](https://huggingface.co/deep-rl-course/unit4/introduction) + +# Let's code Reinforce algorithm from scratch ๐Ÿ”ฅ + +## An advice ๐Ÿ’ก + +It's better to run this colab in a copy on your Google Drive, so that **if it timeouts** you still have the saved notebook on your Google Drive and do not need to fill everything from scratch. + +To do that you can either do `Ctrl + S` or `File > Save a copy in Google Drive.` + +## 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 + +- `Hardware Accelerator > GPU` + +GPU Step 2 + +## Create a virtual display ๐Ÿ–ฅ + +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 the librairies and create and run a virtual screen ๐Ÿ–ฅ + +```python +%%capture +!apt install python-opengl +!apt install ffmpeg +!apt install xvfb +!pip install pyvirtualdisplay +!pip install pyglet==1.5.1 +``` + +```python +# Virtual display +from pyvirtualdisplay import Display + +virtual_display = Display(visible=0, size=(1400, 900)) +virtual_display.start() +``` + +## Install the dependencies ๐Ÿ”ฝ + +The first step is to install the dependencies. Weโ€™ll install multiple ones: + +- `gym` +- `gym-games`: Extra gym environments made with PyGame. +- `huggingface_hub`: The 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 Reinforce models available ๐Ÿ‘‰ https://huggingface.co/models?other=reinforce + +And you can find all the Deep Reinforcement Learning models here ๐Ÿ‘‰ https://huggingface.co/models?pipeline_tag=reinforcement-learning + + +```bash +!pip install -r https://raw.githubusercontent.com/huggingface/deep-rl-class/main/notebooks/unit4/requirements-unit4.txt +``` + +## Import the packages ๐Ÿ“ฆ + +In addition to import the installed libraries, we also import: + +- `imageio`: A library that will help us to generate a replay video + + + +```python +import numpy as np + +from collections import deque + +import matplotlib.pyplot as plt +%matplotlib inline + +# PyTorch +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.optim as optim +from torch.distributions import Categorical + +# Gym +import gym +import gym_pygame + +# Hugging Face Hub +from huggingface_hub import notebook_login # To log to our Hugging Face account to be able to upload models to the Hub. +import imageio +``` + +## Check if we have a GPU + +- Let's check if we have a GPU +- If it's the case you should see `device:cuda0` + +```python +device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") +``` + +```python +print(device) +``` + +We're now ready to implement our Reinforce algorithm ๐Ÿ”ฅ + +# First agent: Playing CartPole-v1 ๐Ÿค– + +## Create the CartPole environment and understand how it works + +### [The environment ๐ŸŽฎ](https://www.gymlibrary.dev/environments/classic_control/cart_pole/) + +### Why do we use a simple environment like CartPole-v1? + +As explained in [Reinforcement Learning Tips and Tricks](https://stable-baselines3.readthedocs.io/en/master/guide/rl_tips.html), when you implement your agent from scratch, you need **to be sure that it works correctly and find bugs with easy environments before going deeper** as finding bugs will be much easier in simple environments. + + +> Try to have some โ€œsign of lifeโ€ on toy problems + + +> Validate the implementation by making it run on harder and harder envs (you can compare results against the RL zoo). You usually need to run hyperparameter optimization for that step. + + +### The CartPole-v1 environment + +> A pole is attached by an un-actuated joint to a cart, which moves along a frictionless track. The pendulum is placed upright on the cart and the goal is to balance the pole by applying forces in the left and right direction on the cart. + + + +So, we start with CartPole-v1. The goal is to push the cart left or right **so that the pole stays in the equilibrium.** + +The episode ends if: +- The pole Angle is greater than ยฑ12ยฐ +- Cart Position is greater than ยฑ2.4 +- Episode length is greater than 500 + +We get a reward ๐Ÿ’ฐ of +1 every timestep the Pole stays in the equilibrium. + +```python +env_id = "CartPole-v1" +# Create the env +env = gym.make(env_id) + +# Create the evaluation env +eval_env = gym.make(env_id) + +# Get the state space and action space +s_size = env.observation_space.shape[0] +a_size = env.action_space.n +``` + +```python +print("_____OBSERVATION SPACE_____ \n") +print("The State Space is: ", s_size) +print("Sample observation", env.observation_space.sample()) # Get a random observation +``` + +```python +print("\n _____ACTION SPACE_____ \n") +print("The Action Space is: ", a_size) +print("Action Space Sample", env.action_space.sample()) # Take a random action +``` + +## Let's build the Reinforce Architecture + +This implementation is based on three implementations: +- [PyTorch official Reinforcement Learning example](https://github.com/pytorch/examples/blob/main/reinforcement_learning/reinforce.py) +- [Udacity Reinforce](https://github.com/udacity/deep-reinforcement-learning/blob/master/reinforce/REINFORCE.ipynb) +- [Improvement of the integration by Chris1nexus](https://github.com/huggingface/deep-rl-class/pull/95) + +Reinforce + +So we want: +- Two fully connected layers (fc1 and fc2). +- Using ReLU as activation function of fc1 +- Using Softmax to output a probability distribution over actions + +```python +class Policy(nn.Module): + def __init__(self, s_size, a_size, h_size): + super(Policy, self).__init__() + # Create two fully connected layers + + + + def forward(self, x): + # Define the forward pass + # state goes to fc1 then we apply ReLU activation function + + # fc1 outputs goes to fc2 + + # We output the softmax + + def act(self, state): + """ + Given a state, take action + """ + state = torch.from_numpy(state).float().unsqueeze(0).to(device) + probs = self.forward(state).cpu() + m = Categorical(probs) + action = np.argmax(m) + return action.item(), m.log_prob(action) +``` + +### Solution + +```python +class Policy(nn.Module): + def __init__(self, s_size, a_size, h_size): + super(Policy, self).__init__() + self.fc1 = nn.Linear(s_size, h_size) + self.fc2 = nn.Linear(h_size, a_size) + + def forward(self, x): + x = F.relu(self.fc1(x)) + x = self.fc2(x) + return F.softmax(x, dim=1) + + def act(self, state): + state = torch.from_numpy(state).float().unsqueeze(0).to(device) + probs = self.forward(state).cpu() + m = Categorical(probs) + action = np.argmax(m) + return action.item(), m.log_prob(action) +``` + +I make a mistake, can you guess where? + +- To find out let's make a forward pass: + +```python +debug_policy = Policy(s_size, a_size, 64).to(device) +debug_policy.act(env.reset()) +``` + +- Here we see that the error says `ValueError: The value argument to log_prob must be a Tensor` + +- It means that `action` in `m.log_prob(action)` must be a Tensor **but it's not.** + +- Do you know why? Check the act function and try to see why it does not work. + +Advice ๐Ÿ’ก: Something is wrong in this implementation. Remember that we act function **we want to sample an action from the probability distribution over actions**. + + +### (Real) Solution + +```python +class Policy(nn.Module): + def __init__(self, s_size, a_size, h_size): + super(Policy, self).__init__() + self.fc1 = nn.Linear(s_size, h_size) + self.fc2 = nn.Linear(h_size, a_size) + + def forward(self, x): + x = F.relu(self.fc1(x)) + x = self.fc2(x) + return F.softmax(x, dim=1) + + def act(self, state): + state = torch.from_numpy(state).float().unsqueeze(0).to(device) + probs = self.forward(state).cpu() + m = Categorical(probs) + action = m.sample() + return action.item(), m.log_prob(action) +``` + +By using CartPole, it was easier to debug since **we know that the bug comes from our integration and not from our simple environment**. + +- Since **we want to sample an action from the probability distribution over actions**, we can't use `action = np.argmax(m)` since it will always output the action that have the highest probability. + +- We need to replace with `action = m.sample()` that will sample an action from the probability distribution P(.|s) + +### Let's build the Reinforce Training Algorithm +This is the Reinforce algorithm pseudocode: + +Policy gradient pseudocode + + +- When we calculate the return Gt (line 6), we see that we calculate the sum of discounted rewards **starting at timestep t**. + +- Why? Because our policy should only **reinforce actions on the basis of the consequences**: so rewards obtained before taking an action are useless (since they were not because of the action), **only the ones that come after the action matters**. + +- Before coding this you should read this section [don't let the past distract you](https://spinningup.openai.com/en/latest/spinningup/rl_intro3.html#don-t-let-the-past-distract-you) that explains why we use reward-to-go policy gradient. + +We use an interesting technique coded by [Chris1nexus](https://github.com/Chris1nexus) to **compute the return at each timestep efficiently**. The comments explained the procedure. Don't hesitate also [to check the PR explanation](https://github.com/huggingface/deep-rl-class/pull/95) +But overall the idea is to **compute the return at each timestep efficiently**. + +The second question you may ask is **why do we minimize the loss**? Did you talk about Gradient Ascent, not Gradient Descent? + +- We want to maximize our utility function $J(\theta)$, but in PyTorch and TensorFlow, it's better to **minimize an objective function.** + - So let's say we want to reinforce action 3 at a certain timestep. Before training this action P is 0.25. + - So we want to modify $\theta$ such that $\pi_\theta(a_3|s; \theta) > 0.25$ + - Because all P must sum to 1, max $\pi_\theta(a_3|s; \theta)$ will **minimize other action probability.** + - So we should tell PyTorch **to min $1 - \pi_\theta(a_3|s; \theta)$.** + - This loss function approaches 0 as $\pi_\theta(a_3|s; \theta)$ nears 1. + - So we are encouraging the gradient to max $\pi_\theta(a_3|s; \theta)$ + + +```python +def reinforce(policy, optimizer, n_training_episodes, max_t, gamma, print_every): + # Help us to calculate the score during the training + scores_deque = deque(maxlen=100) + scores = [] + # Line 3 of pseudocode + for i_episode in range(1, n_training_episodes+1): + saved_log_probs = [] + rewards = [] + state = # TODO: reset the environment + # Line 4 of pseudocode + for t in range(max_t): + action, log_prob = # TODO get the action + saved_log_probs.append(log_prob) + state, reward, done, _ = # TODO: take an env step + rewards.append(reward) + if done: + break + scores_deque.append(sum(rewards)) + scores.append(sum(rewards)) + + # Line 6 of pseudocode: calculate the return + returns = deque(maxlen=max_t) + n_steps = len(rewards) + # Compute the discounted returns at each timestep, + # as the sum of the gamma-discounted return at time t (G_t) + the reward at time t + + # In O(N) time, where N is the number of time steps + # (this definition of the discounted return G_t follows the definition of this quantity + # shown at page 44 of Sutton&Barto 2017 2nd draft) + # G_t = r_(t+1) + r_(t+2) + ... + + # Given this formulation, the returns at each timestep t can be computed + # by re-using the computed future returns G_(t+1) to compute the current return G_t + # G_t = r_(t+1) + gamma*G_(t+1) + # G_(t-1) = r_t + gamma* G_t + # (this follows a dynamic programming approach, with which we memorize solutions in order + # to avoid computing them multiple times) + + # This is correct since the above is equivalent to (see also page 46 of Sutton&Barto 2017 2nd draft) + # G_(t-1) = r_t + gamma*r_(t+1) + gamma*gamma*r_(t+2) + ... + + + ## Given the above, we calculate the returns at timestep t as: + # gamma[t] * return[t] + reward[t] + # + ## We compute this starting from the last timestep to the first, in order + ## to employ the formula presented above and avoid redundant computations that would be needed + ## if we were to do it from first to last. + + ## Hence, the queue "returns" will hold the returns in chronological order, from t=0 to t=n_steps + ## thanks to the appendleft() function which allows to append to the position 0 in constant time O(1) + ## a normal python list would instead require O(N) to do this. + for t in range(n_steps)[::-1]: + disc_return_t = (returns[0] if len(returns)>0 else 0) + returns.appendleft( ) # TODO: complete here + + ## standardization of the returns is employed to make training more stable + eps = np.finfo(np.float32).eps.item() + + ## eps is the smallest representable float, which is + # added to the standard deviation of the returns to avoid numerical instabilities + returns = torch.tensor(returns) + returns = (returns - returns.mean()) / (returns.std() + eps) + + # Line 7: + policy_loss = [] + for log_prob, disc_return in zip(saved_log_probs, returns): + policy_loss.append(-log_prob * disc_return) + policy_loss = torch.cat(policy_loss).sum() + + # Line 8: PyTorch prefers gradient descent + optimizer.zero_grad() + policy_loss.backward() + optimizer.step() + + if i_episode % print_every == 0: + print('Episode {}\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_deque))) + + return scores +``` + +#### Solution + +```python +def reinforce(policy, optimizer, n_training_episodes, max_t, gamma, print_every): + # Help us to calculate the score during the training + scores_deque = deque(maxlen=100) + scores = [] + # Line 3 of pseudocode + for i_episode in range(1, n_training_episodes + 1): + saved_log_probs = [] + rewards = [] + state = env.reset() + # Line 4 of pseudocode + for t in range(max_t): + action, log_prob = policy.act(state) + saved_log_probs.append(log_prob) + state, reward, done, _ = env.step(action) + rewards.append(reward) + if done: + break + scores_deque.append(sum(rewards)) + scores.append(sum(rewards)) + + # Line 6 of pseudocode: calculate the return + returns = deque(maxlen=max_t) + n_steps = len(rewards) + # Compute the discounted returns at each timestep, + # as + # the sum of the gamma-discounted return at time t (G_t) + the reward at time t + # + # In O(N) time, where N is the number of time steps + # (this definition of the discounted return G_t follows the definition of this quantity + # shown at page 44 of Sutton&Barto 2017 2nd draft) + # G_t = r_(t+1) + r_(t+2) + ... + + # Given this formulation, the returns at each timestep t can be computed + # by re-using the computed future returns G_(t+1) to compute the current return G_t + # G_t = r_(t+1) + gamma*G_(t+1) + # G_(t-1) = r_t + gamma* G_t + # (this follows a dynamic programming approach, with which we memorize solutions in order + # to avoid computing them multiple times) + + # This is correct since the above is equivalent to (see also page 46 of Sutton&Barto 2017 2nd draft) + # G_(t-1) = r_t + gamma*r_(t+1) + gamma*gamma*r_(t+2) + ... + + ## Given the above, we calculate the returns at timestep t as: + # gamma[t] * return[t] + reward[t] + # + ## We compute this starting from the last timestep to the first, in order + ## to employ the formula presented above and avoid redundant computations that would be needed + ## if we were to do it from first to last. + + ## Hence, the queue "returns" will hold the returns in chronological order, from t=0 to t=n_steps + ## thanks to the appendleft() function which allows to append to the position 0 in constant time O(1) + ## a normal python list would instead require O(N) to do this. + for t in range(n_steps)[::-1]: + disc_return_t = returns[0] if len(returns) > 0 else 0 + returns.appendleft(gamma * disc_return_t + rewards[t]) + + ## standardization of the returns is employed to make training more stable + eps = np.finfo(np.float32).eps.item() + ## eps is the smallest representable float, which is + # added to the standard deviation of the returns to avoid numerical instabilities + returns = torch.tensor(returns) + returns = (returns - returns.mean()) / (returns.std() + eps) + + # Line 7: + policy_loss = [] + for log_prob, disc_return in zip(saved_log_probs, returns): + policy_loss.append(-log_prob * disc_return) + policy_loss = torch.cat(policy_loss).sum() + + # Line 8: PyTorch prefers gradient descent + optimizer.zero_grad() + policy_loss.backward() + optimizer.step() + + if i_episode % print_every == 0: + print("Episode {}\tAverage Score: {:.2f}".format(i_episode, np.mean(scores_deque))) + + return scores +``` + +## Train it +- We're now ready to train our agent. +- But first, we define a variable containing all the training hyperparameters. +- You can change the training parameters (and should ๐Ÿ˜‰) + +```python +cartpole_hyperparameters = { + "h_size": 16, + "n_training_episodes": 1000, + "n_evaluation_episodes": 10, + "max_t": 1000, + "gamma": 1.0, + "lr": 1e-2, + "env_id": env_id, + "state_space": s_size, + "action_space": a_size, +} +``` + +```python +# Create policy and place it to the device +cartpole_policy = Policy( + cartpole_hyperparameters["state_space"], + cartpole_hyperparameters["action_space"], + cartpole_hyperparameters["h_size"], +).to(device) +cartpole_optimizer = optim.Adam(cartpole_policy.parameters(), lr=cartpole_hyperparameters["lr"]) +``` + +```python +scores = reinforce( + cartpole_policy, + cartpole_optimizer, + cartpole_hyperparameters["n_training_episodes"], + cartpole_hyperparameters["max_t"], + cartpole_hyperparameters["gamma"], + 100, +) +``` + +## Define evaluation method ๐Ÿ“ +- Here we define the evaluation method that we're going to use to test our Reinforce agent. + +```python +def evaluate_agent(env, max_steps, n_eval_episodes, policy): + """ + Evaluate the agent for ``n_eval_episodes`` episodes and returns average reward and std of reward. + :param env: The evaluation environment + :param n_eval_episodes: Number of episode to evaluate the agent + :param policy: The Reinforce agent + """ + episode_rewards = [] + for episode in range(n_eval_episodes): + state = env.reset() + step = 0 + done = False + total_rewards_ep = 0 + + for step in range(max_steps): + action, _ = policy.act(state) + new_state, reward, done, info = env.step(action) + total_rewards_ep += reward + + if done: + break + state = new_state + episode_rewards.append(total_rewards_ep) + mean_reward = np.mean(episode_rewards) + std_reward = np.std(episode_rewards) + + return mean_reward, std_reward +``` + +## Evaluate our agent ๐Ÿ“ˆ + +```python +evaluate_agent( + eval_env, cartpole_hyperparameters["max_t"], cartpole_hyperparameters["n_evaluation_episodes"], cartpole_policy +) +``` + +### 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. + +Here's an example of a Model Card: + + + +### Push to the Hub +#### Do not modify this code + +```python +from huggingface_hub import HfApi, snapshot_download +from huggingface_hub.repocard import metadata_eval_result, metadata_save + +from pathlib import Path +import datetime +import json +import imageio + +import tempfile + +import os +``` + +```python +def record_video(env, policy, out_directory, fps=30): + """ + Generate a replay video of the agent + :param env + :param Qtable: Qtable of our agent + :param out_directory + :param fps: how many frame per seconds (with taxi-v3 and frozenlake-v1 we use 1) + """ + images = [] + done = False + state = env.reset() + img = env.render(mode="rgb_array") + images.append(img) + while not done: + # Take the action (index) that have the maximum expected future reward given that state + action, _ = policy.act(state) + state, reward, done, info = env.step(action) # We directly put next_state = state for recording logic + img = env.render(mode="rgb_array") + images.append(img) + imageio.mimsave(out_directory, [np.array(img) for i, img in enumerate(images)], fps=fps) +``` + +```python +def push_to_hub(repo_id, + model, + hyperparameters, + eval_env, + video_fps=30 + ): + """ + Evaluate, Generate a video and Upload a model to Hugging Face Hub. + This method does the complete pipeline: + - It evaluates the model + - It generates the model card + - It generates a replay video of the agent + - It pushes everything to the Hub + + :param repo_id: repo_id: id of the model repository from the Hugging Face Hub + :param model: the pytorch model we want to save + :param hyperparameters: training hyperparameters + :param eval_env: evaluation environment + :param video_fps: how many frame per seconds to record our video replay + """ + + _, repo_name = repo_id.split("/") + api = HfApi() + + # Step 1: Create the repo + repo_url = api.create_repo( + repo_id=repo_id, + exist_ok=True, + ) + + with tempfile.TemporaryDirectory() as tmpdirname: + local_directory = Path(tmpdirname) + + # Step 2: Save the model + torch.save(model, local_directory / "model.pt") + + # Step 3: Save the hyperparameters to JSON + with open(local_directory / "hyperparameters.json", "w") as outfile: + json.dump(hyperparameters, outfile) + + # Step 4: Evaluate the model and build JSON + mean_reward, std_reward = evaluate_agent(eval_env, + hyperparameters["max_t"], + hyperparameters["n_evaluation_episodes"], + model) + # Get datetime + eval_datetime = datetime.datetime.now() + eval_form_datetime = eval_datetime.isoformat() + + evaluate_data = { + "env_id": hyperparameters["env_id"], + "mean_reward": mean_reward, + "n_evaluation_episodes": hyperparameters["n_evaluation_episodes"], + "eval_datetime": eval_form_datetime, + } + + # Write a JSON file + with open(local_directory / "results.json", "w") as outfile: + json.dump(evaluate_data, outfile) + + # Step 5: Create the model card + env_name = hyperparameters["env_id"] + + metadata = {} + metadata["tags"] = [ + env_name, + "reinforce", + "reinforcement-learning", + "custom-implementation", + "deep-rl-class" + ] + + # Add metrics + eval = metadata_eval_result( + model_pretty_name=repo_name, + task_pretty_name="reinforcement-learning", + task_id="reinforcement-learning", + metrics_pretty_name="mean_reward", + metrics_id="mean_reward", + metrics_value=f"{mean_reward:.2f} +/- {std_reward:.2f}", + dataset_pretty_name=env_name, + dataset_id=env_name, + ) + + # Merges both dictionaries + metadata = {**metadata, **eval} + + model_card = f""" + # **Reinforce** Agent playing **{env_id}** + This is a trained model of a **Reinforce** agent playing **{env_id}** . + To learn to use this model and train yours check Unit 4 of the Deep Reinforcement Learning Course: https://huggingface.co/deep-rl-course/unit4/introduction + """ + + readme_path = local_directory / "README.md" + readme = "" + if readme_path.exists(): + with readme_path.open("r", encoding="utf8") as f: + readme = f.read() + else: + readme = model_card + + with readme_path.open("w", encoding="utf-8") as f: + f.write(readme) + + # Save our metrics to Readme metadata + metadata_save(readme_path, metadata) + + # Step 6: Record a video + video_path = local_directory / "replay.mp4" + record_video(env, model, video_path, video_fps) + + # Step 7. Push everything to the Hub + api.upload_folder( + repo_id=repo_id, + folder_path=local_directory, + path_in_repo=".", + ) + + print(f"Your model is pushed to the Hub. You can view your model here: {repo_url}") +``` + +By using `push_to_hub` **you evaluate, record a replay, generate a model card of your agent and push it to the Hub**. + +This way: +- You can **showcase our work** ๐Ÿ”ฅ +- You can **visualize your agent playing** ๐Ÿ‘€ +- You can **share with the community an agent that others can use** ๐Ÿ’พ +- You can **access a leaderboard ๐Ÿ† to see how well your agent is performing compared to your classmates** ๐Ÿ‘‰ https://huggingface.co/spaces/huggingface-projects/Deep-Reinforcement-Learning-Leaderboard + + +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 a new token (https://huggingface.co/settings/tokens) **with write role** + + +Create HF Token + + +```python +notebook_login() +``` + +If you don't want to use a Google Colab or a Jupyter Notebook, you need to use this command instead: `huggingface-cli login` (or `login`) + +3๏ธโƒฃ We're now ready to push our trained agent to the ๐Ÿค— Hub ๐Ÿ”ฅ using `package_to_hub()` function + +```python +repo_id = "" # TODO Define your repo id {username/Reinforce-{model-id}} +push_to_hub( + repo_id, + cartpole_policy, # The model we want to save + cartpole_hyperparameters, # Hyperparameters + eval_env, # Evaluation environment + video_fps=30 +) +``` + +Now that we try the robustness of our implementation, let's try a more complex environment: PixelCopter ๐Ÿš + + + + +## Second agent: PixelCopter ๐Ÿš + +### Study the PixelCopter environment ๐Ÿ‘€ +- [The Environment documentation](https://pygame-learning-environment.readthedocs.io/en/latest/user/games/pixelcopter.html) + + +```python +env_id = "Pixelcopter-PLE-v0" +env = gym.make(env_id) +eval_env = gym.make(env_id) +s_size = env.observation_space.shape[0] +a_size = env.action_space.n +``` + +```python +print("_____OBSERVATION SPACE_____ \n") +print("The State Space is: ", s_size) +print("Sample observation", env.observation_space.sample()) # Get a random observation +``` + +```python +print("\n _____ACTION SPACE_____ \n") +print("The Action Space is: ", a_size) +print("Action Space Sample", env.action_space.sample()) # Take a random action +``` + +The observation space (7) ๐Ÿ‘€: +- player y position +- player velocity +- player distance to floor +- player distance to ceiling +- next block x distance to player +- next blocks top y location +- next blocks bottom y location + +The action space(2) ๐ŸŽฎ: +- Up +- Down + +The reward function ๐Ÿ’ฐ: +- For each vertical block it passes through it gains a positive reward of +1. Each time a terminal state reached it receives a negative reward of -1. + +### Define the new Policy ๐Ÿง  +- We need to have a deeper neural network since the environment is more complex + +```python +class Policy(nn.Module): + def __init__(self, s_size, a_size, h_size): + super(Policy, self).__init__() + # Define the three layers here + + def forward(self, x): + # Define the forward process here + return F.softmax(x, dim=1) + + def act(self, state): + state = torch.from_numpy(state).float().unsqueeze(0).to(device) + probs = self.forward(state).cpu() + m = Categorical(probs) + action = m.sample() + return action.item(), m.log_prob(action) +``` + +#### Solution + +```python +class Policy(nn.Module): + def __init__(self, s_size, a_size, h_size): + super(Policy, self).__init__() + self.fc1 = nn.Linear(s_size, h_size) + self.fc2 = nn.Linear(h_size, h_size * 2) + self.fc3 = nn.Linear(h_size * 2, a_size) + + def forward(self, x): + x = F.relu(self.fc1(x)) + x = F.relu(self.fc2(x)) + x = self.fc3(x) + return F.softmax(x, dim=1) + + def act(self, state): + state = torch.from_numpy(state).float().unsqueeze(0).to(device) + probs = self.forward(state).cpu() + m = Categorical(probs) + action = m.sample() + return action.item(), m.log_prob(action) +``` + +### Define the hyperparameters โš™๏ธ +- Because this environment is more complex. +- Especially for the hidden size, we need more neurons. + +```python +pixelcopter_hyperparameters = { + "h_size": 64, + "n_training_episodes": 50000, + "n_evaluation_episodes": 10, + "max_t": 10000, + "gamma": 0.99, + "lr": 1e-4, + "env_id": env_id, + "state_space": s_size, + "action_space": a_size, +} +``` + +### Train it +- We're now ready to train our agent ๐Ÿ”ฅ. + +```python +# Create policy and place it to the device +# torch.manual_seed(50) +pixelcopter_policy = Policy( + pixelcopter_hyperparameters["state_space"], + pixelcopter_hyperparameters["action_space"], + pixelcopter_hyperparameters["h_size"], +).to(device) +pixelcopter_optimizer = optim.Adam(pixelcopter_policy.parameters(), lr=pixelcopter_hyperparameters["lr"]) +``` + +```python +scores = reinforce( + pixelcopter_policy, + pixelcopter_optimizer, + pixelcopter_hyperparameters["n_training_episodes"], + pixelcopter_hyperparameters["max_t"], + pixelcopter_hyperparameters["gamma"], + 1000, +) +``` + +### Publish our trained model on the Hub ๐Ÿ”ฅ + +```python +repo_id = "" # TODO Define your repo id {username/Reinforce-{model-id}} +push_to_hub( + repo_id, + pixelcopter_policy, # The model we want to save + pixelcopter_hyperparameters, # Hyperparameters + eval_env, # Evaluation environment + video_fps=30 +) +``` + +## Some additional challenges ๐Ÿ† + +The best way to learn **is to try things on your own**! As you saw, the current agent is not doing great. As a first suggestion, you can train for more steps. But also trying to find better parameters. + +In the [Leaderboard](https://huggingface.co/spaces/huggingface-projects/Deep-Reinforcement-Learning-Leaderboard) you will find your agents. Can you get to the top? + +Here are some ideas to achieve so: +* Train more steps +* Try different hyperparameters by looking at what your classmates have done ๐Ÿ‘‰ https://huggingface.co/models?other=reinforce +* **Push your new trained model** on the Hub ๐Ÿ”ฅ +* **Improving the implementation for more complex environments** (for instance, what about changing the network to a Convolutional Neural Network to handle +frames as observation)? + +________________________________________________________________________ + +**Congrats on finishing this unit**!ย There was a lot of information. +And congrats on finishing the tutorial. You've just coded your first Deep Reinforcement Learning agent from scratch using PyTorch and shared it on the Hub ๐Ÿฅณ. + +Don't hesitate to iterate on this unit **by improving the implementation for more complex environments** (for instance, what about changing the network to a Convolutional Neural Network to handle +frames as observation)? + +In the next unit, **we're going to learn more about Unity MLAgents**, by training agents in Unity environments. This way, you will be ready to participate in the **AI vs AI challenges where you'll train your agents +to compete against other agents in a snowball fight and a soccer game.** + +Sounds fun? See you next time! + +Finally, we would love **to hear what you think of the course and how we can improve it**. If you have some feedback then, please ๐Ÿ‘‰ [fill this form](https://forms.gle/BzKXWzLAGZESGNaE9) + +See you in Unit 5! ๐Ÿ”ฅ + +### Keep Learning, stay awesome ๐Ÿค— diff --git a/units/en/unit4/introduction.mdx b/units/en/unit4/introduction.mdx new file mode 100644 index 0000000..20ded5d --- /dev/null +++ b/units/en/unit4/introduction.mdx @@ -0,0 +1,24 @@ +# Introduction [[introduction]] + + thumbnail + +In the last unit, we learned about Deep Q-Learning. In this value-based deep reinforcement learning algorithm, weย **used a deep neural network to approximate the different Q-values for each possible action at a state.** + +Since the beginning of the course, we only studied value-based methods,ย **where we estimate a value function as an intermediate step towards finding an optimal policy.** + +Link value policy + +In value-based methods, theย policy ** \\(ฯ€\\) only exists because of the action value estimates since the policy is just a function**ย (for instance, greedy-policy) that will select the action with the highest value given a state. + +But, with policy-based methods, we want to optimize the policy directlyย **without having an intermediate step of learning a value function.** + +So today,ย **we'll learn about policy-based methods and study a subset of these methods called policy gradient**. Then we'll implement our first policy gradient algorithm called Monte Carlo **Reinforce** from scratch using PyTorch. +Then, we'll test its robustness using the CartPole-v1 and PixelCopter environments. + +You'll then be able to iterate and improve this implementation for more advanced environments. + +
+ Environments +
+ +Let's get started, diff --git a/units/en/unit4/pg-theorem.mdx b/units/en/unit4/pg-theorem.mdx new file mode 100644 index 0000000..82bae14 --- /dev/null +++ b/units/en/unit4/pg-theorem.mdx @@ -0,0 +1,82 @@ +# (Optional) the Policy Gradient Theorem + +In this optional section where we're **going to study how we differentiate the objective function that we will use to approximate the policy gradient**. + +Let's first recap our different formulas: + +1. The Objective function + +Return + + +2. The probability of a trajectory (given that action comes from \\(\pi_\theta\\)): + +Probability + + +So we have: + +\\(\nabla_\theta J(\theta) = \nabla_\theta \sum_{\tau}P(\tau;\theta)R(\tau)\\) + + +We can rewrite the gradient of the sum as the sum of the gradient: + +\\( = \sum_{\tau} \nabla_\theta P(\tau;\theta)R(\tau) \\) + +We then multiply every term in the sum by \\(\frac{P(\tau;\theta)}{P(\tau;\theta)}\\)(which is possible since it's = 1) + +\\( = \sum_{\tau} \frac{P(\tau;\theta)}{P(\tau;\theta)}\nabla_\theta P(\tau;\theta)R(\tau) \\) + +We can simplify further this since \\( \frac{P(\tau;\theta)}{P(\tau;\theta)}\nabla_\theta P(\tau;\theta) = P(\tau;\theta)\frac{\nabla_\theta P(\tau;\theta)}{P(\tau;\theta)} \\) + +\\(= \sum_{\tau} P(\tau;\theta) \frac{\nabla_\theta P(\tau;\theta)}{P(\tau;\theta)}R(\tau) \\) + +We can then use the *derivative log trick* (also called *likelihood ratio trick* or *REINFORCE trick*), a simple rule in calculus that implies that \\( \nabla_x log f(x) = \frac{\nabla_x f(x)}{f(x)} \\) + +So given we have \\(\frac{\nabla_\theta P(\tau;\theta)}{P(\tau;\theta)} \\) we transform it as \\(\nabla_\theta log P(\tau|\theta) \\) + + + +So this is our likelihood policy gradient: + +\\( \nabla_\theta J(\theta) = \sum_{\tau} P(\tau;\theta) \nabla_\theta log P(\tau;\theta) R(\tau) \\) + + + + + +Thanks for this new formula, we can estimate the gradient using trajectory samples (we can approximate the likelihood ratio policy gradient with sample-based estimate if you prefer). + +\\(\nabla_\theta J(\theta) = \frac{1}{m} \sum^{m}_{i=1} \nabla_\theta log P(\tau^{(i)};\theta)R(\tau^{(i)})\\) where each \\(\tau^{(i)}\\) is a sampled trajectory. + + +But we still have some mathematics work to do there: we need to simplify \\( \nabla_\theta log P(\tau|\theta) \\) + +We know that: + +\\(\nabla_\theta log P(\tau^{(i)};\theta)= \nabla_\theta log[ \mu(s_0) \prod_{t=0}^{H} P(s_{t+1}^{(i)}|s_{t}^{(i)}, a_{t}^{(i)}) \pi_\theta(a_{t}^{(i)}|s_{t}^{(i)})]\\) + +Where \\(\mu(s_0)\\) is the initial state distribution and \\( P(s_{t+1}^{(i)}|s_{t}^{(i)}, a_{t}^{(i)}) \\) is the state transition dynamics of the MDP. + +We know that the log of a product is equal to the sum of the logs: + +\\(\nabla_\theta log P(\tau^{(i)};\theta)= \nabla_\theta \left[ \sum_{t=0}^{H} log P(s_{t+1}^{(i)}|s_{t}^{(i)} a_{t}^{(i)}) + \sum_{t=0}^{H} log \pi_\theta(a_{t}^{(i)}|s_{t}^{(i)})\right]\\) + +We also know that the gradient of the sum is equal to the sum of gradient: + +\\( \nabla_\theta log P(\tau^{(i)};\theta)= \nabla_\theta \sum_{t=0}^{H} log P(s_{t+1}^{(i)}|s_{t}^{(i)} a_{t}^{(i)}) + \nabla_\theta \sum_{t=0}^{H} log \pi_\theta(a_{t}^{(i)}|s_{t}^{(i)}) \\) + +Since neither initial state distribution or state transition dynamics of the MDP are dependent of \\(\theta\\), the derivate of both terms are 0. So we can remove them: + +Since: +\\(\nabla_\theta \sum_{t=0}^{H} log P(s_{t+1}^{(i)}|s_{t}^{(i)} a_{t}^{(i)}) = 0 \\) and \\( \nabla_\theta \mu(s_0) = 0\\) + +\\(\nabla_\theta log P(\tau^{(i)};\theta) = \nabla_\theta \sum_{t=0}^{H} log \pi_\theta(a_{t}^{(i)}|s_{t}^{(i)})\\) + +We can rewrite the gradient of the sum as the sum of gradients: + +\\( \nabla_\theta log P(\tau^{(i)};\theta)= \sum_{t=0}^{H} \nabla_\theta log \pi_\theta(a_{t}^{(i)}|s_{t}^{(i)}) \\) + +So, the final formula for estimating the policy gradient is: + +\\( \nabla_{\theta} J(\theta) = \hat{g} = \frac{1}{m} \sum^{m}_{i=1} \sum^{H}_{t=0} \nabla_\theta \log \pi_\theta(a^{(i)}_{t} | s_{t}^{(i)})R(\tau^{(i)}) \\) diff --git a/units/en/unit4/policy-gradient.mdx b/units/en/unit4/policy-gradient.mdx new file mode 100644 index 0000000..341d0f0 --- /dev/null +++ b/units/en/unit4/policy-gradient.mdx @@ -0,0 +1,120 @@ +# Diving deeper into policy-gradient methods + +## Getting the big picture + +We just learned that policy-gradient methods aim to find parameters \\( \theta \\) that **maximize the expected return**. + +The idea is that we have a *parameterized stochastic policy*. In our case, a neural network outputs a probability distribution over actions. The probability of taking each action is also called *action preference*. + +If we take the example of CartPole-v1: +- As input, we have a state. +- As output, we have a probability distribution over actions at that state. + +Policy based + +Our goal with policy-gradient is to **control the probability distribution of actions** by tuning the policy such that **good actions (that maximize the return)ย are sampled more frequently in the future.** +Each time the agent interacts with the environment, we tweak the parameters such that good actions will be sampled more likely in the future. + +But **how are we going to optimize the weights using the expected return**? + +The idea is that we're going to **let the agent interact during an episode**. And if we win the episode, we consider that each action taken was good and must be more sampled in the future +since they lead to win. + +So for each state-action pair, we want to increase the \\(P(a|s)\\): the probability of taking that action at that state. Or decrease if we lost. + +The Policy-gradient algorithm (simplified) looks like this: +
+ Policy Gradient Big Picture +
+ +Now that we got the big picture, let's dive deeper into policy-gradient methods. + +## Diving deeper into policy-gradient methods + +We have our stochastic policy \\(\pi\\) which has a parameter \\(\theta\\). This \\(\pi\\), given a state, **outputs a probability distribution of actions**. + +
+ Policy +
+ +Where \\(\pi_\theta(a_t|s_t)\\) is the probability of the agent selecting action \\(a_t\\) from state \\(s_t\\) given our policy. + +**But how do we know if our policy is good?** We need to have a way to measure it. To know that, we define a score/objective function called \\(J(\theta)\\). + +### The objective function + +The *objective function* gives us the **performance of the agent** given a trajectory (state action sequence without considering reward (contrary to an episode)), and it outputs the *expected cumulative reward*. + +Return + +Let's detail a little bit more this formula: +- The *expected return* (also called expected cumulative reward), is the weighted average (where the weights are given by \\(P(\tau;\theta)\\) of all possible values that the return \\(R(\tau)\\) can take. + +Return + + +- \\(R(\tau)\\) : Return from an arbitrary trajectory. To take this quantity and use it to calculate the expected return, we need to multiply it by the probability of each possible trajectory. +- \\(P(\tau;\theta)\\) : Probability of each possible trajectory \\(\tau\\) (that probability depends on \\( \theta\\) since it defines the policy that it uses to select the actions of the trajectory which as an impact of the states visited). + +Probability + +- \\(J(\theta)\\) : Expected return, we calculate it by summing for all trajectories, the probability of taking that trajectory given $\theta$, and the return of this trajectory. + +Our objective then is to maximize the expected cumulative rewards by finding \\(\theta \\) that will output the best action probability distributions: + + +Max objective + + +## Gradient Ascent and the Policy-gradient Theorem + +Policy-gradient is an optimization problem: we want to find the values of \\(\theta\\) that maximize our objective function \\(J(\theta)\\), we need to use **gradient-ascent**. It's the inverse of *gradient-descent* since it gives the direction of the steepest increase of \\(J(\theta)\\). + +(If you need a refresher on the difference between gradient descent and gradient ascent [check this](https://www.baeldung.com/cs/gradient-descent-vs-ascent) and [this](https://stats.stackexchange.com/questions/258721/gradient-ascent-vs-gradient-descent-in-logistic-regression)). + +Our update step for gradient-ascent is: + +\\( \theta \leftarrow \theta + \alpha * \nabla_\theta J(\theta) \\) + +We can repeatedly apply this update state in the hope that \\(\theta \\) converges to the value that maximizes \\(J(\theta)\\). + +However, we have two problems to obtain the derivative of \\(J(\theta)\\): +1. We can't calculate the true gradient of the objective function since it would imply calculating the probability of each possible trajectory which is computationally super expensive. +We want then to **calculate a gradient estimation with a sample-based estimate (collect some trajectories)**. + +2. We have another problem that I detail in the next optional section. To differentiate this objective function, we need to differentiate the state distribution, called Markov Decision Process dynamics. This is attached to the environment. It gives us the probability of the environment going into the next state, given the current state and the action taken by the agent. The problem is that we can't differentiate it because we might not know about it. + +Probability + +Fortunately we're going to use a solution called the Policy Gradient Theorem that will help us to reformulate the objective function into a differentiable function that does not involve the differentiation of the state distribution. + +Policy Gradient + +If you want to understand how we derivate this formula that we will use to approximate the gradient, check the next (optional) section. + +## The Reinforce algorithm (Monte Carlo Reinforce) + +The Reinforce algorithm, also called Monte-Carlo policy-gradient, is a policy-gradient algorithm that **uses an estimated return from an entire episode to update the policy parameter** \\(\theta\\): + +In a loop: +- Use the policy \\(\pi_\theta\\) to collect an episode \\(\tau\\) +- Use the episode to estimate the gradient \\(\hat{g} = \nabla_\theta J(\theta)\\) + +
+ Policy Gradient +
+ +- Update the weights of the policy: \\(\theta \leftarrow \theta + \alpha \hat{g}\\) + +The interpretation we can make is this one: +- \\(\nabla_\theta log \pi_\theta(a_t|s_t)\\) is the direction of **steepest increase of the (log) probability** of selecting action at from state st. +This tells us **how we should change the weights of policy** if we want to increase/decrease the log probability of selecting action \\(a_t\\) at state \\(s_t\\). +- \\(R(\tau)\\): is the scoring function: + - If the return is high, it will **push up the probabilities** of the (state, action) combinations. + - Else, if the return is low, it will **push down the probabilities** of the (state, action) combinations. + + +We can also **collect multiple episodes (trajectories)** to estimate the gradient: +
+ Policy Gradient +
diff --git a/units/en/unit4/quiz.mdx b/units/en/unit4/quiz.mdx new file mode 100644 index 0000000..0d38c13 --- /dev/null +++ b/units/en/unit4/quiz.mdx @@ -0,0 +1,82 @@ +# Quiz + +The best way to learn and [to avoid the illusion of competence](https://www.coursera.org/lecture/learning-how-to-learn/illusions-of-competence-BuFzf) **is to test yourself.** This will help you to find **where you need to reinforce your knowledge**. + + +### Q1: What are the advantages of policy-gradient over value-based methods? (Check all that apply) + + + +### Q2: What is the Policy Gradient Theorem? + +
+Solution + +*The Policy Gradient Theorem* is a formula that will help us to reformulate the objective function into a differentiable function that does not involve the differentiation of the state distribution. + +Policy Gradient + +
+ + +### Q3: What's the difference between policy-based methods and policy-gradient methods? (Check all that apply) + + + + +### Q4: Why do we use gradient ascent instead of gradient descent to optimize J(ฮธ)? + + + +Congrats on finishing this Quiz ๐Ÿฅณ, if you missed some elements, take time to read the chapter again to reinforce (๐Ÿ˜) your knowledge. diff --git a/units/en/unit4/what-are-policy-based-methods.mdx b/units/en/unit4/what-are-policy-based-methods.mdx new file mode 100644 index 0000000..b06ddac --- /dev/null +++ b/units/en/unit4/what-are-policy-based-methods.mdx @@ -0,0 +1,42 @@ +# What are the policy-based methods? + +The main goal of Reinforcement learning is to **find the optimal policy \\(\pi^{*}\\) that will maximize the expected cumulative reward**. +Because Reinforcement Learning is based on the *reward hypothesis*: **all goals can be described as the maximization of the expected cumulative reward.** + +For instance, in a soccer game (where you're going to train the agents in two units), the goal is to win the game. We can describe this goal in reinforcement learning as +**maximizing the number of goals scored** (when the ball crosses the goal line) into your opponent's soccer goals. And **minimizing the number of goals in your soccer goals**. + +Soccer + +## Value-based, Policy-based, and Actor-critic methods + +We studied in the first unit, that we had two methods to find (most of the time approximate) this optimal policy \\(\pi^{*}\\). + +- In *value-based methods*, we learn a value function. + - The idea is that an optimal value function leads to an optimal policy \\(\pi^{*}\\). + - Our objective is to **minimize the loss between the predicted and target value** to approximate the true action-value function. + - We have a policy, but it's implicit since it **was generated directly from the value function**. For instance, in Q-Learning, we defined an epsilon-greedy policy. + +- On the other hand, in *policy-based methods*, we directly learn to approximate \\(\pi^{*}\\) without having to learn a value function. + - The idea is **to parameterize the policy**. For instance, using a neural network \\(\pi_\theta\\), this policy will output a probability distribution over actions (stochastic policy). + - stochastic policy + - Our objective then is **to maximize the performance of the parameterized policy using gradient ascent**. + - To do that, we control the parameter \\(\theta\\) that will affect the distribution of actions over a state. + +Policy based + +- Finally, we'll study the next time *actor-critic* which is a combination of value-based and policy-based methods. + +Consequently, thanks to policy-based methods, we can directly optimize our policy \\(\pi_\theta\\) to output a probability distribution over actions \\(\pi_\theta(a|s)\\) that leads to the best cumulative return. +To do that, we define an objective function \\(J(\theta)\\), that is, the expected cumulative reward, and we **want to find \\(\theta\\) that maximizes this objective function**. + +## The difference between policy-based and policy-gradient methods + +Policy-gradient methods, what we're going to study in this unit, is a subclass of policy-based methods. In policy-based methods, the optimization is most of the time *on-policy* since for each update, we only use data (trajectories) collected **by our most recent version of** \\(\pi_\theta\\). + +The difference between these two methods **lies on how we optimize the parameter** \\(\theta\\): + +- In *policy-based methods*, we search directly for the optimal policy. We can optimize the parameter \\(\theta\\) **indirectly** by maximizing the local approximation of the objective function with techniques like hill climbing, simulated annealing, or evolution strategies. +- In *policy-gradient methods*, because we're a subclass of the policy-based methods, we search directly for the optimal policy. But we optimize the parameter \\(\theta\\) **directly** by performing the gradient ascent on the performance of the objective function \\(J(\theta)\\). + +Before diving more into how works policy-gradient methods (the objective function, policy gradient theorem, gradient ascent, etc.), let's study the advantages and disadvantages of policy-based methods.