File size: 27,157 Bytes
da35c69
44529bb
da35c69
793be05
 
 
 
 
 
da35c69
44529bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da35c69
 
44529bb
 
 
 
 
 
da35c69
 
44529bb
 
0450c4e
44529bb
 
 
 
 
 
 
da35c69
44529bb
da35c69
44529bb
 
 
0450c4e
44529bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0450c4e
44529bb
 
 
 
 
 
 
 
 
 
 
 
 
0450c4e
44529bb
 
 
 
 
 
da35c69
 
 
44529bb
 
 
 
acfee14
44529bb
 
 
 
 
 
0450c4e
44529bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0450c4e
44529bb
 
 
0450c4e
44529bb
 
 
 
 
 
 
 
 
 
 
da35c69
44529bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
793be05
 
 
 
 
 
 
a06316f
793be05
 
 
 
 
 
 
 
27ff91e
 
 
 
 
1223129
27ff91e
 
 
 
 
793be05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44529bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
793be05
 
 
 
 
 
 
 
a06316f
793be05
 
 
 
 
 
 
 
27ff91e
 
 
 
 
 
 
793be05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44529bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0450c4e
44529bb
da35c69
44529bb
0450c4e
da35c69
 
793be05
 
 
 
 
 
 
a06316f
793be05
 
 
 
 
 
 
 
 
27ff91e
 
 
 
 
793be05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44529bb
 
 
 
 
 
18bf871
 
44529bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
acfee14
44529bb
 
 
 
 
 
 
da35c69
0450c4e
da35c69
 
44529bb
 
da35c69
 
 
 
44529bb
 
 
 
 
 
da35c69
44529bb
da35c69
44529bb
 
 
 
0450c4e
44529bb
 
 
 
 
0450c4e
da35c69
 
793be05
 
 
 
 
 
 
a06316f
793be05
 
 
 
 
 
 
 
 
27ff91e
 
 
 
 
793be05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44529bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
from dataclasses import dataclass
from typing import Any, Final

from llmdataparser.base_parser import (
    DatasetDescription,
    EvaluationMetric,
    HuggingFaceDatasetParser,
    HuggingFaceParseEntry,
)

MMLU_VALID_ANSWERS: Final[set[str]] = {"A", "B", "C", "D"}
MMLU_PRO_VALID_ANSWERS: Final[set[str]] = {
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
}
MMLU_VALID_ANSWER_STR: Final[str] = ", ".join(sorted(MMLU_VALID_ANSWERS))
MMLU_PRO_VALID_ANSWER_STR: Final[str] = ", ".join(sorted(MMLU_PRO_VALID_ANSWERS))


@dataclass(frozen=True, kw_only=True, slots=True)
class MMLUParseEntry(HuggingFaceParseEntry):
    """Custom entry class for MMLU, with fields specific to this dataset parser."""

    raw_choices: list[str]
    task_name: str

    @classmethod
    def create(
        cls,
        question: str,
        answer: str,
        raw_question: str,
        raw_choices: list[str],
        raw_answer: str,
        task_name: str,
    ) -> "MMLUParseEntry":
        if answer not in MMLU_VALID_ANSWERS:
            raise ValueError(
                f"Invalid answer_letter '{answer}'; must be one of {MMLU_VALID_ANSWER_STR}"
            )
        if not task_name:
            raise ValueError("Task name cannot be empty")
        return cls(
            question=question,
            answer=answer,
            raw_question=raw_question,
            raw_answer=raw_answer,
            raw_choices=raw_choices,
            task_name=task_name,
        )


@dataclass(frozen=True, kw_only=True, slots=True)
class MMLUProParseEntry(HuggingFaceParseEntry):
    """Custom entry class for MMLU, with fields specific to this dataset parser."""

    raw_choices: list[str]
    task_name: str

    @classmethod
    def create(
        cls,
        question: str,
        answer: str,
        raw_question: str,
        raw_choices: list[str],
        raw_answer: str,
        task_name: str,
    ) -> "MMLUProParseEntry":
        if answer not in MMLU_PRO_VALID_ANSWERS:
            raise ValueError(
                f"Invalid answer_letter '{answer}'; must be one of {MMLU_PRO_VALID_ANSWER_STR}"
            )
        if not task_name:
            raise ValueError("Task name cannot be empty")
        return cls(
            question=question,
            answer=answer,
            raw_question=raw_question,
            raw_choices=raw_choices,
            raw_answer=raw_answer,
            task_name=task_name,
        )


class MMLUDatasetParser(HuggingFaceDatasetParser[MMLUParseEntry]):
    """Base class for MMLU dataset parsers with common functionality."""

    def _get_task_from_entry(self, data_entry: dict[str, Any]) -> str:
        """Get the task name from the data entry or default task name."""
        task_name: str = data_entry.get("subject", "")
        return task_name if task_name else (self._current_task or self._default_task)

    def process_entry(
        self, row: dict[str, Any], task_name: str | None = None, **kwargs: Any
    ) -> MMLUParseEntry:
        """
        Generate a question and expected answer from the given row.

        Args:
            row: A data point to be formatted.
            task_name: Optional task name for the entry.
            **kwargs: Additional keyword arguments.

        Returns:
            MMLUParseEntry: The formatted entry object.
        """
        task = task_name or self._get_current_task(row)
        # Ensure task is not None
        final_task = task or self._default_task

        choices = "\n".join(
            f"{chr(65 + i)}. {choice}" for i, choice in enumerate(row["choices"])
        )
        raw_question = row["question"]
        raw_choices = row["choices"]
        raw_answer = str(row["answer"])  # Ensure raw_answer is a string

        question = f"Question: {raw_question}\n{choices}\nAnswer:"
        answer_letter = chr(65 + int(raw_answer))  # Convert index to 'A', 'B', 'C', 'D'

        return MMLUParseEntry.create(
            question=question,
            answer=answer_letter,
            raw_question=raw_question,
            raw_choices=raw_choices,
            raw_answer=raw_answer,
            task_name=final_task,
        )


class BaseMMLUDatasetParser(MMLUDatasetParser):
    """Parser for the original MMLU dataset."""

    _data_source = "cais/mmlu"
    _default_task = "all"
    _task_names = [
        "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",
    ]

    def get_dataset_description(self) -> DatasetDescription:
        """Returns a description of the MMLU dataset."""
        return DatasetDescription.create(
            name="Massive Multitask Language Understanding (MMLU)",
            purpose="Evaluate models' extensive world knowledge and problem-solving abilities across diverse branches of knowledge",
            source="https://huggingface.co/datasets/cais/mmlu",
            language="English",
            category=["General Knowledge and Reasoning"],
            format="Multiple choice questions with four options (A, B, C, D)",
            characteristics=(
                "Comprehensive evaluation benchmark spanning humanities, social sciences, hard sciences, "
                "and other essential areas of knowledge. The test includes 57 subjects such as "
                "elementary mathematics, US history, computer science, and law. Success on this test "
                "requires both extensive world knowledge and strong problem-solving capabilities."
            ),
            citation="""@article{hendryckstest2021,
    title={Measuring Massive Multitask Language Understanding},
    author={Dan Hendrycks and Collin Burns and Steven Basart and Andy Zou and Mantas Mazeika and Dawn Song and Jacob Steinhardt},
    journal={Proceedings of the International Conference on Learning Representations (ICLR)},
    year={2021}
    }
@article{hendrycks2021ethics,
    title={Aligning AI With Shared Human Values},
    author={Dan Hendrycks and Collin Burns and Steven Basart and Andrew Critch and Jerry Li and Dawn Song and Jacob Steinhardt},
    journal={Proceedings of the International Conference on Learning Representations (ICLR)},
    year={2021}
    }""",
            additional_info={
                "subjects": "57 tasks/subjects",
                "categories": [
                    "Humanities",
                    "Social Sciences",
                    "Hard Sciences",
                    "Other",
                ],
                "example_subjects": [
                    "Elementary Mathematics",
                    "US History",
                    "Computer Science",
                    "Law",
                ],
                "requirements": [
                    "Extensive world knowledge",
                    "Problem solving ability",
                ],
            },
        )

    def get_evaluation_metrics(self) -> list[EvaluationMetric]:
        """Returns the recommended evaluation metrics for MMLU dataset."""
        return [
            EvaluationMetric.create(
                name="accuracy",
                type="classification",
                description="Proportion of correctly answered multiple-choice questions (exact match with A, B, C, D)",
                implementation="evaluate.load('accuracy')",
                primary=True,
            ),
            EvaluationMetric.create(
                name="subject_accuracy",
                type="classification",
                description="Per-subject accuracy scores across all 57 tasks",
                implementation="custom_subject_accuracy",
                primary=True,
            ),
            EvaluationMetric.create(
                name="category_accuracy",
                type="classification",
                description="Accuracy grouped by major categories (Humanities, Social Sciences, Hard Sciences, Other)",
                implementation="custom_category_accuracy",
                primary=True,
            ),
            EvaluationMetric.create(
                name="task_correlation",
                type="analysis",
                description="Analysis of performance correlations between different subjects/tasks",
                implementation="custom_task_correlation",
                primary=False,
            ),
        ]


class MMLUReduxDatasetParser(MMLUDatasetParser):
    """Parser for the MMLU Redux dataset."""

    _data_source = "edinburgh-dawg/mmlu-redux"
    _default_task = "anatomy"
    _task_names = [
        "anatomy",
        "astronomy",
        "business_ethics",
        "clinical_knowledge",
        "college_chemistry",
        "college_computer_science",
        "college_mathematics",
        "college_medicine",
        "college_physics",
        "conceptual_physics",
        "econometrics",
        "electrical_engineering",
        "formal_logic",
        "global_facts",
        "high_school_chemistry",
        "high_school_geography",
        "high_school_macroeconomics",
        "high_school_mathematics",
        "high_school_physics",
        "high_school_statistics",
        "high_school_us_history",
        "human_aging",
        "logical_fallacies",
        "machine_learning",
        "miscellaneous",
        "philosophy",
        "professional_accounting",
        "professional_law",
        "public_relations",
        "virology",
    ]

    def get_dataset_description(self) -> DatasetDescription:
        """Returns description of the MMLU Redux dataset."""
        return DatasetDescription.create(
            name="MMLU Redux",
            purpose="Provide a manually re-annotated subset of MMLU with error analysis and corrections",
            source="https://huggingface.co/datasets/edinburgh-dawg/mmlu-redux",
            language="English",
            format="Multiple choice questions with four options (A, B, C, D)",
            category=["General Knowledge and Reasoning"],
            characteristics=(
                "A carefully curated subset of 3,000 questions across 30 MMLU subjects, "
                "manually re-annotated to identify and classify various types of errors. "
                "The dataset maintains the original questions but provides additional "
                "error annotations and corrections based on expert review and verification "
                "against credible sources."
            ),
            citation="""@misc{gema2024mmlu,
    title={Are We Done with MMLU?},
    author={Aryo Pradipta Gema and Joshua Ong Jun Leang and Giwon Hong and Alessio Devoto and Alberto Carlo Maria Mancino and Rohit Saxena and Xuanli He and Yu Zhao and Xiaotang Du and Mohammad Reza Ghasemi Madani and Claire Barale and Robert McHardy and Joshua Harris and Jean Kaddour and Emile van Krieken and Pasquale Minervini},
    year={2024},
    eprint={2406.04127},
    archivePrefix={arXiv},
    primaryClass={cs.CL}
    }""",
            additional_info={
                "size": "3,000 questions (100 per subject)",
                "subjects": "30 MMLU subjects",
                "license": "CC-BY-4.0",
                "error_types": {
                    "Question Assessment": [
                        "Bad Question Clarity",
                        "Bad Options Clarity",
                    ],
                    "Ground Truth Verification": [
                        "No Correct Answer",
                        "Multiple Correct Answers",
                        "Wrong Ground Truth",
                    ],
                },
                "verification_process": "Expert review with source verification",
                "base_dataset": "cais/mmlu",
            },
        )

    def get_evaluation_metrics(self) -> list[EvaluationMetric]:
        """Returns the recommended evaluation metrics for MMLU Redux dataset."""
        return [
            EvaluationMetric.create(
                name="accuracy",
                type="classification",
                description="Proportion of correctly answered multiple-choice questions (exact match with A, B, C, D)",
                implementation="evaluate.load('accuracy')",
                primary=True,
            ),
            EvaluationMetric.create(
                name="subject_accuracy",
                type="classification",
                description="Per-subject accuracy scores across 30 subjects (100 questions each)",
                implementation="custom_subject_accuracy",
                primary=True,
            ),
            EvaluationMetric.create(
                name="question_clarity",
                type="analysis",
                description="Analysis of performance on questions with different clarity issues",
                implementation="custom_clarity_analysis",
                primary=False,
            ),
        ]


class TMMLUPlusDatasetParser(MMLUDatasetParser):
    """Parser for the TMMLU+ dataset."""

    _data_source = "ikala/tmmluplus"
    _default_task = "taiwanese_hokkien"
    _task_names = [
        "engineering_math",
        "dentistry",
        "traditional_chinese_medicine_clinical_medicine",
        "clinical_psychology",
        "technical",
        "culinary_skills",
        "mechanical",
        "logic_reasoning",
        "real_estate",
        "general_principles_of_law",
        "finance_banking",
        "anti_money_laundering",
        "ttqav2",
        "marketing_management",
        "business_management",
        "organic_chemistry",
        "advance_chemistry",
        "physics",
        "secondary_physics",
        "human_behavior",
        "national_protection",
        "jce_humanities",
        "politic_science",
        "agriculture",
        "official_document_management",
        "financial_analysis",
        "pharmacy",
        "educational_psychology",
        "statistics_and_machine_learning",
        "management_accounting",
        "introduction_to_law",
        "computer_science",
        "veterinary_pathology",
        "accounting",
        "fire_science",
        "optometry",
        "insurance_studies",
        "pharmacology",
        "taxation",
        "trust_practice",
        "geography_of_taiwan",
        "physical_education",
        "auditing",
        "administrative_law",
        "education_(profession_level)",
        "economics",
        "veterinary_pharmacology",
        "nautical_science",
        "occupational_therapy_for_psychological_disorders",
        "basic_medical_science",
        "macroeconomics",
        "trade",
        "chinese_language_and_literature",
        "tve_design",
        "junior_science_exam",
        "junior_math_exam",
        "junior_chinese_exam",
        "junior_social_studies",
        "tve_mathematics",
        "tve_chinese_language",
        "tve_natural_sciences",
        "junior_chemistry",
        "music",
        "education",
        "three_principles_of_people",
        "taiwanese_hokkien",
    ]

    def process_entry(
        self, row: dict[str, Any], task_name: str | None = None, **kwargs: Any
    ) -> MMLUParseEntry:
        """Process a single TMMLU+ entry."""
        # Extract choices in order
        raw_choices = [row["A"], row["B"], row["C"], row["D"]]
        choices = "\n".join(
            f"{chr(65 + i)}. {choice}" for i, choice in enumerate(raw_choices)
        )
        raw_question = row["question"]
        raw_answer = row["answer"]

        question = f"Question: {raw_question}\n{choices}\nAnswer:"
        task = task_name or self._get_current_task(row)

        return MMLUParseEntry.create(
            question, raw_answer, raw_question, raw_choices, raw_answer, task
        )

    def get_dataset_description(self) -> DatasetDescription:
        """Returns description of the TMMLU+ dataset."""
        return DatasetDescription.create(
            name="Traditional Chinese Massive Multitask Language Understanding Plus (TMMLU+)",
            purpose="Evaluate language models' understanding and reasoning capabilities in Traditional Chinese across diverse subjects",
            source="https://huggingface.co/datasets/ikala/tmmluplus",
            language="Traditional Chinese",
            category=["General Knowledge and Reasoning", "Taiwan"],
            format="Multiple choice questions with four options (A, B, C, D)",
            characteristics=(
                "A comprehensive evaluation benchmark featuring 66 subjects from elementary "
                "to professional level. The dataset is six times larger than the original TMMLU "
                "and provides more balanced subject coverage. Includes benchmark results from "
                "both closed-source models and 20 open-weight Chinese language models with "
                "parameters ranging from 1.8B to 72B."
            ),
            citation="""@article{ikala2024improved,
    title={An Improved Traditional Chinese Evaluation Suite for Foundation Model},
    author={Tam, Zhi-Rui and Pai, Ya-Ting and Lee, Yen-Wei and Cheng, Sega and Shuai, Hong-Han},
    journal={arXiv preprint arXiv:2403.01858},
    year={2024}
    }""",
            additional_info={
                "subjects": "66 diverse subjects",
                "difficulty_levels": ["Elementary", "Secondary", "Professional"],
                "model_benchmarks": {
                    "model_types": ["Closed-source models", "Open-weight Chinese LLMs"],
                    "parameter_range": "1.8B - 72B",
                },
                "comparison": "6x larger than original TMMLU",
                "script": "Traditional Chinese",
            },
        )

    def get_evaluation_metrics(self) -> list[EvaluationMetric]:
        """Returns the recommended evaluation metrics for TMMLU+ dataset."""
        return [
            EvaluationMetric.create(
                name="accuracy",
                type="classification",
                description="Overall percentage of correctly answered multiple-choice questions",
                implementation="evaluate.load('accuracy')",
                primary=True,
            ),
            EvaluationMetric.create(
                name="subject_accuracy",
                type="classification",
                description="Per-subject accuracy scores across all 66 subjects",
                implementation="custom_subject_accuracy",
                primary=True,
            ),
            EvaluationMetric.create(
                name="difficulty_analysis",
                type="classification",
                description="Performance analysis across different difficulty levels (elementary to professional)",
                implementation="custom_difficulty_analysis",
                primary=False,
            ),
        ]


class MMLUProDatasetParser(HuggingFaceDatasetParser[MMLUProParseEntry]):
    """Parser for the MMLU Pro dataset."""

    _data_source = "TIGER-Lab/MMLU-Pro"
    _default_task = "default"
    _task_names = ["default"]
    _hidden_task_names = [
        "math",
        "physics",
        "chemistry",
        "law",
        "engineering",
        "other",
        "economics",
        "health",
        "psychology",
        "business",
        "biology",
        "philosophy",
        "computer_science",
        "history",
    ]

    def _get_task_from_entry(self, data_entry: dict[str, Any]) -> str:
        """Get the task name from the data entry or default task name."""
        if data_entry is not None:
            task_name: str = data_entry.get("category", "")
            if task_name:
                return task_name
        return self._current_task or self._default_task

    def process_entry(
        self, row: dict[str, Any], task_name: str | None = None, **kwargs: Any
    ) -> MMLUProParseEntry:
        """
        Generate a question and expected answer from the given row.

        Args:
            row (dict[str, Any]): A data point to be formatted with MMLU Pro specific structure
                containing 'question', 'options', 'answer', and 'answer_index' keys.

        Returns:
            MMLUParseEntry: The formatted entry object.
        """
        task = task_name or self._get_current_task(row)
        # Ensure task is not None
        final_task = task or self._default_task

        # Extract choices in order
        raw_choices = row["options"]
        choices = "\n".join(
            f"{chr(65 + i)}. {choice}" for i, choice in enumerate(raw_choices)
        )
        raw_question = row["question"]
        raw_answer = row["answer"]
        answer_index = row["answer_index"]

        question = f"Question: {raw_question}\n{choices}\nAnswer:"
        answer_letter = chr(
            65 + answer_index
        )  # Convert index to 'A', 'B', 'C', 'D', etc.

        return MMLUProParseEntry.create(
            question, answer_letter, raw_question, raw_choices, raw_answer, final_task
        )

    def get_dataset_description(self) -> DatasetDescription:
        """Returns description of the MMLU Pro dataset."""
        return DatasetDescription.create(
            name="MMLU Pro",
            purpose="Provide a more robust and challenging multi-task language understanding benchmark with enhanced reasoning requirements",
            source="https://huggingface.co/datasets/TIGER-Lab/MMLU-Pro",
            language="English",
            category=["General Knowledge and Reasoning", "Advanced Reasoning"],
            format="Multiple choice questions with up to 10 options (expanded from original 4)",
            characteristics=(
                "A more challenging version of MMLU containing 12K complex questions across various "
                "disciplines. Features increased number of options (up to 10), stronger focus on "
                "reasoning over pure knowledge, and reduced sensitivity to prompt variations. "
                "Questions are sourced from original MMLU, STEM websites, TheoremQA, and SciBench, "
                "with expert review and GPT-4 assisted distractor generation."
            ),
            citation="""@article{wang2024mmlu,
    title={Mmlu-pro: A more robust and challenging multi-task language understanding benchmark},
    author={Wang, Yubo and Ma, Xueguang and Zhang, Ge and Ni, Yuansheng and Chandra, Abhranil and Guo, Shiguang and Ren, Weiming and Arulraj, Aaran and He, Xuan and Jiang, Ziyan and others},
    journal={arXiv preprint arXiv:2406.01574},
    year={2024}
    }""",
            additional_info={
                "size": "12,000 complex questions",
                "options": "Up to 10 choices per question",
                "sources": [
                    "Original MMLU (filtered)",
                    "STEM Website",
                    "TheoremQA",
                    "SciBench",
                ],
                "enhanced_subjects": [
                    "Biology",
                    "Business",
                    "Chemistry",
                    "Computer Science",
                    "Economics",
                    "Engineering",
                    "Math",
                    "Physics",
                    "Psychology",
                ],
                "construction_process": [
                    "Initial MMLU filtering",
                    "Question collection from multiple sources",
                    "GPT-4 assisted option augmentation",
                    "Expert review by 10+ experts",
                ],
                "prompt_sensitivity": "2% (reduced from 4-5% in MMLU)",
                "reasoning_improvement": "20% higher CoT performance compared to PPL",
            },
        )

    def get_evaluation_metrics(self) -> list[EvaluationMetric]:
        """Returns the recommended evaluation metrics for MMLU Pro dataset."""
        return [
            EvaluationMetric.create(
                name="accuracy",
                type="classification",
                description="Proportion of correctly answered multiple-choice questions (exact match)",
                implementation="evaluate.load('accuracy')",
                primary=True,
            ),
            EvaluationMetric.create(
                name="subject_accuracy",
                type="classification",
                description="Per-subject accuracy scores with focus on enhanced subjects",
                implementation="custom_subject_accuracy",
                primary=True,
            ),
            EvaluationMetric.create(
                name="reasoning_analysis",
                type="analysis",
                description="Comparison of Chain-of-Thought vs standard PPL performance",
                implementation="custom_reasoning_analysis",
                primary=True,
            ),
            EvaluationMetric.create(
                name="prompt_robustness",
                type="analysis",
                description="Analysis of performance stability across different prompt variations",
                implementation="custom_prompt_sensitivity",
                primary=False,
            ),
        ]


if __name__ == "__main__":
    # Example usage of MMLU Pro parser
    parser = MMLUProDatasetParser()
    parser.load()
    parser.parse()

    # Get parsed data with correct type
    parsed_data = parser.get_parsed_data

    # Print example entry
    if parsed_data:
        example = parsed_data[0]
        print("\nExample parsed entry:")
        print(f"Task: {example.task_name}")
        print(f"Question: {example.raw_question}")
        print("Choices:")
        for i, choice in enumerate(example.raw_choices):
            print(f"{chr(65 + i)}. {choice}")
        print(f"Correct Answer: {example.answer}")