|
|
|
@ -7,6 +7,7 @@ from transformers.generation.logits_process import LogitsProcessor
|
|
|
|
|
from transformers.generation.utils import LogitsProcessorList
|
|
|
|
|
from evaluators.evaluator import Evaluator
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class InvalidScoreLogitsProcessor(LogitsProcessor):
|
|
|
|
|
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
|
|
|
|
|
if torch.isnan(scores).any() or torch.isinf(scores).any():
|
|
|
|
@ -14,6 +15,7 @@ class InvalidScoreLogitsProcessor(LogitsProcessor):
|
|
|
|
|
scores[..., 5] = 5e4
|
|
|
|
|
return scores
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ChatGLM_Evaluator(Evaluator):
|
|
|
|
|
def __init__(self, choices, k, model_name, device, finetune=None):
|
|
|
|
|
super(ChatGLM_Evaluator, self).__init__(choices, model_name, k)
|
|
|
|
@ -21,7 +23,7 @@ class ChatGLM_Evaluator(Evaluator):
|
|
|
|
|
# or directly clone the model
|
|
|
|
|
self.tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True, mirror="tuna")
|
|
|
|
|
if finetune:
|
|
|
|
|
CHECKPOINT_PATH="ptuning/" + finetune
|
|
|
|
|
CHECKPOINT_PATH = "ptuning/" + finetune
|
|
|
|
|
config = AutoConfig.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True, pre_seq_len=128)
|
|
|
|
|
self.model = AutoModel.from_pretrained("THUDM/chatglm-6b", config=config, trust_remote_code=True)
|
|
|
|
|
prefix_state_dict = torch.load(os.path.join(CHECKPOINT_PATH, "pytorch_model.bin"))
|
|
|
|
@ -34,7 +36,8 @@ class ChatGLM_Evaluator(Evaluator):
|
|
|
|
|
self.model.transformer.prefix_encoder.float()
|
|
|
|
|
print("Model loaded! use GLM + " + finetune)
|
|
|
|
|
else:
|
|
|
|
|
self.model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True, mirror="tuna", resume_download=True).half().to(device)
|
|
|
|
|
self.model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True, mirror="tuna",
|
|
|
|
|
resume_download=True).half().to(device)
|
|
|
|
|
print("Model loaded!(GLM)")
|
|
|
|
|
|
|
|
|
|
# self.model = self.model.eval()
|
|
|
|
@ -45,6 +48,7 @@ class ChatGLM_Evaluator(Evaluator):
|
|
|
|
|
if few_shot:
|
|
|
|
|
result = []
|
|
|
|
|
score = []
|
|
|
|
|
answer_list = []
|
|
|
|
|
if few_shot:
|
|
|
|
|
history = self.generate_few_shot_prompt(subject_name, dev_df, cot=cot)
|
|
|
|
|
else:
|
|
|
|
@ -58,7 +62,8 @@ class ChatGLM_Evaluator(Evaluator):
|
|
|
|
|
# For ChatGLM, we use answer extraction in answer-only mode too.
|
|
|
|
|
ans, direct_extract = self.extract_cot_answer(row, response)
|
|
|
|
|
else: # zero-shot by extracting answer from distribution
|
|
|
|
|
ans = self.generate_dist(self.model, self.tokenizer, question, do_sample=False, max_length=2048, history=history)
|
|
|
|
|
ans = self.generate_dist(self.model, self.tokenizer, question, do_sample=False, max_length=2048,
|
|
|
|
|
history=history)
|
|
|
|
|
if ans == answers[row_index]:
|
|
|
|
|
correct_num += 1
|
|
|
|
|
correct = 1
|
|
|
|
@ -68,12 +73,14 @@ class ChatGLM_Evaluator(Evaluator):
|
|
|
|
|
if few_shot:
|
|
|
|
|
result.append(response)
|
|
|
|
|
score.append(correct)
|
|
|
|
|
correct_ratio = 100*correct_num/len(answers)
|
|
|
|
|
answer_list.append(ans)
|
|
|
|
|
correct_ratio = 100 * correct_num / len(answers)
|
|
|
|
|
|
|
|
|
|
if save_result_dir:
|
|
|
|
|
if few_shot:
|
|
|
|
|
test_df['model_output'] = result
|
|
|
|
|
test_df['correctness'] = score
|
|
|
|
|
test_df['model_answer'] = answer_list
|
|
|
|
|
result_file_name = f'{subject_name}_{correct_ratio}_test.csv'
|
|
|
|
|
if few_shot:
|
|
|
|
|
result_file_name = f'{subject_name}_{correct_ratio}_few_shot_test.csv'
|
|
|
|
@ -81,12 +88,24 @@ class ChatGLM_Evaluator(Evaluator):
|
|
|
|
|
|
|
|
|
|
return correct_ratio
|
|
|
|
|
|
|
|
|
|
def eval_qa(self, subject_name, qa_df, save_result_dir=None):
|
|
|
|
|
history = []
|
|
|
|
|
for row_index, row in tqdm(qa_df.iterrows(), total=len(qa_df)):
|
|
|
|
|
question = row['question']
|
|
|
|
|
response, _ = self.model.chat(self.tokenizer, question, do_sample=False, history=history)
|
|
|
|
|
response = response.strip()
|
|
|
|
|
qa_df.loc[row_index, 'model_output'] = response
|
|
|
|
|
if save_result_dir:
|
|
|
|
|
result_file_name = f'{subject_name}_qa_test_result.csv'
|
|
|
|
|
qa_df.to_csv(os.path.join(save_result_dir, result_file_name))
|
|
|
|
|
|
|
|
|
|
def generate_few_shot_prompt(self, subject, dev_df, cot=False):
|
|
|
|
|
message = []
|
|
|
|
|
k = self.k
|
|
|
|
|
if self.k == -1:
|
|
|
|
|
k = dev_df.shape[0]
|
|
|
|
|
message.append(self.format_example(dev_df.iloc[0, :], cot=cot, add_prompt=f"以下是中国关于{subject}考试的单项选择题,请选出其中的正确答案。\n\n"))
|
|
|
|
|
message.append(self.format_example(dev_df.iloc[0, :], cot=cot,
|
|
|
|
|
add_prompt=f"以下是中国关于{subject}考试的单项选择题,请选出其中的正确答案。\n\n"))
|
|
|
|
|
for i in range(1, k):
|
|
|
|
|
message.append(self.format_example(dev_df.iloc[i, :], cot=cot))
|
|
|
|
|
return message
|
|
|
|
@ -164,5 +183,6 @@ class ChatGLM_Evaluator(Evaluator):
|
|
|
|
|
|
|
|
|
|
score = outputs.scores[0][0].tolist()
|
|
|
|
|
choice_score = [score[167], score[333], score[251], score[416]]
|
|
|
|
|
ranked_index = [index for index, value in sorted(list(enumerate(choice_score)), key=lambda x:x[1], reverse=True)]
|
|
|
|
|
ranked_index = [index for index, value in
|
|
|
|
|
sorted(list(enumerate(choice_score)), key=lambda x: x[1], reverse=True)]
|
|
|
|
|
return self.choices[ranked_index[0]]
|
|
|
|
|