File size: 14,812 Bytes
5db30ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import json
import re
from typing import Any, Iterator

from elbench.loaders.base import BaseLoader
from elbench.registry import ResolvedRegistryItem
from elbench.schemas.evaluation import RawRecord, Sample


class MMLUProJsonlLoader(BaseLoader):
    def iter_raw_records(self, item: ResolvedRegistryItem) -> Iterator[RawRecord]:
        with item.path.open("r", encoding="utf-8") as handle:
            for row_index, line in enumerate(handle, start=1):
                if not line.strip():
                    continue
                yield RawRecord(
                    source_path=str(item.path),
                    source_file=item.entry.canonical_name,
                    row_index=row_index,
                    record=json.loads(line),
                )

    def iter_samples(self, item: ResolvedRegistryItem) -> Iterator[Sample]:
        for raw_record in self.iter_raw_records(item):
            record = raw_record.record
            target = self._string_or_none(record.get("target"))
            choices = self._choices(record.get("choices"))
            metadata = self._metadata(record, raw_record.row_index)
            dimension = self._dimension(record, metadata)
            yield Sample(
                sample_id=self._sample_id(
                    item.entry.canonical_name,
                    record,
                    raw_record.row_index,
                    namespace=dimension,
                ),
                source_file=item.entry.canonical_name,
                source_path=str(item.path),
                module=item.entry.module,
                subset=item.entry.subset,
                task=item.entry.task,
                dimension=dimension,
                prompt=self._build_zero_shot_prompt(record, choices, item.entry.task),
                reference={"target": target},
                metadata=metadata,
                raw_record=record,
            )

    def _build_zero_shot_prompt(self, record: dict[str, Any], choices: list[str], task: str | None) -> str:
        question = self._extract_question(record)
        option_lines = [f"{chr(65 + index)}) {choice}" for index, choice in enumerate(choices)]
        letters = ",".join(chr(65 + index) for index in range(len(choices)))
        if task == "ceval":
            return "\n".join(
                [
                    "请回答以下单项选择题。",
                    "请先逐步思考,再给出答案。",
                    f"你回答的最后一行必须严格使用格式:答案:[LETTER],其中 [LETTER] 是 {letters} 中的一个。",
                    "",
                    "问题:",
                    question,
                    "选项:",
                    *option_lines,
                ]
            )
        return "\n".join(
            [
                "Answer the following multiple choice question.",
                "Think step by step before answering.",
                f"The last line of your response must be exactly: ANSWER: [LETTER], where [LETTER] is one of {letters}.",
                "",
                "Question:",
                question,
                "Options:",
                *option_lines,
            ]
        )

    def _extract_question(self, record: dict[str, Any]) -> str:
        input_messages = record.get("input")
        if isinstance(input_messages, list):
            for message in reversed(input_messages):
                if not isinstance(message, dict):
                    continue
                content = message.get("content")
                if not isinstance(content, str):
                    continue
                matches = re.findall(r"Question:\n(.*?)\nOptions:", content, flags=re.S)
                if not matches:
                    matches = re.findall(r"问题[::]\s*(.*?)\n选项[::]", content, flags=re.S)
                if matches:
                    return matches[-1].strip()
        raise ValueError("Cannot extract multiple-choice question from input messages.")

    def _metadata(self, record: dict[str, Any], row_index: int) -> dict[str, Any]:
        metadata = {}
        raw_metadata = record.get("metadata")
        if isinstance(raw_metadata, dict):
            metadata.update(raw_metadata)
        metadata["choices"] = self._choices(record.get("choices"))
        metadata["subset_key"] = self._string_or_none(record.get("subset_key"))
        metadata["row_index"] = row_index
        return metadata

    def _dimension(self, record: dict[str, Any], metadata: dict[str, Any]) -> str | None:
        return (
            self._string_or_none(record.get("subset_key"))
            or self._string_or_none(metadata.get("subject"))
            or self._string_or_none(metadata.get("id"))
        )

    def _sample_id(
        self,
        canonical_name: str,
        record: dict[str, Any],
        row_index: int,
        namespace: str | None = None,
    ) -> str:
        value = record.get("id")
        if value in (None, ""):
            value = row_index
        value_part = self._slug_component(value)
        namespace_part = self._slug_component(namespace)
        if namespace_part:
            return f"{canonical_name.replace('.', '_')}-{namespace_part}-{value_part}"
        return f"{canonical_name.replace('.', '_')}-{value_part}"

    def _choices(self, value: Any) -> list[str]:
        if not isinstance(value, list) or not value:
            raise ValueError("Multiple-choice record must contain a non-empty choices list.")
        return [str(choice) for choice in value]

    def _string_or_none(self, value: Any) -> str | None:
        if value in (None, ""):
            return None
        return str(value)

    def _slug_component(self, value: Any) -> str:
        if value in (None, ""):
            return ""
        text = re.sub(r"[^\w]+", "_", str(value)).strip("_")
        return text or str(value)

    def expected_answer_from_sample(self, sample: Sample) -> str | None:
        reference = sample.reference or {}
        if isinstance(reference, dict):
            value = reference.get("target")
        else:
            value = reference
        if value in (None, ""):
            return None
        normalized = str(value).strip().upper()
        return normalized[0] if normalized else None

    def valid_letters_from_sample(self, sample: Sample) -> list[str]:
        choices = sample.metadata.get("choices")
        if isinstance(choices, list) and choices:
            return [chr(65 + index) for index in range(len(choices))]
        return list("ABCDEFGHIJ")


class CEvalJsonlLoader(MMLUProJsonlLoader):
    pass


class IFEvalJsonlLoader(BaseLoader):
    def iter_raw_records(self, item: ResolvedRegistryItem) -> Iterator[RawRecord]:
        with item.path.open("r", encoding="utf-8") as handle:
            for row_index, line in enumerate(handle, start=1):
                if not line.strip():
                    continue
                yield RawRecord(
                    source_path=str(item.path),
                    source_file=item.entry.canonical_name,
                    row_index=row_index,
                    record=json.loads(line),
                )

    def iter_samples(self, item: ResolvedRegistryItem) -> Iterator[Sample]:
        for raw_record in self.iter_raw_records(item):
            record = raw_record.record
            metadata = self._metadata(record, raw_record.row_index)
            yield Sample(
                sample_id=self._sample_id(item.entry.canonical_name, record, raw_record.row_index),
                source_file=item.entry.canonical_name,
                source_path=str(item.path),
                module=item.entry.module,
                subset=item.entry.subset,
                task=item.entry.task,
                dimension="default",
                prompt=self._prompt(record, metadata),
                reference={"target": self._string_or_empty(record.get("target"))},
                metadata=metadata,
                raw_record=record,
            )

    def _metadata(self, record: dict[str, Any], row_index: int) -> dict[str, Any]:
        metadata: dict[str, Any] = {}
        raw_metadata = record.get("metadata")
        if isinstance(raw_metadata, dict):
            metadata.update(raw_metadata)

        metadata["instruction_id_list"] = self._instruction_ids(metadata.get("instruction_id_list"))
        metadata["kwargs"] = self._kwargs(metadata.get("kwargs"))
        metadata["key"] = self._string_or_empty(metadata.get("key"))
        metadata["prompt"] = self._prompt(record, metadata)
        metadata["row_index"] = row_index
        return metadata

    def _prompt(self, record: dict[str, Any], metadata: dict[str, Any]) -> str:
        prompt = metadata.get("prompt")
        if isinstance(prompt, str) and prompt:
            return prompt
        input_messages = record.get("input")
        if isinstance(input_messages, list):
            for message in input_messages:
                if isinstance(message, dict) and isinstance(message.get("content"), str):
                    return message["content"]
        return ""

    def _kwargs(self, value: Any) -> list[dict[str, Any]]:
        if not isinstance(value, list):
            return []
        parsed_kwargs = []
        for item in value:
            if isinstance(item, dict):
                parsed_kwargs.append(item)
                continue
            if isinstance(item, str):
                try:
                    parsed = json.loads(item)
                except json.JSONDecodeError:
                    parsed = {}
                parsed_kwargs.append(parsed if isinstance(parsed, dict) else {})
                continue
            parsed_kwargs.append({})
        return parsed_kwargs

    def _instruction_ids(self, value: Any) -> list[str]:
        if not isinstance(value, list):
            return []
        return [str(item) for item in value]

    def _sample_id(self, canonical_name: str, record: dict[str, Any], row_index: int) -> str:
        value = record.get("id")
        if value in (None, ""):
            value = row_index
        return f"{canonical_name.replace('.', '_')}-{value}"

    def _string_or_empty(self, value: Any) -> str:
        if value in (None, ""):
            return ""
        return str(value)

    def instruction_ids_from_sample(self, sample: Sample) -> list[str]:
        return self._instruction_ids(sample.metadata.get("instruction_id_list"))

    def kwargs_from_sample(self, sample: Sample) -> list[dict[str, Any]]:
        return self._kwargs(sample.metadata.get("kwargs"))

    def prompt_key_from_sample(self, sample: Sample) -> str:
        return self._string_or_empty(sample.metadata.get("key"))


class MATH500JsonlLoader(BaseLoader):
    def iter_raw_records(self, item: ResolvedRegistryItem) -> Iterator[RawRecord]:
        with item.path.open("r", encoding="utf-8") as handle:
            for row_index, line in enumerate(handle, start=1):
                if not line.strip():
                    continue
                yield RawRecord(
                    source_path=str(item.path),
                    source_file=item.entry.canonical_name,
                    row_index=row_index,
                    record=json.loads(line),
                )

    def iter_samples(self, item: ResolvedRegistryItem) -> Iterator[Sample]:
        for raw_record in self.iter_raw_records(item):
            record = raw_record.record
            metadata = self._metadata(record, raw_record.row_index)
            yield Sample(
                sample_id=self._sample_id(item.entry.canonical_name, record, raw_record.row_index),
                source_file=item.entry.canonical_name,
                source_path=str(item.path),
                module=item.entry.module,
                subset=item.entry.subset,
                task=item.entry.task,
                dimension=self._string_or_none(record.get("subset_key")) or "default",
                prompt=self._prompt(record),
                reference={"target": self._string_or_empty(record.get("target"))},
                metadata=metadata,
                raw_record=record,
            )

    def _metadata(self, record: dict[str, Any], row_index: int) -> dict[str, Any]:
        metadata: dict[str, Any] = {}
        raw_metadata = record.get("metadata")
        if isinstance(raw_metadata, dict):
            metadata.update(raw_metadata)
        metadata["subset_key"] = self._string_or_none(record.get("subset_key"))
        metadata["row_index"] = row_index
        return metadata

    def _prompt(self, record: dict[str, Any]) -> str:
        input_messages = record.get("input")
        if isinstance(input_messages, list):
            for message in input_messages:
                if isinstance(message, dict) and isinstance(message.get("content"), str):
                    return message["content"]
        return ""

    def _sample_id(self, canonical_name: str, record: dict[str, Any], row_index: int) -> str:
        value = record.get("id")
        subset_key = self._string_or_none(record.get("subset_key")) or "default"
        if value in (None, ""):
            value = row_index
        subset_slug = re.sub(r"[^A-Za-z0-9]+", "_", subset_key).strip("_").lower()
        return f"{canonical_name.replace('.', '_')}-{subset_slug}-{value}"

    def _string_or_none(self, value: Any) -> str | None:
        if value in (None, ""):
            return None
        return str(value)

    def _string_or_empty(self, value: Any) -> str:
        if value in (None, ""):
            return ""
        return str(value)

    def expected_answer_from_sample(self, sample: Sample) -> str:
        reference = sample.reference or {}
        if isinstance(reference, dict):
            value = reference.get("target")
        else:
            value = reference
        return "" if value in (None, "") else str(value)


class AIMEJsonlLoader(MATH500JsonlLoader):
    def iter_samples(self, item: ResolvedRegistryItem) -> Iterator[Sample]:
        for raw_record in self.iter_raw_records(item):
            record = raw_record.record
            metadata = self._metadata(record, raw_record.row_index)
            yield Sample(
                sample_id=self._sample_id(item.entry.canonical_name, record, raw_record.row_index),
                source_file=item.entry.canonical_name,
                source_path=str(item.path),
                module=item.entry.module,
                subset=item.entry.subset,
                task=item.entry.task,
                dimension="default",
                prompt=self._prompt(record),
                reference={"target": self._string_or_empty(record.get("target"))},
                metadata=metadata,
                raw_record=record,
            )