CoolFace
Apppublic

open-llm-leaderboard/open_llm_leaderboard

sourceHugging Faceapache-2.0updated 4mo agoView on Hugging Face
14klikes
app.py366 linesDownload Raw Back to root
1import os2import logging3import time4import gradio as gr5import datasets6from huggingface_hub import snapshot_download, WebhooksServer, WebhookPayload, RepoCard7from gradio_leaderboard import Leaderboard, ColumnFilter, SelectColumns8 9from src.display.about import (10    CITATION_BUTTON_LABEL,11    CITATION_BUTTON_TEXT,12    EVALUATION_QUEUE_TEXT,13    FAQ_TEXT,14    INTRODUCTION_TEXT,15    LLM_BENCHMARKS_TEXT,16    TITLE,17)18from src.display.css_html_js import custom_css19from src.display.utils import (20    BENCHMARK_COLS,21    COLS,22    EVAL_COLS,23    EVAL_TYPES,24    AutoEvalColumn,25    ModelType,26    Precision,27    WeightType,28    fields,29)30from src.envs import (31    API,32    EVAL_REQUESTS_PATH,33    AGGREGATED_REPO,34    HF_TOKEN,35    QUEUE_REPO,36    REPO_ID,37    HF_HOME,38)39from src.populate import get_evaluation_queue_df, get_leaderboard_df40from src.submission.submit import add_new_eval41from src.tools.plots import create_metric_plot_obj, create_plot_df, create_scores_df42 43# Configure logging44logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")45 46 47# Convert the environment variable "LEADERBOARD_FULL_INIT" to a boolean value, defaulting to True if the variable is not set.48# This controls whether a full initialization should be performed.49DO_FULL_INIT = os.getenv("LEADERBOARD_FULL_INIT", "True") == "True"50 51def restart_space():52    API.restart_space(repo_id=REPO_ID, token=HF_TOKEN)53 54 55def time_diff_wrapper(func):56    def wrapper(*args, **kwargs):57        start_time = time.time()58        result = func(*args, **kwargs)59        end_time = time.time()60        diff = end_time - start_time61        logging.info(f"Time taken for {func.__name__}: {diff} seconds")62        return result63 64    return wrapper65 66 67@time_diff_wrapper68def download_dataset(repo_id, local_dir, repo_type="dataset", max_attempts=3, backoff_factor=1.5):69    """Download dataset with exponential backoff retries."""70    attempt = 071    while attempt < max_attempts:72        try:73            logging.info(f"Downloading {repo_id} to {local_dir}")74            snapshot_download(75                repo_id=repo_id,76                local_dir=local_dir,77                repo_type=repo_type,78                tqdm_class=None,79                etag_timeout=30,80                max_workers=8,81            )82            logging.info("Download successful")83            return84        except Exception as e:85            wait_time = backoff_factor**attempt86            logging.error(f"Error downloading {repo_id}: {e}, retrying in {wait_time}s")87            time.sleep(wait_time)88            attempt += 189    raise Exception(f"Failed to download {repo_id} after {max_attempts} attempts")90 91def get_latest_data_leaderboard():92    leaderboard_dataset = datasets.load_dataset(93        AGGREGATED_REPO, 94        "default", 95        split="train", 96        cache_dir=HF_HOME, 97        download_mode=datasets.DownloadMode.REUSE_DATASET_IF_EXISTS, # Uses the cached dataset 98        verification_mode="no_checks"99    )100 101    leaderboard_df = get_leaderboard_df(102        leaderboard_dataset=leaderboard_dataset, 103        cols=COLS,104        benchmark_cols=BENCHMARK_COLS,105    )106 107    return leaderboard_df108 109def get_latest_data_queue():110    eval_queue_dfs = get_evaluation_queue_df(EVAL_REQUESTS_PATH, EVAL_COLS)111    return eval_queue_dfs112 113def init_space():114    """Initializes the application space, loading only necessary data."""115    if DO_FULL_INIT:116        # These downloads only occur on full initialization117        try:118            download_dataset(QUEUE_REPO, EVAL_REQUESTS_PATH)119        except Exception:120            restart_space()121 122    # Always redownload the leaderboard DataFrame123    leaderboard_df = get_latest_data_leaderboard()124 125    # Evaluation queue DataFrame retrieval is independent of initialization detail level126    eval_queue_dfs = get_latest_data_queue()127 128    return leaderboard_df, eval_queue_dfs129 130 131# Calls the init_space function with the `full_init` parameter determined by the `do_full_init` variable.132# This initializes various DataFrames used throughout the application, with the level of initialization detail controlled by the `do_full_init` flag.133leaderboard_df, eval_queue_dfs = init_space()134finished_eval_queue_df, running_eval_queue_df, pending_eval_queue_df = eval_queue_dfs135 136 137# Data processing for plots now only on demand in the respective Gradio tab138def load_and_create_plots():139    plot_df = create_plot_df(create_scores_df(leaderboard_df))140    return plot_df141 142def init_leaderboard(dataframe):143    return Leaderboard(144        value = dataframe,145        datatype=[c.type for c in fields(AutoEvalColumn)],146        select_columns=SelectColumns(147            default_selection=[c.name for c in fields(AutoEvalColumn) if c.displayed_by_default],148            cant_deselect=[c.name for c in fields(AutoEvalColumn) if c.never_hidden or c.dummy],149            label="Select Columns to Display:",150        ),151        search_columns=[AutoEvalColumn.model.name, AutoEvalColumn.fullname.name, AutoEvalColumn.license.name],152        hide_columns=[c.name for c in fields(AutoEvalColumn) if c.hidden],153        filter_columns=[154            ColumnFilter(AutoEvalColumn.model_type.name, type="checkboxgroup", label="Model types"),155            ColumnFilter(AutoEvalColumn.precision.name, type="checkboxgroup", label="Precision"),156            ColumnFilter(157                AutoEvalColumn.params.name,158                type="slider",159                min=0.01,160                max=150,161                label="Select the number of parameters (B)",162            ),163            ColumnFilter(164                AutoEvalColumn.still_on_hub.name, type="boolean", label="Private or deleted", default=True165            ),166            ColumnFilter(167                AutoEvalColumn.merged.name, type="boolean", label="Contains a merge/moerge", default=True168            ),169            ColumnFilter(AutoEvalColumn.moe.name, type="boolean", label="MoE", default=False),170            ColumnFilter(AutoEvalColumn.not_flagged.name, type="boolean", label="Flagged", default=True),171        ],172        bool_checkboxgroup_label="Hide models",173    )174 175 176demo = gr.Blocks(css=custom_css)177with demo:178    gr.HTML(TITLE)179    gr.Markdown(INTRODUCTION_TEXT, elem_classes="markdown-text")180 181    with gr.Tabs(elem_classes="tab-buttons") as tabs:182        with gr.TabItem("๐Ÿ… LLM Benchmark", elem_id="llm-benchmark-tab-table", id=0):183            leaderboard = init_leaderboard(leaderboard_df)184 185        with gr.TabItem("๐Ÿ“ˆ Metrics through time", elem_id="llm-benchmark-tab-table", id=2):186            with gr.Row():187                with gr.Column():188                    plot_df = load_and_create_plots()189                    chart = create_metric_plot_obj(190                        plot_df,191                        [AutoEvalColumn.average.name],192                        title="Average of Top Scores and Human Baseline Over Time (from last update)",193                    )194                    gr.Plot(value=chart, min_width=500)195                with gr.Column():196                    plot_df = load_and_create_plots()197                    chart = create_metric_plot_obj(198                        plot_df,199                        BENCHMARK_COLS,200                        title="Top Scores and Human Baseline Over Time (from last update)",201                    )202                    gr.Plot(value=chart, min_width=500)203 204        with gr.TabItem("๐Ÿ“ About", elem_id="llm-benchmark-tab-table", id=3):205            gr.Markdown(LLM_BENCHMARKS_TEXT, elem_classes="markdown-text")206 207        with gr.TabItem("โ—FAQ", elem_id="llm-benchmark-tab-table", id=4):208            gr.Markdown(FAQ_TEXT, elem_classes="markdown-text")209 210        with gr.TabItem("๐Ÿš€ Submit ", elem_id="llm-benchmark-tab-table", id=5):211            with gr.Column():212                with gr.Row():213                    gr.Markdown(EVALUATION_QUEUE_TEXT, elem_classes="markdown-text")214 215            with gr.Row():216                gr.Markdown("# โœ‰๏ธโœจ Submit your model here!", elem_classes="markdown-text")217 218            with gr.Row():219                with gr.Column():220                    model_name_textbox = gr.Textbox(label="Model name")221                    revision_name_textbox = gr.Textbox(label="Revision commit", placeholder="main")222                    model_type = gr.Dropdown(223                        choices=[t.to_str(" : ") for t in ModelType if t != ModelType.Unknown],224                        label="Model type",225                        multiselect=False,226                        value=ModelType.FT.to_str(" : "),227                        interactive=True,228                    )229 230                with gr.Column():231                    precision = gr.Dropdown(232                        choices=[i.value.name for i in Precision if i != Precision.Unknown],233                        label="Precision",234                        multiselect=False,235                        value="float16",236                        interactive=True,237                    )238                    weight_type = gr.Dropdown(239                        choices=[i.value.name for i in WeightType],240                        label="Weights type",241                        multiselect=False,242                        value="Original",243                        interactive=True,244                    )245                    base_model_name_textbox = gr.Textbox(label="Base model (for delta or adapter weights)")246 247            with gr.Column():248                with gr.Accordion(249                    f"โœ… Finished Evaluations ({len(finished_eval_queue_df)})",250                    open=False,251                ):252                    with gr.Row():253                        finished_eval_table = gr.components.Dataframe(254                            value=finished_eval_queue_df,255                            headers=EVAL_COLS,256                            datatype=EVAL_TYPES,257                            row_count=5,258                        )259                with gr.Accordion(260                    f"๐Ÿ”„ Running Evaluation Queue ({len(running_eval_queue_df)})",261                    open=False,262                ):263                    with gr.Row():264                        running_eval_table = gr.components.Dataframe(265                            value=running_eval_queue_df,266                            headers=EVAL_COLS,267                            datatype=EVAL_TYPES,268                            row_count=5,269                        )270 271                with gr.Accordion(272                    f"โณ Pending Evaluation Queue ({len(pending_eval_queue_df)})",273                    open=False,274                ):275                    with gr.Row():276                        pending_eval_table = gr.components.Dataframe(277                            value=pending_eval_queue_df,278                            headers=EVAL_COLS,279                            datatype=EVAL_TYPES,280                            row_count=5,281                        )282 283            submit_button = gr.Button("Submit Eval")284            submission_result = gr.Markdown()285            submit_button.click(286                add_new_eval,287                [288                    model_name_textbox,289                    base_model_name_textbox,290                    revision_name_textbox,291                    precision,292                    weight_type,293                    model_type,294                ],295                submission_result,296            )297 298    with gr.Row():299        with gr.Accordion("๐Ÿ“™ Citation", open=False):300            citation_button = gr.Textbox(301                value=CITATION_BUTTON_TEXT,302                label=CITATION_BUTTON_LABEL,303                lines=20,304                elem_id="citation-button",305                show_copy_button=True,306            )307 308    demo.load(fn=get_latest_data_leaderboard, inputs=None, outputs=[leaderboard])309    demo.load(fn=get_latest_data_queue, inputs=None, outputs=[finished_eval_table, running_eval_table, pending_eval_table])310 311demo.queue(default_concurrency_limit=40)312 313# Start ephemeral Spaces on PRs (see config in README.md)314from gradio_space_ci.webhook import IS_EPHEMERAL_SPACE, SPACE_ID, configure_space_ci315 316def enable_space_ci_and_return_server(ui: gr.Blocks) -> WebhooksServer:317    # Taken from https://huggingface.co/spaces/Wauplin/gradio-space-ci/blob/075119aee75ab5e7150bf0814eec91c83482e790/src/gradio_space_ci/webhook.py#L61318    # Compared to original, this one do not monkeypatch Gradio which allows us to define more webhooks.319    # ht to Lucain!320    if SPACE_ID is None:321        print("Not in a Space: Space CI disabled.")322        return WebhooksServer(ui=demo)323 324    if IS_EPHEMERAL_SPACE:325        print("In an ephemeral Space: Space CI disabled.")326        return WebhooksServer(ui=demo)327 328    card = RepoCard.load(repo_id_or_path=SPACE_ID, repo_type="space")329    config = card.data.get("space_ci", {})330    print(f"Enabling Space CI with config from README: {config}")331 332    return configure_space_ci(333        blocks=ui,334        trusted_authors=config.get("trusted_authors"),335        private=config.get("private", "auto"),336        variables=config.get("variables", "auto"),337        secrets=config.get("secrets"),338        hardware=config.get("hardware"),339        storage=config.get("storage"),340    )341 342# Create webhooks server (with CI url if in Space and not ephemeral)343webhooks_server = enable_space_ci_and_return_server(ui=demo)344 345# Add webhooks346@webhooks_server.add_webhook347async def update_leaderboard(payload: WebhookPayload) -> None:348    """Redownloads the leaderboard dataset each time it updates"""349    if payload.repo.type == "dataset" and payload.event.action == "update":350        datasets.load_dataset(351            AGGREGATED_REPO, 352            "default", 353            split="train", 354            cache_dir=HF_HOME, 355            download_mode=datasets.DownloadMode.FORCE_REDOWNLOAD, 356            verification_mode="no_checks"357        )358 359@webhooks_server.add_webhook    360async def update_queue(payload: WebhookPayload) -> None:361    """Redownloads the queue dataset each time it updates"""362    if payload.repo.type == "dataset" and payload.event.action == "update":363        download_dataset(QUEUE_REPO, EVAL_REQUESTS_PATH)364 365webhooks_server.launch()366