Quentin Gallouédec commited on
Commit
158554b
1 Parent(s): 0e40d4c

main commit

Browse files
Files changed (10) hide show
  1. .gitignore +2 -0
  2. .pre-commit-config.yaml +53 -0
  3. Makefile +13 -0
  4. README.md +1 -1
  5. app.py +90 -0
  6. packages.txt +3 -0
  7. pyproject.toml +15 -0
  8. requirements.txt +27 -0
  9. src/backend.py +594 -0
  10. src/logging.py +37 -0
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ __pycache__/
2
+ .DS_Store
.pre-commit-config.yaml ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ default_language_version:
16
+ python: python3
17
+
18
+ ci:
19
+ autofix_prs: true
20
+ autoupdate_commit_msg: '[pre-commit.ci] pre-commit suggestions'
21
+ autoupdate_schedule: quarterly
22
+
23
+ repos:
24
+ - repo: https://github.com/pre-commit/pre-commit-hooks
25
+ rev: v4.3.0
26
+ hooks:
27
+ - id: check-yaml
28
+ - id: check-case-conflict
29
+ - id: detect-private-key
30
+ - id: check-added-large-files
31
+ args: ['--maxkb=1000']
32
+ - id: requirements-txt-fixer
33
+ - id: end-of-file-fixer
34
+ - id: trailing-whitespace
35
+
36
+ - repo: https://github.com/PyCQA/isort
37
+ rev: 5.12.0
38
+ hooks:
39
+ - id: isort
40
+ name: Format imports
41
+
42
+ - repo: https://github.com/psf/black
43
+ rev: 22.12.0
44
+ hooks:
45
+ - id: black
46
+ name: Format code
47
+ additional_dependencies: ['click==8.0.2']
48
+
49
+ - repo: https://github.com/charliermarsh/ruff-pre-commit
50
+ # Ruff version.
51
+ rev: 'v0.0.267'
52
+ hooks:
53
+ - id: ruff
Makefile ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .PHONY: style format
2
+
3
+
4
+ style:
5
+ python -m black --line-length 119 src app.py
6
+ python -m isort src app.py
7
+ ruff check --fix src app.py
8
+
9
+
10
+ quality:
11
+ python -m black --check --line-length 119 src app.py
12
+ python -m isort --check-only src app.py
13
+ ruff check src app.py
README.md CHANGED
@@ -1,5 +1,5 @@
1
  ---
2
- title: Sb3 Backend
3
  emoji: 🏃
4
  colorFrom: green
5
  colorTo: red
 
1
  ---
2
+ title: SB3 Backend
3
  emoji: 🏃
4
  colorFrom: green
5
  colorTo: red
app.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from functools import partial
3
+ from io import StringIO
4
+
5
+ import gradio as gr
6
+ from apscheduler.schedulers.background import BackgroundScheduler
7
+ from bs4 import BeautifulSoup
8
+ from rich.console import Console
9
+ from rich.syntax import Syntax
10
+
11
+ from src.backend import backend_routine
12
+ from src.logging import configure_root_logger, log_file, setup_logger
13
+
14
+ logging.getLogger("httpx").setLevel(logging.WARNING)
15
+ logging.getLogger("numexpr").setLevel(logging.WARNING)
16
+ logging.getLogger("absl").setLevel(logging.WARNING)
17
+
18
+ configure_root_logger()
19
+
20
+ logging.basicConfig(level=logging.INFO)
21
+ logger = setup_logger(__name__)
22
+
23
+
24
+ def log_file_to_html_string(reverse=True):
25
+ with open(log_file, "rt") as f:
26
+ lines = f.readlines()
27
+ lines = lines[-300:]
28
+
29
+ if reverse:
30
+ lines = reversed(lines)
31
+
32
+ output = "".join(lines)
33
+ syntax = Syntax(output, "python", theme="monokai", word_wrap=True)
34
+
35
+ console = Console(record=True, width=150, style="#272822", file=StringIO())
36
+ console.print(syntax)
37
+ html_content = console.export_html(inline_styles=True)
38
+
39
+ # Parse the HTML content using BeautifulSoup
40
+ soup = BeautifulSoup(html_content, "lxml")
41
+
42
+ # Modify the <pre> tag and add custom styles
43
+ pre_tag = soup.pre
44
+ pre_tag["class"] = "scrollable"
45
+ del pre_tag["style"]
46
+
47
+ # Add your custom styles and the .scrollable CSS to the <style> tag
48
+ style_tag = soup.style
49
+ style_tag.append(
50
+ """
51
+ pre, code {
52
+ background-color: #272822;
53
+ }
54
+ .scrollable {
55
+ font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace;
56
+ height: 500px;
57
+ overflow: auto;
58
+ }
59
+ """
60
+ )
61
+
62
+ return soup.prettify()
63
+
64
+
65
+ REPO_ID = "open-rl-leaderboard/leaderboard"
66
+ RESULTS_REPO = "open-rl-leaderboard/results"
67
+
68
+
69
+ links_md = f"""
70
+ # Important links
71
+ | Description | Link |
72
+ |-----------------|------|
73
+ | Leaderboard | [{REPO_ID}](https://huggingface.co/spaces/{REPO_ID}) |
74
+ | Results Repo | [{RESULTS_REPO}](https://huggingface.co/datasets/{RESULTS_REPO}) |
75
+ """
76
+
77
+
78
+ with gr.Blocks() as demo:
79
+ gr.Markdown(links_md)
80
+ gr.HTML(partial(log_file_to_html_string), every=1)
81
+ with gr.Row():
82
+ gr.DownloadButton("Download Log File", value=log_file)
83
+
84
+
85
+ scheduler = BackgroundScheduler()
86
+ scheduler.add_job(func=backend_routine, trigger="interval", seconds=5 * 60, max_instances=1)
87
+ scheduler.start()
88
+
89
+ if __name__ == "__main__":
90
+ demo.queue().launch()
packages.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ swig
2
+ libosmesa6-dev
3
+ patchelf
pyproject.toml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.ruff]
2
+ line-length = 119
3
+
4
+ [tool.ruff.lint]
5
+ # Enable pycodestyle (`E`) and Pyflakes (`F`) codes by default.
6
+ select = ["E", "F"]
7
+ ignore = ["E501"] # line too long (black is taking care of this)
8
+ fixable = ["A", "B", "C", "D", "E", "F", "G", "I", "N", "Q", "S", "T", "W", "ANN", "ARG", "BLE", "COM", "DJ", "DTZ", "EM", "ERA", "EXE", "FBT", "ICN", "INP", "ISC", "NPY", "PD", "PGH", "PIE", "PL", "PT", "PTH", "PYI", "RET", "RSE", "RUF", "SIM", "SLF", "TCH", "TID", "TRY", "UP", "YTT"]
9
+
10
+ [tool.isort]
11
+ profile = "black"
12
+ line_length = 119
13
+
14
+ [tool.black]
15
+ line-length = 119
requirements.txt ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ APScheduler==3.10.1
2
+ black==23.11.0
3
+ click==8.1.3
4
+ datasets==2.14.5
5
+ gradio==4.20.0
6
+ gradio_client
7
+ gymnasium[all,accept-rom-license]==0.29.1
8
+ huggingface-hub>=0.18.0
9
+ matplotlib==3.7.1
10
+ free-mujoco-py
11
+ mujoco<=2.3.7
12
+ numpy==1.24.2
13
+ pandas==2.0.0
14
+ python-dateutil==2.8.2
15
+ requests==2.28.2
16
+ rliable==1.0.8
17
+ rl-zoo3==2.3.0
18
+ sb3-contrib==2.3.0
19
+ torch==2.2.2
20
+ tqdm==4.65.0
21
+
22
+
23
+
24
+ # Log Visualizer
25
+ BeautifulSoup4==4.12.2
26
+ lxml==4.9.3
27
+ rich==13.3.4
src/backend.py ADDED
@@ -0,0 +1,594 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fnmatch
2
+ import importlib
3
+ import json
4
+ import os
5
+ import re
6
+ import shutil
7
+ import sys
8
+ import tempfile
9
+ import time
10
+ import zipfile
11
+ from pathlib import Path
12
+ from typing import Optional
13
+
14
+ import numpy as np
15
+ import rl_zoo3.import_envs # noqa: F401 pylint: disable=unused-import
16
+ import torch as th
17
+ import yaml
18
+ from huggingface_hub import CommitOperationAdd, HfApi
19
+ from huggingface_hub.utils import EntryNotFoundError
20
+ from huggingface_sb3 import EnvironmentName, ModelName, ModelRepoId, load_from_hub
21
+ from requests.exceptions import HTTPError
22
+ from rl_zoo3 import ALGOS, create_test_env, get_latest_run_id, get_saved_hyperparams
23
+ from rl_zoo3.exp_manager import ExperimentManager
24
+ from rl_zoo3.utils import get_model_path
25
+ from stable_baselines3.common.utils import set_random_seed
26
+
27
+ from src.logging import setup_logger
28
+
29
+ ALL_ENV_IDS = [
30
+ "AdventureNoFrameskip-v4",
31
+ "AirRaidNoFrameskip-v4",
32
+ "AlienNoFrameskip-v4",
33
+ "AmidarNoFrameskip-v4",
34
+ "AssaultNoFrameskip-v4",
35
+ "AsterixNoFrameskip-v4",
36
+ "AsteroidsNoFrameskip-v4",
37
+ "AtlantisNoFrameskip-v4",
38
+ "BankHeistNoFrameskip-v4",
39
+ "BattleZoneNoFrameskip-v4",
40
+ "BeamRiderNoFrameskip-v4",
41
+ "BerzerkNoFrameskip-v4",
42
+ "BowlingNoFrameskip-v4",
43
+ "BoxingNoFrameskip-v4",
44
+ "BreakoutNoFrameskip-v4",
45
+ "CarnivalNoFrameskip-v4",
46
+ "CentipedeNoFrameskip-v4",
47
+ "ChopperCommandNoFrameskip-v4",
48
+ "CrazyClimberNoFrameskip-v4",
49
+ "DefenderNoFrameskip-v4",
50
+ "DemonAttackNoFrameskip-v4",
51
+ "DoubleDunkNoFrameskip-v4",
52
+ "ElevatorActionNoFrameskip-v4",
53
+ "EnduroNoFrameskip-v4",
54
+ "FishingDerbyNoFrameskip-v4",
55
+ "FreewayNoFrameskip-v4",
56
+ "FrostbiteNoFrameskip-v4",
57
+ "GopherNoFrameskip-v4",
58
+ "GravitarNoFrameskip-v4",
59
+ "HeroNoFrameskip-v4",
60
+ "IceHockeyNoFrameskip-v4",
61
+ "JamesbondNoFrameskip-v4",
62
+ "JourneyEscapeNoFrameskip-v4",
63
+ "KangarooNoFrameskip-v4",
64
+ "KrullNoFrameskip-v4",
65
+ "KungFuMasterNoFrameskip-v4",
66
+ "MontezumaRevengeNoFrameskip-v4",
67
+ "MsPacmanNoFrameskip-v4",
68
+ "NameThisGameNoFrameskip-v4",
69
+ "PhoenixNoFrameskip-v4",
70
+ "PitfallNoFrameskip-v4",
71
+ "PongNoFrameskip-v4",
72
+ "PooyanNoFrameskip-v4",
73
+ "PrivateEyeNoFrameskip-v4",
74
+ "QbertNoFrameskip-v4",
75
+ "RiverraidNoFrameskip-v4",
76
+ "RoadRunnerNoFrameskip-v4",
77
+ "RobotankNoFrameskip-v4",
78
+ "SeaquestNoFrameskip-v4",
79
+ "SkiingNoFrameskip-v4",
80
+ "SolarisNoFrameskip-v4",
81
+ "SpaceInvadersNoFrameskip-v4",
82
+ "StarGunnerNoFrameskip-v4",
83
+ "TennisNoFrameskip-v4",
84
+ "TimePilotNoFrameskip-v4",
85
+ "TutankhamNoFrameskip-v4",
86
+ "UpNDownNoFrameskip-v4",
87
+ "VentureNoFrameskip-v4",
88
+ "VideoPinballNoFrameskip-v4",
89
+ "WizardOfWorNoFrameskip-v4",
90
+ "YarsRevengeNoFrameskip-v4",
91
+ "ZaxxonNoFrameskip-v4",
92
+ # Box2D
93
+ "BipedalWalker-v3",
94
+ "BipedalWalkerHardcore-v3",
95
+ "CarRacing-v2",
96
+ "LunarLander-v2",
97
+ "LunarLanderContinuous-v2",
98
+ # Toy text
99
+ "Blackjack-v1",
100
+ "CliffWalking-v0",
101
+ "FrozenLake-v1",
102
+ "FrozenLake8x8-v1",
103
+ # Classic control
104
+ "Acrobot-v1",
105
+ "CartPole-v1",
106
+ "MountainCar-v0",
107
+ "MountainCarContinuous-v0",
108
+ "Pendulum-v1",
109
+ # MuJoCo
110
+ "Ant-v4",
111
+ "HalfCheetah-v4",
112
+ "Hopper-v4",
113
+ "Humanoid-v4",
114
+ "HumanoidStandup-v4",
115
+ "InvertedDoublePendulum-v4",
116
+ "InvertedPendulum-v4",
117
+ "Pusher-v4",
118
+ "Reacher-v4",
119
+ "Swimmer-v4",
120
+ "Walker2d-v4",
121
+ ]
122
+
123
+
124
+ def download_from_hub(
125
+ algo: str,
126
+ env_name: EnvironmentName,
127
+ exp_id: int,
128
+ folder: str,
129
+ organization: str,
130
+ repo_name: Optional[str] = None,
131
+ force: bool = False,
132
+ ) -> None:
133
+ """
134
+ Try to load a model from the Huggingface hub
135
+ and save it following the RL Zoo structure.
136
+ Default repo name is {organization}/{algo}-{env_id}
137
+ where repo_name = {algo}-{env_id}
138
+
139
+ :param algo: Algorithm
140
+ :param env_name: Environment name
141
+ :param exp_id: Experiment id
142
+ :param folder: Log folder
143
+ :param organization: Huggingface organization
144
+ :param repo_name: Overwrite default repository name
145
+ :param force: Allow overwritting the folder
146
+ if it already exists.
147
+ """
148
+
149
+ model_name = ModelName(algo, env_name)
150
+
151
+ if repo_name is None:
152
+ repo_name = model_name # Note: model name is {algo}-{env_name}
153
+
154
+ # Note: repo id is {organization}/{repo_name}
155
+ repo_id = ModelRepoId(organization, repo_name)
156
+ logger.info(f"Downloading from https://huggingface.co/{repo_id}")
157
+
158
+ checkpoint = load_from_hub(repo_id, model_name.filename)
159
+ try:
160
+ config_path = load_from_hub(repo_id, "config.yml")
161
+ except EntryNotFoundError: # hotfix for old models
162
+ config_path = load_from_hub(repo_id, "config.json")
163
+ with open(config_path, "r") as f:
164
+ config = json.load(f)
165
+ config_path = config_path.replace(".json", ".yml")
166
+ with open(config_path, "w") as f:
167
+ yaml.dump(config, f)
168
+
169
+ # If VecNormalize, download
170
+ try:
171
+ vec_normalize_stats = load_from_hub(repo_id, "vec_normalize.pkl")
172
+ except HTTPError:
173
+ logger.info("No normalization file")
174
+ vec_normalize_stats = None
175
+
176
+ try:
177
+ saved_args = load_from_hub(repo_id, "args.yml")
178
+ except EntryNotFoundError:
179
+ logger.info("No args file")
180
+ saved_args = None
181
+
182
+ try:
183
+ env_kwargs = load_from_hub(repo_id, "env_kwargs.yml")
184
+ except EntryNotFoundError:
185
+ logger.info("No env_kwargs file")
186
+ env_kwargs = None
187
+
188
+ try:
189
+ train_eval_metrics = load_from_hub(repo_id, "train_eval_metrics.zip")
190
+ except EntryNotFoundError:
191
+ logger.info("No train_eval_metrics file")
192
+ train_eval_metrics = None
193
+
194
+ if exp_id == 0:
195
+ exp_id = get_latest_run_id(os.path.join(folder, algo), env_name) + 1
196
+ # Sanity checks
197
+ if exp_id > 0:
198
+ log_path = os.path.join(folder, algo, f"{env_name}_{exp_id}")
199
+ else:
200
+ log_path = os.path.join(folder, algo)
201
+
202
+ # Check that the folder does not exist
203
+ log_folder = Path(log_path)
204
+ if log_folder.is_dir():
205
+ if force:
206
+ logger.info(f"The folder {log_path} already exists, overwritting")
207
+ # Delete the current one to avoid errors
208
+ shutil.rmtree(log_path)
209
+ else:
210
+ raise ValueError(
211
+ f"The folder {log_path} already exists, use --force to overwrite it, "
212
+ "or choose '--exp-id 0' to create a new folder"
213
+ )
214
+
215
+ logger.info(f"Saving to {log_path}")
216
+ # Create folder structure
217
+ os.makedirs(log_path, exist_ok=True)
218
+ config_folder = os.path.join(log_path, env_name)
219
+ os.makedirs(config_folder, exist_ok=True)
220
+
221
+ # Copy config files and saved stats
222
+ shutil.copy(checkpoint, os.path.join(log_path, f"{env_name}.zip"))
223
+ if saved_args is not None:
224
+ shutil.copy(saved_args, os.path.join(config_folder, "args.yml"))
225
+ shutil.copy(config_path, os.path.join(config_folder, "config.yml"))
226
+ if env_kwargs is not None:
227
+ shutil.copy(env_kwargs, os.path.join(config_folder, "env_kwargs.yml"))
228
+ if vec_normalize_stats is not None:
229
+ shutil.copy(vec_normalize_stats, os.path.join(config_folder, "vecnormalize.pkl"))
230
+
231
+ # Extract monitor file and evaluation file
232
+ if train_eval_metrics is not None:
233
+ with zipfile.ZipFile(train_eval_metrics, "r") as zip_ref:
234
+ zip_ref.extractall(log_path)
235
+
236
+
237
+ def pattern_match(patterns, source_list):
238
+ if isinstance(patterns, str):
239
+ patterns = [patterns]
240
+
241
+ env_ids = set()
242
+ for pattern in patterns:
243
+ for matching in fnmatch.filter(source_list, pattern):
244
+ env_ids.add(matching)
245
+ return sorted(list(env_ids))
246
+
247
+
248
+ def evaluate(
249
+ user_id,
250
+ repo_name,
251
+ env="CartPole-v1",
252
+ folder="rl-trained-agents",
253
+ algo="ppo",
254
+ # n_timesteps=1000,
255
+ n_episodes=50,
256
+ num_threads=-1,
257
+ n_envs=1,
258
+ exp_id=0,
259
+ verbose=1,
260
+ no_render=False,
261
+ deterministic=False,
262
+ device="auto",
263
+ load_best=False,
264
+ load_checkpoint=None,
265
+ load_last_checkpoint=False,
266
+ stochastic=False,
267
+ norm_reward=False,
268
+ seed=0,
269
+ reward_log="",
270
+ gym_packages=[],
271
+ env_kwargs=None,
272
+ custom_objects=False,
273
+ progress=False,
274
+ ):
275
+ """
276
+ Enjoy trained agent
277
+
278
+ :param env: (str) Environment ID
279
+ :param folder: (str) Log folder
280
+ :param algo: (str) RL Algorithm
281
+ :param n_timesteps: (int) Number of timesteps
282
+ :param num_threads: (int) Number of threads for PyTorch
283
+ :param n_envs: (int) Number of environments
284
+ :param exp_id: (int) Experiment ID (default: 0: latest, -1: no exp folder)
285
+ :param verbose: (int) Verbose mode (0: no output, 1: INFO)
286
+ :param no_render: (bool) Do not render the environment (useful for tests)
287
+ :param deterministic: (bool) Use deterministic actions
288
+ :param device: (str) PyTorch device to be use (ex: cpu, cuda...)
289
+ :param load_best: (bool) Load best model instead of last model if available
290
+ :param load_checkpoint: (int) Load checkpoint instead of last model if available
291
+ :param load_last_checkpoint: (bool) Load last checkpoint instead of last model if available
292
+ :param stochastic: (bool) Use stochastic actions
293
+ :param norm_reward: (bool) Normalize reward if applicable (trained with VecNormalize)
294
+ :param seed: (int) Random generator seed
295
+ :param reward_log: (str) Where to log reward
296
+ :param gym_packages: (List[str]) Additional external Gym environment package modules to import
297
+ :param env_kwargs: (Dict[str, Any]) Optional keyword argument to pass to the env constructor
298
+ :param custom_objects: (bool) Use custom objects to solve loading issues
299
+ :param progress: (bool) if toggled, display a progress bar using tqdm and rich
300
+ """
301
+
302
+ # Going through custom gym packages to let them register in the global registory
303
+ for env_module in gym_packages:
304
+ importlib.import_module(env_module)
305
+
306
+ env_name = EnvironmentName(env)
307
+
308
+ # try:
309
+ # _, model_path, log_path = get_model_path(
310
+ # exp_id,
311
+ # folder,
312
+ # algo,
313
+ # env_name,
314
+ # load_best,
315
+ # load_checkpoint,
316
+ # load_last_checkpoint,
317
+ # )
318
+ # except (AssertionError, ValueError) as e:
319
+ # # Special case for rl-trained agents
320
+ # # auto-download from the hub
321
+ # if "rl-trained-agents" not in folder:
322
+ # raise e
323
+ # else:
324
+ # logger.info("Pretrained model not found, trying to download it from sb3 Huggingface hub: https://huggingface.co/sb3")
325
+ # Auto-download
326
+ download_from_hub(
327
+ algo=algo,
328
+ env_name=env_name,
329
+ exp_id=exp_id,
330
+ folder=folder,
331
+ # organization="sb3",
332
+ organization=user_id,
333
+ # repo_name=None,
334
+ repo_name=repo_name,
335
+ force=False,
336
+ )
337
+ # Try again
338
+ _, model_path, log_path = get_model_path(
339
+ exp_id,
340
+ folder,
341
+ algo,
342
+ env_name,
343
+ load_best,
344
+ load_checkpoint,
345
+ load_last_checkpoint,
346
+ )
347
+
348
+ logger.info(f"Loading {model_path}")
349
+
350
+ # Off-policy algorithm only support one env for now
351
+ off_policy_algos = ["qrdqn", "dqn", "ddpg", "sac", "her", "td3", "tqc"]
352
+
353
+ set_random_seed(seed)
354
+
355
+ if num_threads > 0:
356
+ if verbose > 1:
357
+ logger.info(f"Setting torch.num_threads to {num_threads}")
358
+ th.set_num_threads(num_threads)
359
+
360
+ is_atari = ExperimentManager.is_atari(env_name.gym_id)
361
+ is_minigrid = ExperimentManager.is_minigrid(env_name.gym_id)
362
+
363
+ stats_path = os.path.join(log_path, env_name)
364
+ hyperparams, maybe_stats_path = get_saved_hyperparams(stats_path, norm_reward=norm_reward, test_mode=True)
365
+
366
+ # load env_kwargs if existing
367
+ env_kwargs = {}
368
+ args_path = os.path.join(log_path, env_name, "args.yml")
369
+ if os.path.isfile(args_path):
370
+ with open(args_path) as f:
371
+ loaded_args = yaml.load(f, Loader=yaml.UnsafeLoader)
372
+ if loaded_args["env_kwargs"] is not None:
373
+ env_kwargs = loaded_args["env_kwargs"]
374
+ # overwrite with command line arguments
375
+ if env_kwargs is not None:
376
+ env_kwargs.update(env_kwargs)
377
+
378
+ log_dir = reward_log if reward_log != "" else None
379
+
380
+ env = create_test_env(
381
+ env_name.gym_id,
382
+ n_envs=n_envs,
383
+ stats_path=maybe_stats_path,
384
+ seed=seed,
385
+ log_dir=log_dir,
386
+ should_render=not no_render,
387
+ hyperparams=hyperparams,
388
+ env_kwargs=env_kwargs,
389
+ )
390
+
391
+ kwargs = dict(seed=seed)
392
+ if algo in off_policy_algos:
393
+ # Dummy buffer size as we don't need memory to enjoy the trained agent
394
+ kwargs.update(dict(buffer_size=1))
395
+ # Hack due to breaking change in v1.6
396
+ # handle_timeout_termination cannot be at the same time
397
+ # with optimize_memory_usage
398
+ if "optimize_memory_usage" in hyperparams:
399
+ kwargs.update(optimize_memory_usage=False)
400
+
401
+ # Check if we are running python 3.8+
402
+ # we need to patch saved model under python 3.6/3.7 to load them
403
+ newer_python_version = sys.version_info.major == 3 and sys.version_info.minor >= 8
404
+
405
+ custom_objects = {}
406
+ if newer_python_version or custom_objects:
407
+ custom_objects = {
408
+ "learning_rate": 0.0,
409
+ "lr_schedule": lambda _: 0.0,
410
+ "clip_range": lambda _: 0.0,
411
+ }
412
+
413
+ if "HerReplayBuffer" in hyperparams.get("replay_buffer_class", ""):
414
+ kwargs["env"] = env
415
+
416
+ model = ALGOS[algo].load(model_path, custom_objects=custom_objects, device=device, **kwargs)
417
+ obs = env.reset()
418
+
419
+ # Deterministic by default except for atari games
420
+ stochastic = stochastic or (is_atari or is_minigrid) and not deterministic
421
+ deterministic = not stochastic
422
+
423
+ episode_reward = 0.0
424
+ episode_rewards, episode_lengths = [], []
425
+ ep_len = 0
426
+ # For HER, monitor success rate
427
+ successes = []
428
+ lstm_states = None
429
+ episode_start = np.ones((env.num_envs,), dtype=bool)
430
+
431
+ # generator = range(n_timesteps)
432
+ # if progress:
433
+ # if tqdm is None:
434
+ # raise ImportError("Please install tqdm and rich to use the progress bar")
435
+ # generator = tqdm(generator)
436
+
437
+ try:
438
+ # for _ in generator:
439
+ while len(episode_rewards) < n_episodes:
440
+ action, lstm_states = model.predict(
441
+ obs, # type: ignore[arg-type]
442
+ state=lstm_states,
443
+ episode_start=episode_start,
444
+ deterministic=deterministic,
445
+ )
446
+ obs, reward, done, infos = env.step(action)
447
+
448
+ episode_start = done
449
+
450
+ if not no_render:
451
+ env.render("human")
452
+
453
+ episode_reward += reward[0]
454
+ ep_len += 1
455
+
456
+ if n_envs == 1:
457
+ # For atari the return reward is not the atari score
458
+ # so we have to get it from the infos dict
459
+ if is_atari and infos is not None and verbose >= 1:
460
+ episode_infos = infos[0].get("episode")
461
+ if episode_infos is not None:
462
+ logger.info(f"Atari Episode Score: {episode_infos['r']:.2f}")
463
+ logger.info("Atari Episode Length", episode_infos["l"])
464
+
465
+ if done and not is_atari and verbose > 0:
466
+ # NOTE: for env using VecNormalize, the mean reward
467
+ # is a normalized reward when `--norm_reward` flag is passed
468
+ logger.info(f"Episode Reward: {episode_reward:.2f}")
469
+ logger.info("Episode Length", ep_len)
470
+ episode_rewards.append(episode_reward)
471
+ episode_lengths.append(ep_len)
472
+ episode_reward = 0.0
473
+ ep_len = 0
474
+
475
+ # Reset also when the goal is achieved when using HER
476
+ if done and infos[0].get("is_success") is not None:
477
+ if verbose > 1:
478
+ logger.info("Success?", infos[0].get("is_success", False))
479
+
480
+ if infos[0].get("is_success") is not None:
481
+ successes.append(infos[0].get("is_success", False))
482
+ episode_reward, ep_len = 0.0, 0
483
+
484
+ except KeyboardInterrupt:
485
+ pass
486
+
487
+ if verbose > 0 and len(successes) > 0:
488
+ logger.info(f"Success rate: {100 * np.mean(successes):.2f}%")
489
+
490
+ if verbose > 0 and len(episode_rewards) > 0:
491
+ logger.info(f"{len(episode_rewards)} Episodes")
492
+ logger.info(f"Mean reward: {np.mean(episode_rewards):.2f} +/- {np.std(episode_rewards):.2f}")
493
+
494
+ if verbose > 0 and len(episode_lengths) > 0:
495
+ logger.info(f"Mean episode length: {np.mean(episode_lengths):.2f} +/- {np.std(episode_lengths):.2f}")
496
+
497
+ env.close()
498
+
499
+ return episode_rewards
500
+
501
+
502
+ logger = setup_logger(__name__)
503
+
504
+ API = HfApi(token=os.environ.get("TOKEN"))
505
+ RESULTS_REPO = "open-rl-leaderboard/results"
506
+
507
+
508
+ def _backend_routine():
509
+ # List only the text classification models
510
+ rl_models = list(API.list_models(filter=["reinforcement-learning", "stable-baselines3"]))
511
+ logger.info(f"Found {len(rl_models)} RL models")
512
+ compatible_models = []
513
+ for model in rl_models:
514
+ compatible_models.append((model.modelId, model.sha))
515
+
516
+ logger.info(f"Found {len(compatible_models)} compatible models")
517
+
518
+ # Get the results
519
+ pattern = re.compile(r"^[^/]*/[^/]*/[^/]*results_[a-f0-9]+\.json$")
520
+ filenames = API.list_repo_files(RESULTS_REPO, repo_type="dataset")
521
+ filenames = [filename for filename in filenames if pattern.match(filename)]
522
+
523
+ evaluated_models = set()
524
+ for filename in filenames:
525
+ path = API.hf_hub_download(repo_id=RESULTS_REPO, filename=filename, repo_type="dataset")
526
+ with open(path) as fp:
527
+ report = json.load(fp)
528
+ evaluated_models.add((report["config"]["model_id"], report["config"]["model_sha"]))
529
+
530
+ # Find the models that are not associated with any results
531
+ pending_models = list(set(compatible_models) - evaluated_models)
532
+ logger.info(f"Found {len(pending_models)} pending models")
533
+
534
+ if len(pending_models) == 0:
535
+ return None
536
+
537
+ # Run an evaluation on the models
538
+ with tempfile.TemporaryDirectory() as tmp_dir:
539
+ for model_id, sha in pending_models:
540
+ time.sleep(60)
541
+ commits = []
542
+ model_info = API.model_info(model_id, revision=sha)
543
+
544
+ # Extract the environment IDs from the tags (usually only one)
545
+ env_ids = pattern_match(model_info.tags, ALL_ENV_IDS)
546
+ if len(env_ids) == 0:
547
+ logger.error(f"No environment found for {model_id}")
548
+ continue
549
+ else:
550
+ env = env_ids[0]
551
+ user_id, repo_name = model_id.split("/")
552
+ algo = model_info.model_index[0]["name"].lower()
553
+
554
+ logger.info(f"Running evaluation on {model_id}")
555
+ report = {"config": {"model_id": model_id, "model_sha": sha}}
556
+ try:
557
+ episodic_returns = evaluate(
558
+ user_id, repo_name, env, "rl-trained-agents", algo, no_render=True, verbose=1
559
+ )
560
+ evaluations = {env: {"episodic_returns": episodic_returns}}
561
+ except Exception as e:
562
+ logger.error(f"Error evaluating {model_id}: {e}")
563
+ evaluations = None
564
+
565
+ if evaluations is not None:
566
+ report["results"] = evaluations
567
+ report["status"] = "DONE"
568
+ else:
569
+ report["status"] = "FAILED"
570
+
571
+ # Update the results
572
+ dumped = json.dumps(report, indent=2)
573
+ path_in_repo = f"{model_id}/results_{sha}.json"
574
+ local_path = os.path.join(tmp_dir, path_in_repo)
575
+ os.makedirs(os.path.dirname(local_path), exist_ok=True)
576
+ with open(local_path, "w") as f:
577
+ f.write(dumped)
578
+
579
+ commits.append(CommitOperationAdd(path_in_repo=path_in_repo, path_or_fileobj=local_path))
580
+
581
+ API.create_commit(
582
+ repo_id=RESULTS_REPO, commit_message="Add evaluation results", operations=commits, repo_type="dataset"
583
+ )
584
+
585
+
586
+ def backend_routine():
587
+ try:
588
+ _backend_routine()
589
+ except Exception as e:
590
+ logger.error(f"{e.__class__.__name__}: {str(e)}")
591
+
592
+
593
+ if __name__ == "__main__":
594
+ backend_routine()
src/logging.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+ proj_dir = Path(__file__).parents[1]
4
+
5
+ log_file = proj_dir / "output.log"
6
+
7
+
8
+ import logging
9
+
10
+
11
+ def setup_logger(name: str):
12
+ logger = logging.getLogger(name)
13
+ logger.setLevel(logging.INFO)
14
+
15
+ formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
16
+
17
+ # Create a file handler to write logs to a file
18
+ file_handler = logging.FileHandler(log_file)
19
+ file_handler.setLevel(logging.INFO)
20
+ file_handler.setFormatter(formatter)
21
+ logger.addHandler(file_handler)
22
+
23
+ return logger
24
+
25
+
26
+ def configure_root_logger():
27
+ # Configure the root logger
28
+ logging.basicConfig(level=logging.INFO)
29
+ root_logger = logging.getLogger()
30
+
31
+ formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
32
+
33
+ file_handler = logging.FileHandler(log_file)
34
+ file_handler.setLevel(logging.INFO)
35
+ file_handler.setFormatter(formatter)
36
+
37
+ root_logger.addHandler(file_handler)