File size: 17,668 Bytes
50373cb
1ab30f9
50373cb
bd09cee
8f56293
dbdbe46
 
c6141e9
82b9bd2
50373cb
dbdbe46
 
50373cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbdbe46
c6141e9
dbdbe46
c6141e9
 
 
 
 
dbdbe46
 
50373cb
bd09cee
50373cb
 
dbdbe46
 
 
 
120caf1
dbdbe46
 
 
 
 
50373cb
dbdbe46
 
50373cb
 
dbdbe46
 
 
 
 
bd09cee
ccd50f1
 
 
 
 
bd09cee
dbdbe46
 
 
 
 
 
 
 
 
 
 
 
 
 
bd09cee
ccd50f1
 
 
 
 
bd09cee
dbdbe46
 
 
 
 
 
 
 
 
 
 
 
 
 
50373cb
 
5b0b7d5
50373cb
 
 
 
 
2144d6f
50373cb
dbdbe46
 
 
82b9bd2
120caf1
b2f90ed
82b9bd2
120caf1
dbdbe46
78a8c9c
 
82b9bd2
b2f90ed
 
 
dbdbe46
 
78a8c9c
120caf1
 
 
b2f90ed
78a8c9c
dbdbe46
c6141e9
dbdbe46
 
78a8c9c
c6141e9
5b0b7d5
 
c6141e9
120caf1
78a8c9c
c6141e9
1264ff3
 
c6141e9
dbdbe46
78a8c9c
120caf1
78a8c9c
120caf1
78a8c9c
120caf1
 
700205f
 
 
bd09cee
b2f90ed
700205f
bd09cee
b2f90ed
 
bd09cee
700205f
 
 
bd09cee
b2f90ed
 
bd09cee
700205f
b2f90ed
bd09cee
700205f
 
bd09cee
b2f90ed
 
 
 
 
 
bd09cee
78a8c9c
120caf1
78a8c9c
 
 
1264ff3
bd09cee
5b0b7d5
 
 
 
700205f
4e06ea4
 
c6141e9
700205f
 
 
 
 
 
82b9bd2
700205f
c6141e9
82b9bd2
700205f
c6141e9
82b9bd2
5b0b7d5
 
 
1264ff3
 
 
4e06ea4
366074b
dbdbe46
8f56293
 
 
 
dbdbe46
5b0b7d5
 
 
240cd3c
 
 
 
 
 
 
 
 
 
 
 
 
82b9bd2
240cd3c
 
 
 
5b0b7d5
 
 
 
 
 
 
 
c6141e9
5b0b7d5
 
 
240cd3c
 
8f56293
240cd3c
 
 
 
 
 
 
 
 
02baba1
240cd3c
 
50373cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1264ff3
dbdbe46
 
 
 
82b9bd2
700205f
5b0b7d5
700205f
 
 
 
 
 
 
 
 
5b0b7d5
82b9bd2
700205f
 
 
 
 
 
b833760
 
5b0b7d5
82b9bd2
5c1ec97
2144d6f
82b9bd2
1264ff3
 
82b9bd2
b833760
dbdbe46
5b0b7d5
b833760
82b9bd2
120caf1
 
dbdbe46
fcb44f9
 
 
 
 
 
 
 
 
 
b833760
fcb44f9
 
 
 
 
 
 
 
 
 
 
 
efd3c08
683aa2a
2144d6f
47d9606
683aa2a
dbdbe46
50373cb
 
dbdbe46
50373cb
dbdbe46
 
50373cb
47d9606
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
import gradio as gr
from gradio_leaderboard import Leaderboard, ColumnFilter, SelectColumns
from apscheduler.schedulers.background import BackgroundScheduler
from huggingface_hub import snapshot_download
import pandas as pd
import os
import logging
from datetime import datetime
from datasets import Dataset

from src.core.evaluation import EvaluationManager, EvaluationRequest
from src.logging_config import setup_logging
from src.about import (
    CITATION_BUTTON_LABEL,
    CITATION_BUTTON_TEXT,
    EVALUATION_QUEUE_TEXT,
    INTRODUCTION_TEXT,
    LLM_BENCHMARKS_TEXT,
    TITLE,
)
from src.display.css_html_js import custom_css
from src.display.utils import (
    BENCHMARK_COLS,
    COLS,
    EVAL_COLS,
    EVAL_TYPES,
    ModelType,
    WeightType,
    Precision
)
from src.envs import (
    API,
    CACHE_PATH,
    EVAL_REQUESTS_PATH,
    EVAL_RESULTS_PATH,
    QUEUE_REPO,
    REPO_ID,
    RESULTS_REPO,
    TOKEN
)
from src.populate import get_evaluation_queue_df, get_leaderboard_df
from src.submission.submit import initialize_queue_repo, initialize_results_repo


# Setup logging
setup_logging(log_dir="logs")
logger = logging.getLogger('web')

# Initialize evaluation manager
evaluation_manager = EvaluationManager(
    results_dir=EVAL_RESULTS_PATH,
    backup_dir=os.path.join(CACHE_PATH, "eval-backups")
)

def restart_space():
    """Restart the Hugging Face space."""
    logger.info("Restarting space")
    API.restart_space(repo_id=REPO_ID)

def initialize_space():
    """Initialize the space by downloading required data."""
    logger.info("Initializing space")
    try:
        logger.info(f"Downloading queue data from {QUEUE_REPO}")

        # Initialize queue repository if needed
        if not initialize_queue_repo():
            logger.error("Failed to initialize queue repository")
            restart_space()
            return

        snapshot_download(
            repo_id=QUEUE_REPO,
            local_dir=EVAL_REQUESTS_PATH,
            repo_type="dataset",
            tqdm_class=None,
            etag_timeout=30,
            token=TOKEN
        )
    except Exception as e:
        logger.error(f"Failed to download queue data: {str(e)}")
        restart_space()

    try:
        logger.info(f"Downloading results data from {RESULTS_REPO}")

        # Initialize results repository if needed
        if not initialize_results_repo():
            logger.error("Failed to initialize results repository")
            restart_space()
            return

        snapshot_download(
            repo_id=RESULTS_REPO,
            local_dir=EVAL_RESULTS_PATH,
            repo_type="dataset",
            tqdm_class=None,
            etag_timeout=30,
            token=TOKEN
        )
    except Exception as e:
        logger.error(f"Failed to download results data: {str(e)}")
        restart_space()

# Initialize space
initialize_space()


LEADERBOARD_DF = get_leaderboard_df(COLS, BENCHMARK_COLS)

(
    finished_eval_queue_df,
    running_eval_queue_df,
    pending_eval_queue_df,
) = get_evaluation_queue_df(EVAL_COLS)

def process_evaluation_queue():
    """Process pending evaluation requests."""
    logger.info("Processing evaluation queue")

    # Fetch pending requests from Hugging Face repository
    _, _, pending_requests = get_evaluation_queue_df(EVAL_COLS + ['model_raw', 'timestamp'])

    for _, request in pending_requests.iterrows():
        try:
            model_name = request['model_raw']
            logger.info(f"Processing request for model: {model_name}")

            # Update status to RUNNING
            update_request_status(model_name, "RUNNING")

            # Convert queue request to evaluation request
            eval_request = EvaluationRequest(
                model=model_name,
                revision=request['revision'],
                precision=request['precision'],
                weight_type=request['weight_type'],
                submitted_time=request['timestamp'],  # Use the actual timestamp field
                model_type=request.get('model_type', '')
            )

            # Run evaluation
            results = evaluation_manager.run_evaluation(eval_request)
            logger.info(f"Evaluation complete for {model_name}")

            # Save results to stacklok/results
            save_results_to_repo(results, RESULTS_REPO)

            # Update request status in stacklok/requests
            update_request_status(model_name, "FINISHED")

            # Update leaderboard
            update_leaderboard()

        except Exception as e:
            logger.error(f"Evaluation failed for {model_name}: {str(e)}", exc_info=True)
            # Update request status to indicate failure
            update_request_status(model_name, "FAILED")

def update_request_status(model_name, status):
    """Update the status of a request in the Hugging Face repository."""
    try:
        # Load the current dataset
        from datasets import load_dataset
        dataset = load_dataset(QUEUE_REPO, split="train")

        # Convert to dictionary for easier manipulation
        data_dict = dataset.to_dict()

        # Find the most recent request for this model
        indices = [i for i, m in enumerate(data_dict["model_raw"]) if m == model_name]

        if not indices:
            logger.error(f"No request found for model {model_name}")
            return

        # Get the most recent request (last index)
        latest_index = indices[-1]

        # Update the status for the found request
        data_dict["status"][latest_index] = status

        # Create new dataset with updated status
        updated_dataset = Dataset.from_dict(data_dict)

        # Push the updated dataset back to the hub with a descriptive commit message
        updated_dataset.push_to_hub(
            QUEUE_REPO,
            split="train",
            commit_message=f"Update status to {status} for {model_name}"
        )

        logger.info(f"Updated status for {model_name} to {status}")
    except Exception as e:
        logger.error(f"Failed to update status for {model_name}: {str(e)}", exc_info=True)

# Remove the extract_model_name function as it's no longer needed



def save_results_to_repo(results, repo):
    """Save evaluation results to the specified repository."""
    try:
        model_id = results.get('model', '')
        if not model_id:
            raise ValueError("Model ID not found in results")

        # Convert all values to lists if they aren't already
        dataset_dict = {
            k: [v] if not isinstance(v, list) else v
            for k, v in results.items()
        }

        # Create a Dataset object from the results
        dataset = Dataset.from_dict(dataset_dict)

        # Push the dataset to the Hugging Face Hub
        dataset.push_to_hub(repo, split="train")

        logger.info(f"Saved results for {model_id} to {repo}")
    except Exception as e:
        logger.error(f"Failed to save results to {repo}: {str(e)}", exc_info=True)

def update_leaderboard():
    """Update the leaderboard with latest evaluation results."""
    global LEADERBOARD_DF
    LEADERBOARD_DF = get_leaderboard_df(COLS, BENCHMARK_COLS)
    return LEADERBOARD_DF

def init_leaderboard(df):
    """Initialize the leaderboard with the given DataFrame."""
    if df is None or df.empty:
        df = pd.DataFrame(columns=COLS)
        logger.info("Creating empty leaderboard - no evaluations completed yet")
    else:
        logger.info(f"Initializing leaderboard with {len(df)} rows")

    # Ensure all required columns exist
    for col in COLS:
        if col not in df.columns:
            logger.warning(f"Column {col} not found in DataFrame, adding with None values")
            df[col] = None

    # Map dataset columns to display columns
    column_mapping = {
        "model_id": "Model",
        "security_score": "Security Score ⬆️",
        "safetensors_compliant": "Safetensors",
        "precision": "Precision"
    }

    for src, dst in column_mapping.items():
        if src in df.columns:
            df[dst] = df[src]
            logger.debug(f"Mapped column {src} to {dst}")

    # Sort by Security Score if available
    if "Security Score ⬆️" in df.columns:
        df = df.sort_values(by="Security Score ⬆️", ascending=False)
        logger.info("Sorted leaderboard by Security Score")

    # Select only the columns we want to display
    df = df[COLS]

    logger.info(f"Final leaderboard columns: {df.columns.tolist()}")
    logger.debug(f"Leaderboard data:\n{df}")

    # Create the leaderboard using gradio_leaderboard
    return Leaderboard(
        value=df,
        datatype=["html" if col == "Model" else "number" if col == "Security Score ⬆️" else "bool" if col == "Safetensors" else "str" for col in COLS],
        select_columns=SelectColumns(
            default_selection=COLS,
            cant_deselect=["Model", "Security Score ⬆️", "Safetensors"],
            label="Select Columns to Display:",
        ),
        search_columns=["Model"],
        filter_columns=[
            ColumnFilter("Safetensors", type="boolean", label="Show only Safetensors models"),
            ColumnFilter("Security Score ⬆️", type="slider", min=0, max=1, label="Minimum Security Score"),
        ],
        interactive=False,
    )


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("πŸ”’ Security Leaderboard", elem_id="security-leaderboard-tab", id=0):
            leaderboard = init_leaderboard(LEADERBOARD_DF)

        with gr.TabItem("πŸ“ About", elem_id="about-tab", id=2):
            gr.Markdown(LLM_BENCHMARKS_TEXT, elem_classes="markdown-text")

        with gr.TabItem("πŸš€ Submit Model", elem_id="submit-tab", id=3):
            with gr.Column():
                with gr.Row():
                    gr.Markdown(EVALUATION_QUEUE_TEXT, elem_classes="markdown-text")

                with gr.Column():
                    with gr.Accordion(
                        f"βœ… Finished Evaluations ({len(finished_eval_queue_df)})",
                        open=False,
                    ):
                        with gr.Row():
                            finished_eval_table = gr.components.Dataframe(
                                value=finished_eval_queue_df,
                                headers=EVAL_COLS,
                                datatype=EVAL_TYPES,
                                row_count=5,
                            )
                    with gr.Accordion(
                        f"πŸ”„ Running Evaluation Queue ({len(running_eval_queue_df)})",
                        open=False,
                    ):
                        with gr.Row():
                            running_eval_table = gr.components.Dataframe(
                                value=running_eval_queue_df,
                                headers=EVAL_COLS,
                                datatype=EVAL_TYPES,
                                row_count=5,
                            )

                    with gr.Accordion(
                        f"⏳ Pending Evaluation Queue ({len(pending_eval_queue_df)})",
                        open=False,
                    ):
                        with gr.Row():
                            pending_eval_table = gr.components.Dataframe(
                                value=pending_eval_queue_df,
                                headers=EVAL_COLS,
                                datatype=EVAL_TYPES,
                                row_count=5,
                            )
            with gr.Row():
                gr.Markdown("# πŸ”’ Submit Your Model for Security Evaluation", elem_classes="markdown-text")

            with gr.Row():
                with gr.Column():
                    model_name_textbox = gr.Textbox(
                        label="Model name (organization/model-name)",
                        placeholder="huggingface/model-name"
                    )
                    revision_name_textbox = gr.Textbox(
                        label="Revision commit",
                        placeholder="main"
                    )
                    model_type = gr.Dropdown(
                        choices=[t.to_str(" : ") for t in ModelType if t != ModelType.Unknown],
                        label="Model type",
                        multiselect=False,
                        value=None,
                        interactive=True,
                    )

                with gr.Column():
                    precision = gr.Dropdown(
                        choices=[i.value.name for i in Precision if i != Precision.Unknown],
                        label="Precision",
                        multiselect=False,
                        value="float16",
                        interactive=True,
                    )
                    weight_type = gr.Dropdown(
                        choices=[i.value.name for i in WeightType],
                        label="Weight Format",
                        multiselect=False,
                        value="Safetensors",
                        interactive=True,
                    )
                    base_model_name_textbox = gr.Textbox(
                        label="Base model (for delta or adapter weights)",
                        placeholder="Optional: base model path"
                    )

            with gr.Row():
                gr.Markdown(
                    """
                    ### Security Requirements:
                    1. Model weights must be in safetensors format
                    2. Model card must include security considerations
                    3. Model will be evaluated on secure coding capabilities
                    """,
                    elem_classes="markdown-text"
                )

            submit_button = gr.Button("Submit for Security Evaluation")
            submission_result = gr.Markdown()

            def handle_submission(model, base_model, revision, precision, weight_type, model_type):
                """Handle new model submission."""
                try:
                    logger.info(f"New submission received for {model}")

                    # Prepare request data as a dataset-compatible dictionary (all values must be lists)
                    request_data = {
                        "model": [model],
                        "model_raw": [model],  # Store raw model name for processing
                        "base_model": [base_model if base_model else ""],
                        "revision": [revision if revision else "main"],
                        "precision": [precision],
                        "weight_type": [weight_type],
                        "model_type": [model_type],
                        "status": ["PENDING"],
                        "timestamp": [datetime.now().isoformat()]
                    }

                    # Convert to dataset and push to hub
                    dataset = Dataset.from_dict(request_data)
                    dataset.push_to_hub(
                        QUEUE_REPO,
                        config_name=model.replace("/", "_"),
                        split="train"
                    )

                    logger.info(f"Added request for {model} to {QUEUE_REPO}")

                    # Get updated pending evaluations
                    _, _, pending_eval_queue_df = get_evaluation_queue_df(EVAL_COLS)

                    # Start processing queue in background
                    scheduler.add_job(process_evaluation_queue, id='process_queue_job', replace_existing=True)

                    return "Submission successful! Your model has been added to the evaluation queue. Please check the 'Pending Evaluation Queue' for status updates.", pending_eval_queue_df
                except Exception as e:
                    logger.error(f"Submission failed: {str(e)}", exc_info=True)
                    return f"Error: {str(e)}", None

            # Remove the queue_manager initialization
            # queue_manager = QueueManager(queue_dir=os.path.join(CACHE_PATH, "eval-queue"))

            submit_button.click(
                handle_submission,
                [
                    model_name_textbox,
                    base_model_name_textbox,
                    revision_name_textbox,
                    precision,
                    weight_type,
                    model_type,
                ],
                [submission_result, pending_eval_table],
            )

    with gr.Row():
        with gr.Accordion("πŸ“™ Citation", open=False):
            citation_button = gr.Textbox(
                value=CITATION_BUTTON_TEXT,
                label=CITATION_BUTTON_LABEL,
                lines=20,
                elem_id="citation-button",
                show_copy_button=True,
            )

# Update evaluation tables periodically
def update_evaluation_tables():
    finished_eval_queue_df, running_eval_queue_df, pending_eval_queue_df = get_evaluation_queue_df(EVAL_COLS)
    return finished_eval_queue_df, running_eval_queue_df, pending_eval_queue_df

# Setup schedulers
scheduler = BackgroundScheduler()
scheduler.add_job(restart_space, "interval", seconds=1800)
scheduler.add_job(process_evaluation_queue, "interval", seconds=300)  # Process queue every 5 minutes
scheduler.start()

logger.info("Application startup complete")
demo.queue(default_concurrency_limit=40).launch()

# Update evaluation tables every 60 seconds
demo.load(update_evaluation_tables, outputs=[finished_eval_table, running_eval_table, pending_eval_table], every=60)