MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / eval / hellaswag.py
| 1 | """HellaSwag — Commonsense Reasoning benchmark. |
| 2 | |
| 3 | Multiple choice sentence completion. Choose the most plausible ending. |
| 4 | Uses rowan/hellaswag dataset. |
| 5 | """ |
| 6 | |
| 7 | import json |
| 8 | import re |
| 9 | import time |
| 10 | from typing import Optional |
| 11 | |
| 12 | from .base import BaseBenchmark, LlamaCppEvaluator, extract_letter_answer, normalize_answer |
| 13 | from .dataset import get_dataset_stream |
| 14 | |
| 15 | |
| 16 | FEW_SHOT_EXAMPLES = [ |
| 17 | { |
| 18 | "ctx": "A woman is sitting on a bench. She", |
| 19 | "endings": ["A. stands up and walks away.", "B. flies into the sky.", "C. turns into a dragon.", "D. disappears."], |
| 20 | "answer": "A" |
| 21 | }, |
| 22 | { |
| 23 | "ctx": "A man is cooking in the kitchen. He", |
| 24 | "endings": ["A. starts singing opera loudly.", "B. chops vegetables for the soup.", "C. dissolves into thin air.", "D. forgets how to cook."], |
| 25 | "answer": "B" |
| 26 | }, |
| 27 | { |
| 28 | "ctx": "A child is playing in the park. The child", |
| 29 | "endings": ["A. grows wings and flies away.", "B. starts levitating.", "C. runs toward the swings.", "D. turns into a tree."], |
| 30 | "answer": "C" |
| 31 | }, |
| 32 | { |
| 33 | "ctx": "A person is driving a car. They approach a red light. They", |
| 34 | "endings": ["A. accelerate through the intersection.", "B. stop the car and wait.", "C. close their eyes.", "D. get out and run."], |
| 35 | "answer": "B" |
| 36 | }, |
| 37 | { |
| 38 | "ctx": "A student is taking an exam. The student", |
| 39 | "endings": ["A. reads the questions carefully.", "B. eats the exam paper.", "C. falls asleep on the floor.", "D. turns into a bird."], |
| 40 | "answer": "A" |
| 41 | } |
| 42 | ] |
| 43 | |
| 44 | |
| 45 | def _build_hellaswag_prompt(ctx, endings): |
| 46 | """Build a HellaSwag prompt with few-shot examples.""" |
| 47 | prompt_lines = [ |
| 48 | "Choose the most plausible ending for each situation.", |
| 49 | "" |
| 50 | ] |
| 51 | for ex in FEW_SHOT_EXAMPLES: |
| 52 | prompt_lines.append(ex["ctx"]) |
| 53 | for e in ex["endings"]: |
| 54 | prompt_lines.append(e) |
| 55 | prompt_lines.append(f"Answer: {ex['answer']}") |
| 56 | prompt_lines.append("") |
| 57 | |
| 58 | prompt_lines.append(ctx) |
| 59 | for e in endings: |
| 60 | prompt_lines.append(e) |
| 61 | prompt_lines.append("Answer:") |
| 62 | |
| 63 | return "\n".join(prompt_lines) |
| 64 | |
| 65 | |
| 66 | class HellaSwagBenchmark(BaseBenchmark): |
| 67 | """HellaSwag — commonsense reasoning, multiple choice.""" |
| 68 | |
| 69 | @property |
| 70 | def name(self) -> str: |
| 71 | return "HellaSwag" |
| 72 | |
| 73 | def run(self, backend_url: str, model_name: str, |
| 74 | max_samples: int = 0, **kwargs) -> dict: |
| 75 | evaluator = LlamaCppEvaluator(backend_url, temperature=0.0, max_tokens=32) |
| 76 | t0 = time.time() |
| 77 | |
| 78 | records = get_dataset_stream("hellaswag") |
| 79 | if not records: |
| 80 | return {"name": "HellaSwag", "accuracy": 0, "correct": 0, "total": 0, |
| 81 | "per_category": {}, "metrics": {"elapsed": time.time() - t0}, |
| 82 | "samples": 0, "error": "No dataset. Run download first."} |
| 83 | |
| 84 | if max_samples > 0: |
| 85 | records = records[:max_samples] |
| 86 | |
| 87 | correct = 0 |
| 88 | total = 0 |
| 89 | labels = ["A", "B", "C", "D"] |
| 90 | |
| 91 | for record in records: |
| 92 | ctx = record.get("ctx", "") |
| 93 | endings = record.get("endings", []) |
| 94 | label = record.get("label", "") |
| 95 | |
| 96 | # Map label to index |
| 97 | label_idx = None |
| 98 | if label in "0123": |
| 99 | label_idx = int(label) |
| 100 | elif label.isdigit() and 0 <= int(label) < len(endings): |
| 101 | label_idx = int(label) |
| 102 | elif label in labels: |
| 103 | label_idx = labels.index(label) |
| 104 | else: |
| 105 | continue |
| 106 | |
| 107 | answer_letter = labels[label_idx] if 0 <= label_idx < len(labels) else None |
| 108 | if answer_letter is None: |
| 109 | continue |
| 110 | |
| 111 | # Format endings with letter labels |
| 112 | formatted = [f"{labels[i]}. {endings[i]}" for i in range(len(endings))] |
| 113 | prompt = _build_hellaswag_prompt(ctx, formatted) |
| 114 | |
| 115 | try: |
| 116 | generated = evaluator.complete(prompt, max_tokens=16) |
| 117 | predicted = extract_letter_answer(generated) |
| 118 | if predicted is None: |
| 119 | m = re.search(r'\b([A-D])\b', generated) |
| 120 | if m: |
| 121 | predicted = m.group(1) |
| 122 | if predicted == answer_letter: |
| 123 | correct += 1 |
| 124 | except Exception: |
| 125 | pass |
| 126 | |
| 127 | total += 1 |
| 128 | |
| 129 | elapsed = time.time() - t0 |
| 130 | stats = evaluator.get_stats() |
| 131 | acc = correct / total if total > 0 else 0 |
| 132 | |
| 133 | print(f" HellaSwag: {acc*100:.2f}% ({correct}/{total})") |
| 134 | |
| 135 | return { |
| 136 | "name": "HellaSwag", |
| 137 | "accuracy": acc, |
| 138 | "correct": correct, |
| 139 | "total": total, |
| 140 | "per_category": {"commonsense_reasoning": {"correct": correct, "total": total, "accuracy": acc}}, |
| 141 | "metrics": {"elapsed": elapsed, "api_calls": stats["api_calls"], "api_errors": stats["api_errors"]}, |
| 142 | "samples": total |
| 143 | } |