margsli commited on
Commit
b260191
β€’
1 Parent(s): ce89e6a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +378 -0
app.py ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ notebook_url = "https://colab.research.google.com/drive/1KdwokPjirkTmpO_P1WByFNFiqxWQquwH#scrollTo=o_CpbkGEbhrK"
12
+
13
+
14
+ basic_component_values = [None] * 6
15
+ leader_component_values = [None] * 5
16
+
17
+
18
+ def make_default_md(arena_df, elo_results):
19
+
20
+ leaderboard_md = f"""
21
+ # πŸ†
22
+ | [GitHub](https://)
23
+ """
24
+ return leaderboard_md
25
+
26
+
27
+ def make_arena_leaderboard_md(arena_df):
28
+ total_votes = sum(arena_df["num_battles"]) // 2
29
+ total_models = len(arena_df)
30
+
31
+ leaderboard_md = f"""
32
+ Last updated: April 9, 2024.
33
+ Find more analysis in the [notebook]({notebook_url}).
34
+ """
35
+ return leaderboard_md
36
+
37
+
38
+ def make_full_leaderboard_md(elo_results):
39
+ leaderboard_md = f"""
40
+ enchmarks are displayed:
41
+ """
42
+ return leaderboard_md
43
+
44
+
45
+ def make_leaderboard_md_live(elo_results):
46
+ leaderboard_md = f"""
47
+ # Leaderboard
48
+ Last updated: {elo_results["last_updated_datetime"]}
49
+ {elo_results["leaderboard_table"]}
50
+ """
51
+ return leaderboard_md
52
+
53
+
54
+ def update_elo_components(max_num_files, elo_results_file):
55
+ log_files = get_log_files(max_num_files)
56
+
57
+ # Leaderboard
58
+ if elo_results_file is None: # Do live update
59
+ battles = clean_battle_data(log_files)
60
+ elo_results = report_elo_analysis_results(battles)
61
+
62
+ leader_component_values[0] = make_leaderboard_md_live(elo_results)
63
+ leader_component_values[1] = elo_results["win_fraction_heatmap"]
64
+
65
+ # Basic stats
66
+ basic_stats = report_basic_stats(log_files)
67
+ md0 = f"Last updated: {basic_stats['last_updated_datetime']}"
68
+
69
+ md1 = "### Action Histogram\n"
70
+ md1 += basic_stats["action_hist_md"] + "\n"
71
+
72
+ basic_component_values[0] = md0
73
+ basic_component_values[1] = basic_stats["chat_dates_bar"]
74
+ basic_component_values[2] = md1]
75
+
76
+
77
+ def update_worker(max_num_files, interval, elo_results_file):
78
+ while True:
79
+ tic = time.time()
80
+ update_elo_components(max_num_files, elo_results_file)
81
+ durtaion = time.time() - tic
82
+ print(f"update duration: {durtaion:.2f} s")
83
+ time.sleep(max(interval - durtaion, 0))
84
+
85
+
86
+ def load_demo(url_params, request: gr.Request):
87
+ logger.info(f"load_demo. ip: {request.client.host}. params: {url_params}")
88
+ return basic_component_values + leader_component_values
89
+
90
+
91
+ def model_hyperlink(model_name, link):
92
+ return f'<a target="_blank" href="{link}" style="color: var(--link-text-color); text-decoration: underline;text-decoration-style: dotted;">{model_name}</a>'
93
+
94
+
95
+ def load_leaderboard_table_csv(filename, add_hyperlink=True):
96
+ lines = open(filename).readlines()
97
+ heads = [v.strip() for v in lines[0].split(",")]
98
+ rows = []
99
+ for i in range(1, len(lines)):
100
+ row = [v.strip() for v in lines[i].split(",")]
101
+ for j in range(len(heads)):
102
+ item = {}
103
+ for h, v in zip(heads, row):
104
+ if h == "":
105
+ if v != "-":
106
+ v = int(ast.literal_eval(v))
107
+ else:
108
+ v = np.nan
109
+ item[h] = v
110
+ if add_hyperlink:
111
+ item["Model"] = model_hyperlink(item["Model"], item["Link"])
112
+ rows.append(item)
113
+
114
+ return rows
115
+
116
+
117
+ def build_basic_stats_tab():
118
+ empty = "Loading ..."
119
+ basic_component_values[:] = [empty, None, empty, empty, empty, empty]
120
+
121
+ md0 = gr.Markdown(empty)
122
+ gr.Markdown("#### Figure 1:")
123
+ plot_1 = gr.Plot(show_label=False)
124
+ with gr.Row():
125
+ with gr.Column():
126
+ md1 = gr.Markdown(empty)
127
+ with gr.Column():
128
+ md2 = gr.Markdown(empty)
129
+ with gr.Row():
130
+ with gr.Column():
131
+ md3 = gr.Markdown(empty)
132
+ with gr.Column():
133
+ md4 = gr.Markdown(empty)
134
+ return [md0, plot_1, md1, md2, md3, md4]
135
+
136
+ def get_full_table(arena_df, model_table_df):
137
+ values = []
138
+ for i in range(len(model_table_df)):
139
+ row = []
140
+ model_key = model_table_df.iloc[i]["key"]
141
+ model_name = model_table_df.iloc[i]["Model"]
142
+ # model display name
143
+ row.append(model_name)
144
+ if model_key in arena_df.index:
145
+ idx = arena_df.index.get_loc(model_key)
146
+ row.append(round(arena_df.iloc[idx]["rating"]))
147
+ else:
148
+ row.append(np.nan)
149
+ # Organization
150
+ row.append(model_table_df.iloc[i]["Organization"])
151
+ # license
152
+ row.append(model_table_df.iloc[i]["License"])
153
+
154
+ values.append(row)
155
+ values.sort(key=lambda x: -x[1] if not np.isnan(x[1]) else 1e9)
156
+ return values
157
+
158
+
159
+ def get_arena_table(arena_df, model_table_df):
160
+ # sort by rating
161
+ arena_df = arena_df.sort_values(by=["final_ranking", "rating"], ascending=[True, False])
162
+ values = []
163
+ for i in range(len(arena_df)):
164
+ row = []
165
+ model_key = arena_df.index[i]
166
+ model_name = model_table_df[model_table_df["key"] == model_key]["Model"].values[
167
+ 0
168
+ ]
169
+
170
+ # rank
171
+ ranking = arena_df.iloc[i].get("final_ranking") or i+1
172
+ row.append(ranking)
173
+ # model display name
174
+ row.append(model_name)
175
+ # elo rating
176
+ row.append(round(arena_df.iloc[i]["rating"]))
177
+ upper_diff = round(
178
+ arena_df.iloc[i]["rating_q975"] - arena_df.iloc[i]["rating"]
179
+ )
180
+ lower_diff = round(
181
+ arena_df.iloc[i]["rating"] - arena_df.iloc[i]["rating_q025"]
182
+ )
183
+ row.append(f"+{upper_diff}/-{lower_diff}")
184
+ # num battles
185
+ row.append(round(arena_df.iloc[i]["num_battles"]))
186
+ # Organization
187
+ row.append(
188
+ model_table_df[model_table_df["key"] == model_key]["Organization"].values[0]
189
+ )
190
+ # license
191
+ row.append(
192
+ model_table_df[model_table_df["key"] == model_key]["License"].values[0]
193
+ )
194
+
195
+ cutoff_date = model_table_df[model_table_df["key"] == model_key]["Knowledge cutoff date"].values[0]
196
+ if cutoff_date == "-":
197
+ row.append("Unknown")
198
+ else:
199
+ row.append(cutoff_date)
200
+ values.append(row)
201
+ return values
202
+
203
+ def build_leaderboard_tab(elo_results_file, leaderboard_table_file, show_plot=False):
204
+ if elo_results_file is None: # Do live update
205
+ default_md = "Loading ..."
206
+ p1 = p2 = p3 = p4 = None
207
+ else:
208
+ with open(elo_results_file, "rb") as fin:
209
+ elo_results = pickle.load(fin)
210
+ if "full" in elo_results:
211
+ elo_results = elo_results["full"]
212
+
213
+ arena_df = elo_results["leaderboard_table_df"]
214
+ default_md = make_default_md(arena_df, elo_results)
215
+
216
+ md_1 = gr.Markdown(default_md, elem_id="leaderboard_markdown")
217
+ if leaderboard_table_file:
218
+ data = load_leaderboard_table_csv(leaderboard_table_file)
219
+ model_table_df = pd.DataFrame(data)
220
+
221
+ with gr.Tabs() as tabs:
222
+ # arena table
223
+ arena_table_vals = get_arena_table(arena_df, model_table_df)
224
+ with gr.Tab("Arena Elo", id=0):
225
+ md = make_arena_leaderboard_md(arena_df)
226
+ gr.Markdown(md, elem_id="leaderboard_markdown")
227
+ gr.Dataframe(
228
+ headers=[
229
+ "Rank",
230
+ "πŸ€– Model",
231
+ "Organization",
232
+ "License",
233
+ ],
234
+ datatype=[
235
+ "str",
236
+ "markdown",
237
+ "str",
238
+ "str",
239
+ ],
240
+ value=arena_table_vals,
241
+ elem_id="arena_leaderboard_dataframe",
242
+ height=700,
243
+ column_widths=[50, 200, 120, 100, 100, 150, 150, 100],
244
+ wrap=True,
245
+ )
246
+ with gr.Tab("Full Leaderboard", id=1):
247
+ md = make_full_leaderboard_md(elo_results)
248
+ gr.Markdown(md, elem_id="leaderboard_markdown")
249
+ full_table_vals = get_full_table(arena_df, model_table_df)
250
+ gr.Dataframe(
251
+ headers=[
252
+ "πŸ€– Model",
253
+ "πŸ“š MMLU",
254
+ "Organization",
255
+ "License",
256
+ ],
257
+ datatype=["markdown", "number", "str", "str"],
258
+ value=full_table_vals,
259
+ elem_id="full_leaderboard_dataframe",
260
+ column_widths=[200, 100, 100, 100, 150, 150],
261
+ height=700,
262
+ wrap=True,
263
+ )
264
+ if not show_plot:
265
+ gr.Markdown(
266
+ """ ## Visit our [HF space](https://huggingface.co/spaces/) for more analysis!
267
+ """,
268
+ elem_id="leaderboard_markdown",
269
+ )
270
+ else:
271
+ pass
272
+
273
+ gr.Markdown(
274
+ f"""
275
+ """,
276
+ elem_id="leaderboard_markdown"
277
+ )
278
+
279
+ leader_component_values[:] = [default_md, p1, p2, p3, p4]
280
+
281
+ if show_plot:
282
+ gr.Markdown(
283
+ f"""## More Statistics\n
284
+ Below are figures for more statistics. The code for generating them is also included in this [notebook]({notebook_url}).
285
+ """,
286
+ elem_id="leaderboard_markdown"
287
+ )
288
+ with gr.Row():
289
+ with gr.Column():
290
+ gr.Markdown(
291
+ "#### Figure 1: "
292
+ )
293
+ with gr.Column():
294
+ gr.Markdown(
295
+ "#### Figure 2: "
296
+ )
297
+
298
+ with gr.Accordion(
299
+ "πŸ“ Citation",
300
+ open=True,
301
+ ):
302
+ citation_md = """
303
+ ### Citation
304
+ """
305
+ gr.Markdown(citation_md, elem_id="leaderboard_markdown")
306
+ gr.Markdown(acknowledgment_md)
307
+
308
+ if show_plot:
309
+ return [md_1, plot_1, plot_2, plot_3, plot_4]
310
+ return [md_1]
311
+
312
+ block_css = """
313
+ #notice_markdown {
314
+ font-size: 104%
315
+ }
316
+ #notice_markdown th {
317
+ display: none;
318
+ }
319
+ #notice_markdown td {
320
+ padding-top: 6px;
321
+ padding-bottom: 6px;
322
+ }
323
+ #leaderboard_markdown {
324
+ font-size: 104%
325
+ }
326
+ #leaderboard_markdown td {
327
+ padding-top: 6px;
328
+ padding-bottom: 6px;
329
+ }
330
+ #leaderboard_dataframe td {
331
+ line-height: 0.1em;
332
+ }
333
+ footer {
334
+ display:none !important
335
+ }
336
+ .sponsor-image-about img {
337
+ margin: 0 20px;
338
+ margin-top: 20px;
339
+ height: 40px;
340
+ max-height: 100%;
341
+ width: auto;
342
+ float: left;
343
+ }
344
+ """
345
+
346
+ acknowledgment_md = """
347
+ ### Acknowledgment
348
+ """
349
+
350
+ def build_demo(elo_results_file, leaderboard_table_file):
351
+ text_size = gr.themes.sizes.text_lg
352
+
353
+ with gr.Blocks(
354
+ title="Leaderboard",
355
+ theme=gr.themes.Base(text_size=text_size),
356
+ css=block_css,
357
+ ) as demo:
358
+ leader_components = build_leaderboard_tab(
359
+ elo_results_file, leaderboard_table_file, show_plot=True
360
+ )
361
+ return demo
362
+
363
+
364
+ if __name__ == "__main__":
365
+ parser = argparse.ArgumentParser()
366
+ parser.add_argument("--share", action="store_true")
367
+ args = parser.parse_args()
368
+
369
+ elo_result_files = glob.glob("elo_results_*.pkl")
370
+ elo_result_files.sort(key=lambda x: int(x[12:-4]))
371
+ elo_result_file = elo_result_files[-1]
372
+
373
+ leaderboard_table_files = glob.glob("leaderboard_table_*.csv")
374
+ leaderboard_table_files.sort(key=lambda x: int(x[18:-4]))
375
+ leaderboard_table_file = leaderboard_table_files[-1]
376
+
377
+ demo = build_demo(elo_result_file, leaderboard_table_file)
378
+ demo.launch(share=args.share)