evaluator.py 7.19 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
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#
# This code is inspired by the Dan's test library.
# https://github.com/hendrycks/test/blob/master/evaluate_flan.py
#
# 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.
#
# MIT License
#
# Copyright (c) 2020 Dan Hendrycks
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
39
40
41

import json
import os
chenych's avatar
chenych committed
42
from typing import TYPE_CHECKING, Any, Optional
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
43
44
45
46
47
48
49
50
51
52
53
54
55
56

import numpy as np
import torch
from datasets import load_dataset
from tqdm import tqdm, trange
from transformers.utils import cached_file

from ..data import get_template_and_fix_tokenizer
from ..extras.constants import CHOICES, SUBJECTS
from ..hparams import get_eval_args
from ..model import load_model, load_tokenizer
from .template import get_eval_template


luopl's avatar
luopl committed
57
58
59
60
if TYPE_CHECKING:
    from numpy.typing import NDArray


Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
61
class Evaluator:
chenych's avatar
chenych committed
62
    def __init__(self, args: Optional[dict[str, Any]] = None) -> None:
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
63
        self.model_args, self.data_args, self.eval_args, finetuning_args = get_eval_args(args)
chenych's avatar
chenych committed
64
        self.tokenizer = load_tokenizer(self.model_args)["tokenizer"]
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
65
        self.tokenizer.padding_side = "right"  # avoid overflow issue in batched inference for llama2
luopl's avatar
luopl committed
66
        self.template = get_template_and_fix_tokenizer(self.tokenizer, self.data_args)
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
67
68
        self.model = load_model(self.tokenizer, self.model_args, finetuning_args)
        self.eval_template = get_eval_template(self.eval_args.lang)
chenych's avatar
chenych committed
69
        self.choice_inputs = [self.tokenizer.encode(ch, add_special_tokens=False)[-1] for ch in CHOICES]
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
70
71

    @torch.inference_mode()
chenych's avatar
chenych committed
72
    def batch_inference(self, batch_input: dict[str, "torch.Tensor"]) -> list[str]:
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
73
74
75
76
77
78
79
        logits = self.model(**batch_input).logits
        lengths = torch.sum(batch_input["attention_mask"], dim=-1)
        word_probs = torch.stack([logits[i, lengths[i] - 1] for i in range(len(lengths))], dim=0)
        choice_probs = torch.nn.functional.softmax(word_probs[:, self.choice_inputs], dim=-1).detach()
        return [chr(ord("A") + offset.item()) for offset in torch.argmax(choice_probs, dim=-1)]

    def eval(self) -> None:
chenych's avatar
chenych committed
80
81
82
        eval_task = self.eval_args.task.split("_")[0]
        eval_split = self.eval_args.task.split("_")[1]

Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
83
        mapping = cached_file(
chenych's avatar
chenych committed
84
            path_or_repo_id=os.path.join(self.eval_args.task_dir, eval_task),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
85
86
87
88
89
            filename="mapping.json",
            cache_dir=self.model_args.cache_dir,
            token=self.model_args.hf_hub_token,
        )

luopl's avatar
luopl committed
90
        with open(mapping, encoding="utf-8") as f:
chenych's avatar
chenych committed
91
            categorys: dict[str, dict[str, str]] = json.load(f)
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
92
93
94
95
96
97

        category_corrects = {subj: np.array([], dtype="bool") for subj in SUBJECTS}
        pbar = tqdm(categorys.keys(), desc="Processing subjects", position=0)
        results = {}
        for subject in pbar:
            dataset = load_dataset(
chenych's avatar
chenych committed
98
                path=os.path.join(self.eval_args.task_dir, eval_task),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
99
100
101
102
                name=subject,
                cache_dir=self.model_args.cache_dir,
                download_mode=self.eval_args.download_mode,
                token=self.model_args.hf_hub_token,
luopl's avatar
luopl committed
103
                trust_remote_code=self.model_args.trust_remote_code,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
104
105
106
            )
            pbar.set_postfix_str(categorys[subject]["name"])
            inputs, outputs, labels = [], [], []
chenych's avatar
chenych committed
107
            for i in trange(len(dataset[eval_split]), desc="Formatting batches", position=1, leave=False):
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
108
109
110
111
                support_set = (
                    dataset["train"].shuffle().select(range(min(self.eval_args.n_shot, len(dataset["train"]))))
                )
                messages = self.eval_template.format_example(
chenych's avatar
chenych committed
112
                    target_data=dataset[eval_split][i],
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
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
                    support_set=support_set,
                    subject_name=categorys[subject]["name"],
                )

                input_ids, _ = self.template.encode_oneturn(tokenizer=self.tokenizer, messages=messages)
                inputs.append({"input_ids": input_ids, "attention_mask": [1] * len(input_ids)})
                labels.append(messages[-1]["content"])

            for i in trange(
                0, len(inputs), self.eval_args.batch_size, desc="Predicting batches", position=1, leave=False
            ):
                batch_input = self.tokenizer.pad(
                    inputs[i : i + self.eval_args.batch_size], return_attention_mask=True, return_tensors="pt"
                ).to(self.model.device)
                preds = self.batch_inference(batch_input)
                outputs += preds

            corrects = np.array(outputs) == np.array(labels)
            category_name = categorys[subject]["category"]
            category_corrects[category_name] = np.concatenate([category_corrects[category_name], corrects], axis=0)
            category_corrects["Average"] = np.concatenate([category_corrects["Average"], corrects], axis=0)
            results[subject] = {str(i): outputs[i] for i in range(len(outputs))}

        pbar.close()
        self._save_results(category_corrects, results)

chenych's avatar
chenych committed
139
    def _save_results(self, category_corrects: dict[str, "NDArray"], results: dict[str, dict[int, str]]) -> None:
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
140
141
        score_info = "\n".join(
            [
luopl's avatar
luopl committed
142
                f"{category_name:>15}: {100 * np.mean(category_correct):.2f}"
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
143
144
145
146
147
148
149
150
151
152
153
154
155
156
                for category_name, category_correct in category_corrects.items()
                if len(category_correct)
            ]
        )
        print(score_info)
        if self.eval_args.save_dir is not None:
            os.makedirs(self.eval_args.save_dir, exist_ok=False)
            with open(os.path.join(self.eval_args.save_dir, "results.json"), "w", encoding="utf-8", newline="\n") as f:
                json.dump(results, f, indent=2)

            with open(os.path.join(self.eval_args.save_dir, "results.log"), "w", encoding="utf-8", newline="\n") as f:
                f.write(score_info)


chenych's avatar
chenych committed
157
158
def run_eval() -> None:
    Evaluator().eval()