File size: 10,171 Bytes
74e3b17
 
69cf5b3
0811d37
74e3b17
de52ad3
74e3b17
 
5174522
95c19d6
7b86855
3922a8b
74e3b17
2a5f9fb
3922a8b
74e3b17
95c19d6
2a73469
69cf5b3
 
 
 
3922a8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69cf5b3
 
 
3922a8b
 
103ee13
 
3922a8b
 
 
103ee13
3922a8b
 
69cf5b3
 
3922a8b
69cf5b3
 
3922a8b
 
69cf5b3
 
103ee13
69cf5b3
3922a8b
 
 
103ee13
 
 
 
 
 
69cf5b3
 
74e3b17
 
 
69cf5b3
 
 
 
74e3b17
69cf5b3
 
5174522
69cf5b3
74e3b17
69cf5b3
 
 
 
 
 
 
74e3b17
 
69cf5b3
 
74e3b17
 
 
69cf5b3
 
 
 
3922a8b
74e3b17
3922a8b
 
69cf5b3
3922a8b
69cf5b3
 
 
 
 
 
041b899
69cf5b3
 
95c19d6
 
08990fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
041b899
74e3b17
 
 
69cf5b3
 
 
 
 
 
 
3922a8b
 
 
69cf5b3
3922a8b
69cf5b3
 
 
 
 
3922a8b
 
 
 
6366df9
3922a8b
 
 
 
 
 
 
 
 
 
 
 
 
 
74e3b17
 
 
95c19d6
8c49cb6
74e3b17
3922a8b
74e3b17
95c19d6
 
0811d37
69cf5b3
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import json
import os
import re

import gradio as gr
import numpy as np
import pandas as pd
from apscheduler.schedulers.background import BackgroundScheduler
from huggingface_hub import HfApi

from src.backend import backend_routine

from src.logging import configure_root_logger, setup_logger


configure_root_logger()
logger = setup_logger(__name__)

API = HfApi(token=os.environ.get("TOKEN"))
RESULTS_REPO = f"open-rl-leaderboard/results"
ALL_ENV_IDS = {
    "Atari": [
        "Adventure",
        "AirRaid",
        "Alien",
        "Amidar",
        "Assault",
        "Asterix",
        "Asteroids",
        "Atlantis",
        "BankHeist",
        "BattleZone",
        "BeamRider",
        "Berzerk",
        "Bowling",
        "Boxing",
        "Breakout",
        "Carnival",
        "Centipede",
        "ChopperCommand",
        "CrazyClimber",
        "Defender",
        "DemonAttack",
        "DoubleDunk",
        "ElevatorAction",
        "Enduro",
        "FishingDerby",
        "Freeway",
        "Frostbite",
        "Gopher",
        "Gravitar",
        "Hero",
        "IceHockey",
        "Jamesbond",
        "JourneyEscape",
        "Kangaroo",
        "Krull",
        "KungFuMaster",
        "MontezumaRevenge",
        "MsPacman",
        "NameThisGame",
        "Phoenix",
        "Pitfall",
        "Pong",
        "Pooyan",
        "PrivateEye",
        "Qbert",
        "Riverraid",
        "RoadRunner",
        "Robotank",
        "Seaquest",
        "Skiing",
        "Solaris",
        "SpaceInvaders",
        "StarGunner",
        "Tennis",
        "TimePilot",
        "Tutankham",
        "UpNDown",
        "Venture",
        "VideoPinball",
        "WizardOfWor",
        "YarsRevenge",
        "Zaxxon",
    ],
    "Box2D": [
        "BipedalWalker-v3",
        "BipedalWalkerHardcore-v3",
        "CarRacing-v2",
        "LunarLander-v2",
        "LunarLanderContinuous-v2",
    ],
    "Toy text": [
        "Blackjack-v1",
        "CliffWalking-v0",
        "FrozenLake-v1",
        "FrozenLake8x8-v1",
    ],
    "Classic control": [
        "Acrobot-v1",
        "CartPole-v1",
        "MountainCar-v0",
        "MountainCarContinuous-v0",
        "Pendulum-v1",
    ],
    "MuJoCo": [
        "Ant-v4",
        "HalfCheetah-v4",
        "Hopper-v4",
        "Humanoid-v4",
        "HumanoidStandup-v4",
        "InvertedDoublePendulum-v4",
        "InvertedPendulum-v4",
        "Pusher-v4",
        "Reacher-v4",
        "Swimmer-v4",
        "Walker2d-v4",
    ],
}


def get_leaderboard_df():
    # List all results files in results repo
    pattern = re.compile(r"^[^/]*/[^/]*/[^/]*results_[a-f0-9]+\.json$")
    filenames = API.list_repo_files(RESULTS_REPO, repo_type="dataset")
    filenames = [filename for filename in filenames if pattern.match(filename)]

    data = []
    for filename in filenames:
        path = API.hf_hub_download(repo_id=RESULTS_REPO, filename=filename, repo_type="dataset")
        with open(path) as fp:
            report = json.load(fp)
        user_id, model_id = report["config"]["model_id"].split("/")
        row = {"user_id": user_id, "model_id": model_id}
        if report["status"] == "DONE" and len(report["results"]) > 0:
            env_ids = list(report["results"].keys())
            assert len(env_ids) == 1, "Only one environment supported for the moment"
            row["env_id"] = env_ids[0]
            row["mean_episodic_return"] = np.mean(report["results"][env_ids[0]]["episodic_returns"])
        data.append(row)

    df = pd.DataFrame(data)  # create DataFrame
    df = df.fillna("")  # replace NaN values with empty strings
    return df


def select_env(df: pd.DataFrame, env_id: str):
    df = df[df["env_id"] == env_id]
    df = df.sort_values("mean_episodic_return", ascending=False)
    df["ranking"] = np.arange(1, len(df) + 1)
    return df


def format_df(df: pd.DataFrame):
    # Add hyperlinks
    df = df.copy()
    for index, row in df.iterrows():
        user_id = row["user_id"]
        model_id = row["model_id"]
        df.loc[index, "user_id"] = f"[{user_id}](https://huggingface.co/{user_id})"
        df.loc[index, "model_id"] = f"[{model_id}](https://huggingface.co/{user_id}/{model_id})"

    # Keep only the relevant columns
    df = df[["ranking", "user_id", "model_id", "mean_episodic_return"]]
    return df.values.tolist()


TITLE = """
πŸš€ Open RL Leaderboard
"""

INTRODUCTION_TEXT = """
Welcome to the Open RL Leaderboard! This is a community-driven benchmark for reinforcement learning models.
"""

ABOUT_TEXT = r"""
The Open RL Leaderboard is a community-driven benchmark for reinforcement learning models.

## πŸ”Œ How to have your agent evaluated?

The Open RL Leaderboard constantly scans the πŸ€— Hub to detect new models to be evaluated. For your model to be evaluated, it must meet the following criteria.

1. The model must be public on the πŸ€— Hub
2. The model must contain an `agent.pt` file.
3. The model must be [tagged](https://huggingface.co/docs/hub/model-cards#model-cards) `reinforcement-learning`
4. The model must be [tagged](https://huggingface.co/docs/hub/model-cards#model-cards) with the name of the environment you want to evaluate (for example `MountainCar-v0`)

Once your model meets these criteria, it will be automatically evaluated on the Open RL Leaderboard. That's it!

## πŸ—οΈ How do I build the `agent.pt`?

The `agent.pt` file is a [TorchScript module](https://pytorch.org/docs/stable/jit.html#). It must be loadable using `torch.jit.load`.
The module must take batch of observations as input and return batch of actions. To check if your model is compatible with the Open RL Leaderboard, you can run the following code:

```python
import gymnasium as gym
import numpy as np
import torch

agent_path = "path/to/agent.pt"
env_id = ... # e.g. "MountainCar-v0"

agent = torch.jit.load(agent_path)
env = gym.make(env_id)
observations = np.array([env.observation_space.sample()])
observations = torch.from_numpy(observations)
actions = agent(observations)
actions = actions.numpy()[0]
assert env.action_space.contains(actions)
```

## πŸ•΅ How are the models evaluated?

The evaluation is done by running the agent on the environment for 100 episodes. 

For further information, please refer to the [Open RL Leaderboard evaulation script](https://huggingface.co/spaces/open-rl-leaderboard/leaderboard/blob/main/src/evaluation.py).

### The particular case of Atari environments

Atari environments are evaluated on the `NoFrameskip-v4` version of the environment. For example, to evaluate an agent on the `Pong` environment, you must tag your model with `PongNoFrameskip-v4`. The environment is then wrapped to match the standard Atari preprocessing pipeline.

- No-op reset with a maximum of 30 no-ops
- Max and skip with a skip of 4
- Episodic life (although the reported score is for the full episode, not the life)
- Fire reset
- Clip reward (although the reported score is not clipped)
- Resize observation to 84x84
- Grayscale observation
- Frame stack of 4

## πŸš‘ Troubleshooting

If you encounter any issue, please open an issue on the [Open RL Leaderboard repository](https://huggingface.co/spaces/open-rl-leaderboard/leaderboard/discussions/new).

## πŸ“œ Citation

```bibtex
@misc{open-rl-leaderboard,
  author = {Quentin GallouΓ©dec and TODO},
  title = {Open RL Leaderboard},
  year = {2024},
  publisher = {Hugging Face},
  howpublished = "\url{https://huggingface.co/spaces/open-rl-leaderboard/leaderboard}",
}
```
"""


with gr.Blocks() as demo:
    gr.HTML(TITLE)
    gr.Markdown(INTRODUCTION_TEXT, elem_classes="markdown-text")
    with gr.Tabs(elem_classes="tab-buttons") as tabs:
        with gr.TabItem("πŸ… Leaderboard"):
            df = get_leaderboard_df()
            for env_domain, env_ids in ALL_ENV_IDS.items():
                with gr.TabItem(env_domain):
                    for env_id in env_ids:
                        with gr.TabItem(env_id):
                            with gr.Row(equal_height=False):
                                if env_domain == "Atari":
                                    env_id = f"{env_id}NoFrameskip-v4"
                                env_df = select_env(df, env_id)
                                gr.components.Dataframe(
                                    value=format_df(env_df),
                                    headers=["πŸ† Ranking", "πŸ§‘ User", "πŸ€– Model id", "πŸ“Š Mean episodic return"],
                                    datatype=["number", "markdown", "markdown", "number"],
                                    row_count=(10, "fixed"),
                                    scale=3,
                                )
                                # Get the best model and
                                if not env_df.empty:
                                    user_id = env_df.iloc[0]["user_id"]
                                    model_id = env_df.iloc[0]["model_id"]
                                    video_path = API.hf_hub_download(
                                        repo_id=f"{user_id}/{model_id}",
                                        filename="replay.mp4",
                                        revision="main",
                                        repo_type="model",
                                    )
                                    video = gr.PlayableVideo(
                                        video_path,
                                        autoplay=True,
                                        scale=1,
                                        min_width=50,
                                        show_download_button=False,
                                        label=model_id,
                                    )
                                    # Doesn't loop for the moment, see https://github.com/gradio-app/gradio/issues/7689

        with gr.TabItem("πŸ“ About", elem_id="llm-benchmark-tab-table", id=2):
            gr.Markdown(ABOUT_TEXT)


scheduler = BackgroundScheduler()
scheduler.add_job(func=backend_routine, trigger="interval", seconds=10 * 60, max_instances=1)
scheduler.start()


if __name__ == "__main__":
    demo.queue().launch()