#!/usr/bin/env python3 """ Evaluate a chat model on KuMMLU. Works with any OpenAI-compatible chat-completions endpoint: OpenRouter (default), OpenAI, or a local server such as vLLM / llama.cpp / Ollama (--base-url). export OPENROUTER_API_KEY=... python evaluate.py --model google/gemini-2.5-flash python evaluate.py --model my-model --base-url http://localhost:8000/v1 --api-key none python evaluate.py --model openai/gpt-4o --limit 50 # smoke test Protocol (as in the KuMMLU paper): every question's options are shuffled with a fixed per-question seed and labelled 0..N-1; the chosen number is parsed from the reply. """ import argparse, asyncio, glob, json, os, random, re, sys from collections import defaultdict import aiohttp SEED = 42 SYSTEM_PROMPT = ("You are taking a multiple choice exam in Kurdish. " "Respond with ONLY the number of the correct answer. No explanation.") HERE = os.path.dirname(os.path.abspath(__file__)) def load_questions(data_dir=None, hf_repo=None): if hf_repo: from datasets import load_dataset return list(load_dataset(hf_repo, "all", split="test")) data_dir = data_dir or os.path.join(HERE, "..", "data") rows = [] for path in sorted(glob.glob(os.path.join(data_dir, "*.jsonl"))): with open(path, encoding="utf-8") as f: rows.extend(json.loads(line) for line in f) return rows def present(q): """Return (choices in presentation order, index of the correct choice).""" order = list(range(len(q["choices"]))) random.Random(f"{SEED}:{q['id']}").shuffle(order) return [q["choices"][i] for i in order], order.index(q["answer"]) def format_prompt(question, choices): lines = "\n".join(f"{i}: {c}" for i, c in enumerate(choices)) return (f"Question: {question}\n\nChoices:\n{lines}\n\n" f"Answer with a single number from 0 to {len(choices) - 1}:") def extract_answer(text, n): """Chosen index from a model response; tolerates reasoning text. None if unparsable.""" if not text: return None valid = {str(i) for i in range(n)} t = text.strip() if t in valid: return int(t) for line in reversed(t.splitlines()): digits = [d for d in re.findall(r"\d", line) if d in valid] if digits: return int(digits[-1] if len(digits) == 1 else digits[0]) return None async def ask(session, args, prompt, retries=5): payload = {"model": args.model, "temperature": 0, "max_tokens": args.max_tokens, "messages": [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": prompt}]} if args.reasoning == "off": payload["reasoning"] = {"enabled": False} elif args.reasoning != "default": payload["reasoning"] = {"effort": args.reasoning} url = args.base_url.rstrip("/") + "/chat/completions" for attempt in range(retries): try: async with session.post(url, json=payload) as r: if r.status == 200: data = await r.json() return ((data.get("choices") or [{}])[0].get("message") or {}).get("content") if r.status == 429 or r.status >= 500: await asyncio.sleep(2 ** attempt) continue print(f"HTTP {r.status}: {(await r.text())[:200]}", file=sys.stderr) return None except (aiohttp.ClientError, asyncio.TimeoutError): await asyncio.sleep(1 + attempt) return None async def run(args): questions = load_questions(args.data_dir, args.hf_repo) if args.limit: questions = questions[: args.limit] key = args.api_key or os.environ.get("OPENROUTER_API_KEY") or os.environ.get("OPENAI_API_KEY") if not key: sys.exit("Set OPENROUTER_API_KEY (or pass --api-key; use --api-key none for local servers).") headers = {"Authorization": f"Bearer {key}", "Content-Type": "application/json"} sem = asyncio.Semaphore(args.concurrency) timeout = aiohttp.ClientTimeout(total=args.timeout) async def one(session, q): choices, gold = present(q) async with sem: raw = await ask(session, args, format_prompt(q["question"], choices)) pred = extract_answer(raw, len(choices)) return {"id": q["id"], "subject": q["subject"], "source": q["source"], "gold_shuffled": gold, "predicted_shuffled": pred, "correct": pred == gold, "raw_tail": (raw or "")[-80:] or None} async with aiohttp.ClientSession(headers=headers, timeout=timeout) as session: results = await asyncio.gather(*(one(session, q) for q in questions)) summary = summarize(results) summary.update(model=args.model, reasoning=args.reasoning) os.makedirs(args.out_dir, exist_ok=True) stem = os.path.join(args.out_dir, args.model.replace("/", "__")) with open(stem + ".jsonl", "w", encoding="utf-8") as f: for r in results: f.write(json.dumps(r, ensure_ascii=False) + "\n") with open(stem + ".summary.json", "w", encoding="utf-8") as f: json.dump(summary, f, ensure_ascii=False, indent=2) print(json.dumps({k: summary[k] for k in ("model", "accuracy", "native_accuracy", "translated_accuracy", "response_rate")}, indent=2)) print(f"saved {stem}.jsonl and .summary.json") def summarize(results): def acc(rows): return round(100 * sum(r["correct"] for r in rows) / len(rows), 2) if rows else None by_subject = defaultdict(list) for r in results: by_subject[r["subject"]].append(r) answered = [r for r in results if r["predicted_shuffled"] is not None] return { "questions": len(results), "accuracy": acc(results), "native_accuracy": acc([r for r in results if r["source"] == "native"]), "translated_accuracy": acc([r for r in results if r["source"] == "translated"]), "macro_accuracy": round(sum(acc(v) for v in by_subject.values()) / len(by_subject), 2), "response_rate": round(100 * len(answered) / len(results), 2), "accuracy_on_answered": acc(answered), "by_subject": {s: acc(v) for s, v in sorted(by_subject.items())}, } def main(): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--model", required=True) p.add_argument("--base-url", default="https://openrouter.ai/api/v1") p.add_argument("--api-key") p.add_argument("--reasoning", default="default", help="default | off | low | medium | high (OpenRouter reasoning control)") p.add_argument("--max-tokens", type=int, default=512) p.add_argument("--concurrency", type=int, default=8) p.add_argument("--timeout", type=int, default=120) p.add_argument("--limit", type=int) p.add_argument("--data-dir", help="folder with the *.jsonl files (default: ../data)") p.add_argument("--hf-repo", help="load from the Hugging Face Hub instead, e.g. akam-ot/KuMMLU") p.add_argument("--out-dir", default="outputs") asyncio.run(run(p.parse_args())) if __name__ == "__main__": main()