hynky HF staff commited on
Commit
2d9c70c
1 Parent(s): c9c1f2b

first commit

Browse files
Files changed (2) hide show
  1. app.py +331 -0
  2. requirements.txt +2 -0
app.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ast
2
+ from collections import defaultdict
3
+ from functools import partial
4
+ import itertools
5
+ import os
6
+ import re
7
+ from concurrent.futures import ThreadPoolExecutor
8
+ import numpy as np
9
+ from datetime import datetime
10
+
11
+ import gradio as gr
12
+ import huggingface_hub
13
+ import pandas as pd
14
+ import plotly.graph_objects as go
15
+ from huggingface_hub.file_download import repo_folder_name
16
+ from huggingface_hub.hf_api import RepoFile
17
+ from huggingface_hub.utils import EntryNotFoundError
18
+
19
+ FALLBACK_TOKEN_NAME = "HF_TOKEN"
20
+
21
+ def is_arary_like(x):
22
+ return isinstance(x, list) or isinstance(x, tuple) or isinstance(x, np.ndarray)
23
+
24
+ def get_task_type(df):
25
+ if all(isinstance(pred, str) for pred in df['predictions'].iloc[0]):
26
+ return "generative"
27
+ if all(is_arary_like(pred) and all(isinstance(item, float) for item in pred) for pred in df['predictions'].iloc[0]):
28
+ return "multiple_choice"
29
+ return "mixed"
30
+
31
+ def fix_df(df):
32
+ # For some reason some metrics and predictions are stored as strings
33
+ for col in ["predictions", "metrics", "choices", "gold", "gold_index"]:
34
+ df[col] = [ast.literal_eval(x) if isinstance(x, str) else x for x in df[col].values]
35
+ return df
36
+
37
+ def get_run_name_seed(run_name):
38
+ if "-seed-" not in run_name:
39
+ return run_name, 5
40
+ run_name, seed = run_name.split("-seed-")
41
+ return run_name, int(seed)
42
+
43
+ def fetch_repo_structure(repo_name, oauth_token: gr.OAuthToken | None = None):
44
+ token = os.environ.get(FALLBACK_TOKEN_NAME)
45
+ if oauth_token:
46
+ token = oauth_token.token
47
+
48
+ files = list(huggingface_hub.list_repo_tree(repo_name, "details", recursive=False, token=token))
49
+
50
+ runs = {file.path.split('/')[-1] for file in files if isinstance(file, huggingface_hub.hf_api.RepoFolder)}
51
+ if not runs:
52
+ return {}, gr.update(choices=[], value=None)
53
+
54
+ def process_run(run):
55
+ run_files = list(huggingface_hub.list_repo_tree(repo_name, f"details/{run}", recursive=False, token=token))
56
+ return run, [file.path.split('/')[-1] for file in run_files if isinstance(file, huggingface_hub.hf_api.RepoFolder)]
57
+
58
+ with ThreadPoolExecutor() as executor:
59
+ results = list(executor.map(process_run, runs))
60
+
61
+ checkpoints_dict = dict(results)
62
+
63
+ return checkpoints_dict, gr.update(choices=list(checkpoints_dict), value=None)
64
+
65
+ def update_checkpoints(selected_runs, checkpoints):
66
+ if not selected_runs:
67
+ return gr.update(choices=[], value=None)
68
+
69
+ common_checkpoints = set(checkpoints[selected_runs[0]])
70
+ for run in selected_runs[1:]:
71
+ common_checkpoints.intersection_update(set(checkpoints[run]))
72
+
73
+ common_checkpoints = sorted(list(common_checkpoints))
74
+
75
+ return gr.update(choices=common_checkpoints, value=common_checkpoints[0] if common_checkpoints else None)
76
+
77
+
78
+ def select_runs_by_regex(runs, current_selected, regex_to_select):
79
+ comp_re = re.compile(regex_to_select)
80
+ return list(sorted(set((current_selected if current_selected else []) +
81
+ [run for run in runs if comp_re.fullmatch(run)])))
82
+
83
+ def select_runs_by_language(runs, current_selected, language):
84
+ if language:
85
+ return select_runs_by_regex(runs, current_selected, f".*-{language}-.*")
86
+ return current_selected
87
+
88
+ def fetch_available_tasks(repo_name, runs_to_fetch, checkpoint) -> dict[str, dict[str, str]]:
89
+ token = os.environ.get(FALLBACK_TOKEN_NAME)
90
+
91
+ all_tasks = defaultdict(lambda: defaultdict(dict))
92
+ for run in runs_to_fetch:
93
+ try:
94
+ files = huggingface_hub.list_repo_tree(repo_name, f"details/{run}/{checkpoint}", token=token)
95
+ parquet_files = [f.path.split('/')[-1] for f in files if f.path.endswith('.parquet')]
96
+
97
+ for full_filename in parquet_files:
98
+ task_name, date_str = full_filename.replace('.parquet', '').rsplit('_', 1)
99
+ date = datetime.strptime(date_str, '%Y-%m-%dT%H-%M-%S.%f')
100
+
101
+ if run not in all_tasks[task_name] or date > all_tasks[task_name][run]['date']:
102
+ all_tasks[task_name][run] = {'filename': full_filename, 'date': date}
103
+ except EntryNotFoundError:
104
+ print(f"Checkpoint not found for run: {run}")
105
+
106
+ available_tasks = {
107
+ task: {run: info['filename'] for run, info in runs.items()}
108
+ for task, runs in all_tasks.items()
109
+ if set(runs.keys()) == set(runs_to_fetch)
110
+ }
111
+
112
+ return available_tasks
113
+
114
+ def fetch_run_results(repo_name, runs_to_fetch, checkpoint,
115
+ oauth_token: gr.OAuthToken | None = None, progress=gr.Progress()):
116
+
117
+ task_runs_dict = fetch_available_tasks(repo_name, runs_to_fetch, checkpoint)
118
+ task_names = list(task_runs_dict.keys())
119
+ return gr.update(choices=task_names, value=task_names[0] if task_names else None), task_runs_dict
120
+
121
+
122
+ def filter_with_metric(df, selected_runs, metric_name):
123
+ if df is None or not selected_runs or not metric_name:
124
+ return None
125
+ kept_metrics = [f"metric_{metric_name}_{run_name}" for run_name in selected_runs]
126
+ other_metrics = [col for col in df.columns if col.startswith(f"metric_") and col not in kept_metrics]
127
+ df = df.drop(columns=other_metrics)
128
+ widths = get_column_widths(df)
129
+ df = consize_runname_metric(df, selected_runs, metric_name)
130
+ return gr.update(value=df, column_widths=widths)
131
+
132
+ def get_column_widths(df):
133
+ column_widths = []
134
+ for col in df.columns:
135
+ if col == "full_prompt":
136
+ column_widths.append("300px")
137
+ elif col in ["choices", "gold"]:
138
+ column_widths.append("250px")
139
+ elif col.startswith("metric_"):
140
+ column_widths.append("100px")
141
+ else:
142
+ column_widths.append("200px") # Default width for other columns
143
+ return column_widths
144
+
145
+
146
+ def consize_runname_metric(df, run_names, metric_name):
147
+ """
148
+ Turns metric columns (metric_{metric}_{run_name}) into {metric}_i
149
+ """
150
+ # Initialize the new column with empty strings
151
+ for idx, run_name in enumerate(run_names):
152
+ original_column = f"metric_{metric_name}_{run_name}"
153
+ if original_column in df.columns:
154
+ # Append the run name and metric value to the concise column
155
+ df[f"{metric_name}_{idx}"] = df[original_column]
156
+ df = df.drop(columns=[original_column])
157
+ return df
158
+
159
+
160
+ def load_task_data(repo_name, runs_to_fetch, checkpoint, task_name, tasks_files, progress=gr.Progress()):
161
+ token = os.environ.get(FALLBACK_TOKEN_NAME)
162
+ if not runs_to_fetch or not task_name:
163
+ return None, None, None
164
+
165
+ def fetch_run_file(run_to_fetch):
166
+ file_path = f"details/{run_to_fetch}/{checkpoint}/{tasks_files[task_name][run_to_fetch]}"
167
+ try:
168
+ cached_path = huggingface_hub.hf_hub_download(repo_name, file_path, token=token)
169
+ df = pd.read_parquet(cached_path)
170
+ return df, run_to_fetch
171
+ except EntryNotFoundError:
172
+ print(f"File not found: {file_path}")
173
+ return None, run_to_fetch
174
+
175
+ with ThreadPoolExecutor() as pool:
176
+ results = list(progress.tqdm(pool.map(fetch_run_file, runs_to_fetch), total=len(runs_to_fetch),
177
+ desc="Fetching run data..."))
178
+
179
+ dfs = [fix_df(df) for df, _ in results if df is not None]
180
+ run_names = [run for _, run in results if run is not None]
181
+
182
+ if not dfs:
183
+ return None, None, gr.update(choices=[], value=None)
184
+
185
+ task_type = get_task_type(dfs[0])
186
+ def prepare_df(df, run_name, task_type):
187
+ def get_choice_predictions(df, task_type):
188
+ # For some evals it's string for other it's list
189
+ predictions = df['predictions']
190
+ if task_type == "generative":
191
+ return predictions
192
+
193
+ if task_type == "multiple_choice":
194
+ n_choices = len(df['choices'])
195
+ return df['choices'][np.argmax([pred[0] for pred in predictions[:n_choices]])]
196
+
197
+ if task_type == "mixed":
198
+ return predictions[0]
199
+
200
+ return predictions
201
+
202
+ prepared_df = pd.DataFrame({
203
+ 'full_prompt': df['full_prompt'],
204
+ f'{run_name}': df.apply(partial(get_choice_predictions, task_type=task_type), axis=1)
205
+ })
206
+ # For some reason some metrics are stored as strings
207
+ metrics = df['metrics']
208
+ # Assume all metrics are the same
209
+ for metric_key in metrics[0].keys():
210
+ prepared_df[f'metric_{metric_key}_{run_name}'] = [metric[metric_key] for metric in metrics]
211
+ return prepared_df.set_index('full_prompt')
212
+
213
+ def get_gold_label(df, task_type):
214
+ if task_type == "generative":
215
+ return df['gold']
216
+ return [df['choices'][idx] for idx in df['gold_index']]
217
+
218
+ # Prepare the first DataFrame with choices and gold
219
+ combined_df = dfs[0][['full_prompt', 'choices']].set_index('full_prompt')
220
+ combined_df['gold'] = dfs[0].apply(lambda row: get_gold_label(row, task_type), axis=1).values
221
+
222
+ # Join all prepared DataFrames
223
+ for df, run_name in zip(dfs, run_names):
224
+ prepared_df = prepare_df(df, run_name, task_type)
225
+ combined_df = combined_df.join(prepared_df, how='outer', )
226
+
227
+
228
+ available_metrics = list(set("_".join(col.split('_')[1:-1]) for col in combined_df.columns if col.startswith("metric_")))
229
+ combined_df = combined_df.reset_index()
230
+
231
+ return combined_df, filter_with_metric(combined_df, runs_to_fetch, available_metrics[0]), gr.update(choices=available_metrics, value=available_metrics[0])
232
+
233
+ def render_results_table(df: pd.DataFrame):
234
+ if df is None or df.empty:
235
+ return None
236
+
237
+ # Select a subset of 100 examples
238
+ df_subset = df.sample(n=min(100, len(df)), random_state=42)
239
+
240
+ # Prepare the data for display
241
+ display_data = []
242
+ for _, row in df_subset.iterrows():
243
+ example_data = {
244
+ 'text': row['example'],
245
+ 'choices': row['choices'],
246
+ 'gold_index': row['gold_index'],
247
+ }
248
+ for run in df['run'].unique():
249
+ run_data = df[(df['run'] == run) & (df['example'] == row['example'])]
250
+ if not run_data.empty:
251
+ example_data[f'{run}_prediction'] = run_data['predictions'].values[0]
252
+ example_data[f'{run}_score'] = run_data['metrics'].values[0]
253
+ display_data.append(example_data)
254
+
255
+ return pd.DataFrame(display_data)
256
+
257
+ with gr.Blocks() as demo:
258
+ runs_checkpoints = gr.State({})
259
+ results_df_full = gr.State(None)
260
+ tasks_files = gr.State({})
261
+ login_button = gr.LoginButton(visible=False)
262
+ repo = gr.Textbox(label="HF Repo", value="HuggingFaceFW-Dev/multiligual-ablation-logs-dev", visible=True)
263
+ with gr.Column():
264
+ gr.Markdown("# FineWeb experiments results explorer")
265
+ with gr.Row():
266
+ with gr.Column():
267
+ select_by_regex_text = gr.Textbox(label="Regex to select runs",
268
+ value="ind_minhash(-CC-MAIN-|_)\\d{4}-\\d{2}-seed.*")
269
+ select_by_regex_button = gr.Button("Select matching runs")
270
+ with gr.Column():
271
+ select_by_language = gr.Dropdown(choices=["ar", "fr", "ru", "hi", "th", "tr", "zh", "sw", "te"],
272
+ interactive=True, label="Select by language",
273
+ info="Choose a language to prefill the regex")
274
+ selected_runs = gr.Dropdown(choices=[], interactive=True, multiselect=True, label="Selected runs")
275
+ checkpoint = gr.Dropdown(choices=[], interactive=True, label="Checkpoint")
276
+ fetch_res = gr.Button("Fetch results")
277
+ task_name = gr.Dropdown(choices=[], interactive=True, label="Task name")
278
+ metric_name = gr.Dropdown(choices=[], interactive=True, label="Metric")
279
+ results_df = gr.Dataframe(interactive=False, wrap=True)
280
+
281
+ # Run selection
282
+ gr.on(
283
+ triggers=[repo.change],
284
+ fn=fetch_repo_structure, inputs=[repo], outputs=[runs_checkpoints, selected_runs],
285
+ )
286
+ gr.on(
287
+ triggers=[select_by_regex_button.click],
288
+ fn=select_runs_by_regex,
289
+ inputs=[runs_checkpoints, selected_runs, select_by_regex_text], outputs=[selected_runs]
290
+ )
291
+ gr.on(
292
+ triggers=[select_by_language.change],
293
+ fn=select_runs_by_language,
294
+ inputs=[runs_checkpoints, selected_runs, select_by_language], outputs=[selected_runs]
295
+ )
296
+
297
+ # Update checkpoints based on selected runs
298
+ gr.on(
299
+ triggers=[selected_runs.change],
300
+ fn=update_checkpoints,
301
+ inputs=[selected_runs, runs_checkpoints],
302
+ outputs=[checkpoint]
303
+ )
304
+
305
+ # Fetch available tasks
306
+ gr.on(
307
+ triggers=[fetch_res.click],
308
+ fn=fetch_run_results,
309
+ inputs=[repo, selected_runs, checkpoint],
310
+ outputs=[task_name, tasks_files]
311
+ )
312
+
313
+
314
+ # Update results when task name or metric changes
315
+ gr.on(
316
+ triggers=[task_name.change],
317
+ fn=load_task_data,
318
+ inputs=[repo, selected_runs, checkpoint, task_name, tasks_files],
319
+ outputs=[results_df_full, results_df, metric_name]
320
+ )
321
+
322
+ gr.on(
323
+ triggers=[metric_name.change],
324
+ fn=filter_with_metric,
325
+ inputs=[results_df_full, selected_runs, metric_name],
326
+ outputs=[results_df]
327
+ )
328
+
329
+ demo.load(fn=fetch_repo_structure, inputs=[repo], outputs=[runs_checkpoints, selected_runs])
330
+
331
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ pandas
2
+ plotly