-
Notifications
You must be signed in to change notification settings - Fork 1
/
test_closed_models.py
200 lines (183 loc) · 6.71 KB
/
test_closed_models.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
191
192
193
194
195
196
197
198
199
import os
import gc
import torch
import argparse
import base64
import requests
from config import *
from PIL import Image
from tqdm import tqdm
from io import BytesIO
import torch.nn.functional as F
from accelerate import Accelerator
from torch.utils.data import DataLoader
from eval.create_evaluator import Evaluator
from concurrent.futures import ProcessPoolExecutor, as_completed
import time
from datasets import load_dataset
def encode_image(image):
buffered = BytesIO()
image.save(buffered, format="jpeg") # 이미지를 PNG 형식으로 저장 (다른 형식을 사용할 수도 있음)
image_bytes = buffered.getvalue()
return base64.b64encode(image_bytes).decode("utf-8")
def process_sample(model, input,count = 2):
text = input['question_query']
base64_image = encode_image(input['image'])
max_tokens = 32
temperature = 0
if model == "gpt":
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {OPENAI_KEY}"
}
payload = {
"model": "gpt-4o", #select model
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": text
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/{'jpeg'};base64,{base64_image}",
"detail": "low"
}
}
]
}
],
"max_tokens": max_tokens,
"temperature": temperature
}
done = False
while count :
try :
response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
done = True
break
except :
count -= 1
time.sleep(1)
return input, response.json()['choices'][0]['message']['content'].strip()
elif model == "claude":
headers = {
"x-api-key": f"{CLAUDE_KEY}",
"anthropic-version": "2023-06-01",
"content-type": "application/json"
}
payload = {
"model": "claude-3-5-sonnet-20240620", #select model
"messages": [
{"role": "user", "content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/jpeg",
"data": f"{base64_image}",
}
},
{"type": "text", "text": text}
]}
],
"max_tokens": max_tokens,
"temperature": temperature
}
done = False
while count :
try :
response = requests.post("https://api.anthropic.com/v1/messages", headers=headers, json=payload)
done = True
break
except :
count -= 1
time.sleep(1)
# print(response.json())
return input, response.json()['content'][0]['text'].strip()
elif model == "gemini":
headers = {
"Content-Type": "application/json"
}
payload = {
"contents": [
{"parts": [{
"text": text
},
{
"inline_data": {
"mime_type": "image/jpeg",
"data": f"{base64_image}"
}
}
]}],
"generationConfig": {
"temperature": 0,
"maxOutputTokens": 64
}
}
done = False
while count :
try :
response = requests.post(f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro:generateContent?key={GEMINI_KEY}", headers=headers, json=payload) #select model
done = True
break
except :
count -= 1
time.sleep(1)
# print(response.json())
return input, response.json()['candidates'][0]["content"]["parts"][0]['text'].strip()
def test(args):
accel = Accelerator()
# Initialize dataset & evaluator
test_dataset = load_dataset("topyun/SPARK", split="train", cache_dir=args.dataset_dir)
evaluator = Evaluator(root=args.dataset_dir)
results = {}
evaluator.reset()
test_dataloader = DataLoader(test_dataset,
batch_size=args.batch_size,
num_workers=4,
pin_memory=True,
collate_fn=lambda x: x)
error_num = 0
# progress bar
prog_bar = tqdm(enumerate(test_dataloader), total=len(test_dataloader))
# eval start
for batch_ind, inputs in prog_bar:
all_predictions = []
if not args.multiprocess:
for input in inputs:
all_predictions.append(process_sample(args.model,input))
elif args.multiprocess:
with ProcessPoolExecutor(max_workers=64) as executor:
futures = [executor.submit(process_sample,args.model, input) for input in inputs]
for future in as_completed(futures):
try:
if future.result():
all_predictions.append(future.result())
except:
pass
ids = [y[0]['id'] for y in all_predictions]
for x in inputs:
if x['id'] not in ids:
all_predictions.append((x, 'Error'))
error_num += 1
inputs, all_predictions = zip(*all_predictions)
prog_bar .set_description(f'{error_num}', refresh=True)
evaluator.process(inputs, all_predictions)
# evaluate on dataset
evaluator.evaluate(args.model, accel)
accel.print(results)
return
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--dataset_dir', type=str)
parser.add_argument('--model', default='gpt', type=str, help='gpt|claude|gemini')
parser.add_argument('--batch_size', default=32, type=int)
parser.add_argument('--multiprocess', default=False, type=bool)
args = parser.parse_args()
# test
test(args)