Benchmark-TEST / run_our_benchmark.py
PhysiQuanty's picture
Create run_our_benchmark.py
759c25f verified
Raw
History Blame Contribute Delete
18.7 kB
#!/usr/bin/env python3
import argparse
import json
import re
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
import torch
from datasets import load_dataset
from tqdm import tqdm
from transformers import AutoModelForCausalLM, AutoTokenizer
LM_EVAL_TASKS = {
"hellaswag": {
"display": "HellaSwag",
"task": "hellaswag",
"preferred_metrics": ["acc_norm", "acc_norm,none", "acc"],
},
"arc": {
"display": "ARC-Easy",
"task": "arc_easy",
"preferred_metrics": ["acc_norm", "acc_norm,none", "acc"],
},
"arcChall": {
"display": "ARC-Challenge",
"task": "arc_challenge",
"preferred_metrics": ["acc_norm", "acc_norm,none", "acc"],
},
"piqa": {
"display": "PIQA",
"task": "piqa",
"preferred_metrics": ["acc_norm", "acc_norm,none", "acc", "acc,none"],
},
}
OUR_BENCHMARK_DATASET = "WhirlwindAI/Benchmark-TEST"
def die(msg: str, code: int = 1) -> None:
print(f"[ERROR] {msg}", file=sys.stderr)
sys.exit(code)
def run_cmd(cmd: List[str]) -> None:
print("\n[CMD]", " ".join(cmd), flush=True)
proc = subprocess.run(cmd)
if proc.returncode != 0:
die(f"Command failed with exit code {proc.returncode}")
def find_latest_json(path: Path) -> Path:
if path.is_file():
return path
json_files = list(path.rglob("*.json"))
if not json_files:
die(f"No JSON result file found in {path}")
json_files.sort(key=lambda p: p.stat().st_mtime, reverse=True)
return json_files[0]
def load_json(path: Path) -> Dict[str, Any]:
with path.open("r", encoding="utf-8") as f:
return json.load(f)
def metric_from_result(task_result: Dict[str, Any], preferred: List[str]) -> Tuple[str, float]:
for key in preferred:
if key in task_result and isinstance(task_result[key], (int, float)):
return key, float(task_result[key])
for key, value in task_result.items():
if "acc_norm" in key and isinstance(value, (int, float)):
return key, float(value)
for key, value in task_result.items():
if key.startswith("acc") and isinstance(value, (int, float)):
return key, float(value)
die(f"Could not find accuracy metric in result: {task_result}")
def run_lm_eval(
model_id: str,
device: str,
dtype: str,
batch_size: str,
limit: Optional[int],
trust_remote_code: bool,
) -> Dict[str, Dict[str, Any]]:
tasks = ",".join(info["task"] for info in LM_EVAL_TASKS.values())
model_args = [
f"pretrained={model_id}",
f"dtype={dtype}",
]
if trust_remote_code:
model_args.append("trust_remote_code=True")
with tempfile.TemporaryDirectory(prefix="open_slm_lm_eval_") as tmp:
out_dir = Path(tmp)
cmd = [
sys.executable,
"-m",
"lm_eval",
"--model",
"hf",
"--model_args",
",".join(model_args),
"--tasks",
tasks,
"--device",
device,
"--batch_size",
batch_size,
"--output_path",
str(out_dir),
]
if limit is not None:
cmd.extend(["--limit", str(limit)])
run_cmd(cmd)
result_path = find_latest_json(out_dir)
raw = load_json(result_path)
if "results" not in raw:
die(f"Unexpected lm_eval JSON format. Top-level keys: {list(raw.keys())}")
return raw["results"]
def normalize_percent(x: float) -> float:
if x <= 1.0:
return x * 100.0
return x
def extract_lm_eval_scores(raw_results: Dict[str, Dict[str, Any]]) -> Dict[str, Dict[str, Any]]:
scores: Dict[str, Dict[str, Any]] = {}
for key, info in LM_EVAL_TASKS.items():
task_name = info["task"]
if task_name not in raw_results:
die(f"Task {task_name} not found in lm_eval results. Found: {list(raw_results.keys())}")
metric_name, value = metric_from_result(raw_results[task_name], info["preferred_metrics"])
scores[key] = {
"display": info["display"],
"task": task_name,
"metric": metric_name,
"score": normalize_percent(value),
}
return scores
def count_params(model: torch.nn.Module) -> int:
return sum(p.numel() for p in model.parameters())
def pick_first_present(ex: Dict[str, Any], names: List[str]) -> Optional[Any]:
for name in names:
if name in ex and ex[name] is not None:
return ex[name]
return None
def normalize_choices(raw_choices: Any, ex: Dict[str, Any]) -> Optional[List[str]]:
if raw_choices is None:
letter_choices = []
for k in ["A", "B", "C", "D", "E"]:
if k in ex and ex[k] is not None:
letter_choices.append(str(ex[k]))
if len(letter_choices) >= 2:
return letter_choices
lower_choices = []
for k in ["choice_a", "choice_b", "choice_c", "choice_d", "choice_e"]:
if k in ex and ex[k] is not None:
lower_choices.append(str(ex[k]))
if len(lower_choices) >= 2:
return lower_choices
option_choices = []
for k in ["option_a", "option_b", "option_c", "option_d", "option_e"]:
if k in ex and ex[k] is not None:
option_choices.append(str(ex[k]))
if len(option_choices) >= 2:
return option_choices
return None
if isinstance(raw_choices, dict):
if "text" in raw_choices:
return [str(x) for x in raw_choices["text"]]
if "choices" in raw_choices:
return [str(x) for x in raw_choices["choices"]]
if "options" in raw_choices:
return [str(x) for x in raw_choices["options"]]
vals = []
for k in ["A", "B", "C", "D", "E"]:
if k in raw_choices:
vals.append(str(raw_choices[k]))
if len(vals) >= 2:
return vals
if isinstance(raw_choices, list):
return [str(x) for x in raw_choices]
return None
def normalize_answer(raw_answer: Any, choices: List[str]) -> Optional[int]:
if raw_answer is None:
return None
if isinstance(raw_answer, bool):
return int(raw_answer)
if isinstance(raw_answer, int):
if 0 <= raw_answer < len(choices):
return raw_answer
if 1 <= raw_answer <= len(choices):
return raw_answer - 1
if isinstance(raw_answer, float) and raw_answer.is_integer():
return normalize_answer(int(raw_answer), choices)
ans = str(raw_answer).strip()
if len(ans) == 1 and ans.upper() in "ABCDE":
idx = ord(ans.upper()) - ord("A")
if 0 <= idx < len(choices):
return idx
if re.fullmatch(r"\d+", ans):
return normalize_answer(int(ans), choices)
for i, choice in enumerate(choices):
if ans == str(choice).strip():
return i
low = ans.lower()
for i, choice in enumerate(choices):
if low == str(choice).strip().lower():
return i
return None
def build_our_benchmark_item(ex: Dict[str, Any]) -> Optional[Tuple[str, List[str], int]]:
prompt = pick_first_present(
ex,
[
"ctx",
"question",
"prompt",
"input",
"problem",
"query",
"text",
"instruction",
],
)
raw_choices = pick_first_present(
ex,
[
"endings",
"choices",
"options",
"answers",
"candidates",
"multiple_choice",
],
)
choices = normalize_choices(raw_choices, ex)
raw_answer = pick_first_present(
ex,
[
"label",
"answer",
"target",
"correct",
"correct_answer",
"answer_idx",
"answer_index",
"gold",
],
)
if prompt is None or choices is None:
return None
answer_idx = normalize_answer(raw_answer, choices)
if answer_idx is None:
return None
return str(prompt), choices, answer_idx
def score_continuation(
model: torch.nn.Module,
tokenizer: Any,
prompt: str,
continuation: str,
device: str,
normalize: str,
) -> float:
full_text = prompt + continuation
enc_full = tokenizer(full_text, return_tensors="pt", add_special_tokens=False).to(device)
enc_prompt = tokenizer(prompt, return_tensors="pt", add_special_tokens=False).to(device)
input_ids = enc_full["input_ids"]
prompt_len = enc_prompt["input_ids"].shape[1]
if input_ids.shape[1] < 2:
return -1e30
with torch.no_grad():
logits = model(input_ids=input_ids).logits
shift_logits = logits[:, :-1, :]
shift_labels = input_ids[:, 1:]
start = max(prompt_len - 1, 0)
cont_logits = shift_logits[:, start:, :]
cont_labels = shift_labels[:, start:]
if cont_labels.numel() == 0:
return -1e30
log_probs = torch.log_softmax(cont_logits, dim=-1)
token_log_probs = log_probs.gather(-1, cont_labels.unsqueeze(-1)).squeeze(-1)
if normalize == "mean":
return float(token_log_probs.mean().item())
if normalize == "sum":
return float(token_log_probs.sum().item())
raise ValueError(f"Unknown normalize mode: {normalize}")
def run_our_benchmark(
model_id: str,
device: str,
dtype: str,
limit: Optional[int],
trust_remote_code: bool,
normalize: str,
split: Optional[str],
choice_prefix: str,
) -> Dict[str, Any]:
print(f"\n[INFO] Loading model/tokenizer for our_benchmark: {model_id}", flush=True)
tokenizer = AutoTokenizer.from_pretrained(
model_id,
trust_remote_code=trust_remote_code,
)
if tokenizer.pad_token is None and tokenizer.eos_token is not None:
tokenizer.pad_token = tokenizer.eos_token
torch_dtype = {
"float32": torch.float32,
"fp32": torch.float32,
"float16": torch.float16,
"fp16": torch.float16,
"bfloat16": torch.bfloat16,
"bf16": torch.bfloat16,
"auto": "auto",
}.get(dtype, dtype)
model = AutoModelForCausalLM.from_pretrained(
model_id,
torch_dtype=torch_dtype,
trust_remote_code=trust_remote_code,
).to(device)
model.eval()
params = count_params(model)
print(f"[INFO] Loading dataset: {OUR_BENCHMARK_DATASET}", flush=True)
ds = load_dataset(OUR_BENCHMARK_DATASET)
if split is None:
if "test" in ds:
split_name = "test"
elif "validation" in ds:
split_name = "validation"
else:
split_name = list(ds.keys())[0]
else:
split_name = split
data = ds[split_name]
print(f"[INFO] our_benchmark split: {split_name}", flush=True)
print(f"[INFO] our_benchmark columns: {data.column_names}", flush=True)
if len(data) > 0:
print("[INFO] First example preview:")
print(json.dumps(data[0], indent=2, ensure_ascii=False)[:2000])
total = 0
correct = 0
skipped = 0
n = len(data) if limit is None else min(limit, len(data))
for i in tqdm(range(n), desc="our_benchmark"):
ex = dict(data[i])
item = build_our_benchmark_item(ex)
if item is None:
skipped += 1
continue
prompt, choices, answer_idx = item
scores = []
for choice in choices:
continuation = choice_prefix + str(choice)
s = score_continuation(
model=model,
tokenizer=tokenizer,
prompt=prompt,
continuation=continuation,
device=device,
normalize=normalize,
)
scores.append(s)
pred_idx = max(range(len(scores)), key=lambda j: scores[j])
correct += int(pred_idx == answer_idx)
total += 1
if total == 0:
die("our_benchmark: zero valid examples parsed. Need to adapt field parser.")
acc = 100.0 * correct / total
del model
if device.startswith("cuda"):
torch.cuda.empty_cache()
return {
"display": "Our Benchmark",
"task": OUR_BENCHMARK_DATASET,
"metric": f"acc_custom_loglikelihood_{normalize}",
"score": acc,
"correct": correct,
"total": total,
"skipped": skipped,
"split": split_name,
"params": params,
}
def compute_final_avg(scores: Dict[str, Dict[str, Any]]) -> Optional[float]:
hellaswag = scores.get("hellaswag", {}).get("score")
arc = scores.get("arc", {}).get("score")
arc_chall = scores.get("arcChall", {}).get("score")
piqa = scores.get("piqa", {}).get("score")
our_benchmark = scores.get("our_benchmark", {}).get("score")
components = []
if hellaswag is not None:
components.append(hellaswag)
if arc is not None and arc_chall is not None:
components.append((arc + arc_chall) / 2.0)
elif arc is not None:
components.append(arc)
elif arc_chall is not None:
components.append(arc_chall)
if piqa is not None:
components.append(piqa)
if our_benchmark is not None:
components.append(our_benchmark)
if len(components) < 2:
return None
return sum(components) / len(components)
def print_table(model_id: str, params: Optional[int], scores: Dict[str, Dict[str, Any]]) -> None:
final_avg = compute_final_avg(scores)
print("\n" + "=" * 74)
print("OPEN SLM LEADERBOARD STYLE RESULT")
print("=" * 74)
print(f"Model: {model_id}")
if params is not None:
print(f"Params: {params:,}")
print("-" * 74)
print(f"{'Benchmark':<18} {'Task':<18} {'Metric':<28} {'Score':>8}")
print("-" * 74)
order = ["hellaswag", "arc", "arcChall", "piqa", "our_benchmark"]
for key in order:
if key not in scores:
continue
s = scores[key]
print(
f"{s['display']:<18} "
f"{str(s['task'])[:18]:<18} "
f"{str(s['metric'])[:28]:<28} "
f"{s['score']:>7.2f}%"
)
print("-" * 74)
if "arc" in scores and "arcChall" in scores:
arc_avg = (scores["arc"]["score"] + scores["arcChall"]["score"]) / 2.0
print(f"{'ARC Avg':<66} {arc_avg:>7.2f}%")
if final_avg is not None:
print(f"{'Final Avg':<66} {final_avg:>7.2f}%")
else:
print(f"{'Final Avg':<66} {'N/A':>8}")
print("=" * 74)
if "our_benchmark" in scores:
s = scores["our_benchmark"]
if "correct" in s:
print(
f"our_benchmark details: {s['correct']}/{s['total']} correct, "
f"skipped={s['skipped']}, split={s['split']}"
)
def save_result(
path: str,
model_id: str,
params: Optional[int],
scores: Dict[str, Dict[str, Any]],
) -> None:
payload = {
"model": model_id,
"params": params,
"scores": scores,
"arc_avg": None,
"final_avg": compute_final_avg(scores),
}
if "arc" in scores and "arcChall" in scores:
payload["arc_avg"] = (scores["arc"]["score"] + scores["arcChall"]["score"]) / 2.0
with open(path, "w", encoding="utf-8") as f:
json.dump(payload, f, indent=2, ensure_ascii=False)
print(f"\n[INFO] Saved JSON: {path}")
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(
description="Run Open SLM Leaderboard style benchmark on a HF model repo/local path."
)
p.add_argument(
"model",
help="HF repo id or local model path.",
)
p.add_argument("--device", default="cuda:0", help="cuda:0, cuda, cpu...")
p.add_argument("--dtype", default="bfloat16", help="bfloat16, float16, float32, auto")
p.add_argument("--batch-size", default="auto", help="lm_eval batch size, e.g. auto, 1, 2, 4")
p.add_argument(
"--limit",
type=int,
default=None,
help="Debug limit applied to lm_eval and our_benchmark. Do not use for final scores.",
)
p.add_argument(
"--skip-lm-eval",
action="store_true",
help="Skip HellaSwag/ARC/PIQA.",
)
p.add_argument(
"--skip-our-benchmark",
action="store_true",
help="Skip our_benchmark.",
)
p.add_argument(
"--our-benchmark-split",
default=None,
help="Force our_benchmark split, e.g. test/validation/train. Default: test if available.",
)
p.add_argument(
"--our-benchmark-normalize",
default="mean",
choices=["mean", "sum"],
help="Continuation scoring. mean ~= acc_norm style. sum ~= raw loglikelihood.",
)
p.add_argument(
"--choice-prefix",
default="",
help="Prefix added before each answer choice when scoring our_benchmark.",
)
p.add_argument(
"--no-trust-remote-code",
action="store_true",
help="Disable trust_remote_code.",
)
p.add_argument(
"--json-out",
default=None,
help="Optional output JSON file.",
)
return p.parse_args()
def main() -> None:
args = parse_args()
trust_remote_code = not args.no_trust_remote_code
scores: Dict[str, Dict[str, Any]] = {}
params: Optional[int] = None
if not args.skip_lm_eval:
print("[INFO] Running LM-eval standard tasks...", flush=True)
raw_lm = run_lm_eval(
model_id=args.model,
device=args.device,
dtype=args.dtype,
batch_size=args.batch_size,
limit=args.limit,
trust_remote_code=trust_remote_code,
)
scores.update(extract_lm_eval_scores(raw_lm))
if not args.skip_our_benchmark:
print("[INFO] Running our_benchmark...", flush=True)
our_benchmark = run_our_benchmark(
model_id=args.model,
device=args.device,
dtype=args.dtype,
limit=args.limit,
trust_remote_code=trust_remote_code,
normalize=args.our_benchmark_normalize,
split=args.our_benchmark_split,
choice_prefix=args.choice_prefix,
)
params = our_benchmark.get("params")
scores["our_benchmark"] = our_benchmark
print_table(args.model, params, scores)
if args.json_out:
save_result(args.json_out, args.model, params, scores)
if __name__ == "__main__":
main()