|
|
@ -7,6 +7,7 @@ from transformers.generation.logits_process import LogitsProcessor
|
|
|
|
from transformers.generation.utils import LogitsProcessorList
|
|
|
|
from transformers.generation.utils import LogitsProcessorList
|
|
|
|
from evaluators.evaluator import Evaluator
|
|
|
|
from evaluators.evaluator import Evaluator
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class InvalidScoreLogitsProcessor(LogitsProcessor):
|
|
|
|
class InvalidScoreLogitsProcessor(LogitsProcessor):
|
|
|
|
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
|
|
|
|
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
|
|
|
|
if torch.isnan(scores).any() or torch.isinf(scores).any():
|
|
|
|
if torch.isnan(scores).any() or torch.isinf(scores).any():
|
|
|
@ -14,6 +15,7 @@ class InvalidScoreLogitsProcessor(LogitsProcessor):
|
|
|
|
scores[..., 5] = 5e4
|
|
|
|
scores[..., 5] = 5e4
|
|
|
|
return scores
|
|
|
|
return scores
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ChatGLM_Evaluator(Evaluator):
|
|
|
|
class ChatGLM_Evaluator(Evaluator):
|
|
|
|
def __init__(self, choices, k, model_name, device, finetune=None):
|
|
|
|
def __init__(self, choices, k, model_name, device, finetune=None):
|
|
|
|
super(ChatGLM_Evaluator, self).__init__(choices, model_name, k)
|
|
|
|
super(ChatGLM_Evaluator, self).__init__(choices, model_name, k)
|
|
|
@ -34,7 +36,8 @@ class ChatGLM_Evaluator(Evaluator):
|
|
|
|
self.model.transformer.prefix_encoder.float()
|
|
|
|
self.model.transformer.prefix_encoder.float()
|
|
|
|
print("Model loaded! use GLM + " + finetune)
|
|
|
|
print("Model loaded! use GLM + " + finetune)
|
|
|
|
else:
|
|
|
|
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)")
|
|
|
|
print("Model loaded!(GLM)")
|
|
|
|
|
|
|
|
|
|
|
|
# self.model = self.model.eval()
|
|
|
|
# self.model = self.model.eval()
|
|
|
@ -45,6 +48,7 @@ class ChatGLM_Evaluator(Evaluator):
|
|
|
|
if few_shot:
|
|
|
|
if few_shot:
|
|
|
|
result = []
|
|
|
|
result = []
|
|
|
|
score = []
|
|
|
|
score = []
|
|
|
|
|
|
|
|
answer_list = []
|
|
|
|
if few_shot:
|
|
|
|
if few_shot:
|
|
|
|
history = self.generate_few_shot_prompt(subject_name, dev_df, cot=cot)
|
|
|
|
history = self.generate_few_shot_prompt(subject_name, dev_df, cot=cot)
|
|
|
|
else:
|
|
|
|
else:
|
|
|
@ -58,7 +62,8 @@ class ChatGLM_Evaluator(Evaluator):
|
|
|
|
# For ChatGLM, we use answer extraction in answer-only mode too.
|
|
|
|
# For ChatGLM, we use answer extraction in answer-only mode too.
|
|
|
|
ans, direct_extract = self.extract_cot_answer(row, response)
|
|
|
|
ans, direct_extract = self.extract_cot_answer(row, response)
|
|
|
|
else: # zero-shot by extracting answer from distribution
|
|
|
|
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]:
|
|
|
|
if ans == answers[row_index]:
|
|
|
|
correct_num += 1
|
|
|
|
correct_num += 1
|
|
|
|
correct = 1
|
|
|
|
correct = 1
|
|
|
@ -68,12 +73,14 @@ class ChatGLM_Evaluator(Evaluator):
|
|
|
|
if few_shot:
|
|
|
|
if few_shot:
|
|
|
|
result.append(response)
|
|
|
|
result.append(response)
|
|
|
|
score.append(correct)
|
|
|
|
score.append(correct)
|
|
|
|
|
|
|
|
answer_list.append(ans)
|
|
|
|
correct_ratio = 100 * correct_num / len(answers)
|
|
|
|
correct_ratio = 100 * correct_num / len(answers)
|
|
|
|
|
|
|
|
|
|
|
|
if save_result_dir:
|
|
|
|
if save_result_dir:
|
|
|
|
if few_shot:
|
|
|
|
if few_shot:
|
|
|
|
test_df['model_output'] = result
|
|
|
|
test_df['model_output'] = result
|
|
|
|
test_df['correctness'] = score
|
|
|
|
test_df['correctness'] = score
|
|
|
|
|
|
|
|
test_df['model_answer'] = answer_list
|
|
|
|
result_file_name = f'{subject_name}_{correct_ratio}_test.csv'
|
|
|
|
result_file_name = f'{subject_name}_{correct_ratio}_test.csv'
|
|
|
|
if few_shot:
|
|
|
|
if few_shot:
|
|
|
|
result_file_name = f'{subject_name}_{correct_ratio}_few_shot_test.csv'
|
|
|
|
result_file_name = f'{subject_name}_{correct_ratio}_few_shot_test.csv'
|
|
|
@ -81,12 +88,24 @@ class ChatGLM_Evaluator(Evaluator):
|
|
|
|
|
|
|
|
|
|
|
|
return correct_ratio
|
|
|
|
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):
|
|
|
|
def generate_few_shot_prompt(self, subject, dev_df, cot=False):
|
|
|
|
message = []
|
|
|
|
message = []
|
|
|
|
k = self.k
|
|
|
|
k = self.k
|
|
|
|
if self.k == -1:
|
|
|
|
if self.k == -1:
|
|
|
|
k = dev_df.shape[0]
|
|
|
|
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):
|
|
|
|
for i in range(1, k):
|
|
|
|
message.append(self.format_example(dev_df.iloc[i, :], cot=cot))
|
|
|
|
message.append(self.format_example(dev_df.iloc[i, :], cot=cot))
|
|
|
|
return message
|
|
|
|
return message
|
|
|
@ -164,5 +183,6 @@ class ChatGLM_Evaluator(Evaluator):
|
|
|
|
|
|
|
|
|
|
|
|
score = outputs.scores[0][0].tolist()
|
|
|
|
score = outputs.scores[0][0].tolist()
|
|
|
|
choice_score = [score[167], score[333], score[251], score[416]]
|
|
|
|
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]]
|
|
|
|
return self.choices[ranked_index[0]]
|
|
|
|