#!/usr/bin/env python3 from __future__ import annotations import argparse import ast import getpass import json import math import os import re import sys import time import unicodedata from collections import Counter, defaultdict from datetime import datetime, timezone from pathlib import Path from typing import Any import torch from datasets import load_dataset from huggingface_hub import HfApi, get_token, hf_hub_download from huggingface_hub.errors import HfHubHTTPError from transformers import AutoModelForCausalLM, AutoTokenizer DATASET_ID = "ArrowLabs/ArrowBench-Instruct" EXPECTED_CASES = 1000 EXPECTED_CATEGORIES = { "general": 350, "multi_turn": 250, "system_prompts": 200, "recall_in_context": 120, "code": 80, } EXPECTED_DIFFICULTIES = {"easy": 200, "medium": 400, "hard": 400} ELO_SCALE = 400.0 ELO_PRIOR_RATING = 1_000.0 ELO_PRIOR_WEIGHT = 4.0 def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--model", required=True, help="Local model directory or Hugging Face model ID.") parser.add_argument("--out-dir", type=Path, default=Path("runs/bananamind-instruct-bench-1.2")) parser.add_argument("--dataset-id", default=DATASET_ID) parser.add_argument("--dataset-revision", default="main") parser.add_argument( "--hf-token", default=os.environ.get("HF_TOKEN"), help="Optional token. Omit this to use `hf auth login`; inaccessible tokens trigger a hidden CLI prompt.", ) parser.add_argument("--device", default="auto", help="auto, cpu, cuda, cuda:0, etc.") parser.add_argument( "--dtype", choices=("auto", "float32", "bfloat16", "float16"), default="auto", ) parser.add_argument("--threads", type=int, default=16) parser.add_argument("--seed", type=int, default=42) parser.add_argument("--repetition-penalty", type=float, default=1.1) parser.add_argument("--use-cache", action=argparse.BooleanOptionalAction, default=True) parser.add_argument("--trust-remote-code", action=argparse.BooleanOptionalAction, default=True) parser.add_argument("--resume", action="store_true") parser.add_argument( "--limit", type=int, default=None, help="Developer smoke-test limit. A limited run is explicitly marked non-official.", ) return parser.parse_args() def access_error(error: BaseException) -> bool: if not isinstance(error, HfHubHTTPError): return False response = getattr(error, "response", None) return response is not None and response.status_code in {401, 403, 404} def token_has_dataset_access(token: str | None, dataset_id: str, revision: str) -> bool: if not token: return False try: HfApi().whoami(token=token) hf_hub_download( repo_id=dataset_id, filename="data/test.jsonl", repo_type="dataset", revision=revision, token=token, ) return True except HfHubHTTPError as error: if access_error(error): return False raise RuntimeError(f"Could not contact Hugging Face while checking dataset access: {error}") from error def resolve_hf_token(args: argparse.Namespace) -> str: candidates: list[tuple[str, str | None]] = [ ("--hf-token/HF_TOKEN", args.hf_token), ("saved Hugging Face login", get_token()), ] seen: set[str] = set() for source, candidate in candidates: if not candidate or candidate in seen: continue seen.add(candidate) print(f"Checking {source} access to {args.dataset_id}...", flush=True) if token_has_dataset_access(candidate, args.dataset_id, args.dataset_revision): print("Dataset access confirmed.", flush=True) return candidate print(f"The {source} token cannot access the gated dataset.", flush=True) for attempt in range(1, 4): try: candidate = getpass.getpass( f"Hugging Face token with access to {args.dataset_id} (attempt {attempt}/3): " ).strip() except (EOFError, KeyboardInterrupt) as error: raise RuntimeError( "A Hugging Face token is required. Run `hf auth login` or pass --hf-token." ) from error if not candidate: continue if token_has_dataset_access(candidate, args.dataset_id, args.dataset_revision): print("Dataset access confirmed. The prompted token is used only for this process.", flush=True) return candidate print("That token does not have access to the gated dataset.", flush=True) raise RuntimeError( f"No token with access to {args.dataset_id} was provided. Accept the dataset gate first." ) def normalize_messages(value: Any) -> list[dict[str, str]]: if isinstance(value, dict) and set(value) >= {"role", "content"}: value = [dict(role=role, content=content) for role, content in zip(value["role"], value["content"])] messages = [{"role": str(item["role"]), "content": str(item["content"])} for item in value] if not messages or messages[-1]["role"] != "user": raise ValueError("Every benchmark record must end with a user message") return messages def load_suite(args: argparse.Namespace, token: str) -> list[dict[str, Any]]: dataset = load_dataset( args.dataset_id, split="test", revision=args.dataset_revision, token=token, ) records: list[dict[str, Any]] = [] for index, raw in enumerate(dataset, 1): record = dict(raw) if "id" not in record: record["id"] = f"{record.get('category', 'item')}-{index:04d}" if "version" not in record: record["version"] = "1.2" record["messages"] = normalize_messages(record["messages"]) record["evaluator"] = json.loads(record.pop("evaluator_json")) records.append(record) validate_suite(records, require_complete=True) return records[: args.limit] if args.limit is not None else records def validate_suite(records: list[dict[str, Any]], *, require_complete: bool) -> None: required = { "category", "difficulty", "category_weight", "difficulty_weight", "item_elo", "messages", "evaluator", "max_new_tokens", "tags", } ids: set[str] = set() for record in records: missing = required - set(record) if missing: raise ValueError(f"{record.get('id', '')} is missing fields: {sorted(missing)}") if record["id"] in ids: raise ValueError(f"Duplicate benchmark ID: {record['id']}") ids.add(record["id"]) normalize_messages(record["messages"]) if record["difficulty"] not in EXPECTED_DIFFICULTIES: raise ValueError(f"Unknown difficulty in {record['id']}: {record['difficulty']}") if not require_complete: return categories = Counter(record["category"] for record in records) difficulties = Counter(record["difficulty"] for record in records) if len(records) != EXPECTED_CASES: raise ValueError(f"Expected {EXPECTED_CASES} dataset cases, found {len(records)}") if dict(categories) != EXPECTED_CATEGORIES: raise ValueError(f"Category counts differ: {dict(categories)} != {EXPECTED_CATEGORIES}") if dict(difficulties) != EXPECTED_DIFFICULTIES: raise ValueError(f"Difficulty counts differ: {dict(difficulties)} != {EXPECTED_DIFFICULTIES}") def folded(text: str) -> str: value = unicodedata.normalize("NFKD", text) value = "".join(char for char in value if not unicodedata.combining(char)) return " ".join(value.strip().split()) def loose_exact(text: str) -> str: return folded(text).strip(" \t\r\n.!`'\"").casefold() def extract_code(text: str) -> str: match = re.search(r"```(?:python)?\s*\n?(.*?)```", text, flags=re.I | re.S) return match.group(1).strip() if match else text.strip() def evaluate(text: str, spec: dict[str, Any]) -> tuple[bool, dict[str, Any]]: kind = spec["type"] if kind == "exact": actual = loose_exact(text) expected = loose_exact(str(spec["value"])) return actual == expected, {"actual": actual, "expected": expected} if kind in {"contains_any", "contains_all", "not_contains"}: actual = folded(text).casefold() found = {value: folded(str(value)).casefold() in actual for value in spec["values"]} passed = any(found.values()) if kind == "contains_any" else all(found.values()) if kind == "not_contains": passed = not any(found.values()) return passed, {"found": found} if kind == "number": matches = re.findall(r"(? dict[str, torch.Tensor]: if self.tokenizer.chat_template: encoded = self.tokenizer.apply_chat_template( messages, add_generation_prompt=True, return_tensors="pt", return_dict=True, ) else: instruction = messages[-1]["content"] prior = "\n".join(f"{message['role'].capitalize()}: {message['content']}" for message in messages[:-1]) prompt = "Below is an instruction that describes a task" if prior: prompt += ", paired with an input that provides further context" prompt += ". Write a response that appropriately completes the request.\n\n" prompt += f"### Instruction:\n{instruction}\n\n" if prior: prompt += f"### Input:\n{prior}\n\n" prompt += "### Response:\n" encoded = self.tokenizer(prompt, return_tensors="pt") return {name: tensor.to(self.device) for name, tensor in encoded.items()} @torch.inference_mode() def run(self, record: dict[str, Any]) -> dict[str, Any]: started = time.monotonic() inputs = self.encode(record["messages"]) input_tokens = int(inputs["input_ids"].shape[1]) available = self.context_length - input_tokens if available <= 0: return { "text": "", "input_tokens": input_tokens, "generated_tokens": 0, "natural_eos": False, "hit_limit": False, "context_overflow": True, "elapsed_seconds": time.monotonic() - started, } limit = min(int(record["max_new_tokens"]), available) output = self.model.generate( **inputs, max_new_tokens=limit, do_sample=False, repetition_penalty=self.args.repetition_penalty, pad_token_id=self.tokenizer.eos_token_id, eos_token_id=self.tokenizer.eos_token_id, use_cache=self.args.use_cache, ) generated_ids = output[0, input_tokens:] ended = bool(generated_ids.numel() and generated_ids[-1].item() == self.tokenizer.eos_token_id) return { "text": self.tokenizer.decode(generated_ids, skip_special_tokens=True).strip(), "input_tokens": input_tokens, "generated_tokens": int(generated_ids.numel()), "natural_eos": ended, "hit_limit": int(generated_ids.numel()) == limit and not ended, "context_overflow": False, "elapsed_seconds": time.monotonic() - started, } def expected_score(model_elo: float, item_elo: float) -> float: return 1.0 / (1.0 + 10.0 ** ((item_elo - model_elo) / ELO_SCALE)) def estimate_elo(results: list[dict[str, Any]]) -> float: if not results: return ELO_PRIOR_RATING def residual(rating: float) -> float: prior = ELO_PRIOR_WEIGHT * (0.5 - expected_score(rating, ELO_PRIOR_RATING)) games = sum( result["point_weight"] * ((1.0 if result["passed"] else 0.0) - expected_score(rating, result["item_elo"])) for result in results ) return prior + games low, high = 0.0, 3_000.0 for _ in range(80): middle = (low + high) / 2.0 if residual(middle) > 0: low = middle else: high = middle return (low + high) / 2.0 def summarize_group(results: list[dict[str, Any]]) -> dict[str, Any]: passed = sum(bool(result["passed"]) for result in results) possible = sum(result["point_weight"] for result in results) earned = sum(result["earned_points"] for result in results) return { "cases": len(results), "passed": passed, "pass_rate": passed / len(results) if results else 0.0, "weighted_points": earned, "possible_weighted_points": possible, "weighted_score": earned / possible if possible else 0.0, "elo": round(estimate_elo(results)), "elo_unrounded": estimate_elo(results), } def summarize(results: list[dict[str, Any]], *, official: bool) -> dict[str, Any]: categories: dict[str, list[dict[str, Any]]] = defaultdict(list) difficulties: dict[str, list[dict[str, Any]]] = defaultdict(list) for result in results: categories[result["category"]].append(result) difficulties[result["difficulty"]].append(result) summary = summarize_group(results) summary.update( { "official_complete_run": official, "overall_elo": summary.pop("elo"), "overall_elo_unrounded": summary.pop("elo_unrounded"), "categories": {name: summarize_group(items) for name, items in categories.items()}, "difficulties": {name: summarize_group(items) for name, items in difficulties.items()}, "natural_eos_count": sum(bool(result["natural_eos"]) for result in results), "generation_limit_hits": sum(bool(result["hit_limit"]) for result in results), "context_overflows": sum(bool(result["context_overflow"]) for result in results), } ) return summary def read_partial(path: Path) -> dict[str, dict[str, Any]]: if not path.exists(): return {} results: dict[str, dict[str, Any]] = {} with path.open(encoding="utf-8") as handle: for line in handle: if line.strip(): result = json.loads(line) results[result["id"]] = result return results def write_outputs( args: argparse.Namespace, runner: ModelRunner, results: list[dict[str, Any]], *, official: bool, ) -> tuple[Path, Path]: summary = summarize(results, official=official) report = { "created_at": datetime.now(timezone.utc).isoformat(), "benchmark": "BananaMind Instruct Bench 1.2", "dataset_id": args.dataset_id, "dataset_revision": args.dataset_revision, "model": args.model, "device": str(runner.device), "prompt_format": runner.prompt_format, "generation_settings": { "do_sample": False, "repetition_penalty": args.repetition_penalty, "use_cache": args.use_cache, "seed": args.seed, }, "elo": { "scale": ELO_SCALE, "prior_rating": ELO_PRIOR_RATING, "prior_weight": ELO_PRIOR_WEIGHT, "method": "weighted fixed-item logistic maximum-likelihood rating", }, "summary": summary, "results": results, } report_path = args.out_dir / "report.json" report_path.write_text(json.dumps(report, indent=2, ensure_ascii=True) + "\n") lines = [ "# BananaMind Instruct Bench 1.2", "", f"**Model:** {args.model}", f"**Overall Elo:** {summary['overall_elo']}", f"**Raw pass rate:** {summary['passed']}/{summary['cases']} ({summary['pass_rate']:.2%})", f"**Weighted score:** {summary['weighted_score']:.2%}", f"**Official complete run:** {'yes' if official else 'no'}", "", ] for index, result in enumerate(results, 1): lines.extend( [ f"## {index:04d}. {result['id']}", "", f"**Result:** {'PASS' if result['passed'] else 'FAIL'} | " f"**Difficulty:** {result['difficulty']} | **Item Elo:** {result['item_elo']}", "", "**Assistant:**", "", result["text"], "", ] ) transcript_path = args.out_dir / "transcript.md" transcript_path.write_text("\n".join(lines)) return report_path, transcript_path def main() -> None: args = parse_args() if args.limit is not None and not 1 <= args.limit <= EXPECTED_CASES: raise ValueError(f"--limit must be between 1 and {EXPECTED_CASES}") args.out_dir.mkdir(parents=True, exist_ok=True) partial_path = args.out_dir / "partial_results.jsonl" if partial_path.exists() and not args.resume: partial_path.unlink() token = resolve_hf_token(args) records = load_suite(args, token) runner = ModelRunner(args, token) completed = read_partial(partial_path) if args.resume else {} expected_ids = {record["id"] for record in records} completed = {key: value for key, value in completed.items() if key in expected_ids} with partial_path.open("a", encoding="utf-8") as partial: for index, record in enumerate(records, 1): if record["id"] in completed: print(f"[{index:04d}/{len(records):04d}] RESUME {record['id']}", flush=True) continue generation = runner.run(record) if generation["context_overflow"]: passed, evaluation = False, {"error": "input exceeds model context length"} else: passed, evaluation = evaluate(generation["text"], record["evaluator"]) point_weight = float(record["category_weight"]) * float(record["difficulty_weight"]) result = { "id": record["id"], "category": record["category"], "difficulty": record["difficulty"], "category_weight": float(record["category_weight"]), "difficulty_weight": float(record["difficulty_weight"]), "point_weight": point_weight, "earned_points": point_weight if passed else 0.0, "item_elo": int(record["item_elo"]), "messages": record["messages"], **generation, "passed": passed, "evaluation": evaluation, } completed[record["id"]] = result partial.write(json.dumps(result, ensure_ascii=True) + "\n") partial.flush() print( f"[{index:04d}/{len(records):04d}] {'PASS' if passed else 'FAIL'} " f"{record['id']} ({record['difficulty']}, Elo {record['item_elo']})", flush=True, ) ordered_results = [completed[record["id"]] for record in records] official = len(records) == EXPECTED_CASES and len(ordered_results) == EXPECTED_CASES report_path, transcript_path = write_outputs(args, runner, ordered_results, official=official) summary = summarize(ordered_results, official=official) print("\nBananaMind Instruct Bench 1.2") print(f"Overall Elo: {summary['overall_elo']}") print(f"Raw: {summary['passed']}/{summary['cases']} ({summary['pass_rate']:.2%})") print(f"Weighted score: {summary['weighted_score']:.2%}") for category in EXPECTED_CATEGORIES: group = summary["categories"].get(category) if group: print( f"{category}: Elo {group['elo']} | {group['passed']}/{group['cases']} " f"({group['pass_rate']:.2%}) | weighted {group['weighted_score']:.2%}" ) if not official: print(f"NON-OFFICIAL: this was not a complete {EXPECTED_CASES}-case run.") print(f"Report: {report_path}") print(f"Transcript: {transcript_path}") if __name__ == "__main__": try: main() except KeyboardInterrupt: print("\nInterrupted. Re-run with --resume to continue.", file=sys.stderr) raise SystemExit(130)