celikn commited on
Commit
d972660
·
verified ·
1 Parent(s): 213bd4f

Update app.py

Browse files

Added Judge model

Files changed (1) hide show
  1. app.py +88 -7
app.py CHANGED
@@ -128,12 +128,49 @@ def benchmark(config_text, dataset_text, task):
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)")
@@ -142,15 +179,59 @@ with gr.Blocks() as demo:
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()
 
128
 
129
  return df, "\n".join(summary)
130
 
131
+
132
+ def hf_judge(model_name, prompt, candidate, reference=None, rubric=None, max_new_tokens=256):
133
+ """
134
+ Calls a judge model to score candidate output. Returns a dict of scores.
135
+ Rubric should instruct JSON output, e.g.:
136
+ {"relevance": int, "factuality": int, "clarity": int, "overall": float}
137
+ """
138
+ from huggingface_hub import InferenceClient
139
+ client = InferenceClient(model=model_name, token=os.getenv("HF_TOKEN"))
140
+
141
+ rubric = rubric or (
142
+ "Evaluate the candidate answer. Score 1–5 for:\n"
143
+ "- Relevance: addresses the prompt\n"
144
+ "- Factuality: correct and supported\n"
145
+ "- Clarity: clear and well-structured\n"
146
+ "Return JSON: {\"relevance\": int, \"factuality\": int, \"clarity\": int, \"overall\": float}"
147
+ )
148
+
149
+ judge_prompt = (
150
+ f"{rubric}\n\nPrompt:\n{prompt}\n\n"
151
+ f"Candidate:\n{candidate}\n\n"
152
+ f"Reference (if available):\n{reference if reference is not None else 'N/A'}\n"
153
+ )
154
+
155
+ try:
156
+ text = client.text_generation(judge_prompt, max_new_tokens=max_new_tokens, temperature=0.0)
157
+ # Attempt to parse JSON anywhere in the response:
158
+ import re, json
159
+ m = re.search(r'\{.*\}', text, re.S)
160
+ return json.loads(m.group(0)) if m else {"raw": text}
161
+ except Exception as e:
162
+ return {"error": str(e)}
163
+
164
+
165
  # ---------------- Gradio UI ---------------- #
166
  with gr.Blocks() as demo:
167
  gr.Markdown("# LLM Benchmarking App (Hugging Face)")
168
  gr.Markdown("Upload config.yaml and dataset.jsonl, select task, and run benchmark.")
169
+
170
 
171
  with gr.Row():
172
+ use_judge = gr.Checkbox(label="Use judge model", value=False)
173
+ judge_model = gr.Textbox(label="Judge model (HF repo id)", value="mistralai/Mistral-7B-Instruct")
174
  config_file = gr.File(label="Upload Config (YAML)", type="filepath")
175
  dataset_file = gr.File(label="Upload Dataset (JSONL)", type="filepath")
176
  task = gr.Textbox(label="Task (e.g., qa, summarization, classification)")
 
179
  results_table = gr.Dataframe(headers=["model","id","task","prediction","reference","latency_seconds","exact_match","f1","rougeL_f","bleu"], label="Results")
180
  summary_box = gr.Textbox(label="Summary", lines=10)
181
  download_csv = gr.File(label="Download CSV")
182
+
183
+
184
 
185
+
186
+
187
+ def run_benchmark(config_path, dataset_path, task, use_judge=False, judge_model=None):
188
  config_text = open(config_path, "r", encoding="utf-8").read()
189
  dataset_text = open(dataset_path, "r", encoding="utf-8").read()
190
+ cfg = yaml.safe_load(config_text)
191
+ data = [json.loads(line) for line in dataset_text.splitlines() if line.strip()]
192
+ template = cfg.get("prompt_templates", {}).get(task, "{{text}}")
193
+
194
+ results = []
195
+ for m in cfg.get("models", []):
196
+ model_name = m["name"]
197
+ max_tokens = m.get("params", {}).get("max_tokens", 256)
198
+ temperature = m.get("params", {}).get("temperature", 0.2)
199
+
200
+ for ex in data:
201
+ variables = {k: ex.get(k, "") for k in ("question", "context", "text", "labels")}
202
+ prompt = template
203
+ for k, v in variables.items():
204
+ prompt = prompt.replace(f"{{{{{k}}}}}", str(v))
205
+
206
+ prediction, latency = hf_generate(model_name, prompt, max_new_tokens=max_tokens, temperature=temperature)
207
+ metrics = compute_metrics(task, prediction, ex.get("reference", ""))
208
+
209
+ row = {
210
+ "model": model_name,
211
+ "id": ex.get("id", ""),
212
+ "task": task,
213
+ "prompt": prompt,
214
+ "prediction": prediction,
215
+ "reference": ex.get("reference", ""),
216
+ "latency_seconds": latency,
217
+ **metrics
218
+ }
219
+
220
+ if use_judge and judge_model:
221
+ scores = hf_judge(judge_model, prompt, prediction, ex.get("reference", ""))
222
+ # Flatten judge scores with prefix
223
+ for k, v in (scores.items() if isinstance(scores, dict) else []):
224
+ row[f"judge_{k}"] = v
225
+
226
+ results.append(row)
227
+
228
+ # Save results and summary as before …
229
+ # (Then return df, summary, csv_path)
230
+
231
+ run_btn.click(
232
+ run_benchmark,
233
+ inputs=[config_file, dataset_file, task, use_judge, judge_model],
234
+ outputs=[results_table, summary_box, download_csv]
235
+ )
236
 
237
  demo.launch()