| """Run SawBench evaluation against a HuggingFace Transformers model. |
| |
| Usage: |
| python run_eval_transformers.py --model Qwen/Qwen2.5-0.5B-Instruct |
| python run_eval_transformers.py --model mistralai/Mistral-7B-Instruct-v0.3 --tasks spell,reverse --max-items 50 |
| """ |
| import argparse, json, re, sys, time |
| from pathlib import Path |
| from collections import defaultdict |
|
|
| import torch |
| from transformers import AutoModelForCausalLM, AutoTokenizer |
| from datasets import load_dataset |
|
|
|
|
| def load_items(tasks=None, max_items=None): |
| """Load test items from HuggingFace, optionally filtering by task.""" |
| ds = load_dataset("omneity-labs/spellbench", split="test") |
| items = list(ds) |
| |
| if tasks: |
| items = [item for item in items if item["task"] in tasks] |
| |
| if max_items: |
| |
| by_task = defaultdict(list) |
| for item in items: |
| by_task[item["task"]].append(item) |
| items = [] |
| for task_items in by_task.values(): |
| items.extend(task_items[:max_items]) |
| return items |
|
|
|
|
| def load_prompts(data_dir): |
| """Load prompt templates.""" |
| with open(data_dir / "prompts.json") as f: |
| return json.load(f) |
|
|
|
|
| def format_prompt(item, prompt_templates): |
| """Format a prompt for a given item using the first template.""" |
| task = item["task"] |
| tmpl_info = prompt_templates.get(task) |
| if not tmpl_info: |
| return f"Task: {task}\nInput: {item['input']}" |
|
|
| tmpl = tmpl_info["prompts"][0] |
| input_val = item["input"] |
|
|
| |
| if " | " in input_val: |
| parts = input_val.split(" | ") |
| main_input = parts[0] |
| params = {} |
| for p in parts[1:]: |
| if ": " in p: |
| k, v = p.split(": ", 1) |
| params[k.strip()] = v.strip() |
|
|
| |
| fmt = {"input": main_input, "word": main_input, "sentence": main_input} |
| fmt.update(params) |
| |
| if "position" in params: |
| fmt["n"] = params["position"] |
| if "word number" in params: |
| fmt["n"] = params["word number"] |
| if "word" in params: |
| fmt["word"] = params["word"] |
|
|
| |
| for p in parts[1:]: |
| m = re.match(r"word (\d+) vs word (\d+)", p.strip()) |
| if m: |
| fmt["n"] = m.group(1) |
| fmt["m"] = m.group(2) |
| else: |
| fmt = {"input": input_val, "word": input_val, "sentence": input_val} |
|
|
| try: |
| return tmpl.format(**fmt) |
| except KeyError: |
| return f"Task: {task}\nInput: {item['input']}" |
|
|
|
|
| def extract_answer(response, task): |
| """Extract the answer from model response. Handles both JSON and natural language.""" |
| response = response.strip() |
|
|
| |
| json_match = re.search(r'\{[^}]+\}', response) |
| if json_match: |
| try: |
| data = json.loads(json_match.group()) |
| if "answer" in data: |
| return str(data["answer"]) |
| if "result" in data: |
| return str(data["result"]) |
| except json.JSONDecodeError: |
| pass |
|
|
| |
| if task in ("word_length", "vowel_count", "consonant_count", "count_letter", |
| "word_count", "total_letters", "nth_word_length"): |
| nums = re.findall(r'\b(\d+)\b', response) |
| if nums: |
| return nums[-1] |
|
|
| |
| if task in ("is_palindrome", "contains_letter"): |
| lower = response.lower() |
| if "true" in lower or "yes" in lower: |
| return "true" |
| if "false" in lower or "no" in lower: |
| return "false" |
|
|
| |
| if task == "compare_lengths": |
| lower = response.lower() |
| if "equal" in lower: |
| return "equal" |
| if "first" in lower: |
| return "first" |
| if "second" in lower: |
| return "second" |
|
|
| |
| if task in ("first_letter", "last_letter", "nth_letter"): |
| |
| m = re.search(r"['\"](.)['\"]", response) |
| if m: |
| return m.group(1) |
| |
| m = re.search(r'\b([a-zA-Z])\b', response) |
| if m: |
| return m.group(1) |
|
|
| |
| lines = response.strip().split("\n") |
| return lines[-1].strip() |
|
|
|
|
| def check_answer(predicted, expected, task): |
| """Compare predicted vs expected, with task-appropriate normalization.""" |
| predicted = str(predicted).strip().lower() |
| expected = str(expected).strip().lower() |
|
|
| if task in ("spell", "reverse", "copy", "remove_vowels", "pig_latin", |
| "sentence_reverse", "longest_word", "shortest_word", |
| "alphabetical_order", "sort_by_length", |
| "nth_word_spell", "nth_word_reverse"): |
| return predicted == expected |
|
|
| if task in ("word_length", "vowel_count", "consonant_count", "count_letter", |
| "word_count", "total_letters", "nth_word_length"): |
| return predicted == expected |
|
|
| if task in ("first_letter", "last_letter", "nth_letter"): |
| return predicted == expected |
|
|
| if task in ("is_palindrome", "contains_letter"): |
| return predicted == expected |
|
|
| if task == "compare_lengths": |
| return predicted == expected |
|
|
| |
| if task in ("unique_letters", "double_letters", "all_first_letters", "letter_positions"): |
| pred_norm = re.sub(r'\s*,\s*', ', ', predicted) |
| exp_norm = re.sub(r'\s*,\s*', ', ', expected) |
| return pred_norm == exp_norm |
|
|
| if task == "char_frequency": |
| return predicted == expected |
|
|
| return predicted == expected |
|
|
|
|
| def run_eval(model_name, data_dir, tasks=None, max_items=None, |
| max_new_tokens=128, device="auto", batch_size=1): |
| """Run evaluation and return results.""" |
| print(f"Loading model: {model_name}") |
| tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) |
| model = AutoModelForCausalLM.from_pretrained( |
| model_name, |
| torch_dtype=torch.bfloat16, |
| device_map=device, |
| trust_remote_code=True, |
| ) |
| model.eval() |
|
|
| if tokenizer.pad_token is None: |
| tokenizer.pad_token = tokenizer.eos_token |
|
|
| prompts_data = load_prompts(data_dir) |
| items = load_items(tasks, max_items) |
| print(f"Loaded {len(items)} items across {len(set(i['task'] for i in items))} tasks") |
|
|
| results = [] |
| task_scores = defaultdict(lambda: {"correct": 0, "total": 0}) |
| t0 = time.time() |
|
|
| for i, item in enumerate(items): |
| prompt_text = format_prompt(item, prompts_data) |
|
|
| messages = [{"role": "user", "content": prompt_text}] |
| text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) |
| inputs = tokenizer(text, return_tensors="pt").to(model.device) |
|
|
| with torch.no_grad(): |
| outputs = model.generate( |
| **inputs, |
| max_new_tokens=max_new_tokens, |
| do_sample=False, |
| temperature=None, |
| top_p=None, |
| ) |
|
|
| response = tokenizer.decode(outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True) |
| predicted = extract_answer(response, item["task"]) |
| correct = check_answer(predicted, item["expected"], item["task"]) |
|
|
| task_scores[item["task"]]["total"] += 1 |
| if correct: |
| task_scores[item["task"]]["correct"] += 1 |
|
|
| results.append({ |
| "id": item["id"], |
| "task": item["task"], |
| "input": item["input"], |
| "expected": item["expected"], |
| "predicted": predicted, |
| "raw_response": response, |
| "correct": correct, |
| "metadata": item["metadata"] |
| }) |
|
|
| if (i + 1) % 50 == 0: |
| elapsed = time.time() - t0 |
| print(f" [{i+1}/{len(items)}] {elapsed:.1f}s elapsed") |
|
|
| elapsed = time.time() - t0 |
|
|
| |
| summary = { |
| "model": model_name, |
| "total_items": len(items), |
| "total_correct": sum(1 for r in results if r["correct"]), |
| "accuracy": sum(1 for r in results if r["correct"]) / len(items) if items else 0, |
| "elapsed_seconds": round(elapsed, 1), |
| "per_task": {}, |
| } |
| for task, scores in sorted(task_scores.items()): |
| acc = scores["correct"] / scores["total"] if scores["total"] else 0 |
| summary["per_task"][task] = { |
| "correct": scores["correct"], |
| "total": scores["total"], |
| "accuracy": round(acc, 4), |
| } |
|
|
| return summary, results |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="Run SawBench evaluation with a HF model") |
| parser.add_argument("--model", required=True, help="HuggingFace model name or path") |
| parser.add_argument("--data-dir", default=str(Path(__file__).parent / "data"), |
| help="Path to data/ directory") |
| parser.add_argument("--tasks", default=None, |
| help="Comma-separated task names (default: all)") |
| parser.add_argument("--max-items", type=int, default=None, |
| help="Max items per task (default: all)") |
| parser.add_argument("--max-new-tokens", type=int, default=128) |
| parser.add_argument("--device", default="auto") |
| parser.add_argument("--output", default="results.json", |
| help="Output file for detailed results") |
| args = parser.parse_args() |
|
|
| tasks = args.tasks.split(",") if args.tasks else None |
| data_dir = Path(args.data_dir) |
|
|
| summary, results = run_eval( |
| args.model, data_dir, tasks, args.max_items, |
| args.max_new_tokens, args.device, |
| ) |
|
|
| |
| print(f"\n{'='*60}") |
| print(f"Model: {summary['model']}") |
| print(f"Overall: {summary['total_correct']}/{summary['total_items']} " |
| f"({summary['accuracy']:.1%})") |
| print(f"Time: {summary['elapsed_seconds']}s") |
| print(f"{'='*60}") |
| print(f"{'Task':<25} {'Correct':>8} {'Total':>6} {'Accuracy':>9}") |
| print(f"{'-'*25} {'-'*8} {'-'*6} {'-'*9}") |
| for task, info in summary["per_task"].items(): |
| print(f"{task:<25} {info['correct']:>8} {info['total']:>6} {info['accuracy']:>8.1%}") |
|
|
| |
| output_path = Path(args.output) |
| with open(output_path, "w") as f: |
| json.dump({"summary": summary, "results": results}, f, indent=2, ensure_ascii=False) |
| print(f"\nDetailed results saved to {output_path}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|