File size: 25,078 Bytes
e6a5f2a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 | #!/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', '<unknown>')} 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"(?<![\w.])-?\d+(?:\.\d+)?", text.replace(",", ""))
actual = float(matches[-1]) if matches else None
expected = float(spec["value"])
passed = actual is not None and math.isclose(actual, expected, rel_tol=0.0, abs_tol=1e-9)
return passed, {"last_number": actual, "expected": expected}
if kind == "regex":
matched = [bool(re.search(pattern, text, flags=re.I | re.S)) for pattern in spec["patterns"]]
passed = all(matched) if spec.get("mode", "any") == "all" else any(matched)
return passed, {"matched": matched, "patterns": spec["patterns"]}
if kind == "json_exact":
candidate = text.strip()
if candidate.startswith("```"):
candidate = re.sub(r"^```(?:json)?\s*|\s*```$", "", candidate, flags=re.I)
try:
parsed = json.loads(candidate)
except json.JSONDecodeError as error:
return False, {"json_error": str(error)}
return parsed == spec["value"], {"parsed": parsed, "expected": spec["value"]}
if kind == "sentence_count":
sentences = [part for part in re.split(r"[.!?]+(?:\s+|$)", text.strip()) if part.strip()]
return len(sentences) == spec["count"], {"sentence_count": len(sentences), "expected": spec["count"]}
if kind == "word_count":
words = re.findall(r"\b[\w'-]+\b", text, flags=re.UNICODE)
return len(words) == spec["count"], {"word_count": len(words), "expected": spec["count"]}
if kind == "bullet_count":
bullets = re.findall(r"(?m)^\s*(?:[-*]|\d+[.)])\s+", text)
required = {term: folded(term).casefold() in folded(text).casefold() for term in spec.get("required", [])}
passed = len(bullets) == spec["count"] and all(required.values())
return passed, {"bullet_count": len(bullets), "expected": spec["count"], "required": required}
if kind == "lines_exact":
lines = [loose_exact(line) for line in text.splitlines() if line.strip()]
expected = [loose_exact(line) for line in spec["values"]]
return lines == expected, {"lines": lines, "expected": expected}
if kind == "code":
code = extract_code(text)
try:
ast.parse(code)
syntax_valid, syntax_error = True, None
except SyntaxError as error:
syntax_valid, syntax_error = False, str(error)
matched = [bool(re.search(pattern, code, flags=re.I | re.S)) for pattern in spec["patterns"]]
patterns_pass = all(matched) if spec.get("mode", "any") == "all" else any(matched)
return syntax_valid and patterns_pass, {
"code": code,
"syntax_valid": syntax_valid,
"syntax_error": syntax_error,
"matched": matched,
"patterns": spec["patterns"],
}
if kind in {"all", "any"}:
outcomes = [evaluate(text, child) for child in spec["evaluators"]]
flags = [outcome[0] for outcome in outcomes]
passed = all(flags) if kind == "all" else any(flags)
return passed, {"subtests": [details | {"passed": flag} for flag, details in outcomes]}
raise ValueError(f"Unsupported evaluator type: {kind}")
class ModelRunner:
def __init__(self, args: argparse.Namespace, token: str):
self.args = args
if args.device == "auto":
args.device = "cuda" if torch.cuda.is_available() else "cpu"
self.device = torch.device(args.device)
torch.manual_seed(args.seed)
torch.set_num_threads(args.threads)
torch.set_float32_matmul_precision("high")
if args.dtype == "auto":
dtype = torch.bfloat16 if self.device.type == "cuda" and torch.cuda.is_bf16_supported() else torch.float32
else:
dtype = {
"float32": torch.float32,
"bfloat16": torch.bfloat16,
"float16": torch.float16,
}[args.dtype]
local = Path(args.model).is_dir()
common = {
"trust_remote_code": args.trust_remote_code,
"local_files_only": local,
"token": None if local else token,
}
print(f"Loading {args.model} on {self.device} as {dtype}...", flush=True)
self.tokenizer = AutoTokenizer.from_pretrained(args.model, **common)
self.model = AutoModelForCausalLM.from_pretrained(args.model, dtype=dtype, **common).to(self.device).eval()
self.prompt_format = "native_chat_template" if self.tokenizer.chat_template else "alpaca_instruction_fallback"
context_candidates = [
getattr(self.model.config, "max_position_embeddings", None),
getattr(self.model.config, "n_positions", None),
]
self.context_length = next((int(value) for value in context_candidates if value), 4096)
def encode(self, messages: list[dict[str, str]]) -> 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) |