File size: 11,698 Bytes
27b8491
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/hanbk/torch_venv/lib/python3.8/site-packages/IPython/core/display.py:419: UserWarning: Consider using IPython.display.IFrame instead\n",
      "  warnings.warn(\"Consider using IPython.display.IFrame instead\")\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/MEt6rrxH8W4\" title=\"YouTube video player\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from IPython.display import HTML\n",
    "\n",
    "HTML(\n",
    "    '<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/MEt6rrxH8W4\" title=\"YouTube video player\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe>'\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import argparse\n",
    "import os\n",
    "import random\n",
    "import time\n",
    "from distutils.util import strtobool\n",
    "\n",
    "import gym\n",
    "import numpy as np\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.optim as optim\n",
    "from torch.distributions.categorical import Categorical\n",
    "from torch.utils.tensorboard import SummaryWriter\n",
    "\n",
    "from huggingface_hub import HfApi, upload_folder\n",
    "from huggingface_hub.repocard import metadata_eval_result, metadata_save\n",
    "\n",
    "from pathlib import Path\n",
    "import datetime\n",
    "import tempfile\n",
    "import json\n",
    "import shutil\n",
    "import imageio\n",
    "\n",
    "from wasabi import Printer\n",
    "\n",
    "msg = Printer()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def parse_args():\n",
    "    # fmt: off\n",
    "    parser = argparse.ArgumentParser()\n",
    "    parser.add_argument(\"--exp-name\", type=str, default=os.path.basename(__file__).rstrip(\".py\"),\n",
    "        help=\"the name of this experiment\")\n",
    "    parser.add_argument(\"--seed\", type=int, default=1,\n",
    "        help=\"seed of the experiment\")\n",
    "    parser.add_argument(\"--torch-deterministic\", type=lambda x: bool(strtobool(x)), default=True, nargs=\"?\", const=True,\n",
    "        help=\"if toggled, `torch.backends.cudnn.deterministic=False`\")\n",
    "    parser.add_argument(\"--cuda\", type=lambda x: bool(strtobool(x)), default=True, nargs=\"?\", const=True,\n",
    "        help=\"if toggled, cuda will be enabled by default\")\n",
    "    parser.add_argument(\"--track\", type=lambda x: bool(strtobool(x)), default=False, nargs=\"?\", const=True,\n",
    "        help=\"if toggled, this experiment will be tracked with Weights and Biases\")\n",
    "    parser.add_argument(\"--wandb-project-name\", type=str, default=\"cleanRL\",\n",
    "        help=\"the wandb's project name\")\n",
    "    parser.add_argument(\"--wandb-entity\", type=str, default=None,\n",
    "        help=\"the entity (team) of wandb's project\")\n",
    "    parser.add_argument(\"--capture-video\", type=lambda x: bool(strtobool(x)), default=False, nargs=\"?\", const=True,\n",
    "        help=\"weather to capture videos of the agent performances (check out `videos` folder)\")\n",
    "\n",
    "    # Algorithm specific arguments\n",
    "    parser.add_argument(\"--env-id\", type=str, default=\"CartPole-v1\",\n",
    "        help=\"the id of the environment\")\n",
    "    parser.add_argument(\"--total-timesteps\", type=int, default=50000,\n",
    "        help=\"total timesteps of the experiments\")\n",
    "    parser.add_argument(\"--learning-rate\", type=float, default=2.5e-4,\n",
    "        help=\"the learning rate of the optimizer\")\n",
    "    parser.add_argument(\"--num-envs\", type=int, default=4,\n",
    "        help=\"the number of parallel game environments\")\n",
    "    parser.add_argument(\"--num-steps\", type=int, default=128,\n",
    "        help=\"the number of steps to run in each environment per policy rollout\")\n",
    "    parser.add_argument(\"--anneal-lr\", type=lambda x: bool(strtobool(x)), default=True, nargs=\"?\", const=True,\n",
    "        help=\"Toggle learning rate annealing for policy and value networks\")\n",
    "    parser.add_argument(\"--gae\", type=lambda x: bool(strtobool(x)), default=True, nargs=\"?\", const=True,\n",
    "        help=\"Use GAE for advantage computation\")\n",
    "    parser.add_argument(\"--gamma\", type=float, default=0.99,\n",
    "        help=\"the discount factor gamma\")\n",
    "    parser.add_argument(\"--gae-lambda\", type=float, default=0.95,\n",
    "        help=\"the lambda for the general advantage estimation\")\n",
    "    parser.add_argument(\"--num-minibatches\", type=int, default=4,\n",
    "        help=\"the number of mini-batches\")\n",
    "    parser.add_argument(\"--update-epochs\", type=int, default=4,\n",
    "        help=\"the K epochs to update the policy\")\n",
    "    parser.add_argument(\"--norm-adv\", type=lambda x: bool(strtobool(x)), default=True, nargs=\"?\", const=True,\n",
    "        help=\"Toggles advantages normalization\")\n",
    "    parser.add_argument(\"--clip-coef\", type=float, default=0.2,\n",
    "        help=\"the surrogate clipping coefficient\")\n",
    "    parser.add_argument(\"--clip-vloss\", type=lambda x: bool(strtobool(x)), default=True, nargs=\"?\", const=True,\n",
    "        help=\"Toggles whether or not to use a clipped loss for the value function, as per the paper.\")\n",
    "    parser.add_argument(\"--ent-coef\", type=float, default=0.01,\n",
    "        help=\"coefficient of the entropy\")\n",
    "    parser.add_argument(\"--vf-coef\", type=float, default=0.5,\n",
    "        help=\"coefficient of the value function\")\n",
    "    parser.add_argument(\"--max-grad-norm\", type=float, default=0.5,\n",
    "        help=\"the maximum norm for the gradient clipping\")\n",
    "    parser.add_argument(\"--target-kl\", type=float, default=None,\n",
    "        help=\"the target KL divergence threshold\")\n",
    "\n",
    "    # Adding HuggingFace argument\n",
    "    parser.add_argument(\"--repo-id\", type=str, default=\"ThomasSimonini/ppo-CartPole-v1\", help=\"id of the model repository from the Hugging Face Hub {username/repo_name}\")\n",
    "\n",
    "    args = parser.parse_args()\n",
    "    args.batch_size = int(args.num_envs * args.num_steps)\n",
    "    args.minibatch_size = int(args.batch_size // args.num_minibatches)\n",
    "    # fmt: on\n",
    "    return args"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def package_to_hub(\n",
    "    repo_id,\n",
    "    model,\n",
    "    hyperparameters,\n",
    "    eval_env,\n",
    "    video_fps=30,\n",
    "    commit_message=\"Push agent to the Hub\",\n",
    "    token=None,\n",
    "    logs=None,\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",
    "    :param repo_id: id of the model repository from the Hugging Face Hub\n",
    "    :param model: trained model\n",
    "    :param eval_env: environment used to evaluate the agent\n",
    "    :param fps: number of fps for rendering the video\n",
    "    :param commit_message: commit message\n",
    "    :param logs: directory on local machine of tensorboard logs you'd like to upload\n",
    "    \"\"\"\n",
    "    msg.info(\n",
    "        \"This function will save, evaluate, generate a video of your agent, \"\n",
    "        \"create a model card and push everything to the hub. \"\n",
    "        \"It might take up to 1min. \\n \"\n",
    "        \"This is a work in progress: if you encounter a bug, please open an issue.\"\n",
    "    )\n",
    "    # Step 1: Clone or create the repo\n",
    "    repo_url = HfApi().create_repo(\n",
    "        repo_id=repo_id,\n",
    "        token=token,\n",
    "        private=False,\n",
    "        exist_ok=True,\n",
    "    )\n",
    "\n",
    "    with tempfile.TemporaryDirectory() as tmpdirname:\n",
    "        tmpdirname = Path(\"./\")\n",
    "\n",
    "        # Step 2: Save the model\n",
    "        torch.save(model.state_dict(), tmpdirname / \"model.pt\")\n",
    "\n",
    "        # Step 3: Evaluate the model and build JSON\n",
    "        mean_reward, std_reward = _evaluate_agent(eval_env, 10, model)\n",
    "\n",
    "        # First 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",
    "            \"std_reward\": std_reward,\n",
    "            \"n_evaluation_episodes\": 10,\n",
    "            \"eval_datetime\": eval_form_datetime,\n",
    "        }\n",
    "\n",
    "        # Write a JSON file\n",
    "        with open(tmpdirname / \"results.json\", \"w\") as outfile:\n",
    "            json.dump(evaluate_data, outfile)\n",
    "\n",
    "        # Step 4: Generate a video\n",
    "        video_path = tmpdirname / \"replay.mp4\"\n",
    "        record_video(eval_env, model, video_path, video_fps)\n",
    "\n",
    "        # Step 5: Generate the model card\n",
    "        generated_model_card, metadata = _generate_model_card(\n",
    "            \"PPO\", hyperparameters.env_id, mean_reward, std_reward, hyperparameters\n",
    "        )\n",
    "        _save_model_card(tmpdirname, generated_model_card, metadata)\n",
    "\n",
    "        # Step 6: Add logs if needed\n",
    "        if logs:\n",
    "            _add_logdir(tmpdirname, Path(logs))\n",
    "\n",
    "        msg.info(f\"Pushing repo {repo_id} to the Hugging Face Hub\")\n",
    "\n",
    "        repo_url = upload_folder(\n",
    "            repo_id=repo_id,\n",
    "            folder_path=tmpdirname,\n",
    "            path_in_repo=\"\",\n",
    "            commit_message=commit_message,\n",
    "            token=token,\n",
    "        )\n",
    "\n",
    "        msg.info(f\"Your model is pushed to the Hub. You can view your model here: {repo_url}\")\n",
    "    return repo_url"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.8.10 ('torch_venv')",
   "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"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "745a3b3e3fb7ac09f0ebb6d5eb47d006584e16db5d9df6f9a8b654baa561b29f"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}