aien-yardsticks
aien-dev/aien-yardsticks
Brought by drakestapleton
GitHub aien-dev/aien-yardsticks#10 (code only)
Apply it
git checkout -b patch-e3b17a850ea02045 0de4106bed6dd0733b8d10cba23920d93a3c4ea8 curl -fsSL https://interplane.io/drakestapleton/aien-yardsticks/patches/e3b17a850ea02045.patch | git am
Provenance
github-import 1
aien-dev/aien-yardsticks
10
99a4f06eade3d7d1e1d2861fd4c38b3ff0aea012
{"kind":"github-import","owner":"aien-dev","repo":"aien-yardsticks","number":10,"url":"https://github.com/aien-dev/aien-yardsticks/pull/10","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:39:54Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/HISTORICAL-PYTHON.md b/HISTORICAL-PYTHON.md index 37e8805..d3cdb30 100644 --- a/HISTORICAL-PYTHON.md +++ b/HISTORICAL-PYTHON.md @@ -1,6 +1,6 @@ # HISTORICAL — NOT PART OF ACTIVE AIEN EXECUTION -The nine Python files listed below are retained, byte for byte, as frozen historical evidence of two outside yardsticks (a Modular MAX Nemotron-H KV-head-expansion adapter and a TinyLlama reference-oracle generator). They are not part of any active AIEN build, qualification run, CI workflow, or runtime. +The Python files listed below (nine marked on 2026-10-09, eleven added on 2026-10-15) are retained, byte for byte, as frozen historical evidence of outside yardsticks (a Modular MAX Nemotron-H KV-head-expansion adapter, a TinyLlama reference-oracle generator and the MojoLlama accuracy eval runners). They are not part of any active AIEN build, qualification run, CI workflow, or runtime. ## Decision @@ -37,6 +37,24 @@ Resolved 2026-10-10: aien-sovereign-core#371 (main 885e42f, closes sc#369) remov `scripts/start_max_lightning_18006.sh` in aien-dev/aien-sovereign-core (and the home-directory copy that `crates/spark-cockpit-rs` launches on a "start"/"restart" of `max-server`) starts the outside Modular MAX server with `--custom-architectures .../aien-yardsticks/yardsticks/modular-nemotron-h-kvexp`. That loads this adapter's Python inside MAX, an outside yardstick server, not an AIEN-built component. This marking does not change that script. Whether the MAX launch is inside the "active trusted execution path" is an operator question and is reported separately. +## Added 2026-10-15: MojoLlama eval runners + +On 2026-10-15 AIEN dropped Mojo and MAX and aien-dev/MojoLlama was archived. Its accuracy eval runners are plain standard-library Python with no Mojo or MAX imports, so they were copied here byte for byte from `src/mojollama/eval/` at MojoLlama commit `cb281d1e8d906d5cf616c3116ef3d43eab29d6ba`. They are held under the same terms as the files above: historical evidence, not part of active AIEN execution, and reactivating them needs a separate task. + +| Path | SHA-256 | Git blob | +|---|---|---| +| `yardsticks/mojollama-eval-runners/eval/arc.py` | `e95e9664f750c313a3593947d288cdd3787f17ed215cd37ce87b8e0c12230865` | `97d0af16286b16cc473d7d474d0921fd41ed2a57` | +| `yardsticks/mojollama-eval-runners/eval/base.py` | `31a710e7c4307d5bec7df2a0e6643c31f8a460473357ecaac236beb17de104be` | `b08579e6cb4e4d8b129d9c50588916039b5fee96` | +| `yardsticks/mojollama-eval-runners/eval/bbh.py` | `f477e4e56bae6523b83cb41a514460b277efef22032c9c3b138bd14060bcfffb` | `b8093275167ef807a49dfc5e40bd45053d12b619` | +| `yardsticks/mojollama-eval-runners/eval/ceval.py` | `38c1fac7f3e768b739329c48fb89f5c71e67b00e4f6013a9487510652af4473d` | `dbf4cd338b04858c47020c5bfe4c27c5f08bffd6` | +| `yardsticks/mojollama-eval-runners/eval/dataset.py` | `fbca09a9b8f5019d185474894962ec8eafd181ac96b3973410bfd21820e0d1fc` | `28d1270d880ee3a041f549035388d8ad03de0230` | +| `yardsticks/mojollama-eval-runners/eval/gsm8k.py` | `904a0314d3afc72277ecfb3a9ecf1b2615b6a212281ab174cef1621fc3fba9b2` | `f8bea4f89eb55224273c607e027410dc4a49007f` | +| `yardsticks/mojollama-eval-runners/eval/hellaswag.py` | `97672bd091a7a3070a2f77e0fe08c0365dfdf633f2dd795dabe5b6ba1afbef40` | `d01e1bce542903ad74ab2cfbc360049374dafe8c` | +| `yardsticks/mojollama-eval-runners/eval/humaneval.py` | `5cb5be00798595782fc0a814c1c318c52e1c53ed017c9e816dc429bd8251b8ed` | `d4f81ba45e8a7106ea62157aaa30bfd6d04cf3ad` | +| `yardsticks/mojollama-eval-runners/eval/__init__.py` | `358906e04b113df64ff8e25bda8de365d71342b0ad3678fcf788d2e3ccbcf81a` | `8b98a3414bf60c87e224c6aa6731d0f4e0cde1c4` | +| `yardsticks/mojollama-eval-runners/eval/mmlu.py` | `9353bae67fb9255f4256ef000e447d62457e67393ea956b2ac80f695656f5690` | `8d6e5991264e1a85c0429e8334b122808987b2eb` | +| `yardsticks/mojollama-eval-runners/eval/orchestrator.py` | `83ec90920e6868432c300f81ae75e03a1d9c6a4679d494f4b5ea58fe9a940375` | `aab30a01aa7ef4b459f4fdc34ca6621a45fbb785` | + ## Rust replacement aien-yardsticks#2 proposes a Rust replacement. It is not done here. If it goes ahead it is a separate task with new evidence (item 6). diff --git a/README.md b/README.md index a32da82..14f234c 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # aien-yardsticks -Outside yardsticks AIEN is measured against. Today this repo holds a Modular MAX adapter, a Hugging Face Transformers reference oracle and a CUDA mirror of an AIEN kernel. There is no llama.cpp or vLLM yardstick here. Never part of AIEN. Nothing here ships in AIEN. +Outside yardsticks AIEN is measured against. Today this repo holds a Modular MAX adapter, a Hugging Face Transformers reference oracle, a CUDA mirror of an AIEN kernel and a frozen copy of the MojoLlama accuracy eval runners. There is no llama.cpp or vLLM yardstick here. Never part of AIEN. Nothing here ships in AIEN. Modular MAX and Mojo were removed from AIEN on 2026-10-15. The Modular MAX adapter below is kept only as a frozen record and is no longer run. @@ -9,5 +9,6 @@ Modular MAX and Mojo were removed from AIEN on 2026-10-15. The Modular MAX adapt | Modular MAX, Nemotron-H KV-head expansion (frozen record, no longer run) | `yardsticks/modular-nemotron-h-kvexp/` | | TinyLlama reference oracle (HF Transformers, CPU FP32) | `yardsticks/tinyllama-oracle/` | | CUDA mirror of the AIEN native prime sieve kernel (Prime Drag Race) | `yardsticks/prime-drag-race-cuda/` | +| MojoLlama accuracy eval runners (MMLU, GSM8K and others; frozen copy) | `yardsticks/mojollama-eval-runners/` | The Python here is retained as frozen historical evidence, not part of active AIEN execution, and is not scheduled for deletion. No Rust replacement has been built or is scheduled (the proposal, aien-yardsticks issue #2, was closed on 2026-10-09 in favour of keeping the Python as historical evidence). See [`HISTORICAL-PYTHON.md`](HISTORICAL-PYTHON.md). diff --git a/yardsticks/mojollama-eval-runners/.crumb b/yardsticks/mojollama-eval-runners/.crumb new file mode 100644 index 0000000..e5d2a9f --- /dev/null +++ b/yardsticks/mojollama-eval-runners/.crumb @@ -0,0 +1,20 @@ +{ + "schema_version": "1.0", + "dir_path": "./yardsticks/mojollama-eval-runners", + "purpose": { + "summary": "Frozen copy of the MojoLlama accuracy eval runners (MMLU, GSM8K, C-Eval, HellaSwag, ARC, BBH, HumanEval); outside AIEN, never linked into AIEN binaries", + "created_by": "AIEN", + "session_id": "cleanup-2026-10-15", + "created_at": "2026-10-15T00:00:00Z" + }, + "parent": { + "canonical": "./yardsticks", + "name": "yardsticks" + }, + "invariants": [ + "outside AIEN; never linked into AIEN binaries", + "files under eval/ are a byte-for-byte copy of aien-dev/MojoLlama src/mojollama/eval/ at cb281d1e8d906d5cf616c3116ef3d43eab29d6ba; do not edit in place", + "historical evidence under HISTORICAL-PYTHON.md; reactivating needs a separate task" + ], + "whispers": [] +} diff --git a/yardsticks/mojollama-eval-runners/README.md b/yardsticks/mojollama-eval-runners/README.md new file mode 100644 index 0000000..b10b4e3 --- /dev/null +++ b/yardsticks/mojollama-eval-runners/README.md @@ -0,0 +1,9 @@ +# MojoLlama eval runners (yardstick, frozen copy) + +Accuracy test runners from MojoLlama: MMLU, GSM8K, C-Eval, HellaSwag, ARC, BBH and HumanEval, plus the shared harness, dataset downloader and orchestrator. + +Source: copied from aien-dev/MojoLlama `src/mojollama/eval/` at commit cb281d1e8d906d5cf616c3116ef3d43eab29d6ba (plain byte-for-byte copy; history stays in that repo, which was archived on 2026-10-15 when AIEN dropped Mojo and MAX). + +These files are plain Python using only the standard library. They have no Mojo or MAX imports. They talk to a model server over HTTP (a llama.cpp-style completion endpoint) and keep downloaded datasets under `~/.mojollama/eval_datasets`. Some messages still name the old `mojollama-studio` command, which no longer exists here. + +This is a yardstick, not part of AIEN. Nothing here ships in AIEN or runs in AIEN's trusted path. Like the other Python in this repository it is kept as historical evidence (see [`HISTORICAL-PYTHON.md`](../../HISTORICAL-PYTHON.md)). diff --git a/yardsticks/mojollama-eval-runners/eval/__init__.py b/yardsticks/mojollama-eval-runners/eval/__init__.py new file mode 100644 index 0000000..8b98a34 --- /dev/null +++ b/yardsticks/mojollama-eval-runners/eval/__init__.py @@ -0,0 +1,5 @@ +"""MojoLlama Evaluation Framework — MMLU, GSM8K, CEval, HellaSwag, ARC, BBH, HumanEval.""" + +from . import base, dataset, mmlu, gsm8k, ceval, hellaswag, arc, bbh, humaneval + +__all__ = ["base", "dataset", "mmlu", "gsm8k", "ceval", "hellaswag", "arc", "bbh", "humaneval"] diff --git a/yardsticks/mojollama-eval-runners/eval/arc.py b/yardsticks/mojollama-eval-runners/eval/arc.py new file mode 100644 index 0000000..97d0af1 --- /dev/null +++ b/yardsticks/mojollama-eval-runners/eval/arc.py @@ -0,0 +1,189 @@ +"""ARC — AI2 Reasoning Challenge benchmark. + +Multiple choice science questions (Challenge and Easy sets). +Uses ai2_arc dataset. +""" + +import json +import re +import time +from typing import Optional + +from .base import BaseBenchmark, LlamaCppEvaluator, extract_letter_answer +from .dataset import get_dataset_path + + +FEW_SHOT_EXAMPLES = [ + { + "question": "Which of the following is an example of a chemical change?", + "choices": ["A. Ice melting", "B. Paper burning", "C. Water boiling", "D. Sugar dissolving"], + "answer": "B" + }, + { + "question": "What force keeps planets in orbit around the Sun?", + "choices": ["A. Magnetism", "B. Friction", "C. Gravity", "D. Electricity"], + "answer": "C" + }, + { + "question": "Which organ pumps blood through the human body?", + "choices": ["A. Lungs", "B. Liver", "C. Heart", "D. Brain"], + "answer": "C" + }, + { + "question": "What is the largest planet in our solar system?", + "choices": ["A. Mars", "B. Venus", "C. Saturn", "D. Jupiter"], + "answer": "D" + }, + { + "question": "Which of these is a renewable energy source?", + "choices": ["A. Coal", "B. Natural gas", "C. Solar power", "D. Oil"], + "answer": "C" + } +] + + +def _build_prompt(question, choices): + prompt_lines = [ + "The following are science questions (with answers).", + "" + ] + for ex in FEW_SHOT_EXAMPLES: + prompt_lines.append(ex["question"]) + for ch in ex["choices"]: + prompt_lines.append(ch) + prompt_lines.append(f"Answer: {ex['answer']}") + prompt_lines.append("") + + prompt_lines.append(question) + for ch in choices: + prompt_lines.append(ch) + prompt_lines.append("Answer:") + return "\n".join(prompt_lines) + + +def _load_arc_jsonl(path: str) -> list: + """Load ARC dataset from JSONL format.""" + records = [] + try: + with open(path, "r") as f: + for line in f: + line = line.strip() + if line: + records.append(json.loads(line)) + except Exception: + pass + return records + + +class ARCBenchmark(BaseBenchmark): + """ARC benchmark — AI2 Reasoning Challenge (Challenge + Easy).""" + + @property + def name(self) -> str: + return "ARC" + + def run(self, backend_url: str, model_name: str, + max_samples: int = 0, variant: str = "challenge", + **kwargs) -> dict: + evaluator = LlamaCppEvaluator(backend_url, temperature=0.0, max_tokens=32) + t0 = time.time() + + total_correct = 0 + total_all = 0 + per_category = {} + + variants_to_run = ["challenge", "easy"] if variant == "all" else [variant] + + for v in variants_to_run: + # Try multiple possible file names + possible = [ + get_dataset_path("arc", subject=f"ARC-{v.capitalize()}-Test"), + None + ] + import os + base = os.path.expanduser("~/.mojollama/eval_datasets") + for fname in [ + f"ARC-{v.capitalize()}-Test.jsonl", + f"arc_{v}_test.jsonl", + f"ARC-{v.capitalize()}-Test.json" + ]: + p = os.path.join(base, fname) + if os.path.exists(p): + possible.append(p) + + records = [] + for p in possible: + if p and os.path.exists(p): + records = _load_arc_jsonl(p) + if records: + break + + if not records: + print(f" ⚠ ARC-{v.capitalize()} data not found, download first: mojollama-studio evaluate download") + per_category[f"arc_{v}"] = {"correct": 0, "total": 0, "accuracy": 0} + continue + + if max_samples > 0: + records = records[:max_samples] + + correct = 0 + total = 0 + labels = ["A", "B", "C", "D"] + + for record in records: + question = record.get("question", "") + choices_raw = record.get("choices", {}) + answer_key = record.get("answerKey", "") + + # Handle different ARC formats + if isinstance(choices_raw, dict): + choice_labels = choices_raw.get("label", []) + choice_texts = choices_raw.get("text", []) + choices = [f"{l}. {t}" for l, t in zip(choice_labels, choice_texts)] + elif isinstance(choices_raw, list): + choices = [] + for i, c in enumerate(choices_raw): + if isinstance(c, dict): + label = c.get("label", labels[i] if i < len(labels) else chr(65+i)) + text = c.get("text", str(c)) + choices.append(f"{label}. {text}") + else: + choices.append(f"{labels[i]}. {c}") + else: + continue + + prompt = _build_prompt(question, choices) + + try: + generated = evaluator.complete(prompt, max_tokens=16) + predicted = extract_letter_answer(generated) + if predicted is None: + m = re.search(r'\b([A-D])\b', generated) + if m: + predicted = m.group(1) + if predicted and predicted == answer_key: + correct += 1 + except Exception: + pass + + total += 1 + + acc = correct / total if total > 0 else 0 + per_category[f"arc_{v}"] = {"correct": correct, "total": total, "accuracy": acc} + total_correct += correct + total_all += total + print(f" ARC-{v.capitalize()}: {acc*100:.2f}% ({correct}/{total})") + + elapsed = time.time() - t0 + stats = evaluator.get_stats() + overall_acc = total_correct / total_all if total_all > 0 else 0 + + return { + "name": "ARC", + "accuracy": overall_acc, + "correct": total_correct, + "total": total_all, + "per_category": per_category, + "metrics": {"elapsed": elapsed, "api_calls": stats["api_calls"], "api_errors": stats["api_errors"]}, + "samples": total_all + } diff --git a/yardsticks/mojollama-eval-runners/eval/base.py b/yardsticks/mojollama-eval-runners/eval/base.py new file mode 100644 index 0000000..b08579e --- /dev/null +++ b/yardsticks/mojollama-eval-runners/eval/base.py @@ -0,0 +1,208 @@ +"""Base evaluation harness for MojoLlama benchmarks. + +Defines the abstract interface for all benchmarks and the core evaluation +loop that interacts with llama.cpp server or any backend. +""" + +import json +import os +import re +import time +import sys +import urllib.request +import urllib.error +from abc import ABC, abstractmethod +from typing import Optional + + +class BaseBenchmark(ABC): + """Abstract base for all benchmarks. + + Subclasses must implement: + - name: str — benchmark name + - run(self, backend_url, model_name, **kwargs) -> dict — execute evaluation + + The run() method returns: + { + 'name': str, + 'accuracy': float, # 0.0 to 1.0 + 'correct': int, + 'total': int, + 'per_category': {category: {correct: int, total: int, accuracy: float}}, + 'metrics': {...}, # additional metrics + 'samples': int + } + """ + + @property + @abstractmethod + def name(self) -> str: + ... + + @abstractmethod + def run(self, backend_url: str, model_name: str, + max_samples: int = 0, **kwargs) -> dict: + ... + + +class LlamaCppEvaluator: + """Core evaluator that calls llama.cpp server API for completions.""" + + def __init__(self, backend_url: str = "http://127.0.0.1:8081", + temperature: float = 0.0, max_tokens: int = 256, + timeout: int = 60): + self.backend_url = backend_url.rstrip("/") + self.temperature = temperature + self.max_tokens = max_tokens + self.timeout = timeout + self._stats = {"api_calls": 0, "total_tokens": 0, "api_errors": 0} + + def complete(self, prompt: str, max_tokens: Optional[int] = None, + temperature: Optional[float] = None, + stop: Optional[list] = None) -> str: + """Send a completion request and return the generated text.""" + data = { + "prompt": prompt, + "n_predict": max_tokens or self.max_tokens, + "temperature": temperature if temperature is not None else self.temperature, + "stream": False, + } + if stop: + data["stop"] = stop + + req = urllib.request.Request( + f"{self.backend_url}/completion", + data=json.dumps(data).encode(), + headers={"Content-Type": "application/json"}, + method="POST" + ) + self._stats["api_calls"] += 1 + try: + with urllib.request.urlopen(req, timeout=self.timeout) as resp: + result = json.loads(resp.read().decode("utf-8")) + text = result.get("content", "") + tokens = result.get("tokens", 0) or result.get("tokens_evaluated", 0) + self._stats["total_tokens"] += tokens + return text + except Exception as e: + self._stats["api_errors"] += 1 + raise RuntimeError(f"API call failed: {e}") + + def chat_complete(self, messages: list, max_tokens: Optional[int] = None, + temperature: Optional[float] = None) -> str: + """Send a chat completion request and return the response text.""" + data = { + "messages": messages, + "max_tokens": max_tokens or self.max_tokens, + "temperature": temperature if temperature is not None else self.temperature, + "stream": False, + } + + req = urllib.request.Request( + f"{self.backend_url}/v1/chat/completions", + data=json.dumps(data).encode(), + headers={"Content-Type": "application/json"}, + method="POST" + ) + self._stats["api_calls"] += 1 + try: + with urllib.request.urlopen(req, timeout=self.timeout) as resp: + result = json.loads(resp.read().decode("utf-8")) + text = result.get("choices", [{}])[0].get("message", {}).get("content", "") + usage = result.get("usage", {}) + self._stats["total_tokens"] += usage.get("total_tokens", 0) + return text + except Exception as e: + self._stats["api_errors"] += 1 + raise RuntimeError(f"Chat API call failed: {e}") + + def get_stats(self) -> dict: + """Return evaluation statistics.""" + return dict(self._stats) + + +def normalize_answer(answer: str) -> str: + """Normalize answer for exact match comparison.""" + answer = answer.strip().lower() + # Remove punctuation except period (for single letters) + answer = answer.strip(".,;:!?\"'()[]{}") + answer = answer.strip() + return answer + + +def extract_letter_answer(text: str) -> Optional[str]: + """Extract letter answer (A, B, C, D) from generated text.""" + text = text.strip() + # Look for patterns like "Answer: A", "The answer is B", "A." + patterns = [ + r'(?:^|\n)\s*(?:answer|the answer is|so the answer is|correct answer is|option|choice|answer:\s*)\s*[:\s]*([A-D])\b', + r'(?:^|\n)\s*([A-D])\s*[.:)]?\s*(?:$|\n)', + r'\(([A-D])\)', + r'\b([A-D])\s*(?:is correct|is the answer|is right)\b', + ] + for pat in patterns: + m = re.search(pat, text, re.IGNORECASE) + if m: + return m.group(1).upper() + return None + + +def extract_number_answer(text: str) -> Optional[str]: + """Extract numeric answer from generated text (for GSM8K).""" + text = text.strip() + # Look for patterns like "#### 42", "Answer: 42", final number + patterns = [ + r'####\s*(-?\d+(?:[,\.]\d+)?)', + r'(?:answer|the answer is|result|so the answer is)\s*[:\s]*(-?\d+(?:[,\.]\d+)?)', + r'(?:^|\n)\s*(-?\d+(?:[,\.]\d+)?)\s*(?:$|\n)', + ] + for pat in patterns: + m = re.search(pat, text, re.IGNORECASE) + if m: + return m.group(1).replace(",", "") + return None + + +def check_backend_alive(url: str) -> bool: + """Check if a llama.cpp backend is running.""" + try: + req = urllib.request.Request(f"{url}/health") + with urllib.request.urlopen(req, timeout=5) as resp: + return resp.status == 200 + except Exception: + return False + + +def format_results(results: list) -> str: + """Format benchmark results for display.""" + lines = [] + total_correct = sum(r["correct"] for r in results) + total_all = sum(r["total"] for r in results) + overall_acc = total_correct / total_all if total_all > 0 else 0 + + lines.append(f"{'═'*60}") + lines.append(f" Overall Accuracy: {overall_acc*100:.2f}% ({total_correct}/{total_all})") + lines.append(f"{'═'*60}") + + for r in results: + acc = r["correct"] / r["total"] if r["total"] > 0 else 0 + lines.append(f" {r['name']:30s} {acc*100:6.2f}% ({r['correct']:4d}/{r['total']:<4d})") + + per_cat = r.get("per_category", {}) + if per_cat: + for cat, stats in sorted(per_cat.items()): + cat_acc = stats["correct"] / stats["total"] if stats["total"] > 0 else 0 + lines.append(f" ├─ {cat:40s} {cat_acc*100:6.2f}% ({stats['correct']}/{stats['total']})") + + lines.append(f"{'═'*60}") + metrics = {} + for r in results: + if "metrics" in r: + for k, v in r["metrics"].items(): + metrics[k] = metrics.get(k, 0) + (v if isinstance(v, (int, float)) else 0) + if metrics: + lines.append(f" Runtime: {metrics.get('elapsed', 0):.1f}s, " + f"API calls: {metrics.get('api_calls', 0)}, " + f"Errors: {metrics.get('api_errors', 0)}") + + return "\n".join(lines) diff --git a/yardsticks/mojollama-eval-runners/eval/bbh.py b/yardsticks/mojollama-eval-runners/eval/bbh.py new file mode 100644 index 0000000..b809327 --- /dev/null +++ b/yardsticks/mojollama-eval-runners/eval/bbh.py @@ -0,0 +1,128 @@ +"""BBH — Big-Bench Hard benchmark. + +27 challenging reasoning tasks (subset of BIG-Bench). +Few-shot CoT evaluation. +""" + +import json +import re +import time +from typing import Optional + +from .base import BaseBenchmark, LlamaCppEvaluator, normalize_answer +from .dataset import get_dataset_stream, DATASET_SOURCES + + +# Example for each BBH task +TASK_EXAMPLES = { + "boolean_expressions": { + "ex": "Question: (not True or False) and (True or False)\nAnswer: Let's think step by step. (not True) is False. (False or False) is False. (True or False) is True. False and True is False. So the answer is False.\nTherefore, the answer is False.", + }, + "causal_judgment": { + "ex": "Question: ...\nAnswer: Let's think step by step. ... Therefore, the answer is No.", + }, +} + + +def _build_bbh_prompt(task_name: str, question: str, cot: bool = True) -> str: + """Build BBH prompt with optional chain-of-thought.""" + examples = TASK_EXAMPLES.get(task_name, {}) + + if cot and examples: + prompt = f"{examples['ex']}\n\nQuestion: {question}\nAnswer: Let's think step by step." + else: + prompt = f"Question: {question}\nAnswer:" + return prompt + + +def _extract_bbh_answer(text: str) -> str: + """Extract final answer from BBH output.""" + text = text.strip() + # Look for "the answer is X" patterns + patterns = [ + r'(?:answer is|so the answer is|therefore,?\s*(?:the\s+)?answer\s+is)\s*[:.]?\s*["\']?(\w+)["\']?', + r'(?:^|\n)\s*answer\s*:\s*["\']?(\w+)["\']?', + r'(\w+)\s*$', + ] + for pat in patterns: + m = re.search(pat, text, re.IGNORECASE) + if m: + return m.group(1).strip().strip('.,;:!?') + # Last word as fallback + words = text.split() + return words[-1].strip('.,;:!?') if words else "" + + +class BBHBenchmark(BaseBenchmark): + """BBH — Big-Bench Hard, 27 challenging reasoning tasks.""" + + @property + def name(self) -> str: + return "BBH" + + @property + def tasks(self) -> list: + return list(DATASET_SOURCES.get("bbh", {}).get("url_templates", {}).keys()) + + def run(self, backend_url: str, model_name: str, + max_samples: int = 0, tasks: Optional[list] = None, + use_cot: bool = True, + **kwargs) -> dict: + evaluator = LlamaCppEvaluator(backend_url, temperature=0.0, max_tokens=256) + t0 = time.time() + + all_tasks = tasks or self.tasks + per_category = {} + total_correct = 0 + total_all = 0 + + for task_name in all_tasks: + records = get_dataset_stream("bbh", task_name) + if not records: + print(f" ⚠ No data for {task_name}, skipping") + per_category[task_name] = {"correct": 0, "total": 0, "accuracy": 0} + continue + + if max_samples > 0: + records = records[:max_samples] + + task_correct = 0 + task_total = 0 + + for record in records: + question = record.get("input", record.get("question", "")) + target = record.get("target", record.get("answer", "")) + + prompt = _build_bbh_prompt(task_name, question, use_cot) + + try: + max_tok = 128 if not use_cot else 256 + generated = evaluator.complete(prompt, max_tokens=max_tok) + predicted = _extract_bbh_answer(generated) + if normalize_answer(predicted) == normalize_answer(target): + task_correct += 1 + except Exception: + pass + + task_total += 1 + + acc = task_correct / task_total if task_total > 0 else 0 + per_category[task_name] = {"correct": task_correct, "total": task_total, "accuracy": acc} + total_correct += task_correct + total_all += task_total + print(f" {task_name:40s} {acc*100:6.2f}% ({task_correct}/{task_total})") + + elapsed = time.time() - t0 + stats = evaluator.get_stats() + overall_acc = total_correct / total_all if total_all > 0 else 0 + + return { + "name": "BBH", + "accuracy": overall_acc, + "correct": total_correct, + "total": total_all, + "per_category": per_category, + "metrics": {"elapsed": elapsed, "api_calls": stats["api_calls"], "api_errors": stats["api_errors"], + "tasks_evaluated": len([t for t in per_category if per_category[t]["total"] > 0])}, + "samples": total_all + } diff --git a/yardsticks/mojollama-eval-runners/eval/ceval.py b/yardsticks/mojollama-eval-runners/eval/ceval.py new file mode 100644 index 0000000..dbf4cd3 --- /dev/null +++ b/yardsticks/mojollama-eval-runners/eval/ceval.py @@ -0,0 +1,159 @@ +"""CEval — Chinese Evaluation benchmark. + +52 subjects, multiple choice evaluation in Chinese. +Uses ceval/ceval-exam dataset format. +""" + +import json +import re +import time +from typing import Optional + +from .base import BaseBenchmark, LlamaCppEvaluator, extract_letter_answer +from .dataset import get_dataset_stream, get_subjects + + +# Few-shot examples for CEval +CEVAL_FEW_SHOT = [ + { + "question": "中国的首都是哪个城市?", + "choices": ["A. 上海", "B. 北京", "C. 广州", "D. 深圳"], + "answer": "B" + }, + { + "question": "太阳从哪个方向升起?", + "choices": ["A. 西方", "B. 南方", "C. 北方", "D. 东方"], + "answer": "D" + }, + { + "question": "一年有多少个月?", + "choices": ["A. 10个月", "B. 11个月", "C. 12个月", "D. 13个月"], + "answer": "C" + }, + { + "question": "以下哪个是中国的四大发明?", + "choices": ["A. 造纸术", "B. 蒸汽机", "C. 电灯", "D. 手机"], + "answer": "A" + }, + { + "question": "水的化学式是什么?", + "choices": ["A. CO2", "B. H2O", "C. NaCl", "D. O2"], + "answer": "B" + } +] + + +def _build_ceval_prompt(question, choices, few_shot=None): + """Build a CEval prompt in Chinese with few-shot examples.""" + if few_shot is None: + few_shot = CEVAL_FEW_SHOT + + prompt_lines = [ + "以下是选择题(请选择正确的答案)。", + "" + ] + for ex in few_shot: + prompt_lines.append(ex["question"]) + for ch in ex["choices"]: + prompt_lines.append(ch) + prompt_lines.append(f"答案: {ex['answer']}") + prompt_lines.append("") + + prompt_lines.append(question) + for ch in choices: + prompt_lines.append(ch) + prompt_lines.append("答案:") + + return "\n".join(prompt_lines) + + +class CEvalBenchmark(BaseBenchmark): + """CEval benchmark — 52 subjects, Chinese multiple choice.""" + + @property + def name(self) -> str: + return "CEval" + + def run(self, backend_url: str, model_name: str, + max_samples: int = 0, subjects: Optional[list] = None, + **kwargs) -> dict: + evaluator = LlamaCppEvaluator(backend_url, temperature=0.0, max_tokens=50) + t0 = time.time() + + all_subjects = subjects or get_subjects("ceval") + per_category = {} + total_correct = 0 + total_all = 0 + + for subject in all_subjects: + records = get_dataset_stream("ceval", subject) + if not records: + print(f" ⚠ No data for {subject}, skipping") + continue + + if max_samples > 0: + records = records[:max_samples] + + subject_correct = 0 + subject_total = 0 + + for record in records: + question = record.get("question", "") + choices = record.get("choices", []) + answer_idx = record.get("answer", -1) + + labels = ["A", "B", "C", "D"] + answer_letter = labels[answer_idx] if 0 <= answer_idx < len(labels) else None + if answer_letter is None: + continue + + formatted_choices = [ + f"{labels[i]}. {choices[i]}" + for i in range(len(choices)) + ] + + prompt = _build_ceval_prompt(question, formatted_choices) + + try: + generated = evaluator.complete(prompt, max_tokens=32) + predicted = extract_letter_answer(generated) + if predicted is None: + m = re.search(r'\b([A-D])\b', generated) + if m: + predicted = m.group(1) + if predicted == answer_letter: + subject_correct += 1 + except Exception as e: + pass + + subject_total += 1 + + per_category[subject] = { + "correct": subject_correct, + "total": subject_total, + "accuracy": subject_correct / subject_total if subject_total > 0 else 0 + } + total_correct += subject_correct + total_all += subject_total + + pct = (subject_correct / subject_total * 100) if subject_total > 0 else 0 + print(f" {subject:40s} {pct:6.2f}% ({subject_correct}/{subject_total})") + + elapsed = time.time() - t0 + stats = evaluator.get_stats() + + return { + "name": "CEval", + "accuracy": total_correct / total_all if total_all > 0 else 0, + "correct": total_correct, + "total": total_all, + "per_category": per_category, + "metrics": { + "elapsed": elapsed, + "api_calls": stats["api_calls"], + "api_errors": stats["api_errors"], + "total_tokens": stats["total_tokens"], + "subjects_evaluated": len([s for s in per_category if per_category[s]["total"] > 0]) + }, + "samples": total_all + } diff --git a/yardsticks/mojollama-eval-runners/eval/dataset.py b/yardsticks/mojollama-eval-runners/eval/dataset.py new file mode 100644 index 0000000..28d1270 --- /dev/null +++ b/yardsticks/mojollama-eval-runners/eval/dataset.py @@ -0,0 +1,242 @@ +"""Dataset downloader — Caches evaluation datasets locally. + +Downloads from Hugging Face datasets or mirrors. Supports MMLU, GSM8K, +CEval, HellaSwag, ARC, BBH, HumanEval. +""" + +import json +import os +import urllib.request +import urllib.error +import gzip +import shutil +import hashlib +import re +from pathlib import Path +from typing import Optional + +CACHE_DIR = os.path.expanduser("~/.mojollama/eval_datasets") +os.makedirs(CACHE_DIR, exist_ok=True) + +DATASET_SOURCES = { + "mmlu": { + "url": "https://huggingface.co/datasets/lukaemon/mmlu/resolve/main/data/{subject}_test.json", + "fallback_url": "https://huggingface.co/datasets/lukaemon/mmlu/raw/main/data/{subject}_test.json", + "subjects": [ + "abstract_algebra", "anatomy", "astronomy", "business_ethics", + "clinical_knowledge", "college_biology", "college_chemistry", + "college_computer_science", "college_mathematics", "college_medicine", + "college_physics", "computer_security", "conceptual_physics", + "econometrics", "electrical_engineering", "elementary_mathematics", + "formal_logic", "global_facts", "high_school_biology", + "high_school_chemistry", "high_school_computer_science", + "high_school_european_history", "high_school_geography", + "high_school_government_and_politics", "high_school_macroeconomics", + "high_school_mathematics", "high_school_microeconomics", + "high_school_physics", "high_school_psychology", + "high_school_statistics", "high_school_us_history", + "high_school_world_history", "human_aging", "human_sexuality", + "international_law", "jurisprudence", "logical_fallacies", + "machine_learning", "management", "marketing", "medical_genetics", + "miscellaneous", "moral_disputes", "moral_scenarios", + "nutrition", "philosophy", "prehistory", "professional_accounting", + "professional_law", "professional_medicine", "professional_psychology", + "public_relations", "security_studies", "sociology", + "us_foreign_policy", "virology", "world_religions" + ] + }, + "gsm8k": { + "url": "https://huggingface.co/datasets/openai/gsm8k/resolve/main/data/test.jsonl", + "fallback_url": "https://huggingface.co/datasets/openai/gsm8k/raw/main/data/test.jsonl" + }, + "ceval": { + "url": "https://huggingface.co/datasets/ceval/ceval-exam/resolve/main/data/{subject}_test.json", + "subjects": [ + "accountant", "advanced_mathematics", "art_studies", "basic_medicine", + "business_administration", "chinese_language_and_literature", + "college_chemistry", "college_physics", "computer_network", + "computer_organization_and_architecture", "criminal_law", "criminal_procedure_law", + "discrete_mathematics", "education_science", "electrical_engineer", + "environmental_impact_assessment_engineer", "fire_fighting", + "high_school_biology", "high_school_chemistry", "high_school_chinese", + "high_school_geography", "high_school_history", "high_school_mathematics", + "high_school_physics", "high_school_politics", "ideological_and_moral_cultivation", + "internet_information_service_engineer", "law", "lawyer_qualification", + "legal_professional", "legal_system_and_legal_institutions", + "logistics_engineering_and_management", "mao_zedong_thought", + "marxism", "metrology_engineer", "middle_school_biology", + "middle_school_chemistry", "middle_school_geography", "middle_school_history", + "middle_school_mathematics", "middle_school_physics", "middle_school_politics", + "modern_chinese_history", "operating_system", "pharmacy", + "principles_of_computer_composition", "probability_and_statistics", + "professional_geography_of_civil_engineering", "professional_knowledge_of_civil_engineering", + "sports_training", "tax_law_agent", "teacher_qualification", + "tour_guide", "urban_and_rural_planning", "veterinary_medicine", + "water_resources", "writer" + ] + }, + "hellaswag": { + "url": "https://huggingface.co/datasets/rowan/hellaswag/resolve/main/data/hellaswag_test.jsonl", + "fallback_url": "https://huggingface.co/datasets/rowan/hellaswag/raw/main/data/hellaswag_test.jsonl" + }, + "arc": { + "challenge_url": "https://huggingface.co/datasets/ai2_arc/resolve/main/data/ARC-Challenge-Test.jsonl", + "easy_url": "https://huggingface.co/datasets/ai2_arc/resolve/main/data/ARC-Easy-Test.jsonl", + "challenge_fallback": "https://huggingface.co/datasets/ai2_arc/raw/main/data/ARC-Challenge-Test.jsonl", + "easy_fallback": "https://huggingface.co/datasets/ai2_arc/raw/main/data/ARC-Easy-Test.jsonl" + }, + "bbh": { + "url_templates": { + "boolean_expressions": "https://huggingface.co/datasets/lukaemon/bbh/resolve/main/data/boolean_expressions/test.jsonl", + "causal_judgment": "https://huggingface.co/datasets/lukaemon/bbh/resolve/main/data/causal_judgment/test.jsonl", + "date_understanding": "https://huggingface.co/datasets/lukaemon/bbh/resolve/main/data/date_understanding/test.jsonl", + "disambiguation_qa": "https://huggingface.co/datasets/lukaemon/bbh/resolve/main/data/disambiguation_qa/test.jsonl", + "dyck_languages": "https://huggingface.co/datasets/lukaemon/bbh/resolve/main/data/dyck_languages/test.jsonl", + "formal_fallacies": "https://huggingface.co/datasets/lukaemon/bbh/resolve/main/data/formal_fallacies/test.jsonl", + "geometric_shapes": "https://huggingface.co/datasets/lukaemon/bbh/resolve/main/data/geometric_shapes/test.jsonl", + "hyperbaton": "https://huggingface.co/datasets/lukaemon/bbh/resolve/main/data/hyperbaton/test.jsonl", + "logical_deduction_five_objects": "https://huggingface.co/datasets/lukaemon/bbh/resolve/main/data/logical_deduction_five_objects/test.jsonl", + "logical_deduction_seven_objects": "https://huggingface.co/datasets/lukaemon/bbh/resolve/main/data/logical_deduction_seven_objects/test.jsonl", + "logical_deduction_three_objects": "https://huggingface.co/datasets/lukaemon/bbh/resolve/main/data/logical_deduction_three_objects/test.jsonl", + "movie_recommendation": "https://huggingface.co/datasets/lukaemon/bbh/resolve/main/data/movie_recommendation/test.jsonl", + "multistep_arithmetic_two": "https://huggingface.co/datasets/lukaemon/bbh/resolve/main/data/multistep_arithmetic_two/test.jsonl", + "navigate": "https://huggingface.co/datasets/lukaemon/bbh/resolve/main/data/navigate/test.jsonl", + "object_counting": "https://huggingface.co/datasets/lukaemon/bbh/resolve/main/data/object_counting/test.jsonl", + "penguins_in_a_table": "https://huggingface.co/datasets/lukaemon/bbh/resolve/main/data/penguins_in_a_table/test.jsonl", + "reasoning_about_colored_objects": "https://huggingface.co/datasets/lukaemon/bbh/resolve/main/data/reasoning_about_colored_objects/test.jsonl", + "ruin_names": "https://huggingface.co/datasets/lukaemon/bbh/resolve/main/data/ruin_names/test.jsonl", + "salient_translation_error_detection": "https://huggingface.co/datasets/lukaemon/bbh/resolve/main/data/salient_translation_error_detection/test.jsonl", + "snarks": "https://huggingface.co/datasets/lukaemon/bbh/resolve/main/data/snarks/test.jsonl", + "sports_understanding": "https://huggingface.co/datasets/lukaemon/bbh/resolve/main/data/sports_understanding/test.jsonl", + "temporal_sequences": "https://huggingface.co/datasets/lukaemon/bbh/resolve/main/data/temporal_sequences/test.jsonl", + "tracking_shuffled_objects_five_objects": "https://huggingface.co/datasets/lukaemon/bbh/resolve/main/data/tracking_shuffled_objects_five_objects/test.jsonl", + "tracking_shuffled_objects_seven_objects": "https://huggingface.co/datasets/lukaemon/bbh/resolve/main/data/tracking_shuffled_objects_seven_objects/test.jsonl", + "tracking_shuffled_objects_three_objects": "https://huggingface.co/datasets/lukaemon/bbh/resolve/main/data/tracking_shuffled_objects_three_objects/test.jsonl", + "web_of_lies": "https://huggingface.co/datasets/lukaemon/bbh/resolve/main/data/web_of_lies/test.jsonl", + } + }, + "humaneval": { + "url": "https://huggingface.co/datasets/openai/openai_humaneval/resolve/main/data/test.jsonl", + "fallback_url": "https://huggingface.co/datasets/openai/openai_humaneval/raw/main/data/test.jsonl" + } +} + +# Embedded mini test data for benchmarks that don't need full download +EMBEDDED_SAMPLES = {} + + +def _download_file(url: str, dest: str) -> bool: + """Download a file with progress. Returns True on success.""" + try: + print(f" Downloading {url}...") + urllib.request.urlretrieve(url, dest) + return True + except Exception as e: + print(f" Download failed: {e}") + return False + + +def get_dataset_path(name: str, subject: Optional[str] = None, force_download: bool = False) -> Optional[str]: + """Get cached path for a dataset. Downloads if needed. + + Args: + name: Dataset name (mmlu, gsm8k, ceval, hellaswag, arc, bbh, humaneval) + subject: Subject name for multi-subject datasets (mmlu, ceval) + force_download: Re-download even if cached + + Returns: + Path to cached file, or None if download failed + """ + source = DATASET_SOURCES.get(name) + if not source: + return None + + if subject: + cache_file = os.path.join(CACHE_DIR, name, f"{subject}.json") + os.makedirs(os.path.join(CACHE_DIR, name), exist_ok=True) + else: + cache_file = os.path.join(CACHE_DIR, f"{name}.jsonl") + os.makedirs(CACHE_DIR, exist_ok=True) + + if os.path.exists(cache_file) and not force_download: + return cache_file + + # Build URL + if subject: + url = source.get("url", "").replace("{subject}", subject) + fallback = source.get("fallback_url", "").replace("{subject}", subject) + else: + url = source.get("url", "") + fallback = source.get("fallback_url", "") + + if not url: + return None + + if _download_file(url, cache_file): + return cache_file + if fallback and _download_file(fallback, cache_file): + return cache_file + + return None + + +def get_dataset_stream(name: str, subject: Optional[str] = None): + """Get a stream of JSON records for a dataset. + + Usage: for record in get_dataset_stream('gsm8k'): + question = record['question'] + + Returns an iterable of parsed JSON dicts, or empty list on failure. + """ + path = get_dataset_path(name, subject) + if not path: + return [] + + records = [] + try: + with open(path, "r") as f: + for line in f: + line = line.strip() + if line: + records.append(json.loads(line)) + except json.JSONDecodeError: + # Try as JSON array + try: + with open(path, "r") as f: + data = json.load(f) + if isinstance(data, list): + records = data + except Exception: + pass + except Exception: + pass + + return records + + +def get_subjects(name: str) -> list: + """Get list of subjects for multi-subject datasets.""" + source = DATASET_SOURCES.get(name, {}) + return source.get("subjects", []) + + +def list_available_datasets() -> dict: + """List which datasets are already cached.""" + available = {} + for name in DATASET_SOURCES: + path = os.path.join(CACHE_DIR, f"{name}.jsonl") + if os.path.exists(path): + available[name] = { + "path": path, + "size": os.path.getsize(path) + } + else: + subj_dir = os.path.join(CACHE_DIR, name) + if os.path.isdir(subj_dir): + files = os.listdir(subj_dir) + available[name] = { + "path": subj_dir, + "subjects": len(files), + "size": sum(os.path.getsize(os.path.join(subj_dir, f)) for f in files if os.path.isfile(os.path.join(subj_dir, f))) + } + return available diff --git a/yardsticks/mojollama-eval-runners/eval/gsm8k.py b/yardsticks/mojollama-eval-runners/eval/gsm8k.py new file mode 100644 index 0000000..f8bea4f --- /dev/null +++ b/yardsticks/mojollama-eval-runners/eval/gsm8k.py @@ -0,0 +1,163 @@ +"""GSM8K — Grade School Math benchmark. + +8-shot chain-of-thought evaluation. Exact match accuracy on final answer. +Uses openai/gsm8k dataset. +""" + +import json +import re +import time +from typing import Optional + +from .base import BaseBenchmark, LlamaCppEvaluator, extract_number_answer, normalize_answer +from .dataset import get_dataset_stream + + +# 8-shot CoT examples for GSM8K +COT_EXAMPLES = [ + { + "question": "Beth has 4 bags of marbles. Each bag has 24 marbles. She gives away 3 marbles. How many marbles does she have left?", + "answer": "Beth has 4 bags * 24 marbles = 96 marbles total. She gives away 3, so she has 96 - 3 = 93 marbles. #### 93" + }, + { + "question": "Janet's ducks lay 16 eggs per day. She eats three for breakfast every morning and bakes muffins with four every day. She sells the rest at the farmers' market daily for $2 per fresh egg. How much in dollars does she make every day at the farmers' market?", + "answer": "She uses 3 + 4 = 7 eggs each day. She has 16 - 7 = 9 eggs left. She makes 9 * $2 = $18 each day. #### 18" + }, + { + "question": "A robe takes 2 1/4 yards of material and a jacket takes 4 3/4 yards of material. How much more material does a jacket require than a robe?", + "answer": "4 3/4 - 2 1/4 = 2 1/2. The jacket requires 2 1/2 yards more. #### 2.5" + }, + { + "question": "There are 15 trees in the grove. Grove workers will plant trees in the grove today. After they are done, there will be 21 trees. How many trees did the grove workers plant today?", + "answer": "There are 15 trees initially and 21 after planting. So they planted 21 - 15 = 6 trees. #### 6" + }, + { + "question": "If there are 3 cars in the parking lot and 2 more cars arrive, how many cars are in the parking lot?", + "answer": "There are originally 3 cars. 2 more arrive, so 3 + 2 = 5 cars. #### 5" + }, + { + "question": "Leah had 32 chocolates and her sister had 42. If they ate 35, how many pieces do they have left in total?", + "answer": "Originally, Leah had 32 and her sister had 42, so 32 + 42 = 74. They ate 35, so 74 - 35 = 39 pieces left. #### 39" + }, + { + "question": "Shawn has five toys. For Christmas, he got two toys each from his mom and dad. How many toys does he have now?", + "answer": "Shawn started with 5 toys. He got 2 from mom and 2 from dad, so 5 + 2 + 2 = 9 toys. #### 9" + }, + { + "question": "There were nine computers in the server room. Five more computers were installed each day, from Monday to Thursday. How many computers are now in the server room?", + "answer": "There were originally 9 computers. From Monday to Thursday is 4 days. Each day 5 computers are installed, so 4 * 5 = 20 computers. Total: 9 + 20 = 29 computers. #### 29" + } +] + + +def _build_gsm8k_prompt(question, use_cot=True): + """Build a GSM8K prompt with 8-shot CoT examples.""" + prompt_lines = [] + + for ex in COT_EXAMPLES: + prompt_lines.append(f"Question: {ex['question']}") + prompt_lines.append(f"Answer: {ex['answer']}") + prompt_lines.append("") + + prompt_lines.append(f"Question: {question}") + prompt_lines.append("Answer:") + + return "\n".join(prompt_lines) + + +def _extract_gsm8k_answer(text: str) -> Optional[str]: + """Extract the final numeric answer from GSM8K output.""" + # Look for #### N pattern + m = re.search(r'####\s*(-?\d+(?:[.,]\d+)?)', text) + if m: + return m.group(1).replace(",", "") + + # Try to get the last number mentioned + numbers = re.findall(r'-?\d+(?:[.,]\d+)?', text) + if numbers: + return numbers[-1].replace(",", "") + + return None + + +class GSM8KBenchmark(BaseBenchmark): + """GSM8K benchmark — 8-shot chain-of-thought math word problems.""" + + @property + def name(self) -> str: + return "GSM8K" + + def run(self, backend_url: str, model_name: str, + max_samples: int = 0, use_cot: bool = True, + **kwargs) -> dict: + evaluator = LlamaCppEvaluator(backend_url, temperature=0.0, max_tokens=512) + t0 = time.time() + + records = get_dataset_stream("gsm8k") + if not records: + return { + "name": "GSM8K", + "accuracy": 0, "correct": 0, "total": 0, + "per_category": {}, + "metrics": {"elapsed": time.time() - t0, "api_calls": 0, "api_errors": 0}, + "samples": 0, + "error": "No dataset found. Run `mojollama-studio evaluate download` first." + } + + if max_samples > 0: + records = records[:max_samples] + + correct = 0 + total = 0 + errors = 0 + + for i, record in enumerate(records): + question = record.get("question", "") + answer = record.get("answer", "") + + # Extract ground truth answer (after ####) + gt = _extract_gsm8k_answer(answer) + if gt is None: + continue + + prompt = _build_gsm8k_prompt(question, use_cot) + + try: + generated = evaluator.complete(prompt, max_tokens=256, + stop=["Question:"]) + predicted = _extract_gsm8k_answer(generated) + if predicted and normalize_answer(predicted) == normalize_answer(gt): + correct += 1 + elif predicted: + # Try numeric comparison + try: + if abs(float(predicted) - float(gt)) < 0.01: + correct += 1 + except (ValueError, TypeError): + pass + except Exception as e: + errors += 1 + + total += 1 + + if (i + 1) % 20 == 0 or (i + 1) == len(records): + pct = (correct / total * 100) if total > 0 else 0 + print(f" GSM8K: {pct:.1f}% ({correct}/{total}) — {i+1}/{len(records)}") + + elapsed = time.time() - t0 + stats = evaluator.get_stats() + + return { + "name": "GSM8K", + "accuracy": correct / total if total > 0 else 0, + "correct": correct, + "total": total, + "per_category": {"math": {"correct": correct, "total": total, "accuracy": correct / total if total > 0 else 0}}, + "metrics": { + "elapsed": elapsed, + "api_calls": stats["api_calls"], + "api_errors": stats["api_errors"], + "total_tokens": stats["total_tokens"], + }, + "samples": total + } diff --git a/yardsticks/mojollama-eval-runners/eval/hellaswag.py b/yardsticks/mojollama-eval-runners/eval/hellaswag.py new file mode 100644 index 0000000..d01e1bc --- /dev/null +++ b/yardsticks/mojollama-eval-runners/eval/hellaswag.py @@ -0,0 +1,143 @@ +"""HellaSwag — Commonsense Reasoning benchmark. + +Multiple choice sentence completion. Choose the most plausible ending. +Uses rowan/hellaswag dataset. +""" + +import json +import re +import time +from typing import Optional + +from .base import BaseBenchmark, LlamaCppEvaluator, extract_letter_answer, normalize_answer +from .dataset import get_dataset_stream + + +FEW_SHOT_EXAMPLES = [ + { + "ctx": "A woman is sitting on a bench. She", + "endings": ["A. stands up and walks away.", "B. flies into the sky.", "C. turns into a dragon.", "D. disappears."], + "answer": "A" + }, + { + "ctx": "A man is cooking in the kitchen. He", + "endings": ["A. starts singing opera loudly.", "B. chops vegetables for the soup.", "C. dissolves into thin air.", "D. forgets how to cook."], + "answer": "B" + }, + { + "ctx": "A child is playing in the park. The child", + "endings": ["A. grows wings and flies away.", "B. starts levitating.", "C. runs toward the swings.", "D. turns into a tree."], + "answer": "C" + }, + { + "ctx": "A person is driving a car. They approach a red light. They", + "endings": ["A. accelerate through the intersection.", "B. stop the car and wait.", "C. close their eyes.", "D. get out and run."], + "answer": "B" + }, + { + "ctx": "A student is taking an exam. The student", + "endings": ["A. reads the questions carefully.", "B. eats the exam paper.", "C. falls asleep on the floor.", "D. turns into a bird."], + "answer": "A" + } +] + + +def _build_hellaswag_prompt(ctx, endings): + """Build a HellaSwag prompt with few-shot examples.""" + prompt_lines = [ + "Choose the most plausible ending for each situation.", + "" + ] + for ex in FEW_SHOT_EXAMPLES: + prompt_lines.append(ex["ctx"]) + for e in ex["endings"]: + prompt_lines.append(e) + prompt_lines.append(f"Answer: {ex['answer']}") + prompt_lines.append("") + + prompt_lines.append(ctx) + for e in endings: + prompt_lines.append(e) + prompt_lines.append("Answer:") + + return "\n".join(prompt_lines) + + +class HellaSwagBenchmark(BaseBenchmark): + """HellaSwag — commonsense reasoning, multiple choice.""" + + @property + def name(self) -> str: + return "HellaSwag" + + def run(self, backend_url: str, model_name: str, + max_samples: int = 0, **kwargs) -> dict: + evaluator = LlamaCppEvaluator(backend_url, temperature=0.0, max_tokens=32) + t0 = time.time() + + records = get_dataset_stream("hellaswag") + if not records: + return {"name": "HellaSwag", "accuracy": 0, "correct": 0, "total": 0, + "per_category": {}, "metrics": {"elapsed": time.time() - t0}, + "samples": 0, "error": "No dataset. Run download first."} + + if max_samples > 0: + records = records[:max_samples] + + correct = 0 + total = 0 + labels = ["A", "B", "C", "D"] + + for record in records: + ctx = record.get("ctx", "") + endings = record.get("endings", []) + label = record.get("label", "") + + # Map label to index + label_idx = None + if label in "0123": + label_idx = int(label) + elif label.isdigit() and 0 <= int(label) < len(endings): + label_idx = int(label) + elif label in labels: + label_idx = labels.index(label) + else: + continue + + answer_letter = labels[label_idx] if 0 <= label_idx < len(labels) else None + if answer_letter is None: + continue + + # Format endings with letter labels + formatted = [f"{labels[i]}. {endings[i]}" for i in range(len(endings))] + prompt = _build_hellaswag_prompt(ctx, formatted) + + try: + generated = evaluator.complete(prompt, max_tokens=16) + predicted = extract_letter_answer(generated) + if predicted is None: + m = re.search(r'\b([A-D])\b', generated) + if m: + predicted = m.group(1) + if predicted == answer_letter: + correct += 1 + except Exception: + pass + + total += 1 + + elapsed = time.time() - t0 + stats = evaluator.get_stats() + acc = correct / total if total > 0 else 0 + + print(f" HellaSwag: {acc*100:.2f}% ({correct}/{total})") + + return { + "name": "HellaSwag", + "accuracy": acc, + "correct": correct, + "total": total, + "per_category": {"commonsense_reasoning": {"correct": correct, "total": total, "accuracy": acc}}, + "metrics": {"elapsed": elapsed, "api_calls": stats["api_calls"], "api_errors": stats["api_errors"]}, + "samples": total + } diff --git a/yardsticks/mojollama-eval-runners/eval/humaneval.py b/yardsticks/mojollama-eval-runners/eval/humaneval.py new file mode 100644 index 0000000..d4f81ba --- /dev/null +++ b/yardsticks/mojollama-eval-runners/eval/humaneval.py @@ -0,0 +1,131 @@ +"""HumanEval — Code generation benchmark. + +OpenAI's HumanEval: write function from docstring, pass/fail by unit test. +Evaluates functional correctness (pass@k). +""" + +import json +import re +import time +from typing import Optional + +from .base import BaseBenchmark, LlamaCppEvaluator +from .dataset import get_dataset_stream + + +FEW_SHOT_EXAMPLES = [ + { + "prompt": 'def add(a, b):\n """Return the sum of a and b."""', + "result": ' return a + b' + }, + { + "prompt": 'def is_even(n):\n """Return True if n is even, False otherwise."""', + "result": ' return n % 2 == 0' + }, + { + "prompt": 'def factorial(n):\n """Return n! for n >= 0."""', + "result": ' if n <= 1:\n return 1\n return n * factorial(n - 1)' + } +] + + +def _build_humaneval_prompt(prompt_text: str) -> str: + """Build HumanEval prompt with few-shot examples.""" + parts = [ + "Complete the following Python functions. Return only the function body with proper indentation.", + "" + ] + for ex in FEW_SHOT_EXAMPLES: + parts.append(ex["prompt"]) + parts.append(ex["result"]) + parts.append("") + + parts.append(prompt_text) + return "\n".join(parts) + + +def _extract_code(text: str) -> str: + """Extract code from model output, removing markdown fences.""" + # Remove markdown code blocks + text = re.sub(r'```(?:python)?\n?', '', text) + # Remove trailing explanations + text = re.split(r'\n(?:# |"""|\'\'\'|Explanation)', text)[0] + # Get indented body + lines = text.strip().split('\n') + body = [] + for line in lines: + if line.startswith(' ') or line.startswith('\t') or line.strip() == '': + body.append(line) + elif not body and line.strip(): + # First line might be the signature, skip it + continue + elif body and not line.startswith(' ') and line.strip(): + # We've moved past the function body + break + return '\n'.join(body).strip() + + +class HumanEvalBenchmark(BaseBenchmark): + """HumanEval — code generation, functional correctness.""" + + @property + def name(self) -> str: + return "HumanEval" + + def run(self, backend_url: str, model_name: str, + max_samples: int = 0, **kwargs) -> dict: + evaluator = LlamaCppEvaluator(backend_url, temperature=0.2, max_tokens=512) + t0 = time.time() + + records = get_dataset_stream("humaneval") + if not records: + return {"name": "HumanEval", "accuracy": 0, "correct": 0, "total": 0, + "per_category": {}, "metrics": {"elapsed": time.time() - t0}, + "samples": 0, "error": "No dataset. Run download first."} + + if max_samples > 0: + records = records[:max_samples] + + correct = 0 + total = 0 + + for record in records: + prompt_text = record.get("prompt", "") + entry_point = record.get("entry_point", "") + test_code = record.get("test", "") + canonical = record.get("canonical_solution", "") + + prompt = _build_humaneval_prompt(prompt_text) + + try: + generated = evaluator.complete(prompt, max_tokens=384, temperature=0.2) + body = _extract_code(generated) + + if body: + # Build complete function and run test + full_code = f"{prompt_text}\n{body}\n\n{test_code}\ncheck({entry_point})" + try: + exec_globals = {} + exec(full_code, exec_globals) + correct += 1 + except Exception: + pass + except Exception: + pass + + total += 1 + + elapsed = time.time() - t0 + stats = evaluator.get_stats() + acc = correct / total if total > 0 else 0 + print(f" HumanEval: {acc*100:.2f}% pass@1 ({correct}/{total})") + + return { + "name": "HumanEval", + "accuracy": acc, + "correct": correct, + "total": total, + "per_category": {"python_code_gen": {"correct": correct, "total": total, "accuracy": acc}}, + "metrics": {"elapsed": elapsed, "api_calls": stats["api_calls"], "api_errors": stats["api_errors"]}, + "samples": total + } diff --git a/yardsticks/mojollama-eval-runners/eval/mmlu.py b/yardsticks/mojollama-eval-runners/eval/mmlu.py new file mode 100644 index 0000000..8d6e599 --- /dev/null +++ b/yardsticks/mojollama-eval-runners/eval/mmlu.py @@ -0,0 +1,172 @@ +"""MMLU (Massive Multitask Language Understanding) benchmark. + +57 subjects, 5-shot, multiple-choice evaluation. +Uses the lukaemon/mmlu dataset format from Hugging Face. +""" + +import json +import os +import re +import time +from typing import Optional + +from .base import BaseBenchmark, LlamaCppEvaluator, extract_letter_answer, normalize_answer +from .dataset import get_dataset_stream, get_subjects, get_dataset_path, DATASET_SOURCES + + +# Few-shot examples for MMLU (5-shot) +FEW_SHOT_EXAMPLES = { + "abstract_algebra": [ + { + "question": "Find the degree for the given field extension Q(sqrt(2), sqrt(3), sqrt(5)) over Q.", + "choices": ["A. 4", "B. 6", "C. 8", "D. 2"], + "answer": "C" + }, + { + "question": "Let V be the set of all solutions to the differential equation y'' + 4y' + 3y = 0. What is the dimension of V as a real vector space?", + "choices": ["A. 0", "B. 1", "C. 2", "D. 3"], + "answer": "C" + }, + { + "question": "How many elements of order 5 are in S_7?", + "choices": ["A. 504", "B. 126", "C. 21", "D. 252"], + "answer": "D" + }, + { + "question": "What is the value of the infinite sum 1 + 1/4 + 1/9 + 1/16 + ...?", + "choices": ["A. pi^2/4", "B. pi^2/6", "C. pi^2/8", "D. pi^2/2"], + "answer": "B" + }, + { + "question": "How many ring homomorphisms are there from Z/5Z to Z/20Z?", + "choices": ["A. 1", "B. 2", "C. 3", "D. 5"], + "answer": "A" + } + ] +} + +_DEFAULT_FEW_SHOT = [ + {"question": "What is the capital of France?", "choices": ["A. London", "B. Paris", "C. Berlin", "D. Madrid"], "answer": "B"}, + {"question": "Which planet is known as the Red Planet?", "choices": ["A. Venus", "B. Jupiter", "C. Mars", "D. Saturn"], "answer": "C"}, + {"question": "What is 2 + 2?", "choices": ["A. 3", "B. 4", "C. 5", "D. 6"], "answer": "B"}, +] + + +def _build_mmlu_prompt(question, choices, subject=None, few_shot=None): + """Build a prompt for MMLU with few-shot examples.""" + if few_shot is None: + few_shot = FEW_SHOT_EXAMPLES.get(subject, _DEFAULT_FEW_SHOT) + + prompt_lines = [ + "The following are multiple choice questions (with answers).", + "" + ] + for ex in few_shot: + prompt_lines.append(ex["question"]) + for ch in ex["choices"]: + prompt_lines.append(ch) + prompt_lines.append(f"Answer: {ex['answer']}") + prompt_lines.append("") + + # The actual question + prompt_lines.append(question) + for ch in choices: + prompt_lines.append(ch) + prompt_lines.append("Answer:") + + return "\n".join(prompt_lines) + + +class MMLUBenchmark(BaseBenchmark): + """MMLU benchmark — 57 subjects, 5-shot multiple choice.""" + + @property + def name(self) -> str: + return "MMLU" + + def run(self, backend_url: str, model_name: str, + max_samples: int = 0, subjects: Optional[list] = None, + **kwargs) -> dict: + evaluator = LlamaCppEvaluator(backend_url, temperature=0.0, max_tokens=50) + t0 = time.time() + + all_subjects = subjects or get_subjects("mmlu") + per_category = {} + total_correct = 0 + total_all = 0 + + for subject in all_subjects: + records = get_dataset_stream("mmlu", subject) + if not records: + print(f" ⚠ No data for {subject}, skipping") + continue + + if max_samples > 0: + records = records[:max_samples] + + subject_correct = 0 + subject_total = 0 + + for record in records: + question = record.get("question", "") + choices = record.get("choices", []) + answer_idx = record.get("answer", -1) + + # Convert answer index to letter + labels = ["A", "B", "C", "D"] + answer_letter = labels[answer_idx] if 0 <= answer_idx < len(labels) else None + if answer_letter is None: + continue + + # Format choices as A. text, B. text, etc. + formatted_choices = [ + f"{labels[i]}. {choices[i]}" + for i in range(len(choices)) + ] + + prompt = _build_mmlu_prompt(question, formatted_choices, subject) + + try: + generated = evaluator.complete(prompt, max_tokens=32) + predicted = extract_letter_answer(generated) + if predicted is None: + # Try first letter in output + m = re.search(r'\b([A-D])\b', generated) + if m: + predicted = m.group(1) + if predicted == answer_letter: + subject_correct += 1 + except Exception as e: + print(f" ⚠ Error on {subject}: {e}") + + subject_total += 1 + + per_category[subject] = { + "correct": subject_correct, + "total": subject_total, + "accuracy": subject_correct / subject_total if subject_total > 0 else 0 + } + total_correct += subject_correct + total_all += subject_total + + pct = (subject_correct / subject_total * 100) if subject_total > 0 else 0 + print(f" {subject:40s} {pct:6.2f}% ({subject_correct}/{subject_total})") + + elapsed = time.time() - t0 + stats = evaluator.get_stats() + + return { + "name": "MMLU", + "accuracy": total_correct / total_all if total_all > 0 else 0, + "correct": total_correct, + "total": total_all, + "per_category": per_category, + "metrics": { + "elapsed": elapsed, + "api_calls": stats["api_calls"], + "api_errors": stats["api_errors"], + "total_tokens": stats["total_tokens"], + "subjects_evaluated": len([s for s in per_category if per_category[s]["total"] > 0]) + }, + "samples": total_all + } diff --git a/yardsticks/mojollama-eval-runners/eval/orchestrator.py b/yardsticks/mojollama-eval-runners/eval/orchestrator.py new file mode 100644 index 0000000..aab30a0 --- /dev/null +++ b/yardsticks/mojollama-eval-runners/eval/orchestrator.py @@ -0,0 +1,239 @@ +"""Evaluation orchestrator — runs benchmarks and aggregates results. + +This module provides the main entry point for running evaluations against +a llama.cpp backend, either from the CLI or the REST API. +""" + +import json +import os +import sys +import time +import urllib.request +from typing import Optional + +from .base import BaseBenchmark, LlamaCppEvaluator, check_backend_alive, format_results +from .dataset import get_dataset_path, get_dataset_stream, get_subjects, list_available_datasets, DATASET_SOURCES +from .mmlu import MMLUBenchmark +from .gsm8k import GSM8KBenchmark +from .ceval import CEvalBenchmark +from .hellaswag import HellaSwagBenchmark +from .arc import ARCBenchmark +from .bbh import BBHBenchmark +from .humaneval import HumanEvalBenchmark + + +BENCHMARKS = { + "mmlu": MMLUBenchmark, + "gsm8k": GSM8KBenchmark, + "ceval": CEvalBenchmark, + "hellaswag": HellaSwagBenchmark, + "arc": ARCBenchmark, + "bbh": BBHBenchmark, + "humaneval": HumanEvalBenchmark, +} + + +def get_benchmark(name: str) -> Optional[BaseBenchmark]: + """Get benchmark instance by name.""" + cls = BENCHMARKS.get(name.lower()) + if cls: + return cls() + return None + + +def list_benchmarks() -> list: + """List available benchmarks with descriptions.""" + return [ + {"id": "mmlu", "name": "MMLU", "description": "57 subjects, 5-shot multiple choice"}, + {"id": "gsm8k", "name": "GSM8K", "description": "Grade school math, 8-shot CoT"}, + {"id": "ceval", "name": "CEval", "description": "Chinese evaluation, 52 subjects"}, + {"id": "hellaswag", "name": "HellaSwag", "description": "Commonsense reasoning"}, + {"id": "arc", "name": "ARC", "description": "AI2 Reasoning Challenge (Challenge + Easy)"}, + {"id": "bbh", "name": "BBH", "description": "Big-Bench Hard, 27 reasoning tasks"}, + {"id": "humaneval", "name": "HumanEval", "description": "Code generation (pass@1)"}, + ] + + +def run_benchmark(name: str, backend_url: str, model_name: str, + max_samples: int = 0, **kwargs) -> dict: + """Run a single benchmark. + + Args: + name: Benchmark name (mmlu, gsm8k, etc.) + backend_url: llama.cpp server URL + model_name: Model name/path for logging + max_samples: Max samples per subject (0 = all) + **kwargs: Passed to benchmark.run() + + Returns: + Result dict with accuracy, per_category, etc. + """ + bench = get_benchmark(name) + if not bench: + return {"name": name, "accuracy": 0, "correct": 0, "total": 0, + "error": f"Unknown benchmark: {name}"} + + print(f"\n{'─'*60}") + print(f" Running {bench.name} benchmark...") + print(f" Backend: {backend_url}") + print(f" Model: {model_name}") + if max_samples > 0: + print(f" Samples: {max_samples} per category") + print(f"{'─'*60}") + + return bench.run(backend_url, model_name, max_samples=max_samples, **kwargs) + + +def run_benchmarks(benchmarks: list, backend_url: str, model_name: str, + max_samples: int = 0) -> list: + """Run multiple benchmarks and return aggregated results.""" + results = [] + for name in benchmarks: + try: + result = run_benchmark(name, backend_url, model_name, max_samples) + results.append(result) + except Exception as e: + print(f"\n ❌ {name} benchmark failed: {e}") + results.append({ + "name": name, "accuracy": 0, "correct": 0, "total": 0, + "error": str(e) + }) + return results + + +def download_all_datasets(progress_callback=None) -> dict: + """Download all benchmark datasets. + + Returns: + {name: True/False} for each dataset + """ + results = {} + + # MMLU — one file per subject + subjects = get_subjects("mmlu") + print(f"\n Downloading MMLU ({len(subjects)} subjects)...") + mmlu_ok = 0 + for i, subj in enumerate(subjects): + path = get_dataset_path("mmlu", subj) + if path: + mmlu_ok += 1 + if progress_callback: + progress_callback("mmlu", i + 1, len(subjects)) + results["mmlu"] = mmlu_ok > 0 + print(f" → {mmlu_ok}/{len(subjects)} subjects cached") + + # GSM8K + print(" Downloading GSM8K...") + path = get_dataset_path("gsm8k") + results["gsm8k"] = path is not None + + # CEval + ceval_subjects = get_subjects("ceval") + print(f" Downloading CEval ({len(ceval_subjects)} subjects)...") + ceval_ok = 0 + for subj in ceval_subjects: + path = get_dataset_path("ceval", subj) + if path: + ceval_ok += 1 + results["ceval"] = ceval_ok > 0 + print(f" → {ceval_ok}/{len(ceval_subjects)} subjects cached") + + # HellaSwag + print(" Downloading HellaSwag...") + path = get_dataset_path("hellaswag") + results["hellaswag"] = path is not None + + # ARC — try specific file names + print(" Downloading ARC (Challenge + Easy)...") + arc_ok = False + for v in ["challenge", "easy"]: + for fname in [ + f"ARC-{v.capitalize()}-Test.jsonl", + f"arc_{v}_test.jsonl" + ]: + import os + dest = os.path.join(os.path.expanduser("~/.mojollama/eval_datasets"), fname) + url = DATASET_SOURCES["arc"].get(f"{v}_url", "") + if url: + from .dataset import _download_file + if _download_file(url, dest): + arc_ok = True + results["arc"] = arc_ok + + # BBH + print(" Downloading BBH (27 tasks)...") + bbh_tasks = list(DATASET_SOURCES.get("bbh", {}).get("url_templates", {}).keys()) + bbh_ok = 0 + for task in bbh_tasks: + path = get_dataset_path("bbh", task) + if path: + bbh_ok += 1 + results["bbh"] = bbh_ok > 0 + print(f" → {bbh_ok}/{len(bbh_tasks)} tasks cached") + + # HumanEval + print(" Downloading HumanEval...") + path = get_dataset_path("humaneval") + results["humaneval"] = path is not None + + print(f"\n {'─'*40}") + for name, ok in results.items(): + print(f" {name:20s} {'✅' if ok else '❌'}") + print(f" {'─'*40}") + + return results + + +def get_dataset_info() -> list: + """Get list of cached dataset info.""" + available = list_available_datasets() + info = [] + for name, data in available.items(): + info.append({ + "name": name, + "cached": True, + "size_bytes": data.get("size", 0), + "subjects": data.get("subjects", 0), + }) + return info + + +def serve_stream_results(results: list, wfile) -> None: + """Stream benchmark results line by line for the web UI. + + Each line is a JSON dict with a 'type' field: + - progress: {type:'progress', message:str} + - result: {type:'result', ...benchmark_result} + - done: {type:'done', summary:str} + """ + for r in results: + name = r.get("name", "?") + acc = r.get("accuracy", 0) * 100 + correct = r.get("correct", 0) + total = r.get("total", 0) + + wfile.write(json.dumps({ + "type": "progress", + "name": name, + "message": f"{name}: {acc:.2f}% ({correct}/{total})" + }).encode() + b"\n") + wfile.flush() + + wfile.write(json.dumps({ + "type": "result", + **r + }).encode() + b"\n") + wfile.flush() + + total_correct = sum(r.get("correct", 0) for r in results) + total_all = sum(r.get("total", 0) for r in results) + overall = total_correct / total_all * 100 if total_all > 0 else 0 + + wfile.write(json.dumps({ + "type": "done", + "overall_accuracy": overall, + "total_correct": total_correct, + "total_samples": total_all, + "benchmarks_run": len(results), + }).encode() + b"\n") + wfile.flush()