File size: 15,353 Bytes
e724f3d 10913e4 4e34d94 c92de9d 4e34d94 10913e4 e724f3d 10913e4 e724f3d 10913e4 e724f3d 10913e4 e724f3d 10913e4 e724f3d 10913e4 e724f3d 10913e4 e724f3d 10913e4 e724f3d 10913e4 e724f3d 10913e4 e724f3d 10913e4 4e34d94 10913e4 c92de9d 10913e4 c92de9d 10913e4 c92de9d 10913e4 4e34d94 e724f3d 10913e4 4e34d94 10913e4 e724f3d 10913e4 4e34d94 10913e4 e724f3d 10913e4 e724f3d 4e34d94 e724f3d 4e34d94 10913e4 4e34d94 10913e4 4e34d94 e724f3d 4e34d94 10913e4 4e34d94 e724f3d 4e34d94 10913e4 4e34d94 10913e4 4e34d94 10913e4 c92de9d 4e34d94 c92de9d 10913e4 4e34d94 10913e4 e724f3d 4e34d94 e724f3d 10913e4 e724f3d 10913e4 e724f3d 10913e4 e724f3d 10913e4 e724f3d 10913e4 e724f3d 10913e4 e724f3d 10913e4 e724f3d 4e34d94 10913e4 e724f3d 10913e4 4e34d94 e724f3d 4e34d94 10913e4 4e34d94 e724f3d 4e34d94 e724f3d 4e34d94 e724f3d 4e34d94 e724f3d 10913e4 e724f3d 10913e4 c92de9d e724f3d c92de9d e724f3d 10913e4 e724f3d | 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 | #!/usr/bin/env python3
"""Evaluate a Hugging Face causal LM on the Copy benchmark.
Each subset reports exactly one accuracy:
- binary-copy-recursive-flip: strict string match after strip().
- binary-copy-imbalanced: extract a/A/b/B from the model output, lowercase them,
map a -> 1 and b -> 0, then compare with the binary target.
- python-list-conversion: extract numbers from prediction and gold answer,
then compare the resulting number sequences.
"""
from __future__ import annotations
import argparse
import json
import re
import time
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
# ============================================================
# Loading benchmark records
# ============================================================
def read_jsonl(path: str | Path) -> List[Dict[str, Any]]:
records: List[Dict[str, Any]] = []
with open(path, "r", encoding="utf-8") as f:
for line_id, line in enumerate(f, start=1):
line = line.strip()
if not line:
continue
try:
records.append(json.loads(line))
except json.JSONDecodeError as e:
raise ValueError(f"Invalid JSON at line {line_id} in {path}: {e}") from e
return records
def load_records(args: argparse.Namespace) -> List[Dict[str, Any]]:
if args.data_file is not None:
return read_jsonl(args.data_file)
try:
from datasets import load_dataset
except ImportError as e:
raise ImportError(
"Please install datasets, or use --data-file for a local JSONL file."
) from e
if args.dataset is None or args.subset is None:
raise ValueError("Use either --data-file, or both --dataset and --subset.")
try:
ds = load_dataset(args.dataset, args.subset, split=args.split)
except Exception:
data_file = f"hf://datasets/{args.dataset}/data/{args.subset}.jsonl"
ds = load_dataset("json", data_files=data_file, split="train")
return [dict(x) for x in ds]
def parse_input_obj(input_obj: Any) -> Dict[str, Any]:
if isinstance(input_obj, str):
input_obj = json.loads(input_obj)
if not isinstance(input_obj, dict) or "messages" not in input_obj:
raise ValueError("record has no input.messages")
return input_obj
def get_prompt_messages_and_gold(record: Dict[str, Any]) -> Tuple[List[Dict[str, str]], str]:
"""Return prompt messages before the first assistant message, plus gold answer."""
input_obj = parse_input_obj(record.get("input"))
prompt_messages: List[Dict[str, str]] = []
gold: Optional[str] = None
for msg in input_obj["messages"]:
role = str(msg.get("role", ""))
content = str(msg.get("content", ""))
if role == "assistant" and gold is None:
gold = content
break
prompt_messages.append({"role": role, "content": content})
if gold is None:
raise ValueError(f"Record {record.get('id')} has no assistant gold answer")
return prompt_messages, gold
def get_metadata(record: Dict[str, Any]) -> Dict[str, Any]:
metadata = record.get("metadata", record.get("meta", {}))
if isinstance(metadata, str):
metadata = json.loads(metadata)
return metadata if isinstance(metadata, dict) else {}
def infer_subset(args: argparse.Namespace, records: List[Dict[str, Any]]) -> str:
if args.subset is not None:
return args.subset
if records:
task = get_metadata(records[0]).get("task")
if task in {"binary-copy-recursive-flip", "binary-copy-imbalanced", "python-list-conversion"}:
return str(task)
if args.data_file is not None:
stem = Path(args.data_file).stem
if stem in {"binary-copy-recursive-flip", "binary-copy-imbalanced", "python-list-conversion"}:
return stem
raise ValueError(
"Cannot infer subset. Please pass --subset as one of: "
"binary-copy-recursive-flip, binary-copy-imbalanced, python-list-conversion."
)
# ============================================================
# Prompt formatting
# ============================================================
def format_prompt(
tokenizer: Any,
prompt_messages: List[Dict[str, str]],
prompt_format: str,
) -> str:
has_template = getattr(tokenizer, "chat_template", None) is not None
use_template = prompt_format == "chat" or (prompt_format == "auto" and has_template)
if use_template:
return tokenizer.apply_chat_template(
prompt_messages,
tokenize=False,
add_generation_prompt=True,
)
return "\n\n".join(msg.get("content", "") for msg in prompt_messages).strip()
# ============================================================
# One-metric scoring logic
# ============================================================
_AB_RE = re.compile(r"[abAB]")
_NUM_RE = re.compile(r"-?\d+(?:\.\d+)?")
def strip_code_fences(text: str) -> str:
text = text.strip()
if text.startswith("```"):
text = re.sub(r"^```[a-zA-Z0-9_+-]*\n?", "", text)
text = re.sub(r"\n?```$", "", text)
return text.strip()
def normalize_ab_output(text: str) -> str:
"""Extract a/A/b/B and map a -> 1, b -> 0."""
symbols = _AB_RE.findall(text)
return "".join("1" if symbol.lower() == "a" else "0" for symbol in symbols)
def extract_numbers(text: str) -> List[str]:
return _NUM_RE.findall(strip_code_fences(text))
def score_01_copy(prediction: str, gold: str, metadata: Dict[str, Any]) -> Dict[str, Any]:
match = prediction.strip() == gold.strip()
return {
"metric": "strict_string_match",
"match": match,
"parsed_output": None,
"target": gold,
"pred_num_count": None,
"gold_num_count": None,
}
def score_ab_copy(prediction: str, gold: str, metadata: Dict[str, Any]) -> Dict[str, Any]:
target_binary = metadata.get("target_binary")
if not isinstance(target_binary, str):
# Fallback for older generated files: recover binary target from the gold a/b string.
target_binary = normalize_ab_output(gold)
parsed_output = normalize_ab_output(prediction)
match = parsed_output == target_binary
return {
"metric": "ab_extracted_match",
"match": match,
"parsed_output": parsed_output,
"target": target_binary,
"pred_num_count": None,
"gold_num_count": None,
}
def score_python_list_conversion(
prediction: str,
gold: str,
metadata: Dict[str, Any],
) -> Dict[str, Any]:
pred_nums = extract_numbers(prediction)
gold_nums = extract_numbers(gold)
match = pred_nums == gold_nums
return {
"metric": "number_sequence_match",
"match": match,
"parsed_output": pred_nums,
"target": gold_nums,
"pred_num_count": len(pred_nums),
"gold_num_count": len(gold_nums),
}
def score_prediction(
prediction: str,
gold: str,
subset: str,
metadata: Dict[str, Any],
) -> Dict[str, Any]:
if subset == "binary-copy-recursive-flip":
return score_01_copy(prediction, gold, metadata)
if subset == "binary-copy-imbalanced":
return score_ab_copy(prediction, gold, metadata)
if subset == "python-list-conversion":
return score_python_list_conversion(prediction, gold, metadata)
raise ValueError(f"Unknown subset: {subset}")
# ============================================================
# Evaluation helpers
# ============================================================
def safe_name(name: str) -> str:
return re.sub(r"[^a-zA-Z0-9._-]+", "_", name)
def append_jsonl(path: Path, row: Dict[str, Any]) -> None:
with path.open("a", encoding="utf-8") as f:
f.write(json.dumps(row, ensure_ascii=False) + "\n")
f.flush()
def select_records(
records: List[Dict[str, Any]],
start: int,
limit: Optional[int],
) -> List[Dict[str, Any]]:
if start < 0:
raise ValueError("--start must be non-negative")
if limit is not None and limit <= 0:
raise ValueError("--limit must be positive")
return records[start:] if limit is None else records[start : start + limit]
def resolve_torch_dtype(dtype_name: str) -> Any:
import torch
if dtype_name == "auto":
return "auto"
if dtype_name == "float16":
return torch.float16
if dtype_name == "bfloat16":
return torch.bfloat16
if dtype_name == "float32":
return torch.float32
raise ValueError(f"Unknown dtype: {dtype_name}")
# ============================================================
# Main evaluation
# ============================================================
def evaluate(args: argparse.Namespace) -> Dict[str, Any]:
import torch
from tqdm import tqdm
from transformers import AutoModelForCausalLM, AutoTokenizer
all_records = load_records(args)
subset = infer_subset(args, all_records)
records = select_records(all_records, args.start, args.limit)
if not records:
raise ValueError("No records to evaluate.")
tokenizer = AutoTokenizer.from_pretrained(
args.model,
trust_remote_code=args.trust_remote_code,
padding_side="left",
)
if tokenizer.pad_token_id is None:
tokenizer.pad_token = tokenizer.eos_token
device_map = None if args.device_map == "none" else args.device_map
model = AutoModelForCausalLM.from_pretrained(
args.model,
torch_dtype=resolve_torch_dtype(args.dtype),
device_map=device_map,
trust_remote_code=args.trust_remote_code,
)
model.eval()
if device_map is None:
model.to(args.device)
out_dir = Path(args.output_dir) / safe_name(args.model) / safe_name(subset)
out_dir.mkdir(parents=True, exist_ok=True)
predictions_path = out_dir / "predictions.jsonl"
summary_path = out_dir / "summary.json"
if predictions_path.exists() and not args.resume:
predictions_path.unlink()
done_ids = set()
if args.resume and predictions_path.exists():
for row in read_jsonl(predictions_path):
done_ids.add(row.get("id"))
results: List[Dict[str, Any]] = []
for record in tqdm(records, desc=f"Evaluating {subset}"):
ex_id = record.get("id")
if args.resume and ex_id in done_ids:
continue
metadata = get_metadata(record)
prompt_messages, gold = get_prompt_messages_and_gold(record)
prompt = format_prompt(tokenizer, prompt_messages, args.prompt_format)
inputs = tokenizer(
prompt,
return_tensors="pt",
truncation=args.max_input_tokens is not None,
max_length=args.max_input_tokens,
)
inputs = {key: value.to(model.device) for key, value in inputs.items()}
prompt_token_count = int(inputs["input_ids"].shape[-1])
t0 = time.time()
with torch.inference_mode():
generated = model.generate(
**inputs,
max_new_tokens=args.max_new_tokens,
do_sample=False,
pad_token_id=tokenizer.pad_token_id,
eos_token_id=tokenizer.eos_token_id,
)
latency_sec = time.time() - t0
new_tokens = generated[0, prompt_token_count:]
prediction = tokenizer.decode(new_tokens, skip_special_tokens=True)
output_token_count = int(new_tokens.shape[-1])
score = score_prediction(prediction, gold, subset, metadata)
row = {
"id": ex_id,
"subset": subset,
"metric": score["metric"],
"metadata": metadata,
"prediction": prediction,
"gold": gold,
"parsed_output": score["parsed_output"],
"target": score["target"],
"match": score["match"],
"pred_num_count": score["pred_num_count"],
"gold_num_count": score["gold_num_count"],
"prompt_tokens": prompt_token_count,
"output_tokens": output_token_count,
"latency_sec": latency_sec,
}
if args.save_prompt:
row["prompt"] = prompt
append_jsonl(predictions_path, row)
results.append(row)
if args.resume and predictions_path.exists():
results = read_jsonl(predictions_path)
n = len(results)
correct = sum(1 for row in results if row.get("match"))
avg_prompt_tokens = sum(row.get("prompt_tokens", 0) for row in results) / n
avg_output_tokens = sum(row.get("output_tokens", 0) for row in results) / n
avg_latency = sum(row.get("latency_sec", 0.0) for row in results) / n
metric = results[0].get("metric", "unknown")
summary = {
"model": args.model,
"subset": subset,
"metric": metric,
"num_examples": n,
"num_correct": correct,
"accuracy": correct / n,
"avg_prompt_tokens": avg_prompt_tokens,
"avg_output_tokens": avg_output_tokens,
"avg_latency_sec": avg_latency,
"predictions_path": str(predictions_path),
}
summary_path.write_text(
json.dumps(summary, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
print(json.dumps(summary, ensure_ascii=False, indent=2))
return summary
# ============================================================
# CLI
# ============================================================
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--model", required=True, help="Hugging Face model id or local model path.")
data_group = parser.add_mutually_exclusive_group(required=True)
data_group.add_argument("--dataset", help="Hugging Face dataset repo, e.g. zhangyir/Copy_Benchmark.")
data_group.add_argument("--data-file", help="Local JSONL file, e.g. data/binary-copy-imbalanced.jsonl.")
parser.add_argument("--subset", choices=["binary-copy-recursive-flip", "binary-copy-imbalanced", "python-list-conversion"], help="Benchmark subset.")
parser.add_argument("--split", default="train")
parser.add_argument("--output-dir", default="hf_eval_outputs")
parser.add_argument("--max-new-tokens", type=int, default=32768)
parser.add_argument("--max-input-tokens", type=int, default=None)
parser.add_argument("--start", type=int, default=0)
parser.add_argument("--limit", type=int, default=None)
parser.add_argument("--prompt-format", choices=["auto", "chat", "plain"], default="auto")
parser.add_argument("--dtype", choices=["auto", "float16", "bfloat16", "float32"], default="auto")
parser.add_argument("--device-map", default="auto", help="Use 'auto' by default; use 'none' with --device for manual placement.")
parser.add_argument("--device", default="cuda")
parser.add_argument("--trust-remote-code", action="store_true")
parser.add_argument("--save-prompt", action="store_true")
parser.add_argument("--resume", action="store_true")
return parser.parse_args()
def main() -> None:
args = parse_args()
if args.dataset is not None and args.subset is None:
raise ValueError("--subset is required when using --dataset.")
evaluate(args)
if __name__ == "__main__":
main()
|