-
Notifications
You must be signed in to change notification settings - Fork 1
/
run_eval_llama_mmlu.py
190 lines (159 loc) · 6.76 KB
/
run_eval_llama_mmlu.py
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
# Test ElasticLlama model with pruning consistency and tuning consistency
import os
import sys
import torch
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
import loralib as lora
from transformers import (HfArgumentParser)
from args import MMLUDataTrainingArguments
from models.model_args import ModelArguments
from args import MinusTrainingArguments
from utils import build_trainer
from utils.utils import *
from models import build_model
import numpy as np
import pandas as pd
from tqdm import tqdm
from eval.mmlu.categories import subcategories, categories
from eval.utils import get_next_word_predictions
choices = ["A", "B", "C", "D"]
IGNORE_INDEX = -100
DEFAULT_PAD_TOKEN = "[PAD]"
DEFAULT_EOS_TOKEN = "</s>"
DEFAULT_BOS_TOKEN = "<s>"
DEFAULT_UNK_TOKEN = "<unk>"
PROMPT_DICT = {
"prompt_input": (
"Below is an instruction that describes a task, paired with an input that provides further context. "
"Write a response that appropriately completes the request.\n\n"
"### Instruction:\n{instruction}\n\n### Input:\n{input}\n\n### Response:"
),
"prompt_no_input": (
"Below is an instruction that describes a task. "
"Write a response that appropriately completes the request.\n\n"
"### Instruction:\n{instruction}\n\n### Response:"
),
}
def format_subject(subject):
l = subject.split("_")
s = ""
for entry in l:
s += " " + entry
return s
def format_example(df, idx, include_answer=True):
prompt = df.iloc[idx, 0]
k = df.shape[1] - 2
for j in range(k):
prompt += "\n{}. {}".format(choices[j], df.iloc[idx, j + 1])
prompt += "\nAnswer:"
if include_answer:
prompt += " {}\n\n".format(df.iloc[idx, k + 1])
return prompt
def gen_prompt(train_df, subject, k=-1):
prompt = "The following are multiple choice questions (with answers) about {}.\n\n".format(
format_subject(subject)
)
if k == -1:
k = train_df.shape[0]
for i in range(k):
prompt += format_example(train_df, i)
return prompt
@torch.no_grad()
def eval_hf_model(args, subject, model, tokenizer, dev_df, test_df, batch_size=1):
prompts = []
for i in range(0, test_df.shape[0]):
k = args.ntrain
prompt_end = format_example(test_df, i, include_answer=False)
train_prompt = gen_prompt(dev_df, subject, k)
prompt = train_prompt + prompt_end
tokenized_prompt = tokenizer(prompt, return_tensors="pt", add_special_tokens=False).input_ids
# make sure every prompt is less than 2048 tokens
while tokenized_prompt.shape[-1] > 2048:
k -= 1
train_prompt = gen_prompt(dev_df, subject, k)
prompt = train_prompt + prompt_end
tokenized_prompt = tokenizer(prompt, return_tensors="pt", add_special_tokens=False).input_ids
if args.use_chat_format:
prompt = "<|user|>\n" + prompt.strip() + "\n<|assistant|>\nThe answer is:"
prompts.append(prompt)
# get the answer for all examples
# note: here we cannot directly use convert_tokens_to_ids because the some tokenizers will automatically add space prefix.
answer_choice_ids = [tokenizer.encode(answer_choice, add_special_tokens=False)[0] for answer_choice in choices]
pred_indices, all_probs = get_next_word_predictions(
model, tokenizer, prompts, candidate_token_ids=answer_choice_ids, return_token_predictions=False, batch_size=batch_size
)
# get the metrics
cors = []
groud_truths = test_df.iloc[:, -1].values
for i in range(len(pred_indices)):
prediction = choices[pred_indices[i]]
ground_truth = groud_truths[i]
cors.append(prediction == ground_truth)
acc = np.mean(cors)
cors = np.array(cors)
all_probs = np.array(all_probs)
print("Average accuracy {:.3f} - {}".format(acc, subject))
return cors, acc, all_probs
def main():
parser = HfArgumentParser(
(ModelArguments, MMLUDataTrainingArguments, MinusTrainingArguments))
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
# If we pass only one argument to the script and it's the path to a json file,
# let's parse it to get our arguments.
model_args, data_args, training_args = parser.parse_json_file(
json_file=os.path.abspath(sys.argv[1]))
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
os.makedirs(training_args.output_dir, exist_ok=True)
# training_args.disable_tqdm = False
config, tokenizer, model = build_model(model_args, data_args, training_args, token=os.environ.get('HF_TOKEN', None))
model.head_mask, model.intermediate_mask, model.hidden_mask = None, None, None
for m in model.modules():
if isinstance(m, lora.LoRALayer):
m.scaling = 2
model = model.cuda()
model.eval()
subjects = sorted(
[
f.split("_test.csv")[0]
for f in os.listdir(os.path.join(data_args.data_dir, "test"))
if "_test.csv" in f
]
)
all_cors = []
subcat_cors = {
subcat: [] for subcat_lists in subcategories.values() for subcat in subcat_lists
}
cat_cors = {cat: [] for cat in categories}
for subject in tqdm(subjects, desc=f"Evaluating subjects: "):
dev_df = pd.read_csv(
os.path.join(data_args.data_dir, "dev", subject + "_dev.csv"), header=None
)[: data_args.ntrain]
test_df = pd.read_csv(
os.path.join(data_args.data_dir, "test", subject + "_test.csv"), header=None
)
if data_args.n_instances and data_args.n_instances < test_df.shape[0]:
test_df = test_df.sample(data_args.n_instances, random_state=42)
cors, acc, probs = eval_hf_model(data_args, subject, model, tokenizer, dev_df, test_df, data_args.eval_batch_size)
subcats = subcategories[subject]
for subcat in subcats:
subcat_cors[subcat].append(cors)
for key in categories.keys():
if subcat in categories[key]:
cat_cors[key].append(cors)
all_cors.append(cors)
test_df["correct"] = cors
for j in range(probs.shape[1]):
choice = choices[j]
test_df["choice{}_probs".format(choice)] = probs[:, j]
for subcat in subcat_cors:
subcat_acc = np.mean(np.concatenate(subcat_cors[subcat]))
print("Average accuracy {:.3f} - {}".format(subcat_acc, subcat))
for cat in cat_cors:
cat_acc = np.mean(np.concatenate(cat_cors[cat]))
print("Average accuracy {:.3f} - {}".format(cat_acc, cat))
weighted_acc = np.mean(np.concatenate(all_cors))
print("Average accuracy: {:.3f}".format(weighted_acc))
if __name__ == '__main__':
main()