margsli commited on
Commit
f1118b2
β€’
1 Parent(s): 65872e3

Create _app.py

Browse files
Files changed (1) hide show
  1. _app.py +704 -0
_app.py ADDED
@@ -0,0 +1,704 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A gradio app that renders a static leaderboard. This is used for Hugging Face Space."""
2
+ import ast
3
+ import argparse
4
+ import glob
5
+ import pickle
6
+
7
+ import gradio as gr
8
+ import numpy as np
9
+ import pandas as pd
10
+
11
+
12
+ # notebook_url = "https://colab.research.google.com/drive/1RAWb22-PFNI-X1gPVzc927SGUdfr6nsR?usp=sharing"
13
+ notebook_url = "https://colab.research.google.com/drive/1KdwokPjirkTmpO_P1WByFNFiqxWQquwH#scrollTo=o_CpbkGEbhrK"
14
+
15
+ basic_component_values = [None] * 6
16
+ leader_component_values = [None] * 5
17
+
18
+
19
+ def make_default_md(arena_df, elo_results):
20
+ total_votes = sum(arena_df["num_battles"]) // 2
21
+ total_models = len(arena_df)
22
+
23
+ leaderboard_md = f"""
24
+ # πŸ† LMSYS Chatbot Arena Leaderboard
25
+ | [Vote](https://chat.lmsys.org) | [Blog](https://lmsys.org/blog/2023-05-03-arena/) | [GitHub](https://github.com/lm-sys/FastChat) | [Paper](https://arxiv.org/abs/2306.05685) | [Dataset](https://github.com/lm-sys/FastChat/blob/main/docs/dataset_release.md) | [Twitter](https://twitter.com/lmsysorg) | [Discord](https://discord.gg/HSWAKCrnFx) |
26
+
27
+ LMSYS [Chatbot Arena](https://lmsys.org/blog/2023-05-03-arena/) is a crowdsourced open platform for LLM evals.
28
+ We've collected over **500,000** human preference votes to rank LLMs with the Elo ranking system.
29
+ """
30
+ return leaderboard_md
31
+
32
+
33
+ def make_arena_leaderboard_md(arena_df):
34
+ total_votes = sum(arena_df["num_battles"]) // 2
35
+ total_models = len(arena_df)
36
+ space = "   "
37
+ leaderboard_md = f"""
38
+ Total #models: **{total_models}**.{space} Total #votes: **{"{:,}".format(total_votes)}**.{space} Last updated: April 11, 2024.
39
+
40
+ πŸ“£ **NEW!** View leaderboard for different categories (e.g., coding, long user query)!
41
+
42
+ Code to recreate leaderboard tables and plots in this [notebook]({notebook_url}). Cast your vote πŸ—³οΈ at [chat.lmsys.org](https://chat.lmsys.org)!
43
+ """
44
+ return leaderboard_md
45
+
46
+ def make_category_arena_leaderboard_md(arena_df, arena_subset_df, name="Overall"):
47
+ total_votes = sum(arena_df["num_battles"]) // 2
48
+ total_models = len(arena_df)
49
+ space = "   "
50
+ total_subset_votes = sum(arena_subset_df["num_battles"]) // 2
51
+ total_subset_models = len(arena_subset_df)
52
+ leaderboard_md = f"""### {cat_name_to_explanation[name]}
53
+ #### [Coverage] {space} #models: **{total_subset_models} ({round(total_subset_models/total_models *100)}%)** {space} #votes: **{"{:,}".format(total_subset_votes)} ({round(total_subset_votes/total_votes * 100)}%)**{space}
54
+ """
55
+ return leaderboard_md
56
+
57
+ def make_full_leaderboard_md(elo_results):
58
+ leaderboard_md = f"""
59
+ Three benchmarks are displayed: **Arena Elo**, **MT-Bench** and **MMLU**.
60
+ - [Chatbot Arena](https://chat.lmsys.org/?arena) - a crowdsourced, randomized battle platform. We use 500K+ user votes to compute Elo ratings.
61
+ - [MT-Bench](https://arxiv.org/abs/2306.05685): a set of challenging multi-turn questions. We use GPT-4 to grade the model responses.
62
+ - [MMLU](https://arxiv.org/abs/2009.03300) (5-shot): a test to measure a model's multitask accuracy on 57 tasks.
63
+
64
+ πŸ’» Code: The MT-bench scores (single-answer grading on a scale of 10) are computed by [fastchat.llm_judge](https://github.com/lm-sys/FastChat/tree/main/fastchat/llm_judge).
65
+ The MMLU scores are mostly computed by [InstructEval](https://github.com/declare-lab/instruct-eval).
66
+ Higher values are better for all benchmarks. Empty cells mean not available.
67
+ """
68
+ return leaderboard_md
69
+
70
+
71
+ def make_leaderboard_md_live(elo_results):
72
+ leaderboard_md = f"""
73
+ # Leaderboard
74
+ Last updated: {elo_results["last_updated_datetime"]}
75
+ {elo_results["leaderboard_table"]}
76
+ """
77
+ return leaderboard_md
78
+
79
+
80
+ def update_elo_components(max_num_files, elo_results_file):
81
+ log_files = get_log_files(max_num_files)
82
+
83
+ # Leaderboard
84
+ if elo_results_file is None: # Do live update
85
+ battles = clean_battle_data(log_files)
86
+ elo_results = report_elo_analysis_results(battles)
87
+
88
+ leader_component_values[0] = make_leaderboard_md_live(elo_results)
89
+ leader_component_values[1] = elo_results["win_fraction_heatmap"]
90
+ leader_component_values[2] = elo_results["battle_count_heatmap"]
91
+ leader_component_values[3] = elo_results["bootstrap_elo_rating"]
92
+ leader_component_values[4] = elo_results["average_win_rate_bar"]
93
+
94
+ # Basic stats
95
+ basic_stats = report_basic_stats(log_files)
96
+ md0 = f"Last updated: {basic_stats['last_updated_datetime']}"
97
+
98
+ md1 = "### Action Histogram\n"
99
+ md1 += basic_stats["action_hist_md"] + "\n"
100
+
101
+ md2 = "### Anony. Vote Histogram\n"
102
+ md2 += basic_stats["anony_vote_hist_md"] + "\n"
103
+
104
+ md3 = "### Model Call Histogram\n"
105
+ md3 += basic_stats["model_hist_md"] + "\n"
106
+
107
+ md4 = "### Model Call (Last 24 Hours)\n"
108
+ md4 += basic_stats["num_chats_last_24_hours"] + "\n"
109
+
110
+ basic_component_values[0] = md0
111
+ basic_component_values[1] = basic_stats["chat_dates_bar"]
112
+ basic_component_values[2] = md1
113
+ basic_component_values[3] = md2
114
+ basic_component_values[4] = md3
115
+ basic_component_values[5] = md4
116
+
117
+
118
+ def update_worker(max_num_files, interval, elo_results_file):
119
+ while True:
120
+ tic = time.time()
121
+ update_elo_components(max_num_files, elo_results_file)
122
+ durtaion = time.time() - tic
123
+ print(f"update duration: {durtaion:.2f} s")
124
+ time.sleep(max(interval - durtaion, 0))
125
+
126
+
127
+ def load_demo(url_params, request: gr.Request):
128
+ logger.info(f"load_demo. ip: {request.client.host}. params: {url_params}")
129
+ return basic_component_values + leader_component_values
130
+
131
+
132
+ def model_hyperlink(model_name, link):
133
+ return f'<a target="_blank" href="{link}" style="color: var(--link-text-color); text-decoration: underline;text-decoration-style: dotted;">{model_name}</a>'
134
+
135
+
136
+ def load_leaderboard_table_csv(filename, add_hyperlink=True):
137
+ lines = open(filename).readlines()
138
+ heads = [v.strip() for v in lines[0].split(",")]
139
+ rows = []
140
+ for i in range(1, len(lines)):
141
+ row = [v.strip() for v in lines[i].split(",")]
142
+ for j in range(len(heads)):
143
+ item = {}
144
+ for h, v in zip(heads, row):
145
+ if h == "Arena Elo rating":
146
+ if v != "-":
147
+ v = int(ast.literal_eval(v))
148
+ else:
149
+ v = np.nan
150
+ elif h == "MMLU":
151
+ if v != "-":
152
+ v = round(ast.literal_eval(v) * 100, 1)
153
+ else:
154
+ v = np.nan
155
+ elif h == "MT-bench (win rate %)":
156
+ if v != "-":
157
+ v = round(ast.literal_eval(v[:-1]), 1)
158
+ else:
159
+ v = np.nan
160
+ elif h == "MT-bench (score)":
161
+ if v != "-":
162
+ v = round(ast.literal_eval(v), 2)
163
+ else:
164
+ v = np.nan
165
+ item[h] = v
166
+ if add_hyperlink:
167
+ item["Model"] = model_hyperlink(item["Model"], item["Link"])
168
+ rows.append(item)
169
+
170
+ return rows
171
+
172
+
173
+ def build_basic_stats_tab():
174
+ empty = "Loading ..."
175
+ basic_component_values[:] = [empty, None, empty, empty, empty, empty]
176
+
177
+ md0 = gr.Markdown(empty)
178
+ gr.Markdown("#### Figure 1: Number of model calls and votes")
179
+ plot_1 = gr.Plot(show_label=False)
180
+ with gr.Row():
181
+ with gr.Column():
182
+ md1 = gr.Markdown(empty)
183
+ with gr.Column():
184
+ md2 = gr.Markdown(empty)
185
+ with gr.Row():
186
+ with gr.Column():
187
+ md3 = gr.Markdown(empty)
188
+ with gr.Column():
189
+ md4 = gr.Markdown(empty)
190
+ return [md0, plot_1, md1, md2, md3, md4]
191
+
192
+ def get_full_table(arena_df, model_table_df):
193
+ values = []
194
+ for i in range(len(model_table_df)):
195
+ row = []
196
+ model_key = model_table_df.iloc[i]["key"]
197
+ model_name = model_table_df.iloc[i]["Model"]
198
+ # model display name
199
+ row.append(model_name)
200
+ if model_key in arena_df.index:
201
+ idx = arena_df.index.get_loc(model_key)
202
+ row.append(round(arena_df.iloc[idx]["rating"]))
203
+ else:
204
+ row.append(np.nan)
205
+ row.append(model_table_df.iloc[i]["MT-bench (score)"])
206
+ row.append(model_table_df.iloc[i]["MMLU"])
207
+ # Organization
208
+ row.append(model_table_df.iloc[i]["Organization"])
209
+ # license
210
+ row.append(model_table_df.iloc[i]["License"])
211
+
212
+ values.append(row)
213
+ values.sort(key=lambda x: -x[1] if not np.isnan(x[1]) else 1e9)
214
+ return values
215
+
216
+ def create_ranking_str(ranking, ranking_difference):
217
+ if ranking_difference > 0:
218
+ # return f"{int(ranking)} (\u2191{int(ranking_difference)})"
219
+ return f"{int(ranking)} \u2191"
220
+ elif ranking_difference < 0:
221
+ # return f"{int(ranking)} (\u2193{int(-ranking_difference)})"
222
+ return f"{int(ranking)} \u2193"
223
+ else:
224
+ return f"{int(ranking)}"
225
+
226
+ def recompute_final_ranking(arena_df):
227
+ # compute ranking based on CI
228
+ ranking = {}
229
+ for i, model_a in enumerate(arena_df.index):
230
+ ranking[model_a] = 1
231
+ for j, model_b in enumerate(arena_df.index):
232
+ if i == j:
233
+ continue
234
+ if arena_df.loc[model_b]["rating_q025"] > arena_df.loc[model_a]["rating_q975"]:
235
+ ranking[model_a] += 1
236
+ return list(ranking.values())
237
+
238
+ def get_arena_table(arena_df, model_table_df, arena_subset_df=None):
239
+ arena_df = arena_df.sort_values(by=["final_ranking", "rating"], ascending=[True, False])
240
+ arena_df = arena_df[arena_df["num_battles"] > 2000]
241
+ arena_df["final_ranking"] = recompute_final_ranking(arena_df)
242
+ arena_df = arena_df.sort_values(by=["final_ranking"], ascending=True)
243
+
244
+ # arena_df["final_ranking"] = range(1, len(arena_df) + 1)
245
+ # sort by rating
246
+ if arena_subset_df is not None:
247
+ # filter out models not in the arena_df
248
+ arena_subset_df = arena_subset_df[arena_subset_df.index.isin(arena_df.index)]
249
+ arena_subset_df = arena_subset_df.sort_values(by=["rating"], ascending=False)
250
+ # arena_subset_df = arena_subset_df.sort_values(by=["final_ranking"], ascending=True)
251
+ # arena_subset_df = arena_subset_df[arena_subset_df["num_battles"] > 500]
252
+ arena_subset_df["final_ranking"] = recompute_final_ranking(arena_subset_df)
253
+ # keep only the models in the subset in arena_df and recompute final_ranking
254
+ arena_df = arena_df[arena_df.index.isin(arena_subset_df.index)]
255
+ # recompute final ranking
256
+ arena_df["final_ranking"] = recompute_final_ranking(arena_df)
257
+
258
+ # assign ranking by the order
259
+ arena_subset_df["final_ranking_no_tie"] = range(1, len(arena_subset_df) + 1)
260
+ arena_df["final_ranking_no_tie"] = range(1, len(arena_df) + 1)
261
+ # join arena_df and arena_subset_df on index
262
+ arena_df = arena_subset_df.join(arena_df["final_ranking"], rsuffix="_global", how="inner")
263
+ arena_df["ranking_difference"] = arena_df["final_ranking_global"] - arena_df["final_ranking"]
264
+
265
+ # no tie version
266
+ # arena_df = arena_subset_df.join(arena_df["final_ranking_no_tie"], rsuffix="_global", how="inner")
267
+ # arena_df["ranking_difference"] = arena_df["final_ranking_no_tie_global"] - arena_df["final_ranking_no_tie"]
268
+
269
+ arena_df = arena_df.sort_values(by=["final_ranking", "rating"], ascending=[True, False])
270
+ arena_df["final_ranking"] = arena_df.apply(lambda x: create_ranking_str(x["final_ranking"], x["ranking_difference"]), axis=1)
271
+
272
+ values = []
273
+ for i in range(len(arena_df)):
274
+ row = []
275
+ model_key = arena_df.index[i]
276
+ try: # this is a janky fix for where the model key is not in the model table (model table and arena table dont contain all the same models)
277
+ model_name = model_table_df[model_table_df["key"] == model_key]["Model"].values[
278
+ 0
279
+ ]
280
+ # rank
281
+ ranking = arena_df.iloc[i].get("final_ranking") or i+1
282
+ row.append(ranking)
283
+ if arena_subset_df is not None:
284
+ row.append(arena_df.iloc[i].get("ranking_difference") or 0)
285
+ # model display name
286
+ row.append(model_name)
287
+ # elo rating
288
+ row.append(round(arena_df.iloc[i]["rating"]))
289
+ upper_diff = round(
290
+ arena_df.iloc[i]["rating_q975"] - arena_df.iloc[i]["rating"]
291
+ )
292
+ lower_diff = round(
293
+ arena_df.iloc[i]["rating"] - arena_df.iloc[i]["rating_q025"]
294
+ )
295
+ row.append(f"+{upper_diff}/-{lower_diff}")
296
+ # num battles
297
+ row.append(round(arena_df.iloc[i]["num_battles"]))
298
+ # Organization
299
+ row.append(
300
+ model_table_df[model_table_df["key"] == model_key]["Organization"].values[0]
301
+ )
302
+ # license
303
+ row.append(
304
+ model_table_df[model_table_df["key"] == model_key]["License"].values[0]
305
+ )
306
+ cutoff_date = model_table_df[model_table_df["key"] == model_key]["Knowledge cutoff date"].values[0]
307
+ if cutoff_date == "-":
308
+ row.append("Unknown")
309
+ else:
310
+ row.append(cutoff_date)
311
+ values.append(row)
312
+ except Exception as e:
313
+ print(f"{model_key} - {e}")
314
+ return values
315
+
316
+ key_to_category_name = {
317
+ "full": "Overall",
318
+ "coding": "Coding",
319
+ "long_user": "Longer Query",
320
+ "english": "English",
321
+ "chinese": "Chinese",
322
+ "french": "French",
323
+ "no_tie": "Exclude Ties",
324
+ "no_short": "Exclude Short",
325
+ }
326
+ cat_name_to_explanation = {
327
+ "Overall": "Overall Questions",
328
+ "Coding": "Coding: whether conversation contains code snippets",
329
+ "Longer Query": "Longer Query (>= 500 tokens)",
330
+ "English": "English Prompts",
331
+ "Chinese": "Chinese Prompts",
332
+ "French": "French Prompts",
333
+ "Exclude Ties": "Exclude Ties and Bothbad",
334
+ "Exclude Short": "User Query >= 5 tokens",
335
+ }
336
+
337
+
338
+ def build_leaderboard_tab(elo_results_file, leaderboard_table_file, show_plot=False):
339
+ arena_dfs = {}
340
+ category_elo_results = {}
341
+ if elo_results_file is None: # Do live update
342
+ default_md = "Loading ..."
343
+ p1 = p2 = p3 = p4 = None
344
+ else:
345
+ with open(elo_results_file, "rb") as fin:
346
+ elo_results = pickle.load(fin)
347
+ if "full" in elo_results:
348
+ print("KEYS ", elo_results.keys())
349
+ for k in elo_results.keys():
350
+ if k not in key_to_category_name:
351
+ continue
352
+ arena_dfs[key_to_category_name[k]] = elo_results[k]["leaderboard_table_df"]
353
+ category_elo_results[key_to_category_name[k]] = elo_results[k]
354
+
355
+ p1 = category_elo_results["Overall"]["win_fraction_heatmap"]
356
+ p2 = category_elo_results["Overall"]["battle_count_heatmap"]
357
+ p3 = category_elo_results["Overall"]["bootstrap_elo_rating"]
358
+ p4 = category_elo_results["Overall"]["average_win_rate_bar"]
359
+ arena_df = arena_dfs["Overall"]
360
+ default_md = make_default_md(arena_df, category_elo_results["Overall"])
361
+
362
+ md_1 = gr.Markdown(default_md, elem_id="leaderboard_markdown")
363
+ if leaderboard_table_file:
364
+ data = load_leaderboard_table_csv(leaderboard_table_file)
365
+ model_table_df = pd.DataFrame(data)
366
+
367
+ with gr.Tabs() as tabs:
368
+ # arena table
369
+ arena_table_vals = get_arena_table(arena_df, model_table_df)
370
+ with gr.Tab("Arena Elo", id=0):
371
+ md = make_arena_leaderboard_md(arena_df)
372
+ leaderboard_markdown = gr.Markdown(md, elem_id="leaderboard_markdown")
373
+ with gr.Row():
374
+ with gr.Column(scale=2):
375
+ category_dropdown = gr.Dropdown(choices=list(arena_dfs.keys()), label="Category", value="Overall")
376
+ default_category_details = make_category_arena_leaderboard_md(arena_df, arena_df, name="Overall")
377
+ with gr.Column(scale=4, variant="panel"):
378
+ category_deets = gr.Markdown(default_category_details, elem_id="category_deets")
379
+
380
+ elo_display_df = gr.Dataframe(
381
+ headers=[
382
+ "Rank",
383
+ "πŸ€– Model",
384
+ "⭐ Arena Elo",
385
+ "πŸ“Š 95% CI",
386
+ "πŸ—³οΈ Votes",
387
+ "Organization",
388
+ "License",
389
+ "Knowledge Cutoff",
390
+ ],
391
+ datatype=[
392
+ "number",
393
+ "markdown",
394
+ "number",
395
+ "str",
396
+ "number",
397
+ "str",
398
+ "str",
399
+ "str",
400
+ ],
401
+ value=arena_table_vals,
402
+ elem_id="arena_leaderboard_dataframe",
403
+ height=700,
404
+ column_widths=[70, 190, 110, 100, 90, 160, 150, 140],
405
+ wrap=True,
406
+ )
407
+
408
+ gr.Markdown(
409
+ f"""Note: we take the 95% confidence interval into account when determining a model's ranking.
410
+ A model is ranked higher only if its lower bound of model score is higher than the upper bound of the other model's score.
411
+ See Figure 3 below for visualization of the confidence intervals. More details in [notebook]({notebook_url}).
412
+ """,
413
+ elem_id="leaderboard_markdown"
414
+ )
415
+
416
+ leader_component_values[:] = [default_md, p1, p2, p3, p4]
417
+
418
+ if show_plot:
419
+ more_stats_md = gr.Markdown(
420
+ f"""## More Statistics for Chatbot Arena (Overall)""",
421
+ elem_id="leaderboard_header_markdown"
422
+ )
423
+ with gr.Row():
424
+ with gr.Column():
425
+ gr.Markdown(
426
+ "#### Figure 1: Fraction of Model A Wins for All Non-tied A vs. B Battles", elem_id="plot-title"
427
+ )
428
+ plot_1 = gr.Plot(p1, show_label=False, elem_id="plot-container")
429
+ with gr.Column():
430
+ gr.Markdown(
431
+ "#### Figure 2: Battle Count for Each Combination of Models (without Ties)", elem_id="plot-title"
432
+ )
433
+ plot_2 = gr.Plot(p2, show_label=False)
434
+ with gr.Row():
435
+ with gr.Column():
436
+ gr.Markdown(
437
+ "#### Figure 3: Confidence Intervals on Model Strength (via Bootstrapping)", elem_id="plot-title"
438
+ )
439
+ plot_3 = gr.Plot(p3, show_label=False)
440
+ with gr.Column():
441
+ gr.Markdown(
442
+ "#### Figure 4: Average Win Rate Against All Other Models (Assuming Uniform Sampling and No Ties)", elem_id="plot-title"
443
+ )
444
+ plot_4 = gr.Plot(p4, show_label=False)
445
+
446
+ with gr.Tab("Full Leaderboard", id=1):
447
+ md = make_full_leaderboard_md(elo_results)
448
+ gr.Markdown(md, elem_id="leaderboard_markdown")
449
+ full_table_vals = get_full_table(arena_df, model_table_df)
450
+ gr.Dataframe(
451
+ headers=[
452
+ "πŸ€– Model",
453
+ "⭐ Arena Elo",
454
+ "πŸ“ˆ MT-bench",
455
+ "πŸ“š MMLU",
456
+ "Organization",
457
+ "License",
458
+ ],
459
+ datatype=["markdown", "number", "number", "number", "str", "str"],
460
+ value=full_table_vals,
461
+ elem_id="full_leaderboard_dataframe",
462
+ column_widths=[200, 100, 100, 100, 150, 150],
463
+ height=700,
464
+ wrap=True,
465
+ )
466
+ if not show_plot:
467
+ gr.Markdown(
468
+ """ ## Visit our [HF space](https://huggingface.co/spaces/lmsys/chatbot-arena-leaderboard) for more analysis!
469
+ If you want to see more models, please help us [add them](https://github.com/lm-sys/FastChat/blob/main/docs/arena.md#how-to-add-a-new-model).
470
+ """,
471
+ elem_id="leaderboard_markdown",
472
+ )
473
+ else:
474
+ pass
475
+
476
+ def update_leaderboard_df(arena_table_vals):
477
+ elo_datarame = pd.DataFrame(arena_table_vals, columns=[ "Rank", "Delta", "πŸ€– Model", "⭐ Arena Elo", "πŸ“Š 95% CI", "πŸ—³οΈ Votes", "Organization", "License", "Knowledge Cutoff"])
478
+
479
+ # goal: color the rows based on the rank with styler
480
+ def highlight_max(s):
481
+ # all items in S which contain up arrow should be green, down arrow should be red, otherwise black
482
+ return ["color: green; font-weight: bold" if "\u2191" in v else "color: red; font-weight: bold" if "\u2193" in v else "" for v in s]
483
+
484
+ def highlight_rank_max(s):
485
+ return ["color: green; font-weight: bold" if v > 0 else "color: red; font-weight: bold" if v < 0 else "" for v in s]
486
+
487
+ return elo_datarame.style.apply(highlight_max, subset=["Rank"]).apply(highlight_rank_max, subset=["Delta"])
488
+
489
+ def update_leaderboard_and_plots(category):
490
+ arena_subset_df = arena_dfs[category]
491
+ arena_subset_df = arena_subset_df[arena_subset_df["num_battles"] > 500]
492
+ elo_subset_results = category_elo_results[category]
493
+ arena_df = arena_dfs["Overall"]
494
+ arena_values = get_arena_table(arena_df, model_table_df, arena_subset_df = arena_subset_df if category != "Overall" else None)
495
+ if category != "Overall":
496
+ arena_values = update_leaderboard_df(arena_values)
497
+ arena_values = gr.Dataframe(
498
+ headers=[
499
+ "Rank",
500
+ "Delta",
501
+ "πŸ€– Model",
502
+ "⭐ Arena Elo",
503
+ "πŸ“Š 95% CI",
504
+ "πŸ—³οΈ Votes",
505
+ "Organization",
506
+ "License",
507
+ "Knowledge Cutoff",
508
+ ],
509
+ datatype=[
510
+ "number",
511
+ "number",
512
+ "markdown",
513
+ "number",
514
+ "str",
515
+ "number",
516
+ "str",
517
+ "str",
518
+ "str",
519
+ ],
520
+ value=arena_values,
521
+ elem_id="arena_leaderboard_dataframe",
522
+ height=700,
523
+ column_widths=[60, 70, 190, 110, 100, 90, 160, 150, 140],
524
+ wrap=True,
525
+ )
526
+ else:
527
+ arena_values = gr.Dataframe(
528
+ headers=[
529
+ "Rank",
530
+ "πŸ€– Model",
531
+ "⭐ Arena Elo",
532
+ "πŸ“Š 95% CI",
533
+ "πŸ—³οΈ Votes",
534
+ "Organization",
535
+ "License",
536
+ "Knowledge Cutoff",
537
+ ],
538
+ datatype=[
539
+ "number",
540
+ "markdown",
541
+ "number",
542
+ "str",
543
+ "number",
544
+ "str",
545
+ "str",
546
+ "str",
547
+ ],
548
+ value=arena_values,
549
+ elem_id="arena_leaderboard_dataframe",
550
+ height=700,
551
+ column_widths=[70, 190, 110, 100, 90, 160, 150, 140],
552
+ wrap=True,
553
+ )
554
+
555
+ p1 = elo_subset_results["win_fraction_heatmap"]
556
+ p2 = elo_subset_results["battle_count_heatmap"]
557
+ p3 = elo_subset_results["bootstrap_elo_rating"]
558
+ p4 = elo_subset_results["average_win_rate_bar"]
559
+ more_stats_md = f"""## More Statistics for Chatbot Arena - {category}
560
+ """
561
+ leaderboard_md = make_category_arena_leaderboard_md(arena_df, arena_subset_df, name=category)
562
+ return arena_values, p1, p2, p3, p4, more_stats_md, leaderboard_md
563
+
564
+ category_dropdown.change(update_leaderboard_and_plots, inputs=[category_dropdown], outputs=[elo_display_df, plot_1, plot_2, plot_3, plot_4, more_stats_md, category_deets])
565
+
566
+ with gr.Accordion(
567
+ "πŸ“ Citation",
568
+ open=True,
569
+ ):
570
+ citation_md = """
571
+ ### Citation
572
+ Please cite the following paper if you find our leaderboard or dataset helpful.
573
+ ```
574
+ @misc{chiang2024chatbot,
575
+ title={Chatbot Arena: An Open Platform for Evaluating LLMs by Human Preference},
576
+ author={Wei-Lin Chiang and Lianmin Zheng and Ying Sheng and Anastasios Nikolas Angelopoulos and Tianle Li and Dacheng Li and Hao Zhang and Banghua Zhu and Michael Jordan and Joseph E. Gonzalez and Ion Stoica},
577
+ year={2024},
578
+ eprint={2403.04132},
579
+ archivePrefix={arXiv},
580
+ primaryClass={cs.AI}
581
+ }
582
+ """
583
+ gr.Markdown(citation_md, elem_id="leaderboard_markdown")
584
+ gr.Markdown(acknowledgment_md)
585
+
586
+ if show_plot:
587
+ return [md_1, plot_1, plot_2, plot_3, plot_4]
588
+ return [md_1]
589
+
590
+
591
+ block_css = """
592
+ #notice_markdown {
593
+ font-size: 104%
594
+ }
595
+ #notice_markdown th {
596
+ display: none;
597
+ }
598
+ #notice_markdown td {
599
+ padding-top: 6px;
600
+ padding-bottom: 6px;
601
+ }
602
+
603
+ #category_deets {
604
+ text-align: center;
605
+ padding: 0px;
606
+ padding-left: 5px;
607
+ }
608
+
609
+ #leaderboard_markdown {
610
+ font-size: 104%
611
+ }
612
+ #leaderboard_markdown td {
613
+ padding-top: 6px;
614
+ padding-bottom: 6px;
615
+ }
616
+
617
+ #leaderboard_header_markdown {
618
+ font-size: 104%;
619
+ text-align: center;
620
+ display:block;
621
+ }
622
+
623
+ #leaderboard_dataframe td {
624
+ line-height: 0.1em;
625
+ }
626
+
627
+ #plot-title {
628
+ text-align: center;
629
+ display:block;
630
+ }
631
+
632
+ #non-interactive-button {
633
+ display: inline-block;
634
+ padding: 10px 10px;
635
+ background-color: #f7f7f7; /* Super light grey background */
636
+ text-align: center;
637
+ font-size: 26px; /* Larger text */
638
+ border-radius: 0; /* Straight edges, no border radius */
639
+ border: 0px solid #dcdcdc; /* A light grey border to match the background */
640
+ user-select: none; /* The text inside the button is not selectable */
641
+ pointer-events: none; /* The button is non-interactive */
642
+ }
643
+
644
+ footer {
645
+ display:none !important
646
+ }
647
+ .sponsor-image-about img {
648
+ margin: 0 20px;
649
+ margin-top: 20px;
650
+ height: 40px;
651
+ max-height: 100%;
652
+ width: auto;
653
+ float: left;
654
+ }
655
+ """
656
+
657
+ acknowledgment_md = """
658
+ ### Acknowledgment
659
+ We thank [Kaggle](https://www.kaggle.com/), [MBZUAI](https://mbzuai.ac.ae/), [a16z](https://www.a16z.com/), [Together AI](https://www.together.ai/), [Anyscale](https://www.anyscale.com/), [HuggingFace](https://huggingface.co/) for their generous [sponsorship](https://lmsys.org/donations/).
660
+
661
+ <div class="sponsor-image-about">
662
+ <img src="https://storage.googleapis.com/public-arena-asset/kaggle.png" alt="Kaggle">
663
+ <img src="https://storage.googleapis.com/public-arena-asset/mbzuai.jpeg" alt="MBZUAI">
664
+ <img src="https://storage.googleapis.com/public-arena-asset/a16z.jpeg" alt="a16z">
665
+ <img src="https://storage.googleapis.com/public-arena-asset/together.png" alt="Together AI">
666
+ <img src="https://storage.googleapis.com/public-arena-asset/anyscale.png" alt="AnyScale">
667
+ <img src="https://storage.googleapis.com/public-arena-asset/huggingface.png" alt="HuggingFace">
668
+ </div>
669
+ """
670
+
671
+ def build_demo(elo_results_file, leaderboard_table_file):
672
+ text_size = gr.themes.sizes.text_lg
673
+ theme = gr.themes.Base(text_size=text_size)
674
+ theme.set(button_secondary_background_fill_hover="*primary_300",
675
+ button_secondary_background_fill_hover_dark="*primary_700")
676
+ with gr.Blocks(
677
+ title="Chatbot Arena Leaderboard",
678
+ theme=theme,
679
+ # theme = gr.themes.Base.load("theme.json"), # uncomment to use new cool theme
680
+ css=block_css,
681
+ ) as demo:
682
+ leader_components = build_leaderboard_tab(
683
+ elo_results_file, leaderboard_table_file, show_plot=True
684
+ )
685
+ return demo
686
+
687
+
688
+ if __name__ == "__main__":
689
+ parser = argparse.ArgumentParser()
690
+ parser.add_argument("--share", action="store_true")
691
+ parser.add_argument("--host", default="0.0.0.0")
692
+ parser.add_argument("--port", type=int, default=7860)
693
+ args = parser.parse_args()
694
+
695
+ elo_result_files = glob.glob("elo_results_*.pkl")
696
+ elo_result_files.sort(key=lambda x: int(x[12:-4]))
697
+ elo_result_file = elo_result_files[-1]
698
+
699
+ leaderboard_table_files = glob.glob("leaderboard_table_*.csv")
700
+ leaderboard_table_files.sort(key=lambda x: int(x[18:-4]))
701
+ leaderboard_table_file = leaderboard_table_files[-1]
702
+
703
+ demo = build_demo(elo_result_file, leaderboard_table_file)
704
+ demo.launch(share=args.share, server_name=args.host, server_port=args.port)