gamemeine commited on
Commit
a1fcbcc
·
1 Parent(s): ed39909

Initialize leaderboard

Browse files
Files changed (5) hide show
  1. .env.example +1 -0
  2. .gitignore +4 -0
  3. README.md +1 -1
  4. app.py +286 -0
  5. requirements.txt +3 -0
.env.example ADDED
@@ -0,0 +1 @@
 
 
1
+ HF_TOKEN=
.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ .env
README.md CHANGED
@@ -1,5 +1,5 @@
1
  ---
2
- title: PLLuM SLURM Tutorial
3
  emoji: 💻
4
  colorFrom: indigo
5
  colorTo: yellow
 
1
  ---
2
+ title: "Evaluating LLMs on Athena: a practical introduction to Slurm"
3
  emoji: 💻
4
  colorFrom: indigo
5
  colorTo: yellow
app.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import json
3
+ import logging
4
+ import math
5
+ import os
6
+ import re
7
+ from collections import Counter, defaultdict, deque
8
+ from datetime import datetime, timezone
9
+ from pathlib import Path
10
+
11
+ import gradio as gr
12
+ from dotenv import load_dotenv
13
+ from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download
14
+
15
+ load_dotenv(Path(__file__).with_name(".env"))
16
+
17
+ REPO_ID = "gamemeine/pllum-slurm-dataset"
18
+ DATA_FILE = "data/evaluation_dataset.jsonl"
19
+ TOLERANCE = 1e-6
20
+ ERROR_TYPES = ("wrong_answer", "parsing_error", "tool_error", "call_budget_exceeded",
21
+ "context_limit", "missing_prediction", "evaluation_error")
22
+ RECENT_LIMIT = 50
23
+ api = HfApi(token=os.environ.get("HF_TOKEN"))
24
+
25
+
26
+ def reject_constant(value):
27
+ raise ValueError(f"Invalid JSON value: {value}")
28
+
29
+
30
+ def read_json(path):
31
+ return json.loads(Path(path).read_text(encoding="utf-8"), parse_constant=reject_constant)
32
+
33
+
34
+ def download(filename, revision):
35
+ return hf_hub_download(REPO_ID, filename, repo_type="dataset", revision=revision, token=api.token)
36
+
37
+
38
+ def load_benchmark(revision):
39
+ content = Path(download(DATA_FILE, revision)).read_bytes()
40
+ rows = [json.loads(line, parse_constant=reject_constant) for line in content.decode("utf-8").splitlines() if line.strip()]
41
+ if not rows:
42
+ raise ValueError("The benchmark is empty.")
43
+ return rows, hashlib.sha256(content).hexdigest()
44
+
45
+
46
+ def number(value):
47
+ if isinstance(value, bool) or not isinstance(value, (int, float, str)):
48
+ raise ValueError("Prediction must be a number or null.")
49
+ if isinstance(value, str):
50
+ value = value.replace(",", ".")
51
+ value = float(value)
52
+ if not math.isfinite(value):
53
+ raise ValueError("Numbers must be finite.")
54
+ return value
55
+
56
+
57
+ def classify_error(error):
58
+ """Classify evaluator messages; keep unknown failures as evaluation_error."""
59
+ text = str(error).lower()
60
+ if "tool call budget exhausted" in text:
61
+ return "call_budget_exceeded"
62
+ if "exceeds max-model-len" in text:
63
+ return "context_limit"
64
+ if "unknown tool:" in text or " requires arguments " in text or re.match(
65
+ r"^(add|subtract|multiply|divide|modulo|power|absolute_value|square_root):", text
66
+ ):
67
+ return "tool_error"
68
+ if any(marker in text for marker in (
69
+ "expected only a final number", "final answer does not contain a number",
70
+ "expected exactly one tagged", "tool call must contain", "tool name must",
71
+ "tool arguments must", "expected a finite real number", "floating-point range",
72
+ "expecting value", "expecting property name", "expecting ',' delimiter",
73
+ "expecting ':' delimiter", "unterminated string", "extra data", "invalid control character", "invalid escape",
74
+ )):
75
+ return "parsing_error"
76
+ return "evaluation_error"
77
+
78
+
79
+ def score(samples, benchmark):
80
+ if not isinstance(samples, list) or not all(isinstance(sample, dict) for sample in samples):
81
+ raise ValueError("samples.json must contain a list of evaluator samples.")
82
+ # Match by question and category, so changing row order is harmless.
83
+ def key(row):
84
+ prompt = row.get("prompt", row.get("task"))
85
+ category = row.get("category")
86
+ if not isinstance(prompt, str) or not isinstance(category, str):
87
+ raise ValueError("Each sample must have a prompt and category.")
88
+ return prompt, category
89
+
90
+ if Counter(map(key, samples)) != Counter(map(key, benchmark)):
91
+ raise ValueError("The submission must match the complete benchmark, including duplicate counts.")
92
+ references = defaultdict(deque)
93
+ for row in benchmark:
94
+ references[key(row)].append(number(row["answer"]))
95
+ categories = defaultdict(lambda: {"total": 0, "correct": 0})
96
+ error_counts = dict.fromkeys(ERROR_TYPES, 0)
97
+ details = []
98
+ for index, sample in enumerate(samples):
99
+ answer = references[key(sample)].popleft()
100
+ prediction, absolute_error = None, None
101
+ prediction_error = False
102
+ if sample.get("prediction") is not None:
103
+ try:
104
+ prediction = number(sample["prediction"])
105
+ absolute_error = abs(prediction - answer)
106
+ if not math.isfinite(absolute_error):
107
+ absolute_error = None
108
+ except (ValueError, TypeError, OverflowError):
109
+ prediction_error = True
110
+ if sample.get("error"):
111
+ outcome = classify_error(sample["error"])
112
+ elif prediction_error:
113
+ outcome = "parsing_error"
114
+ elif prediction is None:
115
+ outcome = "missing_prediction"
116
+ elif abs(prediction - answer) <= TOLERANCE:
117
+ outcome = "correct"
118
+ else:
119
+ outcome = "wrong_answer"
120
+ correct = outcome == "correct"
121
+ if not correct:
122
+ error_counts[outcome] += 1
123
+ details.append({
124
+ "index": index, "prompt": key(sample)[0], "category": sample["category"],
125
+ "expected_answer": answer, "prediction": prediction,
126
+ "absolute_error": absolute_error, "outcome": outcome, "error": sample.get("error"),
127
+ })
128
+ category = categories[sample["category"]]
129
+ category["total"] += 1
130
+ category["correct"] += int(correct)
131
+ for category in categories.values():
132
+ category["accuracy"] = category["correct"] / category["total"]
133
+ correct = sum(category["correct"] for category in categories.values())
134
+ return {
135
+ "total": len(samples), "correct": correct, "accuracy": correct / len(samples),
136
+ "by_category": dict(sorted(categories.items())),
137
+ "error_counts": error_counts, "sample_results": details,
138
+ }
139
+
140
+
141
+ def tables(results, categories):
142
+ headers = ["Login", "Submission", "Accuracy (%)"] + [f"{category} (%)" for category in categories]
143
+
144
+ def row(result):
145
+ return [result["login"], result["submission_id"], round(100 * result["accuracy"], 2)] + [
146
+ round(100 * result["by_category"][category]["accuracy"], 2) for category in categories
147
+ ]
148
+
149
+ recent = sorted(results, key=lambda result: result["created_at"], reverse=True)[:RECENT_LIMIT]
150
+ submissions = gr.update(
151
+ headers=["Submitted (UTC)"] + headers + ["Correct / total"] + list(ERROR_TYPES),
152
+ value=[
153
+ [result["created_at"]] + row(result) + [f"{result['correct']} / {result['total']}"]
154
+ + [result["error_counts"][error] for error in ERROR_TYPES]
155
+ for result in recent
156
+ ],
157
+ )
158
+ best = {}
159
+ # Highest accuracy wins; the earliest submission wins an exact tie.
160
+ for result in sorted(results, key=lambda result: (-result["accuracy"], result["created_at"], result["submission_id"])):
161
+ best.setdefault(result["login"], result)
162
+ leaderboard = gr.update(
163
+ headers=["#"] + headers,
164
+ value=[[rank] + row(result) for rank, result in enumerate(best.values(), 1)],
165
+ )
166
+ return submissions, leaderboard
167
+
168
+
169
+ def refresh_tables():
170
+ try:
171
+ revision = api.dataset_info(REPO_ID).sha
172
+ benchmark, digest = load_benchmark(revision)
173
+ categories = sorted({row["category"] for row in benchmark})
174
+ results = []
175
+ for filename in api.list_repo_files(REPO_ID, repo_type="dataset", revision=revision):
176
+ if filename.startswith("submissions/") and filename.endswith("/results.json"):
177
+ result = read_json(download(filename, revision))
178
+ if result.get("dataset_sha256") == digest:
179
+ # Compute diagnostics for submissions saved before error classification existed.
180
+ if "error_counts" not in result:
181
+ samples_file = filename.removesuffix("results.json") + "samples.json"
182
+ result.update(score(read_json(download(samples_file, revision)), benchmark))
183
+ results.append(result)
184
+ return tables(results, categories)
185
+ except Exception as exc:
186
+ logging.exception("Could not load submissions")
187
+ raise gr.Error("Could not load results. Check HF_TOKEN access and the benchmark file in the dataset.") from exc
188
+
189
+
190
+ def submit(login, filepath):
191
+ login = (login or "").strip()
192
+ if not re.fullmatch(r"tutorial0(?:0[1-9]|[12][0-9]|3[0-3])", login):
193
+ raise gr.Error("Use your assigned login: tutorial001–tutorial033.")
194
+ if not filepath:
195
+ raise gr.Error("Upload samples.json.")
196
+ try:
197
+ samples = read_json(filepath)
198
+ revision = api.dataset_info(REPO_ID).sha
199
+ benchmark, digest = load_benchmark(revision)
200
+ result = score(samples, benchmark)
201
+ except (ValueError, TypeError, KeyError, OverflowError) as exc:
202
+ raise gr.Error(f"Invalid submission: {exc}") from exc
203
+ except Exception as exc:
204
+ logging.exception("Could not load the benchmark")
205
+ raise gr.Error("Could not load the benchmark. Check dataset access.") from exc
206
+
207
+ now = datetime.now(timezone.utc)
208
+ submission_id = f"{login}-{now:%Y%m%dT%H%M%S%fZ}"
209
+ result.update(login=login, submission_id=submission_id, created_at=now.isoformat(),
210
+ dataset=DATA_FILE, dataset_sha256=digest, tolerance=TOLERANCE)
211
+ try:
212
+ api.create_commit(
213
+ repo_id=REPO_ID, repo_type="dataset", commit_message=f"Submission {submission_id}",
214
+ operations=[
215
+ CommitOperationAdd(path_in_repo=f"submissions/{submission_id}/samples.json", path_or_fileobj=Path(filepath)),
216
+ CommitOperationAdd(path_in_repo=f"submissions/{submission_id}/results.json",
217
+ path_or_fileobj=json.dumps(result, ensure_ascii=False, indent=2, allow_nan=False).encode("utf-8")),
218
+ ],
219
+ )
220
+ except Exception as exc:
221
+ logging.exception("Could not save the submission")
222
+ raise gr.Error("Could not save the submission. HF_TOKEN needs write access to the dataset.") from exc
223
+ errors = ", ".join(f"{name}: {count}" for name, count in result["error_counts"].items() if count)
224
+ status = (f"Saved **{submission_id}**. Accuracy: **{result['accuracy']:.2%}** "
225
+ f"({result['correct']} / {result['total']} correct).\n\nErrors: {errors or 'none'}.")
226
+ try:
227
+ return status, *refresh_tables()
228
+ except gr.Error:
229
+ return status + " Results are temporarily unavailable — click Refresh.", gr.skip(), gr.skip()
230
+
231
+
232
+ CSS = """
233
+ .gradio-container { max-width: 1280px !important; margin: auto !important; }
234
+ #workshop { width: 100%; margin: auto; }
235
+ #intro, #scoring, #status { text-align: center; }
236
+ #workshop input, #workshop th, #workshop td { text-align: center !important; }
237
+ #workshop .tab-nav { justify-content: center; }
238
+ """
239
+
240
+ with gr.Blocks(title="Evaluating LLMs on Athena: a practical introduction to Slurm") as demo:
241
+ with gr.Column(elem_id="workshop"):
242
+ gr.Markdown("""# Evaluating LLMs on Athena: a practical introduction to Slurm
243
+ Enter your tutorial login and upload **samples.json** from a full benchmark evaluation
244
+ (e.g. `$SCRATCH/pllum-slurm-lab/evaluation/samples.json`). Click **Submit** to score your run.
245
+ **Leaderboard** shows the best run per login; **Submissions** shows the 50 latest runs.
246
+ All accuracy values are percentages. For equal scores, the earliest run wins.
247
+ """, elem_id="intro")
248
+ with gr.Row():
249
+ login = gr.Textbox(label="Login", placeholder="tutorial001", info="tutorial001–tutorial033")
250
+ upload = gr.File(label="samples.json", file_types=[".json"], type="filepath")
251
+ send = gr.Button("Submit", variant="primary")
252
+ status = gr.Markdown(elem_id="status")
253
+ with gr.Accordion("How scoring works", open=False):
254
+ gr.Markdown("""Upload the full benchmark. A prediction is correct if it matches the reference within **1e-6**
255
+ and has no evaluator error. **Accuracy = correct / all questions**, overall and per category.
256
+
257
+ Each failed question receives one error type:
258
+
259
+ | Error type | Meaning |
260
+ | --- | --- |
261
+ | `wrong_answer` | A valid numerical prediction falls outside the tolerance. |
262
+ | `parsing_error` | The evaluator could not parse the response, or the prediction is not a finite number. |
263
+ | `tool_error` | An unknown tool, wrong arguments, or a failed calculator operation. |
264
+ | `call_budget_exceeded` | The model exceeded the allowed number of tool calls. |
265
+ | `context_limit` | The conversation exceeded the model context limit. |
266
+ | `missing_prediction` | No final prediction and no reported evaluator error. |
267
+ | `evaluation_error` | Another evaluator failure, including unrecognized error messages. |
268
+
269
+ Error types are inferred from the evaluator's error messages. A reported evaluator error takes precedence
270
+ over the prediction. Error columns show **counts of failed questions**, so correct + all error counts = total.
271
+ The saved `results.json` includes per-question outcomes, reference answers and absolute differences.
272
+ Both tabs show results for the current benchmark only.
273
+ """, elem_id="scoring")
274
+ with gr.Tabs():
275
+ with gr.Tab("Leaderboard"):
276
+ leaderboard_table = gr.Dataframe(interactive=False, label="Best result per login")
277
+ with gr.Tab("Submissions"):
278
+ submissions_table = gr.Dataframe(interactive=False, label="Latest submissions")
279
+ refresh = gr.Button("Refresh")
280
+ outputs = [submissions_table, leaderboard_table]
281
+ send.click(submit, inputs=[login, upload], outputs=[status, *outputs], concurrency_limit=1)
282
+ refresh.click(refresh_tables, outputs=outputs)
283
+ demo.load(refresh_tables, outputs=outputs)
284
+
285
+ if __name__ == "__main__":
286
+ demo.queue().launch(css=CSS)
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio==6.30.0
2
+ huggingface_hub>=1.0,<2
3
+ python-dotenv>=1.0,<2