Spaces:
Runtime error
Runtime error
Merge branch 'main' of https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard
Browse filesFiles changed (15)
- app.py+51-37
- requirements.txt+3-3
- src/assets/hardcoded_evals.py+1-1
- src/assets/text_content.py+7-6
- src/display_models/modelcard_filter.py → src/filters.pyRenamed+40
- src/display_models/get_model_metadata.py → src/get_model_info/apply_metadata_to_df.pyRenamed+4-7
- src/get_model_info/get_metadata_from_hub.pyAdded+19
- src/display_models/model_metadata_flags.py → src/get_model_info/hardocded_metadata/flags.pyRenamed
- src/display_models/model_metadata_type.py → src/get_model_info/hardocded_metadata/types.pyRenamed
- src/display_models/utils.py → src/get_model_info/utils.pyRenamed
- src/load_from_hub.py+3-18
- src/manage_collections.pyAdded+75
- src/plots/plot_results.pyAdded+223
- src/display_models/read_results.py → src/plots/read_results.pyRenamed+2-2
- src/rate_limiting.pyDeleted-13
12345610 unmodified lines1718192021222324251 unmodified line272829303132333453 unmodified lines88899091929394959620 unmodified lines11711811912012112212312412512612712812913014 unmodified lines14514614714814915015115215315415515615715815916016116216316416516616716816917017117296 unmodified lines269270271272273274275276277278279280281231 unmodified lines513514515516517518import jsonimport osimport refrom datetime import datetime, timezoneimport gradio as gr10 unmodified linesLLM_BENCHMARKS_TEXT,TITLE,)from src.display_models.get_model_metadata import DO_NOT_SUBMIT_MODELS, ModelTypefrom src.display_models.modelcard_filter import check_model_cardfrom src.display_models.utils import (AutoEvalColumn,EvalQueueColumn,fields,1 unmodified linestyled_message,styled_warning,)from src.load_from_hub import get_all_requested_models, get_evaluation_queue_df, get_leaderboard_df, is_model_on_hubfrom src.rate_limiting import user_submission_permissionpd.set_option("display.precision", 1)53 unmodified linesrequested_models, users_to_submission_dates = get_all_requested_models(EVAL_REQUESTS_PATH)original_df = get_leaderboard_df(EVAL_RESULTS_PATH, COLS, BENCHMARK_COLS)leaderboard_df = original_df.copy()models = original_df["model_name_for_query"].tolist() # needed for model backlinks in their to the leaderboardto_be_dumped = f"models = {repr(models)}\n"(20 unmodified linesreturn styled_error("Please select a model type.")# Is the user rate limited?num_models_submitted_in_period = user_submission_permission(model, users_to_submission_dates, RATE_LIMIT_PERIOD)if num_models_submitted_in_period > RATE_LIMIT_QUOTA:error_msg = f"Organisation or user `{model.split('/')[0]}`"error_msg += f"already has {num_models_submitted_in_period} model requests submitted to the leaderboard "error_msg += f"in the last {RATE_LIMIT_PERIOD} days.\n"error_msg += ("Please wait a couple of days before resubmitting, so that everybody can enjoy using the leaderboard 🤗")return styled_error(error_msg)# Did the model authors forbid its submission to the leaderboard?14 unmodified linesif not model_on_hub:return styled_error(f'Model "{model}" {error}')model_info = api.model_info(repo_id=model, revision=revision)size_pattern = size_pattern = re.compile(r"(\d\.)?\d+(b|m)")try:model_size = round(model_info.safetensors["total"] / 1e9, 3)except AttributeError:try:size_match = re.search(size_pattern, model.lower())model_size = size_match.group(0)model_size = round(float(model_size[:-1]) if model_size[-1] == "b" else float(model_size[:-1]) / 1e3, 3)except AttributeError:return 65size_factor = 8 if (precision == "GPTQ" or "GPTQ" in model) else 1model_size = size_factor * model_sizetry:license = model_info.cardData["license"]except Exception:license = "?"# Were the model card and license filled?modelcard_OK, error_msg = check_model_card(model)if not modelcard_OK:return styled_error(error_msg)96 unmodified linesNUMERIC_INTERVALS = {"?": pd.Interval(-1, 0, closed="right"),"0~1.5": pd.Interval(0, 1.5, closed="right"),"1.5~3": pd.Interval(1.5, 3, closed="right"),"3~7": pd.Interval(3, 7, closed="right"),"7~13": pd.Interval(7, 13, closed="right"),"13~35": pd.Interval(13, 35, closed="right"),"35~60": pd.Interval(35, 60, closed="right"),"60+": pd.Interval(60, 10000, closed="right"),}231 unmodified linesleaderboard_table,queue=True,)with gr.TabItem("📝 About", elem_id="llm-benchmark-tab-table", id=2):gr.Markdown(LLM_BENCHMARKS_TEXT, elem_classes="markdown-text")1234510 unmodified lines16171819202122232425262728293031321 unmodified line34353637383940414253 unmodified lines9697989910010110210310410510620 unmodified lines12712812913013113213313414 unmodified lines14915015115215315415515615715815916016116216316416516616796 unmodified lines264265266267268269270271272273274275276231 unmodified lines508509510511512513514515516517518519520521522523524525526527528529530531532import jsonimport osfrom datetime import datetime, timezoneimport gradio as gr10 unmodified linesLLM_BENCHMARKS_TEXT,TITLE,)from src.plots.plot_results import (create_metric_plot_obj,create_scores_df,create_plot_df,join_model_info_with_results,HUMAN_BASELINES,)from src.get_model_info.apply_metadata_to_df import DO_NOT_SUBMIT_MODELS, ModelTypefrom src.get_model_info.get_metadata_from_hub import get_model_sizefrom src.filters import check_model_cardfrom src.get_model_info.utils import (AutoEvalColumn,EvalQueueColumn,fields,1 unmodified linestyled_message,styled_warning,)from src.manage_collections import update_collectionsfrom src.load_from_hub import get_all_requested_models, get_evaluation_queue_df, get_leaderboard_dffrom src.filters import is_model_on_hub, user_submission_permissionpd.set_option("display.precision", 1)53 unmodified linesrequested_models, users_to_submission_dates = get_all_requested_models(EVAL_REQUESTS_PATH)original_df = get_leaderboard_df(EVAL_RESULTS_PATH, COLS, BENCHMARK_COLS)update_collections(original_df.copy())leaderboard_df = original_df.copy()models = original_df["model_name_for_query"].tolist() # needed for model backlinks in their to the leaderboardplot_df = create_plot_df(create_scores_df(join_model_info_with_results(original_df)))to_be_dumped = f"models = {repr(models)}\n"(20 unmodified linesreturn styled_error("Please select a model type.")# Is the user rate limited?user_can_submit, error_msg = user_submission_permission(model, users_to_submission_dates, RATE_LIMIT_PERIOD, RATE_LIMIT_QUOTA)if not user_can_submit:return styled_error(error_msg)# Did the model authors forbid its submission to the leaderboard?14 unmodified linesif not model_on_hub:return styled_error(f'Model "{model}" {error}')try:model_info = api.model_info(repo_id=model, revision=revision)except Exception:return styled_error("Could not get your model information. Please fill it up properly.")model_size = get_model_size(model_info=model_info , precision= precision)# Were the model card and license filled?try:license = model_info.cardData["license"]except Exception:return styled_error("Please select a license for your model")modelcard_OK, error_msg = check_model_card(model)if not modelcard_OK:return styled_error(error_msg)96 unmodified linesNUMERIC_INTERVALS = {"?": pd.Interval(-1, 0, closed="right"),"~1.5": pd.Interval(0, 2, closed="right"),"~3": pd.Interval(2, 4, closed="right"),"~7": pd.Interval(4, 9, closed="right"),"~13": pd.Interval(9, 20, closed="right"),"~35": pd.Interval(20, 45, closed="right"),"~60": pd.Interval(45, 70, closed="right"),"70+": pd.Interval(70, 10000, closed="right"),}231 unmodified linesleaderboard_table,queue=True,)with gr.TabItem("📈 Metrics evolution through time", elem_id="llm-benchmark-tab-table", id=4):with gr.Row():with gr.Column():chart = create_metric_plot_obj(plot_df,["Average ⬆️"],HUMAN_BASELINES,title="Average of Top Scores and Human Baseline Over Time",)gr.Plot(value=chart, interactive=False, width=500, height=500)with gr.Column():chart = create_metric_plot_obj(plot_df,["ARC", "HellaSwag", "MMLU", "TruthfulQA"],HUMAN_BASELINES,title="Top Scores and Human Baseline Over Time",)gr.Plot(value=chart, interactive=False, width=500, height=500)with gr.TabItem("📝 About", elem_id="llm-benchmark-tab-table", id=2):gr.Markdown(LLM_BENCHMARKS_TEXT, elem_classes="markdown-text")
18 unmodified lines1920212223242526272829303128 unmodified lines6061626364656618 unmodified linesfilelock==3.11.0fonttools==4.39.3frozenlist==1.3.3fsspec==2023.4.0gradio==3.43.2gradio-client==0.5.0h11==0.14.0httpcore==0.17.0httpx==0.24.0huggingface-hub==0.16.4idna==3.4Jinja2==3.1.2jsonschema==4.17.328 unmodified linesstarlette==0.26.1toolz==0.12.0tqdm==4.65.0transformers==4.34.0typing_extensions==4.5.0tzdata==2023.3tzlocal==4.318 unmodified lines1920212223242526272829303128 unmodified lines6061626364656618 unmodified linesfilelock==3.11.0fonttools==4.39.3frozenlist==1.3.3fsspec==2023.5.0gradio==3.43.2gradio-client==0.5.0h11==0.14.0httpcore==0.17.0httpx==0.24.0huggingface-hub==0.18.0idna==3.4Jinja2==3.1.2jsonschema==4.17.328 unmodified linesstarlette==0.26.1toolz==0.12.0tqdm==4.65.0transformerstyping_extensions==4.5.0tzdata==2023.3tzlocal==4.3
1234from src.display_models.utils import AutoEvalColumn, model_hyperlinkgpt4_values = {AutoEvalColumn.model.name: model_hyperlink("https://arxiv.org/abs/2303.08774", "gpt4"),1234from src.get_model_info.utils import AutoEvalColumn, model_hyperlinkgpt4_values = {AutoEvalColumn.model.name: model_hyperlink("https://arxiv.org/abs/2303.08774", "gpt4"),
12349 unmodified lines14151617181920212223242526from src.display_models.model_metadata_type import ModelTypeTITLE = """<h1 align="center" id="space-title">🤗 Open LLM Leaderboard</h1>"""9 unmodified linesWith the plethora of large language models (LLMs) and chatbots being released week upon week, often with grandiose claims of their performance, it can be hard to filter out the genuine progress that is being made by the open-source community and which model is the current state of the art.## Icons{ModelType.PT.to_str(" : ")} model{ModelType.FT.to_str(" : ")} model{ModelType.IFT.to_str(" : ")} model{ModelType.RL.to_str(" : ")} modelIf there is no icon, we have not uploaded the information on the model yet, feel free to open an issue with the model information!🏴☠️ indicates that this model has been flagged by the community, and should probably be ignored! Clicking the icon will redirect you to the discussion about the model.(For ex, the model was trained on the evaluation data, and is therefore cheating on the leaderboard.)## How it works12349 unmodified lines1415161718192021222324252627from src.get_model_info.hardocded_metadata.types import ModelTypeTITLE = """<h1 align="center" id="space-title">🤗 Open LLM Leaderboard</h1>"""9 unmodified linesWith the plethora of large language models (LLMs) and chatbots being released week upon week, often with grandiose claims of their performance, it can be hard to filter out the genuine progress that is being made by the open-source community and which model is the current state of the art.## Icons{ModelType.PT.to_str(" : ")} model: new, base models, trained on a given corpora{ModelType.FT.to_str(" : ")} model: pretrained models finetuned on more dataSpecific fine-tune subcategories (more adapted to chat):{ModelType.IFT.to_str(" : ")} model: instruction fine-tunes, which are model fine-tuned specifically on datasets of task instruction{ModelType.RL.to_str(" : ")} model: reinforcement fine-tunes, which usually change the model loss a bit with an added policy.If there is no icon, we have not uploaded the information on the model yet, feel free to open an issue with the model information!"Flagged" indicates that this model has been flagged by the community, and should probably be ignored! Clicking the link will redirect you to the discussion about the model.(For ex, the model was trained on the evaluation data, and is therefore cheating on the leaderboard.)## How it works
1234518 unmodified lines242526import huggingface_hubfrom huggingface_hub import ModelCard# ht to @Wauplin, thank you for the snippet!18 unmodified linesreturn False, "Please add a description to your model card, it is too short."return True, ""1234567818 unmodified lines27282930313233343536373839404142434445464748495051525354555657585960616263646566import huggingface_hubfrom huggingface_hub import ModelCardfrom transformers import AutoConfigfrom datetime import datetime, timedelta, timezone# ht to @Wauplin, thank you for the snippet!18 unmodified linesreturn False, "Please add a description to your model card, it is too short."return True, ""def is_model_on_hub(model_name: str, revision: str) -> bool:try:AutoConfig.from_pretrained(model_name, revision=revision, trust_remote_code=False)return True, Noneexcept ValueError:return (False,"needs to be launched with `trust_remote_code=True`. For safety reason, we do not allow these models to be automatically submitted to the leaderboard.",)except Exception:return False, "was not found on hub!"def user_submission_permission(submission_name, users_to_submission_dates, rate_limit_period, rate_limit_quota):org_or_user, _ = submission_name.split("/")if org_or_user not in users_to_submission_dates:return True, ""submission_dates = sorted(users_to_submission_dates[org_or_user])time_limit = (datetime.now(timezone.utc) - timedelta(days=rate_limit_period)).strftime("%Y-%m-%dT%H:%M:%SZ")submissions_after_timelimit = [d for d in submission_dates if d > time_limit]num_models_submitted_in_period = len(submissions_after_timelimit)if num_models_submitted_in_period > rate_limit_quota:error_msg = f"Organisation or user `{org_or_user}`"error_msg += f"already has {num_models_submitted_in_period} model requests submitted to the leaderboard "error_msg += f"in the last {rate_limit_period} days.\n"error_msg += ("Please wait a couple of days before resubmitting, so that everybody can enjoy using the leaderboard 🤗")return False, error_msgreturn True, ""
5 unmodified lines6789101112131430 unmodified lines454647484950515253545 unmodified linesfrom huggingface_hub import HfApifrom tqdm import tqdmfrom src.display_models.model_metadata_flags import DO_NOT_SUBMIT_MODELS, FLAGGED_MODELSfrom src.display_models.model_metadata_type import MODEL_TYPE_METADATA, ModelType, model_type_from_strfrom src.display_models.utils import AutoEvalColumn, model_hyperlinkapi = HfApi(token=os.environ.get("H4_TOKEN", None))30 unmodified linesmodel_data[AutoEvalColumn.license.name] = request.get("license", "?")model_data[AutoEvalColumn.likes.name] = request.get("likes", 0)model_data[AutoEvalColumn.params.name] = request.get("params", 0)except Exception as e:print(f"Could not find request file for {model_data['model_name_for_query']}: {e}")print(f"{request_file=}")print(f"{request_files=}")if model_data["model_name_for_query"] in MODEL_TYPE_METADATA:model_data[AutoEvalColumn.model_type.name] = MODEL_TYPE_METADATA[model_data["model_name_for_query"]5 unmodified lines6789101112131430 unmodified lines454647484950515 unmodified linesfrom huggingface_hub import HfApifrom tqdm import tqdmfrom src.get_model_info.hardocded_metadata.flags import DO_NOT_SUBMIT_MODELS, FLAGGED_MODELSfrom src.get_model_info.hardocded_metadata.types import MODEL_TYPE_METADATA, ModelType, model_type_from_strfrom src.get_model_info.utils import AutoEvalColumn, model_hyperlinkapi = HfApi(token=os.environ.get("H4_TOKEN", None))30 unmodified linesmodel_data[AutoEvalColumn.license.name] = request.get("license", "?")model_data[AutoEvalColumn.likes.name] = request.get("likes", 0)model_data[AutoEvalColumn.params.name] = request.get("params", 0)except Exception:if model_data["model_name_for_query"] in MODEL_TYPE_METADATA:model_data[AutoEvalColumn.model_type.name] = MODEL_TYPE_METADATA[model_data["model_name_for_query"]
12345678910111213141516171819import refrom huggingface_hub.hf_api import ModelInfo
def get_model_size(model_info: ModelInfo, precision: str): size_pattern = size_pattern = re.compile(r"(\d\.)?\d+(b|m)") try: model_size = round(model_info.safetensors["total"] / 1e9, 3) except AttributeError: try: size_match = re.search(size_pattern, model_info.modelId.lower()) model_size = size_match.group(0) model_size = round(float(model_size[:-1]) if model_size[-1] == "b" else float(model_size[:-1]) / 1e3, 3) except AttributeError: return 0 # Unknown model sizes are indicated as 0, see NUMERIC_INTERVALS in app.py
size_factor = 8 if (precision == "GPTQ" or "gptq" in model_info.modelId.lower()) else 1 model_size = size_factor * model_size return model_size2 unmodified lines3456789101112131475 unmodified lines909192939495969798991001011021031041051062 unmodified linesfrom collections import defaultdictimport pandas as pdfrom transformers import AutoConfigfrom src.assets.hardcoded_evals import baseline, gpt4_values, gpt35_valuesfrom src.display_models.get_model_metadata import apply_metadatafrom src.display_models.read_results import get_eval_results_dicts, make_clickable_modelfrom src.display_models.utils import AutoEvalColumn, EvalQueueColumn, has_no_nan_valuesIS_PUBLIC = bool(os.environ.get("IS_PUBLIC", True))75 unmodified linesdf_finished = pd.DataFrame.from_records(finished_list, columns=cols)return df_finished[cols], df_running[cols], df_pending[cols]def is_model_on_hub(model_name: str, revision: str) -> bool:try:AutoConfig.from_pretrained(model_name, revision=revision, trust_remote_code=False)return True, Noneexcept ValueError:return (False,"needs to be launched with `trust_remote_code=True`. For safety reason, we do not allow these models to be automatically submitted to the leaderboard.",)except Exception:return False, "was not found on hub!"2 unmodified lines34567891011121375 unmodified lines8990912 unmodified linesfrom collections import defaultdictimport pandas as pdfrom src.assets.hardcoded_evals import baseline, gpt4_values, gpt35_valuesfrom src.get_model_info.apply_metadata_to_df import apply_metadatafrom src.plots.read_results import get_eval_results_dicts, make_clickable_modelfrom src.get_model_info.utils import AutoEvalColumn, EvalQueueColumn, has_no_nan_valuesIS_PUBLIC = bool(os.environ.get("IS_PUBLIC", True))75 unmodified linesdf_finished = pd.DataFrame.from_records(finished_list, columns=cols)return df_finished[cols], df_running[cols], df_pending[cols]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475import osimport pandas as pdfrom pandas import DataFramefrom huggingface_hub import get_collection, add_collection_item, update_collection_item, delete_collection_itemfrom huggingface_hub.utils._errors import HfHubHTTPError
from src.get_model_info.hardocded_metadata.types import ModelTypefrom src.get_model_info.utils import AutoEvalColumn
H4_TOKEN = os.environ.get("H4_TOKEN", None)
path_to_collection = "open-llm-leaderboard/llm-leaderboard-best-models-652d6c7965a4619fb5c27a03"intervals = { "1B": pd.Interval(0, 1.5, closed="right"), "3B": pd.Interval(2.5, 3.5, closed="neither"), "7B": pd.Interval(6, 8, closed="neither"), "13B": pd.Interval(10, 14, closed="neither"), "30B":pd.Interval(25, 35, closed="neither"), "65B": pd.Interval(60, 70, closed="neither"),}
def update_collections(df: DataFrame): """This function updates the Open LLM Leaderboard model collection with the latest best models for each size category and type. """ collection = get_collection(collection_slug=path_to_collection, token=H4_TOKEN) params_column = pd.to_numeric(df[AutoEvalColumn.params.name], errors="coerce")
cur_best_models = []
ix = 0 for type in ModelType: if type.value.name == "": continue for size in intervals: # We filter the df to gather the relevant models type_emoji = [t[0] for t in type.value.symbol] filtered_df = df[df[AutoEvalColumn.model_type_symbol.name].isin(type_emoji)]
numeric_interval = pd.IntervalIndex([intervals[size]]) mask = params_column.apply(lambda x: any(numeric_interval.contains(x))) filtered_df = filtered_df.loc[mask]
best_models = list(filtered_df.sort_values(AutoEvalColumn.average.name, ascending=False)[AutoEvalColumn.dummy.name]) print(type.value.symbol, size, best_models[:10])
# We add them one by one to the leaderboard for model in best_models: ix += 1 cur_len_collection = len(collection.items) try: collection = add_collection_item( path_to_collection, item_id=model, item_type="model", exists_ok=True, note=f"Best {type.to_str(' ')} model of around {size} on the leaderboard today!", token=H4_TOKEN ) if len(collection.items) > cur_len_collection: # we added an item - we make sure its position is correct item_object_id = collection.items[-1].item_object_id update_collection_item(collection_slug=path_to_collection, item_object_id=item_object_id, position=ix) cur_len_collection = len(collection.items) cur_best_models.append(model) break except HfHubHTTPError: continue
collection = get_collection(path_to_collection, token=H4_TOKEN) for item in collection.items: if item.item_id not in cur_best_models: try: delete_collection_item(collection_slug=path_to_collection, item_object_id=item.item_object_id, token=H4_TOKEN) except HfHubHTTPError: continue
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223import pandas as pdimport plotly.express as pxfrom plotly.graph_objs import Figureimport picklefrom datetime import datetime, timezonefrom typing import List, Dict, Tuple, Anyfrom src.get_model_info.hardocded_metadata.flags import FLAGGED_MODELS
# Average ⬆️ human baseline is 0.897 (source: averaging human baselines below)# ARC human baseline is 0.80 (source: https://lab42.global/arc/)# HellaSwag human baseline is 0.95 (source: https://deepgram.com/learn/hellaswag-llm-benchmark-guide)# MMLU human baseline is 0.898 (source: https://openreview.net/forum?id=d7KBjmI3GmQ)# TruthfulQA human baseline is 0.94(source: https://arxiv.org/pdf/2109.07958.pdf)# Define the human baselinesHUMAN_BASELINES = { "Average ⬆️": 0.897 * 100, "ARC": 0.80 * 100, "HellaSwag": 0.95 * 100, "MMLU": 0.898 * 100, "TruthfulQA": 0.94 * 100,}
def to_datetime(model_info: Tuple[str, Any]) -> datetime: """ Converts the lastModified attribute of the object to datetime.
:param model_info: A tuple containing the name and object. The object must have a lastModified attribute with a string representing the date and time. :return: A datetime object converted from the lastModified attribute of the input object. """ name, obj = model_info return datetime.strptime(obj.lastModified, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=timezone.utc)
def join_model_info_with_results(results_df: pd.DataFrame) -> pd.DataFrame: """ Integrates model information with the results DataFrame by matching 'Model sha'. :param results_df: A DataFrame containing results information including 'Model sha' column. :return: A DataFrame with updated 'Results Date' columns, which are synchronized with model information. """ # copy dataframe to avoid modifying the original df = results_df.copy(deep=True)
# Filter out FLAGGED_MODELS to ensure graph is not skewed by mistakes df = df[~df["model_name_for_query"].isin(FLAGGED_MODELS.keys())].reset_index(drop=True)
# load cache from disk try: with open("model_info_cache.pkl", "rb") as f: model_info_cache = pickle.load(f) except (EOFError, FileNotFoundError): model_info_cache = {}
# Sort date strings using datetime objects as keys sorted_dates = sorted(list(model_info_cache.items()), key=to_datetime, reverse=True) df["Results Date"] = datetime.now().replace(tzinfo=timezone.utc)
# Define the date format string date_format = "%Y-%m-%dT%H:%M:%S.%fZ"
# Iterate over sorted_dates and update the dataframe for name, obj in sorted_dates: # Convert the lastModified string to a datetime object last_modified_datetime = datetime.strptime(obj.lastModified, date_format).replace(tzinfo=timezone.utc)
# Update the "Results Date" column where "Model sha" equals obj.sha df.loc[df["Model sha"] == obj.sha, "Results Date"] = last_modified_datetime return df
def create_scores_df(results_df: pd.DataFrame) -> pd.DataFrame: """ Generates a DataFrame containing the maximum scores until each result date.
:param results_df: A DataFrame containing result information including metric scores and result dates. :return: A new DataFrame containing the maximum scores until each result date for every metric. """ # Step 1: Ensure 'Results Date' is in datetime format and sort the DataFrame by it results_df["Results Date"] = pd.to_datetime(results_df["Results Date"]) results_df.sort_values(by="Results Date", inplace=True)
# Step 2: Initialize the scores dictionary scores = { "Average ⬆️": [], "ARC": [], "HellaSwag": [], "MMLU": [], "TruthfulQA": [], "Result Date": [], "Model Name": [], }
# Step 3: Iterate over the rows of the DataFrame and update the scores dictionary for i, row in results_df.iterrows(): date = row["Results Date"] for column in scores.keys(): if column == "Result Date": if not scores[column] or scores[column][-1] <= date: scores[column].append(date) continue if column == "Model Name": scores[column].append(row["model_name_for_query"]) continue current_max = scores[column][-1] if scores[column] else float("-inf") scores[column].append(max(current_max, row[column]))
# Step 4: Convert the dictionary to a DataFrame return pd.DataFrame(scores)
def create_plot_df(scores_df: pd.DataFrame) -> pd.DataFrame: """ Transforms the scores DataFrame into a new format suitable for plotting.
:param scores_df: A DataFrame containing metric scores and result dates. :return: A new DataFrame reshaped for plotting purposes. """ # Sample columns cols = ["Average ⬆️", "ARC", "HellaSwag", "MMLU", "TruthfulQA"]
# Initialize the list to store DataFrames dfs = []
# Iterate over the cols and create a new DataFrame for each column for col in cols: d = scores_df[[col, "Model Name", "Result Date"]].copy().reset_index(drop=True) d["Metric Name"] = col d.rename(columns={col: "Metric Value"}, inplace=True) dfs.append(d)
# Concatenate all the created DataFrames concat_df = pd.concat(dfs, ignore_index=True)
# Sort values by 'Result Date' concat_df.sort_values(by="Result Date", inplace=True) concat_df.reset_index(drop=True, inplace=True)
# Drop duplicates based on 'Metric Name' and 'Metric Value' and keep the first (earliest) occurrence concat_df.drop_duplicates(subset=["Metric Name", "Metric Value"], keep="first", inplace=True)
concat_df.reset_index(drop=True, inplace=True) return concat_df
def create_metric_plot_obj( df: pd.DataFrame, metrics: List[str], human_baselines: Dict[str, float], title: str) -> Figure: """ Create a Plotly figure object with lines representing different metrics and horizontal dotted lines representing human baselines.
:param df: The DataFrame containing the metric values, names, and dates. :param metrics: A list of strings representing the names of the metrics to be included in the plot. :param human_baselines: A dictionary where keys are metric names and values are human baseline values for the metrics. :param title: A string representing the title of the plot. :return: A Plotly figure object with lines representing metrics and horizontal dotted lines representing human baselines. """
# Filter the DataFrame based on the specified metrics df = df[df["Metric Name"].isin(metrics)]
# Filter the human baselines based on the specified metrics filtered_human_baselines = {k: v for k, v in human_baselines.items() if k in metrics}
# Create a line figure using plotly express with specified markers and custom data fig = px.line( df, x="Result Date", y="Metric Value", color="Metric Name", markers=True, custom_data=["Metric Name", "Metric Value", "Model Name"], title=title, )
# Update hovertemplate for better hover interaction experience fig.update_traces( hovertemplate="<br>".join( [ "Model Name: %{customdata[2]}", "Metric Name: %{customdata[0]}", "Date: %{x}", "Metric Value: %{y}", ] ) )
# Update the range of the y-axis fig.update_layout(yaxis_range=[0, 100])
# Create a dictionary to hold the color mapping for each metric metric_color_mapping = {}
# Map each metric name to its color in the figure for trace in fig.data: metric_color_mapping[trace.name] = trace.line.color
# Iterate over filtered human baselines and add horizontal lines to the figure for metric, value in filtered_human_baselines.items(): color = metric_color_mapping.get(metric, "blue") # Retrieve color from mapping; default to blue if not found location = "top left" if metric == "HellaSwag" else "bottom left" # Set annotation position # Add horizontal line with matched color and positioned annotation fig.add_hline( y=value, line_dash="dot", annotation_text=f"{metric} human baseline", annotation_position=location, annotation_font_size=10, annotation_font_color=color, line_color=color, )
return fig
# Example Usage:# human_baselines dictionary is defined.# chart = create_metric_plot_obj(scores_df, ["ARC", "HellaSwag", "MMLU", "TruthfulQA"], human_baselines, "Graph Title")5 unmodified lines678910111218 unmodified lines313233343536375 unmodified linesimport dateutilimport numpy as npfrom src.display_models.utils import AutoEvalColumn, make_clickable_modelMETRICS = ["acc_norm", "acc_norm", "acc", "mc2"]BENCHMARKS = ["arc:challenge", "hellaswag", "hendrycksTest", "truthfulqa:mc"]18 unmodified linesdate: str = ""def to_dict(self):from src.load_from_hub import is_model_on_hubif self.org is not None:base_model = f"{self.org}/{self.model}"5 unmodified lines678910111218 unmodified lines313233343536375 unmodified linesimport dateutilimport numpy as npfrom src.get_model_info.utils import AutoEvalColumn, make_clickable_modelMETRICS = ["acc_norm", "acc_norm", "acc", "mc2"]BENCHMARKS = ["arc:challenge", "hellaswag", "hendrycksTest", "truthfulqa:mc"]18 unmodified linesdate: str = ""def to_dict(self):from src.filters import is_model_on_hubif self.org is not None:base_model = f"{self.org}/{self.model}"
12345678910111213from datetime import datetime, timedelta, timezone
def user_submission_permission(submission_name, users_to_submission_dates, rate_limit_period): org_or_user, _ = submission_name.split("/") if org_or_user not in users_to_submission_dates: return 0 submission_dates = sorted(users_to_submission_dates[org_or_user])
time_limit = (datetime.now(timezone.utc) - timedelta(days=rate_limit_period)).strftime("%Y-%m-%dT%H:%M:%SZ") submissions_after_timelimit = [d for d in submission_dates if d > time_limit]
return len(submissions_after_timelimit)app.py+51-37
requirements.txt+3-3
src/assets/hardcoded_evals.py+1-1
src/assets/text_content.py+7-6
src/display_models/modelcard_filter.py → src/filters.pyRenamed+40
src/display_models/get_model_metadata.py → src/get_model_info/apply_metadata_to_df.pyRenamed+4-7
src/get_model_info/get_metadata_from_hub.pyAdded+19
src/display_models/model_metadata_flags.py → src/get_model_info/hardocded_metadata/flags.pyRenamed
src/display_models/model_metadata_type.py → src/get_model_info/hardocded_metadata/types.pyRenamed
src/display_models/utils.py → src/get_model_info/utils.pyRenamed
src/load_from_hub.py+3-18
src/manage_collections.pyAdded+75
src/plots/plot_results.pyAdded+223
src/display_models/read_results.py → src/plots/read_results.pyRenamed+2-2
src/rate_limiting.pyDeleted-13