template.py 2.8 KB
Newer Older
chenych's avatar
chenych committed
1
# Copyright 2025 the LlamaFactory team.
chenych's avatar
chenych committed
2
3
4
5
6
7
8
9
10
11
12
13
14
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
15
16
17
18
19
20
21
22
23
24
25
26
from dataclasses import dataclass

from ..data import Role
from ..extras.constants import CHOICES


@dataclass
class EvalTemplate:
    system: str
    choice: str
    answer: str

chenych's avatar
chenych committed
27
28
29
    def _parse_example(self, example: dict[str, str]) -> tuple[str, str]:
        r"""Parse eval example.

Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
30
        input: a dict with keys {"question", "A", "B", "C", "D", "answer"}
chenych's avatar
chenych committed
31
        output: a tuple of (prompt, response).
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
32
33
34
35
36
        """
        candidates = [self.choice.format(choice=ch, content=example[ch]) for ch in CHOICES if ch in example]
        return "".join([example["question"]] + candidates + [self.answer]), example["answer"]

    def format_example(
chenych's avatar
chenych committed
37
38
39
        self, target_data: dict[str, str], support_set: list[dict[str, str]], subject_name: str
    ) -> list[dict[str, str]]:
        r"""Convert dataset examples to messages."""
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
40
41
42
43
44
45
46
47
48
49
50
51
52
        messages = []
        for k in range(len(support_set)):
            prompt, response = self._parse_example(support_set[k])
            messages.append({"role": Role.USER.value, "content": prompt})
            messages.append({"role": Role.ASSISTANT.value, "content": response})

        prompt, response = self._parse_example(target_data)
        messages.append({"role": Role.USER.value, "content": prompt})
        messages.append({"role": Role.ASSISTANT.value, "content": response})
        messages[0]["content"] = self.system.format(subject=subject_name) + messages[0]["content"]
        return messages


chenych's avatar
chenych committed
53
eval_templates: dict[str, "EvalTemplate"] = {}
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
54
55


chenych's avatar
chenych committed
56
57
def _register_eval_template(name: str, system: str, choice: str, answer: str) -> None:
    eval_templates[name] = EvalTemplate(system=system, choice=choice, answer=answer)
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
58
59
60
61


def get_eval_template(name: str) -> "EvalTemplate":
    eval_template = eval_templates.get(name, None)
luopl's avatar
luopl committed
62
    assert eval_template is not None, f"Template {name} does not exist."
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
63
64
65
66
67
68
69
    return eval_template


_register_eval_template(
    name="en",
    system="The following are multiple choice questions (with answers) about {subject}.\n\n",
    choice="\n{choice}. {content}",
chenych's avatar
chenych committed
70
    answer="\nAnswer:",
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
71
72
73
74
75
76
77
78
79
)


_register_eval_template(
    name="zh",
    system="以下是中国关于{subject}考试的单项选择题,请选出其中的正确答案。\n\n",
    choice="\n{choice}. {content}",
    answer="\n答案:",
)