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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"metadata": {
|
| 6 |
+
"id": "CjRWziAVU2lZ"
|
| 7 |
+
},
|
| 8 |
+
"source": [
|
| 9 |
+
"# Unit 4: Code your first Deep Reinforcement Learning Algorithm with PyTorch: Reinforce. And test its robustness 💪\n",
|
| 10 |
+
"\n",
|
| 11 |
+
"<img src=\"https://huggingface.co/datasets/huggingface-deep-rl-course/course-images/resolve/main/en/unit6/thumbnail.png\" alt=\"thumbnail\"/>\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"\n",
|
| 14 |
+
"In this notebook, you'll code your first Deep Reinforcement Learning algorithm from scratch: Reinforce (also called Monte Carlo Policy Gradient).\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"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",
|
| 17 |
+
"\n",
|
| 18 |
+
"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",
|
| 19 |
+
"\n",
|
| 20 |
+
"To test its robustness, we're going to train it in 2 different simple environments:\n",
|
| 21 |
+
"- Cartpole-v1\n",
|
| 22 |
+
"- PixelcopterEnv\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"⬇️ Here is an example of what **you will achieve at the end of this notebook.** ⬇️"
|
| 25 |
+
]
|
| 26 |
+
},
|
| 27 |
+
{
|
| 28 |
+
"cell_type": "markdown",
|
| 29 |
+
"source": [
|
| 30 |
+
" <img src=\"https://huggingface.co/datasets/huggingface-deep-rl-course/course-images/resolve/main/en/unit6/envs.gif\" alt=\"Environments\"/>\n"
|
| 31 |
+
],
|
| 32 |
+
"metadata": {
|
| 33 |
+
"id": "s4rBom2sbo7S"
|
| 34 |
+
}
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
"cell_type": "markdown",
|
| 38 |
+
"source": [
|
| 39 |
+
"### 🎮 Environments:\n",
|
| 40 |
+
"\n",
|
| 41 |
+
"- [CartPole-v1](https://www.gymlibrary.dev/environments/classic_control/cart_pole/)\n",
|
| 42 |
+
"- [PixelCopter](https://pygame-learning-environment.readthedocs.io/en/latest/user/games/pixelcopter.html)\n",
|
| 43 |
+
"\n",
|
| 44 |
+
"### 📚 RL-Library:\n",
|
| 45 |
+
"\n",
|
| 46 |
+
"- Python\n",
|
| 47 |
+
"- PyTorch\n",
|
| 48 |
+
"\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"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)."
|
| 51 |
+
],
|
| 52 |
+
"metadata": {
|
| 53 |
+
"id": "BPLwsPajb1f8"
|
| 54 |
+
}
|
| 55 |
+
},
|
| 56 |
+
{
|
| 57 |
+
"cell_type": "markdown",
|
| 58 |
+
"metadata": {
|
| 59 |
+
"id": "L_WSo0VUV99t"
|
| 60 |
+
},
|
| 61 |
+
"source": [
|
| 62 |
+
"## Objectives of this notebook 🏆\n",
|
| 63 |
+
"At the end of the notebook, you will:\n",
|
| 64 |
+
"- Be able to **code from scratch a Reinforce algorithm using PyTorch.**\n",
|
| 65 |
+
"- Be able to **test the robustness of your agent using simple environments.**\n",
|
| 66 |
+
"- Be able to **push your trained agent to the Hub** with a nice video replay and an evaluation score 🔥."
|
| 67 |
+
]
|
| 68 |
+
},
|
| 69 |
+
{
|
| 70 |
+
"cell_type": "markdown",
|
| 71 |
+
"metadata": {
|
| 72 |
+
"id": "lEPrZg2eWa4R"
|
| 73 |
+
},
|
| 74 |
+
"source": [
|
| 75 |
+
"## This notebook is from the Deep Reinforcement Learning Course\n",
|
| 76 |
+
"<img src=\"https://huggingface.co/datasets/huggingface-deep-rl-course/course-images/resolve/main/en/notebooks/deep-rl-course-illustration.jpg\" alt=\"Deep RL Course illustration\"/>"
|
| 77 |
+
]
|
| 78 |
+
},
|
| 79 |
+
{
|
| 80 |
+
"cell_type": "markdown",
|
| 81 |
+
"metadata": {
|
| 82 |
+
"id": "6p5HnEefISCB"
|
| 83 |
+
},
|
| 84 |
+
"source": [
|
| 85 |
+
"In this free course, you will:\n",
|
| 86 |
+
"\n",
|
| 87 |
+
"- 📖 Study Deep Reinforcement Learning in **theory and practice**.\n",
|
| 88 |
+
"- 🧑💻 Learn to **use famous Deep RL libraries** such as Stable Baselines3, RL Baselines3 Zoo, CleanRL and Sample Factory 2.0.\n",
|
| 89 |
+
"- 🤖 Train **agents in unique environments**\n",
|
| 90 |
+
"\n",
|
| 91 |
+
"And more check 📚 the syllabus 👉 https://simoninithomas.github.io/deep-rl-course\n",
|
| 92 |
+
"\n",
|
| 93 |
+
"Don’t forget to **<a href=\"http://eepurl.com/ic5ZUD\">sign up to the course</a>** (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",
|
| 94 |
+
"\n",
|
| 95 |
+
"\n",
|
| 96 |
+
"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"
|
| 97 |
+
]
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
"cell_type": "markdown",
|
| 101 |
+
"metadata": {
|
| 102 |
+
"id": "mjY-eq3eWh9O"
|
| 103 |
+
},
|
| 104 |
+
"source": [
|
| 105 |
+
"## Prerequisites 🏗️\n",
|
| 106 |
+
"Before diving into the notebook, you need to:\n",
|
| 107 |
+
"\n",
|
| 108 |
+
"🔲 📚 [Study Policy Gradients by reading Unit 4](https://huggingface.co/deep-rl-course/unit4/introduction)"
|
| 109 |
+
]
|
| 110 |
+
},
|
| 111 |
+
{
|
| 112 |
+
"cell_type": "markdown",
|
| 113 |
+
"source": [
|
| 114 |
+
"# Let's code Reinforce algorithm from scratch 🔥\n",
|
| 115 |
+
"\n",
|
| 116 |
+
"\n",
|
| 117 |
+
"To validate this hands-on for the certification process, you need to push your trained models to the Hub.\n",
|
| 118 |
+
"\n",
|
| 119 |
+
"- Get a result of >= 350 for `Cartpole-v1`.\n",
|
| 120 |
+
"- Get a result of >= 5 for `PixelCopter`.\n",
|
| 121 |
+
"\n",
|
| 122 |
+
"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",
|
| 123 |
+
"\n",
|
| 124 |
+
"For more information about the certification process, check this section 👉 https://huggingface.co/deep-rl-course/en/unit0/introduction#certification-process\n"
|
| 125 |
+
],
|
| 126 |
+
"metadata": {
|
| 127 |
+
"id": "Bsh4ZAamchSl"
|
| 128 |
+
}
|
| 129 |
+
},
|
| 130 |
+
{
|
| 131 |
+
"cell_type": "markdown",
|
| 132 |
+
"source": [
|
| 133 |
+
"## An advice 💡\n",
|
| 134 |
+
"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",
|
| 135 |
+
"\n",
|
| 136 |
+
"To do that you can either do `Ctrl + S` or `File > Save a copy in Google Drive.`"
|
| 137 |
+
],
|
| 138 |
+
"metadata": {
|
| 139 |
+
"id": "JoTC9o2SczNn"
|
| 140 |
+
}
|
| 141 |
+
},
|
| 142 |
+
{
|
| 143 |
+
"cell_type": "markdown",
|
| 144 |
+
"source": [
|
| 145 |
+
"## Set the GPU 💪\n",
|
| 146 |
+
"- To **accelerate the agent's training, we'll use a GPU**. To do that, go to `Runtime > Change Runtime type`\n",
|
| 147 |
+
"\n",
|
| 148 |
+
"<img src=\"https://huggingface.co/datasets/huggingface-deep-rl-course/course-images/resolve/main/en/notebooks/gpu-step1.jpg\" alt=\"GPU Step 1\">"
|
| 149 |
+
],
|
| 150 |
+
"metadata": {
|
| 151 |
+
"id": "PU4FVzaoM6fC"
|
| 152 |
+
}
|
| 153 |
+
},
|
| 154 |
+
{
|
| 155 |
+
"cell_type": "markdown",
|
| 156 |
+
"source": [
|
| 157 |
+
"- `Hardware Accelerator > GPU`\n",
|
| 158 |
+
"\n",
|
| 159 |
+
"<img src=\"https://huggingface.co/datasets/huggingface-deep-rl-course/course-images/resolve/main/en/notebooks/gpu-step2.jpg\" alt=\"GPU Step 2\">"
|
| 160 |
+
],
|
| 161 |
+
"metadata": {
|
| 162 |
+
"id": "KV0NyFdQM9ZG"
|
| 163 |
+
}
|
| 164 |
+
},
|
| 165 |
+
{
|
| 166 |
+
"cell_type": "markdown",
|
| 167 |
+
"source": [
|
| 168 |
+
"## Create a virtual display 🖥\n",
|
| 169 |
+
"\n",
|
| 170 |
+
"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",
|
| 171 |
+
"\n",
|
| 172 |
+
"Hence the following cell will install the librairies and create and run a virtual screen 🖥"
|
| 173 |
+
],
|
| 174 |
+
"metadata": {
|
| 175 |
+
"id": "bTpYcVZVMzUI"
|
| 176 |
+
}
|
| 177 |
+
},
|
| 178 |
+
{
|
| 179 |
+
"cell_type": "code",
|
| 180 |
+
"execution_count": null,
|
| 181 |
+
"metadata": {
|
| 182 |
+
"id": "jV6wjQ7Be7p5"
|
| 183 |
+
},
|
| 184 |
+
"outputs": [],
|
| 185 |
+
"source": [
|
| 186 |
+
"%%capture\n",
|
| 187 |
+
"!apt install python-opengl\n",
|
| 188 |
+
"!apt install ffmpeg\n",
|
| 189 |
+
"!apt install xvfb\n",
|
| 190 |
+
"!pip install pyvirtualdisplay\n",
|
| 191 |
+
"!pip install pyglet==1.5.1"
|
| 192 |
+
]
|
| 193 |
+
},
|
| 194 |
+
{
|
| 195 |
+
"cell_type": "code",
|
| 196 |
+
"source": [
|
| 197 |
+
"# Virtual display\n",
|
| 198 |
+
"from pyvirtualdisplay import Display\n",
|
| 199 |
+
"\n",
|
| 200 |
+
"virtual_display = Display(visible=0, size=(1400, 900))\n",
|
| 201 |
+
"virtual_display.start()"
|
| 202 |
+
],
|
| 203 |
+
"metadata": {
|
| 204 |
+
"id": "Sr-Nuyb1dBm0"
|
| 205 |
+
},
|
| 206 |
+
"execution_count": null,
|
| 207 |
+
"outputs": []
|
| 208 |
+
},
|
| 209 |
+
{
|
| 210 |
+
"cell_type": "markdown",
|
| 211 |
+
"metadata": {
|
| 212 |
+
"id": "tjrLfPFIW8XK"
|
| 213 |
+
},
|
| 214 |
+
"source": [
|
| 215 |
+
"## Install the dependencies 🔽\n",
|
| 216 |
+
"The first step is to install the dependencies. We’ll install multiple ones:\n",
|
| 217 |
+
"\n",
|
| 218 |
+
"- `gym`\n",
|
| 219 |
+
"- `gym-games`: Extra gym environments made with PyGame.\n",
|
| 220 |
+
"- `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",
|
| 221 |
+
"\n",
|
| 222 |
+
"You may be wondering why we install gym and not gymnasium, a more recent version of gym? **Because the gym-games we are using are not updated yet with gymnasium**.\n",
|
| 223 |
+
"\n",
|
| 224 |
+
"The differences you'll encounter here:\n",
|
| 225 |
+
"- In `gym` we don't have `terminated` and `truncated` but only `done`.\n",
|
| 226 |
+
"- In `gym` using `env.step()` returns `state, reward, done, info`\n",
|
| 227 |
+
"\n",
|
| 228 |
+
"You can learn more about the differences between Gym and Gymnasium here 👉 https://gymnasium.farama.org/content/migration-guide/\n",
|
| 229 |
+
"\n",
|
| 230 |
+
"\n",
|
| 231 |
+
"You can see here all the Reinforce models available 👉 https://huggingface.co/models?other=reinforce\n",
|
| 232 |
+
"\n",
|
| 233 |
+
"And you can find all the Deep Reinforcement Learning models here 👉 https://huggingface.co/models?pipeline_tag=reinforcement-learning\n"
|
| 234 |
+
]
|
| 235 |
+
},
|
| 236 |
+
{
|
| 237 |
+
"cell_type": "code",
|
| 238 |
+
"source": [
|
| 239 |
+
"!pip install -r https://raw.githubusercontent.com/huggingface/deep-rl-class/main/notebooks/unit4/requirements-unit4.txt"
|
| 240 |
+
],
|
| 241 |
+
"metadata": {
|
| 242 |
+
"id": "e8ZVi-uydpgL"
|
| 243 |
+
},
|
| 244 |
+
"execution_count": null,
|
| 245 |
+
"outputs": []
|
| 246 |
+
},
|
| 247 |
+
{
|
| 248 |
+
"cell_type": "markdown",
|
| 249 |
+
"metadata": {
|
| 250 |
+
"id": "AAHAq6RZW3rn"
|
| 251 |
+
},
|
| 252 |
+
"source": [
|
| 253 |
+
"## Import the packages 📦\n",
|
| 254 |
+
"In addition to import the installed libraries, we also import:\n",
|
| 255 |
+
"\n",
|
| 256 |
+
"- `imageio`: A library that will help us to generate a replay video\n",
|
| 257 |
+
"\n"
|
| 258 |
+
]
|
| 259 |
+
},
|
| 260 |
+
{
|
| 261 |
+
"cell_type": "code",
|
| 262 |
+
"execution_count": null,
|
| 263 |
+
"metadata": {
|
| 264 |
+
"id": "V8oadoJSWp7C"
|
| 265 |
+
},
|
| 266 |
+
"outputs": [],
|
| 267 |
+
"source": [
|
| 268 |
+
"import numpy as np\n",
|
| 269 |
+
"\n",
|
| 270 |
+
"from collections import deque\n",
|
| 271 |
+
"\n",
|
| 272 |
+
"import matplotlib.pyplot as plt\n",
|
| 273 |
+
"%matplotlib inline\n",
|
| 274 |
+
"\n",
|
| 275 |
+
"# PyTorch\n",
|
| 276 |
+
"import torch\n",
|
| 277 |
+
"import torch.nn as nn\n",
|
| 278 |
+
"import torch.nn.functional as F\n",
|
| 279 |
+
"import torch.optim as optim\n",
|
| 280 |
+
"from torch.distributions import Categorical\n",
|
| 281 |
+
"\n",
|
| 282 |
+
"# Gym\n",
|
| 283 |
+
"import gym\n",
|
| 284 |
+
"import gym_pygame\n",
|
| 285 |
+
"\n",
|
| 286 |
+
"# Hugging Face Hub\n",
|
| 287 |
+
"from huggingface_hub import notebook_login # To log to our Hugging Face account to be able to upload models to the Hub.\n",
|
| 288 |
+
"import imageio"
|
| 289 |
+
]
|
| 290 |
+
},
|
| 291 |
+
{
|
| 292 |
+
"cell_type": "markdown",
|
| 293 |
+
"source": [
|
| 294 |
+
"## Check if we have a GPU\n",
|
| 295 |
+
"\n",
|
| 296 |
+
"- Let's check if we have a GPU\n",
|
| 297 |
+
"- If it's the case you should see `device:cuda0`"
|
| 298 |
+
],
|
| 299 |
+
"metadata": {
|
| 300 |
+
"id": "RfxJYdMeeVgv"
|
| 301 |
+
}
|
| 302 |
+
},
|
| 303 |
+
{
|
| 304 |
+
"cell_type": "code",
|
| 305 |
+
"execution_count": null,
|
| 306 |
+
"metadata": {
|
| 307 |
+
"id": "kaJu5FeZxXGY"
|
| 308 |
+
},
|
| 309 |
+
"outputs": [],
|
| 310 |
+
"source": [
|
| 311 |
+
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")"
|
| 312 |
+
]
|
| 313 |
+
},
|
| 314 |
+
{
|
| 315 |
+
"cell_type": "code",
|
| 316 |
+
"execution_count": null,
|
| 317 |
+
"metadata": {
|
| 318 |
+
"id": "U5TNYa14aRav"
|
| 319 |
+
},
|
| 320 |
+
"outputs": [],
|
| 321 |
+
"source": [
|
| 322 |
+
"print(device)"
|
| 323 |
+
]
|
| 324 |
+
},
|
| 325 |
+
{
|
| 326 |
+
"cell_type": "markdown",
|
| 327 |
+
"metadata": {
|
| 328 |
+
"id": "PBPecCtBL_pZ"
|
| 329 |
+
},
|
| 330 |
+
"source": [
|
| 331 |
+
"We're now ready to implement our Reinforce algorithm 🔥"
|
| 332 |
+
]
|
| 333 |
+
},
|
| 334 |
+
{
|
| 335 |
+
"cell_type": "markdown",
|
| 336 |
+
"metadata": {
|
| 337 |
+
"id": "8KEyKYo2ZSC-"
|
| 338 |
+
},
|
| 339 |
+
"source": [
|
| 340 |
+
"# First agent: Playing CartPole-v1 🤖"
|
| 341 |
+
]
|
| 342 |
+
},
|
| 343 |
+
{
|
| 344 |
+
"cell_type": "markdown",
|
| 345 |
+
"metadata": {
|
| 346 |
+
"id": "haLArKURMyuF"
|
| 347 |
+
},
|
| 348 |
+
"source": [
|
| 349 |
+
"## Create the CartPole environment and understand how it works\n",
|
| 350 |
+
"### [The environment 🎮](https://www.gymlibrary.dev/environments/classic_control/cart_pole/)\n"
|
| 351 |
+
]
|
| 352 |
+
},
|
| 353 |
+
{
|
| 354 |
+
"cell_type": "markdown",
|
| 355 |
+
"metadata": {
|
| 356 |
+
"id": "AH_TaLKFXo_8"
|
| 357 |
+
},
|
| 358 |
+
"source": [
|
| 359 |
+
"### Why do we use a simple environment like CartPole-v1?\n",
|
| 360 |
+
"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",
|
| 361 |
+
"\n",
|
| 362 |
+
"\n",
|
| 363 |
+
"> Try to have some “sign of life” on toy problems\n",
|
| 364 |
+
"\n",
|
| 365 |
+
"\n",
|
| 366 |
+
"> 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",
|
| 367 |
+
"___\n",
|
| 368 |
+
"### The CartPole-v1 environment\n",
|
| 369 |
+
"\n",
|
| 370 |
+
"> 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",
|
| 371 |
+
"\n",
|
| 372 |
+
"\n",
|
| 373 |
+
"\n",
|
| 374 |
+
"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",
|
| 375 |
+
"\n",
|
| 376 |
+
"The episode ends if:\n",
|
| 377 |
+
"- The pole Angle is greater than ±12°\n",
|
| 378 |
+
"- Cart Position is greater than ±2.4\n",
|
| 379 |
+
"- Episode length is greater than 500\n",
|
| 380 |
+
"\n",
|
| 381 |
+
"We get a reward 💰 of +1 every timestep the Pole stays in the equilibrium."
|
| 382 |
+
]
|
| 383 |
+
},
|
| 384 |
+
{
|
| 385 |
+
"cell_type": "code",
|
| 386 |
+
"execution_count": null,
|
| 387 |
+
"metadata": {
|
| 388 |
+
"id": "POOOk15_K6KA"
|
| 389 |
+
},
|
| 390 |
+
"outputs": [],
|
| 391 |
+
"source": [
|
| 392 |
+
"env_id = \"CartPole-v1\"\n",
|
| 393 |
+
"# Create the env\n",
|
| 394 |
+
"env = gym.make(env_id)\n",
|
| 395 |
+
"\n",
|
| 396 |
+
"# Create the evaluation env\n",
|
| 397 |
+
"eval_env = gym.make(env_id)\n",
|
| 398 |
+
"\n",
|
| 399 |
+
"# Get the state space and action space\n",
|
| 400 |
+
"s_size = env.observation_space.shape[0]\n",
|
| 401 |
+
"a_size = env.action_space.n"
|
| 402 |
+
]
|
| 403 |
+
},
|
| 404 |
+
{
|
| 405 |
+
"cell_type": "code",
|
| 406 |
+
"execution_count": null,
|
| 407 |
+
"metadata": {
|
| 408 |
+
"id": "FMLFrjiBNLYJ"
|
| 409 |
+
},
|
| 410 |
+
"outputs": [],
|
| 411 |
+
"source": [
|
| 412 |
+
"print(\"_____OBSERVATION SPACE_____ \\n\")\n",
|
| 413 |
+
"print(\"The State Space is: \", s_size)\n",
|
| 414 |
+
"print(\"Sample observation\", env.observation_space.sample()) # Get a random observation"
|
| 415 |
+
]
|
| 416 |
+
},
|
| 417 |
+
{
|
| 418 |
+
"cell_type": "code",
|
| 419 |
+
"execution_count": null,
|
| 420 |
+
"metadata": {
|
| 421 |
+
"id": "Lu6t4sRNNWkN"
|
| 422 |
+
},
|
| 423 |
+
"outputs": [],
|
| 424 |
+
"source": [
|
| 425 |
+
"print(\"\\n _____ACTION SPACE_____ \\n\")\n",
|
| 426 |
+
"print(\"The Action Space is: \", a_size)\n",
|
| 427 |
+
"print(\"Action Space Sample\", env.action_space.sample()) # Take a random action"
|
| 428 |
+
]
|
| 429 |
+
},
|
| 430 |
+
{
|
| 431 |
+
"cell_type": "markdown",
|
| 432 |
+
"metadata": {
|
| 433 |
+
"id": "7SJMJj3WaFOz"
|
| 434 |
+
},
|
| 435 |
+
"source": [
|
| 436 |
+
"## Let's build the Reinforce Architecture\n",
|
| 437 |
+
"This implementation is based on two implementations:\n",
|
| 438 |
+
"- [PyTorch official Reinforcement Learning example](https://github.com/pytorch/examples/blob/main/reinforcement_learning/reinforce.py)\n",
|
| 439 |
+
"- [Udacity Reinforce](https://github.com/udacity/deep-reinforcement-learning/blob/master/reinforce/REINFORCE.ipynb)\n",
|
| 440 |
+
"- [Improvement of the integration by Chris1nexus](https://github.com/huggingface/deep-rl-class/pull/95)\n",
|
| 441 |
+
"\n",
|
| 442 |
+
"<img src=\"https://huggingface.co/datasets/huggingface-deep-rl-course/course-images/resolve/main/en/unit6/reinforce.png\" alt=\"Reinforce\"/>"
|
| 443 |
+
]
|
| 444 |
+
},
|
| 445 |
+
{
|
| 446 |
+
"cell_type": "markdown",
|
| 447 |
+
"metadata": {
|
| 448 |
+
"id": "49kogtxBODX8"
|
| 449 |
+
},
|
| 450 |
+
"source": [
|
| 451 |
+
"So we want:\n",
|
| 452 |
+
"- Two fully connected layers (fc1 and fc2).\n",
|
| 453 |
+
"- Using ReLU as activation function of fc1\n",
|
| 454 |
+
"- Using Softmax to output a probability distribution over actions"
|
| 455 |
+
]
|
| 456 |
+
},
|
| 457 |
+
{
|
| 458 |
+
"cell_type": "code",
|
| 459 |
+
"execution_count": null,
|
| 460 |
+
"metadata": {
|
| 461 |
+
"id": "w2LHcHhVZvPZ"
|
| 462 |
+
},
|
| 463 |
+
"outputs": [],
|
| 464 |
+
"source": [
|
| 465 |
+
"class Policy(nn.Module):\n",
|
| 466 |
+
" def __init__(self, s_size, a_size, h_size):\n",
|
| 467 |
+
" super(Policy, self).__init__()\n",
|
| 468 |
+
" # Create two fully connected layers\n",
|
| 469 |
+
"\n",
|
| 470 |
+
"\n",
|
| 471 |
+
"\n",
|
| 472 |
+
" def forward(self, x):\n",
|
| 473 |
+
" # Define the forward pass\n",
|
| 474 |
+
" # state goes to fc1 then we apply ReLU activation function\n",
|
| 475 |
+
"\n",
|
| 476 |
+
" # fc1 outputs goes to fc2\n",
|
| 477 |
+
"\n",
|
| 478 |
+
" # We output the softmax\n",
|
| 479 |
+
"\n",
|
| 480 |
+
" def act(self, state):\n",
|
| 481 |
+
" \"\"\"\n",
|
| 482 |
+
" Given a state, take action\n",
|
| 483 |
+
" \"\"\"\n",
|
| 484 |
+
" state = torch.from_numpy(state).float().unsqueeze(0).to(device)\n",
|
| 485 |
+
" probs = self.forward(state).cpu()\n",
|
| 486 |
+
" m = Categorical(probs)\n",
|
| 487 |
+
" action = np.argmax(m)\n",
|
| 488 |
+
" return action.item(), m.log_prob(action)"
|
| 489 |
+
]
|
| 490 |
+
},
|
| 491 |
+
{
|
| 492 |
+
"cell_type": "markdown",
|
| 493 |
+
"metadata": {
|
| 494 |
+
"id": "rOMrdwSYOWSC"
|
| 495 |
+
},
|
| 496 |
+
"source": [
|
| 497 |
+
"### Solution"
|
| 498 |
+
]
|
| 499 |
+
},
|
| 500 |
+
{
|
| 501 |
+
"cell_type": "code",
|
| 502 |
+
"execution_count": null,
|
| 503 |
+
"metadata": {
|
| 504 |
+
"id": "jGdhRSVrOV4K"
|
| 505 |
+
},
|
| 506 |
+
"outputs": [],
|
| 507 |
+
"source": [
|
| 508 |
+
"class Policy(nn.Module):\n",
|
| 509 |
+
" def __init__(self, s_size, a_size, h_size):\n",
|
| 510 |
+
" super(Policy, self).__init__()\n",
|
| 511 |
+
" self.fc1 = nn.Linear(s_size, h_size)\n",
|
| 512 |
+
" self.fc2 = nn.Linear(h_size, a_size)\n",
|
| 513 |
+
"\n",
|
| 514 |
+
" def forward(self, x):\n",
|
| 515 |
+
" x = F.relu(self.fc1(x))\n",
|
| 516 |
+
" x = self.fc2(x)\n",
|
| 517 |
+
" return F.softmax(x, dim=1)\n",
|
| 518 |
+
"\n",
|
| 519 |
+
" def act(self, state):\n",
|
| 520 |
+
" state = torch.from_numpy(state).float().unsqueeze(0).to(device)\n",
|
| 521 |
+
" probs = self.forward(state).cpu()\n",
|
| 522 |
+
" m = Categorical(probs)\n",
|
| 523 |
+
" action = np.argmax(m)\n",
|
| 524 |
+
" return action.item(), m.log_prob(action)"
|
| 525 |
+
]
|
| 526 |
+
},
|
| 527 |
+
{
|
| 528 |
+
"cell_type": "markdown",
|
| 529 |
+
"metadata": {
|
| 530 |
+
"id": "ZTGWL4g2eM5B"
|
| 531 |
+
},
|
| 532 |
+
"source": [
|
| 533 |
+
"I make a mistake, can you guess where?\n",
|
| 534 |
+
"\n",
|
| 535 |
+
"- To find out let's make a forward pass:"
|
| 536 |
+
]
|
| 537 |
+
},
|
| 538 |
+
{
|
| 539 |
+
"cell_type": "code",
|
| 540 |
+
"execution_count": null,
|
| 541 |
+
"metadata": {
|
| 542 |
+
"id": "lwnqGBCNePor"
|
| 543 |
+
},
|
| 544 |
+
"outputs": [],
|
| 545 |
+
"source": [
|
| 546 |
+
"debug_policy = Policy(s_size, a_size, 64).to(device)\n",
|
| 547 |
+
"debug_policy.act(env.reset())"
|
| 548 |
+
]
|
| 549 |
+
},
|
| 550 |
+
{
|
| 551 |
+
"cell_type": "markdown",
|
| 552 |
+
"metadata": {
|
| 553 |
+
"id": "14UYkoxCPaor"
|
| 554 |
+
},
|
| 555 |
+
"source": [
|
| 556 |
+
"- Here we see that the error says `ValueError: The value argument to log_prob must be a Tensor`\n",
|
| 557 |
+
"\n",
|
| 558 |
+
"- It means that `action` in `m.log_prob(action)` must be a Tensor **but it's not.**\n",
|
| 559 |
+
"\n",
|
| 560 |
+
"- Do you know why? Check the act function and try to see why it does not work.\n",
|
| 561 |
+
"\n",
|
| 562 |
+
"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"
|
| 563 |
+
]
|
| 564 |
+
},
|
| 565 |
+
{
|
| 566 |
+
"cell_type": "markdown",
|
| 567 |
+
"metadata": {
|
| 568 |
+
"id": "gfGJNZBUP7Vn"
|
| 569 |
+
},
|
| 570 |
+
"source": [
|
| 571 |
+
"### (Real) Solution"
|
| 572 |
+
]
|
| 573 |
+
},
|
| 574 |
+
{
|
| 575 |
+
"cell_type": "code",
|
| 576 |
+
"execution_count": null,
|
| 577 |
+
"metadata": {
|
| 578 |
+
"id": "Ho_UHf49N9i4"
|
| 579 |
+
},
|
| 580 |
+
"outputs": [],
|
| 581 |
+
"source": [
|
| 582 |
+
"class Policy(nn.Module):\n",
|
| 583 |
+
" def __init__(self, s_size, a_size, h_size):\n",
|
| 584 |
+
" super(Policy, self).__init__()\n",
|
| 585 |
+
" self.fc1 = nn.Linear(s_size, h_size)\n",
|
| 586 |
+
" self.fc2 = nn.Linear(h_size, a_size)\n",
|
| 587 |
+
"\n",
|
| 588 |
+
" def forward(self, x):\n",
|
| 589 |
+
" x = F.relu(self.fc1(x))\n",
|
| 590 |
+
" x = self.fc2(x)\n",
|
| 591 |
+
" return F.softmax(x, dim=1)\n",
|
| 592 |
+
"\n",
|
| 593 |
+
" def act(self, state):\n",
|
| 594 |
+
" state = torch.from_numpy(state).float().unsqueeze(0).to(device)\n",
|
| 595 |
+
" probs = self.forward(state).cpu()\n",
|
| 596 |
+
" m = Categorical(probs)\n",
|
| 597 |
+
" action = m.sample()\n",
|
| 598 |
+
" return action.item(), m.log_prob(action)"
|
| 599 |
+
]
|
| 600 |
+
},
|
| 601 |
+
{
|
| 602 |
+
"cell_type": "markdown",
|
| 603 |
+
"metadata": {
|
| 604 |
+
"id": "rgJWQFU_eUYw"
|
| 605 |
+
},
|
| 606 |
+
"source": [
|
| 607 |
+
"By using CartPole, it was easier to debug since **we know that the bug comes from our integration and not from our simple environment**."
|
| 608 |
+
]
|
| 609 |
+
},
|
| 610 |
+
{
|
| 611 |
+
"cell_type": "markdown",
|
| 612 |
+
"source": [
|
| 613 |
+
"- 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",
|
| 614 |
+
"\n",
|
| 615 |
+
"- We need to replace with `action = m.sample()` that will sample an action from the probability distribution P(.|s)"
|
| 616 |
+
],
|
| 617 |
+
"metadata": {
|
| 618 |
+
"id": "c-20i7Pk0l1T"
|
| 619 |
+
}
|
| 620 |
+
},
|
| 621 |
+
{
|
| 622 |
+
"cell_type": "markdown",
|
| 623 |
+
"metadata": {
|
| 624 |
+
"id": "4MXoqetzfIoW"
|
| 625 |
+
},
|
| 626 |
+
"source": [
|
| 627 |
+
"### Let's build the Reinforce Training Algorithm\n",
|
| 628 |
+
"This is the Reinforce algorithm pseudocode:\n",
|
| 629 |
+
"\n",
|
| 630 |
+
"<img src=\"https://huggingface.co/datasets/huggingface-deep-rl-course/course-images/resolve/main/en/unit6/pg_pseudocode.png\" alt=\"Policy gradient pseudocode\"/>\n",
|
| 631 |
+
" "
|
| 632 |
+
]
|
| 633 |
+
},
|
| 634 |
+
{
|
| 635 |
+
"cell_type": "markdown",
|
| 636 |
+
"source": [
|
| 637 |
+
"- When we calculate the return Gt (line 6) we see that we calculate the sum of discounted rewards **starting at timestep t**.\n",
|
| 638 |
+
"\n",
|
| 639 |
+
"- 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",
|
| 640 |
+
"\n",
|
| 641 |
+
"- 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",
|
| 642 |
+
"\n",
|
| 643 |
+
"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",
|
| 644 |
+
"But overall the idea is to **compute the return at each timestep efficiently**."
|
| 645 |
+
],
|
| 646 |
+
"metadata": {
|
| 647 |
+
"id": "QmcXG-9i2Qu2"
|
| 648 |
+
}
|
| 649 |
+
},
|
| 650 |
+
{
|
| 651 |
+
"cell_type": "markdown",
|
| 652 |
+
"metadata": {
|
| 653 |
+
"id": "O554nUGPpcoq"
|
| 654 |
+
},
|
| 655 |
+
"source": [
|
| 656 |
+
"The second question you may ask is **why do we minimize the loss**? You talked about Gradient Ascent not Gradient Descent?\n",
|
| 657 |
+
"\n",
|
| 658 |
+
"- We want to maximize our utility function $J(\\theta)$ but in PyTorch like in Tensorflow it's better to **minimize an objective function.**\n",
|
| 659 |
+
" - So let's say we want to reinforce action 3 at a certain timestep. Before training this action P is 0.25.\n",
|
| 660 |
+
" - So we want to modify $\\theta$ such that $\\pi_\\theta(a_3|s; \\theta) > 0.25$\n",
|
| 661 |
+
" - Because all P must sum to 1, max $\\pi_\\theta(a_3|s; \\theta)$ will **minimize other action probability.**\n",
|
| 662 |
+
" - So we should tell PyTorch **to min $1 - \\pi_\\theta(a_3|s; \\theta)$.**\n",
|
| 663 |
+
" - This loss function approaches 0 as $\\pi_\\theta(a_3|s; \\theta)$ nears 1.\n",
|
| 664 |
+
" - So we are encouraging the gradient to max $\\pi_\\theta(a_3|s; \\theta)$\n"
|
| 665 |
+
]
|
| 666 |
+
},
|
| 667 |
+
{
|
| 668 |
+
"cell_type": "code",
|
| 669 |
+
"execution_count": null,
|
| 670 |
+
"metadata": {
|
| 671 |
+
"id": "iOdv8Q9NfLK7"
|
| 672 |
+
},
|
| 673 |
+
"outputs": [],
|
| 674 |
+
"source": [
|
| 675 |
+
"def reinforce(policy, optimizer, n_training_episodes, max_t, gamma, print_every):\n",
|
| 676 |
+
" # Help us to calculate the score during the training\n",
|
| 677 |
+
" scores_deque = deque(maxlen=100)\n",
|
| 678 |
+
" scores = []\n",
|
| 679 |
+
" # Line 3 of pseudocode\n",
|
| 680 |
+
" for i_episode in range(1, n_training_episodes+1):\n",
|
| 681 |
+
" saved_log_probs = []\n",
|
| 682 |
+
" rewards = []\n",
|
| 683 |
+
" state = # TODO: reset the environment\n",
|
| 684 |
+
" # Line 4 of pseudocode\n",
|
| 685 |
+
" for t in range(max_t):\n",
|
| 686 |
+
" action, log_prob = # TODO get the action\n",
|
| 687 |
+
" saved_log_probs.append(log_prob)\n",
|
| 688 |
+
" state, reward, done, _ = # TODO: take an env step\n",
|
| 689 |
+
" rewards.append(reward)\n",
|
| 690 |
+
" if done:\n",
|
| 691 |
+
" break\n",
|
| 692 |
+
" scores_deque.append(sum(rewards))\n",
|
| 693 |
+
" scores.append(sum(rewards))\n",
|
| 694 |
+
"\n",
|
| 695 |
+
" # Line 6 of pseudocode: calculate the return\n",
|
| 696 |
+
" returns = deque(maxlen=max_t)\n",
|
| 697 |
+
" n_steps = len(rewards)\n",
|
| 698 |
+
" # Compute the discounted returns at each timestep,\n",
|
| 699 |
+
" # as the sum of the gamma-discounted return at time t (G_t) + the reward at time t\n",
|
| 700 |
+
"\n",
|
| 701 |
+
" # In O(N) time, where N is the number of time steps\n",
|
| 702 |
+
" # (this definition of the discounted return G_t follows the definition of this quantity\n",
|
| 703 |
+
" # shown at page 44 of Sutton&Barto 2017 2nd draft)\n",
|
| 704 |
+
" # G_t = r_(t+1) + r_(t+2) + ...\n",
|
| 705 |
+
"\n",
|
| 706 |
+
" # Given this formulation, the returns at each timestep t can be computed\n",
|
| 707 |
+
" # by re-using the computed future returns G_(t+1) to compute the current return G_t\n",
|
| 708 |
+
" # G_t = r_(t+1) + gamma*G_(t+1)\n",
|
| 709 |
+
" # G_(t-1) = r_t + gamma* G_t\n",
|
| 710 |
+
" # (this follows a dynamic programming approach, with which we memorize solutions in order\n",
|
| 711 |
+
" # to avoid computing them multiple times)\n",
|
| 712 |
+
"\n",
|
| 713 |
+
" # This is correct since the above is equivalent to (see also page 46 of Sutton&Barto 2017 2nd draft)\n",
|
| 714 |
+
" # G_(t-1) = r_t + gamma*r_(t+1) + gamma*gamma*r_(t+2) + ...\n",
|
| 715 |
+
"\n",
|
| 716 |
+
"\n",
|
| 717 |
+
" ## Given the above, we calculate the returns at timestep t as:\n",
|
| 718 |
+
" # gamma[t] * return[t] + reward[t]\n",
|
| 719 |
+
" #\n",
|
| 720 |
+
" ## We compute this starting from the last timestep to the first, in order\n",
|
| 721 |
+
" ## to employ the formula presented above and avoid redundant computations that would be needed\n",
|
| 722 |
+
" ## if we were to do it from first to last.\n",
|
| 723 |
+
"\n",
|
| 724 |
+
" ## Hence, the queue \"returns\" will hold the returns in chronological order, from t=0 to t=n_steps\n",
|
| 725 |
+
" ## thanks to the appendleft() function which allows to append to the position 0 in constant time O(1)\n",
|
| 726 |
+
" ## a normal python list would instead require O(N) to do this.\n",
|
| 727 |
+
" for t in range(n_steps)[::-1]:\n",
|
| 728 |
+
" disc_return_t = (returns[0] if len(returns)>0 else 0)\n",
|
| 729 |
+
" returns.appendleft( ) # TODO: complete here\n",
|
| 730 |
+
"\n",
|
| 731 |
+
" ## standardization of the returns is employed to make training more stable\n",
|
| 732 |
+
" eps = np.finfo(np.float32).eps.item()\n",
|
| 733 |
+
"\n",
|
| 734 |
+
" ## eps is the smallest representable float, which is\n",
|
| 735 |
+
" # added to the standard deviation of the returns to avoid numerical instabilities\n",
|
| 736 |
+
" returns = torch.tensor(returns)\n",
|
| 737 |
+
" returns = (returns - returns.mean()) / (returns.std() + eps)\n",
|
| 738 |
+
"\n",
|
| 739 |
+
" # Line 7:\n",
|
| 740 |
+
" policy_loss = []\n",
|
| 741 |
+
" for log_prob, disc_return in zip(saved_log_probs, returns):\n",
|
| 742 |
+
" policy_loss.append(-log_prob * disc_return)\n",
|
| 743 |
+
" policy_loss = torch.cat(policy_loss).sum()\n",
|
| 744 |
+
"\n",
|
| 745 |
+
" # Line 8: PyTorch prefers gradient descent\n",
|
| 746 |
+
" optimizer.zero_grad()\n",
|
| 747 |
+
" policy_loss.backward()\n",
|
| 748 |
+
" optimizer.step()\n",
|
| 749 |
+
"\n",
|
| 750 |
+
" if i_episode % print_every == 0:\n",
|
| 751 |
+
" print('Episode {}\\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_deque)))\n",
|
| 752 |
+
"\n",
|
| 753 |
+
" return scores"
|
| 754 |
+
]
|
| 755 |
+
},
|
| 756 |
+
{
|
| 757 |
+
"cell_type": "markdown",
|
| 758 |
+
"metadata": {
|
| 759 |
+
"id": "YB0Cxrw1StrP"
|
| 760 |
+
},
|
| 761 |
+
"source": [
|
| 762 |
+
"#### Solution"
|
| 763 |
+
]
|
| 764 |
+
},
|
| 765 |
+
{
|
| 766 |
+
"cell_type": "code",
|
| 767 |
+
"execution_count": null,
|
| 768 |
+
"metadata": {
|
| 769 |
+
"id": "NCNvyElRStWG"
|
| 770 |
+
},
|
| 771 |
+
"outputs": [],
|
| 772 |
+
"source": [
|
| 773 |
+
"def reinforce(policy, optimizer, n_training_episodes, max_t, gamma, print_every):\n",
|
| 774 |
+
" # Help us to calculate the score during the training\n",
|
| 775 |
+
" scores_deque = deque(maxlen=100)\n",
|
| 776 |
+
" scores = []\n",
|
| 777 |
+
" # Line 3 of pseudocode\n",
|
| 778 |
+
" for i_episode in range(1, n_training_episodes+1):\n",
|
| 779 |
+
" saved_log_probs = []\n",
|
| 780 |
+
" rewards = []\n",
|
| 781 |
+
" state = env.reset()\n",
|
| 782 |
+
" # Line 4 of pseudocode\n",
|
| 783 |
+
" for t in range(max_t):\n",
|
| 784 |
+
" action, log_prob = policy.act(state)\n",
|
| 785 |
+
" saved_log_probs.append(log_prob)\n",
|
| 786 |
+
" state, reward, done, _ = env.step(action)\n",
|
| 787 |
+
" rewards.append(reward)\n",
|
| 788 |
+
" if done:\n",
|
| 789 |
+
" break\n",
|
| 790 |
+
" scores_deque.append(sum(rewards))\n",
|
| 791 |
+
" scores.append(sum(rewards))\n",
|
| 792 |
+
"\n",
|
| 793 |
+
" # Line 6 of pseudocode: calculate the return\n",
|
| 794 |
+
" returns = deque(maxlen=max_t)\n",
|
| 795 |
+
" n_steps = len(rewards)\n",
|
| 796 |
+
" # Compute the discounted returns at each timestep,\n",
|
| 797 |
+
" # as\n",
|
| 798 |
+
" # the sum of the gamma-discounted return at time t (G_t) + the reward at time t\n",
|
| 799 |
+
" #\n",
|
| 800 |
+
" # In O(N) time, where N is the number of time steps\n",
|
| 801 |
+
" # (this definition of the discounted return G_t follows the definition of this quantity\n",
|
| 802 |
+
" # shown at page 44 of Sutton&Barto 2017 2nd draft)\n",
|
| 803 |
+
" # G_t = r_(t+1) + r_(t+2) + ...\n",
|
| 804 |
+
"\n",
|
| 805 |
+
" # Given this formulation, the returns at each timestep t can be computed\n",
|
| 806 |
+
" # by re-using the computed future returns G_(t+1) to compute the current return G_t\n",
|
| 807 |
+
" # G_t = r_(t+1) + gamma*G_(t+1)\n",
|
| 808 |
+
" # G_(t-1) = r_t + gamma* G_t\n",
|
| 809 |
+
" # (this follows a dynamic programming approach, with which we memorize solutions in order\n",
|
| 810 |
+
" # to avoid computing them multiple times)\n",
|
| 811 |
+
"\n",
|
| 812 |
+
" # This is correct since the above is equivalent to (see also page 46 of Sutton&Barto 2017 2nd draft)\n",
|
| 813 |
+
" # G_(t-1) = r_t + gamma*r_(t+1) + gamma*gamma*r_(t+2) + ...\n",
|
| 814 |
+
"\n",
|
| 815 |
+
"\n",
|
| 816 |
+
" ## Given the above, we calculate the returns at timestep t as:\n",
|
| 817 |
+
" # gamma[t] * return[t] + reward[t]\n",
|
| 818 |
+
" #\n",
|
| 819 |
+
" ## We compute this starting from the last timestep to the first, in order\n",
|
| 820 |
+
" ## to employ the formula presented above and avoid redundant computations that would be needed\n",
|
| 821 |
+
" ## if we were to do it from first to last.\n",
|
| 822 |
+
"\n",
|
| 823 |
+
" ## Hence, the queue \"returns\" will hold the returns in chronological order, from t=0 to t=n_steps\n",
|
| 824 |
+
" ## thanks to the appendleft() function which allows to append to the position 0 in constant time O(1)\n",
|
| 825 |
+
" ## a normal python list would instead require O(N) to do this.\n",
|
| 826 |
+
" for t in range(n_steps)[::-1]:\n",
|
| 827 |
+
" disc_return_t = (returns[0] if len(returns)>0 else 0)\n",
|
| 828 |
+
" returns.appendleft( gamma*disc_return_t + rewards[t] )\n",
|
| 829 |
+
"\n",
|
| 830 |
+
" ## standardization of the returns is employed to make training more stable\n",
|
| 831 |
+
" eps = np.finfo(np.float32).eps.item()\n",
|
| 832 |
+
" ## eps is the smallest representable float, which is\n",
|
| 833 |
+
" # added to the standard deviation of the returns to avoid numerical instabilities\n",
|
| 834 |
+
" returns = torch.tensor(returns)\n",
|
| 835 |
+
" returns = (returns - returns.mean()) / (returns.std() + eps)\n",
|
| 836 |
+
"\n",
|
| 837 |
+
" # Line 7:\n",
|
| 838 |
+
" policy_loss = []\n",
|
| 839 |
+
" for log_prob, disc_return in zip(saved_log_probs, returns):\n",
|
| 840 |
+
" policy_loss.append(-log_prob * disc_return)\n",
|
| 841 |
+
" policy_loss = torch.cat(policy_loss).sum()\n",
|
| 842 |
+
"\n",
|
| 843 |
+
" # Line 8: PyTorch prefers gradient descent\n",
|
| 844 |
+
" optimizer.zero_grad()\n",
|
| 845 |
+
" policy_loss.backward()\n",
|
| 846 |
+
" optimizer.step()\n",
|
| 847 |
+
"\n",
|
| 848 |
+
" if i_episode % print_every == 0:\n",
|
| 849 |
+
" print('Episode {}\\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_deque)))\n",
|
| 850 |
+
"\n",
|
| 851 |
+
" return scores"
|
| 852 |
+
]
|
| 853 |
+
},
|
| 854 |
+
{
|
| 855 |
+
"cell_type": "markdown",
|
| 856 |
+
"metadata": {
|
| 857 |
+
"id": "RIWhQyJjfpEt"
|
| 858 |
+
},
|
| 859 |
+
"source": [
|
| 860 |
+
"## Train it\n",
|
| 861 |
+
"- We're now ready to train our agent.\n",
|
| 862 |
+
"- But first, we define a variable containing all the training hyperparameters.\n",
|
| 863 |
+
"- You can change the training parameters (and should 😉)"
|
| 864 |
+
]
|
| 865 |
+
},
|
| 866 |
+
{
|
| 867 |
+
"cell_type": "code",
|
| 868 |
+
"execution_count": null,
|
| 869 |
+
"metadata": {
|
| 870 |
+
"id": "utRe1NgtVBYF"
|
| 871 |
+
},
|
| 872 |
+
"outputs": [],
|
| 873 |
+
"source": [
|
| 874 |
+
"cartpole_hyperparameters = {\n",
|
| 875 |
+
" \"h_size\": 16,\n",
|
| 876 |
+
" \"n_training_episodes\": 1000,\n",
|
| 877 |
+
" \"n_evaluation_episodes\": 10,\n",
|
| 878 |
+
" \"max_t\": 1000,\n",
|
| 879 |
+
" \"gamma\": 1.0,\n",
|
| 880 |
+
" \"lr\": 1e-2,\n",
|
| 881 |
+
" \"env_id\": env_id,\n",
|
| 882 |
+
" \"state_space\": s_size,\n",
|
| 883 |
+
" \"action_space\": a_size,\n",
|
| 884 |
+
"}"
|
| 885 |
+
]
|
| 886 |
+
},
|
| 887 |
+
{
|
| 888 |
+
"cell_type": "code",
|
| 889 |
+
"execution_count": null,
|
| 890 |
+
"metadata": {
|
| 891 |
+
"id": "D3lWyVXBVfl6"
|
| 892 |
+
},
|
| 893 |
+
"outputs": [],
|
| 894 |
+
"source": [
|
| 895 |
+
"# Create policy and place it to the device\n",
|
| 896 |
+
"cartpole_policy = Policy(cartpole_hyperparameters[\"state_space\"], cartpole_hyperparameters[\"action_space\"], cartpole_hyperparameters[\"h_size\"]).to(device)\n",
|
| 897 |
+
"cartpole_optimizer = optim.Adam(cartpole_policy.parameters(), lr=cartpole_hyperparameters[\"lr\"])"
|
| 898 |
+
]
|
| 899 |
+
},
|
| 900 |
+
{
|
| 901 |
+
"cell_type": "code",
|
| 902 |
+
"execution_count": null,
|
| 903 |
+
"metadata": {
|
| 904 |
+
"id": "uGf-hQCnfouB"
|
| 905 |
+
},
|
| 906 |
+
"outputs": [],
|
| 907 |
+
"source": [
|
| 908 |
+
"scores = reinforce(cartpole_policy,\n",
|
| 909 |
+
" cartpole_optimizer,\n",
|
| 910 |
+
" cartpole_hyperparameters[\"n_training_episodes\"],\n",
|
| 911 |
+
" cartpole_hyperparameters[\"max_t\"],\n",
|
| 912 |
+
" cartpole_hyperparameters[\"gamma\"],\n",
|
| 913 |
+
" 100)"
|
| 914 |
+
]
|
| 915 |
+
},
|
| 916 |
+
{
|
| 917 |
+
"cell_type": "markdown",
|
| 918 |
+
"metadata": {
|
| 919 |
+
"id": "Qajj2kXqhB3g"
|
| 920 |
+
},
|
| 921 |
+
"source": [
|
| 922 |
+
"## Define evaluation method 📝\n",
|
| 923 |
+
"- Here we define the evaluation method that we're going to use to test our Reinforce agent."
|
| 924 |
+
]
|
| 925 |
+
},
|
| 926 |
+
{
|
| 927 |
+
"cell_type": "code",
|
| 928 |
+
"execution_count": null,
|
| 929 |
+
"metadata": {
|
| 930 |
+
"id": "3FamHmxyhBEU"
|
| 931 |
+
},
|
| 932 |
+
"outputs": [],
|
| 933 |
+
"source": [
|
| 934 |
+
"def evaluate_agent(env, max_steps, n_eval_episodes, policy):\n",
|
| 935 |
+
" \"\"\"\n",
|
| 936 |
+
" Evaluate the agent for ``n_eval_episodes`` episodes and returns average reward and std of reward.\n",
|
| 937 |
+
" :param env: The evaluation environment\n",
|
| 938 |
+
" :param n_eval_episodes: Number of episode to evaluate the agent\n",
|
| 939 |
+
" :param policy: The Reinforce agent\n",
|
| 940 |
+
" \"\"\"\n",
|
| 941 |
+
" episode_rewards = []\n",
|
| 942 |
+
" for episode in range(n_eval_episodes):\n",
|
| 943 |
+
" state = env.reset()\n",
|
| 944 |
+
" step = 0\n",
|
| 945 |
+
" done = False\n",
|
| 946 |
+
" total_rewards_ep = 0\n",
|
| 947 |
+
"\n",
|
| 948 |
+
" for step in range(max_steps):\n",
|
| 949 |
+
" action, _ = policy.act(state)\n",
|
| 950 |
+
" new_state, reward, done, info = env.step(action)\n",
|
| 951 |
+
" total_rewards_ep += reward\n",
|
| 952 |
+
"\n",
|
| 953 |
+
" if done:\n",
|
| 954 |
+
" break\n",
|
| 955 |
+
" state = new_state\n",
|
| 956 |
+
" episode_rewards.append(total_rewards_ep)\n",
|
| 957 |
+
" mean_reward = np.mean(episode_rewards)\n",
|
| 958 |
+
" std_reward = np.std(episode_rewards)\n",
|
| 959 |
+
"\n",
|
| 960 |
+
" return mean_reward, std_reward"
|
| 961 |
+
]
|
| 962 |
+
},
|
| 963 |
+
{
|
| 964 |
+
"cell_type": "markdown",
|
| 965 |
+
"metadata": {
|
| 966 |
+
"id": "xdH2QCrLTrlT"
|
| 967 |
+
},
|
| 968 |
+
"source": [
|
| 969 |
+
"## Evaluate our agent 📈"
|
| 970 |
+
]
|
| 971 |
+
},
|
| 972 |
+
{
|
| 973 |
+
"cell_type": "code",
|
| 974 |
+
"execution_count": null,
|
| 975 |
+
"metadata": {
|
| 976 |
+
"id": "ohGSXDyHh0xx"
|
| 977 |
+
},
|
| 978 |
+
"outputs": [],
|
| 979 |
+
"source": [
|
| 980 |
+
"evaluate_agent(eval_env,\n",
|
| 981 |
+
" cartpole_hyperparameters[\"max_t\"],\n",
|
| 982 |
+
" cartpole_hyperparameters[\"n_evaluation_episodes\"],\n",
|
| 983 |
+
" cartpole_policy)"
|
| 984 |
+
]
|
| 985 |
+
},
|
| 986 |
+
{
|
| 987 |
+
"cell_type": "markdown",
|
| 988 |
+
"metadata": {
|
| 989 |
+
"id": "7CoeLkQ7TpO8"
|
| 990 |
+
},
|
| 991 |
+
"source": [
|
| 992 |
+
"### Publish our trained model on the Hub 🔥\n",
|
| 993 |
+
"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",
|
| 994 |
+
"\n",
|
| 995 |
+
"Here's an example of a Model Card:\n",
|
| 996 |
+
"\n",
|
| 997 |
+
"<img src=\"https://huggingface.co/datasets/huggingface-deep-rl-course/course-images/resolve/main/en/unit6/modelcard.png\"/>"
|
| 998 |
+
]
|
| 999 |
+
},
|
| 1000 |
+
{
|
| 1001 |
+
"cell_type": "markdown",
|
| 1002 |
+
"metadata": {
|
| 1003 |
+
"id": "Jmhs1k-cftIq"
|
| 1004 |
+
},
|
| 1005 |
+
"source": [
|
| 1006 |
+
"### Push to the Hub\n",
|
| 1007 |
+
"#### Do not modify this code"
|
| 1008 |
+
]
|
| 1009 |
+
},
|
| 1010 |
+
{
|
| 1011 |
+
"cell_type": "code",
|
| 1012 |
+
"source": [
|
| 1013 |
+
"from huggingface_hub import HfApi, snapshot_download\n",
|
| 1014 |
+
"from huggingface_hub.repocard import metadata_eval_result, metadata_save\n",
|
| 1015 |
+
"\n",
|
| 1016 |
+
"from pathlib import Path\n",
|
| 1017 |
+
"import datetime\n",
|
| 1018 |
+
"import json\n",
|
| 1019 |
+
"import imageio\n",
|
| 1020 |
+
"\n",
|
| 1021 |
+
"import tempfile\n",
|
| 1022 |
+
"\n",
|
| 1023 |
+
"import os"
|
| 1024 |
+
],
|
| 1025 |
+
"metadata": {
|
| 1026 |
+
"id": "LIVsvlW_8tcw"
|
| 1027 |
+
},
|
| 1028 |
+
"execution_count": null,
|
| 1029 |
+
"outputs": []
|
| 1030 |
+
},
|
| 1031 |
+
{
|
| 1032 |
+
"cell_type": "code",
|
| 1033 |
+
"execution_count": null,
|
| 1034 |
+
"metadata": {
|
| 1035 |
+
"id": "Lo4JH45if81z"
|
| 1036 |
+
},
|
| 1037 |
+
"outputs": [],
|
| 1038 |
+
"source": [
|
| 1039 |
+
"def record_video(env, policy, out_directory, fps=30):\n",
|
| 1040 |
+
" \"\"\"\n",
|
| 1041 |
+
" Generate a replay video of the agent\n",
|
| 1042 |
+
" :param env\n",
|
| 1043 |
+
" :param Qtable: Qtable of our agent\n",
|
| 1044 |
+
" :param out_directory\n",
|
| 1045 |
+
" :param fps: how many frame per seconds (with taxi-v3 and frozenlake-v1 we use 1)\n",
|
| 1046 |
+
" \"\"\"\n",
|
| 1047 |
+
" images = []\n",
|
| 1048 |
+
" done = False\n",
|
| 1049 |
+
" state = env.reset()\n",
|
| 1050 |
+
" img = env.render(mode='rgb_array')\n",
|
| 1051 |
+
" images.append(img)\n",
|
| 1052 |
+
" while not done:\n",
|
| 1053 |
+
" # Take the action (index) that have the maximum expected future reward given that state\n",
|
| 1054 |
+
" action, _ = policy.act(state)\n",
|
| 1055 |
+
" state, reward, done, info = env.step(action) # We directly put next_state = state for recording logic\n",
|
| 1056 |
+
" img = env.render(mode='rgb_array')\n",
|
| 1057 |
+
" images.append(img)\n",
|
| 1058 |
+
" imageio.mimsave(out_directory, [np.array(img) for i, img in enumerate(images)], fps=fps)"
|
| 1059 |
+
]
|
| 1060 |
+
},
|
| 1061 |
+
{
|
| 1062 |
+
"cell_type": "code",
|
| 1063 |
+
"source": [
|
| 1064 |
+
"def push_to_hub(repo_id,\n",
|
| 1065 |
+
" model,\n",
|
| 1066 |
+
" hyperparameters,\n",
|
| 1067 |
+
" eval_env,\n",
|
| 1068 |
+
" video_fps=30\n",
|
| 1069 |
+
" ):\n",
|
| 1070 |
+
" \"\"\"\n",
|
| 1071 |
+
" Evaluate, Generate a video and Upload a model to Hugging Face Hub.\n",
|
| 1072 |
+
" This method does the complete pipeline:\n",
|
| 1073 |
+
" - It evaluates the model\n",
|
| 1074 |
+
" - It generates the model card\n",
|
| 1075 |
+
" - It generates a replay video of the agent\n",
|
| 1076 |
+
" - It pushes everything to the Hub\n",
|
| 1077 |
+
"\n",
|
| 1078 |
+
" :param repo_id: repo_id: id of the model repository from the Hugging Face Hub\n",
|
| 1079 |
+
" :param model: the pytorch model we want to save\n",
|
| 1080 |
+
" :param hyperparameters: training hyperparameters\n",
|
| 1081 |
+
" :param eval_env: evaluation environment\n",
|
| 1082 |
+
" :param video_fps: how many frame per seconds to record our video replay\n",
|
| 1083 |
+
" \"\"\"\n",
|
| 1084 |
+
"\n",
|
| 1085 |
+
" _, repo_name = repo_id.split(\"/\")\n",
|
| 1086 |
+
" api = HfApi()\n",
|
| 1087 |
+
"\n",
|
| 1088 |
+
" # Step 1: Create the repo\n",
|
| 1089 |
+
" repo_url = api.create_repo(\n",
|
| 1090 |
+
" repo_id=repo_id,\n",
|
| 1091 |
+
" exist_ok=True,\n",
|
| 1092 |
+
" )\n",
|
| 1093 |
+
"\n",
|
| 1094 |
+
" with tempfile.TemporaryDirectory() as tmpdirname:\n",
|
| 1095 |
+
" local_directory = Path(tmpdirname)\n",
|
| 1096 |
+
"\n",
|
| 1097 |
+
" # Step 2: Save the model\n",
|
| 1098 |
+
" torch.save(model, local_directory / \"model.pt\")\n",
|
| 1099 |
+
"\n",
|
| 1100 |
+
" # Step 3: Save the hyperparameters to JSON\n",
|
| 1101 |
+
" with open(local_directory / \"hyperparameters.json\", \"w\") as outfile:\n",
|
| 1102 |
+
" json.dump(hyperparameters, outfile)\n",
|
| 1103 |
+
"\n",
|
| 1104 |
+
" # Step 4: Evaluate the model and build JSON\n",
|
| 1105 |
+
" mean_reward, std_reward = evaluate_agent(eval_env,\n",
|
| 1106 |
+
" hyperparameters[\"max_t\"],\n",
|
| 1107 |
+
" hyperparameters[\"n_evaluation_episodes\"],\n",
|
| 1108 |
+
" model)\n",
|
| 1109 |
+
" # Get datetime\n",
|
| 1110 |
+
" eval_datetime = datetime.datetime.now()\n",
|
| 1111 |
+
" eval_form_datetime = eval_datetime.isoformat()\n",
|
| 1112 |
+
"\n",
|
| 1113 |
+
" evaluate_data = {\n",
|
| 1114 |
+
" \"env_id\": hyperparameters[\"env_id\"],\n",
|
| 1115 |
+
" \"mean_reward\": mean_reward,\n",
|
| 1116 |
+
" \"n_evaluation_episodes\": hyperparameters[\"n_evaluation_episodes\"],\n",
|
| 1117 |
+
" \"eval_datetime\": eval_form_datetime,\n",
|
| 1118 |
+
" }\n",
|
| 1119 |
+
"\n",
|
| 1120 |
+
" # Write a JSON file\n",
|
| 1121 |
+
" with open(local_directory / \"results.json\", \"w\") as outfile:\n",
|
| 1122 |
+
" json.dump(evaluate_data, outfile)\n",
|
| 1123 |
+
"\n",
|
| 1124 |
+
" # Step 5: Create the model card\n",
|
| 1125 |
+
" env_name = hyperparameters[\"env_id\"]\n",
|
| 1126 |
+
"\n",
|
| 1127 |
+
" metadata = {}\n",
|
| 1128 |
+
" metadata[\"tags\"] = [\n",
|
| 1129 |
+
" env_name,\n",
|
| 1130 |
+
" \"reinforce\",\n",
|
| 1131 |
+
" \"reinforcement-learning\",\n",
|
| 1132 |
+
" \"custom-implementation\",\n",
|
| 1133 |
+
" \"deep-rl-class\"\n",
|
| 1134 |
+
" ]\n",
|
| 1135 |
+
"\n",
|
| 1136 |
+
" # Add metrics\n",
|
| 1137 |
+
" eval = metadata_eval_result(\n",
|
| 1138 |
+
" model_pretty_name=repo_name,\n",
|
| 1139 |
+
" task_pretty_name=\"reinforcement-learning\",\n",
|
| 1140 |
+
" task_id=\"reinforcement-learning\",\n",
|
| 1141 |
+
" metrics_pretty_name=\"mean_reward\",\n",
|
| 1142 |
+
" metrics_id=\"mean_reward\",\n",
|
| 1143 |
+
" metrics_value=f\"{mean_reward:.2f} +/- {std_reward:.2f}\",\n",
|
| 1144 |
+
" dataset_pretty_name=env_name,\n",
|
| 1145 |
+
" dataset_id=env_name,\n",
|
| 1146 |
+
" )\n",
|
| 1147 |
+
"\n",
|
| 1148 |
+
" # Merges both dictionaries\n",
|
| 1149 |
+
" metadata = {**metadata, **eval}\n",
|
| 1150 |
+
"\n",
|
| 1151 |
+
" model_card = f\"\"\"\n",
|
| 1152 |
+
" # **Reinforce** Agent playing **{env_id}**\n",
|
| 1153 |
+
" This is a trained model of a **Reinforce** agent playing **{env_id}** .\n",
|
| 1154 |
+
" 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",
|
| 1155 |
+
" \"\"\"\n",
|
| 1156 |
+
"\n",
|
| 1157 |
+
" readme_path = local_directory / \"README.md\"\n",
|
| 1158 |
+
" readme = \"\"\n",
|
| 1159 |
+
" if readme_path.exists():\n",
|
| 1160 |
+
" with readme_path.open(\"r\", encoding=\"utf8\") as f:\n",
|
| 1161 |
+
" readme = f.read()\n",
|
| 1162 |
+
" else:\n",
|
| 1163 |
+
" readme = model_card\n",
|
| 1164 |
+
"\n",
|
| 1165 |
+
" with readme_path.open(\"w\", encoding=\"utf-8\") as f:\n",
|
| 1166 |
+
" f.write(readme)\n",
|
| 1167 |
+
"\n",
|
| 1168 |
+
" # Save our metrics to Readme metadata\n",
|
| 1169 |
+
" metadata_save(readme_path, metadata)\n",
|
| 1170 |
+
"\n",
|
| 1171 |
+
" # Step 6: Record a video\n",
|
| 1172 |
+
" video_path = local_directory / \"replay.mp4\"\n",
|
| 1173 |
+
" record_video(env, model, video_path, video_fps)\n",
|
| 1174 |
+
"\n",
|
| 1175 |
+
" # Step 7. Push everything to the Hub\n",
|
| 1176 |
+
" api.upload_folder(\n",
|
| 1177 |
+
" repo_id=repo_id,\n",
|
| 1178 |
+
" folder_path=local_directory,\n",
|
| 1179 |
+
" path_in_repo=\".\",\n",
|
| 1180 |
+
" )\n",
|
| 1181 |
+
"\n",
|
| 1182 |
+
" print(f\"Your model is pushed to the Hub. You can view your model here: {repo_url}\")"
|
| 1183 |
+
],
|
| 1184 |
+
"metadata": {
|
| 1185 |
+
"id": "_TPdq47D7_f_"
|
| 1186 |
+
},
|
| 1187 |
+
"execution_count": null,
|
| 1188 |
+
"outputs": []
|
| 1189 |
+
},
|
| 1190 |
+
{
|
| 1191 |
+
"cell_type": "markdown",
|
| 1192 |
+
"metadata": {
|
| 1193 |
+
"id": "w17w8CxzoURM"
|
| 1194 |
+
},
|
| 1195 |
+
"source": [
|
| 1196 |
+
"### .\n",
|
| 1197 |
+
"\n",
|
| 1198 |
+
"By using `push_to_hub` **you evaluate, record a replay, generate a model card of your agent and push it to the Hub**.\n",
|
| 1199 |
+
"\n",
|
| 1200 |
+
"This way:\n",
|
| 1201 |
+
"- You can **showcase our work** 🔥\n",
|
| 1202 |
+
"- You can **visualize your agent playing** 👀\n",
|
| 1203 |
+
"- You can **share with the community an agent that others can use** 💾\n",
|
| 1204 |
+
"- 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"
|
| 1205 |
+
]
|
| 1206 |
+
},
|
| 1207 |
+
{
|
| 1208 |
+
"cell_type": "markdown",
|
| 1209 |
+
"metadata": {
|
| 1210 |
+
"id": "cWnFC0iZooTw"
|
| 1211 |
+
},
|
| 1212 |
+
"source": [
|
| 1213 |
+
"To be able to share your model with the community there are three more steps to follow:\n",
|
| 1214 |
+
"\n",
|
| 1215 |
+
"1️⃣ (If it's not already done) create an account to HF ➡ https://huggingface.co/join\n",
|
| 1216 |
+
"\n",
|
| 1217 |
+
"2️⃣ Sign in and then, you need to store your authentication token from the Hugging Face website.\n",
|
| 1218 |
+
"- Create a new token (https://huggingface.co/settings/tokens) **with write role**\n",
|
| 1219 |
+
"\n",
|
| 1220 |
+
"\n",
|
| 1221 |
+
"<img src=\"https://huggingface.co/datasets/huggingface-deep-rl-course/course-images/resolve/main/en/notebooks/create-token.jpg\" alt=\"Create HF Token\">\n"
|
| 1222 |
+
]
|
| 1223 |
+
},
|
| 1224 |
+
{
|
| 1225 |
+
"cell_type": "code",
|
| 1226 |
+
"execution_count": null,
|
| 1227 |
+
"metadata": {
|
| 1228 |
+
"id": "QB5nIcxR8paT"
|
| 1229 |
+
},
|
| 1230 |
+
"outputs": [],
|
| 1231 |
+
"source": [
|
| 1232 |
+
"notebook_login()"
|
| 1233 |
+
]
|
| 1234 |
+
},
|
| 1235 |
+
{
|
| 1236 |
+
"cell_type": "markdown",
|
| 1237 |
+
"metadata": {
|
| 1238 |
+
"id": "GyWc1x3-o3xG"
|
| 1239 |
+
},
|
| 1240 |
+
"source": [
|
| 1241 |
+
"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`)"
|
| 1242 |
+
]
|
| 1243 |
+
},
|
| 1244 |
+
{
|
| 1245 |
+
"cell_type": "markdown",
|
| 1246 |
+
"metadata": {
|
| 1247 |
+
"id": "F-D-zhbRoeOm"
|
| 1248 |
+
},
|
| 1249 |
+
"source": [
|
| 1250 |
+
"3️⃣ We're now ready to push our trained agent to the 🤗 Hub 🔥 using `package_to_hub()` function"
|
| 1251 |
+
]
|
| 1252 |
+
},
|
| 1253 |
+
{
|
| 1254 |
+
"cell_type": "code",
|
| 1255 |
+
"execution_count": null,
|
| 1256 |
+
"metadata": {
|
| 1257 |
+
"id": "UNwkTS65Uq3Q"
|
| 1258 |
+
},
|
| 1259 |
+
"outputs": [],
|
| 1260 |
+
"source": [
|
| 1261 |
+
"repo_id = \"\" #TODO Define your repo id {username/Reinforce-{model-id}}\n",
|
| 1262 |
+
"push_to_hub(repo_id,\n",
|
| 1263 |
+
" cartpole_policy, # The model we want to save\n",
|
| 1264 |
+
" cartpole_hyperparameters, # Hyperparameters\n",
|
| 1265 |
+
" eval_env, # Evaluation environment\n",
|
| 1266 |
+
" video_fps=30\n",
|
| 1267 |
+
" )"
|
| 1268 |
+
]
|
| 1269 |
+
},
|
| 1270 |
+
{
|
| 1271 |
+
"cell_type": "markdown",
|
| 1272 |
+
"metadata": {
|
| 1273 |
+
"id": "jrnuKH1gYZSz"
|
| 1274 |
+
},
|
| 1275 |
+
"source": [
|
| 1276 |
+
"Now that we try the robustness of our implementation, let's try a more complex environment: PixelCopter 🚁\n",
|
| 1277 |
+
"\n",
|
| 1278 |
+
"\n"
|
| 1279 |
+
]
|
| 1280 |
+
},
|
| 1281 |
+
{
|
| 1282 |
+
"cell_type": "markdown",
|
| 1283 |
+
"source": [
|
| 1284 |
+
"## Second agent: PixelCopter 🚁\n",
|
| 1285 |
+
"\n",
|
| 1286 |
+
"### Study the PixelCopter environment 👀\n",
|
| 1287 |
+
"- [The Environment documentation](https://pygame-learning-environment.readthedocs.io/en/latest/user/games/pixelcopter.html)\n"
|
| 1288 |
+
],
|
| 1289 |
+
"metadata": {
|
| 1290 |
+
"id": "JNLVmKKVKA6j"
|
| 1291 |
+
}
|
| 1292 |
+
},
|
| 1293 |
+
{
|
| 1294 |
+
"cell_type": "code",
|
| 1295 |
+
"execution_count": null,
|
| 1296 |
+
"metadata": {
|
| 1297 |
+
"id": "JBSc8mlfyin3"
|
| 1298 |
+
},
|
| 1299 |
+
"outputs": [],
|
| 1300 |
+
"source": [
|
| 1301 |
+
"env_id = \"Pixelcopter-PLE-v0\"\n",
|
| 1302 |
+
"env = gym.make(env_id)\n",
|
| 1303 |
+
"eval_env = gym.make(env_id)\n",
|
| 1304 |
+
"s_size = env.observation_space.shape[0]\n",
|
| 1305 |
+
"a_size = env.action_space.n"
|
| 1306 |
+
]
|
| 1307 |
+
},
|
| 1308 |
+
{
|
| 1309 |
+
"cell_type": "code",
|
| 1310 |
+
"source": [
|
| 1311 |
+
"print(\"_____OBSERVATION SPACE_____ \\n\")\n",
|
| 1312 |
+
"print(\"The State Space is: \", s_size)\n",
|
| 1313 |
+
"print(\"Sample observation\", env.observation_space.sample()) # Get a random observation"
|
| 1314 |
+
],
|
| 1315 |
+
"metadata": {
|
| 1316 |
+
"id": "L5u_zAHsKBy7"
|
| 1317 |
+
},
|
| 1318 |
+
"execution_count": null,
|
| 1319 |
+
"outputs": []
|
| 1320 |
+
},
|
| 1321 |
+
{
|
| 1322 |
+
"cell_type": "code",
|
| 1323 |
+
"source": [
|
| 1324 |
+
"print(\"\\n _____ACTION SPACE_____ \\n\")\n",
|
| 1325 |
+
"print(\"The Action Space is: \", a_size)\n",
|
| 1326 |
+
"print(\"Action Space Sample\", env.action_space.sample()) # Take a random action"
|
| 1327 |
+
],
|
| 1328 |
+
"metadata": {
|
| 1329 |
+
"id": "D7yJM9YXKNbq"
|
| 1330 |
+
},
|
| 1331 |
+
"execution_count": null,
|
| 1332 |
+
"outputs": []
|
| 1333 |
+
},
|
| 1334 |
+
{
|
| 1335 |
+
"cell_type": "markdown",
|
| 1336 |
+
"metadata": {
|
| 1337 |
+
"id": "NNWvlyvzalXr"
|
| 1338 |
+
},
|
| 1339 |
+
"source": [
|
| 1340 |
+
"The observation space (7) 👀:\n",
|
| 1341 |
+
"- player y position\n",
|
| 1342 |
+
"- player velocity\n",
|
| 1343 |
+
"- player distance to floor\n",
|
| 1344 |
+
"- player distance to ceiling\n",
|
| 1345 |
+
"- next block x distance to player\n",
|
| 1346 |
+
"- next blocks top y location\n",
|
| 1347 |
+
"- next blocks bottom y location\n",
|
| 1348 |
+
"\n",
|
| 1349 |
+
"The action space(2) 🎮:\n",
|
| 1350 |
+
"- Up (press accelerator)\n",
|
| 1351 |
+
"- Do nothing (don't press accelerator)\n",
|
| 1352 |
+
"\n",
|
| 1353 |
+
"The reward function 💰:\n",
|
| 1354 |
+
"- 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."
|
| 1355 |
+
]
|
| 1356 |
+
},
|
| 1357 |
+
{
|
| 1358 |
+
"cell_type": "markdown",
|
| 1359 |
+
"source": [
|
| 1360 |
+
"### Define the new Policy 🧠\n",
|
| 1361 |
+
"- We need to have a deeper neural network since the environment is more complex"
|
| 1362 |
+
],
|
| 1363 |
+
"metadata": {
|
| 1364 |
+
"id": "aV1466QP8crz"
|
| 1365 |
+
}
|
| 1366 |
+
},
|
| 1367 |
+
{
|
| 1368 |
+
"cell_type": "code",
|
| 1369 |
+
"execution_count": null,
|
| 1370 |
+
"metadata": {
|
| 1371 |
+
"id": "I1eBkCiX2X_S"
|
| 1372 |
+
},
|
| 1373 |
+
"outputs": [],
|
| 1374 |
+
"source": [
|
| 1375 |
+
"class Policy(nn.Module):\n",
|
| 1376 |
+
" def __init__(self, s_size, a_size, h_size):\n",
|
| 1377 |
+
" super(Policy, self).__init__()\n",
|
| 1378 |
+
" # Define the three layers here\n",
|
| 1379 |
+
"\n",
|
| 1380 |
+
" def forward(self, x):\n",
|
| 1381 |
+
" # Define the forward process here\n",
|
| 1382 |
+
" return F.softmax(x, dim=1)\n",
|
| 1383 |
+
"\n",
|
| 1384 |
+
" def act(self, state):\n",
|
| 1385 |
+
" state = torch.from_numpy(state).float().unsqueeze(0).to(device)\n",
|
| 1386 |
+
" probs = self.forward(state).cpu()\n",
|
| 1387 |
+
" m = Categorical(probs)\n",
|
| 1388 |
+
" action = m.sample()\n",
|
| 1389 |
+
" return action.item(), m.log_prob(action)"
|
| 1390 |
+
]
|
| 1391 |
+
},
|
| 1392 |
+
{
|
| 1393 |
+
"cell_type": "markdown",
|
| 1394 |
+
"source": [
|
| 1395 |
+
"#### Solution"
|
| 1396 |
+
],
|
| 1397 |
+
"metadata": {
|
| 1398 |
+
"id": "47iuAFqV8Ws-"
|
| 1399 |
+
}
|
| 1400 |
+
},
|
| 1401 |
+
{
|
| 1402 |
+
"cell_type": "code",
|
| 1403 |
+
"source": [
|
| 1404 |
+
"class Policy(nn.Module):\n",
|
| 1405 |
+
" def __init__(self, s_size, a_size, h_size):\n",
|
| 1406 |
+
" super(Policy, self).__init__()\n",
|
| 1407 |
+
" self.fc1 = nn.Linear(s_size, h_size)\n",
|
| 1408 |
+
" self.fc2 = nn.Linear(h_size, h_size*2)\n",
|
| 1409 |
+
" self.fc3 = nn.Linear(h_size*2, a_size)\n",
|
| 1410 |
+
"\n",
|
| 1411 |
+
" def forward(self, x):\n",
|
| 1412 |
+
" x = F.relu(self.fc1(x))\n",
|
| 1413 |
+
" x = F.relu(self.fc2(x))\n",
|
| 1414 |
+
" x = self.fc3(x)\n",
|
| 1415 |
+
" return F.softmax(x, dim=1)\n",
|
| 1416 |
+
"\n",
|
| 1417 |
+
" def act(self, state):\n",
|
| 1418 |
+
" state = torch.from_numpy(state).float().unsqueeze(0).to(device)\n",
|
| 1419 |
+
" probs = self.forward(state).cpu()\n",
|
| 1420 |
+
" m = Categorical(probs)\n",
|
| 1421 |
+
" action = m.sample()\n",
|
| 1422 |
+
" return action.item(), m.log_prob(action)"
|
| 1423 |
+
],
|
| 1424 |
+
"metadata": {
|
| 1425 |
+
"id": "wrNuVcHC8Xu7"
|
| 1426 |
+
},
|
| 1427 |
+
"execution_count": null,
|
| 1428 |
+
"outputs": []
|
| 1429 |
+
},
|
| 1430 |
+
{
|
| 1431 |
+
"cell_type": "markdown",
|
| 1432 |
+
"metadata": {
|
| 1433 |
+
"id": "SM1QiGCSbBkM"
|
| 1434 |
+
},
|
| 1435 |
+
"source": [
|
| 1436 |
+
"### Define the hyperparameters ⚙️\n",
|
| 1437 |
+
"- Because this environment is more complex.\n",
|
| 1438 |
+
"- Especially for the hidden size, we need more neurons."
|
| 1439 |
+
]
|
| 1440 |
+
},
|
| 1441 |
+
{
|
| 1442 |
+
"cell_type": "code",
|
| 1443 |
+
"execution_count": null,
|
| 1444 |
+
"metadata": {
|
| 1445 |
+
"id": "y0uujOR_ypB6"
|
| 1446 |
+
},
|
| 1447 |
+
"outputs": [],
|
| 1448 |
+
"source": [
|
| 1449 |
+
"pixelcopter_hyperparameters = {\n",
|
| 1450 |
+
" \"h_size\": 64,\n",
|
| 1451 |
+
" \"n_training_episodes\": 50000,\n",
|
| 1452 |
+
" \"n_evaluation_episodes\": 10,\n",
|
| 1453 |
+
" \"max_t\": 10000,\n",
|
| 1454 |
+
" \"gamma\": 0.99,\n",
|
| 1455 |
+
" \"lr\": 1e-4,\n",
|
| 1456 |
+
" \"env_id\": env_id,\n",
|
| 1457 |
+
" \"state_space\": s_size,\n",
|
| 1458 |
+
" \"action_space\": a_size,\n",
|
| 1459 |
+
"}"
|
| 1460 |
+
]
|
| 1461 |
+
},
|
| 1462 |
+
{
|
| 1463 |
+
"cell_type": "markdown",
|
| 1464 |
+
"source": [
|
| 1465 |
+
"### Train it\n",
|
| 1466 |
+
"- We're now ready to train our agent 🔥."
|
| 1467 |
+
],
|
| 1468 |
+
"metadata": {
|
| 1469 |
+
"id": "wyvXTJWm9GJG"
|
| 1470 |
+
}
|
| 1471 |
+
},
|
| 1472 |
+
{
|
| 1473 |
+
"cell_type": "code",
|
| 1474 |
+
"execution_count": null,
|
| 1475 |
+
"metadata": {
|
| 1476 |
+
"id": "7mM2P_ckysFE"
|
| 1477 |
+
},
|
| 1478 |
+
"outputs": [],
|
| 1479 |
+
"source": [
|
| 1480 |
+
"# Create policy and place it to the device\n",
|
| 1481 |
+
"# torch.manual_seed(50)\n",
|
| 1482 |
+
"pixelcopter_policy = Policy(pixelcopter_hyperparameters[\"state_space\"], pixelcopter_hyperparameters[\"action_space\"], pixelcopter_hyperparameters[\"h_size\"]).to(device)\n",
|
| 1483 |
+
"pixelcopter_optimizer = optim.Adam(pixelcopter_policy.parameters(), lr=pixelcopter_hyperparameters[\"lr\"])"
|
| 1484 |
+
]
|
| 1485 |
+
},
|
| 1486 |
+
{
|
| 1487 |
+
"cell_type": "code",
|
| 1488 |
+
"execution_count": null,
|
| 1489 |
+
"metadata": {
|
| 1490 |
+
"id": "v1HEqP-fy-Rf"
|
| 1491 |
+
},
|
| 1492 |
+
"outputs": [],
|
| 1493 |
+
"source": [
|
| 1494 |
+
"scores = reinforce(pixelcopter_policy,\n",
|
| 1495 |
+
" pixelcopter_optimizer,\n",
|
| 1496 |
+
" pixelcopter_hyperparameters[\"n_training_episodes\"],\n",
|
| 1497 |
+
" pixelcopter_hyperparameters[\"max_t\"],\n",
|
| 1498 |
+
" pixelcopter_hyperparameters[\"gamma\"],\n",
|
| 1499 |
+
" 1000)"
|
| 1500 |
+
]
|
| 1501 |
+
},
|
| 1502 |
+
{
|
| 1503 |
+
"cell_type": "markdown",
|
| 1504 |
+
"source": [
|
| 1505 |
+
"### Publish our trained model on the Hub 🔥"
|
| 1506 |
+
],
|
| 1507 |
+
"metadata": {
|
| 1508 |
+
"id": "8kwFQ-Ip85BE"
|
| 1509 |
+
}
|
| 1510 |
+
},
|
| 1511 |
+
{
|
| 1512 |
+
"cell_type": "code",
|
| 1513 |
+
"source": [
|
| 1514 |
+
"repo_id = \"\" #TODO Define your repo id {username/Reinforce-{model-id}}\n",
|
| 1515 |
+
"push_to_hub(repo_id,\n",
|
| 1516 |
+
" pixelcopter_policy, # The model we want to save\n",
|
| 1517 |
+
" pixelcopter_hyperparameters, # Hyperparameters\n",
|
| 1518 |
+
" eval_env, # Evaluation environment\n",
|
| 1519 |
+
" video_fps=30\n",
|
| 1520 |
+
" )"
|
| 1521 |
+
],
|
| 1522 |
+
"metadata": {
|
| 1523 |
+
"id": "6PtB7LRbTKWK"
|
| 1524 |
+
},
|
| 1525 |
+
"execution_count": null,
|
| 1526 |
+
"outputs": []
|
| 1527 |
+
},
|
| 1528 |
+
{
|
| 1529 |
+
"cell_type": "markdown",
|
| 1530 |
+
"metadata": {
|
| 1531 |
+
"id": "7VDcJ29FcOyb"
|
| 1532 |
+
},
|
| 1533 |
+
"source": [
|
| 1534 |
+
"## Some additional challenges 🏆\n",
|
| 1535 |
+
"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",
|
| 1536 |
+
"\n",
|
| 1537 |
+
"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",
|
| 1538 |
+
"\n",
|
| 1539 |
+
"Here are some ideas to achieve so:\n",
|
| 1540 |
+
"* Train more steps\n",
|
| 1541 |
+
"* Try different hyperparameters by looking at what your classmates have done 👉 https://huggingface.co/models?other=reinforce\n",
|
| 1542 |
+
"* **Push your new trained model** on the Hub 🔥\n",
|
| 1543 |
+
"* **Improving the implementation for more complex environments** (for instance, what about changing the network to a Convolutional Neural Network to handle\n",
|
| 1544 |
+
"frames as observation)?"
|
| 1545 |
+
]
|
| 1546 |
+
},
|
| 1547 |
+
{
|
| 1548 |
+
"cell_type": "markdown",
|
| 1549 |
+
"metadata": {
|
| 1550 |
+
"id": "x62pP0PHdA-y"
|
| 1551 |
+
},
|
| 1552 |
+
"source": [
|
| 1553 |
+
"________________________________________________________________________\n",
|
| 1554 |
+
"\n",
|
| 1555 |
+
"**Congrats on finishing this unit**! There was a lot of information.\n",
|
| 1556 |
+
"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",
|
| 1557 |
+
"\n",
|
| 1558 |
+
"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",
|
| 1559 |
+
"frames as observation)?\n",
|
| 1560 |
+
"\n",
|
| 1561 |
+
"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",
|
| 1562 |
+
"to compete against other agents in a snowball fight and a soccer game.**\n",
|
| 1563 |
+
"\n",
|
| 1564 |
+
"Sounds fun? See you next time!\n",
|
| 1565 |
+
"\n",
|
| 1566 |
+
"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",
|
| 1567 |
+
"\n",
|
| 1568 |
+
"See you in Unit 5! 🔥\n",
|
| 1569 |
+
"\n",
|
| 1570 |
+
"### Keep Learning, stay awesome 🤗\n",
|
| 1571 |
+
"\n"
|
| 1572 |
+
]
|
| 1573 |
+
}
|
| 1574 |
+
],
|
| 1575 |
+
"metadata": {
|
| 1576 |
+
"accelerator": "GPU",
|
| 1577 |
+
"colab": {
|
| 1578 |
+
"private_outputs": true,
|
| 1579 |
+
"provenance": [],
|
| 1580 |
+
"collapsed_sections": [
|
| 1581 |
+
"BPLwsPajb1f8",
|
| 1582 |
+
"L_WSo0VUV99t",
|
| 1583 |
+
"mjY-eq3eWh9O",
|
| 1584 |
+
"JoTC9o2SczNn",
|
| 1585 |
+
"gfGJNZBUP7Vn",
|
| 1586 |
+
"YB0Cxrw1StrP",
|
| 1587 |
+
"47iuAFqV8Ws-",
|
| 1588 |
+
"x62pP0PHdA-y"
|
| 1589 |
+
]
|
| 1590 |
+
},
|
| 1591 |
+
"gpuClass": "standard",
|
| 1592 |
+
"kernelspec": {
|
| 1593 |
+
"display_name": "Python 3 (ipykernel)",
|
| 1594 |
+
"language": "python",
|
| 1595 |
+
"name": "python3"
|
| 1596 |
+
},
|
| 1597 |
+
"language_info": {
|
| 1598 |
+
"codemirror_mode": {
|
| 1599 |
+
"name": "ipython",
|
| 1600 |
+
"version": 3
|
| 1601 |
+
},
|
| 1602 |
+
"file_extension": ".py",
|
| 1603 |
+
"mimetype": "text/x-python",
|
| 1604 |
+
"name": "python",
|
| 1605 |
+
"nbconvert_exporter": "python",
|
| 1606 |
+
"pygments_lexer": "ipython3",
|
| 1607 |
+
"version": "3.8.10"
|
| 1608 |
+
}
|
| 1609 |
+
},
|
| 1610 |
+
"nbformat": 4,
|
| 1611 |
+
"nbformat_minor": 0
|
| 1612 |
+
}
|