import gradio as gr from gradio_leaderboard import Leaderboard import pandas as pd from huggingface_hub import snapshot_download, create_repo from huggingface_hub.utils import RepositoryNotFoundError import os from src.about import ( INTRODUCTION_TEXT, LLM_BENCHMARKS_TEXT, TITLE, ) from src.display.css_html_js import custom_css from src.display.utils import ( BENCHMARK_COLS, COLS, AutoEvalColumn, fields, ) from src.envs import API, EVAL_RESULTS_PATH, RESULTS_REPO, TOKEN, OWNER from src.populate import get_leaderboard_df from src.evaluation.dynamic_eval import run_dynamic_perplexity_eval def init_leaderboard(dataframe): if dataframe is None: raise ValueError("Leaderboard DataFrame is None.") print("\n=== Initializing Leaderboard ===", flush=True) print(f"DataFrame shape: {dataframe.shape}", flush=True) print(f"DataFrame columns: {dataframe.columns.tolist()}", flush=True) return Leaderboard( value=dataframe, select_columns=[c.name for c in fields(AutoEvalColumn) if not c.hidden], search_columns=[AutoEvalColumn.model.name], hide_columns=[c.name for c in fields(AutoEvalColumn) if c.hidden], filter_columns=[ AutoEvalColumn.model_type.name, AutoEvalColumn.precision.name, ], ) def run_perplexity_test(model_name, revision, precision): """Run perplexity evaluation on demand.""" import sys import traceback import gradio as gr if not model_name: return "Please enter a model name." try: # Use stderr for more reliable logging in HF Spaces sys.stderr.write(f"\n=== RUNNING PERPLEXITY TEST ===\n") sys.stderr.write(f"Model: {model_name}\n") sys.stderr.write(f"Revision: {revision}\n") sys.stderr.write(f"Precision: {precision}\n") sys.stderr.flush() success, result = run_dynamic_perplexity_eval(model_name, revision, precision) sys.stderr.write(f"Evaluation result - Success: {success}, Result: {result}\n") sys.stderr.flush() if success: sys.stderr.write("Evaluation succeeded - results saved to dataset\n") sys.stderr.flush() return f"""โœ… **Perplexity evaluation completed successfully!** **Model**: {model_name} **Perplexity Score**: {result:.4f} ๐ŸŽ‰ **Results have been saved to the dataset.** ๐Ÿ“‹ **To see your results in the leaderboard:** 1. Click on the **๐Ÿ… Leaderboard** tab above 2. Refresh the page (Ctrl+R or Cmd+R) 3. Your model should now appear in the rankings! ๐Ÿ’ก **Note**: Due to technical limitations with the leaderboard component, results cannot be updated dynamically. The refresh is necessary to see the latest rankings.""" else: return f"โŒ **Evaluation failed**: {result}" except Exception as e: error_msg = str(e) traceback_str = traceback.format_exc() sys.stderr.write(f"Critical error in run_perplexity_test: {error_msg}\n") sys.stderr.write(f"Traceback: {traceback_str}\n") sys.stderr.flush() return f"โŒ **Critical error**: {error_msg}" # Initialize results repository and directory try: # Try to download existing repository try: snapshot_download( repo_id=RESULTS_REPO, local_dir=EVAL_RESULTS_PATH, repo_type="dataset", tqdm_class=None, etag_timeout=30, token=TOKEN ) except RepositoryNotFoundError: # Create the repository if it doesn't exist print(f"Creating new results repository: {RESULTS_REPO}") create_repo( repo_id=RESULTS_REPO, repo_type="dataset", private=False, token=TOKEN ) # Create local directory os.makedirs(EVAL_RESULTS_PATH, exist_ok=True) except Exception as e: print(f"Error initializing results: {e}") # Ensure local directory exists even if repo operations fail os.makedirs(EVAL_RESULTS_PATH, exist_ok=True) # Get initial leaderboard data LEADERBOARD_DF = get_leaderboard_df(EVAL_RESULTS_PATH, COLS, BENCHMARK_COLS) # Create the Gradio interface demo = gr.Blocks(css=custom_css) with demo: gr.HTML(TITLE) gr.Markdown(INTRODUCTION_TEXT, elem_classes="markdown-text") with gr.Tabs(elem_classes="tab-buttons") as tabs: with gr.TabItem("๐Ÿ… Leaderboard", elem_id="leaderboard-tab", id=0): leaderboard = init_leaderboard(LEADERBOARD_DF) with gr.TabItem("๐Ÿ“ About", elem_id="about-tab", id=1): gr.Markdown(LLM_BENCHMARKS_TEXT, elem_classes="markdown-text") with gr.TabItem("๐Ÿงช Test Model", elem_id="test-model-tab", id=2): gr.Markdown("## Run Perplexity Test\n\nTest any Hugging Face model for perplexity evaluation.") with gr.Row(): with gr.Column(): model_name = gr.Textbox(label="Model name", placeholder="openai-community/gpt2") revision = gr.Textbox(label="Revision", placeholder="main", value="main") precision = gr.Dropdown( choices=["float16", "bfloat16"], label="Precision", value="float16" ) debug_mode = gr.Checkbox(label="Enable debug mode (more verbose logging)", value=True) with gr.Column(): test_button = gr.Button("๐Ÿš€ Run Perplexity Test", variant="primary") result = gr.Markdown() gr.Markdown(""" ### Tips: - **Check stderr logs** in HF Spaces for detailed debugging information - **After evaluation completes**, click the ๐Ÿ… Leaderboard tab and refresh the page to see results - **Example models to test**: `openai-community/gpt2`, `EleutherAI/gpt-neo-1.3B`, `openai-community/gpt2-large` - **Lower perplexity scores = better performance** (better at predicting text) ### How it works: 1. Enter a model name from Hugging Face Hub 2. Click "Run Perplexity Test" 3. Wait for evaluation to complete (may take a few minutes for large models) 4. Go to ๐Ÿ… Leaderboard tab and refresh the page to see your results! """) test_button.click( run_perplexity_test, [model_name, revision, precision], [result] ) demo.queue(default_concurrency_limit=5).launch()