MoreThought commited on
Commit
e6a5f2a
·
verified ·
1 Parent(s): add22f6

Upload 2 files

Browse files
Files changed (2) hide show
  1. Test.jsonl +0 -0
  2. benchmark.py +592 -0
Test.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
benchmark.py ADDED
@@ -0,0 +1,592 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import ast
7
+ import getpass
8
+ import json
9
+ import math
10
+ import os
11
+ import re
12
+ import sys
13
+ import time
14
+ import unicodedata
15
+ from collections import Counter, defaultdict
16
+ from datetime import datetime, timezone
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ import torch
21
+ from datasets import load_dataset
22
+ from huggingface_hub import HfApi, get_token, hf_hub_download
23
+ from huggingface_hub.errors import HfHubHTTPError
24
+ from transformers import AutoModelForCausalLM, AutoTokenizer
25
+
26
+
27
+ DATASET_ID = "ArrowLabs/ArrowBench-Instruct"
28
+ EXPECTED_CASES = 1000
29
+ EXPECTED_CATEGORIES = {
30
+ "general": 350,
31
+ "multi_turn": 250,
32
+ "system_prompts": 200,
33
+ "recall_in_context": 120,
34
+ "code": 80,
35
+ }
36
+ EXPECTED_DIFFICULTIES = {"easy": 200, "medium": 400, "hard": 400}
37
+ ELO_SCALE = 400.0
38
+ ELO_PRIOR_RATING = 1_000.0
39
+ ELO_PRIOR_WEIGHT = 4.0
40
+
41
+
42
+ def parse_args() -> argparse.Namespace:
43
+ parser = argparse.ArgumentParser(description=__doc__)
44
+ parser.add_argument("--model", required=True, help="Local model directory or Hugging Face model ID.")
45
+ parser.add_argument("--out-dir", type=Path, default=Path("runs/bananamind-instruct-bench-1.2"))
46
+ parser.add_argument("--dataset-id", default=DATASET_ID)
47
+ parser.add_argument("--dataset-revision", default="main")
48
+ parser.add_argument(
49
+ "--hf-token",
50
+ default=os.environ.get("HF_TOKEN"),
51
+ help="Optional token. Omit this to use `hf auth login`; inaccessible tokens trigger a hidden CLI prompt.",
52
+ )
53
+ parser.add_argument("--device", default="auto", help="auto, cpu, cuda, cuda:0, etc.")
54
+ parser.add_argument(
55
+ "--dtype",
56
+ choices=("auto", "float32", "bfloat16", "float16"),
57
+ default="auto",
58
+ )
59
+ parser.add_argument("--threads", type=int, default=16)
60
+ parser.add_argument("--seed", type=int, default=42)
61
+ parser.add_argument("--repetition-penalty", type=float, default=1.1)
62
+ parser.add_argument("--use-cache", action=argparse.BooleanOptionalAction, default=True)
63
+ parser.add_argument("--trust-remote-code", action=argparse.BooleanOptionalAction, default=True)
64
+ parser.add_argument("--resume", action="store_true")
65
+ parser.add_argument(
66
+ "--limit",
67
+ type=int,
68
+ default=None,
69
+ help="Developer smoke-test limit. A limited run is explicitly marked non-official.",
70
+ )
71
+ return parser.parse_args()
72
+
73
+
74
+ def access_error(error: BaseException) -> bool:
75
+ if not isinstance(error, HfHubHTTPError):
76
+ return False
77
+ response = getattr(error, "response", None)
78
+ return response is not None and response.status_code in {401, 403, 404}
79
+
80
+
81
+ def token_has_dataset_access(token: str | None, dataset_id: str, revision: str) -> bool:
82
+ if not token:
83
+ return False
84
+ try:
85
+ HfApi().whoami(token=token)
86
+ hf_hub_download(
87
+ repo_id=dataset_id,
88
+ filename="data/test.jsonl",
89
+ repo_type="dataset",
90
+ revision=revision,
91
+ token=token,
92
+ )
93
+ return True
94
+ except HfHubHTTPError as error:
95
+ if access_error(error):
96
+ return False
97
+ raise RuntimeError(f"Could not contact Hugging Face while checking dataset access: {error}") from error
98
+
99
+
100
+ def resolve_hf_token(args: argparse.Namespace) -> str:
101
+ candidates: list[tuple[str, str | None]] = [
102
+ ("--hf-token/HF_TOKEN", args.hf_token),
103
+ ("saved Hugging Face login", get_token()),
104
+ ]
105
+ seen: set[str] = set()
106
+ for source, candidate in candidates:
107
+ if not candidate or candidate in seen:
108
+ continue
109
+ seen.add(candidate)
110
+ print(f"Checking {source} access to {args.dataset_id}...", flush=True)
111
+ if token_has_dataset_access(candidate, args.dataset_id, args.dataset_revision):
112
+ print("Dataset access confirmed.", flush=True)
113
+ return candidate
114
+ print(f"The {source} token cannot access the gated dataset.", flush=True)
115
+
116
+ for attempt in range(1, 4):
117
+ try:
118
+ candidate = getpass.getpass(
119
+ f"Hugging Face token with access to {args.dataset_id} (attempt {attempt}/3): "
120
+ ).strip()
121
+ except (EOFError, KeyboardInterrupt) as error:
122
+ raise RuntimeError(
123
+ "A Hugging Face token is required. Run `hf auth login` or pass --hf-token."
124
+ ) from error
125
+ if not candidate:
126
+ continue
127
+ if token_has_dataset_access(candidate, args.dataset_id, args.dataset_revision):
128
+ print("Dataset access confirmed. The prompted token is used only for this process.", flush=True)
129
+ return candidate
130
+ print("That token does not have access to the gated dataset.", flush=True)
131
+ raise RuntimeError(
132
+ f"No token with access to {args.dataset_id} was provided. Accept the dataset gate first."
133
+ )
134
+
135
+
136
+ def normalize_messages(value: Any) -> list[dict[str, str]]:
137
+ if isinstance(value, dict) and set(value) >= {"role", "content"}:
138
+ value = [dict(role=role, content=content) for role, content in zip(value["role"], value["content"])]
139
+ messages = [{"role": str(item["role"]), "content": str(item["content"])} for item in value]
140
+ if not messages or messages[-1]["role"] != "user":
141
+ raise ValueError("Every benchmark record must end with a user message")
142
+ return messages
143
+
144
+
145
+ def load_suite(args: argparse.Namespace, token: str) -> list[dict[str, Any]]:
146
+ dataset = load_dataset(
147
+ args.dataset_id,
148
+ split="test",
149
+ revision=args.dataset_revision,
150
+ token=token,
151
+ )
152
+ records: list[dict[str, Any]] = []
153
+ for index, raw in enumerate(dataset, 1):
154
+ record = dict(raw)
155
+ if "id" not in record:
156
+ record["id"] = f"{record.get('category', 'item')}-{index:04d}"
157
+ if "version" not in record:
158
+ record["version"] = "1.2"
159
+ record["messages"] = normalize_messages(record["messages"])
160
+ record["evaluator"] = json.loads(record.pop("evaluator_json"))
161
+ records.append(record)
162
+ validate_suite(records, require_complete=True)
163
+ return records[: args.limit] if args.limit is not None else records
164
+
165
+
166
+ def validate_suite(records: list[dict[str, Any]], *, require_complete: bool) -> None:
167
+ required = {
168
+ "category", "difficulty", "category_weight",
169
+ "difficulty_weight", "item_elo", "messages", "evaluator",
170
+ "max_new_tokens", "tags",
171
+ }
172
+ ids: set[str] = set()
173
+ for record in records:
174
+ missing = required - set(record)
175
+ if missing:
176
+ raise ValueError(f"{record.get('id', '<unknown>')} is missing fields: {sorted(missing)}")
177
+ if record["id"] in ids:
178
+ raise ValueError(f"Duplicate benchmark ID: {record['id']}")
179
+ ids.add(record["id"])
180
+ normalize_messages(record["messages"])
181
+ if record["difficulty"] not in EXPECTED_DIFFICULTIES:
182
+ raise ValueError(f"Unknown difficulty in {record['id']}: {record['difficulty']}")
183
+ if not require_complete:
184
+ return
185
+ categories = Counter(record["category"] for record in records)
186
+ difficulties = Counter(record["difficulty"] for record in records)
187
+ if len(records) != EXPECTED_CASES:
188
+ raise ValueError(f"Expected {EXPECTED_CASES} dataset cases, found {len(records)}")
189
+ if dict(categories) != EXPECTED_CATEGORIES:
190
+ raise ValueError(f"Category counts differ: {dict(categories)} != {EXPECTED_CATEGORIES}")
191
+ if dict(difficulties) != EXPECTED_DIFFICULTIES:
192
+ raise ValueError(f"Difficulty counts differ: {dict(difficulties)} != {EXPECTED_DIFFICULTIES}")
193
+
194
+
195
+ def folded(text: str) -> str:
196
+ value = unicodedata.normalize("NFKD", text)
197
+ value = "".join(char for char in value if not unicodedata.combining(char))
198
+ return " ".join(value.strip().split())
199
+
200
+
201
+ def loose_exact(text: str) -> str:
202
+ return folded(text).strip(" \t\r\n.!`'\"").casefold()
203
+
204
+
205
+ def extract_code(text: str) -> str:
206
+ match = re.search(r"```(?:python)?\s*\n?(.*?)```", text, flags=re.I | re.S)
207
+ return match.group(1).strip() if match else text.strip()
208
+
209
+
210
+ def evaluate(text: str, spec: dict[str, Any]) -> tuple[bool, dict[str, Any]]:
211
+ kind = spec["type"]
212
+ if kind == "exact":
213
+ actual = loose_exact(text)
214
+ expected = loose_exact(str(spec["value"]))
215
+ return actual == expected, {"actual": actual, "expected": expected}
216
+ if kind in {"contains_any", "contains_all", "not_contains"}:
217
+ actual = folded(text).casefold()
218
+ found = {value: folded(str(value)).casefold() in actual for value in spec["values"]}
219
+ passed = any(found.values()) if kind == "contains_any" else all(found.values())
220
+ if kind == "not_contains":
221
+ passed = not any(found.values())
222
+ return passed, {"found": found}
223
+ if kind == "number":
224
+ matches = re.findall(r"(?<![\w.])-?\d+(?:\.\d+)?", text.replace(",", ""))
225
+ actual = float(matches[-1]) if matches else None
226
+ expected = float(spec["value"])
227
+ passed = actual is not None and math.isclose(actual, expected, rel_tol=0.0, abs_tol=1e-9)
228
+ return passed, {"last_number": actual, "expected": expected}
229
+ if kind == "regex":
230
+ matched = [bool(re.search(pattern, text, flags=re.I | re.S)) for pattern in spec["patterns"]]
231
+ passed = all(matched) if spec.get("mode", "any") == "all" else any(matched)
232
+ return passed, {"matched": matched, "patterns": spec["patterns"]}
233
+ if kind == "json_exact":
234
+ candidate = text.strip()
235
+ if candidate.startswith("```"):
236
+ candidate = re.sub(r"^```(?:json)?\s*|\s*```$", "", candidate, flags=re.I)
237
+ try:
238
+ parsed = json.loads(candidate)
239
+ except json.JSONDecodeError as error:
240
+ return False, {"json_error": str(error)}
241
+ return parsed == spec["value"], {"parsed": parsed, "expected": spec["value"]}
242
+ if kind == "sentence_count":
243
+ sentences = [part for part in re.split(r"[.!?]+(?:\s+|$)", text.strip()) if part.strip()]
244
+ return len(sentences) == spec["count"], {"sentence_count": len(sentences), "expected": spec["count"]}
245
+ if kind == "word_count":
246
+ words = re.findall(r"\b[\w'-]+\b", text, flags=re.UNICODE)
247
+ return len(words) == spec["count"], {"word_count": len(words), "expected": spec["count"]}
248
+ if kind == "bullet_count":
249
+ bullets = re.findall(r"(?m)^\s*(?:[-*]|\d+[.)])\s+", text)
250
+ required = {term: folded(term).casefold() in folded(text).casefold() for term in spec.get("required", [])}
251
+ passed = len(bullets) == spec["count"] and all(required.values())
252
+ return passed, {"bullet_count": len(bullets), "expected": spec["count"], "required": required}
253
+ if kind == "lines_exact":
254
+ lines = [loose_exact(line) for line in text.splitlines() if line.strip()]
255
+ expected = [loose_exact(line) for line in spec["values"]]
256
+ return lines == expected, {"lines": lines, "expected": expected}
257
+ if kind == "code":
258
+ code = extract_code(text)
259
+ try:
260
+ ast.parse(code)
261
+ syntax_valid, syntax_error = True, None
262
+ except SyntaxError as error:
263
+ syntax_valid, syntax_error = False, str(error)
264
+ matched = [bool(re.search(pattern, code, flags=re.I | re.S)) for pattern in spec["patterns"]]
265
+ patterns_pass = all(matched) if spec.get("mode", "any") == "all" else any(matched)
266
+ return syntax_valid and patterns_pass, {
267
+ "code": code,
268
+ "syntax_valid": syntax_valid,
269
+ "syntax_error": syntax_error,
270
+ "matched": matched,
271
+ "patterns": spec["patterns"],
272
+ }
273
+ if kind in {"all", "any"}:
274
+ outcomes = [evaluate(text, child) for child in spec["evaluators"]]
275
+ flags = [outcome[0] for outcome in outcomes]
276
+ passed = all(flags) if kind == "all" else any(flags)
277
+ return passed, {"subtests": [details | {"passed": flag} for flag, details in outcomes]}
278
+ raise ValueError(f"Unsupported evaluator type: {kind}")
279
+
280
+
281
+ class ModelRunner:
282
+ def __init__(self, args: argparse.Namespace, token: str):
283
+ self.args = args
284
+ if args.device == "auto":
285
+ args.device = "cuda" if torch.cuda.is_available() else "cpu"
286
+ self.device = torch.device(args.device)
287
+ torch.manual_seed(args.seed)
288
+ torch.set_num_threads(args.threads)
289
+ torch.set_float32_matmul_precision("high")
290
+ if args.dtype == "auto":
291
+ dtype = torch.bfloat16 if self.device.type == "cuda" and torch.cuda.is_bf16_supported() else torch.float32
292
+ else:
293
+ dtype = {
294
+ "float32": torch.float32,
295
+ "bfloat16": torch.bfloat16,
296
+ "float16": torch.float16,
297
+ }[args.dtype]
298
+ local = Path(args.model).is_dir()
299
+ common = {
300
+ "trust_remote_code": args.trust_remote_code,
301
+ "local_files_only": local,
302
+ "token": None if local else token,
303
+ }
304
+ print(f"Loading {args.model} on {self.device} as {dtype}...", flush=True)
305
+ self.tokenizer = AutoTokenizer.from_pretrained(args.model, **common)
306
+ self.model = AutoModelForCausalLM.from_pretrained(args.model, dtype=dtype, **common).to(self.device).eval()
307
+ self.prompt_format = "native_chat_template" if self.tokenizer.chat_template else "alpaca_instruction_fallback"
308
+ context_candidates = [
309
+ getattr(self.model.config, "max_position_embeddings", None),
310
+ getattr(self.model.config, "n_positions", None),
311
+ ]
312
+ self.context_length = next((int(value) for value in context_candidates if value), 4096)
313
+
314
+ def encode(self, messages: list[dict[str, str]]) -> dict[str, torch.Tensor]:
315
+ if self.tokenizer.chat_template:
316
+ encoded = self.tokenizer.apply_chat_template(
317
+ messages,
318
+ add_generation_prompt=True,
319
+ return_tensors="pt",
320
+ return_dict=True,
321
+ )
322
+ else:
323
+ instruction = messages[-1]["content"]
324
+ prior = "\n".join(f"{message['role'].capitalize()}: {message['content']}" for message in messages[:-1])
325
+ prompt = "Below is an instruction that describes a task"
326
+ if prior:
327
+ prompt += ", paired with an input that provides further context"
328
+ prompt += ". Write a response that appropriately completes the request.\n\n"
329
+ prompt += f"### Instruction:\n{instruction}\n\n"
330
+ if prior:
331
+ prompt += f"### Input:\n{prior}\n\n"
332
+ prompt += "### Response:\n"
333
+ encoded = self.tokenizer(prompt, return_tensors="pt")
334
+ return {name: tensor.to(self.device) for name, tensor in encoded.items()}
335
+
336
+ @torch.inference_mode()
337
+ def run(self, record: dict[str, Any]) -> dict[str, Any]:
338
+ started = time.monotonic()
339
+ inputs = self.encode(record["messages"])
340
+ input_tokens = int(inputs["input_ids"].shape[1])
341
+ available = self.context_length - input_tokens
342
+ if available <= 0:
343
+ return {
344
+ "text": "",
345
+ "input_tokens": input_tokens,
346
+ "generated_tokens": 0,
347
+ "natural_eos": False,
348
+ "hit_limit": False,
349
+ "context_overflow": True,
350
+ "elapsed_seconds": time.monotonic() - started,
351
+ }
352
+ limit = min(int(record["max_new_tokens"]), available)
353
+ output = self.model.generate(
354
+ **inputs,
355
+ max_new_tokens=limit,
356
+ do_sample=False,
357
+ repetition_penalty=self.args.repetition_penalty,
358
+ pad_token_id=self.tokenizer.eos_token_id,
359
+ eos_token_id=self.tokenizer.eos_token_id,
360
+ use_cache=self.args.use_cache,
361
+ )
362
+ generated_ids = output[0, input_tokens:]
363
+ ended = bool(generated_ids.numel() and generated_ids[-1].item() == self.tokenizer.eos_token_id)
364
+ return {
365
+ "text": self.tokenizer.decode(generated_ids, skip_special_tokens=True).strip(),
366
+ "input_tokens": input_tokens,
367
+ "generated_tokens": int(generated_ids.numel()),
368
+ "natural_eos": ended,
369
+ "hit_limit": int(generated_ids.numel()) == limit and not ended,
370
+ "context_overflow": False,
371
+ "elapsed_seconds": time.monotonic() - started,
372
+ }
373
+
374
+
375
+ def expected_score(model_elo: float, item_elo: float) -> float:
376
+ return 1.0 / (1.0 + 10.0 ** ((item_elo - model_elo) / ELO_SCALE))
377
+
378
+
379
+ def estimate_elo(results: list[dict[str, Any]]) -> float:
380
+ if not results:
381
+ return ELO_PRIOR_RATING
382
+
383
+ def residual(rating: float) -> float:
384
+ prior = ELO_PRIOR_WEIGHT * (0.5 - expected_score(rating, ELO_PRIOR_RATING))
385
+ games = sum(
386
+ result["point_weight"]
387
+ * ((1.0 if result["passed"] else 0.0) - expected_score(rating, result["item_elo"]))
388
+ for result in results
389
+ )
390
+ return prior + games
391
+
392
+ low, high = 0.0, 3_000.0
393
+ for _ in range(80):
394
+ middle = (low + high) / 2.0
395
+ if residual(middle) > 0:
396
+ low = middle
397
+ else:
398
+ high = middle
399
+ return (low + high) / 2.0
400
+
401
+
402
+ def summarize_group(results: list[dict[str, Any]]) -> dict[str, Any]:
403
+ passed = sum(bool(result["passed"]) for result in results)
404
+ possible = sum(result["point_weight"] for result in results)
405
+ earned = sum(result["earned_points"] for result in results)
406
+ return {
407
+ "cases": len(results),
408
+ "passed": passed,
409
+ "pass_rate": passed / len(results) if results else 0.0,
410
+ "weighted_points": earned,
411
+ "possible_weighted_points": possible,
412
+ "weighted_score": earned / possible if possible else 0.0,
413
+ "elo": round(estimate_elo(results)),
414
+ "elo_unrounded": estimate_elo(results),
415
+ }
416
+
417
+
418
+ def summarize(results: list[dict[str, Any]], *, official: bool) -> dict[str, Any]:
419
+ categories: dict[str, list[dict[str, Any]]] = defaultdict(list)
420
+ difficulties: dict[str, list[dict[str, Any]]] = defaultdict(list)
421
+ for result in results:
422
+ categories[result["category"]].append(result)
423
+ difficulties[result["difficulty"]].append(result)
424
+ summary = summarize_group(results)
425
+ summary.update(
426
+ {
427
+ "official_complete_run": official,
428
+ "overall_elo": summary.pop("elo"),
429
+ "overall_elo_unrounded": summary.pop("elo_unrounded"),
430
+ "categories": {name: summarize_group(items) for name, items in categories.items()},
431
+ "difficulties": {name: summarize_group(items) for name, items in difficulties.items()},
432
+ "natural_eos_count": sum(bool(result["natural_eos"]) for result in results),
433
+ "generation_limit_hits": sum(bool(result["hit_limit"]) for result in results),
434
+ "context_overflows": sum(bool(result["context_overflow"]) for result in results),
435
+ }
436
+ )
437
+ return summary
438
+
439
+
440
+ def read_partial(path: Path) -> dict[str, dict[str, Any]]:
441
+ if not path.exists():
442
+ return {}
443
+ results: dict[str, dict[str, Any]] = {}
444
+ with path.open(encoding="utf-8") as handle:
445
+ for line in handle:
446
+ if line.strip():
447
+ result = json.loads(line)
448
+ results[result["id"]] = result
449
+ return results
450
+
451
+
452
+ def write_outputs(
453
+ args: argparse.Namespace,
454
+ runner: ModelRunner,
455
+ results: list[dict[str, Any]],
456
+ *,
457
+ official: bool,
458
+ ) -> tuple[Path, Path]:
459
+ summary = summarize(results, official=official)
460
+ report = {
461
+ "created_at": datetime.now(timezone.utc).isoformat(),
462
+ "benchmark": "BananaMind Instruct Bench 1.2",
463
+ "dataset_id": args.dataset_id,
464
+ "dataset_revision": args.dataset_revision,
465
+ "model": args.model,
466
+ "device": str(runner.device),
467
+ "prompt_format": runner.prompt_format,
468
+ "generation_settings": {
469
+ "do_sample": False,
470
+ "repetition_penalty": args.repetition_penalty,
471
+ "use_cache": args.use_cache,
472
+ "seed": args.seed,
473
+ },
474
+ "elo": {
475
+ "scale": ELO_SCALE,
476
+ "prior_rating": ELO_PRIOR_RATING,
477
+ "prior_weight": ELO_PRIOR_WEIGHT,
478
+ "method": "weighted fixed-item logistic maximum-likelihood rating",
479
+ },
480
+ "summary": summary,
481
+ "results": results,
482
+ }
483
+ report_path = args.out_dir / "report.json"
484
+ report_path.write_text(json.dumps(report, indent=2, ensure_ascii=True) + "\n")
485
+
486
+ lines = [
487
+ "# BananaMind Instruct Bench 1.2",
488
+ "",
489
+ f"**Model:** {args.model}",
490
+ f"**Overall Elo:** {summary['overall_elo']}",
491
+ f"**Raw pass rate:** {summary['passed']}/{summary['cases']} ({summary['pass_rate']:.2%})",
492
+ f"**Weighted score:** {summary['weighted_score']:.2%}",
493
+ f"**Official complete run:** {'yes' if official else 'no'}",
494
+ "",
495
+ ]
496
+ for index, result in enumerate(results, 1):
497
+ lines.extend(
498
+ [
499
+ f"## {index:04d}. {result['id']}",
500
+ "",
501
+ f"**Result:** {'PASS' if result['passed'] else 'FAIL'} | "
502
+ f"**Difficulty:** {result['difficulty']} | **Item Elo:** {result['item_elo']}",
503
+ "",
504
+ "**Assistant:**",
505
+ "",
506
+ result["text"],
507
+ "",
508
+ ]
509
+ )
510
+ transcript_path = args.out_dir / "transcript.md"
511
+ transcript_path.write_text("\n".join(lines))
512
+ return report_path, transcript_path
513
+
514
+
515
+ def main() -> None:
516
+ args = parse_args()
517
+ if args.limit is not None and not 1 <= args.limit <= EXPECTED_CASES:
518
+ raise ValueError(f"--limit must be between 1 and {EXPECTED_CASES}")
519
+ args.out_dir.mkdir(parents=True, exist_ok=True)
520
+ partial_path = args.out_dir / "partial_results.jsonl"
521
+ if partial_path.exists() and not args.resume:
522
+ partial_path.unlink()
523
+
524
+ token = resolve_hf_token(args)
525
+ records = load_suite(args, token)
526
+ runner = ModelRunner(args, token)
527
+ completed = read_partial(partial_path) if args.resume else {}
528
+ expected_ids = {record["id"] for record in records}
529
+ completed = {key: value for key, value in completed.items() if key in expected_ids}
530
+
531
+ with partial_path.open("a", encoding="utf-8") as partial:
532
+ for index, record in enumerate(records, 1):
533
+ if record["id"] in completed:
534
+ print(f"[{index:04d}/{len(records):04d}] RESUME {record['id']}", flush=True)
535
+ continue
536
+ generation = runner.run(record)
537
+ if generation["context_overflow"]:
538
+ passed, evaluation = False, {"error": "input exceeds model context length"}
539
+ else:
540
+ passed, evaluation = evaluate(generation["text"], record["evaluator"])
541
+ point_weight = float(record["category_weight"]) * float(record["difficulty_weight"])
542
+ result = {
543
+ "id": record["id"],
544
+ "category": record["category"],
545
+ "difficulty": record["difficulty"],
546
+ "category_weight": float(record["category_weight"]),
547
+ "difficulty_weight": float(record["difficulty_weight"]),
548
+ "point_weight": point_weight,
549
+ "earned_points": point_weight if passed else 0.0,
550
+ "item_elo": int(record["item_elo"]),
551
+ "messages": record["messages"],
552
+ **generation,
553
+ "passed": passed,
554
+ "evaluation": evaluation,
555
+ }
556
+ completed[record["id"]] = result
557
+ partial.write(json.dumps(result, ensure_ascii=True) + "\n")
558
+ partial.flush()
559
+ print(
560
+ f"[{index:04d}/{len(records):04d}] {'PASS' if passed else 'FAIL'} "
561
+ f"{record['id']} ({record['difficulty']}, Elo {record['item_elo']})",
562
+ flush=True,
563
+ )
564
+
565
+ ordered_results = [completed[record["id"]] for record in records]
566
+ official = len(records) == EXPECTED_CASES and len(ordered_results) == EXPECTED_CASES
567
+ report_path, transcript_path = write_outputs(args, runner, ordered_results, official=official)
568
+ summary = summarize(ordered_results, official=official)
569
+
570
+ print("\nBananaMind Instruct Bench 1.2")
571
+ print(f"Overall Elo: {summary['overall_elo']}")
572
+ print(f"Raw: {summary['passed']}/{summary['cases']} ({summary['pass_rate']:.2%})")
573
+ print(f"Weighted score: {summary['weighted_score']:.2%}")
574
+ for category in EXPECTED_CATEGORIES:
575
+ group = summary["categories"].get(category)
576
+ if group:
577
+ print(
578
+ f"{category}: Elo {group['elo']} | {group['passed']}/{group['cases']} "
579
+ f"({group['pass_rate']:.2%}) | weighted {group['weighted_score']:.2%}"
580
+ )
581
+ if not official:
582
+ print(f"NON-OFFICIAL: this was not a complete {EXPECTED_CASES}-case run.")
583
+ print(f"Report: {report_path}")
584
+ print(f"Transcript: {transcript_path}")
585
+
586
+
587
+ if __name__ == "__main__":
588
+ try:
589
+ main()
590
+ except KeyboardInterrupt:
591
+ print("\nInterrupted. Re-run with --resume to continue.", file=sys.stderr)
592
+ raise SystemExit(130)