-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathmain.py
More file actions
162 lines (121 loc) · 4.61 KB
/
main.py
File metadata and controls
162 lines (121 loc) · 4.61 KB
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
from pathlib import Path
import string
import re
from fire import Fire
from pydantic import BaseModel
from tqdm import tqdm
from data_loading import Data, convert_text_to_image
from modeling import select_model
from prompting import FullPrompter
class Scorer(BaseModel):
def run(self, sample) -> float:
raise NotImplementedError
class MCQScorer(Scorer):
def run(self, sample) -> float:
punctuations = string.punctuation.replace(":", "")
matches = re.findall(r"[ABCD]", sample.pred)
mapping = {0: "A", 1: "B", 2: "C", 3: "D"}
answer_option = mapping[sample.options.index(sample.answer)]
if matches and len(matches) == 1:
if matches[-1] == answer_option:
return 1.0
if (
sample.answer.lower()
in sample.pred.translate(str.maketrans("", "", punctuations)).lower()
):
return 1.0
if sample.pred.lower() == sample.answer.lower():
return 1.0
return 0.0
class OpenEndedScorer(Scorer):
def run(self, sample) -> float:
punctuations = string.punctuation.replace(":", "")
if (
sample.answer.lower()
in sample.pred.translate(str.maketrans("", "", punctuations))
.lower()
.split()
):
return 1.0
return 0.0
class GptScorer(Scorer):
model = select_model("gpt4o")
def run(self, sample) -> float:
input_prompt = f"""
Evaluate the candidate answer against the correct answer. If the candidate answer is correct, output `[correct]`; otherwise, output `[incorrect]`.
Question: {sample.question}
Candidate Answer: {sample.raw_output}
Correct Answer: {sample.answer}
Evaluation:
""".strip()
output = self.model.run(input_prompt)
print(f"{input_prompt}\n{output}")
if "[correct]" in output:
return 1.0
else:
return 0.0
def evaluate(
dataset: str,
puzzle: str,
question_type: str,
output_dir: str = "outputs",
**kwargs,
):
print(locals())
image_dir = f"{dataset}/data"
data_path = f"{dataset}/data/{puzzle}.json"
data = Data.load_with_image_dir(data_path, image_dir)
model_name = kwargs.get("model_name")
path_out = f"{output_dir}/{dataset}/{question_type}/{model_name}/{puzzle}.jsonl"
print(dict(path_out=path_out))
is_correct = []
progress = tqdm(data.samples, desc=path_out)
# Get Prompter
if model_name == "o1":
cot = False
else:
cot = True
prompter = FullPrompter(question_type=question_type, cot=cot)
# Get Scorer
if question_type == "mcq":
scorer = MCQScorer()
elif question_type == "open":
scorer = GptScorer()
else:
raise f"Unknown question type: {question_type}"
model = select_model(**kwargs)
for sample in progress:
# Initial zero-shot prompting
sample.prompt = prompter.base_prompter.run(sample)
print(f"sample.prompt: {sample.prompt}")
image = convert_text_to_image(sample.image_string)
sample.raw_output = model.run(sample.prompt, image)
print(f"sample.raw_output: {sample.raw_output}")
if question_type == "mcq":
sample.pred = prompter.get_answer(sample.raw_output, sample.options)
# Model-based extraction if prediction not valid
if sample.pred not in sample.options:
sample.prompt = prompter.run(sample)
sample.raw_output = model.run(sample.prompt, image)
sample.pred = prompter.get_answer(sample.raw_output, sample.options)
elif question_type == "open":
pass
else:
raise f"Unknown question type: {question_type}"
# Scoring
score = scorer.run(sample)
sample.correct = score
is_correct.append(score)
score = sum(is_correct) / len(is_correct)
progress.set_postfix(score=score)
print(sample.json(indent=2, exclude={"image_string"}))
print(dict(is_correct=is_correct[-1]))
data.save(path_out)
"""
python main.py evaluate --dataset PuzzleVQA --puzzle color_hexagon --question_type open --model_name gpt4o --output_dir outputs_test
python main.py evaluate --dataset PuzzleVQA --puzzle color_hexagon --question_type mcq --model_name gpt4o --output_dir outputs_test
python main.py evaluate --dataset AlgoPuzzleVQA --puzzle board_tile --question_type open --model_name gpt4o --output_dir outputs_test
python main.py evaluate --dataset AlgoPuzzleVQA --puzzle board_tile --question_type mcq --model_name gpt4o --output_dir outputs_test
"""
if __name__ == "__main__":
Fire()