MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / eval / base.py
| 1 | """Base evaluation harness for MojoLlama benchmarks. |
| 2 | |
| 3 | Defines the abstract interface for all benchmarks and the core evaluation |
| 4 | loop that interacts with llama.cpp server or any backend. |
| 5 | """ |
| 6 | |
| 7 | import json |
| 8 | import os |
| 9 | import re |
| 10 | import time |
| 11 | import sys |
| 12 | import urllib.request |
| 13 | import urllib.error |
| 14 | from abc import ABC, abstractmethod |
| 15 | from typing import Optional |
| 16 | |
| 17 | |
| 18 | class BaseBenchmark(ABC): |
| 19 | """Abstract base for all benchmarks. |
| 20 | |
| 21 | Subclasses must implement: |
| 22 | - name: str — benchmark name |
| 23 | - run(self, backend_url, model_name, **kwargs) -> dict — execute evaluation |
| 24 | |
| 25 | The run() method returns: |
| 26 | { |
| 27 | 'name': str, |
| 28 | 'accuracy': float, # 0.0 to 1.0 |
| 29 | 'correct': int, |
| 30 | 'total': int, |
| 31 | 'per_category': {category: {correct: int, total: int, accuracy: float}}, |
| 32 | 'metrics': {...}, # additional metrics |
| 33 | 'samples': int |
| 34 | } |
| 35 | """ |
| 36 | |
| 37 | @property |
| 38 | @abstractmethod |
| 39 | def name(self) -> str: |
| 40 | ... |
| 41 | |
| 42 | @abstractmethod |
| 43 | def run(self, backend_url: str, model_name: str, |
| 44 | max_samples: int = 0, **kwargs) -> dict: |
| 45 | ... |
| 46 | |
| 47 | |
| 48 | class LlamaCppEvaluator: |
| 49 | """Core evaluator that calls llama.cpp server API for completions.""" |
| 50 | |
| 51 | def __init__(self, backend_url: str = "http://127.0.0.1:8081", |
| 52 | temperature: float = 0.0, max_tokens: int = 256, |
| 53 | timeout: int = 60): |
| 54 | self.backend_url = backend_url.rstrip("/") |
| 55 | self.temperature = temperature |
| 56 | self.max_tokens = max_tokens |
| 57 | self.timeout = timeout |
| 58 | self._stats = {"api_calls": 0, "total_tokens": 0, "api_errors": 0} |
| 59 | |
| 60 | def complete(self, prompt: str, max_tokens: Optional[int] = None, |
| 61 | temperature: Optional[float] = None, |
| 62 | stop: Optional[list] = None) -> str: |
| 63 | """Send a completion request and return the generated text.""" |
| 64 | data = { |
| 65 | "prompt": prompt, |
| 66 | "n_predict": max_tokens or self.max_tokens, |
| 67 | "temperature": temperature if temperature is not None else self.temperature, |
| 68 | "stream": False, |
| 69 | } |
| 70 | if stop: |
| 71 | data["stop"] = stop |
| 72 | |
| 73 | req = urllib.request.Request( |
| 74 | f"{self.backend_url}/completion", |
| 75 | data=json.dumps(data).encode(), |
| 76 | headers={"Content-Type": "application/json"}, |
| 77 | method="POST" |
| 78 | ) |
| 79 | self._stats["api_calls"] += 1 |
| 80 | try: |
| 81 | with urllib.request.urlopen(req, timeout=self.timeout) as resp: |
| 82 | result = json.loads(resp.read().decode("utf-8")) |
| 83 | text = result.get("content", "") |
| 84 | tokens = result.get("tokens", 0) or result.get("tokens_evaluated", 0) |
| 85 | self._stats["total_tokens"] += tokens |
| 86 | return text |
| 87 | except Exception as e: |
| 88 | self._stats["api_errors"] += 1 |
| 89 | raise RuntimeError(f"API call failed: {e}") |
| 90 | |
| 91 | def chat_complete(self, messages: list, max_tokens: Optional[int] = None, |
| 92 | temperature: Optional[float] = None) -> str: |
| 93 | """Send a chat completion request and return the response text.""" |
| 94 | data = { |
| 95 | "messages": messages, |
| 96 | "max_tokens": max_tokens or self.max_tokens, |
| 97 | "temperature": temperature if temperature is not None else self.temperature, |
| 98 | "stream": False, |
| 99 | } |
| 100 | |
| 101 | req = urllib.request.Request( |
| 102 | f"{self.backend_url}/v1/chat/completions", |
| 103 | data=json.dumps(data).encode(), |
| 104 | headers={"Content-Type": "application/json"}, |
| 105 | method="POST" |
| 106 | ) |
| 107 | self._stats["api_calls"] += 1 |
| 108 | try: |
| 109 | with urllib.request.urlopen(req, timeout=self.timeout) as resp: |
| 110 | result = json.loads(resp.read().decode("utf-8")) |
| 111 | text = result.get("choices", [{}])[0].get("message", {}).get("content", "") |
| 112 | usage = result.get("usage", {}) |
| 113 | self._stats["total_tokens"] += usage.get("total_tokens", 0) |
| 114 | return text |
| 115 | except Exception as e: |
| 116 | self._stats["api_errors"] += 1 |
| 117 | raise RuntimeError(f"Chat API call failed: {e}") |
| 118 | |
| 119 | def get_stats(self) -> dict: |
| 120 | """Return evaluation statistics.""" |
| 121 | return dict(self._stats) |
| 122 | |
| 123 | |
| 124 | def normalize_answer(answer: str) -> str: |
| 125 | """Normalize answer for exact match comparison.""" |
| 126 | answer = answer.strip().lower() |
| 127 | # Remove punctuation except period (for single letters) |
| 128 | answer = answer.strip(".,;:!?\"'()[]{}") |
| 129 | answer = answer.strip() |
| 130 | return answer |
| 131 | |
| 132 | |
| 133 | def extract_letter_answer(text: str) -> Optional[str]: |
| 134 | """Extract letter answer (A, B, C, D) from generated text.""" |
| 135 | text = text.strip() |
| 136 | # Look for patterns like "Answer: A", "The answer is B", "A." |
| 137 | patterns = [ |
| 138 | r'(?:^|\n)\s*(?:answer|the answer is|so the answer is|correct answer is|option|choice|answer:\s*)\s*[:\s]*([A-D])\b', |
| 139 | r'(?:^|\n)\s*([A-D])\s*[.:)]?\s*(?:$|\n)', |
| 140 | r'\(([A-D])\)', |
| 141 | r'\b([A-D])\s*(?:is correct|is the answer|is right)\b', |
| 142 | ] |
| 143 | for pat in patterns: |
| 144 | m = re.search(pat, text, re.IGNORECASE) |
| 145 | if m: |
| 146 | return m.group(1).upper() |
| 147 | return None |
| 148 | |
| 149 | |
| 150 | def extract_number_answer(text: str) -> Optional[str]: |
| 151 | """Extract numeric answer from generated text (for GSM8K).""" |
| 152 | text = text.strip() |
| 153 | # Look for patterns like "#### 42", "Answer: 42", final number |
| 154 | patterns = [ |
| 155 | r'####\s*(-?\d+(?:[,\.]\d+)?)', |
| 156 | r'(?:answer|the answer is|result|so the answer is)\s*[:\s]*(-?\d+(?:[,\.]\d+)?)', |
| 157 | r'(?:^|\n)\s*(-?\d+(?:[,\.]\d+)?)\s*(?:$|\n)', |
| 158 | ] |
| 159 | for pat in patterns: |
| 160 | m = re.search(pat, text, re.IGNORECASE) |
| 161 | if m: |
| 162 | return m.group(1).replace(",", "") |
| 163 | return None |
| 164 | |
| 165 | |
| 166 | def check_backend_alive(url: str) -> bool: |
| 167 | """Check if a llama.cpp backend is running.""" |
| 168 | try: |
| 169 | req = urllib.request.Request(f"{url}/health") |
| 170 | with urllib.request.urlopen(req, timeout=5) as resp: |
| 171 | return resp.status == 200 |
| 172 | except Exception: |
| 173 | return False |
| 174 | |
| 175 | |
| 176 | def format_results(results: list) -> str: |
| 177 | """Format benchmark results for display.""" |
| 178 | lines = [] |
| 179 | total_correct = sum(r["correct"] for r in results) |
| 180 | total_all = sum(r["total"] for r in results) |
| 181 | overall_acc = total_correct / total_all if total_all > 0 else 0 |
| 182 | |
| 183 | lines.append(f"{'═'*60}") |
| 184 | lines.append(f" Overall Accuracy: {overall_acc*100:.2f}% ({total_correct}/{total_all})") |
| 185 | lines.append(f"{'═'*60}") |
| 186 | |
| 187 | for r in results: |
| 188 | acc = r["correct"] / r["total"] if r["total"] > 0 else 0 |
| 189 | lines.append(f" {r['name']:30s} {acc*100:6.2f}% ({r['correct']:4d}/{r['total']:<4d})") |
| 190 | |
| 191 | per_cat = r.get("per_category", {}) |
| 192 | if per_cat: |
| 193 | for cat, stats in sorted(per_cat.items()): |
| 194 | cat_acc = stats["correct"] / stats["total"] if stats["total"] > 0 else 0 |
| 195 | lines.append(f" ├─ {cat:40s} {cat_acc*100:6.2f}% ({stats['correct']}/{stats['total']})") |
| 196 | |
| 197 | lines.append(f"{'═'*60}") |
| 198 | metrics = {} |
| 199 | for r in results: |
| 200 | if "metrics" in r: |
| 201 | for k, v in r["metrics"].items(): |
| 202 | metrics[k] = metrics.get(k, 0) + (v if isinstance(v, (int, float)) else 0) |
| 203 | if metrics: |
| 204 | lines.append(f" Runtime: {metrics.get('elapsed', 0):.1f}s, " |
| 205 | f"API calls: {metrics.get('api_calls', 0)}, " |
| 206 | f"Errors: {metrics.get('api_errors', 0)}") |
| 207 | |
| 208 | return "\n".join(lines) |