| |
| """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 |
|
|
|
|
| |
| |
| |
|
|
| 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." |
| ) |
|
|
|
|
| |
| |
| |
|
|
| 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() |
|
|
|
|
| |
| |
| |
|
|
| _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): |
| |
| 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}") |
|
|
|
|
| |
| |
| |
|
|
| 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}") |
|
|
|
|
| |
| |
| |
|
|
| 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 |
|
|
|
|
| |
| |
| |
|
|
| 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() |
|
|