aien-yardsticks
aien-dev/aien-yardsticks
Brought by drakestapleton
aien-yardsticks / yardsticks / mojollama-eval-runners / eval / orchestrator.py
| 1 | """Evaluation orchestrator — runs benchmarks and aggregates results. |
| 2 | |
| 3 | This module provides the main entry point for running evaluations against |
| 4 | a llama.cpp backend, either from the CLI or the REST API. |
| 5 | """ |
| 6 | |
| 7 | import json |
| 8 | import os |
| 9 | import sys |
| 10 | import time |
| 11 | import urllib.request |
| 12 | from typing import Optional |
| 13 | |
| 14 | from .base import BaseBenchmark, LlamaCppEvaluator, check_backend_alive, format_results |
| 15 | from .dataset import get_dataset_path, get_dataset_stream, get_subjects, list_available_datasets, DATASET_SOURCES |
| 16 | from .mmlu import MMLUBenchmark |
| 17 | from .gsm8k import GSM8KBenchmark |
| 18 | from .ceval import CEvalBenchmark |
| 19 | from .hellaswag import HellaSwagBenchmark |
| 20 | from .arc import ARCBenchmark |
| 21 | from .bbh import BBHBenchmark |
| 22 | from .humaneval import HumanEvalBenchmark |
| 23 | |
| 24 | |
| 25 | BENCHMARKS = { |
| 26 | "mmlu": MMLUBenchmark, |
| 27 | "gsm8k": GSM8KBenchmark, |
| 28 | "ceval": CEvalBenchmark, |
| 29 | "hellaswag": HellaSwagBenchmark, |
| 30 | "arc": ARCBenchmark, |
| 31 | "bbh": BBHBenchmark, |
| 32 | "humaneval": HumanEvalBenchmark, |
| 33 | } |
| 34 | |
| 35 | |
| 36 | def get_benchmark(name: str) -> Optional[BaseBenchmark]: |
| 37 | """Get benchmark instance by name.""" |
| 38 | cls = BENCHMARKS.get(name.lower()) |
| 39 | if cls: |
| 40 | return cls() |
| 41 | return None |
| 42 | |
| 43 | |
| 44 | def list_benchmarks() -> list: |
| 45 | """List available benchmarks with descriptions.""" |
| 46 | return [ |
| 47 | {"id": "mmlu", "name": "MMLU", "description": "57 subjects, 5-shot multiple choice"}, |
| 48 | {"id": "gsm8k", "name": "GSM8K", "description": "Grade school math, 8-shot CoT"}, |
| 49 | {"id": "ceval", "name": "CEval", "description": "Chinese evaluation, 52 subjects"}, |
| 50 | {"id": "hellaswag", "name": "HellaSwag", "description": "Commonsense reasoning"}, |
| 51 | {"id": "arc", "name": "ARC", "description": "AI2 Reasoning Challenge (Challenge + Easy)"}, |
| 52 | {"id": "bbh", "name": "BBH", "description": "Big-Bench Hard, 27 reasoning tasks"}, |
| 53 | {"id": "humaneval", "name": "HumanEval", "description": "Code generation (pass@1)"}, |
| 54 | ] |
| 55 | |
| 56 | |
| 57 | def run_benchmark(name: str, backend_url: str, model_name: str, |
| 58 | max_samples: int = 0, **kwargs) -> dict: |
| 59 | """Run a single benchmark. |
| 60 | |
| 61 | Args: |
| 62 | name: Benchmark name (mmlu, gsm8k, etc.) |
| 63 | backend_url: llama.cpp server URL |
| 64 | model_name: Model name/path for logging |
| 65 | max_samples: Max samples per subject (0 = all) |
| 66 | **kwargs: Passed to benchmark.run() |
| 67 | |
| 68 | Returns: |
| 69 | Result dict with accuracy, per_category, etc. |
| 70 | """ |
| 71 | bench = get_benchmark(name) |
| 72 | if not bench: |
| 73 | return {"name": name, "accuracy": 0, "correct": 0, "total": 0, |
| 74 | "error": f"Unknown benchmark: {name}"} |
| 75 | |
| 76 | print(f"\n{'─'*60}") |
| 77 | print(f" Running {bench.name} benchmark...") |
| 78 | print(f" Backend: {backend_url}") |
| 79 | print(f" Model: {model_name}") |
| 80 | if max_samples > 0: |
| 81 | print(f" Samples: {max_samples} per category") |
| 82 | print(f"{'─'*60}") |
| 83 | |
| 84 | return bench.run(backend_url, model_name, max_samples=max_samples, **kwargs) |
| 85 | |
| 86 | |
| 87 | def run_benchmarks(benchmarks: list, backend_url: str, model_name: str, |
| 88 | max_samples: int = 0) -> list: |
| 89 | """Run multiple benchmarks and return aggregated results.""" |
| 90 | results = [] |
| 91 | for name in benchmarks: |
| 92 | try: |
| 93 | result = run_benchmark(name, backend_url, model_name, max_samples) |
| 94 | results.append(result) |
| 95 | except Exception as e: |
| 96 | print(f"\n ❌ {name} benchmark failed: {e}") |
| 97 | results.append({ |
| 98 | "name": name, "accuracy": 0, "correct": 0, "total": 0, |
| 99 | "error": str(e) |
| 100 | }) |
| 101 | return results |
| 102 | |
| 103 | |
| 104 | def download_all_datasets(progress_callback=None) -> dict: |
| 105 | """Download all benchmark datasets. |
| 106 | |
| 107 | Returns: |
| 108 | {name: True/False} for each dataset |
| 109 | """ |
| 110 | results = {} |
| 111 | |
| 112 | # MMLU — one file per subject |
| 113 | subjects = get_subjects("mmlu") |
| 114 | print(f"\n Downloading MMLU ({len(subjects)} subjects)...") |
| 115 | mmlu_ok = 0 |
| 116 | for i, subj in enumerate(subjects): |
| 117 | path = get_dataset_path("mmlu", subj) |
| 118 | if path: |
| 119 | mmlu_ok += 1 |
| 120 | if progress_callback: |
| 121 | progress_callback("mmlu", i + 1, len(subjects)) |
| 122 | results["mmlu"] = mmlu_ok > 0 |
| 123 | print(f" → {mmlu_ok}/{len(subjects)} subjects cached") |
| 124 | |
| 125 | # GSM8K |
| 126 | print(" Downloading GSM8K...") |
| 127 | path = get_dataset_path("gsm8k") |
| 128 | results["gsm8k"] = path is not None |
| 129 | |
| 130 | # CEval |
| 131 | ceval_subjects = get_subjects("ceval") |
| 132 | print(f" Downloading CEval ({len(ceval_subjects)} subjects)...") |
| 133 | ceval_ok = 0 |
| 134 | for subj in ceval_subjects: |
| 135 | path = get_dataset_path("ceval", subj) |
| 136 | if path: |
| 137 | ceval_ok += 1 |
| 138 | results["ceval"] = ceval_ok > 0 |
| 139 | print(f" → {ceval_ok}/{len(ceval_subjects)} subjects cached") |
| 140 | |
| 141 | # HellaSwag |
| 142 | print(" Downloading HellaSwag...") |
| 143 | path = get_dataset_path("hellaswag") |
| 144 | results["hellaswag"] = path is not None |
| 145 | |
| 146 | # ARC — try specific file names |
| 147 | print(" Downloading ARC (Challenge + Easy)...") |
| 148 | arc_ok = False |
| 149 | for v in ["challenge", "easy"]: |
| 150 | for fname in [ |
| 151 | f"ARC-{v.capitalize()}-Test.jsonl", |
| 152 | f"arc_{v}_test.jsonl" |
| 153 | ]: |
| 154 | import os |
| 155 | dest = os.path.join(os.path.expanduser("~/.mojollama/eval_datasets"), fname) |
| 156 | url = DATASET_SOURCES["arc"].get(f"{v}_url", "") |
| 157 | if url: |
| 158 | from .dataset import _download_file |
| 159 | if _download_file(url, dest): |
| 160 | arc_ok = True |
| 161 | results["arc"] = arc_ok |
| 162 | |
| 163 | # BBH |
| 164 | print(" Downloading BBH (27 tasks)...") |
| 165 | bbh_tasks = list(DATASET_SOURCES.get("bbh", {}).get("url_templates", {}).keys()) |
| 166 | bbh_ok = 0 |
| 167 | for task in bbh_tasks: |
| 168 | path = get_dataset_path("bbh", task) |
| 169 | if path: |
| 170 | bbh_ok += 1 |
| 171 | results["bbh"] = bbh_ok > 0 |
| 172 | print(f" → {bbh_ok}/{len(bbh_tasks)} tasks cached") |
| 173 | |
| 174 | # HumanEval |
| 175 | print(" Downloading HumanEval...") |
| 176 | path = get_dataset_path("humaneval") |
| 177 | results["humaneval"] = path is not None |
| 178 | |
| 179 | print(f"\n {'─'*40}") |
| 180 | for name, ok in results.items(): |
| 181 | print(f" {name:20s} {'✅' if ok else '❌'}") |
| 182 | print(f" {'─'*40}") |
| 183 | |
| 184 | return results |
| 185 | |
| 186 | |
| 187 | def get_dataset_info() -> list: |
| 188 | """Get list of cached dataset info.""" |
| 189 | available = list_available_datasets() |
| 190 | info = [] |
| 191 | for name, data in available.items(): |
| 192 | info.append({ |
| 193 | "name": name, |
| 194 | "cached": True, |
| 195 | "size_bytes": data.get("size", 0), |
| 196 | "subjects": data.get("subjects", 0), |
| 197 | }) |
| 198 | return info |
| 199 | |
| 200 | |
| 201 | def serve_stream_results(results: list, wfile) -> None: |
| 202 | """Stream benchmark results line by line for the web UI. |
| 203 | |
| 204 | Each line is a JSON dict with a 'type' field: |
| 205 | - progress: {type:'progress', message:str} |
| 206 | - result: {type:'result', ...benchmark_result} |
| 207 | - done: {type:'done', summary:str} |
| 208 | """ |
| 209 | for r in results: |
| 210 | name = r.get("name", "?") |
| 211 | acc = r.get("accuracy", 0) * 100 |
| 212 | correct = r.get("correct", 0) |
| 213 | total = r.get("total", 0) |
| 214 | |
| 215 | wfile.write(json.dumps({ |
| 216 | "type": "progress", |
| 217 | "name": name, |
| 218 | "message": f"{name}: {acc:.2f}% ({correct}/{total})" |
| 219 | }).encode() + b"\n") |
| 220 | wfile.flush() |
| 221 | |
| 222 | wfile.write(json.dumps({ |
| 223 | "type": "result", |
| 224 | **r |
| 225 | }).encode() + b"\n") |
| 226 | wfile.flush() |
| 227 | |
| 228 | total_correct = sum(r.get("correct", 0) for r in results) |
| 229 | total_all = sum(r.get("total", 0) for r in results) |
| 230 | overall = total_correct / total_all * 100 if total_all > 0 else 0 |
| 231 | |
| 232 | wfile.write(json.dumps({ |
| 233 | "type": "done", |
| 234 | "overall_accuracy": overall, |
| 235 | "total_correct": total_correct, |
| 236 | "total_samples": total_all, |
| 237 | "benchmarks_run": len(results), |
| 238 | }).encode() + b"\n") |
| 239 | wfile.flush() |