File size: 12,389 Bytes
505aa09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

Benchmark data loaders for MMLU, BIG-Bench, and BIG-Bench Hard datasets.



Loads questions from HuggingFace datasets and formats them for agent evaluation.

Each sample contains: question text, choices, correct answer, subject/task.

"""

import random
from dataclasses import dataclass, field

from datasets import load_dataset


@dataclass
class BenchmarkSample:
    """A single benchmark question."""

    dataset_name: str  # "mmlu" or "bbh"
    subject: str  # e.g. "abstract_algebra" or "boolean_expressions"
    question: str  # The full question text
    choices: list[str]  # Answer options (for MMLU: A/B/C/D)
    correct_answer: str  # The correct answer letter or text
    sample_id: str  # Unique identifier for checkpoint/resume
    raw: dict = field(default_factory=dict, repr=False)


# ── MMLU ──────────────────────────────────────────────────────────────────────

MMLU_SUBJECTS = [
    "abstract_algebra",
    "anatomy",
    "astronomy",
    "business_ethics",
    "clinical_knowledge",
    "college_biology",
    "college_chemistry",
    "college_computer_science",
    "college_mathematics",
    "college_medicine",
    "college_physics",
    "computer_security",
    "conceptual_physics",
    "econometrics",
    "electrical_engineering",
    "elementary_mathematics",
    "formal_logic",
    "global_facts",
    "high_school_biology",
    "high_school_chemistry",
    "high_school_computer_science",
    "high_school_european_history",
    "high_school_geography",
    "high_school_government_and_politics",
    "high_school_macroeconomics",
    "high_school_mathematics",
    "high_school_microeconomics",
    "high_school_physics",
    "high_school_psychology",
    "high_school_statistics",
    "high_school_us_history",
    "high_school_world_history",
    "human_aging",
    "human_sexuality",
    "international_law",
    "jurisprudence",
    "logical_fallacies",
    "machine_learning",
    "management",
    "marketing",
    "medical_genetics",
    "miscellaneous",
    "moral_disputes",
    "moral_scenarios",
    "nutrition",
    "philosophy",
    "prehistory",
    "professional_accounting",
    "professional_law",
    "professional_medicine",
    "professional_psychology",
    "public_relations",
    "security_studies",
    "sociology",
    "us_foreign_policy",
    "virology",
    "world_religions",
]

ANSWER_LETTERS = ["A", "B", "C", "D"]


def load_mmlu(

    subjects: list[str] | None = None,

    max_samples_per_subject: int | None = None,

    split: str = "test",

    seed: int = 42,

) -> list[BenchmarkSample]:
    """

    Load MMLU dataset from HuggingFace.



    Args:

        subjects: List of subjects to load (None = all 57).

        max_samples_per_subject: Limit samples per subject for faster testing.

        split: Dataset split to use.

        seed: Random seed for sampling.



    Returns:

        List of BenchmarkSample objects.



    """
    subjects = subjects or MMLU_SUBJECTS
    samples: list[BenchmarkSample] = []
    rng = random.Random(seed)

    for _i, subj in enumerate(subjects, 1):
        try:
            ds = load_dataset("cais/mmlu", subj, split=split)
        except Exception:
            try:
                ds = load_dataset("lukaemon/mmlu", subj, split=split)
            except Exception:
                continue

        items = list(ds)
        if max_samples_per_subject and len(items) > max_samples_per_subject:
            items = rng.sample(items, max_samples_per_subject)

        for idx, row in enumerate(items):
            question_text = row["question"]
            choices = (
                row["choices"]
                if "choices" in row
                else [row.get("A", ""), row.get("B", ""), row.get("C", ""), row.get("D", "")]
            )
            # answer is an int index (0-3) in cais/mmlu
            answer_idx = row["answer"]
            correct = ANSWER_LETTERS[answer_idx] if isinstance(answer_idx, int) else str(answer_idx).strip().upper()

            # Build formatted question
            formatted_q = f"{question_text}\n"
            for letter_i, ch in enumerate(choices):
                formatted_q += f"{ANSWER_LETTERS[letter_i]}. {ch}\n"

            samples.append(
                BenchmarkSample(
                    dataset_name="mmlu",
                    subject=subj,
                    question=formatted_q.strip(),
                    choices=choices,
                    correct_answer=correct,
                    sample_id=f"mmlu_{subj}_{idx}",
                    raw=dict(row),
                )
            )

    return samples


# ── BIG-Bench Hard ────────────────────────────────────────────────────────────

BBH_TASKS = [
    "boolean_expressions",
    "causal_judgement",
    "date_understanding",
    "disambiguation_qa",
    "dyck_languages",
    "formal_fallacies",
    "geometric_shapes",
    "hyperbaton",
    "logical_deduction_five_objects",
    "logical_deduction_seven_objects",
    "logical_deduction_three_objects",
    "movie_recommendation",
    "multistep_arithmetic_two",
    "navigate",
    "object_counting",
    "penguins_in_a_table",
    "reasoning_about_colored_objects",
    "ruin_names",
    "salient_translation_error_detection",
    "snarks",
    "sports_understanding",
    "temporal_sequences",
    "tracking_shuffled_objects_five_objects",
    "tracking_shuffled_objects_seven_objects",
    "tracking_shuffled_objects_three_objects",
    "web_of_lies",
    "word_sorting",
]


def load_bbh(

    tasks: list[str] | None = None,

    max_samples_per_task: int | None = None,

    seed: int = 42,

) -> list[BenchmarkSample]:
    """

    Load BIG-Bench Hard dataset from HuggingFace.



    Args:

        tasks: List of tasks to load (None = all).

        max_samples_per_task: Limit samples per task.

        seed: Random seed for sampling.



    Returns:

        List of BenchmarkSample objects.



    """
    tasks = tasks or BBH_TASKS
    samples: list[BenchmarkSample] = []
    rng = random.Random(seed)

    for _i, task in enumerate(tasks, 1):
        try:
            # Primary source: lukaemon/bbh (maveriq/bigbenchhard is deprecated)
            ds = load_dataset("lukaemon/bbh", task, split="test")
            data = list(ds)
        except Exception:
            try:
                ds = load_dataset("lukaemon/bbh", task, split="train")
                data = list(ds)
            except Exception:
                continue

        if max_samples_per_task and len(data) > max_samples_per_task:
            data = rng.sample(data, max_samples_per_task)

        for idx, row in enumerate(data):
            question_text = row.get("input", row.get("question", ""))
            target = row.get("target", row.get("answer", ""))

            samples.append(
                BenchmarkSample(
                    dataset_name="bbh",
                    subject=task,
                    question=question_text.strip(),
                    choices=[],  # BBH is mostly free-form
                    correct_answer=str(target).strip(),
                    sample_id=f"bbh_{task}_{idx}",
                    raw=dict(row),
                )
            )

    return samples


# ── BIG-Bench (regular) ───────────────────────────────────────────────────────

BIGBENCH_TASKS = [
    "abstract_narrative_understanding",
    "anachronisms",
    "analogical_similarity",
    "causal_judgment",
    "cause_and_effect",
    "elementary_math_qa",
    "epistemic_reasoning",
    "general_knowledge",
    "logical_args",
    "logical_fallacy_detection",
    "logical_sequence",
    "movie_dialog_same_or_different",
    "novel_concepts",
    "odd_one_out",
    "play_dialog_same_or_different",
    "presuppositions_as_nli",
    "riddle_sense",
    "strange_stories",
    "strategyqa",
    "vitaminc_fact_verification",
]


def load_bigbench(

    tasks: list[str] | None = None,

    max_samples_per_task: int | None = None,

    seed: int = 42,

) -> list[BenchmarkSample]:
    """

    Load regular BIG-Bench dataset from HuggingFace (tasksource/bigbench).



    Unlike BBH (free-form), regular BIG-Bench has multiple-choice format

    with 'inputs', 'targets', 'multiple_choice_targets', 'multiple_choice_scores'.



    Args:

        tasks: List of tasks to load (None = default subset).

        max_samples_per_task: Limit samples per task.

        seed: Random seed for sampling.



    Returns:

        List of BenchmarkSample objects.



    """
    tasks = tasks or BIGBENCH_TASKS
    samples: list[BenchmarkSample] = []
    rng = random.Random(seed)

    for i, task in enumerate(tasks, 1):
        try:
            ds = load_dataset("tasksource/bigbench", task, split="train")
            data = list(ds)
        except Exception:
            try:
                ds = load_dataset("tasksource/bigbench", task, split="validation")
                data = list(ds)
            except Exception:
                continue

        if max_samples_per_task and len(data) > max_samples_per_task:
            data = rng.sample(data, max_samples_per_task)

        for idx, row in enumerate(data):
            question_text = row.get("inputs", "")
            targets = row.get("targets", [])
            mc_targets = row.get("multiple_choice_targets", [])
            mc_scores = row.get("multiple_choice_scores", [])

            # Determine correct answer
            if mc_targets and mc_scores:
                # Multiple-choice format
                correct_idx = None
                for i, score in enumerate(mc_scores):
                    if score == 1:
                        correct_idx = i
                        break

                if correct_idx is not None and correct_idx < len(mc_targets):
                    correct_answer = mc_targets[correct_idx]
                elif targets:
                    correct_answer = targets[0] if isinstance(targets, list) else str(targets)
                else:
                    continue

                # Format as multiple-choice question
                choices = mc_targets
                formatted_q = f"{question_text}\n"
                for i, ch in enumerate(choices):
                    letter = chr(65 + i)  # A, B, C, ...
                    formatted_q += f"{letter}. {ch}\n"

                # Store correct as letter
                correct_letter = chr(65 + correct_idx) if correct_idx is not None else str(correct_answer)
            else:
                # Free-form
                correct_answer = targets[0] if isinstance(targets, list) and targets else str(targets)
                formatted_q = question_text
                choices = []
                correct_letter = correct_answer

            samples.append(
                BenchmarkSample(
                    dataset_name="bigbench",
                    subject=task,
                    question=formatted_q.strip(),
                    choices=choices,
                    correct_answer=correct_letter.strip(),
                    sample_id=f"bigbench_{task}_{idx}",
                    raw=dict(row),
                )
            )

    return samples


def load_all_benchmarks(

    mmlu_subjects: list[str] | None = None,

    bbh_tasks: list[str] | None = None,

    bigbench_tasks: list[str] | None = None,

    max_samples_per_subject: int | None = None,

    seed: int = 42,

) -> dict[str, list[BenchmarkSample]]:
    """Load MMLU, BBH, and BIG-Bench datasets."""
    return {
        "mmlu": load_mmlu(mmlu_subjects, max_samples_per_subject, seed=seed),
        "bbh": load_bbh(bbh_tasks, max_samples_per_subject, seed=seed),
        "bigbench": load_bigbench(bigbench_tasks, max_samples_per_subject, seed=seed),
    }