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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import re
|
| 5 |
+
import subprocess
|
| 6 |
+
import sys
|
| 7 |
+
import tempfile
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
from datasets import load_dataset
|
| 13 |
+
from tqdm import tqdm
|
| 14 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
LM_EVAL_TASKS = {
|
| 18 |
+
"hellaswag": {
|
| 19 |
+
"display": "HellaSwag",
|
| 20 |
+
"task": "hellaswag",
|
| 21 |
+
"preferred_metrics": ["acc_norm", "acc_norm,none", "acc"],
|
| 22 |
+
},
|
| 23 |
+
"arc": {
|
| 24 |
+
"display": "ARC-Easy",
|
| 25 |
+
"task": "arc_easy",
|
| 26 |
+
"preferred_metrics": ["acc_norm", "acc_norm,none", "acc"],
|
| 27 |
+
},
|
| 28 |
+
"arcChall": {
|
| 29 |
+
"display": "ARC-Challenge",
|
| 30 |
+
"task": "arc_challenge",
|
| 31 |
+
"preferred_metrics": ["acc_norm", "acc_norm,none", "acc"],
|
| 32 |
+
},
|
| 33 |
+
"piqa": {
|
| 34 |
+
"display": "PIQA",
|
| 35 |
+
"task": "piqa",
|
| 36 |
+
"preferred_metrics": ["acc_norm", "acc_norm,none", "acc", "acc,none"],
|
| 37 |
+
},
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
OUR_BENCHMARK_DATASET = "WhirlwindAI/Benchmark-TEST"
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def die(msg: str, code: int = 1) -> None:
|
| 44 |
+
print(f"[ERROR] {msg}", file=sys.stderr)
|
| 45 |
+
sys.exit(code)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def run_cmd(cmd: List[str]) -> None:
|
| 49 |
+
print("\n[CMD]", " ".join(cmd), flush=True)
|
| 50 |
+
proc = subprocess.run(cmd)
|
| 51 |
+
if proc.returncode != 0:
|
| 52 |
+
die(f"Command failed with exit code {proc.returncode}")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def find_latest_json(path: Path) -> Path:
|
| 56 |
+
if path.is_file():
|
| 57 |
+
return path
|
| 58 |
+
|
| 59 |
+
json_files = list(path.rglob("*.json"))
|
| 60 |
+
if not json_files:
|
| 61 |
+
die(f"No JSON result file found in {path}")
|
| 62 |
+
|
| 63 |
+
json_files.sort(key=lambda p: p.stat().st_mtime, reverse=True)
|
| 64 |
+
return json_files[0]
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def load_json(path: Path) -> Dict[str, Any]:
|
| 68 |
+
with path.open("r", encoding="utf-8") as f:
|
| 69 |
+
return json.load(f)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def metric_from_result(task_result: Dict[str, Any], preferred: List[str]) -> Tuple[str, float]:
|
| 73 |
+
for key in preferred:
|
| 74 |
+
if key in task_result and isinstance(task_result[key], (int, float)):
|
| 75 |
+
return key, float(task_result[key])
|
| 76 |
+
|
| 77 |
+
for key, value in task_result.items():
|
| 78 |
+
if "acc_norm" in key and isinstance(value, (int, float)):
|
| 79 |
+
return key, float(value)
|
| 80 |
+
|
| 81 |
+
for key, value in task_result.items():
|
| 82 |
+
if key.startswith("acc") and isinstance(value, (int, float)):
|
| 83 |
+
return key, float(value)
|
| 84 |
+
|
| 85 |
+
die(f"Could not find accuracy metric in result: {task_result}")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def run_lm_eval(
|
| 89 |
+
model_id: str,
|
| 90 |
+
device: str,
|
| 91 |
+
dtype: str,
|
| 92 |
+
batch_size: str,
|
| 93 |
+
limit: Optional[int],
|
| 94 |
+
trust_remote_code: bool,
|
| 95 |
+
) -> Dict[str, Dict[str, Any]]:
|
| 96 |
+
tasks = ",".join(info["task"] for info in LM_EVAL_TASKS.values())
|
| 97 |
+
|
| 98 |
+
model_args = [
|
| 99 |
+
f"pretrained={model_id}",
|
| 100 |
+
f"dtype={dtype}",
|
| 101 |
+
]
|
| 102 |
+
|
| 103 |
+
if trust_remote_code:
|
| 104 |
+
model_args.append("trust_remote_code=True")
|
| 105 |
+
|
| 106 |
+
with tempfile.TemporaryDirectory(prefix="open_slm_lm_eval_") as tmp:
|
| 107 |
+
out_dir = Path(tmp)
|
| 108 |
+
|
| 109 |
+
cmd = [
|
| 110 |
+
sys.executable,
|
| 111 |
+
"-m",
|
| 112 |
+
"lm_eval",
|
| 113 |
+
"--model",
|
| 114 |
+
"hf",
|
| 115 |
+
"--model_args",
|
| 116 |
+
",".join(model_args),
|
| 117 |
+
"--tasks",
|
| 118 |
+
tasks,
|
| 119 |
+
"--device",
|
| 120 |
+
device,
|
| 121 |
+
"--batch_size",
|
| 122 |
+
batch_size,
|
| 123 |
+
"--output_path",
|
| 124 |
+
str(out_dir),
|
| 125 |
+
]
|
| 126 |
+
|
| 127 |
+
if limit is not None:
|
| 128 |
+
cmd.extend(["--limit", str(limit)])
|
| 129 |
+
|
| 130 |
+
run_cmd(cmd)
|
| 131 |
+
|
| 132 |
+
result_path = find_latest_json(out_dir)
|
| 133 |
+
raw = load_json(result_path)
|
| 134 |
+
|
| 135 |
+
if "results" not in raw:
|
| 136 |
+
die(f"Unexpected lm_eval JSON format. Top-level keys: {list(raw.keys())}")
|
| 137 |
+
|
| 138 |
+
return raw["results"]
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def normalize_percent(x: float) -> float:
|
| 142 |
+
if x <= 1.0:
|
| 143 |
+
return x * 100.0
|
| 144 |
+
return x
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def extract_lm_eval_scores(raw_results: Dict[str, Dict[str, Any]]) -> Dict[str, Dict[str, Any]]:
|
| 148 |
+
scores: Dict[str, Dict[str, Any]] = {}
|
| 149 |
+
|
| 150 |
+
for key, info in LM_EVAL_TASKS.items():
|
| 151 |
+
task_name = info["task"]
|
| 152 |
+
|
| 153 |
+
if task_name not in raw_results:
|
| 154 |
+
die(f"Task {task_name} not found in lm_eval results. Found: {list(raw_results.keys())}")
|
| 155 |
+
|
| 156 |
+
metric_name, value = metric_from_result(raw_results[task_name], info["preferred_metrics"])
|
| 157 |
+
|
| 158 |
+
scores[key] = {
|
| 159 |
+
"display": info["display"],
|
| 160 |
+
"task": task_name,
|
| 161 |
+
"metric": metric_name,
|
| 162 |
+
"score": normalize_percent(value),
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
return scores
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def count_params(model: torch.nn.Module) -> int:
|
| 169 |
+
return sum(p.numel() for p in model.parameters())
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def pick_first_present(ex: Dict[str, Any], names: List[str]) -> Optional[Any]:
|
| 173 |
+
for name in names:
|
| 174 |
+
if name in ex and ex[name] is not None:
|
| 175 |
+
return ex[name]
|
| 176 |
+
return None
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def normalize_choices(raw_choices: Any, ex: Dict[str, Any]) -> Optional[List[str]]:
|
| 180 |
+
if raw_choices is None:
|
| 181 |
+
letter_choices = []
|
| 182 |
+
for k in ["A", "B", "C", "D", "E"]:
|
| 183 |
+
if k in ex and ex[k] is not None:
|
| 184 |
+
letter_choices.append(str(ex[k]))
|
| 185 |
+
if len(letter_choices) >= 2:
|
| 186 |
+
return letter_choices
|
| 187 |
+
|
| 188 |
+
lower_choices = []
|
| 189 |
+
for k in ["choice_a", "choice_b", "choice_c", "choice_d", "choice_e"]:
|
| 190 |
+
if k in ex and ex[k] is not None:
|
| 191 |
+
lower_choices.append(str(ex[k]))
|
| 192 |
+
if len(lower_choices) >= 2:
|
| 193 |
+
return lower_choices
|
| 194 |
+
|
| 195 |
+
option_choices = []
|
| 196 |
+
for k in ["option_a", "option_b", "option_c", "option_d", "option_e"]:
|
| 197 |
+
if k in ex and ex[k] is not None:
|
| 198 |
+
option_choices.append(str(ex[k]))
|
| 199 |
+
if len(option_choices) >= 2:
|
| 200 |
+
return option_choices
|
| 201 |
+
|
| 202 |
+
return None
|
| 203 |
+
|
| 204 |
+
if isinstance(raw_choices, dict):
|
| 205 |
+
if "text" in raw_choices:
|
| 206 |
+
return [str(x) for x in raw_choices["text"]]
|
| 207 |
+
if "choices" in raw_choices:
|
| 208 |
+
return [str(x) for x in raw_choices["choices"]]
|
| 209 |
+
if "options" in raw_choices:
|
| 210 |
+
return [str(x) for x in raw_choices["options"]]
|
| 211 |
+
|
| 212 |
+
vals = []
|
| 213 |
+
for k in ["A", "B", "C", "D", "E"]:
|
| 214 |
+
if k in raw_choices:
|
| 215 |
+
vals.append(str(raw_choices[k]))
|
| 216 |
+
if len(vals) >= 2:
|
| 217 |
+
return vals
|
| 218 |
+
|
| 219 |
+
if isinstance(raw_choices, list):
|
| 220 |
+
return [str(x) for x in raw_choices]
|
| 221 |
+
|
| 222 |
+
return None
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def normalize_answer(raw_answer: Any, choices: List[str]) -> Optional[int]:
|
| 226 |
+
if raw_answer is None:
|
| 227 |
+
return None
|
| 228 |
+
|
| 229 |
+
if isinstance(raw_answer, bool):
|
| 230 |
+
return int(raw_answer)
|
| 231 |
+
|
| 232 |
+
if isinstance(raw_answer, int):
|
| 233 |
+
if 0 <= raw_answer < len(choices):
|
| 234 |
+
return raw_answer
|
| 235 |
+
if 1 <= raw_answer <= len(choices):
|
| 236 |
+
return raw_answer - 1
|
| 237 |
+
|
| 238 |
+
if isinstance(raw_answer, float) and raw_answer.is_integer():
|
| 239 |
+
return normalize_answer(int(raw_answer), choices)
|
| 240 |
+
|
| 241 |
+
ans = str(raw_answer).strip()
|
| 242 |
+
|
| 243 |
+
if len(ans) == 1 and ans.upper() in "ABCDE":
|
| 244 |
+
idx = ord(ans.upper()) - ord("A")
|
| 245 |
+
if 0 <= idx < len(choices):
|
| 246 |
+
return idx
|
| 247 |
+
|
| 248 |
+
if re.fullmatch(r"\d+", ans):
|
| 249 |
+
return normalize_answer(int(ans), choices)
|
| 250 |
+
|
| 251 |
+
for i, choice in enumerate(choices):
|
| 252 |
+
if ans == str(choice).strip():
|
| 253 |
+
return i
|
| 254 |
+
|
| 255 |
+
low = ans.lower()
|
| 256 |
+
for i, choice in enumerate(choices):
|
| 257 |
+
if low == str(choice).strip().lower():
|
| 258 |
+
return i
|
| 259 |
+
|
| 260 |
+
return None
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def build_our_benchmark_item(ex: Dict[str, Any]) -> Optional[Tuple[str, List[str], int]]:
|
| 264 |
+
prompt = pick_first_present(
|
| 265 |
+
ex,
|
| 266 |
+
[
|
| 267 |
+
"ctx",
|
| 268 |
+
"question",
|
| 269 |
+
"prompt",
|
| 270 |
+
"input",
|
| 271 |
+
"problem",
|
| 272 |
+
"query",
|
| 273 |
+
"text",
|
| 274 |
+
"instruction",
|
| 275 |
+
],
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
raw_choices = pick_first_present(
|
| 279 |
+
ex,
|
| 280 |
+
[
|
| 281 |
+
"endings",
|
| 282 |
+
"choices",
|
| 283 |
+
"options",
|
| 284 |
+
"answers",
|
| 285 |
+
"candidates",
|
| 286 |
+
"multiple_choice",
|
| 287 |
+
],
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
choices = normalize_choices(raw_choices, ex)
|
| 291 |
+
|
| 292 |
+
raw_answer = pick_first_present(
|
| 293 |
+
ex,
|
| 294 |
+
[
|
| 295 |
+
"label",
|
| 296 |
+
"answer",
|
| 297 |
+
"target",
|
| 298 |
+
"correct",
|
| 299 |
+
"correct_answer",
|
| 300 |
+
"answer_idx",
|
| 301 |
+
"answer_index",
|
| 302 |
+
"gold",
|
| 303 |
+
],
|
| 304 |
+
)
|
| 305 |
+
|
| 306 |
+
if prompt is None or choices is None:
|
| 307 |
+
return None
|
| 308 |
+
|
| 309 |
+
answer_idx = normalize_answer(raw_answer, choices)
|
| 310 |
+
if answer_idx is None:
|
| 311 |
+
return None
|
| 312 |
+
|
| 313 |
+
return str(prompt), choices, answer_idx
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def score_continuation(
|
| 317 |
+
model: torch.nn.Module,
|
| 318 |
+
tokenizer: Any,
|
| 319 |
+
prompt: str,
|
| 320 |
+
continuation: str,
|
| 321 |
+
device: str,
|
| 322 |
+
normalize: str,
|
| 323 |
+
) -> float:
|
| 324 |
+
full_text = prompt + continuation
|
| 325 |
+
|
| 326 |
+
enc_full = tokenizer(full_text, return_tensors="pt", add_special_tokens=False).to(device)
|
| 327 |
+
enc_prompt = tokenizer(prompt, return_tensors="pt", add_special_tokens=False).to(device)
|
| 328 |
+
|
| 329 |
+
input_ids = enc_full["input_ids"]
|
| 330 |
+
prompt_len = enc_prompt["input_ids"].shape[1]
|
| 331 |
+
|
| 332 |
+
if input_ids.shape[1] < 2:
|
| 333 |
+
return -1e30
|
| 334 |
+
|
| 335 |
+
with torch.no_grad():
|
| 336 |
+
logits = model(input_ids=input_ids).logits
|
| 337 |
+
|
| 338 |
+
shift_logits = logits[:, :-1, :]
|
| 339 |
+
shift_labels = input_ids[:, 1:]
|
| 340 |
+
|
| 341 |
+
start = max(prompt_len - 1, 0)
|
| 342 |
+
cont_logits = shift_logits[:, start:, :]
|
| 343 |
+
cont_labels = shift_labels[:, start:]
|
| 344 |
+
|
| 345 |
+
if cont_labels.numel() == 0:
|
| 346 |
+
return -1e30
|
| 347 |
+
|
| 348 |
+
log_probs = torch.log_softmax(cont_logits, dim=-1)
|
| 349 |
+
token_log_probs = log_probs.gather(-1, cont_labels.unsqueeze(-1)).squeeze(-1)
|
| 350 |
+
|
| 351 |
+
if normalize == "mean":
|
| 352 |
+
return float(token_log_probs.mean().item())
|
| 353 |
+
|
| 354 |
+
if normalize == "sum":
|
| 355 |
+
return float(token_log_probs.sum().item())
|
| 356 |
+
|
| 357 |
+
raise ValueError(f"Unknown normalize mode: {normalize}")
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def run_our_benchmark(
|
| 361 |
+
model_id: str,
|
| 362 |
+
device: str,
|
| 363 |
+
dtype: str,
|
| 364 |
+
limit: Optional[int],
|
| 365 |
+
trust_remote_code: bool,
|
| 366 |
+
normalize: str,
|
| 367 |
+
split: Optional[str],
|
| 368 |
+
choice_prefix: str,
|
| 369 |
+
) -> Dict[str, Any]:
|
| 370 |
+
print(f"\n[INFO] Loading model/tokenizer for our_benchmark: {model_id}", flush=True)
|
| 371 |
+
|
| 372 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 373 |
+
model_id,
|
| 374 |
+
trust_remote_code=trust_remote_code,
|
| 375 |
+
)
|
| 376 |
+
|
| 377 |
+
if tokenizer.pad_token is None and tokenizer.eos_token is not None:
|
| 378 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 379 |
+
|
| 380 |
+
torch_dtype = {
|
| 381 |
+
"float32": torch.float32,
|
| 382 |
+
"fp32": torch.float32,
|
| 383 |
+
"float16": torch.float16,
|
| 384 |
+
"fp16": torch.float16,
|
| 385 |
+
"bfloat16": torch.bfloat16,
|
| 386 |
+
"bf16": torch.bfloat16,
|
| 387 |
+
"auto": "auto",
|
| 388 |
+
}.get(dtype, dtype)
|
| 389 |
+
|
| 390 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 391 |
+
model_id,
|
| 392 |
+
torch_dtype=torch_dtype,
|
| 393 |
+
trust_remote_code=trust_remote_code,
|
| 394 |
+
).to(device)
|
| 395 |
+
|
| 396 |
+
model.eval()
|
| 397 |
+
params = count_params(model)
|
| 398 |
+
|
| 399 |
+
print(f"[INFO] Loading dataset: {OUR_BENCHMARK_DATASET}", flush=True)
|
| 400 |
+
ds = load_dataset(OUR_BENCHMARK_DATASET)
|
| 401 |
+
|
| 402 |
+
if split is None:
|
| 403 |
+
if "test" in ds:
|
| 404 |
+
split_name = "test"
|
| 405 |
+
elif "validation" in ds:
|
| 406 |
+
split_name = "validation"
|
| 407 |
+
else:
|
| 408 |
+
split_name = list(ds.keys())[0]
|
| 409 |
+
else:
|
| 410 |
+
split_name = split
|
| 411 |
+
|
| 412 |
+
data = ds[split_name]
|
| 413 |
+
|
| 414 |
+
print(f"[INFO] our_benchmark split: {split_name}", flush=True)
|
| 415 |
+
print(f"[INFO] our_benchmark columns: {data.column_names}", flush=True)
|
| 416 |
+
|
| 417 |
+
if len(data) > 0:
|
| 418 |
+
print("[INFO] First example preview:")
|
| 419 |
+
print(json.dumps(data[0], indent=2, ensure_ascii=False)[:2000])
|
| 420 |
+
|
| 421 |
+
total = 0
|
| 422 |
+
correct = 0
|
| 423 |
+
skipped = 0
|
| 424 |
+
|
| 425 |
+
n = len(data) if limit is None else min(limit, len(data))
|
| 426 |
+
|
| 427 |
+
for i in tqdm(range(n), desc="our_benchmark"):
|
| 428 |
+
ex = dict(data[i])
|
| 429 |
+
item = build_our_benchmark_item(ex)
|
| 430 |
+
|
| 431 |
+
if item is None:
|
| 432 |
+
skipped += 1
|
| 433 |
+
continue
|
| 434 |
+
|
| 435 |
+
prompt, choices, answer_idx = item
|
| 436 |
+
|
| 437 |
+
scores = []
|
| 438 |
+
for choice in choices:
|
| 439 |
+
continuation = choice_prefix + str(choice)
|
| 440 |
+
s = score_continuation(
|
| 441 |
+
model=model,
|
| 442 |
+
tokenizer=tokenizer,
|
| 443 |
+
prompt=prompt,
|
| 444 |
+
continuation=continuation,
|
| 445 |
+
device=device,
|
| 446 |
+
normalize=normalize,
|
| 447 |
+
)
|
| 448 |
+
scores.append(s)
|
| 449 |
+
|
| 450 |
+
pred_idx = max(range(len(scores)), key=lambda j: scores[j])
|
| 451 |
+
|
| 452 |
+
correct += int(pred_idx == answer_idx)
|
| 453 |
+
total += 1
|
| 454 |
+
|
| 455 |
+
if total == 0:
|
| 456 |
+
die("our_benchmark: zero valid examples parsed. Need to adapt field parser.")
|
| 457 |
+
|
| 458 |
+
acc = 100.0 * correct / total
|
| 459 |
+
|
| 460 |
+
del model
|
| 461 |
+
if device.startswith("cuda"):
|
| 462 |
+
torch.cuda.empty_cache()
|
| 463 |
+
|
| 464 |
+
return {
|
| 465 |
+
"display": "Our Benchmark",
|
| 466 |
+
"task": OUR_BENCHMARK_DATASET,
|
| 467 |
+
"metric": f"acc_custom_loglikelihood_{normalize}",
|
| 468 |
+
"score": acc,
|
| 469 |
+
"correct": correct,
|
| 470 |
+
"total": total,
|
| 471 |
+
"skipped": skipped,
|
| 472 |
+
"split": split_name,
|
| 473 |
+
"params": params,
|
| 474 |
+
}
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def compute_final_avg(scores: Dict[str, Dict[str, Any]]) -> Optional[float]:
|
| 478 |
+
hellaswag = scores.get("hellaswag", {}).get("score")
|
| 479 |
+
arc = scores.get("arc", {}).get("score")
|
| 480 |
+
arc_chall = scores.get("arcChall", {}).get("score")
|
| 481 |
+
piqa = scores.get("piqa", {}).get("score")
|
| 482 |
+
our_benchmark = scores.get("our_benchmark", {}).get("score")
|
| 483 |
+
|
| 484 |
+
components = []
|
| 485 |
+
|
| 486 |
+
if hellaswag is not None:
|
| 487 |
+
components.append(hellaswag)
|
| 488 |
+
|
| 489 |
+
if arc is not None and arc_chall is not None:
|
| 490 |
+
components.append((arc + arc_chall) / 2.0)
|
| 491 |
+
elif arc is not None:
|
| 492 |
+
components.append(arc)
|
| 493 |
+
elif arc_chall is not None:
|
| 494 |
+
components.append(arc_chall)
|
| 495 |
+
|
| 496 |
+
if piqa is not None:
|
| 497 |
+
components.append(piqa)
|
| 498 |
+
|
| 499 |
+
if our_benchmark is not None:
|
| 500 |
+
components.append(our_benchmark)
|
| 501 |
+
|
| 502 |
+
if len(components) < 2:
|
| 503 |
+
return None
|
| 504 |
+
|
| 505 |
+
return sum(components) / len(components)
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
def print_table(model_id: str, params: Optional[int], scores: Dict[str, Dict[str, Any]]) -> None:
|
| 509 |
+
final_avg = compute_final_avg(scores)
|
| 510 |
+
|
| 511 |
+
print("\n" + "=" * 74)
|
| 512 |
+
print("OPEN SLM LEADERBOARD STYLE RESULT")
|
| 513 |
+
print("=" * 74)
|
| 514 |
+
print(f"Model: {model_id}")
|
| 515 |
+
|
| 516 |
+
if params is not None:
|
| 517 |
+
print(f"Params: {params:,}")
|
| 518 |
+
|
| 519 |
+
print("-" * 74)
|
| 520 |
+
print(f"{'Benchmark':<18} {'Task':<18} {'Metric':<28} {'Score':>8}")
|
| 521 |
+
print("-" * 74)
|
| 522 |
+
|
| 523 |
+
order = ["hellaswag", "arc", "arcChall", "piqa", "our_benchmark"]
|
| 524 |
+
|
| 525 |
+
for key in order:
|
| 526 |
+
if key not in scores:
|
| 527 |
+
continue
|
| 528 |
+
|
| 529 |
+
s = scores[key]
|
| 530 |
+
print(
|
| 531 |
+
f"{s['display']:<18} "
|
| 532 |
+
f"{str(s['task'])[:18]:<18} "
|
| 533 |
+
f"{str(s['metric'])[:28]:<28} "
|
| 534 |
+
f"{s['score']:>7.2f}%"
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
print("-" * 74)
|
| 538 |
+
|
| 539 |
+
if "arc" in scores and "arcChall" in scores:
|
| 540 |
+
arc_avg = (scores["arc"]["score"] + scores["arcChall"]["score"]) / 2.0
|
| 541 |
+
print(f"{'ARC Avg':<66} {arc_avg:>7.2f}%")
|
| 542 |
+
|
| 543 |
+
if final_avg is not None:
|
| 544 |
+
print(f"{'Final Avg':<66} {final_avg:>7.2f}%")
|
| 545 |
+
else:
|
| 546 |
+
print(f"{'Final Avg':<66} {'N/A':>8}")
|
| 547 |
+
|
| 548 |
+
print("=" * 74)
|
| 549 |
+
|
| 550 |
+
if "our_benchmark" in scores:
|
| 551 |
+
s = scores["our_benchmark"]
|
| 552 |
+
if "correct" in s:
|
| 553 |
+
print(
|
| 554 |
+
f"our_benchmark details: {s['correct']}/{s['total']} correct, "
|
| 555 |
+
f"skipped={s['skipped']}, split={s['split']}"
|
| 556 |
+
)
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
def save_result(
|
| 560 |
+
path: str,
|
| 561 |
+
model_id: str,
|
| 562 |
+
params: Optional[int],
|
| 563 |
+
scores: Dict[str, Dict[str, Any]],
|
| 564 |
+
) -> None:
|
| 565 |
+
payload = {
|
| 566 |
+
"model": model_id,
|
| 567 |
+
"params": params,
|
| 568 |
+
"scores": scores,
|
| 569 |
+
"arc_avg": None,
|
| 570 |
+
"final_avg": compute_final_avg(scores),
|
| 571 |
+
}
|
| 572 |
+
|
| 573 |
+
if "arc" in scores and "arcChall" in scores:
|
| 574 |
+
payload["arc_avg"] = (scores["arc"]["score"] + scores["arcChall"]["score"]) / 2.0
|
| 575 |
+
|
| 576 |
+
with open(path, "w", encoding="utf-8") as f:
|
| 577 |
+
json.dump(payload, f, indent=2, ensure_ascii=False)
|
| 578 |
+
|
| 579 |
+
print(f"\n[INFO] Saved JSON: {path}")
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
def parse_args() -> argparse.Namespace:
|
| 583 |
+
p = argparse.ArgumentParser(
|
| 584 |
+
description="Run Open SLM Leaderboard style benchmark on a HF model repo/local path."
|
| 585 |
+
)
|
| 586 |
+
|
| 587 |
+
p.add_argument(
|
| 588 |
+
"model",
|
| 589 |
+
help="HF repo id or local model path.",
|
| 590 |
+
)
|
| 591 |
+
|
| 592 |
+
p.add_argument("--device", default="cuda:0", help="cuda:0, cuda, cpu...")
|
| 593 |
+
p.add_argument("--dtype", default="bfloat16", help="bfloat16, float16, float32, auto")
|
| 594 |
+
p.add_argument("--batch-size", default="auto", help="lm_eval batch size, e.g. auto, 1, 2, 4")
|
| 595 |
+
|
| 596 |
+
p.add_argument(
|
| 597 |
+
"--limit",
|
| 598 |
+
type=int,
|
| 599 |
+
default=None,
|
| 600 |
+
help="Debug limit applied to lm_eval and our_benchmark. Do not use for final scores.",
|
| 601 |
+
)
|
| 602 |
+
|
| 603 |
+
p.add_argument(
|
| 604 |
+
"--skip-lm-eval",
|
| 605 |
+
action="store_true",
|
| 606 |
+
help="Skip HellaSwag/ARC/PIQA.",
|
| 607 |
+
)
|
| 608 |
+
|
| 609 |
+
p.add_argument(
|
| 610 |
+
"--skip-our-benchmark",
|
| 611 |
+
action="store_true",
|
| 612 |
+
help="Skip our_benchmark.",
|
| 613 |
+
)
|
| 614 |
+
|
| 615 |
+
p.add_argument(
|
| 616 |
+
"--our-benchmark-split",
|
| 617 |
+
default=None,
|
| 618 |
+
help="Force our_benchmark split, e.g. test/validation/train. Default: test if available.",
|
| 619 |
+
)
|
| 620 |
+
|
| 621 |
+
p.add_argument(
|
| 622 |
+
"--our-benchmark-normalize",
|
| 623 |
+
default="mean",
|
| 624 |
+
choices=["mean", "sum"],
|
| 625 |
+
help="Continuation scoring. mean ~= acc_norm style. sum ~= raw loglikelihood.",
|
| 626 |
+
)
|
| 627 |
+
|
| 628 |
+
p.add_argument(
|
| 629 |
+
"--choice-prefix",
|
| 630 |
+
default="",
|
| 631 |
+
help="Prefix added before each answer choice when scoring our_benchmark.",
|
| 632 |
+
)
|
| 633 |
+
|
| 634 |
+
p.add_argument(
|
| 635 |
+
"--no-trust-remote-code",
|
| 636 |
+
action="store_true",
|
| 637 |
+
help="Disable trust_remote_code.",
|
| 638 |
+
)
|
| 639 |
+
|
| 640 |
+
p.add_argument(
|
| 641 |
+
"--json-out",
|
| 642 |
+
default=None,
|
| 643 |
+
help="Optional output JSON file.",
|
| 644 |
+
)
|
| 645 |
+
|
| 646 |
+
return p.parse_args()
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
def main() -> None:
|
| 650 |
+
args = parse_args()
|
| 651 |
+
|
| 652 |
+
trust_remote_code = not args.no_trust_remote_code
|
| 653 |
+
scores: Dict[str, Dict[str, Any]] = {}
|
| 654 |
+
params: Optional[int] = None
|
| 655 |
+
|
| 656 |
+
if not args.skip_lm_eval:
|
| 657 |
+
print("[INFO] Running LM-eval standard tasks...", flush=True)
|
| 658 |
+
raw_lm = run_lm_eval(
|
| 659 |
+
model_id=args.model,
|
| 660 |
+
device=args.device,
|
| 661 |
+
dtype=args.dtype,
|
| 662 |
+
batch_size=args.batch_size,
|
| 663 |
+
limit=args.limit,
|
| 664 |
+
trust_remote_code=trust_remote_code,
|
| 665 |
+
)
|
| 666 |
+
scores.update(extract_lm_eval_scores(raw_lm))
|
| 667 |
+
|
| 668 |
+
if not args.skip_our_benchmark:
|
| 669 |
+
print("[INFO] Running our_benchmark...", flush=True)
|
| 670 |
+
our_benchmark = run_our_benchmark(
|
| 671 |
+
model_id=args.model,
|
| 672 |
+
device=args.device,
|
| 673 |
+
dtype=args.dtype,
|
| 674 |
+
limit=args.limit,
|
| 675 |
+
trust_remote_code=trust_remote_code,
|
| 676 |
+
normalize=args.our_benchmark_normalize,
|
| 677 |
+
split=args.our_benchmark_split,
|
| 678 |
+
choice_prefix=args.choice_prefix,
|
| 679 |
+
)
|
| 680 |
+
params = our_benchmark.get("params")
|
| 681 |
+
scores["our_benchmark"] = our_benchmark
|
| 682 |
+
|
| 683 |
+
print_table(args.model, params, scores)
|
| 684 |
+
|
| 685 |
+
if args.json_out:
|
| 686 |
+
save_result(args.json_out, args.model, params, scores)
|
| 687 |
+
|
| 688 |
+
|
| 689 |
+
if __name__ == "__main__":
|
| 690 |
+
main()
|