chriscanal commited on
Commit
319b0b7
1 Parent(s): 2ef734a

Creating functions for plotting results over time

Browse files

I've added two graphs and human baselines for each metric. I think this should help us track progress over time more easily.

![Open LLM Leaderboard with Graphs.png](https://cdn-uploads.huggingface.co/production/uploads/62e2c159555a866437a920ca/BAPHzl99NtWdM7hRYa1dT.png)

Files changed (1) hide show
  1. src/display_models/plot_results.py +169 -0
src/display_models/plot_results.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import altair as alt
3
+ import pickle
4
+ from datetime import datetime, timezone
5
+ from typing import List, Dict, Tuple, Any, Union
6
+
7
+ # Average ⬆️ human baseline is 0.897 (source: averaging human baselines below)
8
+ # ARC human baseline is 0.80 (source: https://lab42.global/arc/)
9
+ # HellaSwag human baseline is 0.95 (source: https://deepgram.com/learn/hellaswag-llm-benchmark-guide)
10
+ # MMLU human baseline is 0.898 (source: https://openreview.net/forum?id=d7KBjmI3GmQ)
11
+ # TruthfulQA human baseline is 0.94(source: https://arxiv.org/pdf/2109.07958.pdf)
12
+ # Define the human baselines
13
+ HUMAN_BASELINES = {
14
+ "Average ⬆️": 0.897 * 100,
15
+ "ARC": 0.80 * 100,
16
+ "HellaSwag": 0.95 * 100,
17
+ "MMLU": 0.898 * 100,
18
+ "TruthfulQA": 0.94 * 100,
19
+ }
20
+
21
+
22
+ def to_datetime(model_info: Tuple[str, Any]) -> datetime:
23
+ """
24
+ Converts the lastModified attribute of the object to datetime.
25
+
26
+ :param model_info: A tuple containing the name and object.
27
+ The object must have a lastModified attribute
28
+ with a string representing the date and time.
29
+ :return: A datetime object converted from the lastModified attribute of the input object.
30
+ """
31
+ name, obj = model_info
32
+ return datetime.strptime(obj.lastModified, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=timezone.utc)
33
+
34
+
35
+ def join_model_info_with_results(results_df: pd.DataFrame) -> pd.DataFrame:
36
+ """
37
+ Integrates model information with the results DataFrame by matching 'Model sha'.
38
+
39
+ :param results_df: A DataFrame containing results information including 'Model sha' column.
40
+ :return: A DataFrame with updated 'Results Date' columns, which are synchronized with model information.
41
+ """
42
+ # load cache from disk
43
+ try:
44
+ with open("model_info_cache.pkl", "rb") as f:
45
+ model_info_cache = pickle.load(f)
46
+ except (EOFError, FileNotFoundError):
47
+ model_info_cache = {}
48
+
49
+ # Sort date strings using datetime objects as keys
50
+ sorted_dates = sorted(list(model_info_cache.items()), key=to_datetime, reverse=True)
51
+ results_df["Results Date"] = datetime.now().replace(tzinfo=timezone.utc)
52
+
53
+ # Define the date format string
54
+ date_format = "%Y-%m-%dT%H:%M:%S.%fZ"
55
+
56
+ # Iterate over sorted_dates and update the dataframe
57
+ for name, obj in sorted_dates:
58
+ # Convert the lastModified string to a datetime object
59
+ last_modified_datetime = datetime.strptime(obj.lastModified, date_format).replace(tzinfo=timezone.utc)
60
+
61
+ # Update the "Results Date" column where "Model sha" equals obj.sha
62
+ results_df.loc[results_df["Model sha"] == obj.sha, "Results Date"] = last_modified_datetime
63
+ return results_df
64
+
65
+
66
+ def create_scores_df(results_df: pd.DataFrame) -> pd.DataFrame:
67
+ """
68
+ Generates a DataFrame containing the maximum scores until each result date.
69
+
70
+ :param results_df: A DataFrame containing result information including metric scores and result dates.
71
+ :return: A new DataFrame containing the maximum scores until each result date for every metric.
72
+ """
73
+ # Step 1: Ensure 'Results Date' is in datetime format and sort the DataFrame by it
74
+ results_df["Results Date"] = pd.to_datetime(results_df["Results Date"])
75
+ results_df.sort_values(by="Results Date", inplace=True)
76
+
77
+ # Step 2: Initialize the scores dictionary
78
+ scores = {
79
+ "Average ⬆️": [],
80
+ "ARC": [],
81
+ "HellaSwag": [],
82
+ "MMLU": [],
83
+ "TruthfulQA": [],
84
+ "Result Date": [],
85
+ }
86
+
87
+ # Step 3: Iterate over the rows of the DataFrame and update the scores dictionary
88
+ for i, row in results_df.iterrows():
89
+ date = row["Results Date"]
90
+ for column in scores.keys():
91
+ if column == "Result Date":
92
+ if not scores[column] or scores[column][-1] <= date:
93
+ scores[column].append(date)
94
+ continue
95
+ current_max = scores[column][-1] if scores[column] else float("-inf")
96
+ scores[column].append(max(current_max, row[column]))
97
+
98
+ # Step 4: Convert the dictionary to a DataFrame
99
+ return pd.DataFrame(scores)
100
+
101
+
102
+ def create_plot_df(scores_df: pd.DataFrame) -> pd.DataFrame:
103
+ """
104
+ Transforms the scores DataFrame into a new format suitable for plotting.
105
+
106
+ :param scores_df: A DataFrame containing metric scores and result dates.
107
+ :return: A new DataFrame reshaped for plotting purposes.
108
+ """
109
+ # Sample columns
110
+ cols = ["Average ⬆️", "ARC", "HellaSwag", "MMLU", "TruthfulQA"]
111
+
112
+ # Initialize the list to store DataFrames
113
+ dfs = []
114
+
115
+ # Iterate over the cols and create a new DataFrame for each column
116
+ for col in cols:
117
+ d = scores_df[[col, "Result Date"]].copy().reset_index(drop=True)
118
+ d["Metric Name"] = col
119
+ d.rename(columns={col: "Metric Value"}, inplace=True)
120
+ dfs.append(d)
121
+
122
+ # Concatenate all the created DataFrames
123
+ concat_df = pd.concat(dfs, ignore_index=True)
124
+
125
+ # Sort values by 'Result Date'
126
+ concat_df.sort_values(by="Result Date", inplace=True)
127
+ concat_df.reset_index(drop=True, inplace=True)
128
+
129
+ # Drop duplicates based on 'Metric Name' and 'Metric Value' and keep the first (earliest) occurrence
130
+ concat_df.drop_duplicates(subset=["Metric Name", "Metric Value"], keep="first", inplace=True)
131
+
132
+ concat_df.reset_index(drop=True, inplace=True)
133
+ return concat_df
134
+
135
+
136
+ def create_metric_plot_obj(df: pd.DataFrame, metrics: List[str], human_baselines: Dict[str, float]) -> alt.LayerChart:
137
+ """
138
+ Creates a visualization of metrics over time compared to human baselines.
139
+
140
+ :param df: A DataFrame containing 'Metric Name', 'Metric Value', and 'Result Date' columns.
141
+ :param metrics: A list of metric names to be included in the plot.
142
+ :param human_baselines: A dictionary mapping metric names to their corresponding human baseline values.
143
+ :return: An Altair LayerChart object visualizing the metrics over time.
144
+ """
145
+ # Filter the DataFrame based on the metrics parameter
146
+ df = df[df["Metric Name"].isin(metrics)]
147
+
148
+ # Filter the human_baselines dictionary to include only the specified metrics
149
+ filtered_human_baselines = {k: v for k, v in human_baselines.items() if k in metrics}
150
+
151
+ # Create a DataFrame from filtered human baselines
152
+ human_baselines_df = pd.DataFrame(list(filtered_human_baselines.items()), columns=["Metric Name", "Metric Value"])
153
+
154
+ # Create the lines chart for each metric over time.
155
+ base = alt.Chart(df).encode(x="Result Date:T")
156
+ lines = base.mark_line().encode(
157
+ alt.Y("Metric Value:Q", scale=alt.Scale(domain=[0, 100])),
158
+ color="Metric Name:N",
159
+ )
160
+
161
+ # Create the rules (horizontal lines) chart for the human baselines.
162
+ yrules = (
163
+ alt.Chart(human_baselines_df)
164
+ .mark_rule(strokeDash=[12, 6], size=2)
165
+ .encode(y="Metric Value:Q", color="Metric Name:N")
166
+ )
167
+
168
+ # Combine lines with yrules and return the chart.
169
+ return lines + yrules