celikn commited on
Commit
3217491
·
verified ·
1 Parent(s): e7c2828

Create app.py

Browse files

Benchmarking of llm models

Files changed (1) hide show
  1. app.py +156 -0
app.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ #!/usr/bin/env python3
3
+ # -*- coding: utf-8 -*-
4
+ """
5
+ Hugging Face Space: LLM Benchmarking App using Gradio
6
+ - Upload config.yaml and dataset.jsonl
7
+ - Select task
8
+ - Run benchmarking across multiple models
9
+ - Compute metrics: Exact Match, F1, ROUGE-L, BLEU
10
+ - Display results and allow CSV download
11
+ """
12
+
13
+ import os
14
+ import time
15
+ import json
16
+ import yaml
17
+ import gradio as gr
18
+ import pandas as pd
19
+ from tqdm import tqdm
20
+
21
+ # Optional metrics
22
+ try:
23
+ from rouge_score import rouge_scorer
24
+ except ImportError:
25
+ rouge_scorer = None
26
+
27
+ try:
28
+ import sacrebleu
29
+ except ImportError:
30
+ sacrebleu = None
31
+
32
+ # ---------------- Metrics ---------------- #
33
+ def exact_match(pred, ref):
34
+ return float(pred.strip().lower() == ref.strip().lower())
35
+
36
+ def token_f1(pred, ref):
37
+ pred_tokens = pred.lower().split()
38
+ ref_tokens = ref.lower().split()
39
+ if not pred_tokens and not ref_tokens:
40
+ return 1.0
41
+ if not pred_tokens or not ref_tokens:
42
+ return 0.0
43
+ common = sum(min(pred_tokens.count(t), ref_tokens.count(t)) for t in set(pred_tokens))
44
+ precision = common / len(pred_tokens)
45
+ recall = common / len(ref_tokens)
46
+ return 2 * precision * recall / (precision + recall) if precision + recall else 0.0
47
+
48
+ def rouge_l(pred, ref):
49
+ if rouge_scorer:
50
+ scorer = rouge_scorer.RougeScorer(["rougeL"], use_stemmer=True)
51
+ return scorer.score(ref, pred)["rougeL"].fmeasure
52
+ return 0.0
53
+
54
+ def bleu(pred, ref):
55
+ if sacrebleu:
56
+ return sacrebleu.corpus_bleu([pred], [[ref]]).score
57
+ return 0.0
58
+
59
+ def compute_metrics(task, prediction, reference):
60
+ metrics = {}
61
+ if task in ("qa", "classification"):
62
+ metrics["exact_match"] = exact_match(prediction, reference)
63
+ metrics["f1"] = token_f1(prediction, reference)
64
+ elif task in ("summarization", "translation"):
65
+ metrics["rougeL_f"] = rouge_l(prediction, reference)
66
+ metrics["bleu"] = bleu(prediction, reference)
67
+ else:
68
+ metrics["f1"] = token_f1(prediction, reference)
69
+ return metrics
70
+
71
+ # ---------------- Hugging Face Inference ---------------- #
72
+ def hf_generate(model_name, prompt, max_new_tokens=256, temperature=0.2):
73
+ from huggingface_hub import InferenceClient
74
+ client = InferenceClient(model=model_name, token=os.getenv("HUGGINGFACE_HUB_TOKEN"))
75
+ start = time.time()
76
+ try:
77
+ output = client.text_generation(prompt, max_new_tokens=max_new_tokens, temperature=temperature)
78
+ latency = time.time() - start
79
+ return output.strip(), latency
80
+ except Exception as e:
81
+ return f"ERROR: {e}", time.time() - start
82
+
83
+ # ---------------- Benchmark Function ---------------- #
84
+ def benchmark(config_text, dataset_text, task):
85
+ cfg = yaml.safe_load(config_text)
86
+ data = [json.loads(line) for line in dataset_text.splitlines() if line.strip()]
87
+
88
+ models = cfg.get("models", [])
89
+ templates = cfg.get("prompt_templates", {})
90
+ template = templates.get(task, "{{text}}")
91
+
92
+ results = []
93
+ for m in models:
94
+ model_name = m["name"]
95
+ max_tokens = m.get("params", {}).get("max_tokens", 256)
96
+ temperature = m.get("params", {}).get("temperature", 0.2)
97
+ for ex in tqdm(data, desc=model_name):
98
+ variables = {k: ex.get(k, "") for k in ("question", "context", "text", "labels")}
99
+ prompt = template
100
+ for k, v in variables.items():
101
+ prompt = prompt.replace(f"{{{{{k}}}}}", str(v))
102
+ prediction, latency = hf_generate(model_name, prompt, max_new_tokens=max_tokens, temperature=temperature)
103
+ metrics = compute_metrics(task, prediction, ex.get("reference", ""))
104
+ row = {
105
+ "model": model_name,
106
+ "id": ex.get("id", ""),
107
+ "task": task,
108
+ "prompt": prompt,
109
+ "prediction": prediction,
110
+ "reference": ex.get("reference", ""),
111
+ "latency_seconds": latency,
112
+ **metrics
113
+ }
114
+ results.append(row)
115
+
116
+ df = pd.DataFrame(results)
117
+ summary = []
118
+ for model_name in set(df["model"]):
119
+ sub = df[df["model"] == model_name]
120
+ summary.append(f"## {model_name}")
121
+ summary.append(f"Samples: {len(sub)}")
122
+ for metric in ["exact_match", "f1", "rougeL_f", "bleu"]:
123
+ if metric in sub.columns:
124
+ vals = [v for v in sub[metric] if isinstance(v, (int, float))]
125
+ if vals:
126
+ summary.append(f"{metric}: mean={sum(vals)/len(vals):.4f}")
127
+ summary.append(f"Latency mean: {sum(sub['latency_seconds'])/len(sub):.3f}s\n")
128
+
129
+ return df, "\n".join(summary)
130
+
131
+ # ---------------- Gradio UI ---------------- #
132
+ with gr.Blocks() as demo:
133
+ gr.Markdown("# LLM Benchmarking App (Hugging Face)")
134
+ gr.Markdown("Upload config.yaml and dataset.jsonl, select task, and run benchmark.")
135
+
136
+ with gr.Row():
137
+ config_file = gr.File(label="Upload Config (YAML)", type="filepath")
138
+ dataset_file = gr.File(label="Upload Dataset (JSONL)", type="filepath")
139
+ task = gr.Textbox(label="Task (e.g., qa, summarization, classification)")
140
+ run_btn = gr.Button("Run Benchmark")
141
+
142
+ results_table = gr.Dataframe(headers=["model","id","task","prediction","reference","latency_seconds","exact_match","f1","rougeL_f","bleu"], label="Results")
143
+ summary_box = gr.Textbox(label="Summary", lines=10)
144
+ download_csv = gr.File(label="Download CSV")
145
+
146
+ def run_benchmark(config_path, dataset_path, task):
147
+ config_text = open(config_path, "r", encoding="utf-8").read()
148
+ dataset_text = open(dataset_path, "r", encoding="utf-8").read()
149
+ df, summary = benchmark(config_text, dataset_text, task)
150
+ csv_path = "results.csv"
151
+ df.to_csv(csv_path, index=False)
152
+ return df, summary, csv_path
153
+
154
+ run_btn.click(run_benchmark, inputs=[config_file, dataset_file, task], outputs=[results_table, summary_box, download_csv])
155
+
156
+ demo.launch()